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;
45 using System.Text.RegularExpressions;
46 using System.Threading;
47 using System.Threading.Tasks;
48 using System.Windows.Forms;
50 using OpenTween.Api.DataModel;
51 using OpenTween.Connection;
52 using OpenTween.Models;
53 using OpenTween.OpenTweenCustomControl;
54 using OpenTween.Thumbnail;
58 public partial class TweenMain : OTBaseForm
61 private Size _mySize; //画面サイズ
62 private Point _myLoc; //画面位置
63 private int _mySpDis; //区切り位置
64 private int _mySpDis2; //発言欄区切り位置
65 private int _mySpDis3; //プレビュー区切り位置
66 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
67 private bool _iconCol; //1列表示の時true(48サイズのとき)
70 private bool _initial; //true:起動時処理中
71 private bool _initialLayout = true;
72 private bool _ignoreConfigSave; //true:起動時処理中
73 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
74 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
75 private Point _tabMouseDownPoint;
76 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
77 private readonly object _syncObject = new object(); //ロック用
79 private const string detailHtmlFormatHeaderMono =
80 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
81 + "<style type=\"text/css\"><!-- "
82 + "body, p, pre {margin: 0;} "
83 + "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%);} "
84 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
85 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
86 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
87 + ".quote-tweet.reply {border-color: #f33;} "
88 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
90 + "</head><body><pre>";
91 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
92 private const string detailHtmlFormatHeaderColor =
93 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
94 + "<style type=\"text/css\"><!-- "
95 + "body, p, pre {margin: 0;} "
96 + "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%);} "
97 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
98 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
99 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
100 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
101 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
103 + "</head><body><p>";
104 private const string detailHtmlFormatFooterColor = "</p></body></html>";
105 private string detailHtmlFormatHeader;
106 private string detailHtmlFormatFooter;
108 private bool _myStatusError = false;
109 private bool _myStatusOnline = false;
110 private bool soundfileListup = false;
111 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
114 //private SettingToConfig _cfg; //旧
115 internal SettingLocal _cfgLocal;
116 private SettingCommon _cfgCommon;
119 private TwitterApi twitterApi = new TwitterApi();
123 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
126 internal SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
127 private OpenURL UrlDialog = new OpenURL();
128 public AtIdSupplement AtIdSupl; //@id補助
129 public AtIdSupplement HashSupl; //Hashtag補助
130 public HashtagManage HashMgr;
131 private EventViewerDialog evtDialog;
134 private Font _fntUnread; //未読用フォント
135 private Color _clUnread; //未読用文字色
136 private Font _fntReaded; //既読用フォント
137 private Color _clReaded; //既読用文字色
138 private Color _clFav; //Fav用文字色
139 private Color _clOWL; //片思い用文字色
140 private Color _clRetweet; //Retweet用文字色
141 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
142 private Font _fntDetail; //発言詳細部用フォント
143 private Color _clDetail; //発言詳細部用色
144 private Color _clDetailLink; //発言詳細部用リンク文字色
145 private Color _clDetailBackcolor; //発言詳細部用背景色
146 private Color _clSelf; //自分の発言用背景色
147 private Color _clAtSelf; //自分宛返信用背景色
148 private Color _clTarget; //選択発言者の他の発言用背景色
149 private Color _clAtTarget; //選択発言中の返信先用背景色
150 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
151 private Color _clAtTo; //選択発言の唯一@先
152 private Color _clListBackcolor; //リスト部通常発言背景色
153 private Color _clInputBackcolor; //入力欄背景色
154 private Color _clInputFont; //入力欄文字色
155 private Font _fntInputFont; //入力欄フォント
156 private ImageCache IconCache; //アイコン画像リスト
157 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
158 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
159 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
160 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
161 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
162 private Icon MainIcon; //Main.ico 画面左上のアイコン
163 private Icon ReplyIcon; //5g
164 private Icon ReplyIconBlink; //6g
166 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
168 private PostClass _anchorPost;
169 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
171 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
172 private int _hisIdx; //発言履歴カレントインデックス
174 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
175 private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
178 private List<DateTime> _postTimestamps = new List<DateTime>();
179 private List<DateTime> _favTimestamps = new List<DateTime>();
182 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
183 private SolidBrush _brsBackColorMine;
184 private SolidBrush _brsBackColorAt;
185 private SolidBrush _brsBackColorYou;
186 private SolidBrush _brsBackColorAtYou;
187 private SolidBrush _brsBackColorAtFromTarget;
188 private SolidBrush _brsBackColorAtTo;
189 private SolidBrush _brsBackColorNone;
190 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
191 private StringFormat sfTab = new StringFormat();
193 //////////////////////////////////////////////////////////////////////////////////////////////////////////
194 private TabInformations _statuses;
197 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
200 /// キャッシュクリアのために null が代入されることがあるため、
201 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
202 /// 一旦ローカル変数に代入してから参照すること。
204 private ListViewItemCache _listItemCache = null;
206 internal class ListViewItemCache
208 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
209 public ListView TargetList { get; set; }
211 /// <summary>キャッシュする範囲の開始インデックス</summary>
212 public int StartIndex { get; set; }
214 /// <summary>キャッシュする範囲の終了インデックス</summary>
215 public int EndIndex { get; set; }
217 /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
218 public ListViewItem[] ListItem { get; set; }
220 /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
221 public PostClass[] Post { get; set; }
223 /// <summary>キャッシュされたアイテムの件数</summary>
225 => this.EndIndex - this.StartIndex + 1;
227 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
228 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
229 public bool Contains(int index)
230 => index >= this.StartIndex && index <= this.EndIndex;
232 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
233 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
234 public bool IsSupersetOf(int rangeStart, int rangeEnd)
235 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
237 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
238 /// <returns>取得に成功すれば true、それ以外は false</returns>
239 public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
241 if (this.Contains(index))
243 item = this.ListItem[index - this.StartIndex];
244 post = this.Post[index - this.StartIndex];
256 private TabPage _curTab;
257 private int _curItemIndex;
258 private DetailsListView _curList;
259 private PostClass _curPost;
260 private bool _isColumnChanged = false;
262 private const int MAX_WORKER_THREADS = 20;
263 private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
264 private CancellationTokenSource workerCts = new CancellationTokenSource();
265 private IProgress<string> workerProgress;
267 private int UnreadCounter = -1;
268 private int UnreadAtCounter = -1;
270 private string[] ColumnOrgText = new string[9];
271 private string[] ColumnText = new string[9];
273 private bool _DoFavRetweetFlags = false;
274 private bool osResumed = false;
276 //////////////////////////////////////////////////////////////////////////////////////////////////////////
277 private bool _colorize = false;
279 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
281 private string recommendedStatusFooter;
284 private struct urlUndo
286 public string Before;
290 private List<urlUndo> urlUndoBuffer = null;
292 private struct ReplyChain
294 public long OriginalId;
295 public long InReplyToId;
296 public TabPage OriginalTab;
298 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
300 this.OriginalId = originalId;
301 this.InReplyToId = inReplyToId;
302 this.OriginalTab = originalTab;
306 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
307 private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
310 internal enum SEARCHTYPE
317 private class PostingStatus
319 public string status = "";
320 public long? inReplyToId = null;
321 public string inReplyToName = null;
322 public string imageService = ""; //画像投稿サービス名
323 public IMediaItem[] mediaItems = null;
324 public PostingStatus()
327 public PostingStatus(string status, long? replyToId, string replyToName)
329 this.status = status;
330 this.inReplyToId = replyToId;
331 this.inReplyToName = replyToName;
335 private void TweenMain_Activated(object sender, EventArgs e)
337 //画面がアクティブになったら、発言欄の背景色戻す
338 if (StatusText.Focused)
340 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
344 private bool disposed = false;
347 /// 使用中のリソースをすべてクリーンアップします。
349 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
350 protected override void Dispose(bool disposing)
352 base.Dispose(disposing);
359 this.components?.Dispose();
362 SearchDialog.Dispose();
365 NIconAtRed?.Dispose();
366 NIconAtSmoke?.Dispose();
367 foreach (var iconRefresh in this.NIconRefresh)
369 iconRefresh?.Dispose();
373 ReplyIcon?.Dispose();
374 ReplyIconBlink?.Dispose();
375 _listViewImageList.Dispose();
376 _brsHighLight.Dispose();
377 _brsBackColorMine?.Dispose();
378 _brsBackColorAt?.Dispose();
379 _brsBackColorYou?.Dispose();
380 _brsBackColorAtYou?.Dispose();
381 _brsBackColorAtFromTarget?.Dispose();
382 _brsBackColorAtTo?.Dispose();
383 _brsBackColorNone?.Dispose();
384 _brsDeactiveSelection?.Dispose();
388 this.workerCts.Cancel();
390 if (IconCache != null)
392 this.IconCache.CancelAsync();
393 this.IconCache.Dispose();
396 this.thumbnailTokenSource?.Dispose();
399 this.twitterApi.Dispose();
400 this._hookGlobalHotkey.Dispose();
403 // 終了時にRemoveHandlerしておかないとメモリリークする
404 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
405 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
407 this.disposed = true;
410 private void LoadIcons()
412 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
413 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
416 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
419 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
422 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
425 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
427 // タスクトレイ: オフライン時アイコン
428 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
430 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
431 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
432 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
434 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
435 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
436 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
437 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
438 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
440 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
442 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
443 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
444 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
445 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
446 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
448 if (iconReply != null && iconReplyBlink != null)
450 this.ReplyIcon = iconReply;
451 this.ReplyIconBlink = iconReplyBlink;
455 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
456 this.ReplyIconBlink = this.NIconAt;
459 if (iconRefresh1 == null)
461 this.NIconRefresh = new[] {
462 Properties.Resources.Refresh, Properties.Resources.Refresh2,
463 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
466 else if (iconRefresh2 == null)
468 this.NIconRefresh = new[] { iconRefresh1 };
470 else if (iconRefresh3 == null)
472 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
474 else if (iconRefresh4 == null)
476 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
478 else // iconRefresh1 から iconRefresh4 まで全て揃っている
480 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
484 private Icon LoadIcon(string filePath)
486 if (!File.Exists(filePath))
491 return new Icon(filePath);
499 private void InitColumns(ListView list, bool startup)
501 this.InitColumnText();
503 ColumnHeader[] columns = null;
510 new ColumnHeader(), // アイコン
511 new ColumnHeader(), // 本文
514 columns[0].Text = this.ColumnText[0];
515 columns[1].Text = this.ColumnText[2];
519 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
521 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
522 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
523 columns[0].DisplayIndex = 0;
524 columns[1].DisplayIndex = 1;
529 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
531 columns[idx].Width = curListColumn.Width;
532 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
541 new ColumnHeader(), // アイコン
542 new ColumnHeader(), // ニックネーム
543 new ColumnHeader(), // 本文
544 new ColumnHeader(), // 日付
545 new ColumnHeader(), // ユーザID
546 new ColumnHeader(), // 未読
547 new ColumnHeader(), // マーク&プロテクト
548 new ColumnHeader(), // ソース
551 foreach (var i in Enumerable.Range(0, columns.Length))
552 columns[i].Text = this.ColumnText[i];
556 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
558 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
559 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
560 columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
561 columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
562 columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
563 columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
564 columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
565 columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
567 var displayIndex = new[] {
568 this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
569 this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
570 this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
571 this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
574 foreach (var i in Enumerable.Range(0, displayIndex.Length))
576 columns[i].DisplayIndex = displayIndex[i];
582 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
584 columns[idx].Width = curListColumn.Width;
585 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
591 list.Columns.AddRange(columns);
599 foreach (var column in columns)
605 private void InitColumnText()
608 ColumnText[1] = Properties.Resources.AddNewTabText2;
609 ColumnText[2] = Properties.Resources.AddNewTabText3;
610 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
611 ColumnText[4] = Properties.Resources.AddNewTabText5;
614 ColumnText[7] = "Source";
616 ColumnOrgText[0] = "";
617 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
618 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
619 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
620 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
621 ColumnOrgText[5] = "";
622 ColumnOrgText[6] = "";
623 ColumnOrgText[7] = "Source";
626 switch (_statuses.SortMode)
628 case ComparerMode.Nickname: //ニックネーム
631 case ComparerMode.Data: //本文
634 case ComparerMode.Id: //時刻=発言Id
637 case ComparerMode.Name: //名前
640 case ComparerMode.Source: //Source
647 if (_statuses.SortOrder == SortOrder.Descending)
649 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
650 ColumnText[2] = ColumnOrgText[2] + "▾";
654 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
655 ColumnText[2] = ColumnOrgText[2] + "▴";
660 if (_statuses.SortOrder == SortOrder.Descending)
662 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
663 ColumnText[c] = ColumnOrgText[c] + "▾";
667 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
668 ColumnText[c] = ColumnOrgText[c] + "▴";
673 private void InitializeTraceFrag()
676 TraceOutToolStripMenuItem.Checked = true;
677 MyCommon.TraceFlag = true;
679 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
681 TraceOutToolStripMenuItem.Checked = true;
682 MyCommon.TraceFlag = true;
686 private void TweenMain_Load(object sender, EventArgs e)
688 _ignoreConfigSave = true;
689 this.Visible = false;
691 if (MyApplication.StartupOptions.ContainsKey("d"))
692 MyCommon.TraceFlag = true;
694 InitializeTraceFrag();
696 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
698 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
699 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
701 Regex.CacheSize = 100;
704 _statuses = TabInformations.GetInstance();
708 this.Icon = MainIcon; //メインフォーム(TweenMain)
709 NotifyIcon1.Icon = NIconAt; //タスクトレイ
710 TabImage.Images.Add(TabIcon); //タブ見出し
712 //<<<<<<<<<設定関連>>>>>>>>>
716 // 現在の DPI と設定保存時の DPI との比を取得する
717 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
720 var fontUIGlobal = this._cfgLocal.FontUIGlobal;
721 if (fontUIGlobal != null)
723 OTBaseForm.GlobalFont = fontUIGlobal;
724 this.Font = fontUIGlobal;
728 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
730 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
731 this._cfgCommon.TimelinePeriod = 15;
733 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
734 this._cfgCommon.ReplyPeriod = 15;
736 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
737 this._cfgCommon.DMPeriod = 15;
739 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
740 this._cfgCommon.PubSearchPeriod = 30;
742 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
743 this._cfgCommon.UserTimelinePeriod = 15;
745 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
746 this._cfgCommon.ListsPeriod = 15;
749 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
750 this._cfgCommon.CountApi = 60;
751 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
752 this._cfgCommon.CountApiReply = 40;
754 if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
755 this._cfgCommon.MoreCountApi = 200;
756 if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
757 this._cfgCommon.FirstCountApi = 100;
759 if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
760 this._cfgCommon.FavoritesCountApi = 40;
761 if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
762 this._cfgCommon.ListCountApi = 100;
763 if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
764 this._cfgCommon.SearchCountApi = 100;
765 if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
766 this._cfgCommon.UserTimelineCountApi = 20;
768 //廃止サービスが選択されていた場合ux.nuへ読み替え
769 if (this._cfgCommon.AutoShortUrlFirst < 0)
770 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
772 TwitterApiConnection.RestApiHost = this._cfgCommon.TwitterApiHost;
773 this.tw = new Twitter(this.twitterApi);
776 if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
777 tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
781 Networking.Initialize();
783 bool saveRequired = false;
784 bool firstRun = false;
786 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
787 if (string.IsNullOrEmpty(tw.Username))
792 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
793 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
794 string.IsNullOrEmpty(tw.Username))
796 Application.Exit(); //強制終了
802 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
803 Networking.SetWebProxy(this._cfgLocal.ProxyType,
804 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
805 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
806 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
808 TwitterApiConnection.RestApiHost = this._cfgCommon.TwitterApiHost;
809 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
810 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
811 tw.TrackWord = this._cfgCommon.TrackWord;
812 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
813 tw.AllAtReply = this._cfgCommon.AllAtReply;
814 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
815 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
816 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
817 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
819 // アクセストークンが有効であるか確認する
820 // ここが Twitter API への最初のアクセスになるようにすること
823 this.tw.VerifyCredentials();
825 catch (WebApiException ex)
827 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
828 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
832 //プロキシ設定等の通信まわりの初期化が済んでから処理する
833 ThumbnailGenerator.InitializeGenerator();
835 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
836 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
837 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
839 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
842 ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
845 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
846 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
847 HashMgr = new HashtagManage(HashSupl,
848 _cfgCommon.HashTags.ToArray(),
849 _cfgCommon.HashSelected,
850 _cfgCommon.HashIsPermanent,
851 _cfgCommon.HashIsHead,
852 _cfgCommon.HashIsNotAddToAtReply);
853 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
856 this.IconCache = new ImageCache();
857 this.tweetDetailsView.IconCache = this.IconCache;
860 _fntUnread = this._cfgLocal.FontUnread;
861 _clUnread = this._cfgLocal.ColorUnread;
862 _fntReaded = this._cfgLocal.FontRead;
863 _clReaded = this._cfgLocal.ColorRead;
864 _clFav = this._cfgLocal.ColorFav;
865 _clOWL = this._cfgLocal.ColorOWL;
866 _clRetweet = this._cfgLocal.ColorRetweet;
867 _fntDetail = this._cfgLocal.FontDetail;
868 _clDetail = this._cfgLocal.ColorDetail;
869 _clDetailLink = this._cfgLocal.ColorDetailLink;
870 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
871 _clSelf = this._cfgLocal.ColorSelf;
872 _clAtSelf = this._cfgLocal.ColorAtSelf;
873 _clTarget = this._cfgLocal.ColorTarget;
874 _clAtTarget = this._cfgLocal.ColorAtTarget;
875 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
876 _clAtTo = this._cfgLocal.ColorAtTo;
877 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
878 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
879 _clInputFont = this._cfgLocal.ColorInputFont;
880 _fntInputFont = this._cfgLocal.FontInputFont;
882 _brsBackColorMine = new SolidBrush(_clSelf);
883 _brsBackColorAt = new SolidBrush(_clAtSelf);
884 _brsBackColorYou = new SolidBrush(_clTarget);
885 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
886 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
887 _brsBackColorAtTo = new SolidBrush(_clAtTo);
888 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
889 _brsBackColorNone = new SolidBrush(_clListBackcolor);
891 // StringFormatオブジェクトへの事前設定
892 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
893 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
894 //sf.FormatFlags = StringFormatFlags.LineLimit; //
895 sfTab.Alignment = StringAlignment.Center;
896 sfTab.LineAlignment = StringAlignment.Center;
898 InitDetailHtmlFormat();
900 //Regex statregex = new Regex("^0*");
901 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
903 _history.Add(new PostingStatus());
905 this.inReplyTo = null;
908 SearchDialog.Owner = this;
909 UrlDialog.Owner = this;
912 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
913 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
915 //新着取得時のリストスクロールをするか。trueならスクロールしない
916 ListLockMenuItem.Checked = _cfgCommon.ListLock;
917 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
919 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
920 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
922 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
923 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
926 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
927 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
928 _myLoc = _cfgLocal.FormLocation;
930 if (this.WindowState != FormWindowState.Minimized)
932 this.DesktopLocation = _cfgLocal.FormLocation;
933 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
934 bool outOfScreen = true;
935 if (Screen.AllScreens.Length == 1) //ハングするとの報告
937 foreach (Screen scr in Screen.AllScreens)
939 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
947 this.DesktopLocation = new Point(0, 0);
948 _myLoc = this.DesktopLocation;
952 this.TopMost = this._cfgCommon.AlwaysTop;
953 _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
954 _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
955 if (_cfgLocal.PreviewDistance == -1)
957 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
958 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
959 _cfgLocal.PreviewDistance = _mySpDis3;
963 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
965 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
966 //this.Tween_ClientSizeChanged(this, null);
967 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
968 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
970 StatusText.Font = _fntInputFont;
971 StatusText.ForeColor = _clInputFont;
973 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
974 this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
975 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
977 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
978 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
980 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
981 if (this._cfgCommon.UnreadManage == false)
983 ReadedStripMenuItem.Enabled = false;
984 UnreadStripMenuItem.Enabled = false;
987 //リンク先URL表示部の初期化(画面左下)
988 StatusLabelUrl.Text = "";
990 StatusLabel.Text = "";
991 StatusLabel.AutoToolTip = false;
992 StatusLabel.ToolTipText = "";
994 lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
996 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
997 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
998 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
999 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1001 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1002 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1003 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1004 this.SplitContainer2.Panel2.AccessibleName = "";
1006 ////////////////////////////////////////////////////////////////////////////////
1007 var sortOrder = (SortOrder)_cfgCommon.SortOrder;
1008 var mode = ComparerMode.Id;
1009 switch (_cfgCommon.SortColumn)
1011 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1015 mode = ComparerMode.Id; //Idソートに読み替え
1018 mode = ComparerMode.Nickname;
1021 mode = ComparerMode.Data;
1024 mode = ComparerMode.Id;
1027 mode = ComparerMode.Name;
1030 mode = ComparerMode.Source;
1033 _statuses.SetSortMode(mode, sortOrder);
1034 ////////////////////////////////////////////////////////////////////////////////
1036 ApplyListViewIconSize(this._cfgCommon.IconSize);
1038 //<<<<<<<<タブ関連>>>>>>>
1042 //デフォルトタブの存在チェック、ない場合には追加
1043 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1044 this._statuses.AddTab(new HomeTabModel());
1046 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1047 this._statuses.AddTab(new MentionsTabModel());
1049 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1050 this._statuses.AddTab(new DirectMessagesTabModel());
1052 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1053 this._statuses.AddTab(new FavoritesTabModel());
1055 if (this._statuses.GetTabByType<MuteTabModel>() == null)
1056 this._statuses.AddTab(new MuteTabModel());
1058 foreach (var tab in _statuses.Tabs.Values)
1061 if (tab.TabType == MyCommon.TabUsageType.Mute)
1064 if (!AddNewTab(tab, startup: true))
1065 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1068 _curTab = ListTab.SelectedTab;
1070 _curList = (DetailsListView)_curTab.Tag;
1072 if (this._cfgCommon.TabIconDisp)
1074 ListTab.DrawMode = TabDrawMode.Normal;
1078 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1079 ListTab.DrawItem += ListTab_DrawItem;
1080 ListTab.ImageList = null;
1083 if (this._cfgCommon.HotkeyEnabled)
1086 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1087 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1088 modKey |= HookGlobalHotkey.ModKeys.Alt;
1089 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1090 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1091 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1092 modKey |= HookGlobalHotkey.ModKeys.Shift;
1093 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1094 modKey |= HookGlobalHotkey.ModKeys.Win;
1096 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1099 if (this._cfgCommon.IsUseNotifyGrowl)
1102 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1104 SetMainWindowTitle();
1105 SetNotifyIconText();
1107 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1109 this.Visible = true;
1113 TimerTimeline.AutoReset = true;
1114 TimerTimeline.SynchronizingObject = this;
1116 TimerTimeline.Interval = 1000;
1117 TimerTimeline.Enabled = true;
1119 TimerRefreshIcon.Interval = 200;
1120 TimerRefreshIcon.Enabled = true;
1122 _ignoreConfigSave = false;
1123 this.TweenMain_Resize(null, null);
1124 if (saveRequired) SaveConfigsAll(false);
1126 foreach (var ua in this._cfgCommon.UserAccounts)
1128 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1130 ua.UserId = tw.UserId;
1137 // 初回起動時だけ右下のメニューを目立たせる
1138 HashStripSplitButton.ShowDropDown();
1142 private void InitDetailHtmlFormat()
1144 if (this._cfgCommon.IsMonospace)
1146 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1147 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1151 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1152 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1155 detailHtmlFormatHeader = detailHtmlFormatHeader
1156 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1157 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1158 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1159 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1160 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1161 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1164 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1169 txt = ListTab.TabPages[e.Index].Text;
1176 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1177 if (e.State == DrawItemState.Selected)
1179 e.DrawFocusRectangle();
1184 if (_statuses.Tabs[txt].UnreadCount > 0)
1187 fore = System.Drawing.SystemBrushes.ControlText;
1191 fore = System.Drawing.SystemBrushes.ControlText;
1193 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1196 private void LoadConfig()
1198 _cfgCommon = SettingCommon.Load();
1199 SettingCommon.Instance = this._cfgCommon;
1200 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1202 _cfgCommon.UserAccounts = new List<UserAccount>();
1203 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1205 UserAccount account = new UserAccount();
1206 account.Username = _cfgCommon.UserName;
1207 account.UserId = _cfgCommon.UserId;
1208 account.Token = _cfgCommon.Token;
1209 account.TokenSecret = _cfgCommon.TokenSecret;
1211 _cfgCommon.UserAccounts.Add(account);
1215 _cfgLocal = SettingLocal.Load();
1217 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1218 if (_cfgLocal.ScaleDimension.IsEmpty)
1219 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1221 var tabsSetting = SettingTabs.Load().Tabs;
1222 foreach (var tabSetting in tabsSetting)
1225 switch (tabSetting.TabType)
1227 case MyCommon.TabUsageType.Home:
1228 tab = new HomeTabModel(tabSetting.TabName);
1230 case MyCommon.TabUsageType.Mentions:
1231 tab = new MentionsTabModel(tabSetting.TabName);
1233 case MyCommon.TabUsageType.DirectMessage:
1234 tab = new DirectMessagesTabModel(tabSetting.TabName);
1236 case MyCommon.TabUsageType.Favorites:
1237 tab = new FavoritesTabModel(tabSetting.TabName);
1239 case MyCommon.TabUsageType.UserDefined:
1240 tab = new FilterTabModel(tabSetting.TabName);
1242 case MyCommon.TabUsageType.UserTimeline:
1243 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1245 case MyCommon.TabUsageType.PublicSearch:
1246 tab = new PublicSearchTabModel(tabSetting.TabName)
1248 SearchWords = tabSetting.SearchWords,
1249 SearchLang = tabSetting.SearchLang,
1252 case MyCommon.TabUsageType.Lists:
1253 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1255 case MyCommon.TabUsageType.Mute:
1256 tab = new MuteTabModel(tabSetting.TabName);
1262 tab.UnreadManage = tabSetting.UnreadManage;
1263 tab.Protected = tabSetting.Protected;
1264 tab.Notify = tabSetting.Notify;
1265 tab.SoundFile = tabSetting.SoundFile;
1267 if (tab.IsDistributableTabType)
1269 var filterTab = (FilterTabModel)tab;
1270 filterTab.FilterArray = tabSetting.FilterArray;
1271 filterTab.FilterModified = false;
1274 if (this._statuses.ContainsTab(tab.TabName))
1275 tab.TabName = this._statuses.MakeTabName("MyTab");
1277 this._statuses.AddTab(tab);
1279 if (_statuses.Tabs.Count == 0)
1281 _statuses.AddTab(new HomeTabModel());
1282 _statuses.AddTab(new MentionsTabModel());
1283 _statuses.AddTab(new DirectMessagesTabModel());
1284 _statuses.AddTab(new FavoritesTabModel());
1288 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1290 if (!TimerTimeline.Enabled) return;
1294 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1296 private static int homeCounter = 0;
1297 private static int mentionCounter = 0;
1298 private static int dmCounter = 0;
1299 private static int pubSearchCounter = 0;
1300 private static int userTimelineCounter = 0;
1301 private static int listsCounter = 0;
1302 private static int usCounter = 0;
1303 private static int ResumeWait = 0;
1304 private static int refreshFollowers = 0;
1306 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1308 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1309 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1310 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1311 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1312 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1313 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1314 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1315 Interlocked.Increment(ref refreshFollowers);
1317 var refreshTasks = new List<Task>();
1320 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1322 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1323 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1324 refreshTasks.Add(this.GetHomeTimelineAsync());
1325 ResetTimers.Timeline = false;
1327 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1329 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1330 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1331 refreshTasks.Add(this.GetReplyAsync());
1332 ResetTimers.Reply = false;
1334 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1336 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1337 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1338 refreshTasks.Add(this.GetDirectMessagesAsync());
1339 ResetTimers.DirectMessage = false;
1341 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1343 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1344 if (!ResetTimers.PublicSearch)
1345 refreshTasks.Add(this.GetPublicSearchAllAsync());
1346 ResetTimers.PublicSearch = false;
1348 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1350 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1351 if (!ResetTimers.UserTimeline)
1352 refreshTasks.Add(this.GetUserTimelineAllAsync());
1353 ResetTimers.UserTimeline = false;
1355 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1357 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1358 if (!ResetTimers.Lists)
1359 refreshTasks.Add(this.GetListTimelineAllAsync());
1360 ResetTimers.Lists = false;
1362 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1364 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1365 if (this.tw.UserStreamActive)
1366 this.RefreshTimeline();
1367 ResetTimers.UserStream = false;
1369 if (refreshFollowers > 6 * 3600)
1371 Interlocked.Exchange(ref refreshFollowers, 0);
1372 refreshTasks.AddRange(new[]
1374 this.doGetFollowersMenu(),
1375 this.RefreshNoRetweetIdsAsync(),
1376 this.RefreshTwitterConfigurationAsync(),
1381 Interlocked.Increment(ref ResumeWait);
1382 if (ResumeWait > 30)
1385 Interlocked.Exchange(ref ResumeWait, 0);
1386 refreshTasks.AddRange(new[]
1388 this.GetHomeTimelineAsync(),
1389 this.GetReplyAsync(),
1390 this.GetDirectMessagesAsync(),
1391 this.GetPublicSearchAllAsync(),
1392 this.GetUserTimelineAllAsync(),
1393 this.GetListTimelineAllAsync(),
1394 this.doGetFollowersMenu(),
1395 this.RefreshTwitterConfigurationAsync(),
1400 await Task.WhenAll(refreshTasks);
1403 private void RefreshTimeline()
1405 // 現在表示中のタブのスクロール位置を退避
1406 var curListScroll = this.SaveListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text]);
1408 // 各タブのリスト上の選択位置などを退避
1409 var listSelections = this.SaveListViewSelection();
1412 PostClass[] notifyPosts;
1415 bool newMentionOrDm;
1417 addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1419 if (MyCommon._endingFlag) return;
1424 foreach (TabPage tab in ListTab.TabPages)
1426 DetailsListView lst = (DetailsListView)tab.Tag;
1427 TabModel tabInfo = _statuses.Tabs[tab.Text];
1428 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1430 using (ControlTransaction.Update(lst))
1432 if (lst.Equals(_curList))
1434 this.PurgeListViewItemCache();
1438 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1446 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
1449 if (tabInfo.UnreadCount > 0)
1450 if (this._cfgCommon.TabIconDisp)
1451 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1453 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1457 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1462 this.RestoreListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text], curListScroll);
1465 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1467 SetMainWindowTitle();
1468 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1470 HashSupl.AddRangeItem(tw.GetHashList());
1474 internal struct ListViewScroll
1476 public ScrollLockMode ScrollLockMode { get; set; }
1477 public long? TopItemStatusId { get; set; }
1480 internal enum ScrollLockMode
1482 /// <summary>固定しない</summary>
1485 /// <summary>最上部に固定する</summary>
1488 /// <summary>最下部に固定する</summary>
1491 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1496 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1498 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1500 var listScroll = new ListViewScroll
1502 ScrollLockMode = this.GetScrollLockMode(listView),
1505 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1507 var topItem = listView.TopItem;
1508 if (topItem != null)
1509 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItem.Index);
1515 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1517 if (this._statuses.SortMode == ComparerMode.Id)
1519 if (this._statuses.SortOrder == SortOrder.Ascending)
1522 if (this.ListLockMenuItem.Checked)
1523 return ScrollLockMode.None;
1525 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1528 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1529 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1530 return ScrollLockMode.FixedToBottom;
1532 return ScrollLockMode.None;
1537 if (this.ListLockMenuItem.Checked)
1538 return ScrollLockMode.FixedToItem;
1540 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1541 var topItem = listView.TopItem;
1542 if (topItem == null || topItem.Index == 0)
1543 return ScrollLockMode.FixedToTop;
1545 return ScrollLockMode.FixedToItem;
1550 return ScrollLockMode.FixedToItem;
1554 internal struct ListViewSelection
1556 public long[] SelectedStatusIds { get; set; }
1557 public long? SelectionMarkStatusId { get; set; }
1558 public long? FocusedStatusId { get; set; }
1562 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1564 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1566 var listsDict = new Dictionary<string, ListViewSelection>();
1568 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1570 var listView = (DetailsListView)tabPage.Tag;
1571 var tab = _statuses.Tabs[tabPage.Text];
1573 ListViewSelection listStatus;
1574 if (listView.VirtualListSize != 0)
1576 listStatus = new ListViewSelection
1578 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1579 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1580 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1585 listStatus = new ListViewSelection
1587 SelectedStatusIds = new long[0],
1588 SelectionMarkStatusId = null,
1589 FocusedStatusId = null,
1593 listsDict[tab.TabName] = listStatus;
1599 private long[] GetSelectedStatusIds(DetailsListView listView, TabModel tab)
1601 var selectedIndices = listView.SelectedIndices;
1602 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1603 return tab.GetStatusIdAt(selectedIndices.Cast<int>());
1608 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1610 var focusedItem = listView.FocusedItem;
1612 return focusedItem != null ? tab.GetStatusIdAt(focusedItem.Index) : (long?)null;
1615 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1617 var selectionMarkIndex = listView.SelectionMark;
1619 return selectionMarkIndex != -1 ? tab.GetStatusIdAt(selectionMarkIndex) : (long?)null;
1623 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1625 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1627 if (listView.VirtualListSize == 0)
1630 switch (listScroll.ScrollLockMode)
1632 case ScrollLockMode.FixedToTop:
1633 listView.EnsureVisible(0);
1635 case ScrollLockMode.FixedToBottom:
1636 listView.EnsureVisible(listView.VirtualListSize - 1);
1638 case ScrollLockMode.FixedToItem:
1639 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1641 listView.TopItem = listView.Items[topIndex];
1643 case ScrollLockMode.None:
1650 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1652 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1654 // status_id から ListView 上のインデックスに変換
1655 int[] selectedIndices = null;
1656 if (listSelection.SelectedStatusIds != null)
1657 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1659 var focusedIndex = -1;
1660 if (listSelection.FocusedStatusId != null)
1661 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1663 var selectionMarkIndex = -1;
1664 if (listSelection.SelectionMarkStatusId != null)
1665 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1667 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1670 private bool BalloonRequired()
1672 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1673 ev.Eventtype = MyCommon.EVENTTYPE.None;
1675 return BalloonRequired(ev);
1678 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1680 if (type == MyCommon.EVENTTYPE.None)
1683 if (!this._cfgCommon.EventNotifyEnabled)
1686 return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1689 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1694 return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1697 private bool BalloonRequired(Twitter.FormattedEvent ev)
1702 if (NativeMethods.IsScreenSaverRunning())
1706 if (!this.NewPostPopMenuItem.Checked)
1708 // 「新着通知が無効でもイベントを通知する」にも該当しない
1709 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1713 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1714 if (this._cfgCommon.LimitBalloon)
1716 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1720 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1723 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1725 if (this._cfgCommon.ReadOwnPost)
1727 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1732 if (BalloonRequired())
1734 if (notifyPosts != null && notifyPosts.Length > 0)
1736 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1737 if (this._cfgCommon.IsUseNotifyGrowl)
1739 StringBuilder sb = new StringBuilder();
1743 foreach (PostClass post in notifyPosts)
1745 if (!(notifyPosts.Length > 3))
1751 if (post.IsReply && !post.IsExcludeReply) reply = true;
1752 if (post.IsDm) dm = true;
1753 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1754 switch (this._cfgCommon.NameBalloon)
1756 case MyCommon.NameBalloonEnum.UserID:
1757 sb.Append(post.ScreenName).Append(" : ");
1759 case MyCommon.NameBalloonEnum.NickName:
1760 sb.Append(post.Nickname).Append(" : ");
1763 sb.Append(post.TextFromApi);
1764 if (notifyPosts.Length > 3)
1766 if (notifyPosts.Last() != post) continue;
1769 StringBuilder title = new StringBuilder();
1770 GrowlHelper.NotifyType nt;
1771 if (this._cfgCommon.DispUsername)
1773 title.Append(tw.Username);
1774 title.Append(" - ");
1782 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1783 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1784 title.Append(Application.ProductName);
1785 title.Append(" [DM] ");
1786 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1787 nt = GrowlHelper.NotifyType.DirectMessage;
1791 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1792 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1793 title.Append(Application.ProductName);
1794 title.Append(" [Reply!] ");
1795 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1796 nt = GrowlHelper.NotifyType.Reply;
1800 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1801 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1802 title.Append(Application.ProductName);
1804 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1805 nt = GrowlHelper.NotifyType.Notify;
1807 string bText = sb.ToString();
1808 if (string.IsNullOrEmpty(bText)) return;
1810 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1811 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1816 StringBuilder sb = new StringBuilder();
1819 foreach (PostClass post in notifyPosts)
1821 if (post.IsReply && !post.IsExcludeReply) reply = true;
1822 if (post.IsDm) dm = true;
1823 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1824 switch (this._cfgCommon.NameBalloon)
1826 case MyCommon.NameBalloonEnum.UserID:
1827 sb.Append(post.ScreenName).Append(" : ");
1829 case MyCommon.NameBalloonEnum.NickName:
1830 sb.Append(post.Nickname).Append(" : ");
1833 sb.Append(post.TextFromApi);
1836 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1837 StringBuilder title = new StringBuilder();
1839 if (this._cfgCommon.DispUsername)
1841 title.Append(tw.Username);
1842 title.Append(" - ");
1850 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1851 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1852 ntIcon = ToolTipIcon.Warning;
1853 title.Append(Application.ProductName);
1854 title.Append(" [DM] ");
1855 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1859 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1860 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1861 ntIcon = ToolTipIcon.Warning;
1862 title.Append(Application.ProductName);
1863 title.Append(" [Reply!] ");
1864 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1868 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1869 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1870 ntIcon = ToolTipIcon.Info;
1871 title.Append(Application.ProductName);
1873 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1875 string bText = sb.ToString();
1876 if (string.IsNullOrEmpty(bText)) return;
1877 //NotifyIcon1.BalloonTipText = sb.ToString();
1878 //NotifyIcon1.ShowBalloonTip(500);
1879 NotifyIcon1.BalloonTipTitle = title.ToString();
1880 NotifyIcon1.BalloonTipText = bText;
1881 NotifyIcon1.BalloonTipIcon = ntIcon;
1882 NotifyIcon1.ShowBalloonTip(500);
1888 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1892 string dir = Application.StartupPath;
1893 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1895 dir = Path.Combine(dir, "Sounds");
1897 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1907 //mentions新着時に画面ブリンク
1908 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1910 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1914 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1916 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1918 _curItemIndex = _curList.SelectedIndices[0];
1919 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1923 this._curPost = GetCurTabPost(_curItemIndex);
1925 catch (ArgumentException)
1930 this.PushSelectPostChain();
1932 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1934 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1940 private void ChangeCacheStyleRead(bool Read, int Index)
1942 var tabInfo = _statuses.Tabs[_curTab.Text];
1943 //Read:true=既読 false=未読
1944 //未読管理していなかったら既読として扱う
1945 if (!tabInfo.UnreadManage ||
1946 !this._cfgCommon.UnreadManage) Read = true;
1948 var listCache = this._listItemCache;
1949 if (listCache == null)
1952 // キャッシュに含まれていないアイテムは対象外
1955 if (!listCache.TryGetValue(Index, out itm, out post))
1958 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1961 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1968 Item.SubItems[5].Text = "";
1973 Item.SubItems[5].Text = "★";
1979 else if (Post.RetweetedId != null)
1981 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1983 else if (Read || !this._cfgCommon.UseUnreadStyle)
1988 if (DList == null || Item.Index == -1)
1990 Item.ForeColor = cl;
1991 if (this._cfgCommon.UseUnreadStyle)
1997 if (this._cfgCommon.UseUnreadStyle)
1998 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2000 DList.ChangeItemForeColor(Item.Index, cl);
2001 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2005 private void ColorizeList()
2007 //Index:更新対象のListviewItem.Index。Colorを返す。
2008 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2011 _post = _anchorPost;
2015 if (_post == null) return;
2017 var listCache = this._listItemCache;
2018 if (listCache == null)
2021 var index = listCache.StartIndex;
2022 foreach (var cachedPost in listCache.Post)
2024 var backColor = this.JudgeColor(_post, cachedPost);
2025 this._curList.ChangeItemBackColor(index++, backColor);
2029 private void ColorizeList(ListViewItem Item, int Index)
2031 //Index:更新対象のListviewItem.Index。Colorを返す。
2032 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2035 _post = _anchorPost;
2039 PostClass tPost = GetCurTabPost(Index);
2041 if (_post == null) return;
2043 if (Item.Index == -1)
2044 Item.BackColor = JudgeColor(_post, tPost);
2046 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2049 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2052 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2055 else if (TargetPost.IsMe)
2058 else if (TargetPost.IsReply)
2061 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2063 cl = _clAtFromTarget;
2064 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2067 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2072 cl = _clListBackcolor;
2077 private async void PostButton_Click(object sender, EventArgs e)
2079 if (StatusText.Text.Trim().Length == 0)
2081 if (!ImageSelector.Enabled)
2083 await this.DoRefresh();
2088 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2090 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2092 MessageBoxButtons.YesNoCancel,
2093 MessageBoxIcon.Question);
2096 case DialogResult.Yes:
2097 StatusText.Text = "";
2098 await this.doReTweetOfficial(false);
2100 case DialogResult.Cancel:
2105 var inReplyToStatusId = this.inReplyTo?.Item1;
2106 var inReplyToScreenName = this.inReplyTo?.Item2;
2107 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2109 if (this._cfgCommon.Nicoms)
2111 StatusText.SelectionStart = StatusText.Text.Length;
2112 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2114 //if (SettingDialog.UrlConvertAuto)
2116 // StatusText.SelectionStart = StatusText.Text.Length;
2117 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2119 //else if (SettingDialog.Nicoms)
2121 // StatusText.SelectionStart = StatusText.Text.Length;
2122 // UrlConvert(UrlConverter.Nicoms);
2124 StatusText.SelectionStart = StatusText.Text.Length;
2125 CheckReplyTo(StatusText.Text);
2127 var statusText = this.FormatStatusText(this.StatusText.Text);
2129 if (this.GetRestStatusCount(statusText) < 0)
2131 // 文字数制限を超えているが強制的に投稿するか
2132 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2133 if (ret != DialogResult.OK)
2137 var status = new PostingStatus();
2138 status.status = statusText;
2140 status.inReplyToId = this.inReplyTo?.Item1;
2141 status.inReplyToName = this.inReplyTo?.Item2;
2142 if (ImageSelector.Visible)
2145 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2149 this.inReplyTo = null;
2150 StatusText.Text = "";
2151 _history.Add(new PostingStatus());
2152 _hisIdx = _history.Count - 1;
2153 if (!ToolStripFocusLockMenuItem.Checked)
2154 ((Control)ListTab.SelectedTab.Tag).Focus();
2155 urlUndoBuffer = null;
2156 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2159 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2161 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2162 await this.OpenUriInBrowserAsync(tmp);
2165 await this.PostMessageAsync(status);
2168 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2170 MyCommon._endingFlag = true;
2174 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2176 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2178 //_endingFlag=false:フォームの×ボタン
2180 this.Visible = false;
2184 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2185 _ignoreConfigSave = true;
2186 MyCommon._endingFlag = true;
2187 TimerTimeline.Enabled = false;
2188 TimerRefreshIcon.Enabled = false;
2192 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2194 this.Visible = true;
2195 if (this.WindowState == FormWindowState.Minimized)
2197 this.WindowState = FormWindowState.Normal;
2200 this.BringToFront();
2203 private static int errorCount = 0;
2205 private static bool CheckAccountValid()
2207 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2213 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2222 private Task GetHomeTimelineAsync()
2224 return this.GetHomeTimelineAsync(loadMore: false);
2227 private async Task GetHomeTimelineAsync(bool loadMore)
2229 await this.workerSemaphore.WaitAsync();
2233 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
2234 await homeTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2236 this.RefreshTimeline();
2238 catch (WebApiException ex)
2240 this._myStatusError = true;
2241 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2245 this.workerSemaphore.Release();
2249 private Task GetReplyAsync()
2251 return this.GetReplyAsync(loadMore: false);
2254 private async Task GetReplyAsync(bool loadMore)
2256 await this.workerSemaphore.WaitAsync();
2260 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
2261 await replyTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2263 this.RefreshTimeline();
2265 catch (WebApiException ex)
2267 this._myStatusError = true;
2268 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2272 this.workerSemaphore.Release();
2276 private Task GetDirectMessagesAsync()
2278 return this.GetDirectMessagesAsync(loadMore: false);
2281 private async Task GetDirectMessagesAsync(bool loadMore)
2283 await this.workerSemaphore.WaitAsync();
2287 var dmTab = this._statuses.GetTabByType<DirectMessagesTabModel>();
2288 await dmTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2290 this.RefreshTimeline();
2292 catch (WebApiException ex)
2294 this._myStatusError = true;
2295 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2299 this.workerSemaphore.Release();
2303 private Task GetFavoritesAsync()
2305 return this.GetFavoritesAsync(loadMore: false);
2308 private async Task GetFavoritesAsync(bool loadMore)
2310 await this.workerSemaphore.WaitAsync();
2314 var favTab = this._statuses.GetTabByType<FavoritesTabModel>();
2315 await favTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2317 this.RefreshTimeline();
2319 catch (WebApiException ex)
2321 this._myStatusError = true;
2322 this.StatusLabel.Text = ex.Message;
2326 this.workerSemaphore.Release();
2330 private Task GetPublicSearchAllAsync()
2332 var tabs = this._statuses.GetTabsByType<PublicSearchTabModel>();
2334 return this.GetPublicSearchAsync(tabs, loadMore: false);
2337 private Task GetPublicSearchAsync(PublicSearchTabModel tab)
2339 return this.GetPublicSearchAsync(tab, loadMore: false);
2342 private Task GetPublicSearchAsync(PublicSearchTabModel tab, bool loadMore)
2344 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2347 private async Task GetPublicSearchAsync(IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2349 await this.workerSemaphore.WaitAsync();
2353 foreach (var tab in tabs)
2357 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2359 catch (WebApiException ex)
2361 this._myStatusError = true;
2362 this.StatusLabel.Text = $"Err:{ex.Message}(GetSearch)";
2366 this.RefreshTimeline();
2370 this.workerSemaphore.Release();
2374 private Task GetUserTimelineAllAsync()
2376 var tabs = this._statuses.GetTabsByType<UserTimelineTabModel>();
2378 return this.GetUserTimelineAsync(tabs, loadMore: false);
2381 private Task GetUserTimelineAsync(UserTimelineTabModel tab)
2383 return this.GetUserTimelineAsync(tab, loadMore: false);
2386 private Task GetUserTimelineAsync(UserTimelineTabModel tab, bool loadMore)
2388 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2391 private async Task GetUserTimelineAsync(IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2393 await this.workerSemaphore.WaitAsync();
2397 foreach (var tab in tabs)
2401 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2403 catch (WebApiException ex)
2405 this._myStatusError = true;
2406 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2410 this.RefreshTimeline();
2414 this.workerSemaphore.Release();
2418 private Task GetListTimelineAllAsync()
2420 var tabs = this._statuses.GetTabsByType<ListTimelineTabModel>();
2422 return this.GetListTimelineAsync(tabs, loadMore: false);
2425 private Task GetListTimelineAsync(ListTimelineTabModel tab)
2427 return this.GetListTimelineAsync(tab, loadMore: false);
2430 private Task GetListTimelineAsync(ListTimelineTabModel tab, bool loadMore)
2432 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2435 private async Task GetListTimelineAsync(IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2437 await this.workerSemaphore.WaitAsync();
2441 foreach (var tab in tabs)
2445 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2447 catch (WebApiException ex)
2449 this._myStatusError = true;
2450 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2454 this.RefreshTimeline();
2458 this.workerSemaphore.Release();
2462 private async Task GetRelatedTweetsAsync(RelatedPostsTabModel tab)
2464 await this.workerSemaphore.WaitAsync();
2468 await tab.RefreshAsync(this.tw, this._initial, this.workerProgress);
2470 this.RefreshTimeline();
2472 catch (WebApiException ex)
2474 this._myStatusError = true;
2475 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2479 this.workerSemaphore.Release();
2483 private async Task FavAddAsync(long statusId, TabModel tab)
2485 await this.workerSemaphore.WaitAsync();
2489 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2491 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2493 catch (WebApiException ex)
2495 this._myStatusError = true;
2496 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2500 this.workerSemaphore.Release();
2504 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2506 if (ct.IsCancellationRequested)
2509 if (!CheckAccountValid())
2510 throw new WebApiException("Auth error. Check your account");
2513 if (!tab.Posts.TryGetValue(statusId, out post))
2519 await Task.Run(async () =>
2521 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2525 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2527 .ConfigureAwait(false);
2529 if (this._cfgCommon.RestrictFavCheck)
2531 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2532 .ConfigureAwait(false);
2534 if (status.Favorited != true)
2535 throw new WebApiException("NG(Restricted?)");
2538 this._favTimestamps.Add(DateTime.Now);
2541 if (this._statuses.ContainsKey(statusId))
2543 var postTl = this._statuses[statusId];
2544 postTl.IsFav = true;
2546 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2547 favTab.AddPostQueue(postTl);
2550 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2551 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2553 if (tb.Contains(statusId))
2554 tb.Posts[statusId].IsFav = true;
2557 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2559 catch (WebApiException)
2561 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2566 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2567 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2569 if (this._favTimestamps[i] < oneHour)
2570 this._favTimestamps.RemoveAt(i);
2573 this._statuses.DistributePosts();
2576 if (ct.IsCancellationRequested)
2579 this.RefreshTimeline();
2581 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2583 using (ControlTransaction.Update(this._curList))
2585 var idx = tab.IndexOf(statusId);
2587 this.ChangeCacheStyleRead(post.IsRead, idx);
2590 if (statusId == this._curPost.StatusId)
2591 await this.DispSelectedPost(true); // 選択アイテム再表示
2595 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2597 await this.workerSemaphore.WaitAsync();
2601 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2603 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2605 catch (WebApiException ex)
2607 this._myStatusError = true;
2608 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2612 this.workerSemaphore.Release();
2616 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2618 if (ct.IsCancellationRequested)
2621 if (!CheckAccountValid())
2622 throw new WebApiException("Auth error. Check your account");
2624 var successIds = new List<long>();
2626 await Task.Run(async () =>
2630 var failedCount = 0;
2631 foreach (var statusId in statusIds)
2635 var post = tab.Posts[statusId];
2637 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2644 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2646 .ConfigureAwait(false);
2648 catch (WebApiException)
2654 successIds.Add(statusId);
2655 post.IsFav = false; // リスト再描画必要
2657 if (this._statuses.ContainsKey(statusId))
2659 this._statuses[statusId].IsFav = false;
2662 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2663 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2665 if (tb.Contains(statusId))
2666 tb.Posts[statusId].IsFav = false;
2671 if (ct.IsCancellationRequested)
2674 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2675 foreach (var statusId in successIds)
2677 // ツイートが削除された訳ではないので IsDeleted はセットしない
2678 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2681 this.RefreshTimeline();
2683 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2685 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2691 using (ControlTransaction.Update(this._curList))
2693 foreach (var statusId in successIds)
2695 var idx = tab.IndexOf(statusId);
2699 var post = tab.Posts[statusId];
2700 this.ChangeCacheStyleRead(post.IsRead, idx);
2704 if (successIds.Contains(this._curPost.StatusId))
2705 await this.DispSelectedPost(true); // 選択アイテム再表示
2710 private async Task PostMessageAsync(PostingStatus status)
2712 await this.workerSemaphore.WaitAsync();
2716 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2718 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
2720 catch (WebApiException ex)
2722 this._myStatusError = true;
2723 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2727 this.workerSemaphore.Release();
2731 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
2733 if (ct.IsCancellationRequested)
2736 if (!CheckAccountValid())
2737 throw new WebApiException("Auth error. Check your account");
2739 p.Report("Posting...");
2745 await Task.Run(async () =>
2747 if (status.mediaItems == null || status.mediaItems.Length == 0)
2749 await this.tw.PostStatus(status.status, status.inReplyToId)
2750 .ConfigureAwait(false);
2754 var service = ImageSelector.GetService(status.imageService);
2755 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
2756 .ConfigureAwait(false);
2760 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2762 catch (WebApiException ex)
2764 // 処理は中断せずエラーの表示のみ行う
2765 errMsg = $"Err:{ex.Message}(PostMessage)";
2767 this._myStatusError = true;
2771 // 使い終わった MediaItem は破棄する
2772 if (status.mediaItems != null)
2774 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
2776 disposableItem.Dispose();
2781 if (ct.IsCancellationRequested)
2784 if (!string.IsNullOrEmpty(errMsg) &&
2785 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2786 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2788 var ret = MessageBox.Show(
2790 "{0} ---> [ " + errMsg + " ]" + Environment.NewLine +
2791 "\"" + status.status + "\"" + Environment.NewLine +
2793 Properties.Resources.StatusUpdateFailed1,
2794 Properties.Resources.StatusUpdateFailed2),
2795 "Failed to update status",
2796 MessageBoxButtons.RetryCancel,
2797 MessageBoxIcon.Question);
2799 if (ret == DialogResult.Retry)
2801 await this.PostMessageAsync(status);
2805 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2806 if (this.ToolStripFocusLockMenuItem.Checked)
2807 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2812 this._postTimestamps.Add(DateTime.Now);
2814 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2815 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2817 if (this._postTimestamps[i] < oneHour)
2818 this._postTimestamps.RemoveAt(i);
2821 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2823 this.HashMgr.ClearHashtag();
2824 this.HashStripSplitButton.Text = "#[-]";
2825 this.HashToggleMenuItem.Checked = false;
2826 this.HashToggleToolStripMenuItem.Checked = false;
2829 this.SetMainWindowTitle();
2831 if (this._cfgCommon.PostAndGet)
2833 if (this.tw.UserStreamActive)
2834 this.RefreshTimeline();
2836 await this.GetHomeTimelineAsync();
2840 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2842 await this.workerSemaphore.WaitAsync();
2846 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2848 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2850 catch (WebApiException ex)
2852 this._myStatusError = true;
2853 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2857 this.workerSemaphore.Release();
2861 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2863 if (ct.IsCancellationRequested)
2866 if (!CheckAccountValid())
2867 throw new WebApiException("Auth error. Check your account");
2870 if (!this._cfgCommon.UnreadManage)
2873 read = this._initial && this._cfgCommon.Read;
2875 p.Report("Posting...");
2877 var retweetTasks = from statusId in statusIds
2878 select this.tw.PostRetweet(statusId, read);
2880 await Task.WhenAll(retweetTasks)
2881 .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);
2897 if (this._cfgCommon.PostAndGet && !this.tw.UserStreamActive)
2898 await this.GetHomeTimelineAsync();
2901 private async Task RefreshFollowerIdsAsync()
2903 await this.workerSemaphore.WaitAsync();
2906 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2908 await this.tw.RefreshFollowerIds();
2910 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2912 this.RefreshTimeline();
2913 this.PurgeListViewItemCache();
2914 this._curList?.Refresh();
2916 catch (WebApiException ex)
2918 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2922 this.workerSemaphore.Release();
2926 private async Task RefreshNoRetweetIdsAsync()
2928 await this.workerSemaphore.WaitAsync();
2931 await this.tw.RefreshNoRetweetIds();
2933 this.StatusLabel.Text = "NoRetweetIds refreshed";
2935 catch (WebApiException ex)
2937 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2941 this.workerSemaphore.Release();
2945 private async Task RefreshBlockIdsAsync()
2947 await this.workerSemaphore.WaitAsync();
2950 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2952 await this.tw.RefreshBlockIds();
2954 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2956 catch (WebApiException ex)
2958 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2962 this.workerSemaphore.Release();
2966 private async Task RefreshTwitterConfigurationAsync()
2968 await this.workerSemaphore.WaitAsync();
2971 await this.tw.RefreshConfiguration();
2973 if (this.tw.Configuration.PhotoSizeLimit != 0)
2975 foreach (var service in this.ImageSelector.GetServices())
2977 service.UpdateTwitterConfiguration(this.tw.Configuration);
2981 this.PurgeListViewItemCache();
2983 this._curList?.Refresh();
2985 catch (WebApiException ex)
2987 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2991 this.workerSemaphore.Release();
2995 private async Task RefreshMuteUserIdsAsync()
2997 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3001 await tw.RefreshMuteUserIdsAsync();
3003 catch (WebApiException ex)
3005 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3009 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3012 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3014 if (e.Button == MouseButtons.Left)
3016 this.Visible = true;
3017 if (this.WindowState == FormWindowState.Minimized)
3019 this.WindowState = _formWindowState;
3022 this.BringToFront();
3026 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3028 switch (this._cfgCommon.ListDoubleClickAction)
3031 MakeReplyOrDirectStatus();
3034 await this.FavoriteChange(true);
3037 if (_curPost != null)
3038 await this.ShowUserStatus(_curPost.ScreenName, false);
3044 ShowRelatedStatusesMenuItem_Click(null, null);
3047 MoveToHomeToolStripMenuItem_Click(null, null);
3050 StatusOpenMenuItem_Click(null, null);
3058 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3060 await this.FavoriteChange(true);
3063 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3065 await this.FavoriteChange(false);
3069 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3071 await this.FavoritesRetweetOfficial();
3074 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3076 await this.FavoritesRetweetUnofficial();
3079 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3082 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3085 //trueでFavAdd,falseでFavRemove
3086 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3087 || !this.ExistCurrentPost) return;
3089 if (this._curList.SelectedIndices.Count > 1)
3094 // https://support.twitter.com/articles/76915#favoriting
3095 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3096 _DoFavRetweetFlags = false;
3101 if (multiFavoriteChangeDialogEnable)
3103 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3104 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3105 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3107 if (confirm == DialogResult.Cancel)
3115 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3116 if (selectedPost.IsFav)
3118 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3122 await this.FavAddAsync(selectedPost.StatusId, tab);
3126 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3127 .Select(x => this.GetCurTabPost(x))
3128 .Where(x => x.IsFav);
3130 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3131 if (statusIds.Length == 0)
3133 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3137 await this.FavRemoveAsync(statusIds, tab);
3141 private PostClass GetCurTabPost(int Index)
3143 var listCache = this._listItemCache;
3144 if (listCache != null)
3148 if (listCache.TryGetValue(Index, out item, out post))
3152 return _statuses.Tabs[_curTab.Text][Index];
3155 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3157 if (_curList.SelectedIndices.Count > 0)
3158 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3159 else if (_curList.SelectedIndices.Count == 0)
3160 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3163 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3165 if (_curList.SelectedIndices.Count > 0)
3166 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3169 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3171 if ((!_initialLayout) && this.Visible)
3173 if (this.WindowState == FormWindowState.Normal)
3175 _mySize = this.ClientSize;
3176 _mySpDis = this.SplitContainer1.SplitterDistance;
3177 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3178 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3179 ModifySettingLocal = true;
3184 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3186 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3187 if (comparerMode == null)
3190 this.SetSortColumn(comparerMode.Value);
3194 /// 列インデックスからソートを行う ComparerMode を求める
3196 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3197 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3198 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3201 return ComparerMode.Id;
3203 switch (columnIndex)
3206 return ComparerMode.Nickname;
3208 return ComparerMode.Data;
3210 return ComparerMode.Id;
3212 return ComparerMode.Name;
3214 return ComparerMode.Source;
3216 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3222 /// 発言一覧の指定した位置の列でソートする
3224 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3225 private void SetSortColumnByDisplayIndex(int columnIndex)
3227 // 表示上の列の位置から ColumnHeader を求める
3228 var col = this._curList.Columns.Cast<ColumnHeader>()
3229 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3234 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3235 if (comparerMode == null)
3238 this.SetSortColumn(comparerMode.Value);
3242 /// 発言一覧の最後列の項目でソートする
3244 private void SetSortLastColumn()
3246 // 表示上の最後列にある ColumnHeader を求める
3247 var col = this._curList.Columns.Cast<ColumnHeader>()
3248 .OrderByDescending(x => x.DisplayIndex)
3251 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3252 if (comparerMode == null)
3255 this.SetSortColumn(comparerMode.Value);
3259 /// 発言一覧を指定された ComparerMode に基づいてソートする
3261 private void SetSortColumn(ComparerMode sortColumn)
3263 if (this._cfgCommon.SortOrderLock)
3266 this._statuses.ToggleSortOrder(sortColumn);
3267 this.InitColumnText();
3269 var list = this._curList;
3272 list.Columns[0].Text = this.ColumnText[0];
3273 list.Columns[1].Text = this.ColumnText[2];
3277 for (var i = 0; i <= 7; i++)
3279 list.Columns[i].Text = this.ColumnText[i];
3283 this.PurgeListViewItemCache();
3285 var tab = this._statuses.Tabs[this._curTab.Text];
3286 if (tab.AllCount > 0 && this._curPost != null)
3288 var idx = tab.IndexOf(this._curPost.StatusId);
3291 this.SelectListItem(list, idx);
3292 list.EnsureVisible(idx);
3297 this.ModifySettingCommon = true;
3300 private void TweenMain_LocationChanged(object sender, EventArgs e)
3302 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3304 _myLoc = this.DesktopLocation;
3305 ModifySettingLocal = true;
3309 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3311 if (ListTab.SelectedTab == null) return;
3312 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3313 if (!this.ExistCurrentPost)
3315 ReplyStripMenuItem.Enabled = false;
3316 ReplyAllStripMenuItem.Enabled = false;
3317 DMStripMenuItem.Enabled = false;
3318 ShowProfileMenuItem.Enabled = false;
3319 ShowUserTimelineContextMenuItem.Enabled = false;
3320 ListManageUserContextToolStripMenuItem2.Enabled = false;
3321 MoveToFavToolStripMenuItem.Enabled = false;
3322 TabMenuItem.Enabled = false;
3323 IDRuleMenuItem.Enabled = false;
3324 SourceRuleMenuItem.Enabled = false;
3325 ReadedStripMenuItem.Enabled = false;
3326 UnreadStripMenuItem.Enabled = false;
3330 ShowProfileMenuItem.Enabled = true;
3331 ListManageUserContextToolStripMenuItem2.Enabled = true;
3332 ReplyStripMenuItem.Enabled = true;
3333 ReplyAllStripMenuItem.Enabled = true;
3334 DMStripMenuItem.Enabled = true;
3335 ShowUserTimelineContextMenuItem.Enabled = true;
3336 MoveToFavToolStripMenuItem.Enabled = true;
3337 TabMenuItem.Enabled = true;
3338 IDRuleMenuItem.Enabled = true;
3339 SourceRuleMenuItem.Enabled = true;
3340 ReadedStripMenuItem.Enabled = true;
3341 UnreadStripMenuItem.Enabled = true;
3343 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3345 FavAddToolStripMenuItem.Enabled = false;
3346 FavRemoveToolStripMenuItem.Enabled = false;
3347 StatusOpenMenuItem.Enabled = false;
3348 FavorareMenuItem.Enabled = false;
3349 ShowRelatedStatusesMenuItem.Enabled = false;
3351 ReTweetStripMenuItem.Enabled = false;
3352 ReTweetUnofficialStripMenuItem.Enabled = false;
3353 QuoteStripMenuItem.Enabled = false;
3354 FavoriteRetweetContextMenu.Enabled = false;
3355 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3359 FavAddToolStripMenuItem.Enabled = true;
3360 FavRemoveToolStripMenuItem.Enabled = true;
3361 StatusOpenMenuItem.Enabled = true;
3362 FavorareMenuItem.Enabled = true;
3363 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3367 ReTweetStripMenuItem.Enabled = false; //公式RTは無効に
3368 ReTweetUnofficialStripMenuItem.Enabled = true;
3369 QuoteStripMenuItem.Enabled = true;
3370 FavoriteRetweetContextMenu.Enabled = false; //公式RTは無効に
3371 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3375 if (_curPost.IsProtect)
3377 ReTweetStripMenuItem.Enabled = false;
3378 ReTweetUnofficialStripMenuItem.Enabled = false;
3379 QuoteStripMenuItem.Enabled = false;
3380 FavoriteRetweetContextMenu.Enabled = false;
3381 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3385 ReTweetStripMenuItem.Enabled = true;
3386 ReTweetUnofficialStripMenuItem.Enabled = true;
3387 QuoteStripMenuItem.Enabled = true;
3388 FavoriteRetweetContextMenu.Enabled = true;
3389 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3393 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3395 // RefreshMoreStripMenuItem.Enabled = true;
3399 // RefreshMoreStripMenuItem.Enabled = false;
3401 if (!this.ExistCurrentPost
3402 || _curPost.InReplyToStatusId == null)
3404 RepliedStatusOpenMenuItem.Enabled = false;
3408 RepliedStatusOpenMenuItem.Enabled = true;
3410 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3412 MoveToRTHomeMenuItem.Enabled = false;
3416 MoveToRTHomeMenuItem.Enabled = true;
3419 if (this.ExistCurrentPost)
3421 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3422 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3423 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3425 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3429 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3431 MakeReplyOrDirectStatus(false, true);
3434 private void DMStripMenuItem_Click(object sender, EventArgs e)
3436 MakeReplyOrDirectStatus(false, false);
3439 private async Task doStatusDelete()
3441 if (this._curTab == null || this._curList == null)
3444 if (this._curList.SelectedIndices.Count == 0)
3447 var posts = this._curList.SelectedIndices.Cast<int>()
3448 .Select(x => this.GetCurTabPost(x))
3451 // 選択されたツイートの中に削除可能なものが一つでもあるか
3452 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3455 var ret = MessageBox.Show(this,
3456 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3457 Properties.Resources.DeleteStripMenuItem_ClickText2,
3458 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3460 if (ret != DialogResult.OK)
3463 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3465 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3467 Exception lastException = null;
3468 foreach (var post in posts)
3470 if (!post.CanDeleteBy(this.tw.UserId))
3477 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3482 if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3483 // 他人に RT された自分のツイート
3484 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3487 // 自分のツイート or 自分が RT したツイート
3488 await this.twitterApi.StatusesDestroy(post.StatusId)
3492 catch (WebApiException ex)
3498 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3501 if (lastException == null)
3502 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3504 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3506 this.PurgeListViewItemCache();
3507 this._curPost = null;
3508 this._curItemIndex = -1;
3510 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3512 var listView = (DetailsListView)tabPage.Tag;
3513 var tab = this._statuses.Tabs[tabPage.Text];
3515 using (ControlTransaction.Update(listView))
3517 listView.VirtualListSize = tab.AllCount;
3519 if (tabPage == this._curTab)
3521 listView.SelectedIndices.Clear();
3523 if (tab.AllCount != 0)
3526 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3527 selectedIndex = focusedIndex;
3529 selectedIndex = tab.AllCount - 1;
3531 listView.SelectedIndices.Add(selectedIndex);
3532 listView.EnsureVisible(selectedIndex);
3533 listView.FocusedItem = listView.Items[selectedIndex];
3538 if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3540 if (tabPage.ImageIndex == 0)
3541 tabPage.ImageIndex = -1; // タブアイコン
3545 if (!this._cfgCommon.TabIconDisp)
3546 this.ListTab.Refresh();
3550 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3552 await this.doStatusDelete();
3555 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3557 using (ControlTransaction.Update(this._curList))
3559 foreach (int idx in _curList.SelectedIndices)
3561 var post = this._statuses.Tabs[this._curTab.Text][idx];
3562 this._statuses.SetReadAllTab(post.StatusId, read: true);
3563 ChangeCacheStyleRead(true, idx);
3567 foreach (TabPage tb in ListTab.TabPages)
3569 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3571 if (this._cfgCommon.TabIconDisp)
3573 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3577 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3580 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3582 using (ControlTransaction.Update(this._curList))
3584 foreach (int idx in _curList.SelectedIndices)
3586 var post = this._statuses.Tabs[this._curTab.Text][idx];
3587 this._statuses.SetReadAllTab(post.StatusId, read: false);
3588 ChangeCacheStyleRead(false, idx);
3592 foreach (TabPage tb in ListTab.TabPages)
3594 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3596 if (this._cfgCommon.TabIconDisp)
3598 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3602 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3605 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3607 await this.DoRefresh();
3610 private async Task DoRefresh()
3612 if (_curTab != null)
3615 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3618 switch (_statuses.Tabs[_curTab.Text].TabType)
3620 case MyCommon.TabUsageType.Mentions:
3621 await this.GetReplyAsync();
3623 case MyCommon.TabUsageType.DirectMessage:
3624 await this.GetDirectMessagesAsync();
3626 case MyCommon.TabUsageType.Favorites:
3627 await this.GetFavoritesAsync();
3629 //case MyCommon.TabUsageType.Profile:
3631 case MyCommon.TabUsageType.PublicSearch:
3632 var searchTab = (PublicSearchTabModel)tab;
3633 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3634 await this.GetPublicSearchAsync(searchTab);
3636 case MyCommon.TabUsageType.UserTimeline:
3637 await this.GetUserTimelineAsync((UserTimelineTabModel)tab);
3639 case MyCommon.TabUsageType.Lists:
3640 var listTab = (ListTimelineTabModel)tab;
3641 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3642 await this.GetListTimelineAsync(listTab);
3645 await this.GetHomeTimelineAsync();
3651 await this.GetHomeTimelineAsync();
3655 private async Task DoRefreshMore()
3658 if (_curTab != null)
3661 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3664 switch (_statuses.Tabs[_curTab.Text].TabType)
3666 case MyCommon.TabUsageType.Mentions:
3667 await this.GetReplyAsync(loadMore: true);
3669 case MyCommon.TabUsageType.DirectMessage:
3670 await this.GetDirectMessagesAsync(loadMore: true);
3672 case MyCommon.TabUsageType.Favorites:
3673 await this.GetFavoritesAsync(loadMore: true);
3675 case MyCommon.TabUsageType.Profile:
3678 case MyCommon.TabUsageType.PublicSearch:
3679 var searchTab = (PublicSearchTabModel)tab;
3680 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3681 await this.GetPublicSearchAsync(searchTab, loadMore: true);
3683 case MyCommon.TabUsageType.UserTimeline:
3684 await this.GetUserTimelineAsync((UserTimelineTabModel)tab, loadMore: true);
3686 case MyCommon.TabUsageType.Lists:
3687 var listTab = (ListTimelineTabModel)tab;
3688 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3689 await this.GetListTimelineAsync(listTab, loadMore: true);
3692 await this.GetHomeTimelineAsync(loadMore: true);
3698 await this.GetHomeTimelineAsync(loadMore: true);
3702 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3704 DialogResult result = DialogResult.Abort;
3706 using (var settingDialog = new AppendSettingDialog())
3708 settingDialog.Icon = this.MainIcon;
3709 settingDialog.Owner = this;
3710 settingDialog.ShowInTaskbar = showTaskbarIcon;
3711 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3713 settingDialog.tw = this.tw;
3714 settingDialog.twitterApi = this.twitterApi;
3716 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
3720 result = settingDialog.ShowDialog(this);
3724 return DialogResult.Abort;
3727 if (result == DialogResult.OK)
3731 settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
3739 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3742 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3744 var oldIconSz = this._cfgCommon.IconSize;
3746 if (ShowSettingDialog() == DialogResult.OK)
3750 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
3751 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
3752 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
3753 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
3754 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
3755 TwitterApiConnection.RestApiHost = this._cfgCommon.TwitterApiHost;
3757 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
3758 Networking.SetWebProxy(this._cfgLocal.ProxyType,
3759 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
3760 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
3761 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
3763 ImageSelector.Reset(tw, this.tw.Configuration);
3767 if (this._cfgCommon.TabIconDisp)
3769 ListTab.DrawItem -= ListTab_DrawItem;
3770 ListTab.DrawMode = TabDrawMode.Normal;
3771 ListTab.ImageList = this.TabImage;
3775 ListTab.DrawItem -= ListTab_DrawItem;
3776 ListTab.DrawItem += ListTab_DrawItem;
3777 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3778 ListTab.ImageList = null;
3781 catch (Exception ex)
3783 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3784 ex.Data["IsTerminatePermission"] = false;
3790 if (!this._cfgCommon.UnreadManage)
3792 ReadedStripMenuItem.Enabled = false;
3793 UnreadStripMenuItem.Enabled = false;
3794 if (this._cfgCommon.TabIconDisp)
3796 foreach (TabPage myTab in ListTab.TabPages)
3798 myTab.ImageIndex = -1;
3804 ReadedStripMenuItem.Enabled = true;
3805 UnreadStripMenuItem.Enabled = true;
3808 catch (Exception ex)
3810 ex.Data["Instance"] = "ListTab(UnreadManage)";
3811 ex.Data["IsTerminatePermission"] = false;
3818 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
3820 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3821 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
3822 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
3824 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
3825 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
3826 _fntUnread = this._cfgLocal.FontUnread;
3827 _clUnread = this._cfgLocal.ColorUnread;
3828 _fntReaded = this._cfgLocal.FontRead;
3829 _clReaded = this._cfgLocal.ColorRead;
3830 _clFav = this._cfgLocal.ColorFav;
3831 _clOWL = this._cfgLocal.ColorOWL;
3832 _clRetweet = this._cfgLocal.ColorRetweet;
3833 _fntDetail = this._cfgLocal.FontDetail;
3834 _clDetail = this._cfgLocal.ColorDetail;
3835 _clDetailLink = this._cfgLocal.ColorDetailLink;
3836 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
3837 _clSelf = this._cfgLocal.ColorSelf;
3838 _clAtSelf = this._cfgLocal.ColorAtSelf;
3839 _clTarget = this._cfgLocal.ColorTarget;
3840 _clAtTarget = this._cfgLocal.ColorAtTarget;
3841 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
3842 _clAtTo = this._cfgLocal.ColorAtTo;
3843 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
3844 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
3845 _clInputFont = this._cfgLocal.ColorInputFont;
3846 _fntInputFont = this._cfgLocal.FontInputFont;
3847 _brsBackColorMine.Dispose();
3848 _brsBackColorAt.Dispose();
3849 _brsBackColorYou.Dispose();
3850 _brsBackColorAtYou.Dispose();
3851 _brsBackColorAtFromTarget.Dispose();
3852 _brsBackColorAtTo.Dispose();
3853 _brsBackColorNone.Dispose();
3854 _brsBackColorMine = new SolidBrush(_clSelf);
3855 _brsBackColorAt = new SolidBrush(_clAtSelf);
3856 _brsBackColorYou = new SolidBrush(_clTarget);
3857 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3858 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3859 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3860 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3864 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3865 StatusText.Font = _fntInputFont;
3866 StatusText.ForeColor = _clInputFont;
3868 catch (Exception ex)
3870 MessageBox.Show(ex.Message);
3875 InitDetailHtmlFormat();
3877 catch (Exception ex)
3879 ex.Data["Instance"] = "Font";
3880 ex.Data["IsTerminatePermission"] = false;
3886 foreach (TabPage tb in ListTab.TabPages)
3888 if (this._cfgCommon.TabIconDisp)
3890 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3897 catch (Exception ex)
3899 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3900 ex.Data["IsTerminatePermission"] = false;
3906 var oldIconCol = _iconCol;
3908 if (this._cfgCommon.IconSize != oldIconSz)
3909 ApplyListViewIconSize(this._cfgCommon.IconSize);
3911 foreach (TabPage tp in ListTab.TabPages)
3913 DetailsListView lst = (DetailsListView)tp.Tag;
3915 using (ControlTransaction.Update(lst))
3917 lst.GridLines = this._cfgCommon.ShowGrid;
3918 lst.Font = _fntReaded;
3919 lst.BackColor = _clListBackcolor;
3921 if (_iconCol != oldIconCol)
3926 catch (Exception ex)
3928 ex.Data["Instance"] = "ListView(IconSize)";
3929 ex.Data["IsTerminatePermission"] = false;
3933 SetMainWindowTitle();
3934 SetNotifyIconText();
3936 this.PurgeListViewItemCache();
3937 _curList?.Refresh();
3940 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3941 if (this._cfgCommon.HotkeyEnabled)
3943 ///グローバルホットキーの登録。設定で変更可能にするかも
3944 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
3945 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
3946 modKey |= HookGlobalHotkey.ModKeys.Alt;
3947 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
3948 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3949 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
3950 modKey |= HookGlobalHotkey.ModKeys.Shift;
3951 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
3952 modKey |= HookGlobalHotkey.ModKeys.Win;
3954 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
3957 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
3960 StatusText_TextChanged(null, null);
3969 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3970 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3973 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3975 this.TopMost = this._cfgCommon.AlwaysTop;
3976 SaveConfigsAll(false);
3978 if (tw.Username != oldUser.Username)
3979 await this.doGetFollowersMenu();
3985 private void SetTabAlignment()
3987 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3988 if (ListTab.Alignment == newAlignment) return;
3990 // 各タブのリスト上の選択位置などを退避
3991 var listSelections = this.SaveListViewSelection();
3993 ListTab.Alignment = newAlignment;
3995 foreach (TabPage tab in ListTab.TabPages)
3997 DetailsListView lst = (DetailsListView)tab.Tag;
3998 TabModel tabInfo = _statuses.Tabs[tab.Text];
3999 using (ControlTransaction.Update(lst))
4002 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4007 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4013 case MyCommon.IconSizes.IconNone:
4016 case MyCommon.IconSizes.Icon16:
4019 case MyCommon.IconSizes.Icon24:
4022 case MyCommon.IconSizes.Icon48:
4025 case MyCommon.IconSizes.Icon48_2:
4033 // ディスプレイの DPI 設定を考慮したサイズを設定する
4034 _listViewImageList.ImageSize = new Size(
4036 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4040 _listViewImageList.ImageSize = new Size(1, 1);
4044 private void ResetColumns(DetailsListView list)
4046 using (ControlTransaction.Update(list))
4047 using (ControlTransaction.Layout(list, false))
4050 list.ColumnClick -= MyList_ColumnClick;
4051 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4052 list.ColumnReordered -= MyList_ColumnReordered;
4053 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4055 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4056 list.Columns.Clear();
4057 cols.ForEach(col => col.Dispose());
4060 InitColumns(list, true);
4062 list.ColumnClick += MyList_ColumnClick;
4063 list.DrawColumnHeader += MyList_DrawColumnHeader;
4064 list.ColumnReordered += MyList_ColumnReordered;
4065 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4069 public void AddNewTabForSearch(string searchWord)
4071 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4072 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4074 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4076 foreach (TabPage tp in ListTab.TabPages)
4078 if (tb.TabName == tp.Text)
4080 ListTab.SelectedTab = tp;
4087 string tabName = searchWord;
4088 for (int i = 0; i <= 100; i++)
4090 if (_statuses.ContainsTab(tabName))
4096 var tab = new PublicSearchTabModel(tabName);
4097 _statuses.AddTab(tab);
4098 AddNewTab(tab, startup: false);
4100 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4102 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4103 cmb.Items.Add(searchWord);
4104 cmb.Text = searchWord;
4107 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4110 private void ShowUserTimeline()
4112 if (!this.ExistCurrentPost) return;
4113 AddNewTabForUserTimeline(_curPost.ScreenName);
4116 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4118 if (e.KeyCode == Keys.Escape)
4120 TabPage relTp = ListTab.SelectedTab;
4121 RemoveSpecifiedTab(relTp.Text, false);
4123 e.SuppressKeyPress = true;
4127 public void AddNewTabForUserTimeline(string user)
4129 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4130 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4132 if (tb.ScreenName == user)
4134 foreach (TabPage tp in ListTab.TabPages)
4136 if (tb.TabName == tp.Text)
4138 ListTab.SelectedTab = tp;
4145 string tabName = "user:" + user;
4146 while (_statuses.ContainsTab(tabName))
4151 var tab = new UserTimelineTabModel(tabName, user);
4152 this._statuses.AddTab(tab);
4153 this.AddNewTab(tab, startup: false);
4155 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4158 this.GetUserTimelineAsync(tab);
4161 public bool AddNewTab(TabModel tab, bool startup)
4164 foreach (TabPage tb in ListTab.TabPages)
4166 if (tb.Text == tab.TabName) return false;
4170 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4172 var _tabPage = new TabPage();
4173 var _listCustom = new DetailsListView();
4175 int cnt = ListTab.TabPages.Count;
4177 ///ToDo:Create and set controls follow tabtypes
4179 using (ControlTransaction.Update(_listCustom))
4180 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4181 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4182 using (ControlTransaction.Layout(this.SplitContainer1, false))
4183 using (ControlTransaction.Layout(this.ListTab, false))
4184 using (ControlTransaction.Layout(this))
4185 using (ControlTransaction.Layout(_tabPage, false))
4187 _tabPage.Controls.Add(_listCustom);
4190 var userTab = tab as UserTimelineTabModel;
4191 var listTab = tab as ListTimelineTabModel;
4192 var searchTab = tab as PublicSearchTabModel;
4194 if (userTab != null || listTab != null)
4196 var label = new Label();
4197 label.Dock = DockStyle.Top;
4198 label.Name = "labelUser";
4201 if (listTab != null)
4203 label.Text = listTab.ListInfo.ToString();
4205 else if (userTab != null)
4207 label.Text = userTab.ScreenName + "'s Timeline";
4209 label.TextAlign = ContentAlignment.MiddleLeft;
4210 using (ComboBox tmpComboBox = new ComboBox())
4212 label.Height = tmpComboBox.Height;
4214 _tabPage.Controls.Add(label);
4217 else if (searchTab != null)
4219 var pnl = new Panel();
4221 var lbl = new Label();
4222 var cmb = new ComboBox();
4223 var btn = new Button();
4224 var cmbLang = new ComboBox();
4226 using (ControlTransaction.Layout(pnl, false))
4228 pnl.Controls.Add(cmb);
4229 pnl.Controls.Add(cmbLang);
4230 pnl.Controls.Add(btn);
4231 pnl.Controls.Add(lbl);
4232 pnl.Name = "panelSearch";
4234 pnl.Dock = DockStyle.Top;
4235 pnl.Height = cmb.Height;
4236 pnl.Enter += SearchControls_Enter;
4237 pnl.Leave += SearchControls_Leave;
4240 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4241 cmb.Dock = DockStyle.Fill;
4242 cmb.Name = "comboSearch";
4243 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4244 cmb.ImeMode = ImeMode.NoControl;
4245 cmb.TabStop = false;
4247 cmb.AutoCompleteMode = AutoCompleteMode.None;
4248 cmb.KeyDown += SearchComboBox_KeyDown;
4251 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4252 cmbLang.Dock = DockStyle.Right;
4254 cmbLang.Name = "comboLang";
4255 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4256 cmbLang.TabStop = false;
4257 cmbLang.TabIndex = 2;
4258 cmbLang.Items.Add("");
4259 cmbLang.Items.Add("ja");
4260 cmbLang.Items.Add("en");
4261 cmbLang.Items.Add("ar");
4262 cmbLang.Items.Add("da");
4263 cmbLang.Items.Add("nl");
4264 cmbLang.Items.Add("fa");
4265 cmbLang.Items.Add("fi");
4266 cmbLang.Items.Add("fr");
4267 cmbLang.Items.Add("de");
4268 cmbLang.Items.Add("hu");
4269 cmbLang.Items.Add("is");
4270 cmbLang.Items.Add("it");
4271 cmbLang.Items.Add("no");
4272 cmbLang.Items.Add("pl");
4273 cmbLang.Items.Add("pt");
4274 cmbLang.Items.Add("ru");
4275 cmbLang.Items.Add("es");
4276 cmbLang.Items.Add("sv");
4277 cmbLang.Items.Add("th");
4279 lbl.Text = "Search(C-S-f)";
4280 lbl.Name = "label1";
4281 lbl.Dock = DockStyle.Left;
4283 lbl.Height = cmb.Height;
4284 lbl.TextAlign = ContentAlignment.MiddleLeft;
4287 btn.Text = "Search";
4288 btn.Name = "buttonSearch";
4289 btn.UseVisualStyleBackColor = true;
4290 btn.Dock = DockStyle.Right;
4291 btn.TabStop = false;
4293 btn.Click += SearchButton_Click;
4295 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4297 cmb.Items.Add(searchTab.SearchWords);
4298 cmb.Text = searchTab.SearchWords;
4301 cmbLang.Text = searchTab.SearchLang;
4303 _tabPage.Controls.Add(pnl);
4307 _tabPage.Tag = _listCustom;
4308 this.ListTab.Controls.Add(_tabPage);
4310 _tabPage.Location = new Point(4, 4);
4311 _tabPage.Name = "CTab" + cnt;
4312 _tabPage.Size = new Size(380, 260);
4313 _tabPage.TabIndex = 2 + cnt;
4314 _tabPage.Text = tab.TabName;
4315 _tabPage.UseVisualStyleBackColor = true;
4316 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4318 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4319 _listCustom.TabIndex = 1;
4320 _listCustom.AllowColumnReorder = true;
4321 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4322 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4323 _listCustom.Dock = DockStyle.Fill;
4324 _listCustom.FullRowSelect = true;
4325 _listCustom.HideSelection = false;
4326 _listCustom.Location = new Point(0, 0);
4327 _listCustom.Margin = new Padding(0);
4328 _listCustom.Name = "CList" + Environment.TickCount;
4329 _listCustom.ShowItemToolTips = true;
4330 _listCustom.Size = new Size(380, 260);
4331 _listCustom.UseCompatibleStateImageBehavior = false;
4332 _listCustom.View = View.Details;
4333 _listCustom.OwnerDraw = true;
4334 _listCustom.VirtualMode = true;
4335 _listCustom.Font = _fntReaded;
4336 _listCustom.BackColor = _clListBackcolor;
4338 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4339 _listCustom.AllowDrop = true;
4341 _listCustom.SmallImageList = _listViewImageList;
4343 InitColumns(_listCustom, startup);
4345 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4346 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4347 _listCustom.ColumnClick += MyList_ColumnClick;
4348 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4349 _listCustom.DragDrop += TweenMain_DragDrop;
4350 _listCustom.DragEnter += TweenMain_DragEnter;
4351 _listCustom.DragOver += TweenMain_DragOver;
4352 _listCustom.DrawItem += MyList_DrawItem;
4353 _listCustom.MouseClick += MyList_MouseClick;
4354 _listCustom.ColumnReordered += MyList_ColumnReordered;
4355 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4356 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4357 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4358 _listCustom.DrawSubItem += MyList_DrawSubItem;
4359 _listCustom.HScrolled += MyList_HScrolled;
4365 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4367 var tabInfo = _statuses.GetTabByName(TabName);
4368 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4372 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4373 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4374 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4380 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4381 if (_tabPage == null) return false;
4383 SetListProperty(); //他のタブに列幅等を反映
4386 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4387 _tabPage.Tag = null;
4389 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4390 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4391 using (ControlTransaction.Layout(this.SplitContainer1, false))
4392 using (ControlTransaction.Layout(this.ListTab, false))
4393 using (ControlTransaction.Layout(this))
4394 using (ControlTransaction.Layout(_tabPage, false))
4396 if (this.ListTab.SelectedTab == _tabPage)
4398 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4399 this._beforeSelectedTab = null;
4401 this.ListTab.Controls.Remove(_tabPage);
4404 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4406 using (Control label = _tabPage.Controls["labelUser"])
4408 _tabPage.Controls.Remove(label);
4411 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4413 using (Control pnl = _tabPage.Controls["panelSearch"])
4415 pnl.Enter -= SearchControls_Enter;
4416 pnl.Leave -= SearchControls_Leave;
4417 _tabPage.Controls.Remove(pnl);
4419 foreach (Control ctrl in pnl.Controls)
4421 if (ctrl.Name == "buttonSearch")
4423 ctrl.Click -= SearchButton_Click;
4425 else if (ctrl.Name == "comboSearch")
4427 ctrl.KeyDown -= SearchComboBox_KeyDown;
4429 pnl.Controls.Remove(ctrl);
4435 _tabPage.Controls.Remove(_listCustom);
4437 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4438 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4439 _listCustom.ColumnClick -= MyList_ColumnClick;
4440 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4441 _listCustom.DragDrop -= TweenMain_DragDrop;
4442 _listCustom.DragEnter -= TweenMain_DragEnter;
4443 _listCustom.DragOver -= TweenMain_DragOver;
4444 _listCustom.DrawItem -= MyList_DrawItem;
4445 _listCustom.MouseClick -= MyList_MouseClick;
4446 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4447 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4448 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4449 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4450 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4451 _listCustom.HScrolled -= MyList_HScrolled;
4453 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4454 _listCustom.Columns.Clear();
4455 cols.ForEach(col => col.Dispose());
4458 _listCustom.ContextMenuStrip = null;
4459 _listCustom.ColumnHeaderContextMenuStrip = null;
4460 _listCustom.Font = null;
4462 _listCustom.SmallImageList = null;
4463 _listCustom.ListViewItemSorter = null;
4466 if (_curTab.Equals(_tabPage))
4473 this.PurgeListViewItemCache();
4477 _listCustom.Dispose();
4478 _statuses.RemoveTab(TabName);
4480 foreach (TabPage tp in ListTab.TabPages)
4482 DetailsListView lst = (DetailsListView)tp.Tag;
4483 var count = _statuses.Tabs[tp.Text].AllCount;
4484 lst.VirtualListSize = count;
4490 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4492 this.PurgeListViewItemCache();
4493 _beforeSelectedTab = e.TabPage;
4496 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4500 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4503 Rectangle dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4504 if (!dragEnableRectangle.Contains(e.Location))
4506 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4507 tn = ListTab.SelectedTab.Text;
4510 if (string.IsNullOrEmpty(tn)) return;
4512 foreach (TabPage tb in ListTab.TabPages)
4516 ListTab.DoDragDrop(tb, DragDropEffects.All);
4526 Point cpos = new Point(e.X, e.Y);
4527 for (int i = 0; i < ListTab.TabPages.Count; i++)
4529 Rectangle rect = ListTab.GetTabRect(i);
4530 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4531 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4533 _rclickTabName = ListTab.TabPages[i].Text;
4539 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4541 //_curList.Refresh();
4542 SetMainWindowTitle();
4543 SetStatusLabelUrl();
4544 SetApiStatusLabel();
4545 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4546 TabMenuControl(ListTab.SelectedTab.Text);
4547 this.PushSelectPostChain();
4548 await DispSelectedPost();
4551 private void SetListProperty()
4553 //削除などで見つからない場合は処理せず
4554 if (_curList == null) return;
4555 if (!_isColumnChanged) return;
4557 int[] dispOrder = new int[_curList.Columns.Count];
4558 for (int i = 0; i < _curList.Columns.Count; i++)
4560 for (int j = 0; j < _curList.Columns.Count; j++)
4562 if (_curList.Columns[j].DisplayIndex == i)
4571 foreach (TabPage tb in ListTab.TabPages)
4573 if (!tb.Equals(_curTab))
4575 if (tb.Tag != null && tb.Controls.Count > 0)
4577 DetailsListView lst = (DetailsListView)tb.Tag;
4578 for (int i = 0; i < lst.Columns.Count; i++)
4580 lst.Columns[dispOrder[i]].DisplayIndex = i;
4581 lst.Columns[i].Width = _curList.Columns[i].Width;
4587 _isColumnChanged = false;
4590 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4592 if (e.KeyChar == '@')
4594 if (!this._cfgCommon.UseAtIdSupplement) return;
4596 int cnt = AtIdSupl.ItemCount;
4597 ShowSuplDialog(StatusText, AtIdSupl);
4598 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
4601 else if (e.KeyChar == '#')
4603 if (!this._cfgCommon.UseHashSupplement) return;
4604 ShowSuplDialog(StatusText, HashSupl);
4609 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4611 ShowSuplDialog(owner, dialog, 0, "");
4614 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4616 ShowSuplDialog(owner, dialog, offset, "");
4619 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4621 dialog.StartsWith = startswith;
4628 dialog.ShowDialog();
4630 this.TopMost = this._cfgCommon.AlwaysTop;
4631 int selStart = owner.SelectionStart;
4634 if (dialog.DialogResult == DialogResult.OK)
4636 if (!string.IsNullOrEmpty(dialog.inputText))
4640 fHalf = owner.Text.Substring(0, selStart - offset);
4642 if (selStart < owner.Text.Length)
4644 eHalf = owner.Text.Substring(selStart);
4646 owner.Text = fHalf + dialog.inputText + eHalf;
4647 owner.SelectionStart = selStart + dialog.inputText.Length;
4654 fHalf = owner.Text.Substring(0, selStart);
4656 if (selStart < owner.Text.Length)
4658 eHalf = owner.Text.Substring(selStart);
4660 owner.Text = fHalf + eHalf;
4663 owner.SelectionStart = selStart;
4669 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4672 if (!e.Alt && !e.Control && !e.Shift)
4674 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4676 bool isSpace = false;
4677 foreach (char c in StatusText.Text)
4679 if (c == ' ' || c == ' ')
4692 StatusText.Text = "";
4693 JumpUnreadMenuItem_Click(null, null);
4697 this.StatusText_TextChanged(null, null);
4700 private void StatusText_TextChanged(object sender, EventArgs e)
4703 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
4704 lblLen.Text = pLen.ToString();
4707 StatusText.ForeColor = Color.Red;
4711 StatusText.ForeColor = _clInputFont;
4713 if (string.IsNullOrEmpty(StatusText.Text))
4715 this.inReplyTo = null;
4720 /// ツイート投稿前のフッター付与などの前処理を行います
4722 private string FormatStatusText(string statusText)
4724 statusText = statusText.Replace("\r\n", "\n");
4726 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
4729 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4732 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
4734 // 文中の全角スペースを半角スペース1個にする
4735 statusText = statusText.Replace(" ", " ");
4738 // DM の場合はこれ以降の処理を行わない
4739 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4743 if (this._cfgCommon.PostShiftEnter)
4745 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4749 if (this.StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
4750 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4752 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4755 if (statusText.Contains("RT @"))
4756 disableFooter = true;
4761 var hashtag = this.HashMgr.UseHash;
4762 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4765 header = HashMgr.UseHash + " ";
4767 footer = " " + HashMgr.UseHash;
4772 if (this._cfgLocal.UseRecommendStatus)
4775 footer += this.recommendedStatusFooter;
4777 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
4779 // テキストボックスに入力されている文字列を使用する
4780 footer += " " + this._cfgLocal.StatusText.Trim();
4784 statusText = header + statusText + footer;
4786 if (this.ToolStripMenuItemPreventSmsCommand.Checked)
4788 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4789 // 参照: https://support.twitter.com/articles/14020
4791 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4792 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4794 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4795 statusText = '\u200b' + statusText;
4803 /// 投稿欄に表示する入力可能な文字数を計算します
4805 private int GetRestStatusCount(string statusText)
4808 var remainCount = this.tw.GetTextLengthRemain(statusText);
4810 if (this.ImageSelector.Visible && !string.IsNullOrEmpty(this.ImageSelector.ServiceName))
4812 remainCount -= this.tw.Configuration.CharactersReservedPerMedia;
4818 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4820 if (sender != this._curList)
4823 var listCache = this._listItemCache;
4824 if (listCache != null && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4826 // If the newly requested cache is a subset of the old cache,
4827 // no need to rebuild everything, so do nothing.
4831 // Now we need to rebuild the cache.
4832 this.CreateCache(e.StartIndex, e.EndIndex);
4835 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4837 var listCache = this._listItemCache;
4838 if (listCache != null && listCache.TargetList == sender)
4841 PostClass cacheItemPost;
4842 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
4849 // A cache miss, so create a new ListViewItem and pass it back.
4850 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4853 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4857 // 不正な要求に対する間に合わせの応答
4858 string[] sitem = {"", "", "", "", "", "", "", ""};
4859 e.Item = new ImageListViewItem(sitem);
4863 private void CreateCache(int startIndex, int endIndex)
4865 var tabInfo = this._statuses.Tabs[this._curTab.Text];
4867 if (tabInfo.AllCount == 0)
4870 // キャッシュ要求(要求範囲±30を作成)
4871 startIndex = Math.Max(startIndex - 30, 0);
4872 endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
4874 var cacheLength = endIndex - startIndex + 1;
4876 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4877 var listItems = Enumerable.Range(0, cacheLength)
4878 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4881 var listCache = new ListViewItemCache
4883 TargetList = this._curList,
4884 StartIndex = startIndex,
4885 EndIndex = endIndex,
4887 ListItem = listItems,
4890 Interlocked.Exchange(ref this._listItemCache, listCache);
4894 /// DetailsListView のための ListViewItem のキャッシュを消去する
4896 private void PurgeListViewItemCache()
4898 Interlocked.Exchange(ref this._listItemCache, null);
4901 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
4903 StringBuilder mk = new StringBuilder();
4904 //if (Post.IsDeleted) mk.Append("×");
4905 //if (Post.IsMark) mk.Append("♪");
4906 //if (Post.IsProtect) mk.Append("Ю");
4907 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4908 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4909 ImageListViewItem itm;
4910 if (Post.RetweetedId == null)
4912 string[] sitem= {"",
4914 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
4915 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
4920 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4924 string[] sitem = {"",
4926 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
4927 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
4928 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4932 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4934 itm.StateIndex = Post.StateIndex;
4936 bool read = Post.IsRead;
4937 //未読管理していなかったら既読として扱う
4938 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
4939 ChangeItemStyleRead(read, itm, Post, null);
4940 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
4945 /// 全てのタブの振り分けルールを反映し直します
4947 private void ApplyPostFilters()
4949 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4951 this.PurgeListViewItemCache();
4952 this._curPost = null;
4953 this._curItemIndex = -1;
4954 this._statuses.FilterAll();
4956 foreach (TabPage tabPage in this.ListTab.TabPages)
4958 var tab = this._statuses.Tabs[tabPage.Text];
4960 var listview = (DetailsListView)tabPage.Tag;
4961 using (ControlTransaction.Update(listview))
4963 listview.VirtualListSize = tab.AllCount;
4966 if (this._cfgCommon.TabIconDisp)
4968 if (tab.UnreadCount > 0)
4969 tabPage.ImageIndex = 0;
4971 tabPage.ImageIndex = -1;
4975 if (!this._cfgCommon.TabIconDisp)
4976 this.ListTab.Refresh();
4978 SetMainWindowTitle();
4979 SetStatusLabelUrl();
4983 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4985 e.DrawDefault = true;
4988 private void MyList_HScrolled(object sender, EventArgs e)
4990 DetailsListView listView = (DetailsListView)sender;
4994 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
4996 if (e.State == 0) return;
4997 e.DrawDefault = false;
4999 SolidBrush brs2 = null;
5000 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5002 if (e.Item.BackColor == _clSelf)
5003 brs2 = _brsBackColorMine;
5004 else if (e.Item.BackColor == _clAtSelf)
5005 brs2 = _brsBackColorAt;
5006 else if (e.Item.BackColor == _clTarget)
5007 brs2 = _brsBackColorYou;
5008 else if (e.Item.BackColor == _clAtTarget)
5009 brs2 = _brsBackColorAtYou;
5010 else if (e.Item.BackColor == _clAtFromTarget)
5011 brs2 = _brsBackColorAtFromTarget;
5012 else if (e.Item.BackColor == _clAtTo)
5013 brs2 = _brsBackColorAtTo;
5015 brs2 = _brsBackColorNone;
5020 if (((Control)sender).Focused)
5021 brs2 = _brsHighLight;
5023 brs2 = _brsDeactiveSelection;
5025 e.Graphics.FillRectangle(brs2, e.Bounds);
5026 e.DrawFocusRectangle();
5027 this.DrawListViewItemIcon(e);
5030 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5032 if (e.ItemState == 0) return;
5034 if (e.ColumnIndex > 0)
5037 RectangleF rct = e.Bounds;
5038 rct.Width = e.Header.Width;
5039 int fontHeight = e.Item.Font.Height;
5042 rct.Y += fontHeight;
5043 rct.Height -= fontHeight;
5047 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5049 //if (heightDiff > fontHeight * 0.7)
5051 // rct.Height += fontHeight;
5052 // drawLineCount += 1;
5055 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5056 if (!_iconCol && drawLineCount <= 1)
5058 //rct.Inflate(0, heightDiff / -2);
5059 //rct.Height += fontHeight / 2;
5061 else if (heightDiff < fontHeight * 0.7)
5063 //最終行が70%以上欠けていたら、最終行は表示しない
5064 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5065 rct.Height = (fontHeight * drawLineCount) - 1;
5072 //if (!_iconCol && drawLineCount > 1)
5074 // rct.Y += fontHeight * 0.2;
5075 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5080 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5081 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5086 Rectangle rctB = e.Bounds;
5087 rctB.Width = e.Header.Width;
5088 rctB.Height = fontHeight;
5090 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5092 TextRenderer.DrawText(e.Graphics,
5093 e.Item.SubItems[2].Text,
5095 Rectangle.Round(rct),
5097 TextFormatFlags.WordBreak |
5098 TextFormatFlags.EndEllipsis |
5099 TextFormatFlags.GlyphOverhangPadding |
5100 TextFormatFlags.NoPrefix);
5101 TextRenderer.DrawText(e.Graphics,
5102 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 + "]",
5106 TextFormatFlags.SingleLine |
5107 TextFormatFlags.EndEllipsis |
5108 TextFormatFlags.GlyphOverhangPadding |
5109 TextFormatFlags.NoPrefix);
5112 else if (drawLineCount == 1)
5114 TextRenderer.DrawText(e.Graphics,
5117 Rectangle.Round(rct),
5119 TextFormatFlags.SingleLine |
5120 TextFormatFlags.EndEllipsis |
5121 TextFormatFlags.GlyphOverhangPadding |
5122 TextFormatFlags.NoPrefix |
5123 TextFormatFlags.VerticalCenter);
5127 TextRenderer.DrawText(e.Graphics,
5130 Rectangle.Round(rct),
5132 TextFormatFlags.WordBreak |
5133 TextFormatFlags.EndEllipsis |
5134 TextFormatFlags.GlyphOverhangPadding |
5135 TextFormatFlags.NoPrefix);
5137 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5142 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5144 if (_iconSz == 0) return;
5146 ImageListViewItem item = (ImageListViewItem)e.Item;
5148 //e.Bounds.Leftが常に0を指すから自前で計算
5149 Rectangle itemRect = item.Bounds;
5150 var col0 = e.Item.ListView.Columns[0];
5151 itemRect.Width = col0.Width;
5153 if (col0.DisplayIndex > 0)
5155 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5157 if (clm.DisplayIndex < col0.DisplayIndex)
5158 itemRect.X += clm.Width;
5162 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5163 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5164 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5167 var img = item.Image;
5170 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5171 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5173 if (iconRect.Width > 0)
5175 e.Graphics.FillRectangle(Brushes.White, iconRect);
5176 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5179 e.Graphics.DrawImage(img.Image, iconRect);
5181 catch (ArgumentException)
5183 item.RefreshImageAsync();
5189 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5190 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5192 item.GetImageAsync();
5195 if (item.StateIndex > -1)
5197 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5198 if (stateRect.Width > 0)
5200 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5201 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5202 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5207 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5209 base.ScaleControl(factor, specified);
5211 ScaleChildControl(this.TabImage, factor);
5213 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5214 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5216 foreach (var listview in listviews)
5218 ScaleChildControl(listview, factor);
5222 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5224 // ImageListViewItem item = (ImageListViewItem)e.Item;
5225 // if (item.StateImageIndex > -1)
5227 // ////e.Bounds.Leftが常に0を指すから自前で計算
5228 // //Rectangle itemRect = item.Bounds;
5229 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5231 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5233 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5235 // // itemRect.X += clm.Width;
5239 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5240 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5242 // if (rct.Width > 0)
5244 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5245 // //e.Graphics.FillRectangle(Brushes.White, rct);
5246 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5247 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5252 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5254 var tab = this._statuses.Tabs[this._curTab.Text];
5256 if (tab.AllCount == 0)
5258 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5262 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5267 case SEARCHTYPE.NextSearch: // 次を検索
5268 if (selectedIndex != -1)
5269 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5273 case SEARCHTYPE.PrevSearch: // 前を検索
5274 if (selectedIndex != -1)
5275 startIndex = Math.Max(selectedIndex - 1, 0);
5277 startIndex = tab.AllCount - 1;
5279 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5281 if (selectedIndex != -1)
5282 startIndex = selectedIndex;
5288 Func<string, bool> stringComparer;
5291 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5293 catch (ArgumentException)
5295 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5299 var reverse = searchType == SEARCHTYPE.PrevSearch;
5300 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5301 .DefaultIfEmpty(-1).First();
5303 if (foundIndex == -1)
5305 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5309 this.SelectListItem(this._curList, foundIndex);
5310 this._curList.EnsureVisible(foundIndex);
5313 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5316 this.ShowSearchDialog();
5319 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5321 var previousSearch = this.SearchDialog.ResultOptions;
5322 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5324 this.SearchDialog.Reset();
5325 this.ShowSearchDialog();
5331 previousSearch.Query,
5332 previousSearch.CaseSensitive,
5333 previousSearch.UseRegex,
5334 SEARCHTYPE.NextSearch);
5337 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5339 var previousSearch = this.SearchDialog.ResultOptions;
5340 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5342 this.SearchDialog.Reset();
5343 this.ShowSearchDialog();
5349 previousSearch.Query,
5350 previousSearch.CaseSensitive,
5351 previousSearch.UseRegex,
5352 SEARCHTYPE.PrevSearch);
5356 /// 検索ダイアログを表示し、検索を実行します
5358 private void ShowSearchDialog()
5360 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5362 this.TopMost = this._cfgCommon.AlwaysTop;
5365 this.TopMost = this._cfgCommon.AlwaysTop;
5367 var searchOptions = this.SearchDialog.ResultOptions;
5368 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5370 if (searchOptions.NewTab)
5372 var tabName = Properties.Resources.SearchResults_TabName;
5376 tabName = this._statuses.MakeTabName(tabName);
5378 catch (TabException ex)
5380 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5383 var resultTab = new LocalSearchTabModel(tabName);
5384 this.AddNewTab(resultTab, startup: false);
5385 this._statuses.AddTab(resultTab);
5387 var targetTab = this._statuses.Tabs[this._curTab.Text];
5389 Func<string, bool> stringComparer;
5392 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5394 catch (ArgumentException)
5396 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5400 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5401 if (foundIndices.Length == 0)
5403 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5407 var foundPosts = foundIndices.Select(x => targetTab[x]);
5408 foreach (var post in foundPosts)
5410 resultTab.AddPostQueue(post);
5413 this._statuses.DistributePosts();
5414 this.RefreshTimeline();
5416 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5417 .First(x => x.Text == tabName);
5419 this.ListTab.SelectedTab = tabPage;
5424 searchOptions.Query,
5425 searchOptions.CaseSensitive,
5426 searchOptions.UseRegex,
5427 SEARCHTYPE.DialogSearch);
5430 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5432 this.AddNewTabForSearch(searchOptions.Query);
5436 /// <summary>発言検索に使用するメソッドを生成します</summary>
5437 /// <exception cref="ArgumentException">
5438 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5440 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5444 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5445 var regex = new Regex(query, regexOption);
5447 return x => regex.IsMatch(x);
5451 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5453 return x => x.IndexOf(query, comparisonType) != -1;
5457 private void AboutMenuItem_Click(object sender, EventArgs e)
5459 using (TweenAboutBox about = new TweenAboutBox())
5461 about.ShowDialog(this);
5463 this.TopMost = this._cfgCommon.AlwaysTop;
5466 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5468 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5470 DetailsListView lst = null;
5472 if (ImageSelector.Enabled)
5476 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5479 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5482 ListTab.SelectedIndex = i;
5483 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5484 //_curTab = ListTab.TabPages[i];
5489 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5490 if (idx == -1 && bgnIdx > 0)
5492 for (int i = 0; i < bgnIdx; i++)
5494 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5497 ListTab.SelectedIndex = i;
5498 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5499 //_curTab = ListTab.TabPages[i];
5505 //全部調べたが未読見つからず→先頭タブの最新発言へ
5508 ListTab.SelectedIndex = 0;
5509 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5510 //_curTab = ListTab.TabPages[0];
5511 if (_statuses.SortOrder == SortOrder.Ascending)
5512 idx = lst.VirtualListSize - 1;
5517 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5519 SelectListItem(lst, idx);
5520 if (_statuses.SortMode == ComparerMode.Id)
5522 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5523 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5529 lst.EnsureVisible(idx);
5534 lst.EnsureVisible(idx);
5540 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5542 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5544 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5545 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5549 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5551 if (_curList.SelectedIndices.Count > 0)
5553 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5554 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5558 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5560 await this.CheckNewVersion(false);
5563 private void RunTweenUp()
5565 ProcessStartInfo pinfo = new ProcessStartInfo();
5566 pinfo.UseShellExecute = true;
5567 pinfo.WorkingDirectory = MyCommon.settingPath;
5568 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5569 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5572 Process.Start(pinfo);
5576 MessageBox.Show("Failed to execute TweenUp3.exe.");
5580 public class VersionInfo
5582 public Version Version { get; set; }
5583 public Uri DownloadUri { get; set; }
5584 public string ReleaseNote { get; set; }
5588 /// OpenTween の最新バージョンの情報を取得します
5590 public async Task<VersionInfo> GetVersionInfoAsync()
5592 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5593 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5595 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5596 .ConfigureAwait(false);
5598 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5599 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5601 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5602 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5604 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5606 return new VersionInfo
5608 Version = Version.Parse(msgHeader[0]),
5609 DownloadUri = new Uri(msgHeader[1]),
5610 ReleaseNote = msgBody,
5614 private async Task CheckNewVersion(bool startup = false)
5616 if (ApplicationSettings.VersionInfoUrl == null)
5617 return; // 更新チェック無効化
5621 var versionInfo = await this.GetVersionInfoAsync();
5623 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5628 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5629 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5630 msgtext = MyCommon.ReplaceAppName(msgtext);
5632 MessageBox.Show(msgtext,
5633 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5634 MessageBoxButtons.OK, MessageBoxIcon.Information);
5639 using (var dialog = new UpdateDialog())
5641 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5642 MyCommon.GetReadableVersion(versionInfo.Version));
5643 dialog.DetailsText = versionInfo.ReleaseNote;
5645 if (dialog.ShowDialog(this) == DialogResult.Yes)
5647 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5653 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5656 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5657 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5658 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5663 private async Task Colorize()
5666 await this.DispSelectedPost();
5667 //件数関連の場合、タイトル即時書き換え
5668 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
5669 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5670 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5671 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5673 SetMainWindowTitle();
5675 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
5676 foreach (TabPage tb in ListTab.TabPages)
5678 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5680 if (this._cfgCommon.TabIconDisp)
5682 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5686 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
5689 public string createDetailHtml(string orgdata)
5691 if (this._cfgLocal.UseTwemoji)
5692 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5694 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5697 private Task DispSelectedPost()
5699 return this.DispSelectedPost(false);
5702 private PostClass displayPost = new PostClass();
5705 /// サムネイル表示に使用する CancellationToken の生成元
5707 private CancellationTokenSource thumbnailTokenSource = null;
5709 private async Task DispSelectedPost(bool forceupdate)
5711 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5714 var oldDisplayPost = this.displayPost;
5715 this.displayPost = this._curPost;
5717 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5720 var loadTasks = new List<Task>
5722 this.tweetDetailsView.ShowPostDetails(this._curPost),
5725 this.SplitContainer3.Panel2Collapsed = true;
5727 if (this._cfgCommon.PreviewEnable)
5729 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5730 oldTokenSource?.Cancel();
5732 var token = this.thumbnailTokenSource.Token;
5733 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5738 await Task.WhenAll(loadTasks);
5740 catch (OperationCanceledException) { }
5743 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5745 await this.OpenApplicationWebsite();
5748 private async Task OpenApplicationWebsite()
5750 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5753 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5755 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5758 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5760 if (ListTab.SelectedTab != null)
5762 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
5764 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
5765 if (pnl.Controls["comboSearch"].Focused ||
5766 pnl.Controls["comboLang"].Focused ||
5767 pnl.Controls["buttonSearch"].Focused) return;
5770 if (e.Control || e.Shift || e.Alt)
5771 this._anchorFlag = false;
5774 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
5777 e.SuppressKeyPress = true;
5780 if (asyncTask != null)
5785 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
5787 private void InitializeShortcuts()
5789 this.shortcutCommands = new[]
5791 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5792 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5793 .FocusedOn(FocusedControl.ListTab)
5794 .Do(() => SendKeys.Send("{DOWN}")),
5796 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5797 .FocusedOn(FocusedControl.ListTab)
5798 .Do(() => SendKeys.Send("{UP}")),
5800 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5801 .FocusedOn(FocusedControl.ListTab)
5802 .Do(() => SendKeys.Send("{PGDN}")),
5804 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5805 .FocusedOn(FocusedControl.ListTab)
5806 .Do(() => SendKeys.Send("{PGUP}")),
5808 ShortcutCommand.Create(Keys.F1)
5809 .Do(() => this.OpenApplicationWebsite()),
5811 ShortcutCommand.Create(Keys.F3)
5812 .Do(() => this.MenuItemSearchNext_Click(null, null)),
5814 ShortcutCommand.Create(Keys.F5)
5815 .Do(() => this.DoRefresh()),
5817 ShortcutCommand.Create(Keys.F6)
5818 .Do(() => this.GetReplyAsync()),
5820 ShortcutCommand.Create(Keys.F7)
5821 .Do(() => this.GetDirectMessagesAsync()),
5823 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5824 .NotFocusedOn(FocusedControl.StatusText)
5825 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5827 ShortcutCommand.Create(Keys.G)
5828 .NotFocusedOn(FocusedControl.StatusText)
5829 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5831 ShortcutCommand.Create(Keys.Right, Keys.N)
5832 .FocusedOn(FocusedControl.ListTab)
5833 .Do(() => this.GoRelPost(forward: true)),
5835 ShortcutCommand.Create(Keys.Left, Keys.P)
5836 .FocusedOn(FocusedControl.ListTab)
5837 .Do(() => this.GoRelPost(forward: false)),
5839 ShortcutCommand.Create(Keys.OemPeriod)
5840 .FocusedOn(FocusedControl.ListTab)
5841 .Do(() => this.GoAnchor()),
5843 ShortcutCommand.Create(Keys.I)
5844 .FocusedOn(FocusedControl.ListTab)
5845 .OnlyWhen(() => this.StatusText.Enabled)
5846 .Do(() => this.StatusText.Focus()),
5848 ShortcutCommand.Create(Keys.Enter)
5849 .FocusedOn(FocusedControl.ListTab)
5850 .Do(() => this.MakeReplyOrDirectStatus()),
5852 ShortcutCommand.Create(Keys.R)
5853 .FocusedOn(FocusedControl.ListTab)
5854 .Do(() => this.DoRefresh()),
5856 ShortcutCommand.Create(Keys.L)
5857 .FocusedOn(FocusedControl.ListTab)
5858 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5860 ShortcutCommand.Create(Keys.H)
5861 .FocusedOn(FocusedControl.ListTab)
5862 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5864 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5865 .FocusedOn(FocusedControl.ListTab)
5866 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5868 ShortcutCommand.Create(Keys.S)
5869 .FocusedOn(FocusedControl.ListTab)
5870 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5872 ShortcutCommand.Create(Keys.A)
5873 .FocusedOn(FocusedControl.ListTab)
5874 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5876 // ] in_reply_to参照元へ戻る
5877 ShortcutCommand.Create(Keys.Oem4)
5878 .FocusedOn(FocusedControl.ListTab)
5879 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5881 // [ in_reply_toへジャンプ
5882 ShortcutCommand.Create(Keys.Oem6)
5883 .FocusedOn(FocusedControl.ListTab)
5884 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5886 ShortcutCommand.Create(Keys.Escape)
5887 .FocusedOn(FocusedControl.ListTab)
5889 this._anchorFlag = false;
5890 if (ListTab.SelectedTab != null)
5892 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
5893 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5895 var relTp = ListTab.SelectedTab;
5896 RemoveSpecifiedTab(relTp.Text, false);
5902 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5903 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5904 .FocusedOn(FocusedControl.ListTab)
5905 .Do(() => this._anchorFlag = false, preventDefault: false),
5907 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5908 ShortcutCommand.Create(Keys.Up, Keys.Down)
5909 .FocusedOn(FocusedControl.PostBrowser)
5912 ShortcutCommand.Create(Keys.Control | Keys.R)
5913 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5915 ShortcutCommand.Create(Keys.Control | Keys.D)
5916 .Do(() => this.doStatusDelete()),
5918 ShortcutCommand.Create(Keys.Control | Keys.M)
5919 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5921 ShortcutCommand.Create(Keys.Control | Keys.S)
5922 .Do(() => this.FavoriteChange(FavAdd: true)),
5924 ShortcutCommand.Create(Keys.Control | Keys.I)
5925 .Do(() => this.doRepliedStatusOpen()),
5927 ShortcutCommand.Create(Keys.Control | Keys.Q)
5928 .Do(() => this.doQuoteOfficial()),
5930 ShortcutCommand.Create(Keys.Control | Keys.B)
5931 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5933 ShortcutCommand.Create(Keys.Control | Keys.T)
5934 .Do(() => this.HashManageMenuItem_Click(null, null)),
5936 ShortcutCommand.Create(Keys.Control | Keys.L)
5937 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5939 ShortcutCommand.Create(Keys.Control | Keys.Y)
5940 .NotFocusedOn(FocusedControl.PostBrowser)
5941 .Do(() => this.MultiLineMenuItem_Click(null, null)),
5943 ShortcutCommand.Create(Keys.Control | Keys.F)
5944 .Do(() => this.MenuItemSubSearch_Click(null, null)),
5946 ShortcutCommand.Create(Keys.Control | Keys.U)
5947 .Do(() => this.ShowUserTimeline()),
5949 ShortcutCommand.Create(Keys.Control | Keys.H)
5950 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5952 ShortcutCommand.Create(Keys.Control | Keys.G)
5953 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
5955 ShortcutCommand.Create(Keys.Control | Keys.O)
5956 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
5958 ShortcutCommand.Create(Keys.Control | Keys.E)
5959 .Do(() => this.OpenURLMenuItem_Click(null, null)),
5961 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5962 .FocusedOn(FocusedControl.ListTab)
5963 .Do(() => this._colorize = true, preventDefault: false),
5965 ShortcutCommand.Create(Keys.Control | Keys.N)
5966 .FocusedOn(FocusedControl.ListTab)
5967 .Do(() => this.GoNextTab(forward: true)),
5969 ShortcutCommand.Create(Keys.Control | Keys.P)
5970 .FocusedOn(FocusedControl.ListTab)
5971 .Do(() => this.GoNextTab(forward: false)),
5973 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
5974 .FocusedOn(FocusedControl.ListTab)
5975 .Do(() => this.CopyStot()),
5977 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
5978 ShortcutCommand.Create(Keys.Control | Keys.D1)
5979 .FocusedOn(FocusedControl.ListTab)
5980 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
5981 .Do(() => this.ListTab.SelectedIndex = 0),
5983 ShortcutCommand.Create(Keys.Control | Keys.D2)
5984 .FocusedOn(FocusedControl.ListTab)
5985 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
5986 .Do(() => this.ListTab.SelectedIndex = 1),
5988 ShortcutCommand.Create(Keys.Control | Keys.D3)
5989 .FocusedOn(FocusedControl.ListTab)
5990 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
5991 .Do(() => this.ListTab.SelectedIndex = 2),
5993 ShortcutCommand.Create(Keys.Control | Keys.D4)
5994 .FocusedOn(FocusedControl.ListTab)
5995 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
5996 .Do(() => this.ListTab.SelectedIndex = 3),
5998 ShortcutCommand.Create(Keys.Control | Keys.D5)
5999 .FocusedOn(FocusedControl.ListTab)
6000 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6001 .Do(() => this.ListTab.SelectedIndex = 4),
6003 ShortcutCommand.Create(Keys.Control | Keys.D6)
6004 .FocusedOn(FocusedControl.ListTab)
6005 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6006 .Do(() => this.ListTab.SelectedIndex = 5),
6008 ShortcutCommand.Create(Keys.Control | Keys.D7)
6009 .FocusedOn(FocusedControl.ListTab)
6010 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6011 .Do(() => this.ListTab.SelectedIndex = 6),
6013 ShortcutCommand.Create(Keys.Control | Keys.D8)
6014 .FocusedOn(FocusedControl.ListTab)
6015 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6016 .Do(() => this.ListTab.SelectedIndex = 7),
6018 ShortcutCommand.Create(Keys.Control | Keys.D9)
6019 .FocusedOn(FocusedControl.ListTab)
6020 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6022 ShortcutCommand.Create(Keys.Control | Keys.A)
6023 .FocusedOn(FocusedControl.StatusText)
6024 .Do(() => this.StatusText.SelectAll()),
6026 ShortcutCommand.Create(Keys.Control | Keys.V)
6027 .FocusedOn(FocusedControl.StatusText)
6028 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6030 ShortcutCommand.Create(Keys.Control | Keys.Up)
6031 .FocusedOn(FocusedControl.StatusText)
6033 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6035 var inReplyToStatusId = this.inReplyTo?.Item1;
6036 var inReplyToScreenName = this.inReplyTo?.Item2;
6037 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6040 if (_hisIdx < 0) _hisIdx = 0;
6042 var historyItem = this._history[this._hisIdx];
6043 StatusText.Text = historyItem.status;
6044 StatusText.SelectionStart = StatusText.Text.Length;
6045 if (historyItem.inReplyToId != null)
6046 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6048 this.inReplyTo = null;
6051 ShortcutCommand.Create(Keys.Control | Keys.Down)
6052 .FocusedOn(FocusedControl.StatusText)
6054 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6056 var inReplyToStatusId = this.inReplyTo?.Item1;
6057 var inReplyToScreenName = this.inReplyTo?.Item2;
6058 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6061 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6063 var historyItem = this._history[this._hisIdx];
6064 StatusText.Text = historyItem.status;
6065 StatusText.SelectionStart = StatusText.Text.Length;
6066 if (historyItem.inReplyToId != null)
6067 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6069 this.inReplyTo = null;
6072 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6073 .FocusedOn(FocusedControl.StatusText)
6075 if (ListTab.SelectedIndex == 0)
6077 ListTab.SelectedIndex = ListTab.TabCount - 1;
6081 ListTab.SelectedIndex -= 1;
6086 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6087 .FocusedOn(FocusedControl.StatusText)
6089 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6091 ListTab.SelectedIndex = 0;
6095 ListTab.SelectedIndex += 1;
6100 ShortcutCommand.Create(Keys.Control | Keys.Y)
6101 .FocusedOn(FocusedControl.PostBrowser)
6103 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6104 MultiLineMenuItem_Click(null, null);
6107 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6108 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6110 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6111 .Do(() => this.DoRefreshMore()),
6113 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6114 .Do(() => this.GetReplyAsync(loadMore: true)),
6116 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6117 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6119 ShortcutCommand.Create(Keys.Shift | Keys.R)
6120 .NotFocusedOn(FocusedControl.StatusText)
6121 .Do(() => this.DoRefreshMore()),
6123 ShortcutCommand.Create(Keys.Shift | Keys.H)
6124 .FocusedOn(FocusedControl.ListTab)
6125 .Do(() => this.GoTopEnd(GoTop: true)),
6127 ShortcutCommand.Create(Keys.Shift | Keys.L)
6128 .FocusedOn(FocusedControl.ListTab)
6129 .Do(() => this.GoTopEnd(GoTop: false)),
6131 ShortcutCommand.Create(Keys.Shift | Keys.M)
6132 .FocusedOn(FocusedControl.ListTab)
6133 .Do(() => this.GoMiddle()),
6135 ShortcutCommand.Create(Keys.Shift | Keys.G)
6136 .FocusedOn(FocusedControl.ListTab)
6137 .Do(() => this.GoLast()),
6139 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6140 .FocusedOn(FocusedControl.ListTab)
6141 .Do(() => this.MoveMiddle()),
6143 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6144 .FocusedOn(FocusedControl.ListTab)
6145 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6147 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6148 .FocusedOn(FocusedControl.ListTab)
6149 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6151 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6152 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6153 .FocusedOn(FocusedControl.ListTab)
6154 .Do(() => this.GoFav(forward: true)),
6156 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6157 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6158 .FocusedOn(FocusedControl.ListTab)
6159 .Do(() => this.GoFav(forward: false)),
6161 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6162 .FocusedOn(FocusedControl.ListTab)
6163 .Do(() => this.GoBackSelectPostChain()),
6165 ShortcutCommand.Create(Keys.Alt | Keys.R)
6166 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6168 ShortcutCommand.Create(Keys.Alt | Keys.P)
6169 .OnlyWhen(() => this._curPost != null)
6170 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6172 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6173 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6175 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6176 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6178 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6179 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6181 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6182 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6184 // 別タブの同じ書き込みへ(ALT+←/→)
6185 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6186 .FocusedOn(FocusedControl.ListTab)
6187 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6189 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6190 .FocusedOn(FocusedControl.ListTab)
6191 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6193 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6194 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6196 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6197 .Do(() => this.CopyIdUri()),
6199 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6200 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6201 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6202 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6204 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6205 .Do(() => this.FavoriteChange(FavAdd: false)),
6207 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6208 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6210 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6211 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6213 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6214 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6216 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6217 .Do(() => this.doMoveToRTHome()),
6219 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6220 .Do(() => this.FavorareMenuItem_Click(null, null)),
6222 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6223 .FocusedOn(FocusedControl.StatusText)
6225 if (_curList != null && _curList.VirtualListSize != 0 &&
6226 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6228 var idx = _curList.SelectedIndices[0] - 1;
6229 SelectListItem(_curList, idx);
6230 _curList.EnsureVisible(idx);
6234 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6235 .FocusedOn(FocusedControl.StatusText)
6237 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6238 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6240 var idx = _curList.SelectedIndices[0] + 1;
6241 SelectListItem(_curList, idx);
6242 _curList.EnsureVisible(idx);
6246 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6247 .FocusedOn(FocusedControl.StatusText)
6249 if (StatusText.SelectionStart > 0)
6251 int endidx = StatusText.SelectionStart - 1;
6252 string startstr = "";
6253 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6255 char c = StatusText.Text[i];
6256 if (Char.IsLetterOrDigit(c) || c == '_')
6262 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6263 int cnt = AtIdSupl.ItemCount;
6264 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6265 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6269 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6270 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6280 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6281 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6282 .FocusedOn(FocusedControl.ListTab)
6283 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6285 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6286 .FocusedOn(FocusedControl.ListTab)
6287 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6289 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6290 .FocusedOn(FocusedControl.ListTab)
6291 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6293 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6294 .FocusedOn(FocusedControl.ListTab)
6295 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6297 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6298 .FocusedOn(FocusedControl.ListTab)
6299 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6301 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6302 .FocusedOn(FocusedControl.ListTab)
6303 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6305 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6306 .FocusedOn(FocusedControl.ListTab)
6307 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6309 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6310 .FocusedOn(FocusedControl.ListTab)
6311 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6313 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6314 .FocusedOn(FocusedControl.ListTab)
6315 .Do(() => this.SetSortLastColumn()),
6317 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6318 .Do(() => this.FavoritesRetweetOfficial()),
6320 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6321 .Do(() => this.FavoritesRetweetUnofficial()),
6323 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6324 .Do(() => this.OpenUserAppointUrl()),
6326 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6327 .FocusedOn(FocusedControl.PostBrowser)
6328 .Do(() => this.doReTweetUnofficial()),
6330 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6331 .OnlyWhen(() => this.ExistCurrentPost)
6332 .Do(() => this.tweetDetailsView.DoTranslation()),
6334 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6335 .Do(() => this.doReTweetUnofficial()),
6337 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6338 .Do(() => this.CopyUserId()),
6340 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6341 .Do(() => this.tweetThumbnail1.ScrollUp()),
6343 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6344 .Do(() => this.tweetThumbnail1.ScrollDown()),
6346 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6347 .FocusedOn(FocusedControl.ListTab)
6348 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6349 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6353 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6355 // Task を返す非同期処理があれば asyncTask に代入する
6358 // ShortcutCommand に対応しているコマンドはここで処理される
6359 foreach (var command in this.shortcutCommands)
6361 if (command.IsMatch(keyData, focusedOn))
6363 asyncTask = command.RunCommand();
6364 return command.PreventDefault;
6371 private void GoNextTab(bool forward)
6373 int idx = ListTab.SelectedIndex;
6377 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6382 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6384 ListTab.SelectedIndex = idx;
6387 private void CopyStot()
6390 StringBuilder sb = new StringBuilder();
6391 bool IsProtected = false;
6393 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6394 foreach (int idx in _curList.SelectedIndices)
6396 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6402 if (post.IsDeleted) continue;
6405 if (post.RetweetedId != null)
6406 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6408 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6412 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6417 MessageBox.Show(Properties.Resources.CopyStotText1);
6421 clstr = sb.ToString();
6424 Clipboard.SetDataObject(clstr, false, 5, 100);
6426 catch (Exception ex)
6428 MessageBox.Show(ex.Message);
6433 private void CopyIdUri()
6436 StringBuilder sb = new StringBuilder();
6437 if (this._curTab == null) return;
6438 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
6439 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
6440 foreach (int idx in _curList.SelectedIndices)
6442 var post = _statuses.Tabs[_curTab.Text][idx];
6443 sb.Append(MyCommon.GetStatusUrl(post));
6444 sb.Append(Environment.NewLine);
6448 clstr = sb.ToString();
6451 Clipboard.SetDataObject(clstr, false, 5, 100);
6453 catch (Exception ex)
6455 MessageBox.Show(ex.Message);
6460 private void GoFav(bool forward)
6462 if (_curList.VirtualListSize == 0) return;
6469 if (_curList.SelectedIndices.Count == 0)
6475 fIdx = _curList.SelectedIndices[0] + 1;
6476 if (fIdx > _curList.VirtualListSize - 1) return;
6478 toIdx = _curList.VirtualListSize;
6483 if (_curList.SelectedIndices.Count == 0)
6485 fIdx = _curList.VirtualListSize - 1;
6489 fIdx = _curList.SelectedIndices[0] - 1;
6490 if (fIdx < 0) return;
6496 for (int idx = fIdx; idx != toIdx; idx += stp)
6498 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6500 SelectListItem(_curList, idx);
6501 _curList.EnsureVisible(idx);
6507 private void GoSamePostToAnotherTab(bool left)
6509 if (_curList.VirtualListSize == 0) return;
6515 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
6516 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
6518 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
6523 if (ListTab.SelectedIndex == 0)
6529 fIdx = ListTab.SelectedIndex - 1;
6537 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6543 fIdx = ListTab.SelectedIndex + 1;
6545 toIdx = ListTab.TabCount;
6550 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6552 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
6553 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
6555 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
6557 ListTab.SelectedIndex = tabidx;
6558 SelectListItem(_curList, idx);
6559 _curList.EnsureVisible(idx);
6568 private void GoPost(bool forward)
6570 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
6577 fIdx = _curList.SelectedIndices[0] + 1;
6578 if (fIdx > _curList.VirtualListSize - 1) return;
6579 toIdx = _curList.VirtualListSize;
6584 fIdx = _curList.SelectedIndices[0] - 1;
6585 if (fIdx < 0) return;
6591 if (_curPost.RetweetedId == null)
6593 name = _curPost.ScreenName;
6597 name = _curPost.RetweetedBy;
6599 for (int idx = fIdx; idx != toIdx; idx += stp)
6601 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
6603 if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
6605 SelectListItem(_curList, idx);
6606 _curList.EnsureVisible(idx);
6612 if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
6614 SelectListItem(_curList, idx);
6615 _curList.EnsureVisible(idx);
6622 private void GoRelPost(bool forward)
6624 if (_curList.SelectedIndices.Count == 0) return;
6631 fIdx = _curList.SelectedIndices[0] + 1;
6632 if (fIdx > _curList.VirtualListSize - 1) return;
6633 toIdx = _curList.VirtualListSize;
6638 fIdx = _curList.SelectedIndices[0] - 1;
6639 if (fIdx < 0) return;
6646 if (_curPost == null) return;
6647 _anchorPost = _curPost;
6652 if (_anchorPost == null) return;
6655 for (int idx = fIdx; idx != toIdx; idx += stp)
6657 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6658 if (post.ScreenName == _anchorPost.ScreenName ||
6659 post.RetweetedBy == _anchorPost.ScreenName ||
6660 post.ScreenName == _anchorPost.RetweetedBy ||
6661 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6662 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
6663 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
6664 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
6665 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
6667 SelectListItem(_curList, idx);
6668 _curList.EnsureVisible(idx);
6674 private void GoAnchor()
6676 if (_anchorPost == null) return;
6677 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6678 if (idx == -1) return;
6680 SelectListItem(_curList, idx);
6681 _curList.EnsureVisible(idx);
6684 private void GoTopEnd(bool GoTop)
6686 if (_curList.VirtualListSize == 0)
6694 _item = _curList.GetItemAt(0, 25);
6702 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6704 idx = _curList.VirtualListSize - 1;
6708 SelectListItem(_curList, idx);
6711 private void GoMiddle()
6713 if (_curList.VirtualListSize == 0)
6721 _item = _curList.GetItemAt(0, 0);
6731 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6734 idx2 = _curList.VirtualListSize - 1;
6740 idx3 = (idx1 + idx2) / 2;
6742 SelectListItem(_curList, idx3);
6745 private void GoLast()
6747 if (_curList.VirtualListSize == 0) return;
6749 if (_statuses.SortOrder == SortOrder.Ascending)
6751 SelectListItem(_curList, _curList.VirtualListSize - 1);
6752 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6756 SelectListItem(_curList, 0);
6757 _curList.EnsureVisible(0);
6761 private void MoveTop()
6763 if (_curList.SelectedIndices.Count == 0) return;
6764 int idx = _curList.SelectedIndices[0];
6765 if (_statuses.SortOrder == SortOrder.Ascending)
6767 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6771 _curList.EnsureVisible(0);
6773 _curList.EnsureVisible(idx);
6776 private async Task GoInReplyToPostTree()
6778 if (_curPost == null) return;
6780 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6782 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
6786 var post = await tw.GetStatusApi(false, _curPost.StatusId);
6788 _curPost.InReplyToStatusId = post.InReplyToStatusId;
6789 _curPost.InReplyToUser = post.InReplyToUser;
6790 _curPost.IsReply = post.IsReply;
6791 this.PurgeListViewItemCache();
6792 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
6794 catch (WebApiException ex)
6796 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6800 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
6802 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
6804 replyChains = new Stack<ReplyChain>();
6806 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
6809 string inReplyToTabName;
6810 long inReplyToId = _curPost.InReplyToStatusId.Value;
6811 string inReplyToUser = _curPost.InReplyToUser;
6812 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6814 var inReplyToPosts = from tab in _statuses.Tabs.Values
6815 orderby tab != curTabClass
6816 from post in tab.Posts.Values
6817 where post.StatusId == inReplyToId
6818 let index = tab.IndexOf(post.StatusId)
6820 select new {Tab = tab, Index = index};
6822 var inReplyPost = inReplyToPosts.FirstOrDefault();
6823 if (inReplyPost == null)
6827 await Task.Run(async () =>
6829 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
6830 .ConfigureAwait(false);
6833 _statuses.AddPost(post);
6834 _statuses.DistributePosts();
6837 catch (WebApiException ex)
6839 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6840 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6844 this.RefreshTimeline();
6846 inReplyPost = inReplyToPosts.FirstOrDefault();
6847 if (inReplyPost == null)
6849 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6853 inReplyToTabName = inReplyPost.Tab.TabName;
6854 inReplyToIndex = inReplyPost.Index;
6856 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
6857 DetailsListView listView = (DetailsListView)tabPage.Tag;
6859 if (_curTab != tabPage)
6861 this.ListTab.SelectTab(tabPage);
6864 this.SelectListItem(listView, inReplyToIndex);
6865 listView.EnsureVisible(inReplyToIndex);
6868 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6870 if (_curPost == null) return;
6872 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6873 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6877 if (_curPost.InReplyToStatusId != null)
6879 var posts = from t in _statuses.Tabs
6880 from p in t.Value.Posts
6881 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
6882 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6884 orderby isForward ? indexOf : indexOf * -1
6885 orderby t.Value != curTabClass
6886 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
6889 var postList = posts.ToList();
6890 for (int i = postList.Count - 1; i >= 0; i--)
6893 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
6895 postList.RemoveAt(index);
6898 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
6899 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
6900 if (post == null) post = postList.First();
6901 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6902 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6903 SelectListItem(listView, post.Index);
6904 listView.EnsureVisible(post.Index);
6906 catch (InvalidOperationException)
6914 if (replyChains == null || replyChains.Count < 1)
6916 var posts = from t in _statuses.Tabs
6917 from p in t.Value.Posts
6918 where p.Value.InReplyToStatusId == _curPost.StatusId
6919 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6922 orderby t.Value != curTabClass
6923 select new {Tab = t.Value, Index = indexOf};
6926 var post = posts.First();
6927 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6928 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6929 SelectListItem(listView, post.Index);
6930 listView.EnsureVisible(post.Index);
6932 catch (InvalidOperationException)
6939 ReplyChain chainHead = replyChains.Pop();
6940 if (chainHead.InReplyToId == _curPost.StatusId)
6942 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
6951 ListTab.SelectTab(chainHead.OriginalTab);
6957 SelectListItem(_curList, idx);
6958 _curList.EnsureVisible(idx);
6964 this.GoBackInReplyToPostTree(parallel);
6970 private void GoBackSelectPostChain()
6972 if (this.selectPostChains.Count > 1)
6981 this.selectPostChains.Pop();
6982 var tabPostPair = this.selectPostChains.Peek();
6984 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
6986 if (tabPostPair.Item2 != null)
6988 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
6989 if (idx == -1) continue; //該当ポストが存在しないので無視
6992 tp = tabPostPair.Item1;
6994 this.selectPostChains.Pop();
6996 catch (InvalidOperationException)
7002 while (this.selectPostChains.Count > 1);
7007 //履歴が残り1つであればクリアしておく
7008 if (this.selectPostChains.Count == 1)
7009 this.selectPostChains.Clear();
7013 DetailsListView lst = (DetailsListView)tp.Tag;
7014 this.ListTab.SelectedTab = tp;
7017 SelectListItem(lst, idx);
7018 lst.EnsureVisible(idx);
7024 private void PushSelectPostChain()
7026 int count = this.selectPostChains.Count;
7029 var p = this.selectPostChains.Peek();
7030 if (p.Item1 == this._curTab)
7032 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7033 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7036 if (count >= 2500) TrimPostChain();
7037 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7040 private void TrimPostChain()
7042 if (this.selectPostChains.Count <= 2000) return;
7043 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7044 for (int i = 0; i < 2000; i++)
7046 p.Push(this.selectPostChains.Pop());
7048 this.selectPostChains.Clear();
7049 for (int i = 0; i < 2000; i++)
7051 this.selectPostChains.Push(p.Pop());
7055 private bool GoStatus(long statusId)
7057 if (statusId == 0) return false;
7058 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7060 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7062 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7063 ListTab.SelectedIndex = tabidx;
7064 SelectListItem(_curList, idx);
7065 _curList.EnsureVisible(idx);
7072 private bool GoDirectMessage(long statusId)
7074 if (statusId == 0) return false;
7075 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7077 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7079 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7080 ListTab.SelectedIndex = tabidx;
7081 SelectListItem(_curList, idx);
7082 _curList.EnsureVisible(idx);
7089 private void MyList_MouseClick(object sender, MouseEventArgs e)
7091 _anchorFlag = false;
7094 private void StatusText_Enter(object sender, EventArgs e)
7096 // フォーカスの戻り先を StatusText に設定
7097 this.Tag = StatusText;
7098 StatusText.BackColor = _clInputBackcolor;
7101 public Color InputBackColor
7103 get { return _clInputBackcolor; }
7104 set { _clInputBackcolor = value; }
7107 private void StatusText_Leave(object sender, EventArgs e)
7109 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7110 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7111 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7114 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7117 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7120 e.SuppressKeyPress = true;
7123 this.StatusText_TextChanged(null, null);
7125 if (asyncTask != null)
7129 private void SaveConfigsAll(bool ifModified)
7133 SaveConfigsCommon();
7140 if (ModifySettingCommon) SaveConfigsCommon();
7141 if (ModifySettingLocal) SaveConfigsLocal();
7142 if (ModifySettingAtId) SaveConfigsAtId();
7146 private void SaveConfigsAtId()
7148 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7150 ModifySettingAtId = false;
7151 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7155 private void SaveConfigsCommon()
7157 if (_ignoreConfigSave) return;
7159 ModifySettingCommon = false;
7162 _cfgCommon.UserName = tw.Username;
7163 _cfgCommon.UserId = tw.UserId;
7164 _cfgCommon.Token = tw.AccessToken;
7165 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7167 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7168 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7170 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7173 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7174 switch (_statuses.SortMode)
7176 case ComparerMode.Nickname: //ニックネーム
7177 _cfgCommon.SortColumn = 1;
7179 case ComparerMode.Data: //本文
7180 _cfgCommon.SortColumn = 2;
7182 case ComparerMode.Id: //時刻=発言Id
7183 _cfgCommon.SortColumn = 3;
7185 case ComparerMode.Name: //名前
7186 _cfgCommon.SortColumn = 4;
7188 case ComparerMode.Source: //Source
7189 _cfgCommon.SortColumn = 7;
7193 _cfgCommon.HashTags = HashMgr.HashHistories;
7194 if (HashMgr.IsPermanent)
7196 _cfgCommon.HashSelected = HashMgr.UseHash;
7200 _cfgCommon.HashSelected = "";
7202 _cfgCommon.HashIsHead = HashMgr.IsHead;
7203 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7204 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7205 if (ToolStripFocusLockMenuItem != null &&
7206 ToolStripFocusLockMenuItem.IsDisposed == false)
7208 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7210 _cfgCommon.TrackWord = tw.TrackWord;
7211 _cfgCommon.AllAtReply = tw.AllAtReply;
7212 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7213 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7219 private void SaveConfigsLocal()
7221 if (_ignoreConfigSave) return;
7224 ModifySettingLocal = false;
7225 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7226 _cfgLocal.FormSize = _mySize;
7227 _cfgLocal.FormLocation = _myLoc;
7228 _cfgLocal.SplitterDistance = _mySpDis;
7229 _cfgLocal.PreviewDistance = _mySpDis3;
7230 _cfgLocal.StatusMultiline = StatusText.Multiline;
7231 _cfgLocal.StatusTextHeight = _mySpDis2;
7233 _cfgLocal.FontUnread = _fntUnread;
7234 _cfgLocal.ColorUnread = _clUnread;
7235 _cfgLocal.FontRead = _fntReaded;
7236 _cfgLocal.ColorRead = _clReaded;
7237 _cfgLocal.FontDetail = _fntDetail;
7238 _cfgLocal.ColorDetail = _clDetail;
7239 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7240 _cfgLocal.ColorDetailLink = _clDetailLink;
7241 _cfgLocal.ColorFav = _clFav;
7242 _cfgLocal.ColorOWL = _clOWL;
7243 _cfgLocal.ColorRetweet = _clRetweet;
7244 _cfgLocal.ColorSelf = _clSelf;
7245 _cfgLocal.ColorAtSelf = _clAtSelf;
7246 _cfgLocal.ColorTarget = _clTarget;
7247 _cfgLocal.ColorAtTarget = _clAtTarget;
7248 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7249 _cfgLocal.ColorAtTo = _clAtTo;
7250 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7251 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7252 _cfgLocal.ColorInputFont = _clInputFont;
7253 _cfgLocal.FontInputFont = _fntInputFont;
7255 if (_ignoreConfigSave) return;
7260 private void SaveConfigsTabs()
7262 var tabsSetting = new SettingTabs();
7264 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7265 .Select(x => this._statuses.Tabs[x.Text])
7266 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7268 foreach (var tab in tabs)
7270 if (!tab.IsPermanentTabType)
7273 var tabSetting = new SettingTabs.SettingTabItem
7275 TabName = tab.TabName,
7276 TabType = tab.TabType,
7277 UnreadManage = tab.UnreadManage,
7278 Protected = tab.Protected,
7279 Notify = tab.Notify,
7280 SoundFile = tab.SoundFile,
7283 var filterTab = tab as FilterTabModel;
7284 if (filterTab != null)
7285 tabSetting.FilterArray = filterTab.FilterArray;
7287 var userTab = tab as UserTimelineTabModel;
7288 if (userTab != null)
7289 tabSetting.User = userTab.ScreenName;
7291 var searchTab = tab as PublicSearchTabModel;
7292 if (searchTab != null)
7294 tabSetting.SearchWords = searchTab.SearchWords;
7295 tabSetting.SearchLang = searchTab.SearchLang;
7298 var listTab = tab as ListTimelineTabModel;
7299 if (listTab != null)
7300 tabSetting.ListInfo = listTab.ListInfo;
7302 tabsSetting.Tabs.Add(tabSetting);
7308 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7311 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7312 if (ret != DialogResult.OK)
7315 var match = Twitter.StatusUrlRegex.Match(inputText);
7318 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7319 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7325 var statusId = long.Parse(match.Groups["StatusId"].Value);
7326 await this.OpenRelatedTab(statusId);
7328 catch (TabException ex)
7330 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7334 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7336 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7337 Properties.Resources.SaveLogMenuItem_ClickText2,
7338 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7339 if (rslt == DialogResult.Cancel) return;
7341 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7342 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7343 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7344 SaveFileDialog1.FilterIndex = 0;
7345 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7346 SaveFileDialog1.RestoreDirectory = true;
7348 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7350 if (!SaveFileDialog1.ValidateNames) return;
7351 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7353 if (rslt == DialogResult.Yes)
7356 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7358 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7359 string protect = "";
7360 if (post.IsProtect) protect = "Protect";
7361 sw.WriteLine(post.Nickname + "\t" +
7362 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7363 post.CreatedAt + "\t" +
7364 post.ScreenName + "\t" +
7365 post.StatusId + "\t" +
7366 post.ImageUrl + "\t" +
7367 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7373 foreach (int idx in _curList.SelectedIndices)
7375 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7376 string protect = "";
7377 if (post.IsProtect) protect = "Protect";
7378 sw.WriteLine(post.Nickname + "\t" +
7379 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7380 post.CreatedAt + "\t" +
7381 post.ScreenName + "\t" +
7382 post.StatusId + "\t" +
7383 post.ImageUrl + "\t" +
7384 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7390 this.TopMost = this._cfgCommon.AlwaysTop;
7393 public bool TabRename(ref string tabName)
7396 string newTabText = null;
7397 using (InputTabName inputName = new InputTabName())
7399 inputName.TabName = tabName;
7400 inputName.ShowDialog();
7401 if (inputName.DialogResult == DialogResult.Cancel) return false;
7402 newTabText = inputName.TabName;
7404 this.TopMost = this._cfgCommon.AlwaysTop;
7405 if (!string.IsNullOrEmpty(newTabText))
7408 for (int i = 0; i < ListTab.TabCount; i++)
7410 if (ListTab.TabPages[i].Text == newTabText)
7412 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
7413 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7418 for (int i = 0; i < ListTab.TabCount; i++)
7420 if (ListTab.TabPages[i].Text == tabName)
7422 ListTab.TabPages[i].Text = newTabText;
7426 _statuses.RenameTab(tabName, newTabText);
7428 SaveConfigsCommon();
7430 _rclickTabName = newTabText;
7431 tabName = newTabText;
7440 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7442 if (e.Button == MouseButtons.Middle)
7444 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7446 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7448 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7449 this.SaveConfigsTabs();
7456 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7458 string tn = ListTab.SelectedTab.Text;
7462 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7464 if (this._cfgCommon.TabMouseLock) return;
7465 if (e.Button == MouseButtons.Left)
7467 for (int i = 0; i < ListTab.TabPages.Count; i++)
7469 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7472 _tabMouseDownPoint = e.Location;
7483 private void ListTab_DragEnter(object sender, DragEventArgs e)
7485 if (e.Data.GetDataPresent(typeof(TabPage)))
7486 e.Effect = DragDropEffects.Move;
7488 e.Effect = DragDropEffects.None;
7491 private void ListTab_DragDrop(object sender, DragEventArgs e)
7493 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7498 Point cpos = new Point(e.X, e.Y);
7499 Point spos = ListTab.PointToClient(cpos);
7501 for (i = 0; i < ListTab.TabPages.Count; i++)
7503 Rectangle rect = ListTab.GetTabRect(i);
7504 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7505 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7507 tn = ListTab.TabPages[i].Text;
7508 if (spos.X <= (rect.Left + rect.Right) / 2)
7517 //タブのないところにドロップ->最後尾へ移動
7518 if (string.IsNullOrEmpty(tn))
7520 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7522 i = ListTab.TabPages.Count - 1;
7525 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7526 if (tp.Text == tn) return;
7528 ReOrderTab(tp.Text, tn, bef);
7531 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7533 var baseIndex = this.GetTabPageIndex(baseTabText);
7534 if (baseIndex == -1)
7537 var targetIndex = this.GetTabPageIndex(targetTabText);
7538 if (targetIndex == -1)
7541 using (ControlTransaction.Layout(this.ListTab))
7543 var mTp = this.ListTab.TabPages[targetIndex];
7544 this.ListTab.TabPages.Remove(mTp);
7546 if (targetIndex < baseIndex)
7549 if (isBeforeBaseTab)
7550 ListTab.TabPages.Insert(baseIndex, mTp);
7552 ListTab.TabPages.Insert(baseIndex + 1, mTp);
7558 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7560 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7561 //isReply:true=@,false=DM
7562 if (!StatusText.Enabled) return;
7563 if (_curList == null) return;
7564 if (_curTab == null) return;
7565 if (!this.ExistCurrentPost) return;
7567 // 複数あてリプライはReplyではなく通常ポスト
7568 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7569 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7570 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7572 if (_curList.SelectedIndices.Count > 0)
7575 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7578 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7581 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7582 StatusText.SelectionStart = StatusText.Text.Length;
7584 this.inReplyTo = null;
7587 if (string.IsNullOrEmpty(StatusText.Text))
7591 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7592 StatusText.Text = "@" + _curPost.ScreenName + " ";
7594 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7595 var inReplyToScreenName = this._curPost.ScreenName;
7596 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7604 //1件選んでEnter or DoubleClick
7605 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7607 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7610 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7611 var inReplyToScreenName = this._curPost.ScreenName;
7612 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7616 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7619 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7622 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7623 this.inReplyTo = null;
7628 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7629 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7630 var inReplyToScreenName = this._curPost.ScreenName;
7631 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7638 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7639 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7640 this.inReplyTo = null;
7645 //1件選んでCtrl-Rの場合(返信先操作せず)
7646 int sidx = StatusText.SelectionStart;
7647 string id = "@" + _curPost.ScreenName + " ";
7650 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7655 StatusText.Text = StatusText.Text.Insert(sidx, id);
7657 //if (StatusText.Text.StartsWith("@"))
7660 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7661 // sidx += 5 + _curPost.ScreenName.Length;
7666 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7667 // sidx += 3 + _curPost.ScreenName.Length;
7669 StatusText.SelectionStart = sidx;
7672 //_reply_to_name = null;
7680 if (!isAuto && !isReply) return;
7682 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7686 //Enter or DoubleClick
7688 string sTxt = StatusText.Text;
7689 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7692 this.inReplyTo = null;
7694 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7696 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7697 if (!sTxt.Contains("@" + post.ScreenName + " "))
7699 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7700 //sTxt = "@" + post.ScreenName + " " + sTxt;
7703 StatusText.Text = sTxt;
7708 if (_curList.SelectedIndices.Count > 1)
7713 int sidx = StatusText.SelectionStart;
7714 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7716 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7717 if (!ids.Contains("@" + post.ScreenName + " ") &&
7718 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7720 ids += "@" + post.ScreenName + " ";
7724 foreach (string nm in post.ReplyToList)
7726 if (!ids.Contains("@" + nm + " ") &&
7727 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7729 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7731 ids += "@" + m.Result("${id}") + " ";
7733 ids += "@" + nm + " ";
7738 if (ids.Length == 0) return;
7739 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7741 StatusText.Text = ". " + StatusText.Text;
7743 this.inReplyTo = null;
7747 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7752 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7754 //if (StatusText.Text.StartsWith("@"))
7756 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7757 // sidx += 2 + ids.Length;
7761 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7762 // sidx += 1 + ids.Length;
7764 StatusText.SelectionStart = sidx;
7770 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7773 int sidx = StatusText.SelectionStart;
7774 PostClass post = _curPost;
7775 if (!ids.Contains("@" + post.ScreenName + " ") &&
7776 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7778 ids += "@" + post.ScreenName + " ";
7780 foreach (string nm in post.ReplyToList)
7782 if (!ids.Contains("@" + nm + " ") &&
7783 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7785 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7787 ids += "@" + m.Result("${id}") + " ";
7789 ids += "@" + nm + " ";
7792 if (!string.IsNullOrEmpty(post.RetweetedBy))
7794 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
7795 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7797 ids += "@" + post.RetweetedBy + " ";
7800 if (ids.Length == 0) return;
7801 if (string.IsNullOrEmpty(StatusText.Text))
7804 StatusText.Text = ids;
7805 StatusText.SelectionStart = ids.Length;
7808 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7809 var inReplyToScreenName = this._curPost.ScreenName;
7810 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7816 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7821 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7823 StatusText.SelectionStart = sidx;
7829 StatusText.SelectionStart = StatusText.Text.Length;
7834 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7839 private static int iconCnt = 0;
7840 private static int blinkCnt = 0;
7841 private static bool blink = false;
7842 private static bool idle = false;
7844 private async Task RefreshTasktrayIcon()
7847 await this.Colorize();
7849 if (!TimerRefreshIcon.Enabled) return;
7850 //Static usCheckCnt As int = 0
7852 //Static iconDlListTopItem As ListViewItem = null
7854 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7855 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7857 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7859 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7865 //if (usCheckCnt > 300) //1min
7868 // if (!this.IsReceivedUserStream)
7870 // TraceOut("ReconnectUserStream");
7871 // tw.ReconnectUserStream();
7875 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7877 if (iconCnt >= this.NIconRefresh.Length)
7885 SaveConfigsAll(true);
7890 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7892 _myStatusError = false;
7896 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
7897 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
7899 if (blinkCnt > 0) return;
7901 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
7903 NotifyIcon1.Icon = ReplyIcon;
7907 NotifyIcon1.Icon = ReplyIconBlink;
7915 //優先度:エラー→オフライン→アイドル
7919 NotifyIcon1.Icon = NIconAtRed;
7922 if (_myStatusOnline)
7924 NotifyIcon1.Icon = NIconAt;
7928 NotifyIcon1.Icon = NIconAtSmoke;
7932 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
7935 await this.RefreshTasktrayIcon();
7938 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7940 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7941 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7943 if (ListTab != null && ListTab.SelectedTab != null)
7944 _rclickTabName = ListTab.SelectedTab.Text;
7949 if (_statuses == null) return;
7950 if (_statuses.Tabs == null) return;
7952 TabModel tb = _statuses.Tabs[_rclickTabName];
7953 if (tb == null) return;
7955 NotifyDispMenuItem.Checked = tb.Notify;
7956 this.NotifyTbMenuItem.Checked = tb.Notify;
7958 soundfileListup = true;
7959 SoundFileComboBox.Items.Clear();
7960 this.SoundFileTbComboBox.Items.Clear();
7961 SoundFileComboBox.Items.Add("");
7962 this.SoundFileTbComboBox.Items.Add("");
7963 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
7964 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
7966 oDir = oDir.GetDirectories("Sounds")[0];
7968 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
7970 SoundFileComboBox.Items.Add(oFile.Name);
7971 this.SoundFileTbComboBox.Items.Add(oFile.Name);
7973 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
7974 if (idx == -1) idx = 0;
7975 SoundFileComboBox.SelectedIndex = idx;
7976 this.SoundFileTbComboBox.SelectedIndex = idx;
7977 soundfileListup = false;
7978 UreadManageMenuItem.Checked = tb.UnreadManage;
7979 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
7981 TabMenuControl(_rclickTabName);
7984 private void TabMenuControl(string tabName)
7986 var tabInfo = _statuses.GetTabByName(tabName);
7988 this.FilterEditMenuItem.Enabled = true;
7989 this.EditRuleTbMenuItem.Enabled = true;
7991 if (tabInfo.IsDefaultTabType)
7993 this.ProtectTabMenuItem.Enabled = false;
7994 this.ProtectTbMenuItem.Enabled = false;
7998 this.ProtectTabMenuItem.Enabled = true;
7999 this.ProtectTbMenuItem.Enabled = true;
8002 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8004 this.ProtectTabMenuItem.Checked = true;
8005 this.ProtectTbMenuItem.Checked = true;
8006 this.DeleteTabMenuItem.Enabled = false;
8007 this.DeleteTbMenuItem.Enabled = false;
8011 this.ProtectTabMenuItem.Checked = false;
8012 this.ProtectTbMenuItem.Checked = false;
8013 this.DeleteTabMenuItem.Enabled = true;
8014 this.DeleteTbMenuItem.Enabled = true;
8018 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8020 var checkState = ((ToolStripMenuItem)sender).Checked;
8023 this.ProtectTbMenuItem.Checked = checkState;
8024 this.ProtectTabMenuItem.Checked = checkState;
8027 this.DeleteTabMenuItem.Enabled = !checkState;
8028 this.DeleteTbMenuItem.Enabled = !checkState;
8030 if (string.IsNullOrEmpty(_rclickTabName)) return;
8031 _statuses.Tabs[_rclickTabName].Protected = checkState;
8036 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8038 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8039 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8041 if (string.IsNullOrEmpty(_rclickTabName)) return;
8042 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8047 public void ChangeTabUnreadManage(string tabName, bool isManage)
8049 var idx = this.GetTabPageIndex(tabName);
8053 _statuses.Tabs[tabName].UnreadManage = isManage;
8054 if (this._cfgCommon.TabIconDisp)
8056 if (_statuses.Tabs[tabName].UnreadCount > 0)
8057 ListTab.TabPages[idx].ImageIndex = 0;
8059 ListTab.TabPages[idx].ImageIndex = -1;
8062 if (_curTab.Text == tabName)
8064 this.PurgeListViewItemCache();
8068 SetMainWindowTitle();
8069 SetStatusLabelUrl();
8070 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8073 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8075 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8076 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8078 if (string.IsNullOrEmpty(_rclickTabName)) return;
8080 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8085 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8087 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8089 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8094 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8096 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8098 RemoveSpecifiedTab(_rclickTabName, true);
8102 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8104 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8106 using (var fltDialog = new FilterDialog())
8108 fltDialog.Owner = this;
8109 fltDialog.SetCurrent(_rclickTabName);
8110 fltDialog.ShowDialog(this);
8112 this.TopMost = this._cfgCommon.AlwaysTop;
8114 this.ApplyPostFilters();
8118 private void AddTabMenuItem_Click(object sender, EventArgs e)
8120 string tabName = null;
8121 MyCommon.TabUsageType tabUsage;
8122 using (InputTabName inputName = new InputTabName())
8124 inputName.TabName = _statuses.MakeTabName("MyTab");
8125 inputName.IsShowUsage = true;
8126 inputName.ShowDialog();
8127 if (inputName.DialogResult == DialogResult.Cancel) return;
8128 tabName = inputName.TabName;
8129 tabUsage = inputName.Usage;
8131 this.TopMost = this._cfgCommon.AlwaysTop;
8132 if (!string.IsNullOrEmpty(tabName))
8135 ListElement list = null;
8136 if (tabUsage == MyCommon.TabUsageType.Lists)
8138 using (ListAvailable listAvail = new ListAvailable())
8140 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8141 if (listAvail.SelectedList == null) return;
8142 list = listAvail.SelectedList;
8149 case MyCommon.TabUsageType.UserDefined:
8150 tab = new FilterTabModel(tabName);
8152 case MyCommon.TabUsageType.PublicSearch:
8153 tab = new PublicSearchTabModel(tabName);
8155 case MyCommon.TabUsageType.Lists:
8156 tab = new ListTimelineTabModel(tabName, list);
8162 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8164 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8165 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8171 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8173 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8174 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8176 if (tabUsage == MyCommon.TabUsageType.Lists)
8178 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8179 var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8180 this.GetListTimelineAsync(listTab);
8186 private void TabMenuItem_Click(object sender, EventArgs e)
8188 using (var fltDialog = new FilterDialog())
8190 fltDialog.Owner = this;
8193 foreach (int idx in _curList.SelectedIndices)
8197 if (!SelectTab(out tabName)) return;
8199 fltDialog.SetCurrent(tabName);
8200 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8202 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8206 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8208 fltDialog.ShowDialog(this);
8209 this.TopMost = this._cfgCommon.AlwaysTop;
8213 this.ApplyPostFilters();
8215 if (this.ListTab.SelectedTab != null &&
8216 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8218 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8222 protected override bool ProcessDialogKey(Keys keyData)
8224 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8225 if ((keyData & Keys.KeyCode) == Keys.Enter)
8227 if (StatusText.Focused)
8229 bool _NewLine = false;
8232 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8234 if (StatusText.Multiline)
8236 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8238 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8242 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8246 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8248 if (StatusText.Multiline)
8250 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8252 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8256 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8262 if (StatusText.Multiline)
8264 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8266 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8267 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8271 if (((keyData & Keys.Shift) == Keys.Shift) ||
8272 (((keyData & Keys.Control) != Keys.Control) &&
8273 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8279 int pos1 = StatusText.SelectionStart;
8280 if (StatusText.SelectionLength > 0)
8282 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8284 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8285 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8290 PostButton_Click(null, null);
8294 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8295 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8296 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8298 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8303 return base.ProcessDialogKey(keyData);
8306 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8308 MakeReplyOrDirectStatus(false, true, true);
8311 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8314 if (_curList.SelectedIndices.Count == 0) return;
8316 var tab = this._statuses.Tabs[this._curTab.Text];
8317 var screenNameArray = this._curList.SelectedIndices.Cast<int>()
8318 .Select(x => tab[x])
8319 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8322 this.AddFilterRuleByScreenName(screenNameArray);
8324 if (screenNameArray.Length != 0)
8326 List<string> atids = new List<string>();
8327 foreach (var screenName in screenNameArray)
8329 atids.Add("@" + screenName);
8331 int cnt = AtIdSupl.ItemCount;
8332 AtIdSupl.AddRangeItem(atids.ToArray());
8333 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8337 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8339 if (this._curList.SelectedIndices.Count == 0)
8342 var tab = this._statuses.Tabs[this._curTab.Text];
8343 var sourceArray = this._curList.SelectedIndices.Cast<int>()
8344 .Select(x => tab[x].Source).ToArray();
8346 this.AddFilterRuleBySource(sourceArray);
8349 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8353 if (!SelectTab(out tabName)) return;
8355 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8359 if (tab.TabType != MyCommon.TabUsageType.Mute)
8361 this.MoveOrCopy(out mv, out mk);
8365 // ミュートタブでは常に MoveMatches を true にする
8370 foreach (var screenName in screenNameArray)
8372 tab.AddFilter(new PostFilterRule
8374 FilterName = screenName,
8375 UseNameField = true,
8379 FilterByUrl = false,
8383 this.ApplyPostFilters();
8387 public void AddFilterRuleBySource(params string[] sourceArray)
8389 // タブ選択ダイアログを表示(or追加)
8391 if (!this.SelectTab(out tabName))
8394 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8398 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8400 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8401 this.MoveOrCopy(out mv, out mk);
8405 // ミュートタブでは常に MoveMatches を true にする
8410 // 振り分けルールに追加するSource
8411 foreach (var source in sourceArray)
8413 filterTab.AddFilter(new PostFilterRule
8415 FilterSource = source,
8419 FilterByUrl = false,
8423 this.ApplyPostFilters();
8424 this.SaveConfigsTabs();
8427 private bool SelectTab(out string tabName)
8434 using (var dialog = new TabsDialog(_statuses))
8436 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8438 var selectedTab = dialog.SelectedTab;
8439 tabName = selectedTab == null ? null : selectedTab.TabName;
8442 ListTab.SelectedTab.Focus();
8444 if (tabName == null)
8446 using (InputTabName inputName = new InputTabName())
8448 inputName.TabName = _statuses.MakeTabName("MyTab");
8449 inputName.ShowDialog();
8450 if (inputName.DialogResult == DialogResult.Cancel) return false;
8451 tabName = inputName.TabName;
8453 this.TopMost = this._cfgCommon.AlwaysTop;
8454 if (!string.IsNullOrEmpty(tabName))
8456 var tab = new FilterTabModel(tabName);
8457 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8459 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8460 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8478 private void MoveOrCopy(out bool move, out bool mark)
8482 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8483 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8491 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8492 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8502 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8507 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8512 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8514 if (StatusText.Focused)
8517 StatusText.SelectAll();
8521 // ListView上でのCtrl+A
8522 NativeMethods.SelectAllItems(this._curList);
8526 private void MoveMiddle()
8532 if (_curList.SelectedIndices.Count == 0) return;
8534 int idx = _curList.SelectedIndices[0];
8536 _item = _curList.GetItemAt(0, 25);
8542 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8544 idx2 = _curList.VirtualListSize - 1;
8548 idx -= Math.Abs(idx1 - idx2) / 2;
8549 if (idx < 0) idx = 0;
8551 _curList.EnsureVisible(_curList.VirtualListSize - 1);
8552 _curList.EnsureVisible(idx);
8555 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8557 var linkElements = this.tweetDetailsView.GetLinkElements();
8559 if (linkElements.Length > 0)
8561 UrlDialog.ClearUrl();
8563 string openUrlStr = "";
8565 if (linkElements.Length == 1)
8567 // ツイートに含まれる URL が 1 つのみの場合
8568 // => OpenURL ダイアログを表示せずにリンクを開く
8573 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8575 catch (ArgumentException)
8584 if (string.IsNullOrEmpty(urlStr)) return;
8585 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8587 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8588 await this.OpenUriAsync(new Uri(openUrlStr));
8592 // ツイートに含まれる URL が複数ある場合
8593 // => OpenURL を表示しユーザーが選択したリンクを開く
8595 foreach (var linkElm in linkElements)
8598 string linkText = "";
8602 urlStr = linkElm.GetAttribute("title");
8603 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8604 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8605 linkText = linkElm.InnerText;
8607 catch (ArgumentException)
8616 if (string.IsNullOrEmpty(urlStr)) continue;
8617 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8621 if (UrlDialog.ShowDialog() == DialogResult.OK)
8623 openUrlStr = UrlDialog.SelectedUrl;
8625 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8626 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8633 this.TopMost = this._cfgCommon.AlwaysTop;
8638 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8640 if (string.IsNullOrEmpty(_rclickTabName)) return;
8641 ClearTab(_rclickTabName, true);
8644 private void ClearTab(string tabName, bool showWarning)
8648 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8649 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8655 _statuses.ClearTabIds(tabName);
8656 if (ListTab.SelectedTab.Text == tabName)
8659 _anchorFlag = false;
8660 this.PurgeListViewItemCache();
8664 foreach (TabPage tb in ListTab.TabPages)
8666 if (tb.Text == tabName)
8669 ((DetailsListView)tb.Tag).VirtualListSize = 0;
8673 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8675 SetMainWindowTitle();
8676 SetStatusLabelUrl();
8679 private static long followers = 0;
8681 private void SetMainWindowTitle()
8684 StringBuilder ttl = new StringBuilder(256);
8687 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
8688 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8689 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8690 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8692 foreach (var tab in _statuses.Tabs.Values)
8694 ur += tab.UnreadCount;
8699 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
8700 ttl.Append(Application.ProductName);
8702 switch (this._cfgCommon.DispLatestPost)
8704 case MyCommon.DispTitleEnum.Ver:
8705 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8707 case MyCommon.DispTitleEnum.Post:
8708 if (_history != null && _history.Count > 1)
8709 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8711 case MyCommon.DispTitleEnum.UnreadRepCount:
8712 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8714 case MyCommon.DispTitleEnum.UnreadAllCount:
8715 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8717 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8718 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8720 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8721 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8723 case MyCommon.DispTitleEnum.OwnStatus:
8724 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8725 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8731 this.Text = ttl.ToString();
8733 catch (AccessViolationException)
8735 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8739 private string GetStatusLabelText()
8742 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8743 if (_statuses == null) return "";
8744 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8745 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8746 if (tbRep == null || tbDm == null) return "";
8747 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8752 StringBuilder slbl = new StringBuilder(256);
8755 foreach (var tab in _statuses.Tabs.Values)
8757 ur += tab.UnreadCount;
8759 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
8761 tur = tab.UnreadCount;
8772 UnreadAtCounter = urat;
8774 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8776 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8777 if (this._cfgCommon.TimelinePeriod == 0)
8779 slbl.Append(Properties.Resources.SetStatusLabelText2);
8783 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8785 return slbl.ToString();
8788 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8792 if (this.InvokeRequired && !this.IsDisposed)
8794 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8798 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8799 SetApiStatusLabel(endpointName);
8802 catch (ObjectDisposedException)
8806 catch (InvalidOperationException)
8812 private void SetApiStatusLabel(string endpointName = null)
8814 if (_curTab == null)
8816 this.toolStripApiGauge.ApiEndpoint = null;
8820 var tabType = _statuses.Tabs[_curTab.Text].TabType;
8822 if (endpointName == null)
8827 case MyCommon.TabUsageType.Home:
8828 case MyCommon.TabUsageType.UserDefined:
8829 endpointName = "/statuses/home_timeline";
8832 case MyCommon.TabUsageType.Mentions:
8833 endpointName = "/statuses/mentions_timeline";
8836 case MyCommon.TabUsageType.Favorites:
8837 endpointName = "/favorites/list";
8840 case MyCommon.TabUsageType.DirectMessage:
8841 endpointName = "/direct_messages";
8844 case MyCommon.TabUsageType.UserTimeline:
8845 endpointName = "/statuses/user_timeline";
8848 case MyCommon.TabUsageType.Lists:
8849 endpointName = "/lists/statuses";
8852 case MyCommon.TabUsageType.PublicSearch:
8853 endpointName = "/search/tweets";
8856 case MyCommon.TabUsageType.Related:
8857 endpointName = "/statuses/show/:id";
8864 this.toolStripApiGauge.ApiEndpoint = endpointName;
8868 // 表示中のタブに関連する endpoint であれば更新
8871 switch (endpointName)
8873 case "/statuses/home_timeline":
8874 update = tabType == MyCommon.TabUsageType.Home ||
8875 tabType == MyCommon.TabUsageType.UserDefined;
8878 case "/statuses/mentions_timeline":
8879 update = tabType == MyCommon.TabUsageType.Mentions;
8882 case "/favorites/list":
8883 update = tabType == MyCommon.TabUsageType.Favorites;
8886 case "/direct_messages:":
8887 update = tabType == MyCommon.TabUsageType.DirectMessage;
8890 case "/statuses/user_timeline":
8891 update = tabType == MyCommon.TabUsageType.UserTimeline;
8894 case "/lists/statuses":
8895 update = tabType == MyCommon.TabUsageType.Lists;
8898 case "/search/tweets":
8899 update = tabType == MyCommon.TabUsageType.PublicSearch;
8902 case "/statuses/show/:id":
8903 update = tabType == MyCommon.TabUsageType.Related;
8912 this.toolStripApiGauge.ApiEndpoint = endpointName;
8918 private void SetStatusLabelUrl()
8920 StatusLabelUrl.Text = GetStatusLabelText();
8923 public void SetStatusLabel(string text)
8925 StatusLabel.Text = text;
8928 private static StringBuilder ur = new StringBuilder(64);
8930 private void SetNotifyIconText()
8932 // タスクトレイアイコンのツールチップテキスト書き換え
8934 ur.Remove(0, ur.Length);
8935 if (this._cfgCommon.DispUsername)
8937 ur.Append(tw.Username);
8940 ur.Append(Application.ProductName);
8942 ur.Append("(Debug Build)");
8944 if (UnreadCounter != -1 && UnreadAtCounter != -1)
8947 ur.Append(UnreadCounter);
8949 ur.Append(UnreadAtCounter);
8952 NotifyIcon1.Text = ur.ToString();
8955 internal void CheckReplyTo(string StatusText)
8959 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
8961 foreach (Match hm in m)
8963 if (!hstr.Contains("#" + hm.Result("$3") + " "))
8965 hstr += "#" + hm.Result("$3") + " ";
8966 HashSupl.AddItem("#" + hm.Result("$3"));
8969 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
8971 hstr += HashMgr.UseHash;
8973 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
8975 // 本当にリプライ先指定すべきかどうかの判定
8976 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
8978 if (this._cfgCommon.UseAtIdSupplement)
8980 int bCnt = AtIdSupl.ItemCount;
8981 foreach (Match mid in m)
8983 AtIdSupl.AddItem(mid.Result("${id}"));
8985 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
8988 // リプライ先ステータスIDの指定がない場合は指定しない
8989 if (this.inReplyTo == null)
8993 // 次の条件を満たす場合に in_reply_to_status_id 指定
8994 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
8995 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
8996 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9000 var inReplyToScreenName = this.inReplyTo.Item2;
9001 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9003 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9007 foreach (Match mid in m)
9009 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9014 this.inReplyTo = null;
9017 private void TweenMain_Resize(object sender, EventArgs e)
9019 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9021 this.Visible = false;
9023 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9025 // 現在の DPI と設定保存時の DPI との比を取得する
9026 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9028 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9029 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9030 this.DesktopLocation = _cfgLocal.FormLocation;
9031 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9034 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9035 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9036 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9038 this.SplitContainer1.SplitterDistance = splitterDistance;
9042 StatusText.Multiline = _cfgLocal.StatusMultiline;
9043 if (StatusText.Multiline)
9045 var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9046 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9047 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9049 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9051 StatusText.Height = statusTextHeight;
9055 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9057 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9061 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9062 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9064 this.SplitContainer3.SplitterDistance = previewDistance;
9067 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9068 this.SplitContainer3.Panel2Collapsed = true;
9070 _initialLayout = false;
9072 if (this.WindowState != FormWindowState.Minimized)
9074 _formWindowState = this.WindowState;
9078 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9080 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9081 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9082 if (PlaySoundMenuItem.Checked)
9084 this._cfgCommon.PlaySound = true;
9088 this._cfgCommon.PlaySound = false;
9090 ModifySettingCommon = true;
9093 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9095 if (this._initialLayout)
9098 int splitterDistance;
9099 switch (this.WindowState)
9101 case FormWindowState.Normal:
9102 splitterDistance = this.SplitContainer1.SplitterDistance;
9104 case FormWindowState.Maximized:
9105 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9106 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9107 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9108 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9114 this._mySpDis = splitterDistance;
9115 this.ModifySettingLocal = true;
9118 private async Task doRepliedStatusOpen()
9120 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9122 if (MyCommon.IsKeyDown(Keys.Shift))
9124 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9127 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9129 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9130 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9134 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9136 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9137 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9138 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9141 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9146 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9148 await this.doRepliedStatusOpen();
9151 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9153 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9154 if (multiline != this.StatusText.Multiline)
9156 this.StatusText.Multiline = multiline;
9157 MultiLineMenuItem.Checked = multiline;
9158 ModifySettingLocal = true;
9162 private void StatusText_MultilineChanged(object sender, EventArgs e)
9164 if (this.StatusText.Multiline)
9165 this.StatusText.ScrollBars = ScrollBars.Vertical;
9167 this.StatusText.ScrollBars = ScrollBars.None;
9169 ModifySettingLocal = true;
9172 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9175 StatusText.Multiline = MultiLineMenuItem.Checked;
9176 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
9177 if (MultiLineMenuItem.Checked)
9179 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9180 SplitContainer2.SplitterDistance = 0;
9182 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9186 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9188 ModifySettingLocal = true;
9191 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9193 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9194 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9196 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9197 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9198 //Appendix A. Collected ABNF for URI
9199 //http://www.ietf.org/rfc/rfc3986.txt
9203 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9205 if (StatusText.SelectionLength > 0)
9207 string tmp = StatusText.SelectedText;
9208 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9209 if (tmp.StartsWith("http"))
9211 // 文字列が選択されている場合はその文字列について処理
9213 //nico.ms使用、nicovideoにマッチしたら変換
9214 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
9216 result = nicoms.Shorten(tmp);
9218 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9220 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9223 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9224 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9225 result = resultUri.AbsoluteUri;
9227 catch (WebApiException e)
9229 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9232 catch (UriFormatException e)
9234 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9243 if (!string.IsNullOrEmpty(result))
9245 urlUndo undotmp = new urlUndo();
9247 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
9248 StatusText.SelectedText = result;
9251 undotmp.Before = tmp;
9252 undotmp.After = result;
9254 if (urlUndoBuffer == null)
9256 urlUndoBuffer = new List<urlUndo>();
9257 UrlUndoToolStripMenuItem.Enabled = true;
9260 urlUndoBuffer.Add(undotmp);
9266 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9267 @"(?<url>(?<protocol>https?://)" +
9268 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9269 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9270 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9271 // 正規表現にマッチしたURL文字列をtinyurl化
9272 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9274 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9275 string tmp = mt.Result("${url}");
9276 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9277 urlUndo undotmp = new urlUndo();
9280 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9282 //nico.ms使用、nicovideoにマッチしたら変換
9283 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
9285 result = nicoms.Shorten(tmp);
9287 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9289 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9292 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9293 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9294 result = resultUri.AbsoluteUri;
9296 catch (HttpRequestException e)
9298 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9299 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9300 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9302 this.StatusLabel.Text = Converter_Type + ":" + message;
9305 catch (WebApiException e)
9307 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9310 catch (UriFormatException e)
9312 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9321 if (!string.IsNullOrEmpty(result))
9323 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9324 StatusText.SelectedText = result;
9326 undotmp.Before = mt.Result("${url}");
9327 undotmp.After = result;
9329 if (urlUndoBuffer == null)
9331 urlUndoBuffer = new List<urlUndo>();
9332 UrlUndoToolStripMenuItem.Enabled = true;
9335 urlUndoBuffer.Add(undotmp);
9343 private void doUrlUndo()
9345 if (urlUndoBuffer != null)
9347 string tmp = StatusText.Text;
9348 foreach (urlUndo data in urlUndoBuffer)
9350 tmp = tmp.Replace(data.After, data.Before);
9352 StatusText.Text = tmp;
9353 urlUndoBuffer = null;
9354 UrlUndoToolStripMenuItem.Enabled = false;
9355 StatusText.SelectionStart = 0;
9356 StatusText.SelectionLength = 0;
9360 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9362 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9365 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9367 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9370 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9372 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9375 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9377 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9380 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9382 if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
9384 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
9385 Random rnd = new Random();
9386 // 前回使用した短縮URLサービス以外を選択する
9389 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9391 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9392 await UrlConvertAsync(svc);
9396 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9401 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9403 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9404 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9405 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
9406 ModifySettingCommon = true;
9409 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9411 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9412 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9413 _cfgCommon.ListLock = ListLockMenuItem.Checked;
9414 ModifySettingCommon = true;
9417 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9419 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9420 MenuStrip1.Tag = new Object();
9421 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9424 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9426 if (this.Tag != null) // 設定された戻り先へ遷移
9428 if (this.Tag == this.ListTab.SelectedTab)
9429 ((Control)this.ListTab.SelectedTab.Tag).Select();
9431 ((Control)this.Tag).Select();
9433 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9435 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9437 this.Tag = ListTab.SelectedTab.Tag;
9438 ((Control)this.Tag).Select();
9441 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9442 MenuStrip1.Tag = null;
9445 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9447 DetailsListView lst = (DetailsListView)sender;
9448 if (_cfgLocal == null) return;
9452 _cfgLocal.Width1 = lst.Columns[0].Width;
9453 _cfgLocal.Width3 = lst.Columns[1].Width;
9457 int[] darr = new int[lst.Columns.Count];
9458 for (int i = 0; i < lst.Columns.Count; i++)
9460 darr[lst.Columns[i].DisplayIndex] = i;
9462 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9464 for (int i = 0; i < lst.Columns.Count; i++)
9469 _cfgLocal.DisplayIndex1 = i;
9472 _cfgLocal.DisplayIndex2 = i;
9475 _cfgLocal.DisplayIndex3 = i;
9478 _cfgLocal.DisplayIndex4 = i;
9481 _cfgLocal.DisplayIndex5 = i;
9484 _cfgLocal.DisplayIndex6 = i;
9487 _cfgLocal.DisplayIndex7 = i;
9490 _cfgLocal.DisplayIndex8 = i;
9494 _cfgLocal.Width1 = lst.Columns[0].Width;
9495 _cfgLocal.Width2 = lst.Columns[1].Width;
9496 _cfgLocal.Width3 = lst.Columns[2].Width;
9497 _cfgLocal.Width4 = lst.Columns[3].Width;
9498 _cfgLocal.Width5 = lst.Columns[4].Width;
9499 _cfgLocal.Width6 = lst.Columns[5].Width;
9500 _cfgLocal.Width7 = lst.Columns[6].Width;
9501 _cfgLocal.Width8 = lst.Columns[7].Width;
9503 ModifySettingLocal = true;
9504 _isColumnChanged = true;
9507 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9509 DetailsListView lst = (DetailsListView)sender;
9510 if (_cfgLocal == null) return;
9513 if (_cfgLocal.Width1 != lst.Columns[0].Width)
9515 _cfgLocal.Width1 = lst.Columns[0].Width;
9516 ModifySettingLocal = true;
9517 _isColumnChanged = true;
9519 if (_cfgLocal.Width3 != lst.Columns[1].Width)
9521 _cfgLocal.Width3 = lst.Columns[1].Width;
9522 ModifySettingLocal = true;
9523 _isColumnChanged = true;
9528 if (_cfgLocal.Width1 != lst.Columns[0].Width)
9530 _cfgLocal.Width1 = lst.Columns[0].Width;
9531 ModifySettingLocal = true;
9532 _isColumnChanged = true;
9534 if (_cfgLocal.Width2 != lst.Columns[1].Width)
9536 _cfgLocal.Width2 = lst.Columns[1].Width;
9537 ModifySettingLocal = true;
9538 _isColumnChanged = true;
9540 if (_cfgLocal.Width3 != lst.Columns[2].Width)
9542 _cfgLocal.Width3 = lst.Columns[2].Width;
9543 ModifySettingLocal = true;
9544 _isColumnChanged = true;
9546 if (_cfgLocal.Width4 != lst.Columns[3].Width)
9548 _cfgLocal.Width4 = lst.Columns[3].Width;
9549 ModifySettingLocal = true;
9550 _isColumnChanged = true;
9552 if (_cfgLocal.Width5 != lst.Columns[4].Width)
9554 _cfgLocal.Width5 = lst.Columns[4].Width;
9555 ModifySettingLocal = true;
9556 _isColumnChanged = true;
9558 if (_cfgLocal.Width6 != lst.Columns[5].Width)
9560 _cfgLocal.Width6 = lst.Columns[5].Width;
9561 ModifySettingLocal = true;
9562 _isColumnChanged = true;
9564 if (_cfgLocal.Width7 != lst.Columns[6].Width)
9566 _cfgLocal.Width7 = lst.Columns[6].Width;
9567 ModifySettingLocal = true;
9568 _isColumnChanged = true;
9570 if (_cfgLocal.Width8 != lst.Columns[7].Width)
9572 _cfgLocal.Width8 = lst.Columns[7].Width;
9573 ModifySettingLocal = true;
9574 _isColumnChanged = true;
9577 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9580 // SaveConfigsLocal();
9584 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9586 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9587 ModifySettingLocal = true;
9590 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9592 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9594 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9596 SelectMedia_DragDrop(e);
9599 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9601 var url = GetUrlFromDataObject(e.Data);
9604 if (url.Item2 == null)
9605 appendText = url.Item1;
9607 appendText = url.Item2 + " " + url.Item1;
9609 if (this.StatusText.TextLength == 0)
9610 this.StatusText.Text = appendText;
9612 this.StatusText.Text += " " + appendText;
9614 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9616 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9618 this.StatusText.Text += text;
9620 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9622 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9623 if (data != null) StatusText.Text += data;
9628 /// IDataObject から URL とタイトルの対を取得します
9631 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9633 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9634 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9635 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
9637 if (data.GetDataPresent("text/x-moz-url"))
9639 // Firefox, Google Chrome で利用可能
9640 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9642 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9644 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9645 if (lines.Length < 2)
9646 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9648 return new Tuple<string, string>(lines[0], lines[1]);
9651 else if (data.GetDataPresent("IESiteModeToUrl"))
9653 // Internet Exproler 用
9654 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9656 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9658 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9659 if (lines.Length < 2)
9660 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9662 return new Tuple<string, string>(lines[0], lines[1]);
9665 else if (data.GetDataPresent("UniformResourceLocatorW"))
9669 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9671 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9672 return new Tuple<string, string>(url, null);
9676 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9679 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9681 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9683 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9685 SelectMedia_DragEnter(e);
9689 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9691 e.Effect = DragDropEffects.Copy;
9694 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9696 e.Effect = DragDropEffects.Copy;
9699 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9701 e.Effect = DragDropEffects.Copy;
9705 e.Effect = DragDropEffects.None;
9708 private void TweenMain_DragOver(object sender, DragEventArgs e)
9712 public bool IsNetworkAvailable()
9715 nw = MyCommon.IsNetworkAvailable();
9716 _myStatusOnline = nw;
9720 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9722 var uriStr = uri.AbsoluteUri;
9724 // OpenTween 内部で使用する URL
9725 if (uri.Authority == "opentween")
9727 await this.OpenInternalUriAsync(uri);
9731 // ハッシュタグを含む Twitter 検索
9732 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9735 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9736 var pos = unescapedQuery.IndexOf('#');
9737 if (pos == -1) return;
9739 var hash = unescapedQuery.Substring(pos);
9740 this.HashSupl.AddItem(hash);
9741 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9742 this.AddNewTabForSearch(hash);
9747 // フラグが立っている場合は設定と逆の動作をする
9748 if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
9749 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
9751 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9752 if (userUriMatch.Success)
9754 var screenName = userUriMatch.Groups["ScreenName"].Value;
9755 if (this.IsTwitterId(screenName))
9757 this.AddNewTabForUserTimeline(screenName);
9764 await this.OpenUriInBrowserAsync(uriStr);
9768 /// OpenTween 内部の機能を呼び出すための URL を開きます
9770 private async Task OpenInternalUriAsync(Uri uri)
9772 // ツイートを開く (//opentween/status/:status_id)
9773 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9776 var statusId = long.Parse(match.Groups[1].Value);
9777 await this.OpenRelatedTab(statusId);
9782 public Task OpenUriInBrowserAsync(string UriString)
9784 return Task.Run(() =>
9786 string myPath = UriString;
9790 var configBrowserPath = this._cfgLocal.BrowserPath;
9791 if (!string.IsNullOrEmpty(configBrowserPath))
9793 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9795 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9796 string browserPath = configBrowserPath.Substring(1, sep - 1);
9798 if (sep < configBrowserPath.Length - 1)
9800 arg = configBrowserPath.Substring(sep + 1);
9802 myPath = arg + " " + myPath;
9803 System.Diagnostics.Process.Start(browserPath, myPath);
9807 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9812 System.Diagnostics.Process.Start(myPath);
9817 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9822 private void ListTabSelect(TabPage _tab)
9826 this.PurgeListViewItemCache();
9829 _curList = (DetailsListView)_tab.Tag;
9830 if (_curList.SelectedIndices.Count > 0)
9832 _curItemIndex = _curList.SelectedIndices[0];
9833 _curPost = GetCurTabPost(_curItemIndex);
9842 _anchorFlag = false;
9846 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
9850 for (int i = 0; i < _curList.Columns.Count; i++)
9852 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
9857 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9859 ListTabSelect(e.TabPage);
9862 private void SelectListItem(DetailsListView LView, int Index)
9865 Rectangle bnd = new Rectangle();
9867 var item = LView.FocusedItem;
9876 LView.SelectedIndices.Clear();
9878 while (LView.SelectedIndices.Count > 0);
9879 item = LView.Items[Index];
9880 item.Selected = true;
9881 item.Focused = true;
9883 if (flg) LView.Invalidate(bnd);
9886 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9889 Rectangle bnd = new Rectangle();
9891 var item = LView.FocusedItem;
9902 LView.SelectedIndices.Clear();
9904 while (LView.SelectedIndices.Count > 0);
9905 LView.SelectItems(Index);
9907 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9909 LView.SelectionMark = selectionMarkIndex;
9911 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9913 LView.Items[focusedIndex].Focused = true;
9915 else if (Index != null && Index.Length != 0)
9917 LView.Items[Index.Last()].Focused = true;
9920 if (flg) LView.Invalidate(bnd);
9923 private void StartUserStream()
9925 tw.NewPostFromStream += tw_NewPostFromStream;
9926 tw.UserStreamStarted += tw_UserStreamStarted;
9927 tw.UserStreamStopped += tw_UserStreamStopped;
9928 tw.PostDeleted += tw_PostDeleted;
9929 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9931 this.RefreshUserStreamsMenu();
9933 if (this._cfgCommon.UserstreamStartup)
9934 tw.StartUserStream();
9937 private async void TweenMain_Shown(object sender, EventArgs e)
9939 NotifyIcon1.Visible = true;
9941 if (this.IsNetworkAvailable())
9945 var loadTasks = new List<Task>
9947 this.RefreshMuteUserIdsAsync(),
9948 this.RefreshBlockIdsAsync(),
9949 this.RefreshNoRetweetIdsAsync(),
9950 this.RefreshTwitterConfigurationAsync(),
9951 this.GetHomeTimelineAsync(),
9952 this.GetReplyAsync(),
9953 this.GetDirectMessagesAsync(),
9954 this.GetPublicSearchAllAsync(),
9955 this.GetUserTimelineAllAsync(),
9956 this.GetListTimelineAllAsync(),
9959 if (this._cfgCommon.StartupFollowers)
9960 loadTasks.Add(this.RefreshFollowerIdsAsync());
9962 if (this._cfgCommon.GetFav)
9963 loadTasks.Add(this.GetFavoritesAsync());
9965 var allTasks = Task.WhenAll(loadTasks);
9970 var timeout = Task.Delay(5000);
9971 if (await Task.WhenAny(allTasks, timeout) != timeout)
9975 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
9977 if (MyCommon._endingFlag)
9981 if (MyCommon._endingFlag) return;
9983 if (ApplicationSettings.VersionInfoUrl != null)
9985 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
9986 if (this._cfgCommon.StartupVersion)
9987 await this.CheckNewVersion(true);
9991 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
9992 this.VerUpMenuItem.Enabled = false;
9993 this.VerUpMenuItem.Available = false;
9994 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
9997 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
9998 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10000 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10001 SettingStripMenuItem_Click(null, null);
10005 var reloadTasks = new List<Task>();
10007 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
10008 reloadTasks.Add(this.RefreshFollowerIdsAsync());
10010 if (!tw.GetNoRetweetSuccess)
10011 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10013 if (this.tw.Configuration.PhotoSizeLimit == 0)
10014 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10016 await Task.WhenAll(reloadTasks);
10021 TimerTimeline.Enabled = true;
10024 private async Task doGetFollowersMenu()
10026 await this.RefreshFollowerIdsAsync();
10027 await this.DispSelectedPost(true);
10030 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10032 await this.doGetFollowersMenu();
10035 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10037 doReTweetUnofficial();
10040 private async Task doReTweetOfficial(bool isConfirm)
10043 if (this.ExistCurrentPost)
10045 if (_curPost.IsProtect)
10047 MessageBox.Show("Protected.");
10048 _DoFavRetweetFlags = false;
10051 if (_curList.SelectedIndices.Count > 15)
10053 MessageBox.Show(Properties.Resources.RetweetLimitText);
10054 _DoFavRetweetFlags = false;
10057 else if (_curList.SelectedIndices.Count > 1)
10059 string QuestionText = Properties.Resources.RetweetQuestion2;
10060 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10061 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10063 case DialogResult.Cancel:
10064 case DialogResult.No:
10065 _DoFavRetweetFlags = false;
10071 if (_curPost.IsDm || _curPost.IsMe)
10073 _DoFavRetweetFlags = false;
10076 if (!this._cfgCommon.RetweetNoConfirm)
10078 string Questiontext = Properties.Resources.RetweetQuestion1;
10079 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10080 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10082 _DoFavRetweetFlags = false;
10088 var statusIds = new List<long>();
10089 foreach (int idx in _curList.SelectedIndices)
10091 PostClass post = GetCurTabPost(idx);
10092 if (!post.IsMe && !post.IsProtect && !post.IsDm)
10093 statusIds.Add(post.StatusId);
10096 await this.RetweetAsync(statusIds);
10100 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10102 await this.doReTweetOfficial(true);
10105 private async Task FavoritesRetweetOfficial()
10107 if (!this.ExistCurrentPost) return;
10108 _DoFavRetweetFlags = true;
10109 var retweetTask = this.doReTweetOfficial(true);
10110 if (_DoFavRetweetFlags)
10112 _DoFavRetweetFlags = false;
10113 var favoriteTask = this.FavoriteChange(true, false);
10115 await Task.WhenAll(retweetTask, favoriteTask);
10123 private async Task FavoritesRetweetUnofficial()
10125 if (this.ExistCurrentPost && !_curPost.IsDm)
10127 _DoFavRetweetFlags = true;
10128 var favoriteTask = this.FavoriteChange(true);
10129 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10131 _DoFavRetweetFlags = false;
10132 doReTweetUnofficial();
10135 await favoriteTask;
10140 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10142 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10143 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10144 /// <returns>復元されたツイート本文</returns>
10145 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10147 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10150 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10152 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10154 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10158 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10160 statusHtml = statusHtml.Replace("<br>", " ");
10162 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10163 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10164 statusHtml = statusHtml.Replace(" ", " ");
10166 return WebUtility.HtmlDecode(statusHtml);
10169 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10171 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10173 if (_curPost != null)
10174 await this.DispSelectedPost(true);
10177 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10179 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10180 DebugModeToolStripMenuItem.Visible = true;
10182 DebugModeToolStripMenuItem.Visible = false;
10185 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
10187 this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
10190 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10192 ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
10195 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10197 if (TraceOutToolStripMenuItem.Checked)
10198 MyCommon.TraceFlag = true;
10200 MyCommon.TraceFlag = false;
10203 private void TweenMain_Deactivate(object sender, EventArgs e)
10205 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10206 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10209 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10211 if (string.IsNullOrEmpty(_rclickTabName)) return;
10212 TabRename(ref _rclickTabName);
10215 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10217 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10220 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10222 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10225 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10227 TwitterApiStatus apiStatus;
10229 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10231 var cancellationToken = dialog.EnableCancellation();
10235 var task = this.tw.GetInfoApi();
10236 apiStatus = await dialog.WaitForAsync(this, task);
10238 catch (WebApiException)
10243 if (cancellationToken.IsCancellationRequested)
10246 if (apiStatus == null)
10248 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10253 using (var apiDlg = new ApiInfoDialog())
10255 apiDlg.ShowDialog(this);
10259 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10261 var id = _curPost?.ScreenName ?? "";
10263 await this.FollowCommand(id);
10266 internal async Task FollowCommand(string id)
10268 using (var inputName = new InputTabName())
10270 inputName.FormTitle = "Follow";
10271 inputName.FormDescription = Properties.Resources.FRMessage1;
10272 inputName.TabName = id;
10274 if (inputName.ShowDialog(this) != DialogResult.OK)
10276 if (string.IsNullOrWhiteSpace(inputName.TabName))
10279 id = inputName.TabName.Trim();
10282 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10286 var task = this.twitterApi.FriendshipsCreate(id);
10287 await dialog.WaitForAsync(this, task);
10289 catch (WebApiException ex)
10291 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10296 MessageBox.Show(Properties.Resources.FRMessage3);
10299 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10301 var id = _curPost?.ScreenName ?? "";
10303 await this.RemoveCommand(id, false);
10306 internal async Task RemoveCommand(string id, bool skipInput)
10310 using (var inputName = new InputTabName())
10312 inputName.FormTitle = "Unfollow";
10313 inputName.FormDescription = Properties.Resources.FRMessage1;
10314 inputName.TabName = id;
10316 if (inputName.ShowDialog(this) != DialogResult.OK)
10318 if (string.IsNullOrWhiteSpace(inputName.TabName))
10321 id = inputName.TabName.Trim();
10325 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10329 var task = this.twitterApi.FriendshipsDestroy(id);
10330 await dialog.WaitForAsync(this, task);
10332 catch (WebApiException ex)
10334 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10339 MessageBox.Show(Properties.Resources.FRMessage3);
10342 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10344 var id = _curPost?.ScreenName ?? "";
10346 await this.ShowFriendship(id);
10349 internal async Task ShowFriendship(string id)
10351 using (var inputName = new InputTabName())
10353 inputName.FormTitle = "Show Friendships";
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();
10365 bool isFollowing, isFollowed;
10367 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10369 var cancellationToken = dialog.EnableCancellation();
10373 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10374 var friendship = await dialog.WaitForAsync(this, task);
10376 isFollowing = friendship.Relationship.Source.Following;
10377 isFollowed = friendship.Relationship.Source.FollowedBy;
10379 catch (WebApiException ex)
10381 if (!cancellationToken.IsCancellationRequested)
10382 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10386 if (cancellationToken.IsCancellationRequested)
10390 string result = "";
10393 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10397 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10401 result += Properties.Resources.GetFriendshipInfo3;
10405 result += Properties.Resources.GetFriendshipInfo4;
10407 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10408 MessageBox.Show(result);
10411 internal async Task ShowFriendship(string[] ids)
10413 foreach (string id in ids)
10415 bool isFollowing, isFollowed;
10417 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10419 var cancellationToken = dialog.EnableCancellation();
10423 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10424 var friendship = await dialog.WaitForAsync(this, task);
10426 isFollowing = friendship.Relationship.Source.Following;
10427 isFollowed = friendship.Relationship.Source.FollowedBy;
10429 catch (WebApiException ex)
10431 if (!cancellationToken.IsCancellationRequested)
10432 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10436 if (cancellationToken.IsCancellationRequested)
10440 string result = "";
10446 ff += Properties.Resources.GetFriendshipInfo1;
10450 ff += Properties.Resources.GetFriendshipInfo2;
10453 ff += System.Environment.NewLine + " ";
10456 ff += Properties.Resources.GetFriendshipInfo3;
10460 ff += Properties.Resources.GetFriendshipInfo4;
10462 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10465 if (MessageBox.Show(
10466 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10467 MessageBoxButtons.YesNo,
10468 MessageBoxIcon.Question,
10469 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10471 await this.RemoveCommand(id, true);
10476 MessageBox.Show(result);
10481 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10483 await this.doShowUserStatus(tw.Username, false);
10484 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
10486 // doShowUserStatus(tw.Username, false);
10490 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
10495 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10496 // URLから切り出した文字列を渡す
10498 public bool IsTwitterId(string name)
10500 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10501 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10503 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
10506 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
10508 ModifySettingCommon = true;
10511 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10513 ModifySettingCommon = true;
10516 private void doQuoteOfficial()
10518 if (this.ExistCurrentPost)
10520 if (_curPost.IsDm ||
10521 !StatusText.Enabled) return;
10523 if (_curPost.IsProtect)
10525 MessageBox.Show("Protected.");
10529 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
10531 this.inReplyTo = null;
10533 StatusText.SelectionStart = 0;
10534 StatusText.Focus();
10538 private void doReTweetUnofficial()
10541 if (this.ExistCurrentPost)
10543 if (_curPost.IsDm || !StatusText.Enabled)
10546 if (_curPost.IsProtect)
10548 MessageBox.Show("Protected.");
10551 string rtdata = _curPost.Text;
10552 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10554 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
10556 // 投稿時に in_reply_to_status_id を付加する
10557 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
10558 var inReplyToScreenName = this._curPost.ScreenName;
10559 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
10561 StatusText.SelectionStart = 0;
10562 StatusText.Focus();
10566 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
10571 private void SearchButton_Click(object sender, EventArgs e)
10574 Control pnl = ((Control)sender).Parent;
10575 if (pnl == null) return;
10576 string tbName = pnl.Parent.Text;
10577 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10578 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10579 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10580 cmb.Text = cmb.Text.Trim();
10581 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10582 bool Quote = false;
10583 StringBuilder buf = new StringBuilder();
10584 char[] c = cmb.Text.ToCharArray();
10585 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10587 if (cnt > cmb.Text.Length - 4)
10589 buf.Append(cmb.Text.Substring(cnt));
10598 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10600 buf.Append(" OR ");
10605 buf.Append(c[cnt]);
10607 cmb.Text = buf.ToString();
10609 var listView = (DetailsListView)pnl.Parent.Tag;
10611 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10613 tb.SearchWords = cmb.Text;
10614 tb.SearchLang = cmbLang.Text;
10615 if (string.IsNullOrEmpty(cmb.Text))
10623 int idx = cmb.Items.IndexOf(tb.SearchWords);
10624 if (idx > -1) cmb.Items.RemoveAt(idx);
10625 cmb.Items.Insert(0, tb.SearchWords);
10626 cmb.Text = tb.SearchWords;
10628 this.PurgeListViewItemCache();
10629 listView.VirtualListSize = 0;
10630 _statuses.ClearTabIds(tbName);
10631 SaveConfigsTabs(); //検索条件の保存
10634 this.GetPublicSearchAsync(tb);
10638 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10641 await this.DoRefreshMore();
10645 /// 指定されたタブのListTabにおける位置を返します
10648 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10650 public int GetTabPageIndex(string tabName)
10653 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
10655 if (tabPage.Text == tabName)
10664 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10666 if (_statuses.RemovedTab.Count == 0)
10668 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10673 DetailsListView listView = null;
10675 TabModel tb = _statuses.RemovedTab.Pop();
10676 if (tb.TabType == MyCommon.TabUsageType.Related)
10678 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10679 if (relatedTab != null)
10681 // 関連発言なら既存のタブを置き換える
10682 tb.TabName = relatedTab.TabName;
10683 this.ClearTab(tb.TabName, false);
10684 _statuses.Tabs[tb.TabName] = tb;
10686 for (int i = 0; i < ListTab.TabPages.Count; i++)
10688 var tabPage = ListTab.TabPages[i];
10689 if (tb.TabName == tabPage.Text)
10691 listView = (DetailsListView)tabPage.Tag;
10692 ListTab.SelectedIndex = i;
10699 const string TabName = "Related Tweets";
10700 string renamed = TabName;
10701 for (int i = 2; i <= 100; i++)
10703 if (!_statuses.ContainsTab(renamed)) break;
10704 renamed = TabName + i;
10706 tb.TabName = renamed;
10708 _statuses.AddTab(tb);
10709 AddNewTab(tb, startup: false);
10711 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10712 listView = (DetailsListView)tabPage.Tag;
10713 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10718 string renamed = tb.TabName;
10719 for (int i = 1; i < int.MaxValue; i++)
10721 if (!_statuses.ContainsTab(renamed)) break;
10722 renamed = tb.TabName + "(" + i + ")";
10724 tb.TabName = renamed;
10726 _statuses.AddTab(tb);
10727 AddNewTab(tb, startup: false);
10729 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10730 listView = (DetailsListView)tabPage.Tag;
10731 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10735 if (listView != null)
10737 using (ControlTransaction.Update(listView))
10739 listView.VirtualListSize = tb.AllCount;
10745 private async Task doMoveToRTHome()
10747 if (_curList.SelectedIndices.Count > 0)
10749 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
10750 if (post.RetweetedId != null)
10752 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
10757 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10759 await this.doMoveToRTHome();
10762 private async void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10764 var screenName = this._curPost?.ScreenName;
10765 if (screenName != null)
10766 await this.ListManageUserContext(screenName);
10769 public async Task ListManageUserContext(string screenName)
10771 if (this._statuses.SubscribableLists.Count == 0)
10775 using (var dialog = new WaitingDialog(Properties.Resources.ListsGetting))
10777 var cancellationToken = dialog.EnableCancellation();
10779 var task = this.tw.GetListsApi();
10780 await dialog.WaitForAsync(this, task);
10782 cancellationToken.ThrowIfCancellationRequested();
10785 catch (OperationCanceledException) { return; }
10786 catch (WebApiException ex)
10788 MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
10793 using (MyLists listSelectForm = new MyLists(screenName, this.tw))
10795 listSelectForm.ShowDialog(this);
10799 private void SearchControls_Enter(object sender, EventArgs e)
10801 Control pnl = (Control)sender;
10802 foreach (Control ctl in pnl.Controls)
10804 ctl.TabStop = true;
10808 private void SearchControls_Leave(object sender, EventArgs e)
10810 Control pnl = (Control)sender;
10811 foreach (Control ctl in pnl.Controls)
10813 ctl.TabStop = false;
10817 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10819 if (ListTab.SelectedTab != null)
10821 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
10822 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
10826 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10828 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10831 private void HashManageMenuItem_Click(object sender, EventArgs e)
10833 DialogResult rslt = DialogResult.Cancel;
10836 rslt = HashMgr.ShowDialog();
10842 this.TopMost = this._cfgCommon.AlwaysTop;
10843 if (rslt == DialogResult.Cancel) return;
10844 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10846 HashStripSplitButton.Text = HashMgr.UseHash;
10847 HashToggleMenuItem.Checked = true;
10848 HashToggleToolStripMenuItem.Checked = true;
10852 HashStripSplitButton.Text = "#[-]";
10853 HashToggleMenuItem.Checked = false;
10854 HashToggleToolStripMenuItem.Checked = false;
10856 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10858 // int sidx = StatusText.SelectionStart;
10859 // string hash = HashMgr.UseHash + " ";
10862 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10863 // hash = " " + hash;
10865 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
10866 // sidx += hash.Length;
10867 // StatusText.SelectionStart = sidx;
10868 // StatusText.Focus();
10870 ModifySettingCommon = true;
10871 this.StatusText_TextChanged(null, null);
10874 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10876 HashMgr.ToggleHash();
10877 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10879 HashStripSplitButton.Text = HashMgr.UseHash;
10880 HashToggleMenuItem.Checked = true;
10881 HashToggleToolStripMenuItem.Checked = true;
10885 HashStripSplitButton.Text = "#[-]";
10886 HashToggleMenuItem.Checked = false;
10887 HashToggleToolStripMenuItem.Checked = false;
10889 ModifySettingCommon = true;
10890 this.StatusText_TextChanged(null, null);
10893 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10895 HashToggleMenuItem_Click(null, null);
10898 public void SetPermanentHashtag(string hashtag)
10900 HashMgr.SetPermanentHash("#" + hashtag);
10901 HashStripSplitButton.Text = HashMgr.UseHash;
10902 HashToggleMenuItem.Checked = true;
10903 HashToggleToolStripMenuItem.Checked = true;
10905 ModifySettingCommon = true;
10908 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10910 if (ListTab.SelectedTab == null) return;
10911 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
10912 if (!this.ExistCurrentPost)
10914 this.ReplyOpMenuItem.Enabled = false;
10915 this.ReplyAllOpMenuItem.Enabled = false;
10916 this.DmOpMenuItem.Enabled = false;
10917 this.ShowProfMenuItem.Enabled = false;
10918 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10919 this.ListManageMenuItem.Enabled = false;
10920 this.OpenFavOpMenuItem.Enabled = false;
10921 this.CreateTabRuleOpMenuItem.Enabled = false;
10922 this.CreateIdRuleOpMenuItem.Enabled = false;
10923 this.CreateSourceRuleOpMenuItem.Enabled = false;
10924 this.ReadOpMenuItem.Enabled = false;
10925 this.UnreadOpMenuItem.Enabled = false;
10929 this.ReplyOpMenuItem.Enabled = true;
10930 this.ReplyAllOpMenuItem.Enabled = true;
10931 this.DmOpMenuItem.Enabled = true;
10932 this.ShowProfMenuItem.Enabled = true;
10933 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10934 this.ListManageMenuItem.Enabled = true;
10935 this.OpenFavOpMenuItem.Enabled = true;
10936 this.CreateTabRuleOpMenuItem.Enabled = true;
10937 this.CreateIdRuleOpMenuItem.Enabled = true;
10938 this.CreateSourceRuleOpMenuItem.Enabled = true;
10939 this.ReadOpMenuItem.Enabled = true;
10940 this.UnreadOpMenuItem.Enabled = true;
10943 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
10945 this.FavOpMenuItem.Enabled = false;
10946 this.UnFavOpMenuItem.Enabled = false;
10947 this.OpenStatusOpMenuItem.Enabled = false;
10948 this.OpenFavotterOpMenuItem.Enabled = false;
10949 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10950 this.RtOpMenuItem.Enabled = false;
10951 this.RtUnOpMenuItem.Enabled = false;
10952 this.QtOpMenuItem.Enabled = false;
10953 this.FavoriteRetweetMenuItem.Enabled = false;
10954 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10958 this.FavOpMenuItem.Enabled = true;
10959 this.UnFavOpMenuItem.Enabled = true;
10960 this.OpenStatusOpMenuItem.Enabled = true;
10961 this.OpenFavotterOpMenuItem.Enabled = true;
10962 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
10966 this.RtOpMenuItem.Enabled = false; //公式RTは無効に
10967 this.RtUnOpMenuItem.Enabled = true;
10968 this.QtOpMenuItem.Enabled = true;
10969 this.FavoriteRetweetMenuItem.Enabled = false; //公式RTは無効に
10970 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
10974 if (_curPost.IsProtect)
10976 this.RtOpMenuItem.Enabled = false;
10977 this.RtUnOpMenuItem.Enabled = false;
10978 this.QtOpMenuItem.Enabled = false;
10979 this.FavoriteRetweetMenuItem.Enabled = false;
10980 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10984 this.RtOpMenuItem.Enabled = true;
10985 this.RtUnOpMenuItem.Enabled = true;
10986 this.QtOpMenuItem.Enabled = true;
10987 this.FavoriteRetweetMenuItem.Enabled = true;
10988 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
10993 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
10995 this.RefreshPrevOpMenuItem.Enabled = true;
10999 this.RefreshPrevOpMenuItem.Enabled = false;
11001 if (!this.ExistCurrentPost
11002 || _curPost.InReplyToStatusId == null)
11004 OpenRepSourceOpMenuItem.Enabled = false;
11008 OpenRepSourceOpMenuItem.Enabled = true;
11010 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11012 OpenRterHomeMenuItem.Enabled = false;
11016 OpenRterHomeMenuItem.Enabled = true;
11019 if (this.ExistCurrentPost)
11021 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11025 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11027 ContextMenuTabProperty_Opening(sender, null);
11030 public Twitter TwitterInstance
11035 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11037 if (this._initialLayout)
11040 int splitterDistance;
11041 switch (this.WindowState)
11043 case FormWindowState.Normal:
11044 splitterDistance = this.SplitContainer3.SplitterDistance;
11046 case FormWindowState.Maximized:
11047 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11048 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11049 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11050 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11056 this._mySpDis3 = splitterDistance;
11057 this.ModifySettingLocal = true;
11060 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11062 if (_statuses.RemovedTab.Count == 0)
11064 UndoRemoveTabMenuItem.Enabled = false;
11068 UndoRemoveTabMenuItem.Enabled = true;
11070 if (ListTab.SelectedTab != null)
11072 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11073 PublicSearchQueryMenuItem.Enabled = true;
11075 PublicSearchQueryMenuItem.Enabled = false;
11079 PublicSearchQueryMenuItem.Enabled = false;
11081 if (!this.ExistCurrentPost)
11083 this.CopySTOTMenuItem.Enabled = false;
11084 this.CopyURLMenuItem.Enabled = false;
11085 this.CopyUserIdStripMenuItem.Enabled = false;
11089 this.CopySTOTMenuItem.Enabled = true;
11090 this.CopyURLMenuItem.Enabled = true;
11091 this.CopyUserIdStripMenuItem.Enabled = true;
11092 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11093 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11097 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11099 SetNotifyIconText();
11102 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11104 var id = _curPost?.ScreenName ?? "";
11106 await this.ShowUserStatus(id);
11109 private async Task doShowUserStatus(string id, bool ShowInputDialog)
11111 TwitterUser user = null;
11113 if (ShowInputDialog)
11115 using (var inputName = new InputTabName())
11117 inputName.FormTitle = "Show UserStatus";
11118 inputName.FormDescription = Properties.Resources.FRMessage1;
11119 inputName.TabName = id;
11121 if (inputName.ShowDialog(this) != DialogResult.OK)
11123 if (string.IsNullOrWhiteSpace(inputName.TabName))
11126 id = inputName.TabName.Trim();
11130 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11132 var cancellationToken = dialog.EnableCancellation();
11136 var task = this.twitterApi.UsersShow(id);
11137 user = await dialog.WaitForAsync(this, task);
11139 catch (WebApiException ex)
11141 if (!cancellationToken.IsCancellationRequested)
11142 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11146 if (cancellationToken.IsCancellationRequested)
11150 await this.doShowUserStatus(user);
11153 private async Task doShowUserStatus(TwitterUser user)
11155 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
11157 var showUserTask = userDialog.ShowUserAsync(user);
11158 userDialog.ShowDialog(this);
11161 this.BringToFront();
11163 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11164 await showUserTask;
11168 internal Task ShowUserStatus(string id, bool ShowInputDialog)
11170 return this.doShowUserStatus(id, ShowInputDialog);
11173 internal Task ShowUserStatus(string id)
11175 return this.doShowUserStatus(id, true);
11178 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
11180 if (_curPost != null)
11182 await this.ShowUserStatus(_curPost.ScreenName, false);
11186 private async void RtCountMenuItem_Click(object sender, EventArgs e)
11188 if (!this.ExistCurrentPost)
11191 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11192 TwitterStatus status;
11194 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11196 var cancellationToken = dialog.EnableCancellation();
11200 var task = this.twitterApi.StatusesShow(statusId);
11201 status = await dialog.WaitForAsync(this, task);
11203 catch (WebApiException ex)
11205 if (!cancellationToken.IsCancellationRequested)
11206 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11210 if (cancellationToken.IsCancellationRequested)
11214 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11217 private HookGlobalHotkey _hookGlobalHotkey;
11220 _hookGlobalHotkey = new HookGlobalHotkey(this);
11222 // この呼び出しは、Windows フォーム デザイナで必要です。
11223 InitializeComponent();
11225 // InitializeComponent() 呼び出しの後で初期化を追加します。
11227 if (!this.DesignMode)
11229 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11230 this.StatusText.Dock = DockStyle.Fill;
11233 this.tweetDetailsView.Owner = this;
11235 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11236 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11237 this.gh.NotifyClicked += GrowlHelper_Callback;
11239 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11240 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11242 this.ImageSelector.Visible = false;
11243 this.ImageSelector.Enabled = false;
11244 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11246 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11248 this.ReplaceAppName();
11249 this.InitializeShortcuts();
11252 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11254 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11257 this.Visible = false;
11259 else if (Form.ActiveForm == null)
11261 this.Visible = true;
11262 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11264 this.BringToFront();
11265 this.StatusText.Focus();
11269 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11271 this.MultiLineMenuItem.PerformClick();
11274 public PostClass CurPost
11276 get { return _curPost; }
11280 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11282 if (ImageSelector.Visible)
11283 ImageSelector.EndSelection();
11285 ImageSelector.BeginSelection();
11288 private void SelectMedia_DragEnter(DragEventArgs e)
11290 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11292 e.Effect = DragDropEffects.Copy;
11295 e.Effect = DragDropEffects.None;
11298 private void SelectMedia_DragDrop(DragEventArgs e)
11301 this.BringToFront();
11302 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11303 StatusText.Focus();
11306 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11308 TimelinePanel.Visible = false;
11309 TimelinePanel.Enabled = false;
11312 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11314 TimelinePanel.Visible = true;
11315 TimelinePanel.Enabled = true;
11316 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11319 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11321 this.AllowDrop = false;
11324 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11326 this.AllowDrop = true;
11329 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11331 if (ImageSelector.Visible)
11333 ModifySettingCommon = true;
11334 SaveConfigsAll(true);
11336 if (ImageSelector.ServiceName.Equals("Twitter"))
11337 this.StatusText_TextChanged(null, null);
11341 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11343 this.StatusText_TextChanged(null, null);
11347 /// StatusTextでCtrl+Vが押下された時の処理
11349 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11351 if (Clipboard.ContainsText())
11353 // clipboardにテキストがある場合は貼り付け処理
11354 this.StatusText.Paste(Clipboard.GetText());
11356 else if (Clipboard.ContainsImage())
11359 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11360 Properties.Resources.PostPictureWarn4,
11361 MessageBoxButtons.OKCancel,
11362 MessageBoxIcon.Question,
11363 MessageBoxDefaultButton.Button2)
11364 == DialogResult.OK)
11366 // clipboardから画像を取得
11367 using (var image = Clipboard.GetImage())
11369 this.ImageSelector.BeginSelection(image);
11376 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11378 using (ListManage form = new ListManage(tw))
11380 form.ShowDialog(this);
11384 public bool ModifySettingCommon { get; set; }
11385 public bool ModifySettingLocal { get; set; }
11386 public bool ModifySettingAtId { get; set; }
11388 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11390 if (this.ExistCurrentPost && !_curPost.IsDm)
11391 RtCountMenuItem.Enabled = true;
11393 RtCountMenuItem.Enabled = false;
11395 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11396 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11398 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11401 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11406 private void CopyUserId()
11408 if (_curPost == null) return;
11409 string clstr = _curPost.ScreenName;
11412 Clipboard.SetDataObject(clstr, false, 5, 100);
11414 catch (Exception ex)
11416 MessageBox.Show(ex.Message);
11420 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11422 if (this.ExistCurrentPost && !_curPost.IsDm)
11426 await this.OpenRelatedTab(this._curPost);
11428 catch (TabException ex)
11430 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11436 /// 指定されたツイートに対する関連発言タブを開きます
11438 /// <param name="statusId">表示するツイートのID</param>
11439 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11440 private async Task OpenRelatedTab(long statusId)
11442 var post = this._statuses[statusId];
11447 post = await this.tw.GetStatusApi(false, statusId);
11449 catch (WebApiException ex)
11451 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11456 await this.OpenRelatedTab(post);
11460 /// 指定されたツイートに対する関連発言タブを開きます
11462 /// <param name="post">表示する対象となるツイート</param>
11463 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11464 private async Task OpenRelatedTab(PostClass post)
11466 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11467 if (tabRelated != null)
11469 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11472 var tabName = this._statuses.MakeTabName("Related Tweets");
11474 tabRelated = new RelatedPostsTabModel(tabName, post);
11475 tabRelated.UnreadManage = false;
11476 tabRelated.Notify = false;
11478 this._statuses.AddTab(tabRelated);
11479 this.AddNewTab(tabRelated, startup: false);
11482 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
11484 tabPage = this.ListTab.TabPages[i];
11485 if (tabName == tabPage.Text)
11487 this.ListTab.SelectedIndex = i;
11492 await this.GetRelatedTweetsAsync(tabRelated);
11494 tabPage = this.ListTab.TabPages.Cast<TabPage>()
11495 .FirstOrDefault(x => x.Text == tabRelated.TabName);
11497 if (tabPage != null)
11499 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11501 var listView = (DetailsListView)tabPage.Tag;
11502 var targetPost = tabRelated.TargetPost;
11503 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11505 if (index != -1 && index < listView.Items.Count)
11507 listView.SelectedIndices.Add(index);
11508 listView.Items[index].Focused = true;
11513 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11515 StringBuilder buf = new StringBuilder();
11516 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11517 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11518 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11519 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11520 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11523 private void tw_UserIdChanged()
11525 this.ModifySettingCommon = true;
11528 #region "Userstream"
11529 private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11533 if (InvokeRequired && !IsDisposed)
11535 Invoke((Action) (async () =>
11537 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11538 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
11540 this.PurgeListViewItemCache();
11541 ((DetailsListView)_curTab.Tag).Update();
11542 if (_curPost != null && _curPost.StatusId == e.StatusId)
11543 await this.DispSelectedPost(true);
11549 catch (ObjectDisposedException)
11553 catch (InvalidOperationException)
11559 private int userStreamsRefreshing = 0;
11561 private async void tw_NewPostFromStream(object sender, EventArgs e)
11563 if (this._cfgCommon.ReadOldPosts)
11565 _statuses.SetReadHomeTab(); //新着時未読クリア
11568 this._statuses.DistributePosts();
11570 if (this._cfgCommon.UserstreamPeriod > 0) return;
11572 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
11573 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
11577 await this.InvokeAsync(() => this.RefreshTimeline())
11578 .ConfigureAwait(false);
11582 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
11587 private void tw_UserStreamStarted(object sender, EventArgs e)
11591 if (InvokeRequired && !IsDisposed)
11593 Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
11597 catch (ObjectDisposedException)
11601 catch (InvalidOperationException)
11606 this.RefreshUserStreamsMenu();
11607 this.MenuItemUserStream.Enabled = true;
11609 StatusLabel.Text = "UserStream Started.";
11612 private void tw_UserStreamStopped(object sender, EventArgs e)
11616 if (InvokeRequired && !IsDisposed)
11618 Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
11622 catch (ObjectDisposedException)
11626 catch (InvalidOperationException)
11631 this.RefreshUserStreamsMenu();
11632 this.MenuItemUserStream.Enabled = true;
11634 StatusLabel.Text = "UserStream Stopped.";
11637 private void RefreshUserStreamsMenu()
11639 if (this.tw.UserStreamActive)
11641 this.MenuItemUserStream.Text = "&UserStream ▶";
11642 this.StopToolStripMenuItem.Text = "&Stop";
11646 this.MenuItemUserStream.Text = "&UserStream ■";
11647 this.StopToolStripMenuItem.Text = "&Start";
11651 private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11655 if (InvokeRequired && !IsDisposed)
11657 Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
11661 catch (ObjectDisposedException)
11665 catch (InvalidOperationException)
11669 var ev = e.EventData;
11670 StatusLabel.Text = "Event: " + ev.Event;
11671 //if (ev.Event == "favorite")
11673 // NotifyFavorite(ev);
11676 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11678 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
11680 this.PurgeListViewItemCache();
11681 ((DetailsListView)_curTab.Tag).Update();
11683 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
11685 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11686 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11691 private void NotifyEvent(Twitter.FormattedEvent ev)
11694 if (BalloonRequired(ev))
11696 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11697 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11698 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11699 StringBuilder title = new StringBuilder();
11700 if (this._cfgCommon.DispUsername)
11702 title.Append(tw.Username);
11703 title.Append(" - ");
11709 title.Append(Application.ProductName);
11710 title.Append(" [");
11711 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11712 title.Append("] by ");
11713 if (!string.IsNullOrEmpty(ev.Username))
11715 title.Append(ev.Username);
11719 //title.Append("");
11722 if (!string.IsNullOrEmpty(ev.Target))
11724 //NotifyIcon1.BalloonTipText = ev.Target;
11729 //NotifyIcon1.BalloonTipText = " ";
11732 //NotifyIcon1.ShowBalloonTip(500);
11733 if (this._cfgCommon.IsUseNotifyGrowl)
11735 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11736 ev.Id.ToString(), title.ToString(), text);
11740 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11741 NotifyIcon1.BalloonTipTitle = title.ToString();
11742 NotifyIcon1.BalloonTipText = text;
11743 NotifyIcon1.ShowBalloonTip(500);
11748 string snd = this._cfgCommon.EventSoundFile;
11749 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
11751 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11755 string dir = Application.StartupPath;
11756 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11758 dir = Path.Combine(dir, "Sounds");
11760 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11772 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11774 MenuItemUserStream.Enabled = false;
11775 if (StopRefreshAllMenuItem.Checked)
11777 StopRefreshAllMenuItem.Checked = false;
11780 if (this.tw.UserStreamActive)
11782 tw.StopUserStream();
11786 tw.StartUserStream();
11790 private static string inputTrack = "";
11792 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11794 if (TrackToolStripMenuItem.Checked)
11796 using (InputTabName inputForm = new InputTabName())
11798 inputForm.TabName = inputTrack;
11799 inputForm.FormTitle = "Input track word";
11800 inputForm.FormDescription = "Track word";
11801 if (inputForm.ShowDialog() != DialogResult.OK)
11803 TrackToolStripMenuItem.Checked = false;
11806 inputTrack = inputForm.TabName.Trim();
11808 if (!inputTrack.Equals(tw.TrackWord))
11810 tw.TrackWord = inputTrack;
11811 this.ModifySettingCommon = true;
11812 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11813 tw.ReconnectUserStream();
11819 tw.ReconnectUserStream();
11821 this.ModifySettingCommon = true;
11824 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11826 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11827 this.ModifySettingCommon = true;
11828 tw.ReconnectUserStream();
11831 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11833 if (evtDialog == null || evtDialog.IsDisposed)
11836 evtDialog = new EventViewerDialog();
11837 evtDialog.Owner = this;
11839 Point pos = evtDialog.Location;
11840 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
11841 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
11842 evtDialog.Location = pos;
11844 evtDialog.EventSource = tw.StoredEvent;
11845 if (!evtDialog.Visible)
11847 evtDialog.Show(this);
11851 evtDialog.Activate();
11853 this.TopMost = this._cfgCommon.AlwaysTop;
11857 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11859 MyCommon._endingFlag = true;
11863 Application.Restart();
11867 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
11871 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
11873 if (!string.IsNullOrEmpty(tw.Username))
11874 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
11877 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11879 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11882 private bool ExistCurrentPost
11886 if (_curPost == null) return false;
11887 if (_curPost.IsDeleted) return false;
11892 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11894 ShowUserTimeline();
11897 private string GetUserIdFromCurPostOrInput(string caption)
11899 var id = _curPost?.ScreenName ?? "";
11901 using (InputTabName inputName = new InputTabName())
11903 inputName.FormTitle = caption;
11904 inputName.FormDescription = Properties.Resources.FRMessage1;
11905 inputName.TabName = id;
11906 if (inputName.ShowDialog() == DialogResult.OK &&
11907 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11909 id = inputName.TabName.Trim();
11919 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11921 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11922 if (!string.IsNullOrEmpty(id))
11924 AddNewTabForUserTimeline(id);
11928 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
11930 string id = GetUserIdFromCurPostOrInput("Show Favstar");
11931 if (!string.IsNullOrEmpty(id))
11933 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
11937 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11939 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
11942 private void TimelineRefreshEnableChange(bool isEnable)
11946 tw.StartUserStream();
11950 tw.StopUserStream();
11952 TimerTimeline.Enabled = isEnable;
11955 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11957 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
11960 private async Task OpenUserAppointUrl()
11962 if (this._cfgCommon.UserAppointUrl != null)
11964 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
11966 if (_curPost != null)
11968 string xUrl = this._cfgCommon.UserAppointUrl;
11969 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
11971 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
11972 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
11974 await this.OpenUriInBrowserAsync(xUrl);
11979 await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
11984 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
11986 await this.OpenUserAppointUrl();
11989 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
11991 if (Form.ActiveForm == null)
11993 this.BeginInvoke((Action) (() =>
11995 this.Visible = true;
11996 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11998 this.BringToFront();
11999 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
12001 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12005 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12011 private void ReplaceAppName()
12013 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12014 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12017 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12019 this.SplitContainer3.Panel2Collapsed = false;
12022 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12024 await this.OpenThumbnailPicture(e.Thumbnail);
12027 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
12029 await this.OpenUriInBrowserAsync(e.ImageUrl);
12032 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
12034 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
12036 await this.OpenUriInBrowserAsync(url);
12039 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
12041 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
12044 private void PostButton_KeyDown(object sender, KeyEventArgs e)
12046 if (e.KeyCode == Keys.Space)
12048 this.JumpUnreadMenuItem_Click(null, null);
12050 e.SuppressKeyPress = true;
12054 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
12056 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
12057 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
12058 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
12059 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
12060 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
12062 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
12065 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
12067 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
12070 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
12072 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
12075 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
12077 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
12080 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
12082 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
12085 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
12087 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
12090 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
12092 if (this._cfgCommon.IconSize == iconSize) return;
12094 var oldIconCol = _iconCol;
12096 this._cfgCommon.IconSize = iconSize;
12097 ApplyListViewIconSize(iconSize);
12099 if (_iconCol != oldIconCol)
12101 foreach (TabPage tp in ListTab.TabPages)
12103 ResetColumns((DetailsListView)tp.Tag);
12107 _curList?.Refresh();
12109 ModifySettingCommon = true;
12112 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
12114 var state = this.LockListSortOrderToolStripMenuItem.Checked;
12115 if (this._cfgCommon.SortOrderLock == state) return;
12117 this._cfgCommon.SortOrderLock = state;
12119 ModifySettingCommon = true;
12122 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
12124 if (!string.IsNullOrEmpty(e.StatusText))
12126 this.StatusLabelUrl.Text = e.StatusText;
12130 this.SetStatusLabelUrl();