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))
3621 case MentionsTabModel replyTab:
3622 await this.GetReplyAsync();
3624 case DirectMessagesTabModel dmTab:
3625 await this.GetDirectMessagesAsync();
3627 case FavoritesTabModel favTab:
3628 await this.GetFavoritesAsync();
3630 case PublicSearchTabModel searchTab:
3631 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3632 await this.GetPublicSearchAsync(searchTab);
3634 case UserTimelineTabModel userTab:
3635 await this.GetUserTimelineAsync(userTab);
3637 case ListTimelineTabModel listTab:
3638 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3639 await this.GetListTimelineAsync(listTab);
3642 await this.GetHomeTimelineAsync();
3648 await this.GetHomeTimelineAsync();
3652 private async Task DoRefreshMore()
3655 if (_curTab != null)
3658 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3663 case MentionsTabModel replyTab:
3664 await this.GetReplyAsync(loadMore: true);
3666 case DirectMessagesTabModel dmTab:
3667 await this.GetDirectMessagesAsync(loadMore: true);
3669 case FavoritesTabModel favTab:
3670 await this.GetFavoritesAsync(loadMore: true);
3672 case PublicSearchTabModel searchTab:
3673 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3674 await this.GetPublicSearchAsync(searchTab, loadMore: true);
3676 case UserTimelineTabModel userTab:
3677 await this.GetUserTimelineAsync(userTab, loadMore: true);
3679 case ListTimelineTabModel listTab:
3680 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3681 await this.GetListTimelineAsync(listTab, loadMore: true);
3684 await this.GetHomeTimelineAsync(loadMore: true);
3690 await this.GetHomeTimelineAsync(loadMore: true);
3694 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3696 DialogResult result = DialogResult.Abort;
3698 using (var settingDialog = new AppendSettingDialog())
3700 settingDialog.Icon = this.MainIcon;
3701 settingDialog.Owner = this;
3702 settingDialog.ShowInTaskbar = showTaskbarIcon;
3703 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3705 settingDialog.tw = this.tw;
3706 settingDialog.twitterApi = this.twitterApi;
3708 settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
3712 result = settingDialog.ShowDialog(this);
3716 return DialogResult.Abort;
3719 if (result == DialogResult.OK)
3723 settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
3731 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3734 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3736 var oldIconSz = SettingManager.Common.IconSize;
3738 if (ShowSettingDialog() == DialogResult.OK)
3742 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
3743 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
3744 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
3745 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
3746 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
3747 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
3749 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
3750 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
3751 Networking.SetWebProxy(SettingManager.Local.ProxyType,
3752 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
3753 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
3754 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
3756 ImageSelector.Reset(tw, this.tw.Configuration);
3760 if (SettingManager.Common.TabIconDisp)
3762 ListTab.DrawItem -= ListTab_DrawItem;
3763 ListTab.DrawMode = TabDrawMode.Normal;
3764 ListTab.ImageList = this.TabImage;
3768 ListTab.DrawItem -= ListTab_DrawItem;
3769 ListTab.DrawItem += ListTab_DrawItem;
3770 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3771 ListTab.ImageList = null;
3774 catch (Exception ex)
3776 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3777 ex.Data["IsTerminatePermission"] = false;
3783 if (!SettingManager.Common.UnreadManage)
3785 ReadedStripMenuItem.Enabled = false;
3786 UnreadStripMenuItem.Enabled = false;
3787 if (SettingManager.Common.TabIconDisp)
3789 foreach (TabPage myTab in ListTab.TabPages)
3791 myTab.ImageIndex = -1;
3797 ReadedStripMenuItem.Enabled = true;
3798 UnreadStripMenuItem.Enabled = true;
3801 catch (Exception ex)
3803 ex.Data["Instance"] = "ListTab(UnreadManage)";
3804 ex.Data["IsTerminatePermission"] = false;
3811 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
3813 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3814 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
3815 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
3817 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
3818 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
3819 _fntUnread = SettingManager.Local.FontUnread;
3820 _clUnread = SettingManager.Local.ColorUnread;
3821 _fntReaded = SettingManager.Local.FontRead;
3822 _clReaded = SettingManager.Local.ColorRead;
3823 _clFav = SettingManager.Local.ColorFav;
3824 _clOWL = SettingManager.Local.ColorOWL;
3825 _clRetweet = SettingManager.Local.ColorRetweet;
3826 _fntDetail = SettingManager.Local.FontDetail;
3827 _clDetail = SettingManager.Local.ColorDetail;
3828 _clDetailLink = SettingManager.Local.ColorDetailLink;
3829 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
3830 _clSelf = SettingManager.Local.ColorSelf;
3831 _clAtSelf = SettingManager.Local.ColorAtSelf;
3832 _clTarget = SettingManager.Local.ColorTarget;
3833 _clAtTarget = SettingManager.Local.ColorAtTarget;
3834 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
3835 _clAtTo = SettingManager.Local.ColorAtTo;
3836 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
3837 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
3838 _clInputFont = SettingManager.Local.ColorInputFont;
3839 _fntInputFont = SettingManager.Local.FontInputFont;
3840 _brsBackColorMine.Dispose();
3841 _brsBackColorAt.Dispose();
3842 _brsBackColorYou.Dispose();
3843 _brsBackColorAtYou.Dispose();
3844 _brsBackColorAtFromTarget.Dispose();
3845 _brsBackColorAtTo.Dispose();
3846 _brsBackColorNone.Dispose();
3847 _brsBackColorMine = new SolidBrush(_clSelf);
3848 _brsBackColorAt = new SolidBrush(_clAtSelf);
3849 _brsBackColorYou = new SolidBrush(_clTarget);
3850 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3851 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3852 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3853 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3857 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3858 StatusText.Font = _fntInputFont;
3859 StatusText.ForeColor = _clInputFont;
3861 catch (Exception ex)
3863 MessageBox.Show(ex.Message);
3868 InitDetailHtmlFormat();
3870 catch (Exception ex)
3872 ex.Data["Instance"] = "Font";
3873 ex.Data["IsTerminatePermission"] = false;
3879 foreach (TabPage tb in ListTab.TabPages)
3881 if (SettingManager.Common.TabIconDisp)
3883 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3890 catch (Exception ex)
3892 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3893 ex.Data["IsTerminatePermission"] = false;
3899 var oldIconCol = _iconCol;
3901 if (SettingManager.Common.IconSize != oldIconSz)
3902 ApplyListViewIconSize(SettingManager.Common.IconSize);
3904 foreach (TabPage tp in ListTab.TabPages)
3906 DetailsListView lst = (DetailsListView)tp.Tag;
3908 using (ControlTransaction.Update(lst))
3910 lst.GridLines = SettingManager.Common.ShowGrid;
3911 lst.Font = _fntReaded;
3912 lst.BackColor = _clListBackcolor;
3914 if (_iconCol != oldIconCol)
3919 catch (Exception ex)
3921 ex.Data["Instance"] = "ListView(IconSize)";
3922 ex.Data["IsTerminatePermission"] = false;
3926 SetMainWindowTitle();
3927 SetNotifyIconText();
3929 this.PurgeListViewItemCache();
3930 _curList?.Refresh();
3933 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3934 if (SettingManager.Common.HotkeyEnabled)
3936 ///グローバルホットキーの登録。設定で変更可能にするかも
3937 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
3938 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
3939 modKey |= HookGlobalHotkey.ModKeys.Alt;
3940 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
3941 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3942 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
3943 modKey |= HookGlobalHotkey.ModKeys.Shift;
3944 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
3945 modKey |= HookGlobalHotkey.ModKeys.Win;
3947 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
3950 if (SettingManager.Common.IsUseNotifyGrowl) gh.RegisterGrowl();
3953 StatusText_TextChanged(null, null);
3962 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3963 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3966 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3968 this.TopMost = SettingManager.Common.AlwaysTop;
3969 SaveConfigsAll(false);
3971 if (tw.Username != oldUser.Username)
3972 await this.doGetFollowersMenu();
3978 private void SetTabAlignment()
3980 var newAlignment = SettingManager.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3981 if (ListTab.Alignment == newAlignment) return;
3983 // 各タブのリスト上の選択位置などを退避
3984 var listSelections = this.SaveListViewSelection();
3986 ListTab.Alignment = newAlignment;
3988 foreach (TabPage tab in ListTab.TabPages)
3990 DetailsListView lst = (DetailsListView)tab.Tag;
3991 TabModel tabInfo = _statuses.Tabs[tab.Text];
3992 using (ControlTransaction.Update(lst))
3995 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4000 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4006 case MyCommon.IconSizes.IconNone:
4009 case MyCommon.IconSizes.Icon16:
4012 case MyCommon.IconSizes.Icon24:
4015 case MyCommon.IconSizes.Icon48:
4018 case MyCommon.IconSizes.Icon48_2:
4026 // ディスプレイの DPI 設定を考慮したサイズを設定する
4027 _listViewImageList.ImageSize = new Size(
4029 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4033 _listViewImageList.ImageSize = new Size(1, 1);
4037 private void ResetColumns(DetailsListView list)
4039 using (ControlTransaction.Update(list))
4040 using (ControlTransaction.Layout(list, false))
4043 list.ColumnClick -= MyList_ColumnClick;
4044 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4045 list.ColumnReordered -= MyList_ColumnReordered;
4046 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4048 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4049 list.Columns.Clear();
4050 cols.ForEach(col => col.Dispose());
4053 InitColumns(list, true);
4055 list.ColumnClick += MyList_ColumnClick;
4056 list.DrawColumnHeader += MyList_DrawColumnHeader;
4057 list.ColumnReordered += MyList_ColumnReordered;
4058 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4062 public void AddNewTabForSearch(string searchWord)
4064 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4065 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4067 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4069 foreach (TabPage tp in ListTab.TabPages)
4071 if (tb.TabName == tp.Text)
4073 ListTab.SelectedTab = tp;
4080 string tabName = searchWord;
4081 for (int i = 0; i <= 100; i++)
4083 if (_statuses.ContainsTab(tabName))
4089 var tab = new PublicSearchTabModel(tabName);
4090 _statuses.AddTab(tab);
4091 AddNewTab(tab, startup: false);
4093 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4095 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4096 cmb.Items.Add(searchWord);
4097 cmb.Text = searchWord;
4100 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4103 private void ShowUserTimeline()
4105 if (!this.ExistCurrentPost) return;
4106 AddNewTabForUserTimeline(_curPost.ScreenName);
4109 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4111 if (e.KeyCode == Keys.Escape)
4113 TabPage relTp = ListTab.SelectedTab;
4114 RemoveSpecifiedTab(relTp.Text, false);
4116 e.SuppressKeyPress = true;
4120 public void AddNewTabForUserTimeline(string user)
4122 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4123 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4125 if (tb.ScreenName == user)
4127 foreach (TabPage tp in ListTab.TabPages)
4129 if (tb.TabName == tp.Text)
4131 ListTab.SelectedTab = tp;
4138 string tabName = "user:" + user;
4139 while (_statuses.ContainsTab(tabName))
4144 var tab = new UserTimelineTabModel(tabName, user);
4145 this._statuses.AddTab(tab);
4146 this.AddNewTab(tab, startup: false);
4148 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4151 this.GetUserTimelineAsync(tab);
4154 public bool AddNewTab(TabModel tab, bool startup)
4157 foreach (TabPage tb in ListTab.TabPages)
4159 if (tb.Text == tab.TabName) return false;
4163 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4165 var _tabPage = new TabPage();
4166 var _listCustom = new DetailsListView();
4168 int cnt = ListTab.TabPages.Count;
4170 ///ToDo:Create and set controls follow tabtypes
4172 using (ControlTransaction.Update(_listCustom))
4173 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4174 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4175 using (ControlTransaction.Layout(this.SplitContainer1, false))
4176 using (ControlTransaction.Layout(this.ListTab, false))
4177 using (ControlTransaction.Layout(this))
4178 using (ControlTransaction.Layout(_tabPage, false))
4180 _tabPage.Controls.Add(_listCustom);
4183 var userTab = tab as UserTimelineTabModel;
4184 var listTab = tab as ListTimelineTabModel;
4185 var searchTab = tab as PublicSearchTabModel;
4187 if (userTab != null || listTab != null)
4189 var label = new Label();
4190 label.Dock = DockStyle.Top;
4191 label.Name = "labelUser";
4194 if (listTab != null)
4196 label.Text = listTab.ListInfo.ToString();
4198 else if (userTab != null)
4200 label.Text = userTab.ScreenName + "'s Timeline";
4202 label.TextAlign = ContentAlignment.MiddleLeft;
4203 using (ComboBox tmpComboBox = new ComboBox())
4205 label.Height = tmpComboBox.Height;
4207 _tabPage.Controls.Add(label);
4210 else if (searchTab != null)
4212 var pnl = new Panel();
4214 var lbl = new Label();
4215 var cmb = new ComboBox();
4216 var btn = new Button();
4217 var cmbLang = new ComboBox();
4219 using (ControlTransaction.Layout(pnl, false))
4221 pnl.Controls.Add(cmb);
4222 pnl.Controls.Add(cmbLang);
4223 pnl.Controls.Add(btn);
4224 pnl.Controls.Add(lbl);
4225 pnl.Name = "panelSearch";
4227 pnl.Dock = DockStyle.Top;
4228 pnl.Height = cmb.Height;
4229 pnl.Enter += SearchControls_Enter;
4230 pnl.Leave += SearchControls_Leave;
4233 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4234 cmb.Dock = DockStyle.Fill;
4235 cmb.Name = "comboSearch";
4236 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4237 cmb.ImeMode = ImeMode.NoControl;
4238 cmb.TabStop = false;
4240 cmb.AutoCompleteMode = AutoCompleteMode.None;
4241 cmb.KeyDown += SearchComboBox_KeyDown;
4244 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4245 cmbLang.Dock = DockStyle.Right;
4247 cmbLang.Name = "comboLang";
4248 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4249 cmbLang.TabStop = false;
4250 cmbLang.TabIndex = 2;
4251 cmbLang.Items.Add("");
4252 cmbLang.Items.Add("ja");
4253 cmbLang.Items.Add("en");
4254 cmbLang.Items.Add("ar");
4255 cmbLang.Items.Add("da");
4256 cmbLang.Items.Add("nl");
4257 cmbLang.Items.Add("fa");
4258 cmbLang.Items.Add("fi");
4259 cmbLang.Items.Add("fr");
4260 cmbLang.Items.Add("de");
4261 cmbLang.Items.Add("hu");
4262 cmbLang.Items.Add("is");
4263 cmbLang.Items.Add("it");
4264 cmbLang.Items.Add("no");
4265 cmbLang.Items.Add("pl");
4266 cmbLang.Items.Add("pt");
4267 cmbLang.Items.Add("ru");
4268 cmbLang.Items.Add("es");
4269 cmbLang.Items.Add("sv");
4270 cmbLang.Items.Add("th");
4272 lbl.Text = "Search(C-S-f)";
4273 lbl.Name = "label1";
4274 lbl.Dock = DockStyle.Left;
4276 lbl.Height = cmb.Height;
4277 lbl.TextAlign = ContentAlignment.MiddleLeft;
4280 btn.Text = "Search";
4281 btn.Name = "buttonSearch";
4282 btn.UseVisualStyleBackColor = true;
4283 btn.Dock = DockStyle.Right;
4284 btn.TabStop = false;
4286 btn.Click += SearchButton_Click;
4288 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4290 cmb.Items.Add(searchTab.SearchWords);
4291 cmb.Text = searchTab.SearchWords;
4294 cmbLang.Text = searchTab.SearchLang;
4296 _tabPage.Controls.Add(pnl);
4300 _tabPage.Tag = _listCustom;
4301 this.ListTab.Controls.Add(_tabPage);
4303 _tabPage.Location = new Point(4, 4);
4304 _tabPage.Name = "CTab" + cnt;
4305 _tabPage.Size = new Size(380, 260);
4306 _tabPage.TabIndex = 2 + cnt;
4307 _tabPage.Text = tab.TabName;
4308 _tabPage.UseVisualStyleBackColor = true;
4309 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4311 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4312 _listCustom.TabIndex = 1;
4313 _listCustom.AllowColumnReorder = true;
4314 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4315 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4316 _listCustom.Dock = DockStyle.Fill;
4317 _listCustom.FullRowSelect = true;
4318 _listCustom.HideSelection = false;
4319 _listCustom.Location = new Point(0, 0);
4320 _listCustom.Margin = new Padding(0);
4321 _listCustom.Name = "CList" + Environment.TickCount;
4322 _listCustom.ShowItemToolTips = true;
4323 _listCustom.Size = new Size(380, 260);
4324 _listCustom.UseCompatibleStateImageBehavior = false;
4325 _listCustom.View = View.Details;
4326 _listCustom.OwnerDraw = true;
4327 _listCustom.VirtualMode = true;
4328 _listCustom.Font = _fntReaded;
4329 _listCustom.BackColor = _clListBackcolor;
4331 _listCustom.GridLines = SettingManager.Common.ShowGrid;
4332 _listCustom.AllowDrop = true;
4334 _listCustom.SmallImageList = _listViewImageList;
4336 InitColumns(_listCustom, startup);
4338 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4339 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4340 _listCustom.ColumnClick += MyList_ColumnClick;
4341 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4342 _listCustom.DragDrop += TweenMain_DragDrop;
4343 _listCustom.DragEnter += TweenMain_DragEnter;
4344 _listCustom.DragOver += TweenMain_DragOver;
4345 _listCustom.DrawItem += MyList_DrawItem;
4346 _listCustom.MouseClick += MyList_MouseClick;
4347 _listCustom.ColumnReordered += MyList_ColumnReordered;
4348 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4349 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4350 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4351 _listCustom.DrawSubItem += MyList_DrawSubItem;
4352 _listCustom.HScrolled += MyList_HScrolled;
4358 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4360 var tabInfo = _statuses.GetTabByName(TabName);
4361 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4365 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4366 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4367 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4373 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4374 if (_tabPage == null) return false;
4376 SetListProperty(); //他のタブに列幅等を反映
4379 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4380 _tabPage.Tag = null;
4382 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4383 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4384 using (ControlTransaction.Layout(this.SplitContainer1, false))
4385 using (ControlTransaction.Layout(this.ListTab, false))
4386 using (ControlTransaction.Layout(this))
4387 using (ControlTransaction.Layout(_tabPage, false))
4389 if (this.ListTab.SelectedTab == _tabPage)
4391 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4392 this._beforeSelectedTab = null;
4394 this.ListTab.Controls.Remove(_tabPage);
4397 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4399 using (Control label = _tabPage.Controls["labelUser"])
4401 _tabPage.Controls.Remove(label);
4404 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4406 using (Control pnl = _tabPage.Controls["panelSearch"])
4408 pnl.Enter -= SearchControls_Enter;
4409 pnl.Leave -= SearchControls_Leave;
4410 _tabPage.Controls.Remove(pnl);
4412 foreach (Control ctrl in pnl.Controls)
4414 if (ctrl.Name == "buttonSearch")
4416 ctrl.Click -= SearchButton_Click;
4418 else if (ctrl.Name == "comboSearch")
4420 ctrl.KeyDown -= SearchComboBox_KeyDown;
4422 pnl.Controls.Remove(ctrl);
4428 _tabPage.Controls.Remove(_listCustom);
4430 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4431 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4432 _listCustom.ColumnClick -= MyList_ColumnClick;
4433 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4434 _listCustom.DragDrop -= TweenMain_DragDrop;
4435 _listCustom.DragEnter -= TweenMain_DragEnter;
4436 _listCustom.DragOver -= TweenMain_DragOver;
4437 _listCustom.DrawItem -= MyList_DrawItem;
4438 _listCustom.MouseClick -= MyList_MouseClick;
4439 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4440 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4441 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4442 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4443 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4444 _listCustom.HScrolled -= MyList_HScrolled;
4446 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4447 _listCustom.Columns.Clear();
4448 cols.ForEach(col => col.Dispose());
4451 _listCustom.ContextMenuStrip = null;
4452 _listCustom.ColumnHeaderContextMenuStrip = null;
4453 _listCustom.Font = null;
4455 _listCustom.SmallImageList = null;
4456 _listCustom.ListViewItemSorter = null;
4459 if (_curTab.Equals(_tabPage))
4466 this.PurgeListViewItemCache();
4470 _listCustom.Dispose();
4471 _statuses.RemoveTab(TabName);
4473 foreach (TabPage tp in ListTab.TabPages)
4475 DetailsListView lst = (DetailsListView)tp.Tag;
4476 var count = _statuses.Tabs[tp.Text].AllCount;
4477 lst.VirtualListSize = count;
4483 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4485 this.PurgeListViewItemCache();
4486 _beforeSelectedTab = e.TabPage;
4489 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4493 if (!SettingManager.Common.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4496 Rectangle dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4497 if (!dragEnableRectangle.Contains(e.Location))
4499 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4500 tn = ListTab.SelectedTab.Text;
4503 if (string.IsNullOrEmpty(tn)) return;
4505 foreach (TabPage tb in ListTab.TabPages)
4509 ListTab.DoDragDrop(tb, DragDropEffects.All);
4519 Point cpos = new Point(e.X, e.Y);
4520 for (int i = 0; i < ListTab.TabPages.Count; i++)
4522 Rectangle rect = ListTab.GetTabRect(i);
4523 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4524 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4526 _rclickTabName = ListTab.TabPages[i].Text;
4532 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4534 //_curList.Refresh();
4535 SetMainWindowTitle();
4536 SetStatusLabelUrl();
4537 SetApiStatusLabel();
4538 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4539 TabMenuControl(ListTab.SelectedTab.Text);
4540 this.PushSelectPostChain();
4541 await DispSelectedPost();
4544 private void SetListProperty()
4546 //削除などで見つからない場合は処理せず
4547 if (_curList == null) return;
4548 if (!_isColumnChanged) return;
4550 int[] dispOrder = new int[_curList.Columns.Count];
4551 for (int i = 0; i < _curList.Columns.Count; i++)
4553 for (int j = 0; j < _curList.Columns.Count; j++)
4555 if (_curList.Columns[j].DisplayIndex == i)
4564 foreach (TabPage tb in ListTab.TabPages)
4566 if (!tb.Equals(_curTab))
4568 if (tb.Tag != null && tb.Controls.Count > 0)
4570 DetailsListView lst = (DetailsListView)tb.Tag;
4571 for (int i = 0; i < lst.Columns.Count; i++)
4573 lst.Columns[dispOrder[i]].DisplayIndex = i;
4574 lst.Columns[i].Width = _curList.Columns[i].Width;
4580 _isColumnChanged = false;
4583 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4585 if (e.KeyChar == '@')
4587 if (!SettingManager.Common.UseAtIdSupplement) return;
4589 int cnt = AtIdSupl.ItemCount;
4590 ShowSuplDialog(StatusText, AtIdSupl);
4591 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
4594 else if (e.KeyChar == '#')
4596 if (!SettingManager.Common.UseHashSupplement) return;
4597 ShowSuplDialog(StatusText, HashSupl);
4602 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4604 ShowSuplDialog(owner, dialog, 0, "");
4607 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4609 ShowSuplDialog(owner, dialog, offset, "");
4612 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4614 dialog.StartsWith = startswith;
4621 dialog.ShowDialog();
4623 this.TopMost = SettingManager.Common.AlwaysTop;
4624 int selStart = owner.SelectionStart;
4627 if (dialog.DialogResult == DialogResult.OK)
4629 if (!string.IsNullOrEmpty(dialog.inputText))
4633 fHalf = owner.Text.Substring(0, selStart - offset);
4635 if (selStart < owner.Text.Length)
4637 eHalf = owner.Text.Substring(selStart);
4639 owner.Text = fHalf + dialog.inputText + eHalf;
4640 owner.SelectionStart = selStart + dialog.inputText.Length;
4647 fHalf = owner.Text.Substring(0, selStart);
4649 if (selStart < owner.Text.Length)
4651 eHalf = owner.Text.Substring(selStart);
4653 owner.Text = fHalf + eHalf;
4656 owner.SelectionStart = selStart;
4662 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4665 if (!e.Alt && !e.Control && !e.Shift)
4667 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4669 bool isSpace = false;
4670 foreach (char c in StatusText.Text)
4672 if (c == ' ' || c == ' ')
4685 StatusText.Text = "";
4686 JumpUnreadMenuItem_Click(null, null);
4690 this.StatusText_TextChanged(null, null);
4693 private void StatusText_TextChanged(object sender, EventArgs e)
4696 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
4697 lblLen.Text = pLen.ToString();
4700 StatusText.ForeColor = Color.Red;
4704 StatusText.ForeColor = _clInputFont;
4707 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4709 if (string.IsNullOrEmpty(StatusText.Text))
4711 this.inReplyTo = null;
4716 /// ツイート投稿前のフッター付与などの前処理を行います
4718 private string FormatStatusText(string statusText)
4720 statusText = statusText.Replace("\r\n", "\n");
4722 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
4725 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4728 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
4730 // 文中の全角スペースを半角スペース1個にする
4731 statusText = statusText.Replace(" ", " ");
4734 // DM の場合はこれ以降の処理を行わない
4735 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4739 if (SettingManager.Common.PostShiftEnter)
4741 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4745 if (this.StatusText.Multiline && !SettingManager.Common.PostCtrlEnter)
4746 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4748 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4751 if (statusText.Contains("RT @"))
4752 disableFooter = true;
4757 var hashtag = this.HashMgr.UseHash;
4758 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4761 header = HashMgr.UseHash + " ";
4763 footer = " " + HashMgr.UseHash;
4768 if (SettingManager.Local.UseRecommendStatus)
4771 footer += this.recommendedStatusFooter;
4773 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4775 // テキストボックスに入力されている文字列を使用する
4776 footer += " " + SettingManager.Local.StatusText.Trim();
4780 statusText = header + statusText + footer;
4782 if (this.ToolStripMenuItemPreventSmsCommand.Checked)
4784 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4785 // 参照: https://support.twitter.com/articles/14020
4787 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4788 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4790 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4791 statusText = '\u200b' + statusText;
4799 /// 投稿欄に表示する入力可能な文字数を計算します
4801 private int GetRestStatusCount(string statusText)
4804 var remainCount = this.tw.GetTextLengthRemain(statusText);
4806 var uploadService = this.ImageSelector.SelectedService;
4807 if (this.ImageSelector.Visible && uploadService != null)
4809 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4810 remainCount -= uploadService.GetReservedTextLength(1);
4816 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4818 if (sender != this._curList)
4821 var listCache = this._listItemCache;
4822 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4824 // If the newly requested cache is a subset of the old cache,
4825 // no need to rebuild everything, so do nothing.
4829 // Now we need to rebuild the cache.
4830 this.CreateCache(e.StartIndex, e.EndIndex);
4833 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4835 var listCache = this._listItemCache;
4836 if (listCache?.TargetList == sender)
4839 PostClass cacheItemPost;
4840 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
4847 // A cache miss, so create a new ListViewItem and pass it back.
4848 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4851 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4855 // 不正な要求に対する間に合わせの応答
4856 string[] sitem = {"", "", "", "", "", "", "", ""};
4857 e.Item = new ImageListViewItem(sitem);
4861 private void CreateCache(int startIndex, int endIndex)
4863 var tabInfo = this._statuses.Tabs[this._curTab.Text];
4865 if (tabInfo.AllCount == 0)
4868 // キャッシュ要求(要求範囲±30を作成)
4869 startIndex = Math.Max(startIndex - 30, 0);
4870 endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
4872 var cacheLength = endIndex - startIndex + 1;
4874 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4875 var listItems = Enumerable.Range(0, cacheLength)
4876 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4879 var listCache = new ListViewItemCache
4881 TargetList = this._curList,
4882 StartIndex = startIndex,
4883 EndIndex = endIndex,
4885 ListItem = listItems,
4888 Interlocked.Exchange(ref this._listItemCache, listCache);
4892 /// DetailsListView のための ListViewItem のキャッシュを消去する
4894 private void PurgeListViewItemCache()
4896 Interlocked.Exchange(ref this._listItemCache, null);
4899 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
4901 StringBuilder mk = new StringBuilder();
4902 //if (Post.IsDeleted) mk.Append("×");
4903 //if (Post.IsMark) mk.Append("♪");
4904 //if (Post.IsProtect) mk.Append("Ю");
4905 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4906 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4907 ImageListViewItem itm;
4908 if (Post.RetweetedId == null)
4910 string[] sitem= {"",
4912 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText,
4913 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4918 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4922 string[] sitem = {"",
4924 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText,
4925 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4926 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4930 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4932 itm.StateIndex = Post.StateIndex;
4935 bool read = Post.IsRead;
4936 //未読管理していなかったら既読として扱う
4937 if (!_statuses.Tabs[Tab.Text].UnreadManage || !SettingManager.Common.UnreadManage) read = true;
4938 ChangeItemStyleRead(read, itm, Post, null);
4939 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
4944 /// 全てのタブの振り分けルールを反映し直します
4946 private void ApplyPostFilters()
4948 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4950 this.PurgeListViewItemCache();
4951 this._curPost = null;
4952 this._curItemIndex = -1;
4953 this._statuses.FilterAll();
4955 foreach (TabPage tabPage in this.ListTab.TabPages)
4957 var tab = this._statuses.Tabs[tabPage.Text];
4959 var listview = (DetailsListView)tabPage.Tag;
4960 using (ControlTransaction.Update(listview))
4962 listview.VirtualListSize = tab.AllCount;
4965 if (SettingManager.Common.TabIconDisp)
4967 if (tab.UnreadCount > 0)
4968 tabPage.ImageIndex = 0;
4970 tabPage.ImageIndex = -1;
4974 if (!SettingManager.Common.TabIconDisp)
4975 this.ListTab.Refresh();
4977 SetMainWindowTitle();
4978 SetStatusLabelUrl();
4982 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4984 e.DrawDefault = true;
4987 private void MyList_HScrolled(object sender, EventArgs e)
4989 DetailsListView listView = (DetailsListView)sender;
4993 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
4995 if (e.State == 0) return;
4996 e.DrawDefault = false;
4998 SolidBrush brs2 = null;
4999 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5001 if (e.Item.BackColor == _clSelf)
5002 brs2 = _brsBackColorMine;
5003 else if (e.Item.BackColor == _clAtSelf)
5004 brs2 = _brsBackColorAt;
5005 else if (e.Item.BackColor == _clTarget)
5006 brs2 = _brsBackColorYou;
5007 else if (e.Item.BackColor == _clAtTarget)
5008 brs2 = _brsBackColorAtYou;
5009 else if (e.Item.BackColor == _clAtFromTarget)
5010 brs2 = _brsBackColorAtFromTarget;
5011 else if (e.Item.BackColor == _clAtTo)
5012 brs2 = _brsBackColorAtTo;
5014 brs2 = _brsBackColorNone;
5019 if (((Control)sender).Focused)
5020 brs2 = _brsHighLight;
5022 brs2 = _brsDeactiveSelection;
5024 e.Graphics.FillRectangle(brs2, e.Bounds);
5025 e.DrawFocusRectangle();
5026 this.DrawListViewItemIcon(e);
5029 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5031 if (e.ItemState == 0) return;
5033 if (e.ColumnIndex > 0)
5036 var post = (PostClass)e.Item.Tag;
5038 RectangleF rct = e.Bounds;
5039 rct.Width = e.Header.Width;
5040 int fontHeight = e.Item.Font.Height;
5043 rct.Y += fontHeight;
5044 rct.Height -= fontHeight;
5048 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5050 //if (heightDiff > fontHeight * 0.7)
5052 // rct.Height += fontHeight;
5053 // drawLineCount += 1;
5056 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5057 if (!_iconCol && drawLineCount <= 1)
5059 //rct.Inflate(0, heightDiff / -2);
5060 //rct.Height += fontHeight / 2;
5062 else if (heightDiff < fontHeight * 0.7)
5064 //最終行が70%以上欠けていたら、最終行は表示しない
5065 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5066 rct.Height = (fontHeight * drawLineCount) - 1;
5073 //if (!_iconCol && drawLineCount > 1)
5075 // rct.Y += fontHeight * 0.2;
5076 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5081 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5082 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5087 Rectangle rctB = e.Bounds;
5088 rctB.Width = e.Header.Width;
5089 rctB.Height = fontHeight;
5091 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5093 TextRenderer.DrawText(e.Graphics,
5094 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5096 Rectangle.Round(rct),
5098 TextFormatFlags.WordBreak |
5099 TextFormatFlags.EndEllipsis |
5100 TextFormatFlags.GlyphOverhangPadding |
5101 TextFormatFlags.NoPrefix);
5102 TextRenderer.DrawText(e.Graphics,
5103 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 + "]",
5107 TextFormatFlags.SingleLine |
5108 TextFormatFlags.EndEllipsis |
5109 TextFormatFlags.GlyphOverhangPadding |
5110 TextFormatFlags.NoPrefix);
5116 if (e.ColumnIndex != 2)
5117 text = e.SubItem.Text;
5119 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5121 if (drawLineCount == 1)
5123 TextRenderer.DrawText(e.Graphics,
5126 Rectangle.Round(rct),
5128 TextFormatFlags.SingleLine |
5129 TextFormatFlags.EndEllipsis |
5130 TextFormatFlags.GlyphOverhangPadding |
5131 TextFormatFlags.NoPrefix |
5132 TextFormatFlags.VerticalCenter);
5136 TextRenderer.DrawText(e.Graphics,
5139 Rectangle.Round(rct),
5141 TextFormatFlags.WordBreak |
5142 TextFormatFlags.EndEllipsis |
5143 TextFormatFlags.GlyphOverhangPadding |
5144 TextFormatFlags.NoPrefix);
5147 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5152 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5154 if (_iconSz == 0) return;
5156 ImageListViewItem item = (ImageListViewItem)e.Item;
5158 //e.Bounds.Leftが常に0を指すから自前で計算
5159 Rectangle itemRect = item.Bounds;
5160 var col0 = e.Item.ListView.Columns[0];
5161 itemRect.Width = col0.Width;
5163 if (col0.DisplayIndex > 0)
5165 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5167 if (clm.DisplayIndex < col0.DisplayIndex)
5168 itemRect.X += clm.Width;
5172 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5173 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5174 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5177 var img = item.Image;
5180 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5181 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5183 if (iconRect.Width > 0)
5185 e.Graphics.FillRectangle(Brushes.White, iconRect);
5186 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5189 e.Graphics.DrawImage(img.Image, iconRect);
5191 catch (ArgumentException)
5193 item.RefreshImageAsync();
5199 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5200 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5202 item.GetImageAsync();
5205 if (item.StateIndex > -1)
5207 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5208 if (stateRect.Width > 0)
5210 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5211 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5212 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5217 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5219 base.ScaleControl(factor, specified);
5221 ScaleChildControl(this.TabImage, factor);
5223 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5224 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5226 foreach (var listview in listviews)
5228 ScaleChildControl(listview, factor);
5232 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5234 // ImageListViewItem item = (ImageListViewItem)e.Item;
5235 // if (item.StateImageIndex > -1)
5237 // ////e.Bounds.Leftが常に0を指すから自前で計算
5238 // //Rectangle itemRect = item.Bounds;
5239 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5241 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5243 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5245 // // itemRect.X += clm.Width;
5249 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5250 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5252 // if (rct.Width > 0)
5254 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5255 // //e.Graphics.FillRectangle(Brushes.White, rct);
5256 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5257 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5262 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5264 var tab = this._statuses.Tabs[this._curTab.Text];
5266 if (tab.AllCount == 0)
5268 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5272 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5277 case SEARCHTYPE.NextSearch: // 次を検索
5278 if (selectedIndex != -1)
5279 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5283 case SEARCHTYPE.PrevSearch: // 前を検索
5284 if (selectedIndex != -1)
5285 startIndex = Math.Max(selectedIndex - 1, 0);
5287 startIndex = tab.AllCount - 1;
5289 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5291 if (selectedIndex != -1)
5292 startIndex = selectedIndex;
5298 Func<string, bool> stringComparer;
5301 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5303 catch (ArgumentException)
5305 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5309 var reverse = searchType == SEARCHTYPE.PrevSearch;
5310 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5311 .DefaultIfEmpty(-1).First();
5313 if (foundIndex == -1)
5315 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5319 this.SelectListItem(this._curList, foundIndex);
5320 this._curList.EnsureVisible(foundIndex);
5323 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5326 this.ShowSearchDialog();
5329 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5331 var previousSearch = this.SearchDialog.ResultOptions;
5332 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5334 this.SearchDialog.Reset();
5335 this.ShowSearchDialog();
5341 previousSearch.Query,
5342 previousSearch.CaseSensitive,
5343 previousSearch.UseRegex,
5344 SEARCHTYPE.NextSearch);
5347 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5349 var previousSearch = this.SearchDialog.ResultOptions;
5350 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5352 this.SearchDialog.Reset();
5353 this.ShowSearchDialog();
5359 previousSearch.Query,
5360 previousSearch.CaseSensitive,
5361 previousSearch.UseRegex,
5362 SEARCHTYPE.PrevSearch);
5366 /// 検索ダイアログを表示し、検索を実行します
5368 private void ShowSearchDialog()
5370 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5372 this.TopMost = SettingManager.Common.AlwaysTop;
5375 this.TopMost = SettingManager.Common.AlwaysTop;
5377 var searchOptions = this.SearchDialog.ResultOptions;
5378 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5380 if (searchOptions.NewTab)
5382 var tabName = Properties.Resources.SearchResults_TabName;
5386 tabName = this._statuses.MakeTabName(tabName);
5388 catch (TabException ex)
5390 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5393 var resultTab = new LocalSearchTabModel(tabName);
5394 this.AddNewTab(resultTab, startup: false);
5395 this._statuses.AddTab(resultTab);
5397 var targetTab = this._statuses.Tabs[this._curTab.Text];
5399 Func<string, bool> stringComparer;
5402 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5404 catch (ArgumentException)
5406 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5410 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5411 if (foundIndices.Length == 0)
5413 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5417 var foundPosts = foundIndices.Select(x => targetTab[x]);
5418 foreach (var post in foundPosts)
5420 resultTab.AddPostQueue(post);
5423 this._statuses.DistributePosts();
5424 this.RefreshTimeline();
5426 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5427 .First(x => x.Text == tabName);
5429 this.ListTab.SelectedTab = tabPage;
5434 searchOptions.Query,
5435 searchOptions.CaseSensitive,
5436 searchOptions.UseRegex,
5437 SEARCHTYPE.DialogSearch);
5440 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5442 this.AddNewTabForSearch(searchOptions.Query);
5446 /// <summary>発言検索に使用するメソッドを生成します</summary>
5447 /// <exception cref="ArgumentException">
5448 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5450 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5454 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5455 var regex = new Regex(query, regexOption);
5457 return x => regex.IsMatch(x);
5461 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5463 return x => x.IndexOf(query, comparisonType) != -1;
5467 private void AboutMenuItem_Click(object sender, EventArgs e)
5469 using (TweenAboutBox about = new TweenAboutBox())
5471 about.ShowDialog(this);
5473 this.TopMost = SettingManager.Common.AlwaysTop;
5476 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5478 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5480 if (ImageSelector.Enabled)
5483 TabModel foundTab = null;
5486 DetailsListView lst = null;
5489 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5491 var tabPage = this.ListTab.TabPages[i];
5492 var tab = this._statuses.Tabs[tabPage.Text];
5493 var unreadIndex = tab.NextUnreadIndex;
5495 if (unreadIndex != -1)
5497 ListTab.SelectedIndex = i;
5499 foundIndex = unreadIndex;
5500 lst = (DetailsListView)tabPage.Tag;
5505 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5506 if (foundTab == null && bgnIdx > 0)
5508 for (int i = 0; i < bgnIdx; i++)
5510 var tabPage = this.ListTab.TabPages[i];
5511 var tab = this._statuses.Tabs[tabPage.Text];
5512 var unreadIndex = tab.NextUnreadIndex;
5514 if (unreadIndex != -1)
5516 ListTab.SelectedIndex = i;
5518 foundIndex = unreadIndex;
5519 lst = (DetailsListView)tabPage.Tag;
5525 if (foundTab == null)
5527 //全部調べたが未読見つからず→先頭タブの最新発言へ
5528 ListTab.SelectedIndex = 0;
5529 var tabPage = this.ListTab.TabPages[0];
5530 var tab = this._statuses.Tabs[tabPage.Text];
5532 if (tab.AllCount == 0)
5535 if (_statuses.SortOrder == SortOrder.Ascending)
5536 foundIndex = tab.AllCount - 1;
5540 lst = (DetailsListView)tabPage.Tag;
5543 SelectListItem(lst, foundIndex);
5545 if (_statuses.SortMode == ComparerMode.Id)
5547 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5548 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5554 lst.EnsureVisible(foundIndex);
5559 lst.EnsureVisible(foundIndex);
5565 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5567 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5569 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5570 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5574 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5576 if (_curList.SelectedIndices.Count > 0)
5578 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5579 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5583 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5585 await this.CheckNewVersion(false);
5588 private void RunTweenUp()
5590 ProcessStartInfo pinfo = new ProcessStartInfo();
5591 pinfo.UseShellExecute = true;
5592 pinfo.WorkingDirectory = MyCommon.settingPath;
5593 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5594 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5597 Process.Start(pinfo);
5601 MessageBox.Show("Failed to execute TweenUp3.exe.");
5605 public class VersionInfo
5607 public Version Version { get; set; }
5608 public Uri DownloadUri { get; set; }
5609 public string ReleaseNote { get; set; }
5613 /// OpenTween の最新バージョンの情報を取得します
5615 public async Task<VersionInfo> GetVersionInfoAsync()
5617 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5618 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5620 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5621 .ConfigureAwait(false);
5623 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5624 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5626 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5627 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5629 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5631 return new VersionInfo
5633 Version = Version.Parse(msgHeader[0]),
5634 DownloadUri = new Uri(msgHeader[1]),
5635 ReleaseNote = msgBody,
5639 private async Task CheckNewVersion(bool startup = false)
5641 if (ApplicationSettings.VersionInfoUrl == null)
5642 return; // 更新チェック無効化
5646 var versionInfo = await this.GetVersionInfoAsync();
5648 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5653 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5654 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5655 msgtext = MyCommon.ReplaceAppName(msgtext);
5657 MessageBox.Show(msgtext,
5658 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5659 MessageBoxButtons.OK, MessageBoxIcon.Information);
5664 using (var dialog = new UpdateDialog())
5666 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5667 MyCommon.GetReadableVersion(versionInfo.Version));
5668 dialog.DetailsText = versionInfo.ReleaseNote;
5670 if (dialog.ShowDialog(this) == DialogResult.Yes)
5672 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5678 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5681 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5682 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5683 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5688 private async Task Colorize()
5691 await this.DispSelectedPost();
5692 //件数関連の場合、タイトル即時書き換え
5693 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5694 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5695 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5696 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5698 SetMainWindowTitle();
5700 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5701 SetStatusLabelUrl();
5702 foreach (TabPage tb in ListTab.TabPages)
5704 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5706 if (SettingManager.Common.TabIconDisp)
5708 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5712 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
5715 public string createDetailHtml(string orgdata)
5717 if (SettingManager.Local.UseTwemoji)
5718 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5720 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5723 private Task DispSelectedPost()
5725 return this.DispSelectedPost(false);
5728 private PostClass displayPost = new PostClass();
5731 /// サムネイル表示に使用する CancellationToken の生成元
5733 private CancellationTokenSource thumbnailTokenSource = null;
5735 private async Task DispSelectedPost(bool forceupdate)
5737 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5740 var oldDisplayPost = this.displayPost;
5741 this.displayPost = this._curPost;
5743 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5746 var loadTasks = new List<Task>
5748 this.tweetDetailsView.ShowPostDetails(this._curPost),
5751 this.SplitContainer3.Panel2Collapsed = true;
5753 if (SettingManager.Common.PreviewEnable)
5755 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5756 oldTokenSource?.Cancel();
5758 var token = this.thumbnailTokenSource.Token;
5759 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5764 await Task.WhenAll(loadTasks);
5766 catch (OperationCanceledException) { }
5769 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5771 await this.OpenApplicationWebsite();
5774 private async Task OpenApplicationWebsite()
5776 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5779 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5781 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5784 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5786 if (ListTab.SelectedTab != null)
5788 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
5790 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
5791 if (pnl.Controls["comboSearch"].Focused ||
5792 pnl.Controls["comboLang"].Focused ||
5793 pnl.Controls["buttonSearch"].Focused) return;
5796 if (e.Control || e.Shift || e.Alt)
5797 this._anchorFlag = false;
5800 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
5803 e.SuppressKeyPress = true;
5806 if (asyncTask != null)
5811 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
5813 private void InitializeShortcuts()
5815 this.shortcutCommands = new[]
5817 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5818 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5819 .FocusedOn(FocusedControl.ListTab)
5820 .Do(() => SendKeys.Send("{DOWN}")),
5822 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5823 .FocusedOn(FocusedControl.ListTab)
5824 .Do(() => SendKeys.Send("{UP}")),
5826 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5827 .FocusedOn(FocusedControl.ListTab)
5828 .Do(() => SendKeys.Send("{PGDN}")),
5830 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5831 .FocusedOn(FocusedControl.ListTab)
5832 .Do(() => SendKeys.Send("{PGUP}")),
5834 ShortcutCommand.Create(Keys.F1)
5835 .Do(() => this.OpenApplicationWebsite()),
5837 ShortcutCommand.Create(Keys.F3)
5838 .Do(() => this.MenuItemSearchNext_Click(null, null)),
5840 ShortcutCommand.Create(Keys.F5)
5841 .Do(() => this.DoRefresh()),
5843 ShortcutCommand.Create(Keys.F6)
5844 .Do(() => this.GetReplyAsync()),
5846 ShortcutCommand.Create(Keys.F7)
5847 .Do(() => this.GetDirectMessagesAsync()),
5849 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5850 .NotFocusedOn(FocusedControl.StatusText)
5851 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5853 ShortcutCommand.Create(Keys.G)
5854 .NotFocusedOn(FocusedControl.StatusText)
5855 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5857 ShortcutCommand.Create(Keys.Right, Keys.N)
5858 .FocusedOn(FocusedControl.ListTab)
5859 .Do(() => this.GoRelPost(forward: true)),
5861 ShortcutCommand.Create(Keys.Left, Keys.P)
5862 .FocusedOn(FocusedControl.ListTab)
5863 .Do(() => this.GoRelPost(forward: false)),
5865 ShortcutCommand.Create(Keys.OemPeriod)
5866 .FocusedOn(FocusedControl.ListTab)
5867 .Do(() => this.GoAnchor()),
5869 ShortcutCommand.Create(Keys.I)
5870 .FocusedOn(FocusedControl.ListTab)
5871 .OnlyWhen(() => this.StatusText.Enabled)
5872 .Do(() => this.StatusText.Focus()),
5874 ShortcutCommand.Create(Keys.Enter)
5875 .FocusedOn(FocusedControl.ListTab)
5876 .Do(() => this.MakeReplyOrDirectStatus()),
5878 ShortcutCommand.Create(Keys.R)
5879 .FocusedOn(FocusedControl.ListTab)
5880 .Do(() => this.DoRefresh()),
5882 ShortcutCommand.Create(Keys.L)
5883 .FocusedOn(FocusedControl.ListTab)
5884 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5886 ShortcutCommand.Create(Keys.H)
5887 .FocusedOn(FocusedControl.ListTab)
5888 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5890 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5891 .FocusedOn(FocusedControl.ListTab)
5892 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5894 ShortcutCommand.Create(Keys.S)
5895 .FocusedOn(FocusedControl.ListTab)
5896 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5898 ShortcutCommand.Create(Keys.A)
5899 .FocusedOn(FocusedControl.ListTab)
5900 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5902 // ] in_reply_to参照元へ戻る
5903 ShortcutCommand.Create(Keys.Oem4)
5904 .FocusedOn(FocusedControl.ListTab)
5905 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5907 // [ in_reply_toへジャンプ
5908 ShortcutCommand.Create(Keys.Oem6)
5909 .FocusedOn(FocusedControl.ListTab)
5910 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5912 ShortcutCommand.Create(Keys.Escape)
5913 .FocusedOn(FocusedControl.ListTab)
5915 this._anchorFlag = false;
5916 if (ListTab.SelectedTab != null)
5918 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
5919 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5921 var relTp = ListTab.SelectedTab;
5922 RemoveSpecifiedTab(relTp.Text, false);
5928 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5929 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5930 .FocusedOn(FocusedControl.ListTab)
5931 .Do(() => this._anchorFlag = false, preventDefault: false),
5933 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5934 ShortcutCommand.Create(Keys.Up, Keys.Down)
5935 .FocusedOn(FocusedControl.PostBrowser)
5938 ShortcutCommand.Create(Keys.Control | Keys.R)
5939 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5941 ShortcutCommand.Create(Keys.Control | Keys.D)
5942 .Do(() => this.doStatusDelete()),
5944 ShortcutCommand.Create(Keys.Control | Keys.M)
5945 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5947 ShortcutCommand.Create(Keys.Control | Keys.S)
5948 .Do(() => this.FavoriteChange(FavAdd: true)),
5950 ShortcutCommand.Create(Keys.Control | Keys.I)
5951 .Do(() => this.doRepliedStatusOpen()),
5953 ShortcutCommand.Create(Keys.Control | Keys.Q)
5954 .Do(() => this.doQuoteOfficial()),
5956 ShortcutCommand.Create(Keys.Control | Keys.B)
5957 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5959 ShortcutCommand.Create(Keys.Control | Keys.T)
5960 .Do(() => this.HashManageMenuItem_Click(null, null)),
5962 ShortcutCommand.Create(Keys.Control | Keys.L)
5963 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5965 ShortcutCommand.Create(Keys.Control | Keys.Y)
5966 .NotFocusedOn(FocusedControl.PostBrowser)
5967 .Do(() => this.MultiLineMenuItem_Click(null, null)),
5969 ShortcutCommand.Create(Keys.Control | Keys.F)
5970 .Do(() => this.MenuItemSubSearch_Click(null, null)),
5972 ShortcutCommand.Create(Keys.Control | Keys.U)
5973 .Do(() => this.ShowUserTimeline()),
5975 ShortcutCommand.Create(Keys.Control | Keys.H)
5976 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5978 ShortcutCommand.Create(Keys.Control | Keys.G)
5979 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
5981 ShortcutCommand.Create(Keys.Control | Keys.O)
5982 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
5984 ShortcutCommand.Create(Keys.Control | Keys.E)
5985 .Do(() => this.OpenURLMenuItem_Click(null, null)),
5987 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5988 .FocusedOn(FocusedControl.ListTab)
5989 .Do(() => this._colorize = true, preventDefault: false),
5991 ShortcutCommand.Create(Keys.Control | Keys.N)
5992 .FocusedOn(FocusedControl.ListTab)
5993 .Do(() => this.GoNextTab(forward: true)),
5995 ShortcutCommand.Create(Keys.Control | Keys.P)
5996 .FocusedOn(FocusedControl.ListTab)
5997 .Do(() => this.GoNextTab(forward: false)),
5999 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6000 .FocusedOn(FocusedControl.ListTab)
6001 .Do(() => this.CopyStot()),
6003 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6004 ShortcutCommand.Create(Keys.Control | Keys.D1)
6005 .FocusedOn(FocusedControl.ListTab)
6006 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6007 .Do(() => this.ListTab.SelectedIndex = 0),
6009 ShortcutCommand.Create(Keys.Control | Keys.D2)
6010 .FocusedOn(FocusedControl.ListTab)
6011 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6012 .Do(() => this.ListTab.SelectedIndex = 1),
6014 ShortcutCommand.Create(Keys.Control | Keys.D3)
6015 .FocusedOn(FocusedControl.ListTab)
6016 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6017 .Do(() => this.ListTab.SelectedIndex = 2),
6019 ShortcutCommand.Create(Keys.Control | Keys.D4)
6020 .FocusedOn(FocusedControl.ListTab)
6021 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6022 .Do(() => this.ListTab.SelectedIndex = 3),
6024 ShortcutCommand.Create(Keys.Control | Keys.D5)
6025 .FocusedOn(FocusedControl.ListTab)
6026 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6027 .Do(() => this.ListTab.SelectedIndex = 4),
6029 ShortcutCommand.Create(Keys.Control | Keys.D6)
6030 .FocusedOn(FocusedControl.ListTab)
6031 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6032 .Do(() => this.ListTab.SelectedIndex = 5),
6034 ShortcutCommand.Create(Keys.Control | Keys.D7)
6035 .FocusedOn(FocusedControl.ListTab)
6036 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6037 .Do(() => this.ListTab.SelectedIndex = 6),
6039 ShortcutCommand.Create(Keys.Control | Keys.D8)
6040 .FocusedOn(FocusedControl.ListTab)
6041 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6042 .Do(() => this.ListTab.SelectedIndex = 7),
6044 ShortcutCommand.Create(Keys.Control | Keys.D9)
6045 .FocusedOn(FocusedControl.ListTab)
6046 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6048 ShortcutCommand.Create(Keys.Control | Keys.A)
6049 .FocusedOn(FocusedControl.StatusText)
6050 .Do(() => this.StatusText.SelectAll()),
6052 ShortcutCommand.Create(Keys.Control | Keys.V)
6053 .FocusedOn(FocusedControl.StatusText)
6054 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6056 ShortcutCommand.Create(Keys.Control | Keys.Up)
6057 .FocusedOn(FocusedControl.StatusText)
6059 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6061 var inReplyToStatusId = this.inReplyTo?.Item1;
6062 var inReplyToScreenName = this.inReplyTo?.Item2;
6063 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6066 if (_hisIdx < 0) _hisIdx = 0;
6068 var historyItem = this._history[this._hisIdx];
6069 StatusText.Text = historyItem.status;
6070 StatusText.SelectionStart = StatusText.Text.Length;
6071 if (historyItem.inReplyToId != null)
6072 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6074 this.inReplyTo = null;
6077 ShortcutCommand.Create(Keys.Control | Keys.Down)
6078 .FocusedOn(FocusedControl.StatusText)
6080 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6082 var inReplyToStatusId = this.inReplyTo?.Item1;
6083 var inReplyToScreenName = this.inReplyTo?.Item2;
6084 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6087 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6089 var historyItem = this._history[this._hisIdx];
6090 StatusText.Text = historyItem.status;
6091 StatusText.SelectionStart = StatusText.Text.Length;
6092 if (historyItem.inReplyToId != null)
6093 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6095 this.inReplyTo = null;
6098 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6099 .FocusedOn(FocusedControl.StatusText)
6101 if (ListTab.SelectedIndex == 0)
6103 ListTab.SelectedIndex = ListTab.TabCount - 1;
6107 ListTab.SelectedIndex -= 1;
6112 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6113 .FocusedOn(FocusedControl.StatusText)
6115 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6117 ListTab.SelectedIndex = 0;
6121 ListTab.SelectedIndex += 1;
6126 ShortcutCommand.Create(Keys.Control | Keys.Y)
6127 .FocusedOn(FocusedControl.PostBrowser)
6129 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6130 MultiLineMenuItem_Click(null, null);
6133 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6134 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6136 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6137 .Do(() => this.DoRefreshMore()),
6139 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6140 .Do(() => this.GetReplyAsync(loadMore: true)),
6142 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6143 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6145 ShortcutCommand.Create(Keys.Shift | Keys.R)
6146 .NotFocusedOn(FocusedControl.StatusText)
6147 .Do(() => this.DoRefreshMore()),
6149 ShortcutCommand.Create(Keys.Shift | Keys.H)
6150 .FocusedOn(FocusedControl.ListTab)
6151 .Do(() => this.GoTopEnd(GoTop: true)),
6153 ShortcutCommand.Create(Keys.Shift | Keys.L)
6154 .FocusedOn(FocusedControl.ListTab)
6155 .Do(() => this.GoTopEnd(GoTop: false)),
6157 ShortcutCommand.Create(Keys.Shift | Keys.M)
6158 .FocusedOn(FocusedControl.ListTab)
6159 .Do(() => this.GoMiddle()),
6161 ShortcutCommand.Create(Keys.Shift | Keys.G)
6162 .FocusedOn(FocusedControl.ListTab)
6163 .Do(() => this.GoLast()),
6165 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6166 .FocusedOn(FocusedControl.ListTab)
6167 .Do(() => this.MoveMiddle()),
6169 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6170 .FocusedOn(FocusedControl.ListTab)
6171 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6173 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6174 .FocusedOn(FocusedControl.ListTab)
6175 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6177 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6178 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6179 .FocusedOn(FocusedControl.ListTab)
6180 .Do(() => this.GoFav(forward: true)),
6182 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6183 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6184 .FocusedOn(FocusedControl.ListTab)
6185 .Do(() => this.GoFav(forward: false)),
6187 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6188 .FocusedOn(FocusedControl.ListTab)
6189 .Do(() => this.GoBackSelectPostChain()),
6191 ShortcutCommand.Create(Keys.Alt | Keys.R)
6192 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6194 ShortcutCommand.Create(Keys.Alt | Keys.P)
6195 .OnlyWhen(() => this._curPost != null)
6196 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6198 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6199 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6201 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6202 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6204 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6205 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6207 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6208 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6210 // 別タブの同じ書き込みへ(ALT+←/→)
6211 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6212 .FocusedOn(FocusedControl.ListTab)
6213 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6215 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6216 .FocusedOn(FocusedControl.ListTab)
6217 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6219 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6220 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6222 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6223 .Do(() => this.CopyIdUri()),
6225 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6226 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6227 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6228 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6230 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6231 .Do(() => this.FavoriteChange(FavAdd: false)),
6233 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6234 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6236 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6237 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6239 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6240 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6242 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6243 .Do(() => this.doMoveToRTHome()),
6245 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6246 .Do(() => this.FavorareMenuItem_Click(null, null)),
6248 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6249 .FocusedOn(FocusedControl.StatusText)
6251 if (_curList != null && _curList.VirtualListSize != 0 &&
6252 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6254 var idx = _curList.SelectedIndices[0] - 1;
6255 SelectListItem(_curList, idx);
6256 _curList.EnsureVisible(idx);
6260 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6261 .FocusedOn(FocusedControl.StatusText)
6263 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6264 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6266 var idx = _curList.SelectedIndices[0] + 1;
6267 SelectListItem(_curList, idx);
6268 _curList.EnsureVisible(idx);
6272 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6273 .FocusedOn(FocusedControl.StatusText)
6275 if (StatusText.SelectionStart > 0)
6277 int endidx = StatusText.SelectionStart - 1;
6278 string startstr = "";
6279 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6281 char c = StatusText.Text[i];
6282 if (Char.IsLetterOrDigit(c) || c == '_')
6288 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6289 int cnt = AtIdSupl.ItemCount;
6290 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6291 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6295 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6296 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6306 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6307 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6308 .FocusedOn(FocusedControl.ListTab)
6309 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6311 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6312 .FocusedOn(FocusedControl.ListTab)
6313 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6315 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6316 .FocusedOn(FocusedControl.ListTab)
6317 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6319 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6320 .FocusedOn(FocusedControl.ListTab)
6321 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6323 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6324 .FocusedOn(FocusedControl.ListTab)
6325 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6327 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6328 .FocusedOn(FocusedControl.ListTab)
6329 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6331 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6332 .FocusedOn(FocusedControl.ListTab)
6333 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6335 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6336 .FocusedOn(FocusedControl.ListTab)
6337 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6339 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6340 .FocusedOn(FocusedControl.ListTab)
6341 .Do(() => this.SetSortLastColumn()),
6343 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6344 .Do(() => this.FavoritesRetweetOfficial()),
6346 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6347 .Do(() => this.FavoritesRetweetUnofficial()),
6349 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6350 .Do(() => this.OpenUserAppointUrl()),
6352 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6353 .FocusedOn(FocusedControl.PostBrowser)
6354 .Do(() => this.doReTweetUnofficial()),
6356 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6357 .OnlyWhen(() => this.ExistCurrentPost)
6358 .Do(() => this.tweetDetailsView.DoTranslation()),
6360 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6361 .Do(() => this.doReTweetUnofficial()),
6363 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6364 .Do(() => this.CopyUserId()),
6366 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6367 .Do(() => this.tweetThumbnail1.ScrollUp()),
6369 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6370 .Do(() => this.tweetThumbnail1.ScrollDown()),
6372 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6373 .FocusedOn(FocusedControl.ListTab)
6374 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6375 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6379 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6381 // Task を返す非同期処理があれば asyncTask に代入する
6384 // ShortcutCommand に対応しているコマンドはここで処理される
6385 foreach (var command in this.shortcutCommands)
6387 if (command.IsMatch(keyData, focusedOn))
6389 asyncTask = command.RunCommand();
6390 return command.PreventDefault;
6397 private void GoNextTab(bool forward)
6399 int idx = ListTab.SelectedIndex;
6403 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6408 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6410 ListTab.SelectedIndex = idx;
6413 private void CopyStot()
6416 StringBuilder sb = new StringBuilder();
6417 bool IsProtected = false;
6419 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6420 foreach (int idx in _curList.SelectedIndices)
6422 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6423 if (post.IsDeleted) continue;
6426 if (post.RetweetedId != null)
6427 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6429 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6433 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6438 MessageBox.Show(Properties.Resources.CopyStotText1);
6442 clstr = sb.ToString();
6445 Clipboard.SetDataObject(clstr, false, 5, 100);
6447 catch (Exception ex)
6449 MessageBox.Show(ex.Message);
6454 private void CopyIdUri()
6456 if (this._curTab == null)
6459 var tab = this._statuses.GetTabByName(this._curTab.Text);
6460 if (tab == null || tab is DirectMessagesTabModel)
6463 var copyUrls = new List<string>();
6464 foreach (int idx in _curList.SelectedIndices)
6466 var post = tab[idx];
6467 copyUrls.Add(MyCommon.GetStatusUrl(post));
6470 if (copyUrls.Count == 0)
6475 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6477 catch (ExternalException ex)
6479 MessageBox.Show(ex.Message);
6483 private void GoFav(bool forward)
6485 if (_curList.VirtualListSize == 0) return;
6492 if (_curList.SelectedIndices.Count == 0)
6498 fIdx = _curList.SelectedIndices[0] + 1;
6499 if (fIdx > _curList.VirtualListSize - 1) return;
6501 toIdx = _curList.VirtualListSize;
6506 if (_curList.SelectedIndices.Count == 0)
6508 fIdx = _curList.VirtualListSize - 1;
6512 fIdx = _curList.SelectedIndices[0] - 1;
6513 if (fIdx < 0) return;
6519 for (int idx = fIdx; idx != toIdx; idx += stp)
6521 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6523 SelectListItem(_curList, idx);
6524 _curList.EnsureVisible(idx);
6530 private void GoSamePostToAnotherTab(bool left)
6532 if (this._curList.SelectedIndices.Count == 0)
6535 var tab = this._statuses.Tabs[this._curTab.Text];
6537 // Directタブは対象外(見つかるはずがない)
6538 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6541 var selectedIndex = this._curList.SelectedIndices[0];
6542 var selectedStatusId = tab.GetStatusIdAt(selectedIndex);
6544 int fIdx, toIdx, stp;
6549 if (ListTab.SelectedIndex == 0)
6555 fIdx = ListTab.SelectedIndex - 1;
6563 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6569 fIdx = ListTab.SelectedIndex + 1;
6571 toIdx = ListTab.TabCount;
6575 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6577 var targetTab = this._statuses.Tabs[this.ListTab.TabPages[tabidx].Text];
6580 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6583 var foundIndex = targetTab.IndexOf(selectedStatusId);
6584 if (foundIndex != -1)
6586 ListTab.SelectedIndex = tabidx;
6587 SelectListItem(_curList, foundIndex);
6588 _curList.EnsureVisible(foundIndex);
6594 private void GoPost(bool forward)
6596 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6599 var tab = this._statuses.Tabs[this._curTab.Text];
6600 var selectedIndex = this._curList.SelectedIndices[0];
6602 int fIdx, toIdx, stp;
6606 fIdx = selectedIndex + 1;
6607 if (fIdx > tab.AllCount - 1) return;
6608 toIdx = tab.AllCount;
6613 fIdx = selectedIndex - 1;
6614 if (fIdx < 0) return;
6620 if (_curPost.RetweetedId == null)
6622 name = _curPost.ScreenName;
6626 name = _curPost.RetweetedBy;
6628 for (int idx = fIdx; idx != toIdx; idx += stp)
6630 var post = tab[idx];
6631 if (post.RetweetedId == null)
6633 if (post.ScreenName == name)
6635 SelectListItem(_curList, idx);
6636 _curList.EnsureVisible(idx);
6642 if (post.RetweetedBy == name)
6644 SelectListItem(_curList, idx);
6645 _curList.EnsureVisible(idx);
6652 private void GoRelPost(bool forward)
6654 if (this._curList.SelectedIndices.Count == 0)
6657 var tab = this._statuses.Tabs[this._curTab.Text];
6658 var selectedIndex = this._curList.SelectedIndices[0];
6660 int fIdx, toIdx, stp;
6664 fIdx = selectedIndex + 1;
6665 if (fIdx > tab.AllCount - 1) return;
6666 toIdx = tab.AllCount;
6671 fIdx = selectedIndex - 1;
6672 if (fIdx < 0) return;
6679 if (_curPost == null) return;
6680 _anchorPost = _curPost;
6685 if (_anchorPost == null) return;
6688 for (int idx = fIdx; idx != toIdx; idx += stp)
6690 var post = tab[idx];
6691 if (post.ScreenName == _anchorPost.ScreenName ||
6692 post.RetweetedBy == _anchorPost.ScreenName ||
6693 post.ScreenName == _anchorPost.RetweetedBy ||
6694 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6695 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
6696 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
6697 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
6698 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
6700 SelectListItem(_curList, idx);
6701 _curList.EnsureVisible(idx);
6707 private void GoAnchor()
6709 if (_anchorPost == null) return;
6710 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6711 if (idx == -1) return;
6713 SelectListItem(_curList, idx);
6714 _curList.EnsureVisible(idx);
6717 private void GoTopEnd(bool GoTop)
6719 if (_curList.VirtualListSize == 0)
6727 _item = _curList.GetItemAt(0, 25);
6735 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6737 idx = _curList.VirtualListSize - 1;
6741 SelectListItem(_curList, idx);
6744 private void GoMiddle()
6746 if (_curList.VirtualListSize == 0)
6754 _item = _curList.GetItemAt(0, 0);
6764 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6767 idx2 = _curList.VirtualListSize - 1;
6773 idx3 = (idx1 + idx2) / 2;
6775 SelectListItem(_curList, idx3);
6778 private void GoLast()
6780 if (_curList.VirtualListSize == 0) return;
6782 if (_statuses.SortOrder == SortOrder.Ascending)
6784 SelectListItem(_curList, _curList.VirtualListSize - 1);
6785 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6789 SelectListItem(_curList, 0);
6790 _curList.EnsureVisible(0);
6794 private void MoveTop()
6796 if (_curList.SelectedIndices.Count == 0) return;
6797 int idx = _curList.SelectedIndices[0];
6798 if (_statuses.SortOrder == SortOrder.Ascending)
6800 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6804 _curList.EnsureVisible(0);
6806 _curList.EnsureVisible(idx);
6809 private async Task GoInReplyToPostTree()
6811 if (_curPost == null) return;
6813 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6815 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
6819 var post = await tw.GetStatusApi(false, _curPost.StatusId);
6821 _curPost.InReplyToStatusId = post.InReplyToStatusId;
6822 _curPost.InReplyToUser = post.InReplyToUser;
6823 _curPost.IsReply = post.IsReply;
6824 this.PurgeListViewItemCache();
6825 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
6827 catch (WebApiException ex)
6829 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6833 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
6835 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
6837 replyChains = new Stack<ReplyChain>();
6839 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
6842 string inReplyToTabName;
6843 long inReplyToId = _curPost.InReplyToStatusId.Value;
6844 string inReplyToUser = _curPost.InReplyToUser;
6845 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6847 var inReplyToPosts = from tab in _statuses.Tabs.Values
6848 orderby tab != curTabClass
6849 from post in tab.Posts.Values
6850 where post.StatusId == inReplyToId
6851 let index = tab.IndexOf(post.StatusId)
6853 select new {Tab = tab, Index = index};
6855 var inReplyPost = inReplyToPosts.FirstOrDefault();
6856 if (inReplyPost == null)
6860 await Task.Run(async () =>
6862 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
6863 .ConfigureAwait(false);
6866 _statuses.AddPost(post);
6867 _statuses.DistributePosts();
6870 catch (WebApiException ex)
6872 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6873 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6877 this.RefreshTimeline();
6879 inReplyPost = inReplyToPosts.FirstOrDefault();
6880 if (inReplyPost == null)
6882 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6886 inReplyToTabName = inReplyPost.Tab.TabName;
6887 inReplyToIndex = inReplyPost.Index;
6889 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
6890 DetailsListView listView = (DetailsListView)tabPage.Tag;
6892 if (_curTab != tabPage)
6894 this.ListTab.SelectTab(tabPage);
6897 this.SelectListItem(listView, inReplyToIndex);
6898 listView.EnsureVisible(inReplyToIndex);
6901 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6903 if (_curPost == null) return;
6905 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6906 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6910 if (_curPost.InReplyToStatusId != null)
6912 var posts = from t in _statuses.Tabs
6913 from p in t.Value.Posts
6914 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
6915 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6917 orderby isForward ? indexOf : indexOf * -1
6918 orderby t.Value != curTabClass
6919 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
6922 var postList = posts.ToList();
6923 for (int i = postList.Count - 1; i >= 0; i--)
6926 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
6928 postList.RemoveAt(index);
6931 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
6932 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
6933 if (post == null) post = postList.First();
6934 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6935 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6936 SelectListItem(listView, post.Index);
6937 listView.EnsureVisible(post.Index);
6939 catch (InvalidOperationException)
6947 if (replyChains == null || replyChains.Count < 1)
6949 var posts = from t in _statuses.Tabs
6950 from p in t.Value.Posts
6951 where p.Value.InReplyToStatusId == _curPost.StatusId
6952 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6955 orderby t.Value != curTabClass
6956 select new {Tab = t.Value, Index = indexOf};
6959 var post = posts.First();
6960 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6961 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6962 SelectListItem(listView, post.Index);
6963 listView.EnsureVisible(post.Index);
6965 catch (InvalidOperationException)
6972 ReplyChain chainHead = replyChains.Pop();
6973 if (chainHead.InReplyToId == _curPost.StatusId)
6975 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
6984 ListTab.SelectTab(chainHead.OriginalTab);
6990 SelectListItem(_curList, idx);
6991 _curList.EnsureVisible(idx);
6997 this.GoBackInReplyToPostTree(parallel);
7003 private void GoBackSelectPostChain()
7005 if (this.selectPostChains.Count > 1)
7014 this.selectPostChains.Pop();
7015 var tabPostPair = this.selectPostChains.Peek();
7017 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7019 if (tabPostPair.Item2 != null)
7021 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7022 if (idx == -1) continue; //該当ポストが存在しないので無視
7025 tp = tabPostPair.Item1;
7027 this.selectPostChains.Pop();
7029 catch (InvalidOperationException)
7035 while (this.selectPostChains.Count > 1);
7040 //履歴が残り1つであればクリアしておく
7041 if (this.selectPostChains.Count == 1)
7042 this.selectPostChains.Clear();
7046 DetailsListView lst = (DetailsListView)tp.Tag;
7047 this.ListTab.SelectedTab = tp;
7050 SelectListItem(lst, idx);
7051 lst.EnsureVisible(idx);
7057 private void PushSelectPostChain()
7059 int count = this.selectPostChains.Count;
7062 var p = this.selectPostChains.Peek();
7063 if (p.Item1 == this._curTab)
7065 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7066 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7069 if (count >= 2500) TrimPostChain();
7070 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7073 private void TrimPostChain()
7075 if (this.selectPostChains.Count <= 2000) return;
7076 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7077 for (int i = 0; i < 2000; i++)
7079 p.Push(this.selectPostChains.Pop());
7081 this.selectPostChains.Clear();
7082 for (int i = 0; i < 2000; i++)
7084 this.selectPostChains.Push(p.Pop());
7088 private bool GoStatus(long statusId)
7090 if (statusId == 0) return false;
7091 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7093 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7095 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7096 ListTab.SelectedIndex = tabidx;
7097 SelectListItem(_curList, idx);
7098 _curList.EnsureVisible(idx);
7105 private bool GoDirectMessage(long statusId)
7107 if (statusId == 0) return false;
7108 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7110 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7112 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7113 ListTab.SelectedIndex = tabidx;
7114 SelectListItem(_curList, idx);
7115 _curList.EnsureVisible(idx);
7122 private void MyList_MouseClick(object sender, MouseEventArgs e)
7124 _anchorFlag = false;
7127 private void StatusText_Enter(object sender, EventArgs e)
7129 // フォーカスの戻り先を StatusText に設定
7130 this.Tag = StatusText;
7131 StatusText.BackColor = _clInputBackcolor;
7134 public Color InputBackColor
7136 get { return _clInputBackcolor; }
7137 set { _clInputBackcolor = value; }
7140 private void StatusText_Leave(object sender, EventArgs e)
7142 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7143 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7144 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7147 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7150 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7153 e.SuppressKeyPress = true;
7156 this.StatusText_TextChanged(null, null);
7158 if (asyncTask != null)
7162 private void SaveConfigsAll(bool ifModified)
7166 SaveConfigsCommon();
7173 if (ModifySettingCommon) SaveConfigsCommon();
7174 if (ModifySettingLocal) SaveConfigsLocal();
7175 if (ModifySettingAtId) SaveConfigsAtId();
7179 private void SaveConfigsAtId()
7181 if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7183 ModifySettingAtId = false;
7184 SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7185 SettingManager.SaveAtIdList();
7188 private void SaveConfigsCommon()
7190 if (_ignoreConfigSave) return;
7192 ModifySettingCommon = false;
7195 SettingManager.Common.UserName = tw.Username;
7196 SettingManager.Common.UserId = tw.UserId;
7197 SettingManager.Common.Token = tw.AccessToken;
7198 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7200 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7201 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7203 SettingManager.Common.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7206 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7207 switch (_statuses.SortMode)
7209 case ComparerMode.Nickname: //ニックネーム
7210 SettingManager.Common.SortColumn = 1;
7212 case ComparerMode.Data: //本文
7213 SettingManager.Common.SortColumn = 2;
7215 case ComparerMode.Id: //時刻=発言Id
7216 SettingManager.Common.SortColumn = 3;
7218 case ComparerMode.Name: //名前
7219 SettingManager.Common.SortColumn = 4;
7221 case ComparerMode.Source: //Source
7222 SettingManager.Common.SortColumn = 7;
7226 SettingManager.Common.HashTags = HashMgr.HashHistories;
7227 if (HashMgr.IsPermanent)
7229 SettingManager.Common.HashSelected = HashMgr.UseHash;
7233 SettingManager.Common.HashSelected = "";
7235 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7236 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7237 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7238 if (ToolStripFocusLockMenuItem != null &&
7239 ToolStripFocusLockMenuItem.IsDisposed == false)
7241 SettingManager.Common.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7243 SettingManager.Common.TrackWord = tw.TrackWord;
7244 SettingManager.Common.AllAtReply = tw.AllAtReply;
7245 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7246 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7248 SettingManager.SaveCommon();
7252 private void SaveConfigsLocal()
7254 if (_ignoreConfigSave) return;
7257 ModifySettingLocal = false;
7258 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7259 SettingManager.Local.FormSize = _mySize;
7260 SettingManager.Local.FormLocation = _myLoc;
7261 SettingManager.Local.SplitterDistance = _mySpDis;
7262 SettingManager.Local.PreviewDistance = _mySpDis3;
7263 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7264 SettingManager.Local.StatusTextHeight = _mySpDis2;
7266 SettingManager.Local.FontUnread = _fntUnread;
7267 SettingManager.Local.ColorUnread = _clUnread;
7268 SettingManager.Local.FontRead = _fntReaded;
7269 SettingManager.Local.ColorRead = _clReaded;
7270 SettingManager.Local.FontDetail = _fntDetail;
7271 SettingManager.Local.ColorDetail = _clDetail;
7272 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7273 SettingManager.Local.ColorDetailLink = _clDetailLink;
7274 SettingManager.Local.ColorFav = _clFav;
7275 SettingManager.Local.ColorOWL = _clOWL;
7276 SettingManager.Local.ColorRetweet = _clRetweet;
7277 SettingManager.Local.ColorSelf = _clSelf;
7278 SettingManager.Local.ColorAtSelf = _clAtSelf;
7279 SettingManager.Local.ColorTarget = _clTarget;
7280 SettingManager.Local.ColorAtTarget = _clAtTarget;
7281 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7282 SettingManager.Local.ColorAtTo = _clAtTo;
7283 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7284 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7285 SettingManager.Local.ColorInputFont = _clInputFont;
7286 SettingManager.Local.FontInputFont = _fntInputFont;
7288 if (_ignoreConfigSave) return;
7289 SettingManager.SaveLocal();
7293 private void SaveConfigsTabs()
7295 var tabSettingList = new List<SettingTabs.SettingTabItem>();
7297 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7298 .Select(x => this._statuses.Tabs[x.Text])
7299 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7301 foreach (var tab in tabs)
7303 if (!tab.IsPermanentTabType)
7306 var tabSetting = new SettingTabs.SettingTabItem
7308 TabName = tab.TabName,
7309 TabType = tab.TabType,
7310 UnreadManage = tab.UnreadManage,
7311 Protected = tab.Protected,
7312 Notify = tab.Notify,
7313 SoundFile = tab.SoundFile,
7318 case FilterTabModel filterTab:
7319 tabSetting.FilterArray = filterTab.FilterArray;
7321 case UserTimelineTabModel userTab:
7322 tabSetting.User = userTab.ScreenName;
7324 case PublicSearchTabModel searchTab:
7325 tabSetting.SearchWords = searchTab.SearchWords;
7326 tabSetting.SearchLang = searchTab.SearchLang;
7328 case ListTimelineTabModel listTab:
7329 tabSetting.ListInfo = listTab.ListInfo;
7333 tabSettingList.Add(tabSetting);
7336 SettingManager.Tabs.Tabs = tabSettingList;
7337 SettingManager.SaveTabs();
7340 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7343 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7344 if (ret != DialogResult.OK)
7347 var match = Twitter.StatusUrlRegex.Match(inputText);
7350 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7351 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7357 var statusId = long.Parse(match.Groups["StatusId"].Value);
7358 await this.OpenRelatedTab(statusId);
7360 catch (TabException ex)
7362 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7366 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7368 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7369 Properties.Resources.SaveLogMenuItem_ClickText2,
7370 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7371 if (rslt == DialogResult.Cancel) return;
7373 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7374 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7375 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7376 SaveFileDialog1.FilterIndex = 0;
7377 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7378 SaveFileDialog1.RestoreDirectory = true;
7380 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7382 if (!SaveFileDialog1.ValidateNames) return;
7383 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7385 if (rslt == DialogResult.Yes)
7388 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7390 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7391 string protect = "";
7392 if (post.IsProtect) protect = "Protect";
7393 sw.WriteLine(post.Nickname + "\t" +
7394 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7395 post.CreatedAt + "\t" +
7396 post.ScreenName + "\t" +
7397 post.StatusId + "\t" +
7398 post.ImageUrl + "\t" +
7399 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7405 foreach (int idx in _curList.SelectedIndices)
7407 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7408 string protect = "";
7409 if (post.IsProtect) protect = "Protect";
7410 sw.WriteLine(post.Nickname + "\t" +
7411 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7412 post.CreatedAt + "\t" +
7413 post.ScreenName + "\t" +
7414 post.StatusId + "\t" +
7415 post.ImageUrl + "\t" +
7416 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7422 this.TopMost = SettingManager.Common.AlwaysTop;
7425 public bool TabRename(string origTabName, out string newTabName)
7429 using (InputTabName inputName = new InputTabName())
7431 inputName.TabName = origTabName;
7432 inputName.ShowDialog();
7433 if (inputName.DialogResult == DialogResult.Cancel) return false;
7434 newTabName = inputName.TabName;
7436 this.TopMost = SettingManager.Common.AlwaysTop;
7437 if (!string.IsNullOrEmpty(newTabName))
7440 for (int i = 0; i < ListTab.TabCount; i++)
7442 if (ListTab.TabPages[i].Text == newTabName)
7444 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7445 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7450 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
7451 .FirstOrDefault(x => x.Text == origTabName);
7454 if (tabPage != null)
7455 tabPage.Text = newTabName;
7457 _statuses.RenameTab(origTabName, newTabName);
7459 SaveConfigsCommon();
7461 _rclickTabName = newTabName;
7470 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7472 if (e.Button == MouseButtons.Middle)
7474 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7476 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7478 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7479 this.SaveConfigsTabs();
7486 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7489 TabRename(this.ListTab.SelectedTab.Text, out _);
7492 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7494 if (SettingManager.Common.TabMouseLock) return;
7495 if (e.Button == MouseButtons.Left)
7497 for (int i = 0; i < ListTab.TabPages.Count; i++)
7499 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7502 _tabMouseDownPoint = e.Location;
7513 private void ListTab_DragEnter(object sender, DragEventArgs e)
7515 if (e.Data.GetDataPresent(typeof(TabPage)))
7516 e.Effect = DragDropEffects.Move;
7518 e.Effect = DragDropEffects.None;
7521 private void ListTab_DragDrop(object sender, DragEventArgs e)
7523 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7528 Point cpos = new Point(e.X, e.Y);
7529 Point spos = ListTab.PointToClient(cpos);
7531 for (i = 0; i < ListTab.TabPages.Count; i++)
7533 Rectangle rect = ListTab.GetTabRect(i);
7534 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7535 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7537 tn = ListTab.TabPages[i].Text;
7538 if (spos.X <= (rect.Left + rect.Right) / 2)
7547 //タブのないところにドロップ->最後尾へ移動
7548 if (string.IsNullOrEmpty(tn))
7550 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7552 i = ListTab.TabPages.Count - 1;
7555 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7556 if (tp.Text == tn) return;
7558 ReOrderTab(tp.Text, tn, bef);
7561 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7563 var baseIndex = this.GetTabPageIndex(baseTabText);
7564 if (baseIndex == -1)
7567 var targetIndex = this.GetTabPageIndex(targetTabText);
7568 if (targetIndex == -1)
7571 using (ControlTransaction.Layout(this.ListTab))
7573 var mTp = this.ListTab.TabPages[targetIndex];
7574 this.ListTab.TabPages.Remove(mTp);
7576 if (targetIndex < baseIndex)
7579 if (isBeforeBaseTab)
7580 ListTab.TabPages.Insert(baseIndex, mTp);
7582 ListTab.TabPages.Insert(baseIndex + 1, mTp);
7588 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7590 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7591 //isReply:true=@,false=DM
7592 if (!StatusText.Enabled) return;
7593 if (_curList == null) return;
7594 if (_curTab == null) return;
7595 if (!this.ExistCurrentPost) return;
7597 // 複数あてリプライはReplyではなく通常ポスト
7598 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7599 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7600 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7602 if (_curList.SelectedIndices.Count > 0)
7605 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7608 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7611 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7612 StatusText.SelectionStart = StatusText.Text.Length;
7614 this.inReplyTo = null;
7617 if (string.IsNullOrEmpty(StatusText.Text))
7621 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7622 StatusText.Text = "@" + _curPost.ScreenName + " ";
7624 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7625 var inReplyToScreenName = this._curPost.ScreenName;
7626 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7634 //1件選んでEnter or DoubleClick
7635 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7637 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7640 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7641 var inReplyToScreenName = this._curPost.ScreenName;
7642 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7646 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7649 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7652 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7653 this.inReplyTo = null;
7658 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7659 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7660 var inReplyToScreenName = this._curPost.ScreenName;
7661 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7668 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7669 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7670 this.inReplyTo = null;
7675 //1件選んでCtrl-Rの場合(返信先操作せず)
7676 int sidx = StatusText.SelectionStart;
7677 string id = "@" + _curPost.ScreenName + " ";
7680 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7685 StatusText.Text = StatusText.Text.Insert(sidx, id);
7687 //if (StatusText.Text.StartsWith("@"))
7690 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7691 // sidx += 5 + _curPost.ScreenName.Length;
7696 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7697 // sidx += 3 + _curPost.ScreenName.Length;
7699 StatusText.SelectionStart = sidx;
7702 //_reply_to_name = null;
7710 if (!isAuto && !isReply) return;
7712 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7716 //Enter or DoubleClick
7718 string sTxt = StatusText.Text;
7719 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7722 this.inReplyTo = null;
7724 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7726 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7727 if (!sTxt.Contains("@" + post.ScreenName + " "))
7729 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7730 //sTxt = "@" + post.ScreenName + " " + sTxt;
7733 StatusText.Text = sTxt;
7738 if (_curList.SelectedIndices.Count > 1)
7743 int sidx = StatusText.SelectionStart;
7744 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7746 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7747 if (!ids.Contains("@" + post.ScreenName + " ") &&
7748 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7750 ids += "@" + post.ScreenName + " ";
7754 foreach (string nm in post.ReplyToList)
7756 if (!ids.Contains("@" + nm + " ") &&
7757 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7759 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7761 ids += "@" + m.Result("${id}") + " ";
7763 ids += "@" + nm + " ";
7768 if (ids.Length == 0) return;
7769 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7771 StatusText.Text = ". " + StatusText.Text;
7773 this.inReplyTo = null;
7777 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7782 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7784 //if (StatusText.Text.StartsWith("@"))
7786 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7787 // sidx += 2 + ids.Length;
7791 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7792 // sidx += 1 + ids.Length;
7794 StatusText.SelectionStart = sidx;
7800 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7803 int sidx = StatusText.SelectionStart;
7804 PostClass post = _curPost;
7805 if (!ids.Contains("@" + post.ScreenName + " ") &&
7806 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7808 ids += "@" + post.ScreenName + " ";
7810 foreach (string nm in post.ReplyToList)
7812 if (!ids.Contains("@" + nm + " ") &&
7813 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7815 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7817 ids += "@" + m.Result("${id}") + " ";
7819 ids += "@" + nm + " ";
7822 if (!string.IsNullOrEmpty(post.RetweetedBy))
7824 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
7825 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7827 ids += "@" + post.RetweetedBy + " ";
7830 if (ids.Length == 0) return;
7831 if (string.IsNullOrEmpty(StatusText.Text))
7834 StatusText.Text = ids;
7835 StatusText.SelectionStart = ids.Length;
7838 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7839 var inReplyToScreenName = this._curPost.ScreenName;
7840 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7846 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7851 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7853 StatusText.SelectionStart = sidx;
7859 StatusText.SelectionStart = StatusText.Text.Length;
7864 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7869 private static int iconCnt = 0;
7870 private static int blinkCnt = 0;
7871 private static bool blink = false;
7872 private static bool idle = false;
7874 private async Task RefreshTasktrayIcon()
7877 await this.Colorize();
7879 if (!TimerRefreshIcon.Enabled) return;
7880 //Static usCheckCnt As int = 0
7882 //Static iconDlListTopItem As ListViewItem = null
7884 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7885 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7887 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7889 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7895 //if (usCheckCnt > 300) //1min
7898 // if (!this.IsReceivedUserStream)
7900 // TraceOut("ReconnectUserStream");
7901 // tw.ReconnectUserStream();
7905 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7907 if (iconCnt >= this.NIconRefresh.Length)
7915 SaveConfigsAll(true);
7920 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7922 _myStatusError = false;
7926 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
7927 if (SettingManager.Common.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
7929 if (blinkCnt > 0) return;
7931 if (blink || SettingManager.Common.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
7933 NotifyIcon1.Icon = ReplyIcon;
7937 NotifyIcon1.Icon = ReplyIconBlink;
7945 //優先度:エラー→オフライン→アイドル
7949 NotifyIcon1.Icon = NIconAtRed;
7952 if (_myStatusOnline)
7954 NotifyIcon1.Icon = NIconAt;
7958 NotifyIcon1.Icon = NIconAtSmoke;
7962 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
7965 await this.RefreshTasktrayIcon();
7968 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7970 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7971 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7973 if (ListTab != null && ListTab.SelectedTab != null)
7974 _rclickTabName = ListTab.SelectedTab.Text;
7979 if (_statuses == null) return;
7980 if (_statuses.Tabs == null) return;
7983 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out tb))
7986 NotifyDispMenuItem.Checked = tb.Notify;
7987 this.NotifyTbMenuItem.Checked = tb.Notify;
7989 soundfileListup = true;
7990 SoundFileComboBox.Items.Clear();
7991 this.SoundFileTbComboBox.Items.Clear();
7992 SoundFileComboBox.Items.Add("");
7993 this.SoundFileTbComboBox.Items.Add("");
7994 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
7995 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
7997 oDir = oDir.GetDirectories("Sounds")[0];
7999 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8001 SoundFileComboBox.Items.Add(oFile.Name);
8002 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8004 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8005 if (idx == -1) idx = 0;
8006 SoundFileComboBox.SelectedIndex = idx;
8007 this.SoundFileTbComboBox.SelectedIndex = idx;
8008 soundfileListup = false;
8009 UreadManageMenuItem.Checked = tb.UnreadManage;
8010 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8012 TabMenuControl(_rclickTabName);
8015 private void TabMenuControl(string tabName)
8017 var tabInfo = _statuses.GetTabByName(tabName);
8019 this.FilterEditMenuItem.Enabled = true;
8020 this.EditRuleTbMenuItem.Enabled = true;
8022 if (tabInfo.IsDefaultTabType)
8024 this.ProtectTabMenuItem.Enabled = false;
8025 this.ProtectTbMenuItem.Enabled = false;
8029 this.ProtectTabMenuItem.Enabled = true;
8030 this.ProtectTbMenuItem.Enabled = true;
8033 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8035 this.ProtectTabMenuItem.Checked = true;
8036 this.ProtectTbMenuItem.Checked = true;
8037 this.DeleteTabMenuItem.Enabled = false;
8038 this.DeleteTbMenuItem.Enabled = false;
8042 this.ProtectTabMenuItem.Checked = false;
8043 this.ProtectTbMenuItem.Checked = false;
8044 this.DeleteTabMenuItem.Enabled = true;
8045 this.DeleteTbMenuItem.Enabled = true;
8049 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8051 var checkState = ((ToolStripMenuItem)sender).Checked;
8054 this.ProtectTbMenuItem.Checked = checkState;
8055 this.ProtectTabMenuItem.Checked = checkState;
8058 this.DeleteTabMenuItem.Enabled = !checkState;
8059 this.DeleteTbMenuItem.Enabled = !checkState;
8061 if (string.IsNullOrEmpty(_rclickTabName)) return;
8062 _statuses.Tabs[_rclickTabName].Protected = checkState;
8067 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8069 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8070 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8072 if (string.IsNullOrEmpty(_rclickTabName)) return;
8073 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8078 public void ChangeTabUnreadManage(string tabName, bool isManage)
8080 var idx = this.GetTabPageIndex(tabName);
8084 _statuses.Tabs[tabName].UnreadManage = isManage;
8085 if (SettingManager.Common.TabIconDisp)
8087 if (_statuses.Tabs[tabName].UnreadCount > 0)
8088 ListTab.TabPages[idx].ImageIndex = 0;
8090 ListTab.TabPages[idx].ImageIndex = -1;
8093 if (_curTab.Text == tabName)
8095 this.PurgeListViewItemCache();
8099 SetMainWindowTitle();
8100 SetStatusLabelUrl();
8101 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8104 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8106 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8107 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8109 if (string.IsNullOrEmpty(_rclickTabName)) return;
8111 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8116 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8118 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8120 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8125 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8127 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8129 RemoveSpecifiedTab(_rclickTabName, true);
8133 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8135 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8137 using (var fltDialog = new FilterDialog())
8139 fltDialog.Owner = this;
8140 fltDialog.SetCurrent(_rclickTabName);
8141 fltDialog.ShowDialog(this);
8143 this.TopMost = SettingManager.Common.AlwaysTop;
8145 this.ApplyPostFilters();
8149 private void AddTabMenuItem_Click(object sender, EventArgs e)
8151 string tabName = null;
8152 MyCommon.TabUsageType tabUsage;
8153 using (InputTabName inputName = new InputTabName())
8155 inputName.TabName = _statuses.MakeTabName("MyTab");
8156 inputName.IsShowUsage = true;
8157 inputName.ShowDialog();
8158 if (inputName.DialogResult == DialogResult.Cancel) return;
8159 tabName = inputName.TabName;
8160 tabUsage = inputName.Usage;
8162 this.TopMost = SettingManager.Common.AlwaysTop;
8163 if (!string.IsNullOrEmpty(tabName))
8166 ListElement list = null;
8167 if (tabUsage == MyCommon.TabUsageType.Lists)
8169 using (ListAvailable listAvail = new ListAvailable())
8171 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8172 if (listAvail.SelectedList == null) return;
8173 list = listAvail.SelectedList;
8180 case MyCommon.TabUsageType.UserDefined:
8181 tab = new FilterTabModel(tabName);
8183 case MyCommon.TabUsageType.PublicSearch:
8184 tab = new PublicSearchTabModel(tabName);
8186 case MyCommon.TabUsageType.Lists:
8187 tab = new ListTimelineTabModel(tabName, list);
8193 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8195 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8196 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8202 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8204 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8205 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8207 if (tabUsage == MyCommon.TabUsageType.Lists)
8209 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8210 var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8211 this.GetListTimelineAsync(listTab);
8217 private void TabMenuItem_Click(object sender, EventArgs e)
8219 using (var fltDialog = new FilterDialog())
8221 fltDialog.Owner = this;
8224 foreach (int idx in _curList.SelectedIndices)
8228 if (!SelectTab(out tabName)) return;
8230 fltDialog.SetCurrent(tabName);
8231 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8233 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8237 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8239 fltDialog.ShowDialog(this);
8240 this.TopMost = SettingManager.Common.AlwaysTop;
8244 this.ApplyPostFilters();
8246 if (this.ListTab.SelectedTab != null &&
8247 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8249 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8253 protected override bool ProcessDialogKey(Keys keyData)
8255 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8256 if ((keyData & Keys.KeyCode) == Keys.Enter)
8258 if (StatusText.Focused)
8260 bool _NewLine = false;
8263 if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8265 if (StatusText.Multiline)
8267 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8269 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8273 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8277 else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8279 if (StatusText.Multiline)
8281 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8283 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8287 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8293 if (StatusText.Multiline)
8295 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8297 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8298 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8302 if (((keyData & Keys.Shift) == Keys.Shift) ||
8303 (((keyData & Keys.Control) != Keys.Control) &&
8304 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8310 int pos1 = StatusText.SelectionStart;
8311 if (StatusText.SelectionLength > 0)
8313 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8315 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8316 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8321 PostButton_Click(null, null);
8325 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8326 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8327 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8329 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8334 return base.ProcessDialogKey(keyData);
8337 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8339 MakeReplyOrDirectStatus(false, true, true);
8342 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8345 if (_curList.SelectedIndices.Count == 0) return;
8347 var tab = this._statuses.Tabs[this._curTab.Text];
8348 var screenNameArray = this._curList.SelectedIndices.Cast<int>()
8349 .Select(x => tab[x])
8350 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8353 this.AddFilterRuleByScreenName(screenNameArray);
8355 if (screenNameArray.Length != 0)
8357 List<string> atids = new List<string>();
8358 foreach (var screenName in screenNameArray)
8360 atids.Add("@" + screenName);
8362 int cnt = AtIdSupl.ItemCount;
8363 AtIdSupl.AddRangeItem(atids.ToArray());
8364 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8368 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8370 if (this._curList.SelectedIndices.Count == 0)
8373 var tab = this._statuses.Tabs[this._curTab.Text];
8374 var sourceArray = this._curList.SelectedIndices.Cast<int>()
8375 .Select(x => tab[x].Source).ToArray();
8377 this.AddFilterRuleBySource(sourceArray);
8380 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8384 if (!SelectTab(out tabName)) return;
8386 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8390 if (tab.TabType != MyCommon.TabUsageType.Mute)
8392 this.MoveOrCopy(out mv, out mk);
8396 // ミュートタブでは常に MoveMatches を true にする
8401 foreach (var screenName in screenNameArray)
8403 tab.AddFilter(new PostFilterRule
8405 FilterName = screenName,
8406 UseNameField = true,
8410 FilterByUrl = false,
8414 this.ApplyPostFilters();
8418 public void AddFilterRuleBySource(params string[] sourceArray)
8420 // タブ選択ダイアログを表示(or追加)
8422 if (!this.SelectTab(out tabName))
8425 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8429 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8431 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8432 this.MoveOrCopy(out mv, out mk);
8436 // ミュートタブでは常に MoveMatches を true にする
8441 // 振り分けルールに追加するSource
8442 foreach (var source in sourceArray)
8444 filterTab.AddFilter(new PostFilterRule
8446 FilterSource = source,
8450 FilterByUrl = false,
8454 this.ApplyPostFilters();
8455 this.SaveConfigsTabs();
8458 private bool SelectTab(out string tabName)
8465 using (var dialog = new TabsDialog(_statuses))
8467 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8469 var selectedTab = dialog.SelectedTab;
8470 tabName = selectedTab == null ? null : selectedTab.TabName;
8473 ListTab.SelectedTab.Focus();
8475 if (tabName == null)
8477 using (InputTabName inputName = new InputTabName())
8479 inputName.TabName = _statuses.MakeTabName("MyTab");
8480 inputName.ShowDialog();
8481 if (inputName.DialogResult == DialogResult.Cancel) return false;
8482 tabName = inputName.TabName;
8484 this.TopMost = SettingManager.Common.AlwaysTop;
8485 if (!string.IsNullOrEmpty(tabName))
8487 var tab = new FilterTabModel(tabName);
8488 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8490 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8491 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8509 private void MoveOrCopy(out bool move, out bool mark)
8513 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8514 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8522 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8523 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8533 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8538 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8543 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8545 if (StatusText.Focused)
8548 StatusText.SelectAll();
8552 // ListView上でのCtrl+A
8553 NativeMethods.SelectAllItems(this._curList);
8557 private void MoveMiddle()
8563 if (_curList.SelectedIndices.Count == 0) return;
8565 int idx = _curList.SelectedIndices[0];
8567 _item = _curList.GetItemAt(0, 25);
8573 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8575 idx2 = _curList.VirtualListSize - 1;
8579 idx -= Math.Abs(idx1 - idx2) / 2;
8580 if (idx < 0) idx = 0;
8582 _curList.EnsureVisible(_curList.VirtualListSize - 1);
8583 _curList.EnsureVisible(idx);
8586 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8588 var linkElements = this.tweetDetailsView.GetLinkElements();
8590 if (linkElements.Length > 0)
8592 UrlDialog.ClearUrl();
8594 string openUrlStr = "";
8596 if (linkElements.Length == 1)
8598 // ツイートに含まれる URL が 1 つのみの場合
8599 // => OpenURL ダイアログを表示せずにリンクを開く
8604 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8606 catch (ArgumentException)
8615 if (string.IsNullOrEmpty(urlStr)) return;
8616 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8618 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8619 await this.OpenUriAsync(new Uri(openUrlStr));
8623 // ツイートに含まれる URL が複数ある場合
8624 // => OpenURL を表示しユーザーが選択したリンクを開く
8626 foreach (var linkElm in linkElements)
8629 string linkText = "";
8633 urlStr = linkElm.GetAttribute("title");
8634 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8635 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8636 linkText = linkElm.InnerText;
8638 catch (ArgumentException)
8647 if (string.IsNullOrEmpty(urlStr)) continue;
8648 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8652 if (UrlDialog.ShowDialog() == DialogResult.OK)
8654 openUrlStr = UrlDialog.SelectedUrl;
8656 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8657 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8664 this.TopMost = SettingManager.Common.AlwaysTop;
8669 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8671 if (string.IsNullOrEmpty(_rclickTabName)) return;
8672 ClearTab(_rclickTabName, true);
8675 private void ClearTab(string tabName, bool showWarning)
8679 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8680 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8686 _statuses.ClearTabIds(tabName);
8687 if (ListTab.SelectedTab.Text == tabName)
8690 _anchorFlag = false;
8691 this.PurgeListViewItemCache();
8695 foreach (TabPage tb in ListTab.TabPages)
8697 if (tb.Text == tabName)
8699 ((DetailsListView)tb.Tag).VirtualListSize = 0;
8704 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8706 SetMainWindowTitle();
8707 SetStatusLabelUrl();
8710 private static long followers = 0;
8712 private void SetMainWindowTitle()
8715 StringBuilder ttl = new StringBuilder(256);
8718 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8719 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8720 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8721 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8723 foreach (var tab in _statuses.Tabs.Values)
8725 ur += tab.UnreadCount;
8730 if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8731 ttl.Append(Application.ProductName);
8733 switch (SettingManager.Common.DispLatestPost)
8735 case MyCommon.DispTitleEnum.Ver:
8736 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8738 case MyCommon.DispTitleEnum.Post:
8739 if (_history != null && _history.Count > 1)
8740 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8742 case MyCommon.DispTitleEnum.UnreadRepCount:
8743 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8745 case MyCommon.DispTitleEnum.UnreadAllCount:
8746 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8748 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8749 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8751 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8752 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8754 case MyCommon.DispTitleEnum.OwnStatus:
8755 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8756 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8762 this.Text = ttl.ToString();
8764 catch (AccessViolationException)
8766 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8770 private string GetStatusLabelText()
8773 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8774 if (_statuses == null) return "";
8775 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8776 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8777 if (tbRep == null || tbDm == null) return "";
8778 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8783 StringBuilder slbl = new StringBuilder(256);
8786 foreach (var tab in _statuses.Tabs.Values)
8788 ur += tab.UnreadCount;
8790 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
8792 tur = tab.UnreadCount;
8803 UnreadAtCounter = urat;
8805 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8807 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8808 if (SettingManager.Common.TimelinePeriod == 0)
8810 slbl.Append(Properties.Resources.SetStatusLabelText2);
8814 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8816 return slbl.ToString();
8819 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8823 if (this.InvokeRequired && !this.IsDisposed)
8825 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8829 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8830 SetApiStatusLabel(endpointName);
8833 catch (ObjectDisposedException)
8837 catch (InvalidOperationException)
8843 private void SetApiStatusLabel(string endpointName = null)
8845 if (_curTab == null)
8847 this.toolStripApiGauge.ApiEndpoint = null;
8851 var tabType = _statuses.Tabs[_curTab.Text].TabType;
8853 if (endpointName == null)
8858 case MyCommon.TabUsageType.Home:
8859 case MyCommon.TabUsageType.UserDefined:
8860 endpointName = "/statuses/home_timeline";
8863 case MyCommon.TabUsageType.Mentions:
8864 endpointName = "/statuses/mentions_timeline";
8867 case MyCommon.TabUsageType.Favorites:
8868 endpointName = "/favorites/list";
8871 case MyCommon.TabUsageType.DirectMessage:
8872 endpointName = "/direct_messages";
8875 case MyCommon.TabUsageType.UserTimeline:
8876 endpointName = "/statuses/user_timeline";
8879 case MyCommon.TabUsageType.Lists:
8880 endpointName = "/lists/statuses";
8883 case MyCommon.TabUsageType.PublicSearch:
8884 endpointName = "/search/tweets";
8887 case MyCommon.TabUsageType.Related:
8888 endpointName = "/statuses/show/:id";
8895 this.toolStripApiGauge.ApiEndpoint = endpointName;
8899 // 表示中のタブに関連する endpoint であれば更新
8902 switch (endpointName)
8904 case "/statuses/home_timeline":
8905 update = tabType == MyCommon.TabUsageType.Home ||
8906 tabType == MyCommon.TabUsageType.UserDefined;
8909 case "/statuses/mentions_timeline":
8910 update = tabType == MyCommon.TabUsageType.Mentions;
8913 case "/favorites/list":
8914 update = tabType == MyCommon.TabUsageType.Favorites;
8917 case "/direct_messages:":
8918 update = tabType == MyCommon.TabUsageType.DirectMessage;
8921 case "/statuses/user_timeline":
8922 update = tabType == MyCommon.TabUsageType.UserTimeline;
8925 case "/lists/statuses":
8926 update = tabType == MyCommon.TabUsageType.Lists;
8929 case "/search/tweets":
8930 update = tabType == MyCommon.TabUsageType.PublicSearch;
8933 case "/statuses/show/:id":
8934 update = tabType == MyCommon.TabUsageType.Related;
8943 this.toolStripApiGauge.ApiEndpoint = endpointName;
8949 private void SetStatusLabelUrl()
8951 StatusLabelUrl.Text = GetStatusLabelText();
8954 public void SetStatusLabel(string text)
8956 StatusLabel.Text = text;
8959 private void SetNotifyIconText()
8961 var ur = new StringBuilder(64);
8963 // タスクトレイアイコンのツールチップテキスト書き換え
8965 ur.Remove(0, ur.Length);
8966 if (SettingManager.Common.DispUsername)
8968 ur.Append(tw.Username);
8971 ur.Append(Application.ProductName);
8973 ur.Append("(Debug Build)");
8975 if (UnreadCounter != -1 && UnreadAtCounter != -1)
8978 ur.Append(UnreadCounter);
8980 ur.Append(UnreadAtCounter);
8983 NotifyIcon1.Text = ur.ToString();
8986 internal void CheckReplyTo(string StatusText)
8990 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
8992 foreach (Match hm in m)
8994 if (!hstr.Contains("#" + hm.Result("$3") + " "))
8996 hstr += "#" + hm.Result("$3") + " ";
8997 HashSupl.AddItem("#" + hm.Result("$3"));
9000 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9002 hstr += HashMgr.UseHash;
9004 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9006 // 本当にリプライ先指定すべきかどうかの判定
9007 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9009 if (SettingManager.Common.UseAtIdSupplement)
9011 int bCnt = AtIdSupl.ItemCount;
9012 foreach (Match mid in m)
9014 AtIdSupl.AddItem(mid.Result("${id}"));
9016 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9019 // リプライ先ステータスIDの指定がない場合は指定しない
9020 if (this.inReplyTo == null)
9024 // 次の条件を満たす場合に in_reply_to_status_id 指定
9025 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9026 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9027 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9031 var inReplyToScreenName = this.inReplyTo.Item2;
9032 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9034 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9038 foreach (Match mid in m)
9040 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9045 this.inReplyTo = null;
9048 private void TweenMain_Resize(object sender, EventArgs e)
9050 if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
9052 this.Visible = false;
9054 if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
9056 // 現在の DPI と設定保存時の DPI との比を取得する
9057 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9059 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
9060 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9061 this.DesktopLocation = SettingManager.Local.FormLocation;
9062 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9065 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
9066 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9067 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9069 this.SplitContainer1.SplitterDistance = splitterDistance;
9073 StatusText.Multiline = SettingManager.Local.StatusMultiline;
9074 if (StatusText.Multiline)
9076 var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
9077 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9078 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9080 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9082 StatusText.Height = statusTextHeight;
9086 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9088 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9092 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
9093 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9095 this.SplitContainer3.SplitterDistance = previewDistance;
9098 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9099 this.SplitContainer3.Panel2Collapsed = true;
9101 _initialLayout = false;
9103 if (this.WindowState != FormWindowState.Minimized)
9105 _formWindowState = this.WindowState;
9109 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9111 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9112 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9113 if (PlaySoundMenuItem.Checked)
9115 SettingManager.Common.PlaySound = true;
9119 SettingManager.Common.PlaySound = false;
9121 ModifySettingCommon = true;
9124 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9126 if (this._initialLayout)
9129 int splitterDistance;
9130 switch (this.WindowState)
9132 case FormWindowState.Normal:
9133 splitterDistance = this.SplitContainer1.SplitterDistance;
9135 case FormWindowState.Maximized:
9136 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9137 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9138 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9139 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9145 this._mySpDis = splitterDistance;
9146 this.ModifySettingLocal = true;
9149 private async Task doRepliedStatusOpen()
9151 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9153 if (MyCommon.IsKeyDown(Keys.Shift))
9155 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9158 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9160 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9161 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9165 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9167 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9168 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9169 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9172 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9177 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9179 await this.doRepliedStatusOpen();
9182 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9184 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9185 if (multiline != this.StatusText.Multiline)
9187 this.StatusText.Multiline = multiline;
9188 MultiLineMenuItem.Checked = multiline;
9189 ModifySettingLocal = true;
9193 private void StatusText_MultilineChanged(object sender, EventArgs e)
9195 if (this.StatusText.Multiline)
9196 this.StatusText.ScrollBars = ScrollBars.Vertical;
9198 this.StatusText.ScrollBars = ScrollBars.None;
9200 ModifySettingLocal = true;
9203 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9206 StatusText.Multiline = MultiLineMenuItem.Checked;
9207 SettingManager.Local.StatusMultiline = MultiLineMenuItem.Checked;
9208 if (MultiLineMenuItem.Checked)
9210 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9211 SplitContainer2.SplitterDistance = 0;
9213 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9217 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9219 ModifySettingLocal = true;
9222 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9224 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9225 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9227 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9228 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9229 //Appendix A. Collected ABNF for URI
9230 //http://www.ietf.org/rfc/rfc3986.txt
9234 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9236 if (StatusText.SelectionLength > 0)
9238 string tmp = StatusText.SelectedText;
9239 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9240 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9242 // 文字列が選択されている場合はその文字列について処理
9244 //nico.ms使用、nicovideoにマッチしたら変換
9245 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9247 result = nicoms.Shorten(tmp);
9249 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9251 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9254 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9255 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9256 result = resultUri.AbsoluteUri;
9258 catch (WebApiException e)
9260 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9263 catch (UriFormatException e)
9265 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9274 if (!string.IsNullOrEmpty(result))
9276 urlUndo undotmp = new urlUndo();
9278 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9279 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9280 if (origUrlIndex == -1)
9283 StatusText.Select(origUrlIndex, tmp.Length);
9284 StatusText.SelectedText = result;
9287 undotmp.Before = tmp;
9288 undotmp.After = result;
9290 if (urlUndoBuffer == null)
9292 urlUndoBuffer = new List<urlUndo>();
9293 UrlUndoToolStripMenuItem.Enabled = true;
9296 urlUndoBuffer.Add(undotmp);
9302 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9303 @"(?<url>(?<protocol>https?://)" +
9304 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9305 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9306 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9307 // 正規表現にマッチしたURL文字列をtinyurl化
9308 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9310 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9311 string tmp = mt.Result("${url}");
9312 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9313 urlUndo undotmp = new urlUndo();
9316 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9318 //nico.ms使用、nicovideoにマッチしたら変換
9319 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9321 result = nicoms.Shorten(tmp);
9323 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9325 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9328 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9329 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9330 result = resultUri.AbsoluteUri;
9332 catch (HttpRequestException e)
9334 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9335 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9336 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9338 this.StatusLabel.Text = Converter_Type + ":" + message;
9341 catch (WebApiException e)
9343 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9346 catch (UriFormatException e)
9348 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9357 if (!string.IsNullOrEmpty(result))
9359 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9360 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9361 if (origUrlIndex == -1)
9364 StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9365 StatusText.SelectedText = result;
9367 undotmp.Before = mt.Result("${url}");
9368 undotmp.After = result;
9370 if (urlUndoBuffer == null)
9372 urlUndoBuffer = new List<urlUndo>();
9373 UrlUndoToolStripMenuItem.Enabled = true;
9376 urlUndoBuffer.Add(undotmp);
9384 private void doUrlUndo()
9386 if (urlUndoBuffer != null)
9388 string tmp = StatusText.Text;
9389 foreach (urlUndo data in urlUndoBuffer)
9391 tmp = tmp.Replace(data.After, data.Before);
9393 StatusText.Text = tmp;
9394 urlUndoBuffer = null;
9395 UrlUndoToolStripMenuItem.Enabled = false;
9396 StatusText.SelectionStart = 0;
9397 StatusText.SelectionLength = 0;
9401 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9403 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9406 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9408 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9411 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9413 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9416 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9418 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9421 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9423 if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9425 MyCommon.UrlConverter svc = SettingManager.Common.AutoShortUrlFirst;
9426 Random rnd = new Random();
9427 // 前回使用した短縮URLサービス以外を選択する
9430 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9432 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9433 await UrlConvertAsync(svc);
9437 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9442 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9444 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9445 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9446 SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9447 ModifySettingCommon = true;
9450 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9452 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9453 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9454 SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9455 ModifySettingCommon = true;
9458 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9460 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9461 MenuStrip1.Tag = new Object();
9462 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9465 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9467 if (this.Tag != null) // 設定された戻り先へ遷移
9469 if (this.Tag == this.ListTab.SelectedTab)
9470 ((Control)this.ListTab.SelectedTab.Tag).Select();
9472 ((Control)this.Tag).Select();
9474 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9476 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9478 this.Tag = ListTab.SelectedTab.Tag;
9479 ((Control)this.Tag).Select();
9482 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9483 MenuStrip1.Tag = null;
9486 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9488 DetailsListView lst = (DetailsListView)sender;
9489 if (SettingManager.Local == null) return;
9493 SettingManager.Local.Width1 = lst.Columns[0].Width;
9494 SettingManager.Local.Width3 = lst.Columns[1].Width;
9498 int[] darr = new int[lst.Columns.Count];
9499 for (int i = 0; i < lst.Columns.Count; i++)
9501 darr[lst.Columns[i].DisplayIndex] = i;
9503 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9505 for (int i = 0; i < lst.Columns.Count; i++)
9510 SettingManager.Local.DisplayIndex1 = i;
9513 SettingManager.Local.DisplayIndex2 = i;
9516 SettingManager.Local.DisplayIndex3 = i;
9519 SettingManager.Local.DisplayIndex4 = i;
9522 SettingManager.Local.DisplayIndex5 = i;
9525 SettingManager.Local.DisplayIndex6 = i;
9528 SettingManager.Local.DisplayIndex7 = i;
9531 SettingManager.Local.DisplayIndex8 = i;
9535 SettingManager.Local.Width1 = lst.Columns[0].Width;
9536 SettingManager.Local.Width2 = lst.Columns[1].Width;
9537 SettingManager.Local.Width3 = lst.Columns[2].Width;
9538 SettingManager.Local.Width4 = lst.Columns[3].Width;
9539 SettingManager.Local.Width5 = lst.Columns[4].Width;
9540 SettingManager.Local.Width6 = lst.Columns[5].Width;
9541 SettingManager.Local.Width7 = lst.Columns[6].Width;
9542 SettingManager.Local.Width8 = lst.Columns[7].Width;
9544 ModifySettingLocal = true;
9545 _isColumnChanged = true;
9548 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9550 DetailsListView lst = (DetailsListView)sender;
9551 if (SettingManager.Local == null) return;
9554 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9556 SettingManager.Local.Width1 = lst.Columns[0].Width;
9557 ModifySettingLocal = true;
9558 _isColumnChanged = true;
9560 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9562 SettingManager.Local.Width3 = lst.Columns[1].Width;
9563 ModifySettingLocal = true;
9564 _isColumnChanged = true;
9569 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9571 SettingManager.Local.Width1 = lst.Columns[0].Width;
9572 ModifySettingLocal = true;
9573 _isColumnChanged = true;
9575 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9577 SettingManager.Local.Width2 = lst.Columns[1].Width;
9578 ModifySettingLocal = true;
9579 _isColumnChanged = true;
9581 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9583 SettingManager.Local.Width3 = lst.Columns[2].Width;
9584 ModifySettingLocal = true;
9585 _isColumnChanged = true;
9587 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9589 SettingManager.Local.Width4 = lst.Columns[3].Width;
9590 ModifySettingLocal = true;
9591 _isColumnChanged = true;
9593 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9595 SettingManager.Local.Width5 = lst.Columns[4].Width;
9596 ModifySettingLocal = true;
9597 _isColumnChanged = true;
9599 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9601 SettingManager.Local.Width6 = lst.Columns[5].Width;
9602 ModifySettingLocal = true;
9603 _isColumnChanged = true;
9605 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9607 SettingManager.Local.Width7 = lst.Columns[6].Width;
9608 ModifySettingLocal = true;
9609 _isColumnChanged = true;
9611 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9613 SettingManager.Local.Width8 = lst.Columns[7].Width;
9614 ModifySettingLocal = true;
9615 _isColumnChanged = true;
9618 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9621 // SaveConfigsLocal();
9625 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9627 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9628 ModifySettingLocal = true;
9631 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9633 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9635 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9637 SelectMedia_DragDrop(e);
9640 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9642 var url = GetUrlFromDataObject(e.Data);
9645 if (url.Item2 == null)
9646 appendText = url.Item1;
9648 appendText = url.Item2 + " " + url.Item1;
9650 if (this.StatusText.TextLength == 0)
9651 this.StatusText.Text = appendText;
9653 this.StatusText.Text += " " + appendText;
9655 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9657 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9659 this.StatusText.Text += text;
9661 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9663 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9664 if (data != null) StatusText.Text += data;
9669 /// IDataObject から URL とタイトルの対を取得します
9672 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9674 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9675 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9676 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
9678 if (data.GetDataPresent("text/x-moz-url"))
9680 // Firefox, Google Chrome で利用可能
9681 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9683 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9685 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9686 if (lines.Length < 2)
9687 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9689 return new Tuple<string, string>(lines[0], lines[1]);
9692 else if (data.GetDataPresent("IESiteModeToUrl"))
9694 // Internet Exproler 用
9695 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9697 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9699 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9700 if (lines.Length < 2)
9701 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9703 return new Tuple<string, string>(lines[0], lines[1]);
9706 else if (data.GetDataPresent("UniformResourceLocatorW"))
9710 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9712 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9713 return new Tuple<string, string>(url, null);
9717 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9720 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9722 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9724 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9726 SelectMedia_DragEnter(e);
9730 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9732 e.Effect = DragDropEffects.Copy;
9735 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9737 e.Effect = DragDropEffects.Copy;
9740 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9742 e.Effect = DragDropEffects.Copy;
9746 e.Effect = DragDropEffects.None;
9749 private void TweenMain_DragOver(object sender, DragEventArgs e)
9753 public bool IsNetworkAvailable()
9756 nw = MyCommon.IsNetworkAvailable();
9757 _myStatusOnline = nw;
9761 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9763 var uriStr = uri.AbsoluteUri;
9765 // OpenTween 内部で使用する URL
9766 if (uri.Authority == "opentween")
9768 await this.OpenInternalUriAsync(uri);
9772 // ハッシュタグを含む Twitter 検索
9773 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9776 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9777 var pos = unescapedQuery.IndexOf('#');
9778 if (pos == -1) return;
9780 var hash = unescapedQuery.Substring(pos);
9781 this.HashSupl.AddItem(hash);
9782 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9783 this.AddNewTabForSearch(hash);
9788 // フラグが立っている場合は設定と逆の動作をする
9789 if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9790 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9792 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9793 if (userUriMatch.Success)
9795 var screenName = userUriMatch.Groups["ScreenName"].Value;
9796 if (this.IsTwitterId(screenName))
9798 this.AddNewTabForUserTimeline(screenName);
9805 await this.OpenUriInBrowserAsync(uriStr);
9809 /// OpenTween 内部の機能を呼び出すための URL を開きます
9811 private async Task OpenInternalUriAsync(Uri uri)
9813 // ツイートを開く (//opentween/status/:status_id)
9814 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9817 var statusId = long.Parse(match.Groups[1].Value);
9818 await this.OpenRelatedTab(statusId);
9823 public Task OpenUriInBrowserAsync(string UriString)
9825 return Task.Run(() =>
9827 string myPath = UriString;
9831 var configBrowserPath = SettingManager.Local.BrowserPath;
9832 if (!string.IsNullOrEmpty(configBrowserPath))
9834 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9836 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9837 string browserPath = configBrowserPath.Substring(1, sep - 1);
9839 if (sep < configBrowserPath.Length - 1)
9841 arg = configBrowserPath.Substring(sep + 1);
9843 myPath = arg + " " + myPath;
9844 System.Diagnostics.Process.Start(browserPath, myPath);
9848 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9853 System.Diagnostics.Process.Start(myPath);
9858 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9863 private void ListTabSelect(TabPage _tab)
9867 this.PurgeListViewItemCache();
9870 _curList = (DetailsListView)_tab.Tag;
9872 if (_curList.SelectedIndices.Count > 0)
9874 _curItemIndex = _curList.SelectedIndices[0];
9875 _curPost = GetCurTabPost(_curItemIndex);
9884 _anchorFlag = false;
9888 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
9892 for (int i = 0; i < _curList.Columns.Count; i++)
9894 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
9899 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9901 ListTabSelect(e.TabPage);
9904 private void SelectListItem(DetailsListView LView, int Index)
9907 Rectangle bnd = new Rectangle();
9909 var item = LView.FocusedItem;
9918 LView.SelectedIndices.Clear();
9920 while (LView.SelectedIndices.Count > 0);
9921 item = LView.Items[Index];
9922 item.Selected = true;
9923 item.Focused = true;
9925 if (flg) LView.Invalidate(bnd);
9928 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9931 Rectangle bnd = new Rectangle();
9933 var item = LView.FocusedItem;
9944 LView.SelectedIndices.Clear();
9946 while (LView.SelectedIndices.Count > 0);
9947 LView.SelectItems(Index);
9949 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9951 LView.SelectionMark = selectionMarkIndex;
9953 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9955 LView.Items[focusedIndex].Focused = true;
9957 else if (Index != null && Index.Length != 0)
9959 LView.Items[Index.Last()].Focused = true;
9962 if (flg) LView.Invalidate(bnd);
9965 private void StartUserStream()
9967 tw.NewPostFromStream += tw_NewPostFromStream;
9968 tw.UserStreamStarted += tw_UserStreamStarted;
9969 tw.UserStreamStopped += tw_UserStreamStopped;
9970 tw.PostDeleted += tw_PostDeleted;
9971 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9973 this.RefreshUserStreamsMenu();
9975 if (SettingManager.Common.UserstreamStartup)
9976 tw.StartUserStream();
9979 private async void TweenMain_Shown(object sender, EventArgs e)
9981 NotifyIcon1.Visible = true;
9983 if (this.IsNetworkAvailable())
9987 var loadTasks = new List<Task>
9989 this.RefreshMuteUserIdsAsync(),
9990 this.RefreshBlockIdsAsync(),
9991 this.RefreshNoRetweetIdsAsync(),
9992 this.RefreshTwitterConfigurationAsync(),
9993 this.GetHomeTimelineAsync(),
9994 this.GetReplyAsync(),
9995 this.GetDirectMessagesAsync(),
9996 this.GetPublicSearchAllAsync(),
9997 this.GetUserTimelineAllAsync(),
9998 this.GetListTimelineAllAsync(),
10001 if (SettingManager.Common.StartupFollowers)
10002 loadTasks.Add(this.RefreshFollowerIdsAsync());
10004 if (SettingManager.Common.GetFav)
10005 loadTasks.Add(this.GetFavoritesAsync());
10007 var allTasks = Task.WhenAll(loadTasks);
10012 var timeout = Task.Delay(5000);
10013 if (await Task.WhenAny(allTasks, timeout) != timeout)
10017 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10019 if (MyCommon._endingFlag)
10023 if (MyCommon._endingFlag) return;
10025 if (ApplicationSettings.VersionInfoUrl != null)
10027 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10028 if (SettingManager.Common.StartupVersion)
10029 await this.CheckNewVersion(true);
10033 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10034 this.VerUpMenuItem.Enabled = false;
10035 this.VerUpMenuItem.Available = false;
10036 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10039 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10040 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10042 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10043 SettingStripMenuItem_Click(null, null);
10047 var reloadTasks = new List<Task>();
10049 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
10050 reloadTasks.Add(this.RefreshFollowerIdsAsync());
10052 if (!tw.GetNoRetweetSuccess)
10053 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10055 if (this.tw.Configuration.PhotoSizeLimit == 0)
10056 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10058 await Task.WhenAll(reloadTasks);
10063 TimerTimeline.Enabled = true;
10066 private async Task doGetFollowersMenu()
10068 await this.RefreshFollowerIdsAsync();
10069 await this.DispSelectedPost(true);
10072 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10074 await this.doGetFollowersMenu();
10077 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10079 doReTweetUnofficial();
10082 private async Task doReTweetOfficial(bool isConfirm)
10085 if (this.ExistCurrentPost)
10087 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10089 if (this._curPost.IsProtect)
10090 MessageBox.Show("Protected.");
10092 _DoFavRetweetFlags = false;
10095 if (_curList.SelectedIndices.Count > 15)
10097 MessageBox.Show(Properties.Resources.RetweetLimitText);
10098 _DoFavRetweetFlags = false;
10101 else if (_curList.SelectedIndices.Count > 1)
10103 string QuestionText = Properties.Resources.RetweetQuestion2;
10104 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10105 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10107 case DialogResult.Cancel:
10108 case DialogResult.No:
10109 _DoFavRetweetFlags = false;
10115 if (!SettingManager.Common.RetweetNoConfirm)
10117 string Questiontext = Properties.Resources.RetweetQuestion1;
10118 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10119 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10121 _DoFavRetweetFlags = false;
10127 var statusIds = new List<long>();
10128 foreach (int idx in _curList.SelectedIndices)
10130 PostClass post = GetCurTabPost(idx);
10131 if (post.CanRetweetBy(this.twitterApi.CurrentUserId))
10132 statusIds.Add(post.StatusId);
10135 await this.RetweetAsync(statusIds);
10139 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10141 await this.doReTweetOfficial(true);
10144 private async Task FavoritesRetweetOfficial()
10146 if (!this.ExistCurrentPost) return;
10147 _DoFavRetweetFlags = true;
10148 var retweetTask = this.doReTweetOfficial(true);
10149 if (_DoFavRetweetFlags)
10151 _DoFavRetweetFlags = false;
10152 var favoriteTask = this.FavoriteChange(true, false);
10154 await Task.WhenAll(retweetTask, favoriteTask);
10162 private async Task FavoritesRetweetUnofficial()
10164 if (this.ExistCurrentPost && !_curPost.IsDm)
10166 _DoFavRetweetFlags = true;
10167 var favoriteTask = this.FavoriteChange(true);
10168 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10170 _DoFavRetweetFlags = false;
10171 doReTweetUnofficial();
10174 await favoriteTask;
10179 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10181 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10182 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10183 /// <returns>復元されたツイート本文</returns>
10184 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10186 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10189 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10191 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10193 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10197 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10199 statusHtml = statusHtml.Replace("<br>", " ");
10201 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10202 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10203 statusHtml = statusHtml.Replace(" ", " ");
10205 return WebUtility.HtmlDecode(statusHtml);
10208 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10210 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10212 if (_curPost != null)
10213 await this.DispSelectedPost(true);
10216 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10218 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10219 DebugModeToolStripMenuItem.Visible = true;
10221 DebugModeToolStripMenuItem.Visible = false;
10224 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
10226 SettingManager.Common.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
10229 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10231 ToolStripMenuItemUrlAutoShorten.Checked = SettingManager.Common.UrlConvertAuto;
10234 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10236 if (TraceOutToolStripMenuItem.Checked)
10237 MyCommon.TraceFlag = true;
10239 MyCommon.TraceFlag = false;
10242 private void TweenMain_Deactivate(object sender, EventArgs e)
10244 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10245 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10248 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10250 if (string.IsNullOrEmpty(_rclickTabName)) return;
10253 TabRename(_rclickTabName, out _);
10256 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10258 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10261 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10263 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10266 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10268 TwitterApiStatus apiStatus;
10270 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10272 var cancellationToken = dialog.EnableCancellation();
10276 var task = this.tw.GetInfoApi();
10277 apiStatus = await dialog.WaitForAsync(this, task);
10279 catch (WebApiException)
10284 if (cancellationToken.IsCancellationRequested)
10287 if (apiStatus == null)
10289 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10294 using (var apiDlg = new ApiInfoDialog())
10296 apiDlg.ShowDialog(this);
10300 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10302 var id = _curPost?.ScreenName ?? "";
10304 await this.FollowCommand(id);
10307 internal async Task FollowCommand(string id)
10309 using (var inputName = new InputTabName())
10311 inputName.FormTitle = "Follow";
10312 inputName.FormDescription = Properties.Resources.FRMessage1;
10313 inputName.TabName = id;
10315 if (inputName.ShowDialog(this) != DialogResult.OK)
10317 if (string.IsNullOrWhiteSpace(inputName.TabName))
10320 id = inputName.TabName.Trim();
10323 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10327 var task = this.twitterApi.FriendshipsCreate(id);
10328 await dialog.WaitForAsync(this, task);
10330 catch (WebApiException ex)
10332 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10337 MessageBox.Show(Properties.Resources.FRMessage3);
10340 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10342 var id = _curPost?.ScreenName ?? "";
10344 await this.RemoveCommand(id, false);
10347 internal async Task RemoveCommand(string id, bool skipInput)
10351 using (var inputName = new InputTabName())
10353 inputName.FormTitle = "Unfollow";
10354 inputName.FormDescription = Properties.Resources.FRMessage1;
10355 inputName.TabName = id;
10357 if (inputName.ShowDialog(this) != DialogResult.OK)
10359 if (string.IsNullOrWhiteSpace(inputName.TabName))
10362 id = inputName.TabName.Trim();
10366 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10370 var task = this.twitterApi.FriendshipsDestroy(id);
10371 await dialog.WaitForAsync(this, task);
10373 catch (WebApiException ex)
10375 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10380 MessageBox.Show(Properties.Resources.FRMessage3);
10383 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10385 var id = _curPost?.ScreenName ?? "";
10387 await this.ShowFriendship(id);
10390 internal async Task ShowFriendship(string id)
10392 using (var inputName = new InputTabName())
10394 inputName.FormTitle = "Show Friendships";
10395 inputName.FormDescription = Properties.Resources.FRMessage1;
10396 inputName.TabName = id;
10398 if (inputName.ShowDialog(this) != DialogResult.OK)
10400 if (string.IsNullOrWhiteSpace(inputName.TabName))
10403 id = inputName.TabName.Trim();
10406 bool isFollowing, isFollowed;
10408 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10410 var cancellationToken = dialog.EnableCancellation();
10414 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10415 var friendship = await dialog.WaitForAsync(this, task);
10417 isFollowing = friendship.Relationship.Source.Following;
10418 isFollowed = friendship.Relationship.Source.FollowedBy;
10420 catch (WebApiException ex)
10422 if (!cancellationToken.IsCancellationRequested)
10423 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10427 if (cancellationToken.IsCancellationRequested)
10431 string result = "";
10434 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10438 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10442 result += Properties.Resources.GetFriendshipInfo3;
10446 result += Properties.Resources.GetFriendshipInfo4;
10448 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10449 MessageBox.Show(result);
10452 internal async Task ShowFriendship(string[] ids)
10454 foreach (string id in ids)
10456 bool isFollowing, isFollowed;
10458 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10460 var cancellationToken = dialog.EnableCancellation();
10464 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10465 var friendship = await dialog.WaitForAsync(this, task);
10467 isFollowing = friendship.Relationship.Source.Following;
10468 isFollowed = friendship.Relationship.Source.FollowedBy;
10470 catch (WebApiException ex)
10472 if (!cancellationToken.IsCancellationRequested)
10473 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10477 if (cancellationToken.IsCancellationRequested)
10481 string result = "";
10487 ff += Properties.Resources.GetFriendshipInfo1;
10491 ff += Properties.Resources.GetFriendshipInfo2;
10494 ff += System.Environment.NewLine + " ";
10497 ff += Properties.Resources.GetFriendshipInfo3;
10501 ff += Properties.Resources.GetFriendshipInfo4;
10503 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10506 if (MessageBox.Show(
10507 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10508 MessageBoxButtons.YesNo,
10509 MessageBoxIcon.Question,
10510 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10512 await this.RemoveCommand(id, true);
10517 MessageBox.Show(result);
10522 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10524 await this.doShowUserStatus(tw.Username, false);
10525 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
10527 // doShowUserStatus(tw.Username, false);
10531 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
10536 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10537 // URLから切り出した文字列を渡す
10539 public bool IsTwitterId(string name)
10541 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10542 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10544 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
10547 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
10549 ModifySettingCommon = true;
10552 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10554 ModifySettingCommon = true;
10557 private void doQuoteOfficial()
10559 if (this.ExistCurrentPost)
10561 if (_curPost.IsDm ||
10562 !StatusText.Enabled) return;
10564 if (_curPost.IsProtect)
10566 MessageBox.Show("Protected.");
10570 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
10572 this.inReplyTo = null;
10574 StatusText.SelectionStart = 0;
10575 StatusText.Focus();
10579 private void doReTweetUnofficial()
10582 if (this.ExistCurrentPost)
10584 if (_curPost.IsDm || !StatusText.Enabled)
10587 if (_curPost.IsProtect)
10589 MessageBox.Show("Protected.");
10592 string rtdata = _curPost.Text;
10593 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10595 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
10597 // 投稿時に in_reply_to_status_id を付加する
10598 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
10599 var inReplyToScreenName = this._curPost.ScreenName;
10600 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
10602 StatusText.SelectionStart = 0;
10603 StatusText.Focus();
10607 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
10612 private void SearchButton_Click(object sender, EventArgs e)
10615 Control pnl = ((Control)sender).Parent;
10616 if (pnl == null) return;
10617 string tbName = pnl.Parent.Text;
10618 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10619 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10620 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10621 cmb.Text = cmb.Text.Trim();
10622 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10623 bool Quote = false;
10624 StringBuilder buf = new StringBuilder();
10625 char[] c = cmb.Text.ToCharArray();
10626 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10628 if (cnt > cmb.Text.Length - 4)
10630 buf.Append(cmb.Text.Substring(cnt));
10639 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10641 buf.Append(" OR ");
10646 buf.Append(c[cnt]);
10648 cmb.Text = buf.ToString();
10650 var listView = (DetailsListView)pnl.Parent.Tag;
10652 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10654 tb.SearchWords = cmb.Text;
10655 tb.SearchLang = cmbLang.Text;
10656 if (string.IsNullOrEmpty(cmb.Text))
10664 int idx = cmb.Items.IndexOf(tb.SearchWords);
10665 if (idx > -1) cmb.Items.RemoveAt(idx);
10666 cmb.Items.Insert(0, tb.SearchWords);
10667 cmb.Text = tb.SearchWords;
10669 this.PurgeListViewItemCache();
10670 listView.VirtualListSize = 0;
10671 _statuses.ClearTabIds(tbName);
10672 SaveConfigsTabs(); //検索条件の保存
10675 this.GetPublicSearchAsync(tb);
10679 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10682 await this.DoRefreshMore();
10686 /// 指定されたタブのListTabにおける位置を返します
10689 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10691 public int GetTabPageIndex(string tabName)
10694 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
10696 if (tabPage.Text == tabName)
10705 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10707 if (_statuses.RemovedTab.Count == 0)
10709 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10714 DetailsListView listView = null;
10716 TabModel tb = _statuses.RemovedTab.Pop();
10717 if (tb.TabType == MyCommon.TabUsageType.Related)
10719 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10720 if (relatedTab != null)
10722 // 関連発言なら既存のタブを置き換える
10723 tb.TabName = relatedTab.TabName;
10724 this.ClearTab(tb.TabName, false);
10725 _statuses.Tabs[tb.TabName] = tb;
10727 for (int i = 0; i < ListTab.TabPages.Count; i++)
10729 var tabPage = ListTab.TabPages[i];
10730 if (tb.TabName == tabPage.Text)
10732 listView = (DetailsListView)tabPage.Tag;
10733 ListTab.SelectedIndex = i;
10740 const string TabName = "Related Tweets";
10741 string renamed = TabName;
10742 for (int i = 2; i <= 100; i++)
10744 if (!_statuses.ContainsTab(renamed)) break;
10745 renamed = TabName + i;
10747 tb.TabName = renamed;
10749 _statuses.AddTab(tb);
10750 AddNewTab(tb, startup: false);
10752 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10753 listView = (DetailsListView)tabPage.Tag;
10754 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10759 string renamed = tb.TabName;
10760 for (int i = 1; i < int.MaxValue; i++)
10762 if (!_statuses.ContainsTab(renamed)) break;
10763 renamed = tb.TabName + "(" + i + ")";
10765 tb.TabName = renamed;
10767 _statuses.AddTab(tb);
10768 AddNewTab(tb, startup: false);
10770 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10771 listView = (DetailsListView)tabPage.Tag;
10772 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10776 if (listView != null)
10778 using (ControlTransaction.Update(listView))
10780 listView.VirtualListSize = tb.AllCount;
10786 private async Task doMoveToRTHome()
10788 if (_curList.SelectedIndices.Count > 0)
10790 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
10791 if (post.RetweetedId != null)
10793 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
10798 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10800 await this.doMoveToRTHome();
10803 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10805 var screenName = this._curPost?.ScreenName;
10806 if (screenName != null)
10807 this.ListManageUserContext(screenName);
10810 public void ListManageUserContext(string screenName)
10812 using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10814 listSelectForm.ShowDialog(this);
10818 private void SearchControls_Enter(object sender, EventArgs e)
10820 Control pnl = (Control)sender;
10821 foreach (Control ctl in pnl.Controls)
10823 ctl.TabStop = true;
10827 private void SearchControls_Leave(object sender, EventArgs e)
10829 Control pnl = (Control)sender;
10830 foreach (Control ctl in pnl.Controls)
10832 ctl.TabStop = false;
10836 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10838 if (ListTab.SelectedTab != null)
10840 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
10841 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
10845 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10847 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10850 private void HashManageMenuItem_Click(object sender, EventArgs e)
10852 DialogResult rslt = DialogResult.Cancel;
10855 rslt = HashMgr.ShowDialog();
10861 this.TopMost = SettingManager.Common.AlwaysTop;
10862 if (rslt == DialogResult.Cancel) return;
10863 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10865 HashStripSplitButton.Text = HashMgr.UseHash;
10866 HashToggleMenuItem.Checked = true;
10867 HashToggleToolStripMenuItem.Checked = true;
10871 HashStripSplitButton.Text = "#[-]";
10872 HashToggleMenuItem.Checked = false;
10873 HashToggleToolStripMenuItem.Checked = false;
10875 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10877 // int sidx = StatusText.SelectionStart;
10878 // string hash = HashMgr.UseHash + " ";
10881 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10882 // hash = " " + hash;
10884 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
10885 // sidx += hash.Length;
10886 // StatusText.SelectionStart = sidx;
10887 // StatusText.Focus();
10889 ModifySettingCommon = true;
10890 this.StatusText_TextChanged(null, null);
10893 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10895 HashMgr.ToggleHash();
10896 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10898 HashStripSplitButton.Text = HashMgr.UseHash;
10899 HashToggleMenuItem.Checked = true;
10900 HashToggleToolStripMenuItem.Checked = true;
10904 HashStripSplitButton.Text = "#[-]";
10905 HashToggleMenuItem.Checked = false;
10906 HashToggleToolStripMenuItem.Checked = false;
10908 ModifySettingCommon = true;
10909 this.StatusText_TextChanged(null, null);
10912 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10914 HashToggleMenuItem_Click(null, null);
10917 public void SetPermanentHashtag(string hashtag)
10919 HashMgr.SetPermanentHash("#" + hashtag);
10920 HashStripSplitButton.Text = HashMgr.UseHash;
10921 HashToggleMenuItem.Checked = true;
10922 HashToggleToolStripMenuItem.Checked = true;
10924 ModifySettingCommon = true;
10927 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10929 if (ListTab.SelectedTab == null) return;
10930 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
10931 if (!this.ExistCurrentPost)
10933 this.ReplyOpMenuItem.Enabled = false;
10934 this.ReplyAllOpMenuItem.Enabled = false;
10935 this.DmOpMenuItem.Enabled = false;
10936 this.ShowProfMenuItem.Enabled = false;
10937 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10938 this.ListManageMenuItem.Enabled = false;
10939 this.OpenFavOpMenuItem.Enabled = false;
10940 this.CreateTabRuleOpMenuItem.Enabled = false;
10941 this.CreateIdRuleOpMenuItem.Enabled = false;
10942 this.CreateSourceRuleOpMenuItem.Enabled = false;
10943 this.ReadOpMenuItem.Enabled = false;
10944 this.UnreadOpMenuItem.Enabled = false;
10948 this.ReplyOpMenuItem.Enabled = true;
10949 this.ReplyAllOpMenuItem.Enabled = true;
10950 this.DmOpMenuItem.Enabled = true;
10951 this.ShowProfMenuItem.Enabled = true;
10952 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10953 this.ListManageMenuItem.Enabled = true;
10954 this.OpenFavOpMenuItem.Enabled = true;
10955 this.CreateTabRuleOpMenuItem.Enabled = true;
10956 this.CreateIdRuleOpMenuItem.Enabled = true;
10957 this.CreateSourceRuleOpMenuItem.Enabled = true;
10958 this.ReadOpMenuItem.Enabled = true;
10959 this.UnreadOpMenuItem.Enabled = true;
10962 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
10964 this.FavOpMenuItem.Enabled = false;
10965 this.UnFavOpMenuItem.Enabled = false;
10966 this.OpenStatusOpMenuItem.Enabled = false;
10967 this.OpenFavotterOpMenuItem.Enabled = false;
10968 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10969 this.RtOpMenuItem.Enabled = false;
10970 this.RtUnOpMenuItem.Enabled = false;
10971 this.QtOpMenuItem.Enabled = false;
10972 this.FavoriteRetweetMenuItem.Enabled = false;
10973 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10977 this.FavOpMenuItem.Enabled = true;
10978 this.UnFavOpMenuItem.Enabled = true;
10979 this.OpenStatusOpMenuItem.Enabled = true;
10980 this.OpenFavotterOpMenuItem.Enabled = true;
10981 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
10983 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10985 this.RtOpMenuItem.Enabled = false;
10986 this.RtUnOpMenuItem.Enabled = false;
10987 this.QtOpMenuItem.Enabled = false;
10988 this.FavoriteRetweetMenuItem.Enabled = false;
10989 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10993 this.RtOpMenuItem.Enabled = true;
10994 this.RtUnOpMenuItem.Enabled = true;
10995 this.QtOpMenuItem.Enabled = true;
10996 this.FavoriteRetweetMenuItem.Enabled = true;
10997 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11001 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11003 this.RefreshPrevOpMenuItem.Enabled = true;
11007 this.RefreshPrevOpMenuItem.Enabled = false;
11009 if (!this.ExistCurrentPost
11010 || _curPost.InReplyToStatusId == null)
11012 OpenRepSourceOpMenuItem.Enabled = false;
11016 OpenRepSourceOpMenuItem.Enabled = true;
11018 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11020 OpenRterHomeMenuItem.Enabled = false;
11024 OpenRterHomeMenuItem.Enabled = true;
11027 if (this.ExistCurrentPost)
11029 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11033 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11035 ContextMenuTabProperty_Opening(sender, null);
11038 public Twitter TwitterInstance
11043 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11045 if (this._initialLayout)
11048 int splitterDistance;
11049 switch (this.WindowState)
11051 case FormWindowState.Normal:
11052 splitterDistance = this.SplitContainer3.SplitterDistance;
11054 case FormWindowState.Maximized:
11055 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11056 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11057 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11058 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11064 this._mySpDis3 = splitterDistance;
11065 this.ModifySettingLocal = true;
11068 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11070 if (_statuses.RemovedTab.Count == 0)
11072 UndoRemoveTabMenuItem.Enabled = false;
11076 UndoRemoveTabMenuItem.Enabled = true;
11078 if (ListTab.SelectedTab != null)
11080 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11081 PublicSearchQueryMenuItem.Enabled = true;
11083 PublicSearchQueryMenuItem.Enabled = false;
11087 PublicSearchQueryMenuItem.Enabled = false;
11089 if (!this.ExistCurrentPost)
11091 this.CopySTOTMenuItem.Enabled = false;
11092 this.CopyURLMenuItem.Enabled = false;
11093 this.CopyUserIdStripMenuItem.Enabled = false;
11097 this.CopySTOTMenuItem.Enabled = true;
11098 this.CopyURLMenuItem.Enabled = true;
11099 this.CopyUserIdStripMenuItem.Enabled = true;
11100 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11101 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11105 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11107 SetNotifyIconText();
11110 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11112 var id = _curPost?.ScreenName ?? "";
11114 await this.ShowUserStatus(id);
11117 private async Task doShowUserStatus(string id, bool ShowInputDialog)
11119 TwitterUser user = null;
11121 if (ShowInputDialog)
11123 using (var inputName = new InputTabName())
11125 inputName.FormTitle = "Show UserStatus";
11126 inputName.FormDescription = Properties.Resources.FRMessage1;
11127 inputName.TabName = id;
11129 if (inputName.ShowDialog(this) != DialogResult.OK)
11131 if (string.IsNullOrWhiteSpace(inputName.TabName))
11134 id = inputName.TabName.Trim();
11138 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11140 var cancellationToken = dialog.EnableCancellation();
11144 var task = this.twitterApi.UsersShow(id);
11145 user = await dialog.WaitForAsync(this, task);
11147 catch (WebApiException ex)
11149 if (!cancellationToken.IsCancellationRequested)
11150 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11154 if (cancellationToken.IsCancellationRequested)
11158 await this.doShowUserStatus(user);
11161 private async Task doShowUserStatus(TwitterUser user)
11163 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
11165 var showUserTask = userDialog.ShowUserAsync(user);
11166 userDialog.ShowDialog(this);
11169 this.BringToFront();
11171 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11172 await showUserTask;
11176 internal Task ShowUserStatus(string id, bool ShowInputDialog)
11178 return this.doShowUserStatus(id, ShowInputDialog);
11181 internal Task ShowUserStatus(string id)
11183 return this.doShowUserStatus(id, true);
11186 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
11188 if (_curPost != null)
11190 await this.ShowUserStatus(_curPost.ScreenName, false);
11194 private async void RtCountMenuItem_Click(object sender, EventArgs e)
11196 if (!this.ExistCurrentPost)
11199 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11200 TwitterStatus status;
11202 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11204 var cancellationToken = dialog.EnableCancellation();
11208 var task = this.twitterApi.StatusesShow(statusId);
11209 status = await dialog.WaitForAsync(this, task);
11211 catch (WebApiException ex)
11213 if (!cancellationToken.IsCancellationRequested)
11214 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11218 if (cancellationToken.IsCancellationRequested)
11222 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11225 private HookGlobalHotkey _hookGlobalHotkey;
11228 _hookGlobalHotkey = new HookGlobalHotkey(this);
11230 // この呼び出しは、Windows フォーム デザイナで必要です。
11231 InitializeComponent();
11233 // InitializeComponent() 呼び出しの後で初期化を追加します。
11235 if (!this.DesignMode)
11237 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11238 this.StatusText.Dock = DockStyle.Fill;
11241 this.tweetDetailsView.Owner = this;
11243 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11244 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11245 this.gh.NotifyClicked += GrowlHelper_Callback;
11247 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11248 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11250 this.ImageSelector.Visible = false;
11251 this.ImageSelector.Enabled = false;
11252 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11254 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11256 this.ReplaceAppName();
11257 this.InitializeShortcuts();
11260 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11262 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11265 this.Visible = false;
11267 else if (Form.ActiveForm == null)
11269 this.Visible = true;
11270 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11272 this.BringToFront();
11273 this.StatusText.Focus();
11277 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11279 this.MultiLineMenuItem.PerformClick();
11282 public PostClass CurPost
11284 get { return _curPost; }
11288 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11290 if (ImageSelector.Visible)
11291 ImageSelector.EndSelection();
11293 ImageSelector.BeginSelection();
11296 private void SelectMedia_DragEnter(DragEventArgs e)
11298 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11300 e.Effect = DragDropEffects.Copy;
11303 e.Effect = DragDropEffects.None;
11306 private void SelectMedia_DragDrop(DragEventArgs e)
11309 this.BringToFront();
11310 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11311 StatusText.Focus();
11314 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11316 TimelinePanel.Visible = false;
11317 TimelinePanel.Enabled = false;
11320 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11322 TimelinePanel.Visible = true;
11323 TimelinePanel.Enabled = true;
11324 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11327 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11329 this.AllowDrop = false;
11332 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11334 this.AllowDrop = true;
11337 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11339 if (ImageSelector.Visible)
11341 ModifySettingCommon = true;
11342 SaveConfigsAll(true);
11344 this.StatusText_TextChanged(null, null);
11348 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11350 this.StatusText_TextChanged(null, null);
11354 /// StatusTextでCtrl+Vが押下された時の処理
11356 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11360 if (Clipboard.ContainsText())
11362 // clipboardにテキストがある場合は貼り付け処理
11363 this.StatusText.Paste(Clipboard.GetText());
11365 else if (Clipboard.ContainsImage())
11368 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11369 Properties.Resources.PostPictureWarn4,
11370 MessageBoxButtons.OKCancel,
11371 MessageBoxIcon.Question,
11372 MessageBoxDefaultButton.Button2)
11373 == DialogResult.OK)
11375 // clipboardから画像を取得
11376 using (var image = Clipboard.GetImage())
11378 this.ImageSelector.BeginSelection(image);
11383 catch (ExternalException ex)
11385 MessageBox.Show(ex.Message);
11390 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11392 using (ListManage form = new ListManage(tw))
11394 form.ShowDialog(this);
11398 public bool ModifySettingCommon { get; set; }
11399 public bool ModifySettingLocal { get; set; }
11400 public bool ModifySettingAtId { get; set; }
11402 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11404 if (this.ExistCurrentPost && !_curPost.IsDm)
11405 RtCountMenuItem.Enabled = true;
11407 RtCountMenuItem.Enabled = false;
11409 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11410 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11412 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11415 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11420 private void CopyUserId()
11422 if (_curPost == null) return;
11423 string clstr = _curPost.ScreenName;
11426 Clipboard.SetDataObject(clstr, false, 5, 100);
11428 catch (Exception ex)
11430 MessageBox.Show(ex.Message);
11434 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11436 if (this.ExistCurrentPost && !_curPost.IsDm)
11440 await this.OpenRelatedTab(this._curPost);
11442 catch (TabException ex)
11444 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11450 /// 指定されたツイートに対する関連発言タブを開きます
11452 /// <param name="statusId">表示するツイートのID</param>
11453 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11454 private async Task OpenRelatedTab(long statusId)
11456 var post = this._statuses[statusId];
11461 post = await this.tw.GetStatusApi(false, statusId);
11463 catch (WebApiException ex)
11465 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11470 await this.OpenRelatedTab(post);
11474 /// 指定されたツイートに対する関連発言タブを開きます
11476 /// <param name="post">表示する対象となるツイート</param>
11477 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11478 private async Task OpenRelatedTab(PostClass post)
11480 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11481 if (tabRelated != null)
11483 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11486 var tabName = this._statuses.MakeTabName("Related Tweets");
11488 tabRelated = new RelatedPostsTabModel(tabName, post);
11489 tabRelated.UnreadManage = false;
11490 tabRelated.Notify = false;
11492 this._statuses.AddTab(tabRelated);
11493 this.AddNewTab(tabRelated, startup: false);
11496 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
11498 tabPage = this.ListTab.TabPages[i];
11499 if (tabName == tabPage.Text)
11501 this.ListTab.SelectedIndex = i;
11506 await this.GetRelatedTweetsAsync(tabRelated);
11508 tabPage = this.ListTab.TabPages.Cast<TabPage>()
11509 .FirstOrDefault(x => x.Text == tabRelated.TabName);
11511 if (tabPage != null)
11513 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11515 var listView = (DetailsListView)tabPage.Tag;
11516 var targetPost = tabRelated.TargetPost;
11517 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11519 if (index != -1 && index < listView.Items.Count)
11521 listView.SelectedIndices.Add(index);
11522 listView.Items[index].Focused = true;
11527 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11529 StringBuilder buf = new StringBuilder();
11530 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11531 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11532 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11533 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11534 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11537 private void tw_UserIdChanged()
11539 this.ModifySettingCommon = true;
11542 #region "Userstream"
11543 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11547 if (InvokeRequired && !IsDisposed)
11549 await this.InvokeAsync(async () =>
11551 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11552 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
11554 this.PurgeListViewItemCache();
11555 ((DetailsListView)_curTab.Tag).Update();
11556 if (_curPost != null && _curPost.StatusId == e.StatusId)
11557 await this.DispSelectedPost(true);
11563 catch (ObjectDisposedException)
11567 catch (InvalidOperationException)
11573 private int userStreamsRefreshing = 0;
11575 private async void tw_NewPostFromStream(object sender, EventArgs e)
11577 if (SettingManager.Common.ReadOldPosts)
11579 _statuses.SetReadHomeTab(); //新着時未読クリア
11582 this._statuses.DistributePosts();
11584 if (SettingManager.Common.UserstreamPeriod > 0) return;
11586 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
11587 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
11591 await this.InvokeAsync(() => this.RefreshTimeline())
11592 .ConfigureAwait(false);
11596 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
11601 private async void tw_UserStreamStarted(object sender, EventArgs e)
11605 if (InvokeRequired && !IsDisposed)
11607 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11611 catch (ObjectDisposedException)
11615 catch (InvalidOperationException)
11620 this.RefreshUserStreamsMenu();
11621 this.MenuItemUserStream.Enabled = true;
11623 StatusLabel.Text = "UserStream Started.";
11626 private async void tw_UserStreamStopped(object sender, EventArgs e)
11630 if (InvokeRequired && !IsDisposed)
11632 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11636 catch (ObjectDisposedException)
11640 catch (InvalidOperationException)
11645 this.RefreshUserStreamsMenu();
11646 this.MenuItemUserStream.Enabled = true;
11648 StatusLabel.Text = "UserStream Stopped.";
11651 private void RefreshUserStreamsMenu()
11653 if (this.tw.UserStreamActive)
11655 this.MenuItemUserStream.Text = "&UserStream ▶";
11656 this.StopToolStripMenuItem.Text = "&Stop";
11660 this.MenuItemUserStream.Text = "&UserStream ■";
11661 this.StopToolStripMenuItem.Text = "&Start";
11665 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11669 if (InvokeRequired && !IsDisposed)
11671 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11675 catch (ObjectDisposedException)
11679 catch (InvalidOperationException)
11683 var ev = e.EventData;
11684 StatusLabel.Text = "Event: " + ev.Event;
11685 //if (ev.Event == "favorite")
11687 // NotifyFavorite(ev);
11690 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11692 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
11694 this.PurgeListViewItemCache();
11695 ((DetailsListView)_curTab.Tag).Update();
11697 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
11699 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11700 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11705 private void NotifyEvent(Twitter.FormattedEvent ev)
11708 if (BalloonRequired(ev))
11710 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11711 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11712 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11713 StringBuilder title = new StringBuilder();
11714 if (SettingManager.Common.DispUsername)
11716 title.Append(tw.Username);
11717 title.Append(" - ");
11723 title.Append(Application.ProductName);
11724 title.Append(" [");
11725 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11726 title.Append("] by ");
11727 if (!string.IsNullOrEmpty(ev.Username))
11729 title.Append(ev.Username);
11733 //title.Append("");
11736 if (!string.IsNullOrEmpty(ev.Target))
11738 //NotifyIcon1.BalloonTipText = ev.Target;
11743 //NotifyIcon1.BalloonTipText = " ";
11746 //NotifyIcon1.ShowBalloonTip(500);
11747 if (SettingManager.Common.IsUseNotifyGrowl)
11749 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11750 ev.Id.ToString(), title.ToString(), text);
11754 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11755 NotifyIcon1.BalloonTipTitle = title.ToString();
11756 NotifyIcon1.BalloonTipText = text;
11757 NotifyIcon1.ShowBalloonTip(500);
11762 string snd = SettingManager.Common.EventSoundFile;
11763 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11765 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11769 string dir = Application.StartupPath;
11770 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11772 dir = Path.Combine(dir, "Sounds");
11774 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11786 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11788 MenuItemUserStream.Enabled = false;
11789 if (StopRefreshAllMenuItem.Checked)
11791 StopRefreshAllMenuItem.Checked = false;
11794 if (this.tw.UserStreamActive)
11796 tw.StopUserStream();
11800 tw.StartUserStream();
11804 private static string inputTrack = "";
11806 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11808 if (TrackToolStripMenuItem.Checked)
11810 using (InputTabName inputForm = new InputTabName())
11812 inputForm.TabName = inputTrack;
11813 inputForm.FormTitle = "Input track word";
11814 inputForm.FormDescription = "Track word";
11815 if (inputForm.ShowDialog() != DialogResult.OK)
11817 TrackToolStripMenuItem.Checked = false;
11820 inputTrack = inputForm.TabName.Trim();
11822 if (!inputTrack.Equals(tw.TrackWord))
11824 tw.TrackWord = inputTrack;
11825 this.ModifySettingCommon = true;
11826 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11827 tw.ReconnectUserStream();
11833 tw.ReconnectUserStream();
11835 this.ModifySettingCommon = true;
11838 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11840 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11841 this.ModifySettingCommon = true;
11842 tw.ReconnectUserStream();
11845 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11847 if (evtDialog == null || evtDialog.IsDisposed)
11850 evtDialog = new EventViewerDialog();
11851 evtDialog.Owner = this;
11853 Point pos = evtDialog.Location;
11854 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
11855 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
11856 evtDialog.Location = pos;
11858 evtDialog.EventSource = tw.StoredEvent;
11859 if (!evtDialog.Visible)
11861 evtDialog.Show(this);
11865 evtDialog.Activate();
11867 this.TopMost = SettingManager.Common.AlwaysTop;
11871 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11873 MyCommon._endingFlag = true;
11877 Application.Restart();
11881 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
11885 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
11887 if (!string.IsNullOrEmpty(tw.Username))
11888 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
11891 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11893 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11896 private bool ExistCurrentPost
11900 if (_curPost == null) return false;
11901 if (_curPost.IsDeleted) return false;
11906 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11908 ShowUserTimeline();
11911 private string GetUserIdFromCurPostOrInput(string caption)
11913 var id = _curPost?.ScreenName ?? "";
11915 using (InputTabName inputName = new InputTabName())
11917 inputName.FormTitle = caption;
11918 inputName.FormDescription = Properties.Resources.FRMessage1;
11919 inputName.TabName = id;
11920 if (inputName.ShowDialog() == DialogResult.OK &&
11921 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11923 id = inputName.TabName.Trim();
11933 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11935 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11936 if (!string.IsNullOrEmpty(id))
11938 AddNewTabForUserTimeline(id);
11942 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
11944 string id = GetUserIdFromCurPostOrInput("Show Favstar");
11945 if (!string.IsNullOrEmpty(id))
11947 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
11951 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11953 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
11956 private void TimelineRefreshEnableChange(bool isEnable)
11960 tw.StartUserStream();
11964 tw.StopUserStream();
11966 TimerTimeline.Enabled = isEnable;
11969 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11971 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
11974 private async Task OpenUserAppointUrl()
11976 if (SettingManager.Common.UserAppointUrl != null)
11978 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
11980 if (_curPost != null)
11982 string xUrl = SettingManager.Common.UserAppointUrl;
11983 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
11985 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
11986 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
11988 await this.OpenUriInBrowserAsync(xUrl);
11993 await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
11998 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12000 await this.OpenUserAppointUrl();
12003 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
12005 if (Form.ActiveForm == null)
12007 await this.InvokeAsync(() =>
12009 this.Visible = true;
12010 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12012 this.BringToFront();
12013 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
12015 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12019 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12025 private void ReplaceAppName()
12027 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12028 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12031 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12033 this.SplitContainer3.Panel2Collapsed = false;
12036 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12038 await this.OpenThumbnailPicture(e.Thumbnail);
12041 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
12043 await this.OpenUriInBrowserAsync(e.ImageUrl);
12046 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
12048 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
12050 await this.OpenUriInBrowserAsync(url);
12053 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
12055 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
12058 private void PostButton_KeyDown(object sender, KeyEventArgs e)
12060 if (e.KeyCode == Keys.Space)
12062 this.JumpUnreadMenuItem_Click(null, null);
12064 e.SuppressKeyPress = true;
12068 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
12070 this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
12071 this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
12072 this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
12073 this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
12074 this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
12076 this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
12079 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
12081 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
12084 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
12086 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
12089 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
12091 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
12094 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
12096 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
12099 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
12101 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
12104 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
12106 if (SettingManager.Common.IconSize == iconSize) return;
12108 var oldIconCol = _iconCol;
12110 SettingManager.Common.IconSize = iconSize;
12111 ApplyListViewIconSize(iconSize);
12113 if (_iconCol != oldIconCol)
12115 foreach (TabPage tp in ListTab.TabPages)
12117 ResetColumns((DetailsListView)tp.Tag);
12121 _curList?.Refresh();
12123 ModifySettingCommon = true;
12126 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
12128 var state = this.LockListSortOrderToolStripMenuItem.Checked;
12129 if (SettingManager.Common.SortOrderLock == state) return;
12131 SettingManager.Common.SortOrderLock = state;
12133 ModifySettingCommon = true;
12136 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
12138 if (!string.IsNullOrEmpty(e.StatusText))
12140 this.StatusLabelUrl.Text = e.StatusText;
12144 this.SetStatusLabelUrl();