1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
28 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
29 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
32 using System.Collections.Concurrent;
33 using System.Collections.Generic;
34 using System.ComponentModel;
35 using System.Diagnostics;
37 using System.Globalization;
42 using System.Net.Http;
43 using System.Reflection;
44 using System.Runtime.InteropServices;
46 using System.Text.RegularExpressions;
47 using System.Threading;
48 using System.Threading.Tasks;
49 using System.Windows.Forms;
51 using OpenTween.Api.DataModel;
52 using OpenTween.Connection;
53 using OpenTween.Models;
54 using OpenTween.OpenTweenCustomControl;
55 using OpenTween.Setting;
56 using OpenTween.Thumbnail;
60 public partial class TweenMain : OTBaseForm
63 private Size _mySize; //画面サイズ
64 private Point _myLoc; //画面位置
65 private int _mySpDis; //区切り位置
66 private int _mySpDis2; //発言欄区切り位置
67 private int _mySpDis3; //プレビュー区切り位置
68 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
69 private bool _iconCol; //1列表示の時true(48サイズのとき)
72 private bool _initial; //true:起動時処理中
73 private bool _initialLayout = true;
74 private bool _ignoreConfigSave; //true:起動時処理中
75 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
76 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
77 private Point _tabMouseDownPoint;
78 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
79 private readonly object _syncObject = new object(); //ロック用
81 private const string detailHtmlFormatHeaderMono =
82 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
83 + "<style type=\"text/css\"><!-- "
84 + "body, p, pre {margin: 0;} "
85 + "pre {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
86 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
87 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
88 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
89 + ".quote-tweet.reply {border-color: #f33;} "
90 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
92 + "</head><body><pre>";
93 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
94 private const string detailHtmlFormatHeaderColor =
95 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
96 + "<style type=\"text/css\"><!-- "
97 + "body, p, pre {margin: 0;} "
98 + "body {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); margin: 0; word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
99 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
100 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
101 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
102 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
103 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
105 + "</head><body><p>";
106 private const string detailHtmlFormatFooterColor = "</p></body></html>";
107 private string detailHtmlFormatHeader;
108 private string detailHtmlFormatFooter;
110 private bool _myStatusError = false;
111 private bool _myStatusOnline = false;
112 private bool soundfileListup = false;
113 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
116 //private SettingToConfig _cfg; //旧
117 internal SettingLocal _cfgLocal;
118 private SettingCommon _cfgCommon;
121 private TwitterApi twitterApi = new TwitterApi();
125 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
128 internal SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
129 private OpenURL UrlDialog = new OpenURL();
130 public AtIdSupplement AtIdSupl; //@id補助
131 public AtIdSupplement HashSupl; //Hashtag補助
132 public HashtagManage HashMgr;
133 private EventViewerDialog evtDialog;
136 private Font _fntUnread; //未読用フォント
137 private Color _clUnread; //未読用文字色
138 private Font _fntReaded; //既読用フォント
139 private Color _clReaded; //既読用文字色
140 private Color _clFav; //Fav用文字色
141 private Color _clOWL; //片思い用文字色
142 private Color _clRetweet; //Retweet用文字色
143 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
144 private Font _fntDetail; //発言詳細部用フォント
145 private Color _clDetail; //発言詳細部用色
146 private Color _clDetailLink; //発言詳細部用リンク文字色
147 private Color _clDetailBackcolor; //発言詳細部用背景色
148 private Color _clSelf; //自分の発言用背景色
149 private Color _clAtSelf; //自分宛返信用背景色
150 private Color _clTarget; //選択発言者の他の発言用背景色
151 private Color _clAtTarget; //選択発言中の返信先用背景色
152 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
153 private Color _clAtTo; //選択発言の唯一@先
154 private Color _clListBackcolor; //リスト部通常発言背景色
155 private Color _clInputBackcolor; //入力欄背景色
156 private Color _clInputFont; //入力欄文字色
157 private Font _fntInputFont; //入力欄フォント
158 private ImageCache IconCache; //アイコン画像リスト
159 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
160 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
161 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
162 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
163 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
164 private Icon MainIcon; //Main.ico 画面左上のアイコン
165 private Icon ReplyIcon; //5g
166 private Icon ReplyIconBlink; //6g
168 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
170 private PostClass _anchorPost;
171 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
173 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
174 private int _hisIdx; //発言履歴カレントインデックス
176 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
177 private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
180 private List<DateTime> _postTimestamps = new List<DateTime>();
181 private List<DateTime> _favTimestamps = new List<DateTime>();
184 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
185 private SolidBrush _brsBackColorMine;
186 private SolidBrush _brsBackColorAt;
187 private SolidBrush _brsBackColorYou;
188 private SolidBrush _brsBackColorAtYou;
189 private SolidBrush _brsBackColorAtFromTarget;
190 private SolidBrush _brsBackColorAtTo;
191 private SolidBrush _brsBackColorNone;
192 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
193 private StringFormat sfTab = new StringFormat();
195 //////////////////////////////////////////////////////////////////////////////////////////////////////////
196 private TabInformations _statuses;
199 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
202 /// キャッシュクリアのために null が代入されることがあるため、
203 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
204 /// 一旦ローカル変数に代入してから参照すること。
206 private ListViewItemCache _listItemCache = null;
208 internal class ListViewItemCache
210 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
211 public ListView TargetList { get; set; }
213 /// <summary>キャッシュする範囲の開始インデックス</summary>
214 public int StartIndex { get; set; }
216 /// <summary>キャッシュする範囲の終了インデックス</summary>
217 public int EndIndex { get; set; }
219 /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
220 public ListViewItem[] ListItem { get; set; }
222 /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
223 public PostClass[] Post { get; set; }
225 /// <summary>キャッシュされたアイテムの件数</summary>
227 => this.EndIndex - this.StartIndex + 1;
229 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
230 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
231 public bool Contains(int index)
232 => index >= this.StartIndex && index <= this.EndIndex;
234 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
235 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
236 public bool IsSupersetOf(int rangeStart, int rangeEnd)
237 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
239 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
240 /// <returns>取得に成功すれば true、それ以外は false</returns>
241 public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
243 if (this.Contains(index))
245 item = this.ListItem[index - this.StartIndex];
246 post = this.Post[index - this.StartIndex];
258 private TabPage _curTab;
259 private int _curItemIndex;
260 private DetailsListView _curList;
261 private PostClass _curPost;
262 private bool _isColumnChanged = false;
264 private const int MAX_WORKER_THREADS = 20;
265 private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
266 private CancellationTokenSource workerCts = new CancellationTokenSource();
267 private IProgress<string> workerProgress;
269 private int UnreadCounter = -1;
270 private int UnreadAtCounter = -1;
272 private string[] ColumnOrgText = new string[9];
273 private string[] ColumnText = new string[9];
275 private bool _DoFavRetweetFlags = false;
276 private bool osResumed = false;
278 //////////////////////////////////////////////////////////////////////////////////////////////////////////
279 private bool _colorize = false;
281 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
283 private string recommendedStatusFooter;
286 private struct urlUndo
288 public string Before;
292 private List<urlUndo> urlUndoBuffer = null;
294 private struct ReplyChain
296 public long OriginalId;
297 public long InReplyToId;
298 public TabPage OriginalTab;
300 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
302 this.OriginalId = originalId;
303 this.InReplyToId = inReplyToId;
304 this.OriginalTab = originalTab;
308 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
309 private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
312 internal enum SEARCHTYPE
319 private class PostingStatus
321 public string status = "";
322 public long? inReplyToId = null;
323 public string inReplyToName = null;
324 public string imageService = ""; //画像投稿サービス名
325 public IMediaItem[] mediaItems = null;
326 public PostingStatus()
329 public PostingStatus(string status, long? replyToId, string replyToName)
331 this.status = status;
332 this.inReplyToId = replyToId;
333 this.inReplyToName = replyToName;
337 private void TweenMain_Activated(object sender, EventArgs e)
339 //画面がアクティブになったら、発言欄の背景色戻す
340 if (StatusText.Focused)
342 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
346 private bool disposed = false;
349 /// 使用中のリソースをすべてクリーンアップします。
351 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
352 protected override void Dispose(bool disposing)
354 base.Dispose(disposing);
361 this.components?.Dispose();
364 SearchDialog.Dispose();
367 NIconAtRed?.Dispose();
368 NIconAtSmoke?.Dispose();
369 foreach (var iconRefresh in this.NIconRefresh)
371 iconRefresh?.Dispose();
375 ReplyIcon?.Dispose();
376 ReplyIconBlink?.Dispose();
377 _listViewImageList.Dispose();
378 _brsHighLight.Dispose();
379 _brsBackColorMine?.Dispose();
380 _brsBackColorAt?.Dispose();
381 _brsBackColorYou?.Dispose();
382 _brsBackColorAtYou?.Dispose();
383 _brsBackColorAtFromTarget?.Dispose();
384 _brsBackColorAtTo?.Dispose();
385 _brsBackColorNone?.Dispose();
386 _brsDeactiveSelection?.Dispose();
390 this.workerCts.Cancel();
392 if (IconCache != null)
394 this.IconCache.CancelAsync();
395 this.IconCache.Dispose();
398 this.thumbnailTokenSource?.Dispose();
401 this.twitterApi.Dispose();
402 this._hookGlobalHotkey.Dispose();
405 // 終了時にRemoveHandlerしておかないとメモリリークする
406 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
407 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
409 this.disposed = true;
412 private void LoadIcons()
414 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
415 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
418 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
421 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
424 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
427 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
429 // タスクトレイ: オフライン時アイコン
430 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
432 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
433 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
434 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
436 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
437 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
438 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
439 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
440 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
442 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
444 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
445 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
446 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
447 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
448 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
450 if (iconReply != null && iconReplyBlink != null)
452 this.ReplyIcon = iconReply;
453 this.ReplyIconBlink = iconReplyBlink;
457 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
458 this.ReplyIconBlink = this.NIconAt;
461 if (iconRefresh1 == null)
463 this.NIconRefresh = new[] {
464 Properties.Resources.Refresh, Properties.Resources.Refresh2,
465 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
468 else if (iconRefresh2 == null)
470 this.NIconRefresh = new[] { iconRefresh1 };
472 else if (iconRefresh3 == null)
474 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
476 else if (iconRefresh4 == null)
478 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
480 else // iconRefresh1 から iconRefresh4 まで全て揃っている
482 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
486 private Icon LoadIcon(string filePath)
488 if (!File.Exists(filePath))
493 return new Icon(filePath);
501 private void InitColumns(ListView list, bool startup)
503 this.InitColumnText();
505 ColumnHeader[] columns = null;
512 new ColumnHeader(), // アイコン
513 new ColumnHeader(), // 本文
516 columns[0].Text = this.ColumnText[0];
517 columns[1].Text = this.ColumnText[2];
521 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
523 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
524 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
525 columns[0].DisplayIndex = 0;
526 columns[1].DisplayIndex = 1;
531 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
533 columns[idx].Width = curListColumn.Width;
534 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
543 new ColumnHeader(), // アイコン
544 new ColumnHeader(), // ニックネーム
545 new ColumnHeader(), // 本文
546 new ColumnHeader(), // 日付
547 new ColumnHeader(), // ユーザID
548 new ColumnHeader(), // 未読
549 new ColumnHeader(), // マーク&プロテクト
550 new ColumnHeader(), // ソース
553 foreach (var i in Enumerable.Range(0, columns.Length))
554 columns[i].Text = this.ColumnText[i];
558 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
560 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
561 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
562 columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
563 columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
564 columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
565 columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
566 columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
567 columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
569 var displayIndex = new[] {
570 this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
571 this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
572 this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
573 this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
576 foreach (var i in Enumerable.Range(0, displayIndex.Length))
578 columns[i].DisplayIndex = displayIndex[i];
584 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
586 columns[idx].Width = curListColumn.Width;
587 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
593 list.Columns.AddRange(columns);
601 foreach (var column in columns)
607 private void InitColumnText()
610 ColumnText[1] = Properties.Resources.AddNewTabText2;
611 ColumnText[2] = Properties.Resources.AddNewTabText3;
612 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
613 ColumnText[4] = Properties.Resources.AddNewTabText5;
616 ColumnText[7] = "Source";
618 ColumnOrgText[0] = "";
619 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
620 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
621 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
622 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
623 ColumnOrgText[5] = "";
624 ColumnOrgText[6] = "";
625 ColumnOrgText[7] = "Source";
628 switch (_statuses.SortMode)
630 case ComparerMode.Nickname: //ニックネーム
633 case ComparerMode.Data: //本文
636 case ComparerMode.Id: //時刻=発言Id
639 case ComparerMode.Name: //名前
642 case ComparerMode.Source: //Source
649 if (_statuses.SortOrder == SortOrder.Descending)
651 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
652 ColumnText[2] = ColumnOrgText[2] + "▾";
656 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
657 ColumnText[2] = ColumnOrgText[2] + "▴";
662 if (_statuses.SortOrder == SortOrder.Descending)
664 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
665 ColumnText[c] = ColumnOrgText[c] + "▾";
669 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
670 ColumnText[c] = ColumnOrgText[c] + "▴";
675 private void InitializeTraceFrag()
678 TraceOutToolStripMenuItem.Checked = true;
679 MyCommon.TraceFlag = true;
681 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
683 TraceOutToolStripMenuItem.Checked = true;
684 MyCommon.TraceFlag = true;
688 private void TweenMain_Load(object sender, EventArgs e)
690 _ignoreConfigSave = true;
691 this.Visible = false;
693 if (MyApplication.StartupOptions.ContainsKey("d"))
694 MyCommon.TraceFlag = true;
696 InitializeTraceFrag();
698 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
700 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
701 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
703 Regex.CacheSize = 100;
706 _statuses = TabInformations.GetInstance();
710 this.Icon = MainIcon; //メインフォーム(TweenMain)
711 NotifyIcon1.Icon = NIconAt; //タスクトレイ
712 TabImage.Images.Add(TabIcon); //タブ見出し
714 //<<<<<<<<<設定関連>>>>>>>>>
718 // 現在の DPI と設定保存時の DPI との比を取得する
719 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
722 var fontUIGlobal = this._cfgLocal.FontUIGlobal;
723 if (fontUIGlobal != null)
725 OTBaseForm.GlobalFont = fontUIGlobal;
726 this.Font = fontUIGlobal;
730 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
732 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
733 this._cfgCommon.TimelinePeriod = 15;
735 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
736 this._cfgCommon.ReplyPeriod = 15;
738 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
739 this._cfgCommon.DMPeriod = 15;
741 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
742 this._cfgCommon.PubSearchPeriod = 30;
744 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
745 this._cfgCommon.UserTimelinePeriod = 15;
747 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
748 this._cfgCommon.ListsPeriod = 15;
751 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
752 this._cfgCommon.CountApi = 60;
753 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
754 this._cfgCommon.CountApiReply = 40;
756 if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
757 this._cfgCommon.MoreCountApi = 200;
758 if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
759 this._cfgCommon.FirstCountApi = 100;
761 if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
762 this._cfgCommon.FavoritesCountApi = 40;
763 if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
764 this._cfgCommon.ListCountApi = 100;
765 if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
766 this._cfgCommon.SearchCountApi = 100;
767 if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
768 this._cfgCommon.UserTimelineCountApi = 20;
770 //廃止サービスが選択されていた場合ux.nuへ読み替え
771 if (this._cfgCommon.AutoShortUrlFirst < 0)
772 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
774 TwitterApiConnection.RestApiHost = this._cfgCommon.TwitterApiHost;
775 this.tw = new Twitter(this.twitterApi);
778 if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
779 tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
783 Networking.Initialize();
785 bool saveRequired = false;
786 bool firstRun = false;
788 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
789 if (string.IsNullOrEmpty(tw.Username))
794 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
795 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
796 string.IsNullOrEmpty(tw.Username))
798 Application.Exit(); //強制終了
804 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
805 Networking.UploadImageTimeout = TimeSpan.FromSeconds(this._cfgCommon.UploadImageTimeout);
806 Networking.SetWebProxy(this._cfgLocal.ProxyType,
807 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
808 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
809 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
811 TwitterApiConnection.RestApiHost = this._cfgCommon.TwitterApiHost;
812 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
813 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
814 tw.TrackWord = this._cfgCommon.TrackWord;
815 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
816 tw.AllAtReply = this._cfgCommon.AllAtReply;
817 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
818 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
819 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
820 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
822 // アクセストークンが有効であるか確認する
823 // ここが Twitter API への最初のアクセスになるようにすること
826 this.tw.VerifyCredentials();
828 catch (WebApiException ex)
830 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
831 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
835 //プロキシ設定等の通信まわりの初期化が済んでから処理する
836 ThumbnailGenerator.InitializeGenerator();
838 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
839 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
840 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
842 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
845 ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
848 AtIdSupl = new AtIdSupplement(SettingManager.AtIdList.AtIdList, "@");
849 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
850 HashMgr = new HashtagManage(HashSupl,
851 _cfgCommon.HashTags.ToArray(),
852 _cfgCommon.HashSelected,
853 _cfgCommon.HashIsPermanent,
854 _cfgCommon.HashIsHead,
855 _cfgCommon.HashIsNotAddToAtReply);
856 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
859 this.IconCache = new ImageCache();
860 this.tweetDetailsView.IconCache = this.IconCache;
863 _fntUnread = this._cfgLocal.FontUnread;
864 _clUnread = this._cfgLocal.ColorUnread;
865 _fntReaded = this._cfgLocal.FontRead;
866 _clReaded = this._cfgLocal.ColorRead;
867 _clFav = this._cfgLocal.ColorFav;
868 _clOWL = this._cfgLocal.ColorOWL;
869 _clRetweet = this._cfgLocal.ColorRetweet;
870 _fntDetail = this._cfgLocal.FontDetail;
871 _clDetail = this._cfgLocal.ColorDetail;
872 _clDetailLink = this._cfgLocal.ColorDetailLink;
873 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
874 _clSelf = this._cfgLocal.ColorSelf;
875 _clAtSelf = this._cfgLocal.ColorAtSelf;
876 _clTarget = this._cfgLocal.ColorTarget;
877 _clAtTarget = this._cfgLocal.ColorAtTarget;
878 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
879 _clAtTo = this._cfgLocal.ColorAtTo;
880 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
881 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
882 _clInputFont = this._cfgLocal.ColorInputFont;
883 _fntInputFont = this._cfgLocal.FontInputFont;
885 _brsBackColorMine = new SolidBrush(_clSelf);
886 _brsBackColorAt = new SolidBrush(_clAtSelf);
887 _brsBackColorYou = new SolidBrush(_clTarget);
888 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
889 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
890 _brsBackColorAtTo = new SolidBrush(_clAtTo);
891 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
892 _brsBackColorNone = new SolidBrush(_clListBackcolor);
894 // StringFormatオブジェクトへの事前設定
895 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
896 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
897 //sf.FormatFlags = StringFormatFlags.LineLimit; //
898 sfTab.Alignment = StringAlignment.Center;
899 sfTab.LineAlignment = StringAlignment.Center;
901 InitDetailHtmlFormat();
903 //Regex statregex = new Regex("^0*");
904 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
906 _history.Add(new PostingStatus());
908 this.inReplyTo = null;
911 SearchDialog.Owner = this;
912 UrlDialog.Owner = this;
915 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
916 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
918 //新着取得時のリストスクロールをするか。trueならスクロールしない
919 ListLockMenuItem.Checked = _cfgCommon.ListLock;
920 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
922 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
923 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
925 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
926 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
929 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
930 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
931 _myLoc = _cfgLocal.FormLocation;
933 if (this.WindowState != FormWindowState.Minimized)
935 this.DesktopLocation = _cfgLocal.FormLocation;
936 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
937 bool outOfScreen = true;
938 if (Screen.AllScreens.Length == 1) //ハングするとの報告
940 foreach (Screen scr in Screen.AllScreens)
942 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
950 this.DesktopLocation = new Point(0, 0);
951 _myLoc = this.DesktopLocation;
955 this.TopMost = this._cfgCommon.AlwaysTop;
956 _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
957 _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
958 if (_cfgLocal.PreviewDistance == -1)
960 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
961 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
962 _cfgLocal.PreviewDistance = _mySpDis3;
966 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
968 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
969 //this.Tween_ClientSizeChanged(this, null);
970 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
971 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
973 StatusText.Font = _fntInputFont;
974 StatusText.ForeColor = _clInputFont;
976 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
977 this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
978 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
980 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
981 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
983 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
984 if (this._cfgCommon.UnreadManage == false)
986 ReadedStripMenuItem.Enabled = false;
987 UnreadStripMenuItem.Enabled = false;
990 //リンク先URL表示部の初期化(画面左下)
991 StatusLabelUrl.Text = "";
993 StatusLabel.Text = "";
994 StatusLabel.AutoToolTip = false;
995 StatusLabel.ToolTipText = "";
997 lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
999 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1000 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1001 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1002 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1004 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1005 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1006 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1007 this.SplitContainer2.Panel2.AccessibleName = "";
1009 ////////////////////////////////////////////////////////////////////////////////
1010 var sortOrder = (SortOrder)_cfgCommon.SortOrder;
1011 var mode = ComparerMode.Id;
1012 switch (_cfgCommon.SortColumn)
1014 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1018 mode = ComparerMode.Id; //Idソートに読み替え
1021 mode = ComparerMode.Nickname;
1024 mode = ComparerMode.Data;
1027 mode = ComparerMode.Id;
1030 mode = ComparerMode.Name;
1033 mode = ComparerMode.Source;
1036 _statuses.SetSortMode(mode, sortOrder);
1037 ////////////////////////////////////////////////////////////////////////////////
1039 ApplyListViewIconSize(this._cfgCommon.IconSize);
1041 //<<<<<<<<タブ関連>>>>>>>
1045 //デフォルトタブの存在チェック、ない場合には追加
1046 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1047 this._statuses.AddTab(new HomeTabModel());
1049 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1050 this._statuses.AddTab(new MentionsTabModel());
1052 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1053 this._statuses.AddTab(new DirectMessagesTabModel());
1055 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1056 this._statuses.AddTab(new FavoritesTabModel());
1058 if (this._statuses.GetTabByType<MuteTabModel>() == null)
1059 this._statuses.AddTab(new MuteTabModel());
1061 foreach (var tab in _statuses.Tabs.Values)
1064 if (tab.TabType == MyCommon.TabUsageType.Mute)
1067 if (!AddNewTab(tab, startup: true))
1068 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1071 _curTab = ListTab.SelectedTab;
1073 _curList = (DetailsListView)_curTab.Tag;
1075 if (this._cfgCommon.TabIconDisp)
1077 ListTab.DrawMode = TabDrawMode.Normal;
1081 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1082 ListTab.DrawItem += ListTab_DrawItem;
1083 ListTab.ImageList = null;
1086 if (this._cfgCommon.HotkeyEnabled)
1089 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1090 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1091 modKey |= HookGlobalHotkey.ModKeys.Alt;
1092 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1093 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1094 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1095 modKey |= HookGlobalHotkey.ModKeys.Shift;
1096 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1097 modKey |= HookGlobalHotkey.ModKeys.Win;
1099 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1102 if (this._cfgCommon.IsUseNotifyGrowl)
1105 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1107 SetMainWindowTitle();
1108 SetNotifyIconText();
1110 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1112 this.Visible = true;
1116 TimerTimeline.AutoReset = true;
1117 TimerTimeline.SynchronizingObject = this;
1119 TimerTimeline.Interval = 1000;
1120 TimerTimeline.Enabled = true;
1122 TimerRefreshIcon.Interval = 200;
1123 TimerRefreshIcon.Enabled = true;
1125 _ignoreConfigSave = false;
1126 this.TweenMain_Resize(null, null);
1127 if (saveRequired) SaveConfigsAll(false);
1129 foreach (var ua in this._cfgCommon.UserAccounts)
1131 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1133 ua.UserId = tw.UserId;
1140 // 初回起動時だけ右下のメニューを目立たせる
1141 HashStripSplitButton.ShowDropDown();
1145 private void InitDetailHtmlFormat()
1147 if (this._cfgCommon.IsMonospace)
1149 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1150 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1154 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1155 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1158 detailHtmlFormatHeader = detailHtmlFormatHeader
1159 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1160 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1161 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1162 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1163 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1164 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1167 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1172 txt = ListTab.TabPages[e.Index].Text;
1179 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1180 if (e.State == DrawItemState.Selected)
1182 e.DrawFocusRectangle();
1187 if (_statuses.Tabs[txt].UnreadCount > 0)
1190 fore = System.Drawing.SystemBrushes.ControlText;
1194 fore = System.Drawing.SystemBrushes.ControlText;
1196 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1199 private void LoadConfig()
1201 SettingManager.LoadAll();
1203 this._cfgCommon = SettingManager.Common;
1204 this._cfgLocal = SettingManager.Local;
1206 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1207 if (_cfgLocal.ScaleDimension.IsEmpty)
1208 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1210 var tabSettings = SettingManager.Tabs;
1211 foreach (var tabSetting in tabSettings.Tabs)
1214 switch (tabSetting.TabType)
1216 case MyCommon.TabUsageType.Home:
1217 tab = new HomeTabModel(tabSetting.TabName);
1219 case MyCommon.TabUsageType.Mentions:
1220 tab = new MentionsTabModel(tabSetting.TabName);
1222 case MyCommon.TabUsageType.DirectMessage:
1223 tab = new DirectMessagesTabModel(tabSetting.TabName);
1225 case MyCommon.TabUsageType.Favorites:
1226 tab = new FavoritesTabModel(tabSetting.TabName);
1228 case MyCommon.TabUsageType.UserDefined:
1229 tab = new FilterTabModel(tabSetting.TabName);
1231 case MyCommon.TabUsageType.UserTimeline:
1232 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1234 case MyCommon.TabUsageType.PublicSearch:
1235 tab = new PublicSearchTabModel(tabSetting.TabName)
1237 SearchWords = tabSetting.SearchWords,
1238 SearchLang = tabSetting.SearchLang,
1241 case MyCommon.TabUsageType.Lists:
1242 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1244 case MyCommon.TabUsageType.Mute:
1245 tab = new MuteTabModel(tabSetting.TabName);
1251 tab.UnreadManage = tabSetting.UnreadManage;
1252 tab.Protected = tabSetting.Protected;
1253 tab.Notify = tabSetting.Notify;
1254 tab.SoundFile = tabSetting.SoundFile;
1256 if (tab.IsDistributableTabType)
1258 var filterTab = (FilterTabModel)tab;
1259 filterTab.FilterArray = tabSetting.FilterArray;
1260 filterTab.FilterModified = false;
1263 if (this._statuses.ContainsTab(tab.TabName))
1264 tab.TabName = this._statuses.MakeTabName("MyTab");
1266 this._statuses.AddTab(tab);
1268 if (_statuses.Tabs.Count == 0)
1270 _statuses.AddTab(new HomeTabModel());
1271 _statuses.AddTab(new MentionsTabModel());
1272 _statuses.AddTab(new DirectMessagesTabModel());
1273 _statuses.AddTab(new FavoritesTabModel());
1277 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1279 if (!TimerTimeline.Enabled) return;
1283 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1285 private static int homeCounter = 0;
1286 private static int mentionCounter = 0;
1287 private static int dmCounter = 0;
1288 private static int pubSearchCounter = 0;
1289 private static int userTimelineCounter = 0;
1290 private static int listsCounter = 0;
1291 private static int usCounter = 0;
1292 private static int ResumeWait = 0;
1293 private static int refreshFollowers = 0;
1295 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1297 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1298 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1299 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1300 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1301 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1302 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1303 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1304 Interlocked.Increment(ref refreshFollowers);
1306 var refreshTasks = new List<Task>();
1309 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1311 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1312 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1313 refreshTasks.Add(this.GetHomeTimelineAsync());
1314 ResetTimers.Timeline = false;
1316 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1318 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1319 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1320 refreshTasks.Add(this.GetReplyAsync());
1321 ResetTimers.Reply = false;
1323 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1325 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1326 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1327 refreshTasks.Add(this.GetDirectMessagesAsync());
1328 ResetTimers.DirectMessage = false;
1330 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1332 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1333 if (!ResetTimers.PublicSearch)
1334 refreshTasks.Add(this.GetPublicSearchAllAsync());
1335 ResetTimers.PublicSearch = false;
1337 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1339 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1340 if (!ResetTimers.UserTimeline)
1341 refreshTasks.Add(this.GetUserTimelineAllAsync());
1342 ResetTimers.UserTimeline = false;
1344 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1346 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1347 if (!ResetTimers.Lists)
1348 refreshTasks.Add(this.GetListTimelineAllAsync());
1349 ResetTimers.Lists = false;
1351 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1353 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1354 if (this.tw.UserStreamActive)
1355 this.RefreshTimeline();
1356 ResetTimers.UserStream = false;
1358 if (refreshFollowers > 6 * 3600)
1360 Interlocked.Exchange(ref refreshFollowers, 0);
1361 refreshTasks.AddRange(new[]
1363 this.doGetFollowersMenu(),
1364 this.RefreshNoRetweetIdsAsync(),
1365 this.RefreshTwitterConfigurationAsync(),
1370 Interlocked.Increment(ref ResumeWait);
1371 if (ResumeWait > 30)
1374 Interlocked.Exchange(ref ResumeWait, 0);
1375 refreshTasks.AddRange(new[]
1377 this.GetHomeTimelineAsync(),
1378 this.GetReplyAsync(),
1379 this.GetDirectMessagesAsync(),
1380 this.GetPublicSearchAllAsync(),
1381 this.GetUserTimelineAllAsync(),
1382 this.GetListTimelineAllAsync(),
1383 this.doGetFollowersMenu(),
1384 this.RefreshTwitterConfigurationAsync(),
1389 await Task.WhenAll(refreshTasks);
1392 private void RefreshTimeline()
1394 var curTabModel = this._statuses.Tabs[this._curTab.Text];
1396 // 現在表示中のタブのスクロール位置を退避
1397 var curListScroll = this.SaveListViewScroll(this._curList, curTabModel);
1399 // 各タブのリスト上の選択位置などを退避
1400 var listSelections = this.SaveListViewSelection();
1403 PostClass[] notifyPosts;
1406 bool newMentionOrDm;
1408 addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1410 if (MyCommon._endingFlag) return;
1413 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1415 var listView = (DetailsListView)tabPage.Tag;
1416 var tabModel = this._statuses.Tabs[tabPage.Text];
1418 if (listView.VirtualListSize != tabModel.AllCount || isDelete)
1420 using (ControlTransaction.Update(listView))
1422 if (listView == this._curList)
1423 this.PurgeListViewItemCache();
1428 listView.VirtualListSize = tabModel.AllCount;
1430 catch (NullReferenceException ex)
1432 // WinForms 内部で ListView.set_TopItem が発生させている例外
1433 // https://ja.osdn.net/ticket/browse.php?group_id=6526&tid=36588
1434 MyCommon.TraceOut(ex, $"TabType: {tabModel.TabType}, Count: {tabModel.AllCount}, ListSize: {listView.VirtualListSize}");
1438 this.RestoreListViewSelection(listView, tabModel, listSelections[tabModel.TabName]);
1445 if (this._cfgCommon.TabIconDisp)
1447 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1449 var tabModel = this._statuses.Tabs[tabPage.Text];
1450 if (tabModel.UnreadCount > 0 && tabPage.ImageIndex != 0)
1451 tabPage.ImageIndex = 0; // 未読アイコン
1456 this.ListTab.Refresh();
1461 this.RestoreListViewScroll(this._curList, curTabModel, curListScroll);
1464 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1466 SetMainWindowTitle();
1467 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1469 HashSupl.AddRangeItem(tw.GetHashList());
1473 internal struct ListViewScroll
1475 public ScrollLockMode ScrollLockMode { get; set; }
1476 public long? TopItemStatusId { get; set; }
1479 internal enum ScrollLockMode
1481 /// <summary>固定しない</summary>
1484 /// <summary>最上部に固定する</summary>
1487 /// <summary>最下部に固定する</summary>
1490 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1495 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1497 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1499 var listScroll = new ListViewScroll
1501 ScrollLockMode = this.GetScrollLockMode(listView),
1504 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1506 var topItemIndex = listView.TopItem?.Index ?? -1;
1507 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
1508 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItemIndex);
1514 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1516 if (this._statuses.SortMode == ComparerMode.Id)
1518 if (this._statuses.SortOrder == SortOrder.Ascending)
1521 if (this.ListLockMenuItem.Checked)
1522 return ScrollLockMode.None;
1524 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1527 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1528 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1529 return ScrollLockMode.FixedToBottom;
1531 return ScrollLockMode.None;
1536 if (this.ListLockMenuItem.Checked)
1537 return ScrollLockMode.FixedToItem;
1539 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1540 var topItem = listView.TopItem;
1541 if (topItem == null || topItem.Index == 0)
1542 return ScrollLockMode.FixedToTop;
1544 return ScrollLockMode.FixedToItem;
1549 return ScrollLockMode.FixedToItem;
1553 internal struct ListViewSelection
1555 public long[] SelectedStatusIds { get; set; }
1556 public long? SelectionMarkStatusId { get; set; }
1557 public long? FocusedStatusId { get; set; }
1561 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1563 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1565 var listsDict = new Dictionary<string, ListViewSelection>();
1567 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1569 var listView = (DetailsListView)tabPage.Tag;
1570 var tab = _statuses.Tabs[tabPage.Text];
1572 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1579 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1581 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1583 if (listView.VirtualListSize == 0)
1585 return new ListViewSelection
1587 SelectedStatusIds = new long[0],
1588 SelectionMarkStatusId = null,
1589 FocusedStatusId = null,
1593 return new ListViewSelection
1595 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1596 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1597 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1601 private long[] GetSelectedStatusIds(DetailsListView listView, TabModel tab)
1603 var selectedIndices = listView.SelectedIndices;
1604 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1605 return tab.GetStatusIdAt(selectedIndices.Cast<int>());
1610 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1612 var index = listView.FocusedItem?.Index ?? -1;
1614 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1617 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1619 var index = listView.SelectionMark;
1621 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1625 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1627 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1629 if (listView.VirtualListSize == 0)
1632 switch (listScroll.ScrollLockMode)
1634 case ScrollLockMode.FixedToTop:
1635 listView.EnsureVisible(0);
1637 case ScrollLockMode.FixedToBottom:
1638 listView.EnsureVisible(listView.VirtualListSize - 1);
1640 case ScrollLockMode.FixedToItem:
1641 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1643 listView.TopItem = listView.Items[topIndex];
1645 case ScrollLockMode.None:
1652 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1654 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1656 // status_id から ListView 上のインデックスに変換
1657 int[] selectedIndices = null;
1658 if (listSelection.SelectedStatusIds != null)
1659 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1661 var focusedIndex = -1;
1662 if (listSelection.FocusedStatusId != null)
1663 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1665 var selectionMarkIndex = -1;
1666 if (listSelection.SelectionMarkStatusId != null)
1667 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1669 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1672 private bool BalloonRequired()
1674 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1675 ev.Eventtype = MyCommon.EVENTTYPE.None;
1677 return BalloonRequired(ev);
1680 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1682 if (type == MyCommon.EVENTTYPE.None)
1685 if (!this._cfgCommon.EventNotifyEnabled)
1688 return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1691 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1696 return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1699 private bool BalloonRequired(Twitter.FormattedEvent ev)
1704 if (NativeMethods.IsScreenSaverRunning())
1708 if (!this.NewPostPopMenuItem.Checked)
1710 // 「新着通知が無効でもイベントを通知する」にも該当しない
1711 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1715 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1716 if (this._cfgCommon.LimitBalloon)
1718 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1722 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1725 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1727 if (this._cfgCommon.ReadOwnPost)
1729 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1734 if (BalloonRequired())
1736 if (notifyPosts != null && notifyPosts.Length > 0)
1738 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1739 if (this._cfgCommon.IsUseNotifyGrowl)
1741 StringBuilder sb = new StringBuilder();
1745 foreach (PostClass post in notifyPosts)
1747 if (!(notifyPosts.Length > 3))
1753 if (post.IsReply && !post.IsExcludeReply) reply = true;
1754 if (post.IsDm) dm = true;
1755 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1756 switch (this._cfgCommon.NameBalloon)
1758 case MyCommon.NameBalloonEnum.UserID:
1759 sb.Append(post.ScreenName).Append(" : ");
1761 case MyCommon.NameBalloonEnum.NickName:
1762 sb.Append(post.Nickname).Append(" : ");
1765 sb.Append(post.TextFromApi);
1766 if (notifyPosts.Length > 3)
1768 if (notifyPosts.Last() != post) continue;
1771 StringBuilder title = new StringBuilder();
1772 GrowlHelper.NotifyType nt;
1773 if (this._cfgCommon.DispUsername)
1775 title.Append(tw.Username);
1776 title.Append(" - ");
1784 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1785 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1786 title.Append(Application.ProductName);
1787 title.Append(" [DM] ");
1788 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1789 nt = GrowlHelper.NotifyType.DirectMessage;
1793 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1794 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1795 title.Append(Application.ProductName);
1796 title.Append(" [Reply!] ");
1797 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1798 nt = GrowlHelper.NotifyType.Reply;
1802 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1803 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1804 title.Append(Application.ProductName);
1806 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1807 nt = GrowlHelper.NotifyType.Notify;
1809 string bText = sb.ToString();
1810 if (string.IsNullOrEmpty(bText)) return;
1812 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1813 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1818 StringBuilder sb = new StringBuilder();
1821 foreach (PostClass post in notifyPosts)
1823 if (post.IsReply && !post.IsExcludeReply) reply = true;
1824 if (post.IsDm) dm = true;
1825 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1826 switch (this._cfgCommon.NameBalloon)
1828 case MyCommon.NameBalloonEnum.UserID:
1829 sb.Append(post.ScreenName).Append(" : ");
1831 case MyCommon.NameBalloonEnum.NickName:
1832 sb.Append(post.Nickname).Append(" : ");
1835 sb.Append(post.TextFromApi);
1838 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1839 StringBuilder title = new StringBuilder();
1841 if (this._cfgCommon.DispUsername)
1843 title.Append(tw.Username);
1844 title.Append(" - ");
1852 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1853 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1854 ntIcon = ToolTipIcon.Warning;
1855 title.Append(Application.ProductName);
1856 title.Append(" [DM] ");
1857 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1861 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1862 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1863 ntIcon = ToolTipIcon.Warning;
1864 title.Append(Application.ProductName);
1865 title.Append(" [Reply!] ");
1866 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1870 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1871 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1872 ntIcon = ToolTipIcon.Info;
1873 title.Append(Application.ProductName);
1875 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1877 string bText = sb.ToString();
1878 if (string.IsNullOrEmpty(bText)) return;
1879 //NotifyIcon1.BalloonTipText = sb.ToString();
1880 //NotifyIcon1.ShowBalloonTip(500);
1881 NotifyIcon1.BalloonTipTitle = title.ToString();
1882 NotifyIcon1.BalloonTipText = bText;
1883 NotifyIcon1.BalloonTipIcon = ntIcon;
1884 NotifyIcon1.ShowBalloonTip(500);
1890 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1894 string dir = Application.StartupPath;
1895 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1897 dir = Path.Combine(dir, "Sounds");
1899 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1909 //mentions新着時に画面ブリンク
1910 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1912 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1916 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1918 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1920 _curItemIndex = _curList.SelectedIndices[0];
1921 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1925 this._curPost = GetCurTabPost(_curItemIndex);
1927 catch (ArgumentException)
1932 this.PushSelectPostChain();
1934 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1936 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1942 private void ChangeCacheStyleRead(bool Read, int Index)
1944 var tabInfo = _statuses.Tabs[_curTab.Text];
1945 //Read:true=既読 false=未読
1946 //未読管理していなかったら既読として扱う
1947 if (!tabInfo.UnreadManage ||
1948 !this._cfgCommon.UnreadManage) Read = true;
1950 var listCache = this._listItemCache;
1951 if (listCache == null)
1954 // キャッシュに含まれていないアイテムは対象外
1957 if (!listCache.TryGetValue(Index, out itm, out post))
1960 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1963 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1970 Item.SubItems[5].Text = "";
1975 Item.SubItems[5].Text = "★";
1981 else if (Post.RetweetedId != null)
1983 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1985 else if (Read || !this._cfgCommon.UseUnreadStyle)
1990 if (DList == null || Item.Index == -1)
1992 Item.ForeColor = cl;
1993 if (this._cfgCommon.UseUnreadStyle)
1999 if (this._cfgCommon.UseUnreadStyle)
2000 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2002 DList.ChangeItemForeColor(Item.Index, cl);
2003 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2007 private void ColorizeList()
2009 //Index:更新対象のListviewItem.Index。Colorを返す。
2010 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2013 _post = _anchorPost;
2017 if (_post == null) return;
2019 var listCache = this._listItemCache;
2020 if (listCache == null)
2023 var index = listCache.StartIndex;
2024 foreach (var cachedPost in listCache.Post)
2026 var backColor = this.JudgeColor(_post, cachedPost);
2027 this._curList.ChangeItemBackColor(index++, backColor);
2031 private void ColorizeList(ListViewItem Item, int Index)
2033 //Index:更新対象のListviewItem.Index。Colorを返す。
2034 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2037 _post = _anchorPost;
2041 PostClass tPost = GetCurTabPost(Index);
2043 if (_post == null) return;
2045 if (Item.Index == -1)
2046 Item.BackColor = JudgeColor(_post, tPost);
2048 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2051 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2054 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2057 else if (TargetPost.IsMe)
2060 else if (TargetPost.IsReply)
2063 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2065 cl = _clAtFromTarget;
2066 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2069 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2074 cl = _clListBackcolor;
2079 private async void PostButton_Click(object sender, EventArgs e)
2081 if (StatusText.Text.Trim().Length == 0)
2083 if (!ImageSelector.Enabled)
2085 await this.DoRefresh();
2090 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2092 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2094 MessageBoxButtons.YesNoCancel,
2095 MessageBoxIcon.Question);
2098 case DialogResult.Yes:
2099 StatusText.Text = "";
2100 await this.doReTweetOfficial(false);
2102 case DialogResult.Cancel:
2107 var inReplyToStatusId = this.inReplyTo?.Item1;
2108 var inReplyToScreenName = this.inReplyTo?.Item2;
2109 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2111 if (this._cfgCommon.Nicoms)
2113 StatusText.SelectionStart = StatusText.Text.Length;
2114 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2116 //if (SettingDialog.UrlConvertAuto)
2118 // StatusText.SelectionStart = StatusText.Text.Length;
2119 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2121 //else if (SettingDialog.Nicoms)
2123 // StatusText.SelectionStart = StatusText.Text.Length;
2124 // UrlConvert(UrlConverter.Nicoms);
2126 StatusText.SelectionStart = StatusText.Text.Length;
2127 CheckReplyTo(StatusText.Text);
2129 var statusText = this.FormatStatusText(this.StatusText.Text);
2131 if (this.GetRestStatusCount(statusText) < 0)
2133 // 文字数制限を超えているが強制的に投稿するか
2134 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2135 if (ret != DialogResult.OK)
2139 var status = new PostingStatus();
2140 status.status = statusText;
2142 status.inReplyToId = this.inReplyTo?.Item1;
2143 status.inReplyToName = this.inReplyTo?.Item2;
2144 if (ImageSelector.Visible)
2147 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2151 this.inReplyTo = null;
2152 StatusText.Text = "";
2153 _history.Add(new PostingStatus());
2154 _hisIdx = _history.Count - 1;
2155 if (!ToolStripFocusLockMenuItem.Checked)
2156 ((Control)ListTab.SelectedTab.Tag).Focus();
2157 urlUndoBuffer = null;
2158 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2161 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2163 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2164 await this.OpenUriInBrowserAsync(tmp);
2167 await this.PostMessageAsync(status);
2170 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2172 MyCommon._endingFlag = true;
2176 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2178 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2180 //_endingFlag=false:フォームの×ボタン
2182 this.Visible = false;
2186 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2187 _ignoreConfigSave = true;
2188 MyCommon._endingFlag = true;
2189 TimerTimeline.Enabled = false;
2190 TimerRefreshIcon.Enabled = false;
2194 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2196 this.Visible = true;
2197 if (this.WindowState == FormWindowState.Minimized)
2199 this.WindowState = FormWindowState.Normal;
2202 this.BringToFront();
2205 private static int errorCount = 0;
2207 private static bool CheckAccountValid()
2209 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2215 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2224 private Task GetHomeTimelineAsync()
2226 return this.GetHomeTimelineAsync(loadMore: false);
2229 private async Task GetHomeTimelineAsync(bool loadMore)
2231 await this.workerSemaphore.WaitAsync();
2235 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
2236 await homeTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2238 this.RefreshTimeline();
2240 catch (WebApiException ex)
2242 this._myStatusError = true;
2243 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2247 this.workerSemaphore.Release();
2251 private Task GetReplyAsync()
2253 return this.GetReplyAsync(loadMore: false);
2256 private async Task GetReplyAsync(bool loadMore)
2258 await this.workerSemaphore.WaitAsync();
2262 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
2263 await replyTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2265 this.RefreshTimeline();
2267 catch (WebApiException ex)
2269 this._myStatusError = true;
2270 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2274 this.workerSemaphore.Release();
2278 private Task GetDirectMessagesAsync()
2280 return this.GetDirectMessagesAsync(loadMore: false);
2283 private async Task GetDirectMessagesAsync(bool loadMore)
2285 await this.workerSemaphore.WaitAsync();
2289 var dmTab = this._statuses.GetTabByType<DirectMessagesTabModel>();
2290 await dmTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2292 this.RefreshTimeline();
2294 catch (WebApiException ex)
2296 this._myStatusError = true;
2297 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2301 this.workerSemaphore.Release();
2305 private Task GetFavoritesAsync()
2307 return this.GetFavoritesAsync(loadMore: false);
2310 private async Task GetFavoritesAsync(bool loadMore)
2312 await this.workerSemaphore.WaitAsync();
2316 var favTab = this._statuses.GetTabByType<FavoritesTabModel>();
2317 await favTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2319 this.RefreshTimeline();
2321 catch (WebApiException ex)
2323 this._myStatusError = true;
2324 this.StatusLabel.Text = ex.Message;
2328 this.workerSemaphore.Release();
2332 private Task GetPublicSearchAllAsync()
2334 var tabs = this._statuses.GetTabsByType<PublicSearchTabModel>();
2336 return this.GetPublicSearchAsync(tabs, loadMore: false);
2339 private Task GetPublicSearchAsync(PublicSearchTabModel tab)
2341 return this.GetPublicSearchAsync(tab, loadMore: false);
2344 private Task GetPublicSearchAsync(PublicSearchTabModel tab, bool loadMore)
2346 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2349 private async Task GetPublicSearchAsync(IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2351 await this.workerSemaphore.WaitAsync();
2355 foreach (var tab in tabs)
2359 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2361 catch (WebApiException ex)
2363 this._myStatusError = true;
2364 this.StatusLabel.Text = $"Err:{ex.Message}(GetSearch)";
2368 this.RefreshTimeline();
2372 this.workerSemaphore.Release();
2376 private Task GetUserTimelineAllAsync()
2378 var tabs = this._statuses.GetTabsByType<UserTimelineTabModel>();
2380 return this.GetUserTimelineAsync(tabs, loadMore: false);
2383 private Task GetUserTimelineAsync(UserTimelineTabModel tab)
2385 return this.GetUserTimelineAsync(tab, loadMore: false);
2388 private Task GetUserTimelineAsync(UserTimelineTabModel tab, bool loadMore)
2390 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2393 private async Task GetUserTimelineAsync(IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2395 await this.workerSemaphore.WaitAsync();
2399 foreach (var tab in tabs)
2403 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2405 catch (WebApiException ex)
2407 this._myStatusError = true;
2408 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2412 this.RefreshTimeline();
2416 this.workerSemaphore.Release();
2420 private Task GetListTimelineAllAsync()
2422 var tabs = this._statuses.GetTabsByType<ListTimelineTabModel>();
2424 return this.GetListTimelineAsync(tabs, loadMore: false);
2427 private Task GetListTimelineAsync(ListTimelineTabModel tab)
2429 return this.GetListTimelineAsync(tab, loadMore: false);
2432 private Task GetListTimelineAsync(ListTimelineTabModel tab, bool loadMore)
2434 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2437 private async Task GetListTimelineAsync(IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2439 await this.workerSemaphore.WaitAsync();
2443 foreach (var tab in tabs)
2447 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2449 catch (WebApiException ex)
2451 this._myStatusError = true;
2452 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2456 this.RefreshTimeline();
2460 this.workerSemaphore.Release();
2464 private async Task GetRelatedTweetsAsync(RelatedPostsTabModel tab)
2466 await this.workerSemaphore.WaitAsync();
2470 await tab.RefreshAsync(this.tw, this._initial, this.workerProgress);
2472 this.RefreshTimeline();
2474 catch (WebApiException ex)
2476 this._myStatusError = true;
2477 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2481 this.workerSemaphore.Release();
2485 private async Task FavAddAsync(long statusId, TabModel tab)
2487 await this.workerSemaphore.WaitAsync();
2491 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2493 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2495 catch (WebApiException ex)
2497 this._myStatusError = true;
2498 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2502 this.workerSemaphore.Release();
2506 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2508 if (ct.IsCancellationRequested)
2511 if (!CheckAccountValid())
2512 throw new WebApiException("Auth error. Check your account");
2515 if (!tab.Posts.TryGetValue(statusId, out post))
2521 await Task.Run(async () =>
2523 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2527 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2529 .ConfigureAwait(false);
2531 if (this._cfgCommon.RestrictFavCheck)
2533 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2534 .ConfigureAwait(false);
2536 if (status.Favorited != true)
2537 throw new WebApiException("NG(Restricted?)");
2540 this._favTimestamps.Add(DateTime.Now);
2543 if (this._statuses.ContainsKey(statusId))
2545 var postTl = this._statuses[statusId];
2546 postTl.IsFav = true;
2548 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2549 favTab.AddPostQueue(postTl);
2552 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2553 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2555 if (tb.Contains(statusId))
2556 tb.Posts[statusId].IsFav = true;
2559 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2561 catch (WebApiException)
2563 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2568 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2569 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2571 if (this._favTimestamps[i] < oneHour)
2572 this._favTimestamps.RemoveAt(i);
2575 this._statuses.DistributePosts();
2578 if (ct.IsCancellationRequested)
2581 this.RefreshTimeline();
2583 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2585 using (ControlTransaction.Update(this._curList))
2587 var idx = tab.IndexOf(statusId);
2589 this.ChangeCacheStyleRead(post.IsRead, idx);
2592 if (statusId == this._curPost.StatusId)
2593 await this.DispSelectedPost(true); // 選択アイテム再表示
2597 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2599 await this.workerSemaphore.WaitAsync();
2603 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2605 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2607 catch (WebApiException ex)
2609 this._myStatusError = true;
2610 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2614 this.workerSemaphore.Release();
2618 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2620 if (ct.IsCancellationRequested)
2623 if (!CheckAccountValid())
2624 throw new WebApiException("Auth error. Check your account");
2626 var successIds = new List<long>();
2628 await Task.Run(async () =>
2632 var failedCount = 0;
2633 foreach (var statusId in statusIds)
2637 var post = tab.Posts[statusId];
2639 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2646 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2648 .ConfigureAwait(false);
2650 catch (WebApiException)
2656 successIds.Add(statusId);
2657 post.IsFav = false; // リスト再描画必要
2659 if (this._statuses.ContainsKey(statusId))
2661 this._statuses[statusId].IsFav = false;
2664 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2665 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2667 if (tb.Contains(statusId))
2668 tb.Posts[statusId].IsFav = false;
2673 if (ct.IsCancellationRequested)
2676 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2677 foreach (var statusId in successIds)
2679 // ツイートが削除された訳ではないので IsDeleted はセットしない
2680 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2683 this.RefreshTimeline();
2685 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2687 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2693 using (ControlTransaction.Update(this._curList))
2695 foreach (var statusId in successIds)
2697 var idx = tab.IndexOf(statusId);
2701 var post = tab.Posts[statusId];
2702 this.ChangeCacheStyleRead(post.IsRead, idx);
2706 if (successIds.Contains(this._curPost.StatusId))
2707 await this.DispSelectedPost(true); // 選択アイテム再表示
2712 private async Task PostMessageAsync(PostingStatus status)
2714 await this.workerSemaphore.WaitAsync();
2718 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2720 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
2722 catch (WebApiException ex)
2724 this._myStatusError = true;
2725 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2729 this.workerSemaphore.Release();
2733 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
2735 if (ct.IsCancellationRequested)
2738 if (!CheckAccountValid())
2739 throw new WebApiException("Auth error. Check your account");
2741 p.Report("Posting...");
2747 await Task.Run(async () =>
2749 if (status.mediaItems == null || status.mediaItems.Length == 0)
2751 await this.tw.PostStatus(status.status, status.inReplyToId)
2752 .ConfigureAwait(false);
2756 var service = ImageSelector.GetService(status.imageService);
2757 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
2758 .ConfigureAwait(false);
2762 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2764 catch (WebApiException ex)
2766 // 処理は中断せずエラーの表示のみ行う
2767 errMsg = $"Err:{ex.Message}(PostMessage)";
2769 this._myStatusError = true;
2771 catch (UnauthorizedAccessException ex)
2773 // アップロード対象のファイルが開けなかった場合など
2774 errMsg = $"Err:{ex.Message}(PostMessage)";
2776 this._myStatusError = true;
2780 // 使い終わった MediaItem は破棄する
2781 if (status.mediaItems != null)
2783 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
2785 disposableItem.Dispose();
2790 if (ct.IsCancellationRequested)
2793 if (!string.IsNullOrEmpty(errMsg) &&
2794 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2795 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2797 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, status.status);
2799 var ret = MessageBox.Show(
2801 "Failed to update status",
2802 MessageBoxButtons.RetryCancel,
2803 MessageBoxIcon.Question);
2805 if (ret == DialogResult.Retry)
2807 await this.PostMessageAsync(status);
2811 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2812 if (this.ToolStripFocusLockMenuItem.Checked)
2813 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2818 this._postTimestamps.Add(DateTime.Now);
2820 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2821 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2823 if (this._postTimestamps[i] < oneHour)
2824 this._postTimestamps.RemoveAt(i);
2827 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2829 this.HashMgr.ClearHashtag();
2830 this.HashStripSplitButton.Text = "#[-]";
2831 this.HashToggleMenuItem.Checked = false;
2832 this.HashToggleToolStripMenuItem.Checked = false;
2835 this.SetMainWindowTitle();
2837 if (this._cfgCommon.PostAndGet)
2839 if (this.tw.UserStreamActive)
2840 this.RefreshTimeline();
2842 await this.GetHomeTimelineAsync();
2846 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2848 await this.workerSemaphore.WaitAsync();
2852 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2854 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2856 if (this._cfgCommon.PostAndGet && !this.tw.UserStreamActive)
2857 await this.GetHomeTimelineAsync();
2859 catch (WebApiException ex)
2861 this._myStatusError = true;
2862 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2866 this.workerSemaphore.Release();
2870 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2872 if (ct.IsCancellationRequested)
2875 if (!CheckAccountValid())
2876 throw new WebApiException("Auth error. Check your account");
2879 if (!this._cfgCommon.UnreadManage)
2882 read = this._initial && this._cfgCommon.Read;
2884 p.Report("Posting...");
2886 foreach (var statusId in statusIds)
2888 await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2891 if (ct.IsCancellationRequested)
2894 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2896 this._postTimestamps.Add(DateTime.Now);
2898 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2899 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2901 if (this._postTimestamps[i] < oneHour)
2902 this._postTimestamps.RemoveAt(i);
2906 private async Task RefreshFollowerIdsAsync()
2908 await this.workerSemaphore.WaitAsync();
2911 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2913 await this.tw.RefreshFollowerIds();
2915 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2917 this.RefreshTimeline();
2918 this.PurgeListViewItemCache();
2919 this._curList?.Refresh();
2921 catch (WebApiException ex)
2923 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2927 this.workerSemaphore.Release();
2931 private async Task RefreshNoRetweetIdsAsync()
2933 await this.workerSemaphore.WaitAsync();
2936 await this.tw.RefreshNoRetweetIds();
2938 this.StatusLabel.Text = "NoRetweetIds refreshed";
2940 catch (WebApiException ex)
2942 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2946 this.workerSemaphore.Release();
2950 private async Task RefreshBlockIdsAsync()
2952 await this.workerSemaphore.WaitAsync();
2955 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2957 await this.tw.RefreshBlockIds();
2959 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2961 catch (WebApiException ex)
2963 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2967 this.workerSemaphore.Release();
2971 private async Task RefreshTwitterConfigurationAsync()
2973 await this.workerSemaphore.WaitAsync();
2976 await this.tw.RefreshConfiguration();
2978 if (this.tw.Configuration.PhotoSizeLimit != 0)
2980 foreach (var service in this.ImageSelector.GetServices())
2982 service.UpdateTwitterConfiguration(this.tw.Configuration);
2986 this.PurgeListViewItemCache();
2988 this._curList?.Refresh();
2990 catch (WebApiException ex)
2992 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2996 this.workerSemaphore.Release();
3000 private async Task RefreshMuteUserIdsAsync()
3002 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3006 await tw.RefreshMuteUserIdsAsync();
3008 catch (WebApiException ex)
3010 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3014 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3017 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3019 if (e.Button == MouseButtons.Left)
3021 this.Visible = true;
3022 if (this.WindowState == FormWindowState.Minimized)
3024 this.WindowState = _formWindowState;
3027 this.BringToFront();
3031 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3033 switch (this._cfgCommon.ListDoubleClickAction)
3036 MakeReplyOrDirectStatus();
3039 await this.FavoriteChange(true);
3042 if (_curPost != null)
3043 await this.ShowUserStatus(_curPost.ScreenName, false);
3049 ShowRelatedStatusesMenuItem_Click(null, null);
3052 MoveToHomeToolStripMenuItem_Click(null, null);
3055 StatusOpenMenuItem_Click(null, null);
3063 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3065 await this.FavoriteChange(true);
3068 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3070 await this.FavoriteChange(false);
3074 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3076 await this.FavoritesRetweetOfficial();
3079 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3081 await this.FavoritesRetweetUnofficial();
3084 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3087 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3090 //trueでFavAdd,falseでFavRemove
3091 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3092 || !this.ExistCurrentPost) return;
3094 if (this._curList.SelectedIndices.Count > 1)
3099 // https://support.twitter.com/articles/76915#favoriting
3100 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3101 _DoFavRetweetFlags = false;
3106 if (multiFavoriteChangeDialogEnable)
3108 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3109 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3110 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3112 if (confirm == DialogResult.Cancel)
3120 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3121 if (selectedPost.IsFav)
3123 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3127 await this.FavAddAsync(selectedPost.StatusId, tab);
3131 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3132 .Select(x => this.GetCurTabPost(x))
3133 .Where(x => x.IsFav);
3135 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3136 if (statusIds.Length == 0)
3138 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3142 await this.FavRemoveAsync(statusIds, tab);
3146 private PostClass GetCurTabPost(int Index)
3148 var listCache = this._listItemCache;
3149 if (listCache != null)
3153 if (listCache.TryGetValue(Index, out item, out post))
3157 return _statuses.Tabs[_curTab.Text][Index];
3160 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3162 if (_curList.SelectedIndices.Count > 0)
3163 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3164 else if (_curList.SelectedIndices.Count == 0)
3165 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3168 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3170 if (_curList.SelectedIndices.Count > 0)
3171 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3174 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3176 if ((!_initialLayout) && this.Visible)
3178 if (this.WindowState == FormWindowState.Normal)
3180 _mySize = this.ClientSize;
3181 _mySpDis = this.SplitContainer1.SplitterDistance;
3182 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3183 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3184 ModifySettingLocal = true;
3189 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3191 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3192 if (comparerMode == null)
3195 this.SetSortColumn(comparerMode.Value);
3199 /// 列インデックスからソートを行う ComparerMode を求める
3201 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3202 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3203 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3206 return ComparerMode.Id;
3208 switch (columnIndex)
3211 return ComparerMode.Nickname;
3213 return ComparerMode.Data;
3215 return ComparerMode.Id;
3217 return ComparerMode.Name;
3219 return ComparerMode.Source;
3221 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3227 /// 発言一覧の指定した位置の列でソートする
3229 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3230 private void SetSortColumnByDisplayIndex(int columnIndex)
3232 // 表示上の列の位置から ColumnHeader を求める
3233 var col = this._curList.Columns.Cast<ColumnHeader>()
3234 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3239 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3240 if (comparerMode == null)
3243 this.SetSortColumn(comparerMode.Value);
3247 /// 発言一覧の最後列の項目でソートする
3249 private void SetSortLastColumn()
3251 // 表示上の最後列にある ColumnHeader を求める
3252 var col = this._curList.Columns.Cast<ColumnHeader>()
3253 .OrderByDescending(x => x.DisplayIndex)
3256 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3257 if (comparerMode == null)
3260 this.SetSortColumn(comparerMode.Value);
3264 /// 発言一覧を指定された ComparerMode に基づいてソートする
3266 private void SetSortColumn(ComparerMode sortColumn)
3268 if (this._cfgCommon.SortOrderLock)
3271 this._statuses.ToggleSortOrder(sortColumn);
3272 this.InitColumnText();
3274 var list = this._curList;
3277 list.Columns[0].Text = this.ColumnText[0];
3278 list.Columns[1].Text = this.ColumnText[2];
3282 for (var i = 0; i <= 7; i++)
3284 list.Columns[i].Text = this.ColumnText[i];
3288 this.PurgeListViewItemCache();
3290 var tab = this._statuses.Tabs[this._curTab.Text];
3291 if (tab.AllCount > 0 && this._curPost != null)
3293 var idx = tab.IndexOf(this._curPost.StatusId);
3296 this.SelectListItem(list, idx);
3297 list.EnsureVisible(idx);
3302 this.ModifySettingCommon = true;
3305 private void TweenMain_LocationChanged(object sender, EventArgs e)
3307 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3309 _myLoc = this.DesktopLocation;
3310 ModifySettingLocal = true;
3314 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3316 if (ListTab.SelectedTab == null) return;
3317 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3318 if (!this.ExistCurrentPost)
3320 ReplyStripMenuItem.Enabled = false;
3321 ReplyAllStripMenuItem.Enabled = false;
3322 DMStripMenuItem.Enabled = false;
3323 ShowProfileMenuItem.Enabled = false;
3324 ShowUserTimelineContextMenuItem.Enabled = false;
3325 ListManageUserContextToolStripMenuItem2.Enabled = false;
3326 MoveToFavToolStripMenuItem.Enabled = false;
3327 TabMenuItem.Enabled = false;
3328 IDRuleMenuItem.Enabled = false;
3329 SourceRuleMenuItem.Enabled = false;
3330 ReadedStripMenuItem.Enabled = false;
3331 UnreadStripMenuItem.Enabled = false;
3335 ShowProfileMenuItem.Enabled = true;
3336 ListManageUserContextToolStripMenuItem2.Enabled = true;
3337 ReplyStripMenuItem.Enabled = true;
3338 ReplyAllStripMenuItem.Enabled = true;
3339 DMStripMenuItem.Enabled = true;
3340 ShowUserTimelineContextMenuItem.Enabled = true;
3341 MoveToFavToolStripMenuItem.Enabled = true;
3342 TabMenuItem.Enabled = true;
3343 IDRuleMenuItem.Enabled = true;
3344 SourceRuleMenuItem.Enabled = true;
3345 ReadedStripMenuItem.Enabled = true;
3346 UnreadStripMenuItem.Enabled = true;
3348 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3350 FavAddToolStripMenuItem.Enabled = false;
3351 FavRemoveToolStripMenuItem.Enabled = false;
3352 StatusOpenMenuItem.Enabled = false;
3353 FavorareMenuItem.Enabled = false;
3354 ShowRelatedStatusesMenuItem.Enabled = false;
3356 ReTweetStripMenuItem.Enabled = false;
3357 ReTweetUnofficialStripMenuItem.Enabled = false;
3358 QuoteStripMenuItem.Enabled = false;
3359 FavoriteRetweetContextMenu.Enabled = false;
3360 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3364 FavAddToolStripMenuItem.Enabled = true;
3365 FavRemoveToolStripMenuItem.Enabled = true;
3366 StatusOpenMenuItem.Enabled = true;
3367 FavorareMenuItem.Enabled = true;
3368 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3370 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
3372 ReTweetStripMenuItem.Enabled = false;
3373 ReTweetUnofficialStripMenuItem.Enabled = false;
3374 QuoteStripMenuItem.Enabled = false;
3375 FavoriteRetweetContextMenu.Enabled = false;
3376 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3380 ReTweetStripMenuItem.Enabled = true;
3381 ReTweetUnofficialStripMenuItem.Enabled = true;
3382 QuoteStripMenuItem.Enabled = true;
3383 FavoriteRetweetContextMenu.Enabled = true;
3384 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3387 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3389 // RefreshMoreStripMenuItem.Enabled = true;
3393 // RefreshMoreStripMenuItem.Enabled = false;
3395 if (!this.ExistCurrentPost
3396 || _curPost.InReplyToStatusId == null)
3398 RepliedStatusOpenMenuItem.Enabled = false;
3402 RepliedStatusOpenMenuItem.Enabled = true;
3404 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3406 MoveToRTHomeMenuItem.Enabled = false;
3410 MoveToRTHomeMenuItem.Enabled = true;
3413 if (this.ExistCurrentPost)
3415 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3416 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3417 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3419 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3423 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3425 MakeReplyOrDirectStatus(false, true);
3428 private void DMStripMenuItem_Click(object sender, EventArgs e)
3430 MakeReplyOrDirectStatus(false, false);
3433 private async Task doStatusDelete()
3435 if (this._curTab == null || this._curList == null)
3438 if (this._curList.SelectedIndices.Count == 0)
3441 var posts = this._curList.SelectedIndices.Cast<int>()
3442 .Select(x => this.GetCurTabPost(x))
3445 // 選択されたツイートの中に削除可能なものが一つでもあるか
3446 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3449 var ret = MessageBox.Show(this,
3450 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3451 Properties.Resources.DeleteStripMenuItem_ClickText2,
3452 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3454 if (ret != DialogResult.OK)
3457 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3459 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3461 Exception lastException = null;
3462 foreach (var post in posts)
3464 if (!post.CanDeleteBy(this.tw.UserId))
3471 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3476 if (post.RetweetedByUserId == this.tw.UserId)
3478 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3480 await this.twitterApi.StatusesDestroy(post.StatusId)
3485 if (post.UserId == this.tw.UserId)
3487 if (post.RetweetedId != null)
3488 // 他人に RT された自分のツイート
3489 // => RT 元の自分のツイートを削除
3490 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3495 await this.twitterApi.StatusesDestroy(post.StatusId)
3501 catch (WebApiException ex)
3507 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3510 if (lastException == null)
3511 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3513 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3515 this.PurgeListViewItemCache();
3516 this._curPost = null;
3517 this._curItemIndex = -1;
3519 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3521 var listView = (DetailsListView)tabPage.Tag;
3522 var tab = this._statuses.Tabs[tabPage.Text];
3524 using (ControlTransaction.Update(listView))
3526 listView.VirtualListSize = tab.AllCount;
3528 if (tabPage == this._curTab)
3530 listView.SelectedIndices.Clear();
3532 if (tab.AllCount != 0)
3535 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3536 selectedIndex = focusedIndex;
3538 selectedIndex = tab.AllCount - 1;
3540 listView.SelectedIndices.Add(selectedIndex);
3541 listView.EnsureVisible(selectedIndex);
3542 listView.FocusedItem = listView.Items[selectedIndex];
3547 if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3549 if (tabPage.ImageIndex == 0)
3550 tabPage.ImageIndex = -1; // タブアイコン
3554 if (!this._cfgCommon.TabIconDisp)
3555 this.ListTab.Refresh();
3559 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3561 await this.doStatusDelete();
3564 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3566 using (ControlTransaction.Update(this._curList))
3568 foreach (int idx in _curList.SelectedIndices)
3570 var post = this._statuses.Tabs[this._curTab.Text][idx];
3571 this._statuses.SetReadAllTab(post.StatusId, read: true);
3572 ChangeCacheStyleRead(true, idx);
3576 foreach (TabPage tb in ListTab.TabPages)
3578 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3580 if (this._cfgCommon.TabIconDisp)
3582 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3586 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3589 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3591 using (ControlTransaction.Update(this._curList))
3593 foreach (int idx in _curList.SelectedIndices)
3595 var post = this._statuses.Tabs[this._curTab.Text][idx];
3596 this._statuses.SetReadAllTab(post.StatusId, read: false);
3597 ChangeCacheStyleRead(false, idx);
3601 foreach (TabPage tb in ListTab.TabPages)
3603 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3605 if (this._cfgCommon.TabIconDisp)
3607 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3611 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3614 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3616 await this.DoRefresh();
3619 private async Task DoRefresh()
3621 if (_curTab != null)
3624 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3627 switch (_statuses.Tabs[_curTab.Text].TabType)
3629 case MyCommon.TabUsageType.Mentions:
3630 await this.GetReplyAsync();
3632 case MyCommon.TabUsageType.DirectMessage:
3633 await this.GetDirectMessagesAsync();
3635 case MyCommon.TabUsageType.Favorites:
3636 await this.GetFavoritesAsync();
3638 //case MyCommon.TabUsageType.Profile:
3640 case MyCommon.TabUsageType.PublicSearch:
3641 var searchTab = (PublicSearchTabModel)tab;
3642 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3643 await this.GetPublicSearchAsync(searchTab);
3645 case MyCommon.TabUsageType.UserTimeline:
3646 await this.GetUserTimelineAsync((UserTimelineTabModel)tab);
3648 case MyCommon.TabUsageType.Lists:
3649 var listTab = (ListTimelineTabModel)tab;
3650 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3651 await this.GetListTimelineAsync(listTab);
3654 await this.GetHomeTimelineAsync();
3660 await this.GetHomeTimelineAsync();
3664 private async Task DoRefreshMore()
3667 if (_curTab != null)
3670 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3673 switch (_statuses.Tabs[_curTab.Text].TabType)
3675 case MyCommon.TabUsageType.Mentions:
3676 await this.GetReplyAsync(loadMore: true);
3678 case MyCommon.TabUsageType.DirectMessage:
3679 await this.GetDirectMessagesAsync(loadMore: true);
3681 case MyCommon.TabUsageType.Favorites:
3682 await this.GetFavoritesAsync(loadMore: true);
3684 case MyCommon.TabUsageType.Profile:
3687 case MyCommon.TabUsageType.PublicSearch:
3688 var searchTab = (PublicSearchTabModel)tab;
3689 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3690 await this.GetPublicSearchAsync(searchTab, loadMore: true);
3692 case MyCommon.TabUsageType.UserTimeline:
3693 await this.GetUserTimelineAsync((UserTimelineTabModel)tab, loadMore: true);
3695 case MyCommon.TabUsageType.Lists:
3696 var listTab = (ListTimelineTabModel)tab;
3697 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3698 await this.GetListTimelineAsync(listTab, loadMore: true);
3701 await this.GetHomeTimelineAsync(loadMore: true);
3707 await this.GetHomeTimelineAsync(loadMore: true);
3711 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3713 DialogResult result = DialogResult.Abort;
3715 using (var settingDialog = new AppendSettingDialog())
3717 settingDialog.Icon = this.MainIcon;
3718 settingDialog.Owner = this;
3719 settingDialog.ShowInTaskbar = showTaskbarIcon;
3720 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3722 settingDialog.tw = this.tw;
3723 settingDialog.twitterApi = this.twitterApi;
3725 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
3729 result = settingDialog.ShowDialog(this);
3733 return DialogResult.Abort;
3736 if (result == DialogResult.OK)
3740 settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
3748 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3751 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3753 var oldIconSz = this._cfgCommon.IconSize;
3755 if (ShowSettingDialog() == DialogResult.OK)
3759 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
3760 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
3761 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
3762 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
3763 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
3764 TwitterApiConnection.RestApiHost = this._cfgCommon.TwitterApiHost;
3766 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
3767 Networking.UploadImageTimeout = TimeSpan.FromSeconds(this._cfgCommon.UploadImageTimeout);
3768 Networking.SetWebProxy(this._cfgLocal.ProxyType,
3769 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
3770 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
3771 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
3773 ImageSelector.Reset(tw, this.tw.Configuration);
3777 if (this._cfgCommon.TabIconDisp)
3779 ListTab.DrawItem -= ListTab_DrawItem;
3780 ListTab.DrawMode = TabDrawMode.Normal;
3781 ListTab.ImageList = this.TabImage;
3785 ListTab.DrawItem -= ListTab_DrawItem;
3786 ListTab.DrawItem += ListTab_DrawItem;
3787 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3788 ListTab.ImageList = null;
3791 catch (Exception ex)
3793 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3794 ex.Data["IsTerminatePermission"] = false;
3800 if (!this._cfgCommon.UnreadManage)
3802 ReadedStripMenuItem.Enabled = false;
3803 UnreadStripMenuItem.Enabled = false;
3804 if (this._cfgCommon.TabIconDisp)
3806 foreach (TabPage myTab in ListTab.TabPages)
3808 myTab.ImageIndex = -1;
3814 ReadedStripMenuItem.Enabled = true;
3815 UnreadStripMenuItem.Enabled = true;
3818 catch (Exception ex)
3820 ex.Data["Instance"] = "ListTab(UnreadManage)";
3821 ex.Data["IsTerminatePermission"] = false;
3828 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
3830 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3831 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
3832 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
3834 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
3835 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
3836 _fntUnread = this._cfgLocal.FontUnread;
3837 _clUnread = this._cfgLocal.ColorUnread;
3838 _fntReaded = this._cfgLocal.FontRead;
3839 _clReaded = this._cfgLocal.ColorRead;
3840 _clFav = this._cfgLocal.ColorFav;
3841 _clOWL = this._cfgLocal.ColorOWL;
3842 _clRetweet = this._cfgLocal.ColorRetweet;
3843 _fntDetail = this._cfgLocal.FontDetail;
3844 _clDetail = this._cfgLocal.ColorDetail;
3845 _clDetailLink = this._cfgLocal.ColorDetailLink;
3846 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
3847 _clSelf = this._cfgLocal.ColorSelf;
3848 _clAtSelf = this._cfgLocal.ColorAtSelf;
3849 _clTarget = this._cfgLocal.ColorTarget;
3850 _clAtTarget = this._cfgLocal.ColorAtTarget;
3851 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
3852 _clAtTo = this._cfgLocal.ColorAtTo;
3853 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
3854 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
3855 _clInputFont = this._cfgLocal.ColorInputFont;
3856 _fntInputFont = this._cfgLocal.FontInputFont;
3857 _brsBackColorMine.Dispose();
3858 _brsBackColorAt.Dispose();
3859 _brsBackColorYou.Dispose();
3860 _brsBackColorAtYou.Dispose();
3861 _brsBackColorAtFromTarget.Dispose();
3862 _brsBackColorAtTo.Dispose();
3863 _brsBackColorNone.Dispose();
3864 _brsBackColorMine = new SolidBrush(_clSelf);
3865 _brsBackColorAt = new SolidBrush(_clAtSelf);
3866 _brsBackColorYou = new SolidBrush(_clTarget);
3867 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3868 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3869 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3870 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3874 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3875 StatusText.Font = _fntInputFont;
3876 StatusText.ForeColor = _clInputFont;
3878 catch (Exception ex)
3880 MessageBox.Show(ex.Message);
3885 InitDetailHtmlFormat();
3887 catch (Exception ex)
3889 ex.Data["Instance"] = "Font";
3890 ex.Data["IsTerminatePermission"] = false;
3896 foreach (TabPage tb in ListTab.TabPages)
3898 if (this._cfgCommon.TabIconDisp)
3900 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3907 catch (Exception ex)
3909 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3910 ex.Data["IsTerminatePermission"] = false;
3916 var oldIconCol = _iconCol;
3918 if (this._cfgCommon.IconSize != oldIconSz)
3919 ApplyListViewIconSize(this._cfgCommon.IconSize);
3921 foreach (TabPage tp in ListTab.TabPages)
3923 DetailsListView lst = (DetailsListView)tp.Tag;
3925 using (ControlTransaction.Update(lst))
3927 lst.GridLines = this._cfgCommon.ShowGrid;
3928 lst.Font = _fntReaded;
3929 lst.BackColor = _clListBackcolor;
3931 if (_iconCol != oldIconCol)
3936 catch (Exception ex)
3938 ex.Data["Instance"] = "ListView(IconSize)";
3939 ex.Data["IsTerminatePermission"] = false;
3943 SetMainWindowTitle();
3944 SetNotifyIconText();
3946 this.PurgeListViewItemCache();
3947 _curList?.Refresh();
3950 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3951 if (this._cfgCommon.HotkeyEnabled)
3953 ///グローバルホットキーの登録。設定で変更可能にするかも
3954 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
3955 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
3956 modKey |= HookGlobalHotkey.ModKeys.Alt;
3957 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
3958 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3959 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
3960 modKey |= HookGlobalHotkey.ModKeys.Shift;
3961 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
3962 modKey |= HookGlobalHotkey.ModKeys.Win;
3964 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
3967 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
3970 StatusText_TextChanged(null, null);
3979 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3980 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3983 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3985 this.TopMost = this._cfgCommon.AlwaysTop;
3986 SaveConfigsAll(false);
3988 if (tw.Username != oldUser.Username)
3989 await this.doGetFollowersMenu();
3995 private void SetTabAlignment()
3997 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3998 if (ListTab.Alignment == newAlignment) return;
4000 // 各タブのリスト上の選択位置などを退避
4001 var listSelections = this.SaveListViewSelection();
4003 ListTab.Alignment = newAlignment;
4005 foreach (TabPage tab in ListTab.TabPages)
4007 DetailsListView lst = (DetailsListView)tab.Tag;
4008 TabModel tabInfo = _statuses.Tabs[tab.Text];
4009 using (ControlTransaction.Update(lst))
4012 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4017 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4023 case MyCommon.IconSizes.IconNone:
4026 case MyCommon.IconSizes.Icon16:
4029 case MyCommon.IconSizes.Icon24:
4032 case MyCommon.IconSizes.Icon48:
4035 case MyCommon.IconSizes.Icon48_2:
4043 // ディスプレイの DPI 設定を考慮したサイズを設定する
4044 _listViewImageList.ImageSize = new Size(
4046 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4050 _listViewImageList.ImageSize = new Size(1, 1);
4054 private void ResetColumns(DetailsListView list)
4056 using (ControlTransaction.Update(list))
4057 using (ControlTransaction.Layout(list, false))
4060 list.ColumnClick -= MyList_ColumnClick;
4061 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4062 list.ColumnReordered -= MyList_ColumnReordered;
4063 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4065 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4066 list.Columns.Clear();
4067 cols.ForEach(col => col.Dispose());
4070 InitColumns(list, true);
4072 list.ColumnClick += MyList_ColumnClick;
4073 list.DrawColumnHeader += MyList_DrawColumnHeader;
4074 list.ColumnReordered += MyList_ColumnReordered;
4075 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4079 public void AddNewTabForSearch(string searchWord)
4081 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4082 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4084 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4086 foreach (TabPage tp in ListTab.TabPages)
4088 if (tb.TabName == tp.Text)
4090 ListTab.SelectedTab = tp;
4097 string tabName = searchWord;
4098 for (int i = 0; i <= 100; i++)
4100 if (_statuses.ContainsTab(tabName))
4106 var tab = new PublicSearchTabModel(tabName);
4107 _statuses.AddTab(tab);
4108 AddNewTab(tab, startup: false);
4110 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4112 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4113 cmb.Items.Add(searchWord);
4114 cmb.Text = searchWord;
4117 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4120 private void ShowUserTimeline()
4122 if (!this.ExistCurrentPost) return;
4123 AddNewTabForUserTimeline(_curPost.ScreenName);
4126 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4128 if (e.KeyCode == Keys.Escape)
4130 TabPage relTp = ListTab.SelectedTab;
4131 RemoveSpecifiedTab(relTp.Text, false);
4133 e.SuppressKeyPress = true;
4137 public void AddNewTabForUserTimeline(string user)
4139 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4140 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4142 if (tb.ScreenName == user)
4144 foreach (TabPage tp in ListTab.TabPages)
4146 if (tb.TabName == tp.Text)
4148 ListTab.SelectedTab = tp;
4155 string tabName = "user:" + user;
4156 while (_statuses.ContainsTab(tabName))
4161 var tab = new UserTimelineTabModel(tabName, user);
4162 this._statuses.AddTab(tab);
4163 this.AddNewTab(tab, startup: false);
4165 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4168 this.GetUserTimelineAsync(tab);
4171 public bool AddNewTab(TabModel tab, bool startup)
4174 foreach (TabPage tb in ListTab.TabPages)
4176 if (tb.Text == tab.TabName) return false;
4180 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4182 var _tabPage = new TabPage();
4183 var _listCustom = new DetailsListView();
4185 int cnt = ListTab.TabPages.Count;
4187 ///ToDo:Create and set controls follow tabtypes
4189 using (ControlTransaction.Update(_listCustom))
4190 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4191 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4192 using (ControlTransaction.Layout(this.SplitContainer1, false))
4193 using (ControlTransaction.Layout(this.ListTab, false))
4194 using (ControlTransaction.Layout(this))
4195 using (ControlTransaction.Layout(_tabPage, false))
4197 _tabPage.Controls.Add(_listCustom);
4200 var userTab = tab as UserTimelineTabModel;
4201 var listTab = tab as ListTimelineTabModel;
4202 var searchTab = tab as PublicSearchTabModel;
4204 if (userTab != null || listTab != null)
4206 var label = new Label();
4207 label.Dock = DockStyle.Top;
4208 label.Name = "labelUser";
4211 if (listTab != null)
4213 label.Text = listTab.ListInfo.ToString();
4215 else if (userTab != null)
4217 label.Text = userTab.ScreenName + "'s Timeline";
4219 label.TextAlign = ContentAlignment.MiddleLeft;
4220 using (ComboBox tmpComboBox = new ComboBox())
4222 label.Height = tmpComboBox.Height;
4224 _tabPage.Controls.Add(label);
4227 else if (searchTab != null)
4229 var pnl = new Panel();
4231 var lbl = new Label();
4232 var cmb = new ComboBox();
4233 var btn = new Button();
4234 var cmbLang = new ComboBox();
4236 using (ControlTransaction.Layout(pnl, false))
4238 pnl.Controls.Add(cmb);
4239 pnl.Controls.Add(cmbLang);
4240 pnl.Controls.Add(btn);
4241 pnl.Controls.Add(lbl);
4242 pnl.Name = "panelSearch";
4244 pnl.Dock = DockStyle.Top;
4245 pnl.Height = cmb.Height;
4246 pnl.Enter += SearchControls_Enter;
4247 pnl.Leave += SearchControls_Leave;
4250 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4251 cmb.Dock = DockStyle.Fill;
4252 cmb.Name = "comboSearch";
4253 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4254 cmb.ImeMode = ImeMode.NoControl;
4255 cmb.TabStop = false;
4257 cmb.AutoCompleteMode = AutoCompleteMode.None;
4258 cmb.KeyDown += SearchComboBox_KeyDown;
4261 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4262 cmbLang.Dock = DockStyle.Right;
4264 cmbLang.Name = "comboLang";
4265 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4266 cmbLang.TabStop = false;
4267 cmbLang.TabIndex = 2;
4268 cmbLang.Items.Add("");
4269 cmbLang.Items.Add("ja");
4270 cmbLang.Items.Add("en");
4271 cmbLang.Items.Add("ar");
4272 cmbLang.Items.Add("da");
4273 cmbLang.Items.Add("nl");
4274 cmbLang.Items.Add("fa");
4275 cmbLang.Items.Add("fi");
4276 cmbLang.Items.Add("fr");
4277 cmbLang.Items.Add("de");
4278 cmbLang.Items.Add("hu");
4279 cmbLang.Items.Add("is");
4280 cmbLang.Items.Add("it");
4281 cmbLang.Items.Add("no");
4282 cmbLang.Items.Add("pl");
4283 cmbLang.Items.Add("pt");
4284 cmbLang.Items.Add("ru");
4285 cmbLang.Items.Add("es");
4286 cmbLang.Items.Add("sv");
4287 cmbLang.Items.Add("th");
4289 lbl.Text = "Search(C-S-f)";
4290 lbl.Name = "label1";
4291 lbl.Dock = DockStyle.Left;
4293 lbl.Height = cmb.Height;
4294 lbl.TextAlign = ContentAlignment.MiddleLeft;
4297 btn.Text = "Search";
4298 btn.Name = "buttonSearch";
4299 btn.UseVisualStyleBackColor = true;
4300 btn.Dock = DockStyle.Right;
4301 btn.TabStop = false;
4303 btn.Click += SearchButton_Click;
4305 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4307 cmb.Items.Add(searchTab.SearchWords);
4308 cmb.Text = searchTab.SearchWords;
4311 cmbLang.Text = searchTab.SearchLang;
4313 _tabPage.Controls.Add(pnl);
4317 _tabPage.Tag = _listCustom;
4318 this.ListTab.Controls.Add(_tabPage);
4320 _tabPage.Location = new Point(4, 4);
4321 _tabPage.Name = "CTab" + cnt;
4322 _tabPage.Size = new Size(380, 260);
4323 _tabPage.TabIndex = 2 + cnt;
4324 _tabPage.Text = tab.TabName;
4325 _tabPage.UseVisualStyleBackColor = true;
4326 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4328 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4329 _listCustom.TabIndex = 1;
4330 _listCustom.AllowColumnReorder = true;
4331 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4332 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4333 _listCustom.Dock = DockStyle.Fill;
4334 _listCustom.FullRowSelect = true;
4335 _listCustom.HideSelection = false;
4336 _listCustom.Location = new Point(0, 0);
4337 _listCustom.Margin = new Padding(0);
4338 _listCustom.Name = "CList" + Environment.TickCount;
4339 _listCustom.ShowItemToolTips = true;
4340 _listCustom.Size = new Size(380, 260);
4341 _listCustom.UseCompatibleStateImageBehavior = false;
4342 _listCustom.View = View.Details;
4343 _listCustom.OwnerDraw = true;
4344 _listCustom.VirtualMode = true;
4345 _listCustom.Font = _fntReaded;
4346 _listCustom.BackColor = _clListBackcolor;
4348 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4349 _listCustom.AllowDrop = true;
4351 _listCustom.SmallImageList = _listViewImageList;
4353 InitColumns(_listCustom, startup);
4355 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4356 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4357 _listCustom.ColumnClick += MyList_ColumnClick;
4358 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4359 _listCustom.DragDrop += TweenMain_DragDrop;
4360 _listCustom.DragEnter += TweenMain_DragEnter;
4361 _listCustom.DragOver += TweenMain_DragOver;
4362 _listCustom.DrawItem += MyList_DrawItem;
4363 _listCustom.MouseClick += MyList_MouseClick;
4364 _listCustom.ColumnReordered += MyList_ColumnReordered;
4365 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4366 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4367 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4368 _listCustom.DrawSubItem += MyList_DrawSubItem;
4369 _listCustom.HScrolled += MyList_HScrolled;
4375 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4377 var tabInfo = _statuses.GetTabByName(TabName);
4378 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4382 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4383 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4384 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4390 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4391 if (_tabPage == null) return false;
4393 SetListProperty(); //他のタブに列幅等を反映
4396 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4397 _tabPage.Tag = null;
4399 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4400 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4401 using (ControlTransaction.Layout(this.SplitContainer1, false))
4402 using (ControlTransaction.Layout(this.ListTab, false))
4403 using (ControlTransaction.Layout(this))
4404 using (ControlTransaction.Layout(_tabPage, false))
4406 if (this.ListTab.SelectedTab == _tabPage)
4408 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4409 this._beforeSelectedTab = null;
4411 this.ListTab.Controls.Remove(_tabPage);
4414 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4416 using (Control label = _tabPage.Controls["labelUser"])
4418 _tabPage.Controls.Remove(label);
4421 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4423 using (Control pnl = _tabPage.Controls["panelSearch"])
4425 pnl.Enter -= SearchControls_Enter;
4426 pnl.Leave -= SearchControls_Leave;
4427 _tabPage.Controls.Remove(pnl);
4429 foreach (Control ctrl in pnl.Controls)
4431 if (ctrl.Name == "buttonSearch")
4433 ctrl.Click -= SearchButton_Click;
4435 else if (ctrl.Name == "comboSearch")
4437 ctrl.KeyDown -= SearchComboBox_KeyDown;
4439 pnl.Controls.Remove(ctrl);
4445 _tabPage.Controls.Remove(_listCustom);
4447 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4448 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4449 _listCustom.ColumnClick -= MyList_ColumnClick;
4450 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4451 _listCustom.DragDrop -= TweenMain_DragDrop;
4452 _listCustom.DragEnter -= TweenMain_DragEnter;
4453 _listCustom.DragOver -= TweenMain_DragOver;
4454 _listCustom.DrawItem -= MyList_DrawItem;
4455 _listCustom.MouseClick -= MyList_MouseClick;
4456 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4457 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4458 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4459 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4460 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4461 _listCustom.HScrolled -= MyList_HScrolled;
4463 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4464 _listCustom.Columns.Clear();
4465 cols.ForEach(col => col.Dispose());
4468 _listCustom.ContextMenuStrip = null;
4469 _listCustom.ColumnHeaderContextMenuStrip = null;
4470 _listCustom.Font = null;
4472 _listCustom.SmallImageList = null;
4473 _listCustom.ListViewItemSorter = null;
4476 if (_curTab.Equals(_tabPage))
4483 this.PurgeListViewItemCache();
4487 _listCustom.Dispose();
4488 _statuses.RemoveTab(TabName);
4490 foreach (TabPage tp in ListTab.TabPages)
4492 DetailsListView lst = (DetailsListView)tp.Tag;
4493 var count = _statuses.Tabs[tp.Text].AllCount;
4494 lst.VirtualListSize = count;
4500 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4502 this.PurgeListViewItemCache();
4503 _beforeSelectedTab = e.TabPage;
4506 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4510 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4513 Rectangle dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4514 if (!dragEnableRectangle.Contains(e.Location))
4516 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4517 tn = ListTab.SelectedTab.Text;
4520 if (string.IsNullOrEmpty(tn)) return;
4522 foreach (TabPage tb in ListTab.TabPages)
4526 ListTab.DoDragDrop(tb, DragDropEffects.All);
4536 Point cpos = new Point(e.X, e.Y);
4537 for (int i = 0; i < ListTab.TabPages.Count; i++)
4539 Rectangle rect = ListTab.GetTabRect(i);
4540 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4541 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4543 _rclickTabName = ListTab.TabPages[i].Text;
4549 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4551 //_curList.Refresh();
4552 SetMainWindowTitle();
4553 SetStatusLabelUrl();
4554 SetApiStatusLabel();
4555 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4556 TabMenuControl(ListTab.SelectedTab.Text);
4557 this.PushSelectPostChain();
4558 await DispSelectedPost();
4561 private void SetListProperty()
4563 //削除などで見つからない場合は処理せず
4564 if (_curList == null) return;
4565 if (!_isColumnChanged) return;
4567 int[] dispOrder = new int[_curList.Columns.Count];
4568 for (int i = 0; i < _curList.Columns.Count; i++)
4570 for (int j = 0; j < _curList.Columns.Count; j++)
4572 if (_curList.Columns[j].DisplayIndex == i)
4581 foreach (TabPage tb in ListTab.TabPages)
4583 if (!tb.Equals(_curTab))
4585 if (tb.Tag != null && tb.Controls.Count > 0)
4587 DetailsListView lst = (DetailsListView)tb.Tag;
4588 for (int i = 0; i < lst.Columns.Count; i++)
4590 lst.Columns[dispOrder[i]].DisplayIndex = i;
4591 lst.Columns[i].Width = _curList.Columns[i].Width;
4597 _isColumnChanged = false;
4600 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4602 if (e.KeyChar == '@')
4604 if (!this._cfgCommon.UseAtIdSupplement) return;
4606 int cnt = AtIdSupl.ItemCount;
4607 ShowSuplDialog(StatusText, AtIdSupl);
4608 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
4611 else if (e.KeyChar == '#')
4613 if (!this._cfgCommon.UseHashSupplement) return;
4614 ShowSuplDialog(StatusText, HashSupl);
4619 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4621 ShowSuplDialog(owner, dialog, 0, "");
4624 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4626 ShowSuplDialog(owner, dialog, offset, "");
4629 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4631 dialog.StartsWith = startswith;
4638 dialog.ShowDialog();
4640 this.TopMost = this._cfgCommon.AlwaysTop;
4641 int selStart = owner.SelectionStart;
4644 if (dialog.DialogResult == DialogResult.OK)
4646 if (!string.IsNullOrEmpty(dialog.inputText))
4650 fHalf = owner.Text.Substring(0, selStart - offset);
4652 if (selStart < owner.Text.Length)
4654 eHalf = owner.Text.Substring(selStart);
4656 owner.Text = fHalf + dialog.inputText + eHalf;
4657 owner.SelectionStart = selStart + dialog.inputText.Length;
4664 fHalf = owner.Text.Substring(0, selStart);
4666 if (selStart < owner.Text.Length)
4668 eHalf = owner.Text.Substring(selStart);
4670 owner.Text = fHalf + eHalf;
4673 owner.SelectionStart = selStart;
4679 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4682 if (!e.Alt && !e.Control && !e.Shift)
4684 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4686 bool isSpace = false;
4687 foreach (char c in StatusText.Text)
4689 if (c == ' ' || c == ' ')
4702 StatusText.Text = "";
4703 JumpUnreadMenuItem_Click(null, null);
4707 this.StatusText_TextChanged(null, null);
4710 private void StatusText_TextChanged(object sender, EventArgs e)
4713 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
4714 lblLen.Text = pLen.ToString();
4717 StatusText.ForeColor = Color.Red;
4721 StatusText.ForeColor = _clInputFont;
4724 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4726 if (string.IsNullOrEmpty(StatusText.Text))
4728 this.inReplyTo = null;
4733 /// ツイート投稿前のフッター付与などの前処理を行います
4735 private string FormatStatusText(string statusText)
4737 statusText = statusText.Replace("\r\n", "\n");
4739 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
4742 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4745 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
4747 // 文中の全角スペースを半角スペース1個にする
4748 statusText = statusText.Replace(" ", " ");
4751 // DM の場合はこれ以降の処理を行わない
4752 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4756 if (this._cfgCommon.PostShiftEnter)
4758 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4762 if (this.StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
4763 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4765 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4768 if (statusText.Contains("RT @"))
4769 disableFooter = true;
4774 var hashtag = this.HashMgr.UseHash;
4775 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4778 header = HashMgr.UseHash + " ";
4780 footer = " " + HashMgr.UseHash;
4785 if (this._cfgLocal.UseRecommendStatus)
4788 footer += this.recommendedStatusFooter;
4790 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
4792 // テキストボックスに入力されている文字列を使用する
4793 footer += " " + this._cfgLocal.StatusText.Trim();
4797 statusText = header + statusText + footer;
4799 if (this.ToolStripMenuItemPreventSmsCommand.Checked)
4801 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4802 // 参照: https://support.twitter.com/articles/14020
4804 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4805 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4807 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4808 statusText = '\u200b' + statusText;
4816 /// 投稿欄に表示する入力可能な文字数を計算します
4818 private int GetRestStatusCount(string statusText)
4821 var remainCount = this.tw.GetTextLengthRemain(statusText);
4823 var uploadService = this.ImageSelector.SelectedService;
4824 if (this.ImageSelector.Visible && uploadService != null)
4826 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4827 remainCount -= uploadService.GetReservedTextLength(1);
4833 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4835 if (sender != this._curList)
4838 var listCache = this._listItemCache;
4839 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4841 // If the newly requested cache is a subset of the old cache,
4842 // no need to rebuild everything, so do nothing.
4846 // Now we need to rebuild the cache.
4847 this.CreateCache(e.StartIndex, e.EndIndex);
4850 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4852 var listCache = this._listItemCache;
4853 if (listCache?.TargetList == sender)
4856 PostClass cacheItemPost;
4857 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
4864 // A cache miss, so create a new ListViewItem and pass it back.
4865 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4868 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4872 // 不正な要求に対する間に合わせの応答
4873 string[] sitem = {"", "", "", "", "", "", "", ""};
4874 e.Item = new ImageListViewItem(sitem);
4878 private void CreateCache(int startIndex, int endIndex)
4880 var tabInfo = this._statuses.Tabs[this._curTab.Text];
4882 if (tabInfo.AllCount == 0)
4885 // キャッシュ要求(要求範囲±30を作成)
4886 startIndex = Math.Max(startIndex - 30, 0);
4887 endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
4889 var cacheLength = endIndex - startIndex + 1;
4891 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4892 var listItems = Enumerable.Range(0, cacheLength)
4893 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4896 var listCache = new ListViewItemCache
4898 TargetList = this._curList,
4899 StartIndex = startIndex,
4900 EndIndex = endIndex,
4902 ListItem = listItems,
4905 Interlocked.Exchange(ref this._listItemCache, listCache);
4909 /// DetailsListView のための ListViewItem のキャッシュを消去する
4911 private void PurgeListViewItemCache()
4913 Interlocked.Exchange(ref this._listItemCache, null);
4916 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
4918 StringBuilder mk = new StringBuilder();
4919 //if (Post.IsDeleted) mk.Append("×");
4920 //if (Post.IsMark) mk.Append("♪");
4921 //if (Post.IsProtect) mk.Append("Ю");
4922 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4923 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4924 ImageListViewItem itm;
4925 if (Post.RetweetedId == null)
4927 string[] sitem= {"",
4929 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText,
4930 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
4935 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4939 string[] sitem = {"",
4941 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText,
4942 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
4943 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4947 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4949 itm.StateIndex = Post.StateIndex;
4952 bool read = Post.IsRead;
4953 //未読管理していなかったら既読として扱う
4954 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
4955 ChangeItemStyleRead(read, itm, Post, null);
4956 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
4961 /// 全てのタブの振り分けルールを反映し直します
4963 private void ApplyPostFilters()
4965 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4967 this.PurgeListViewItemCache();
4968 this._curPost = null;
4969 this._curItemIndex = -1;
4970 this._statuses.FilterAll();
4972 foreach (TabPage tabPage in this.ListTab.TabPages)
4974 var tab = this._statuses.Tabs[tabPage.Text];
4976 var listview = (DetailsListView)tabPage.Tag;
4977 using (ControlTransaction.Update(listview))
4979 listview.VirtualListSize = tab.AllCount;
4982 if (this._cfgCommon.TabIconDisp)
4984 if (tab.UnreadCount > 0)
4985 tabPage.ImageIndex = 0;
4987 tabPage.ImageIndex = -1;
4991 if (!this._cfgCommon.TabIconDisp)
4992 this.ListTab.Refresh();
4994 SetMainWindowTitle();
4995 SetStatusLabelUrl();
4999 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5001 e.DrawDefault = true;
5004 private void MyList_HScrolled(object sender, EventArgs e)
5006 DetailsListView listView = (DetailsListView)sender;
5010 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5012 if (e.State == 0) return;
5013 e.DrawDefault = false;
5015 SolidBrush brs2 = null;
5016 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5018 if (e.Item.BackColor == _clSelf)
5019 brs2 = _brsBackColorMine;
5020 else if (e.Item.BackColor == _clAtSelf)
5021 brs2 = _brsBackColorAt;
5022 else if (e.Item.BackColor == _clTarget)
5023 brs2 = _brsBackColorYou;
5024 else if (e.Item.BackColor == _clAtTarget)
5025 brs2 = _brsBackColorAtYou;
5026 else if (e.Item.BackColor == _clAtFromTarget)
5027 brs2 = _brsBackColorAtFromTarget;
5028 else if (e.Item.BackColor == _clAtTo)
5029 brs2 = _brsBackColorAtTo;
5031 brs2 = _brsBackColorNone;
5036 if (((Control)sender).Focused)
5037 brs2 = _brsHighLight;
5039 brs2 = _brsDeactiveSelection;
5041 e.Graphics.FillRectangle(brs2, e.Bounds);
5042 e.DrawFocusRectangle();
5043 this.DrawListViewItemIcon(e);
5046 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5048 if (e.ItemState == 0) return;
5050 if (e.ColumnIndex > 0)
5053 var post = (PostClass)e.Item.Tag;
5055 RectangleF rct = e.Bounds;
5056 rct.Width = e.Header.Width;
5057 int fontHeight = e.Item.Font.Height;
5060 rct.Y += fontHeight;
5061 rct.Height -= fontHeight;
5065 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5067 //if (heightDiff > fontHeight * 0.7)
5069 // rct.Height += fontHeight;
5070 // drawLineCount += 1;
5073 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5074 if (!_iconCol && drawLineCount <= 1)
5076 //rct.Inflate(0, heightDiff / -2);
5077 //rct.Height += fontHeight / 2;
5079 else if (heightDiff < fontHeight * 0.7)
5081 //最終行が70%以上欠けていたら、最終行は表示しない
5082 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5083 rct.Height = (fontHeight * drawLineCount) - 1;
5090 //if (!_iconCol && drawLineCount > 1)
5092 // rct.Y += fontHeight * 0.2;
5093 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5098 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5099 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5104 Rectangle rctB = e.Bounds;
5105 rctB.Width = e.Header.Width;
5106 rctB.Height = fontHeight;
5108 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5110 TextRenderer.DrawText(e.Graphics,
5111 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5113 Rectangle.Round(rct),
5115 TextFormatFlags.WordBreak |
5116 TextFormatFlags.EndEllipsis |
5117 TextFormatFlags.GlyphOverhangPadding |
5118 TextFormatFlags.NoPrefix);
5119 TextRenderer.DrawText(e.Graphics,
5120 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 + "]",
5124 TextFormatFlags.SingleLine |
5125 TextFormatFlags.EndEllipsis |
5126 TextFormatFlags.GlyphOverhangPadding |
5127 TextFormatFlags.NoPrefix);
5133 if (e.ColumnIndex != 2)
5134 text = e.SubItem.Text;
5136 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5138 if (drawLineCount == 1)
5140 TextRenderer.DrawText(e.Graphics,
5143 Rectangle.Round(rct),
5145 TextFormatFlags.SingleLine |
5146 TextFormatFlags.EndEllipsis |
5147 TextFormatFlags.GlyphOverhangPadding |
5148 TextFormatFlags.NoPrefix |
5149 TextFormatFlags.VerticalCenter);
5153 TextRenderer.DrawText(e.Graphics,
5156 Rectangle.Round(rct),
5158 TextFormatFlags.WordBreak |
5159 TextFormatFlags.EndEllipsis |
5160 TextFormatFlags.GlyphOverhangPadding |
5161 TextFormatFlags.NoPrefix);
5164 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5169 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5171 if (_iconSz == 0) return;
5173 ImageListViewItem item = (ImageListViewItem)e.Item;
5175 //e.Bounds.Leftが常に0を指すから自前で計算
5176 Rectangle itemRect = item.Bounds;
5177 var col0 = e.Item.ListView.Columns[0];
5178 itemRect.Width = col0.Width;
5180 if (col0.DisplayIndex > 0)
5182 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5184 if (clm.DisplayIndex < col0.DisplayIndex)
5185 itemRect.X += clm.Width;
5189 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5190 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5191 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5194 var img = item.Image;
5197 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5198 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5200 if (iconRect.Width > 0)
5202 e.Graphics.FillRectangle(Brushes.White, iconRect);
5203 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5206 e.Graphics.DrawImage(img.Image, iconRect);
5208 catch (ArgumentException)
5210 item.RefreshImageAsync();
5216 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5217 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5219 item.GetImageAsync();
5222 if (item.StateIndex > -1)
5224 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5225 if (stateRect.Width > 0)
5227 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5228 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5229 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5234 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5236 base.ScaleControl(factor, specified);
5238 ScaleChildControl(this.TabImage, factor);
5240 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5241 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5243 foreach (var listview in listviews)
5245 ScaleChildControl(listview, factor);
5249 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5251 // ImageListViewItem item = (ImageListViewItem)e.Item;
5252 // if (item.StateImageIndex > -1)
5254 // ////e.Bounds.Leftが常に0を指すから自前で計算
5255 // //Rectangle itemRect = item.Bounds;
5256 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5258 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5260 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5262 // // itemRect.X += clm.Width;
5266 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5267 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5269 // if (rct.Width > 0)
5271 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5272 // //e.Graphics.FillRectangle(Brushes.White, rct);
5273 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5274 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5279 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5281 var tab = this._statuses.Tabs[this._curTab.Text];
5283 if (tab.AllCount == 0)
5285 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5289 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5294 case SEARCHTYPE.NextSearch: // 次を検索
5295 if (selectedIndex != -1)
5296 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5300 case SEARCHTYPE.PrevSearch: // 前を検索
5301 if (selectedIndex != -1)
5302 startIndex = Math.Max(selectedIndex - 1, 0);
5304 startIndex = tab.AllCount - 1;
5306 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5308 if (selectedIndex != -1)
5309 startIndex = selectedIndex;
5315 Func<string, bool> stringComparer;
5318 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5320 catch (ArgumentException)
5322 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5326 var reverse = searchType == SEARCHTYPE.PrevSearch;
5327 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5328 .DefaultIfEmpty(-1).First();
5330 if (foundIndex == -1)
5332 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5336 this.SelectListItem(this._curList, foundIndex);
5337 this._curList.EnsureVisible(foundIndex);
5340 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5343 this.ShowSearchDialog();
5346 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5348 var previousSearch = this.SearchDialog.ResultOptions;
5349 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5351 this.SearchDialog.Reset();
5352 this.ShowSearchDialog();
5358 previousSearch.Query,
5359 previousSearch.CaseSensitive,
5360 previousSearch.UseRegex,
5361 SEARCHTYPE.NextSearch);
5364 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5366 var previousSearch = this.SearchDialog.ResultOptions;
5367 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5369 this.SearchDialog.Reset();
5370 this.ShowSearchDialog();
5376 previousSearch.Query,
5377 previousSearch.CaseSensitive,
5378 previousSearch.UseRegex,
5379 SEARCHTYPE.PrevSearch);
5383 /// 検索ダイアログを表示し、検索を実行します
5385 private void ShowSearchDialog()
5387 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5389 this.TopMost = this._cfgCommon.AlwaysTop;
5392 this.TopMost = this._cfgCommon.AlwaysTop;
5394 var searchOptions = this.SearchDialog.ResultOptions;
5395 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5397 if (searchOptions.NewTab)
5399 var tabName = Properties.Resources.SearchResults_TabName;
5403 tabName = this._statuses.MakeTabName(tabName);
5405 catch (TabException ex)
5407 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5410 var resultTab = new LocalSearchTabModel(tabName);
5411 this.AddNewTab(resultTab, startup: false);
5412 this._statuses.AddTab(resultTab);
5414 var targetTab = this._statuses.Tabs[this._curTab.Text];
5416 Func<string, bool> stringComparer;
5419 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5421 catch (ArgumentException)
5423 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5427 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5428 if (foundIndices.Length == 0)
5430 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5434 var foundPosts = foundIndices.Select(x => targetTab[x]);
5435 foreach (var post in foundPosts)
5437 resultTab.AddPostQueue(post);
5440 this._statuses.DistributePosts();
5441 this.RefreshTimeline();
5443 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5444 .First(x => x.Text == tabName);
5446 this.ListTab.SelectedTab = tabPage;
5451 searchOptions.Query,
5452 searchOptions.CaseSensitive,
5453 searchOptions.UseRegex,
5454 SEARCHTYPE.DialogSearch);
5457 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5459 this.AddNewTabForSearch(searchOptions.Query);
5463 /// <summary>発言検索に使用するメソッドを生成します</summary>
5464 /// <exception cref="ArgumentException">
5465 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5467 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5471 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5472 var regex = new Regex(query, regexOption);
5474 return x => regex.IsMatch(x);
5478 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5480 return x => x.IndexOf(query, comparisonType) != -1;
5484 private void AboutMenuItem_Click(object sender, EventArgs e)
5486 using (TweenAboutBox about = new TweenAboutBox())
5488 about.ShowDialog(this);
5490 this.TopMost = this._cfgCommon.AlwaysTop;
5493 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5495 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5497 if (ImageSelector.Enabled)
5500 TabModel foundTab = null;
5503 DetailsListView lst = null;
5506 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5508 var tabPage = this.ListTab.TabPages[i];
5509 var tab = this._statuses.Tabs[tabPage.Text];
5510 var unreadIndex = tab.NextUnreadIndex;
5512 if (unreadIndex != -1)
5514 ListTab.SelectedIndex = i;
5516 foundIndex = unreadIndex;
5517 lst = (DetailsListView)tabPage.Tag;
5522 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5523 if (foundTab == null && bgnIdx > 0)
5525 for (int i = 0; i < bgnIdx; i++)
5527 var tabPage = this.ListTab.TabPages[i];
5528 var tab = this._statuses.Tabs[tabPage.Text];
5529 var unreadIndex = tab.NextUnreadIndex;
5531 if (unreadIndex != -1)
5533 ListTab.SelectedIndex = i;
5535 foundIndex = unreadIndex;
5536 lst = (DetailsListView)tabPage.Tag;
5542 if (foundTab == null)
5544 //全部調べたが未読見つからず→先頭タブの最新発言へ
5545 ListTab.SelectedIndex = 0;
5546 var tabPage = this.ListTab.TabPages[0];
5547 var tab = this._statuses.Tabs[tabPage.Text];
5549 if (tab.AllCount == 0)
5552 if (_statuses.SortOrder == SortOrder.Ascending)
5553 foundIndex = tab.AllCount - 1;
5557 lst = (DetailsListView)tabPage.Tag;
5560 SelectListItem(lst, foundIndex);
5562 if (_statuses.SortMode == ComparerMode.Id)
5564 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5565 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5571 lst.EnsureVisible(foundIndex);
5576 lst.EnsureVisible(foundIndex);
5582 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5584 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5586 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5587 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5591 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5593 if (_curList.SelectedIndices.Count > 0)
5595 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5596 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5600 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5602 await this.CheckNewVersion(false);
5605 private void RunTweenUp()
5607 ProcessStartInfo pinfo = new ProcessStartInfo();
5608 pinfo.UseShellExecute = true;
5609 pinfo.WorkingDirectory = MyCommon.settingPath;
5610 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5611 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5614 Process.Start(pinfo);
5618 MessageBox.Show("Failed to execute TweenUp3.exe.");
5622 public class VersionInfo
5624 public Version Version { get; set; }
5625 public Uri DownloadUri { get; set; }
5626 public string ReleaseNote { get; set; }
5630 /// OpenTween の最新バージョンの情報を取得します
5632 public async Task<VersionInfo> GetVersionInfoAsync()
5634 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5635 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5637 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5638 .ConfigureAwait(false);
5640 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5641 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5643 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5644 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5646 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5648 return new VersionInfo
5650 Version = Version.Parse(msgHeader[0]),
5651 DownloadUri = new Uri(msgHeader[1]),
5652 ReleaseNote = msgBody,
5656 private async Task CheckNewVersion(bool startup = false)
5658 if (ApplicationSettings.VersionInfoUrl == null)
5659 return; // 更新チェック無効化
5663 var versionInfo = await this.GetVersionInfoAsync();
5665 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5670 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5671 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5672 msgtext = MyCommon.ReplaceAppName(msgtext);
5674 MessageBox.Show(msgtext,
5675 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5676 MessageBoxButtons.OK, MessageBoxIcon.Information);
5681 using (var dialog = new UpdateDialog())
5683 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5684 MyCommon.GetReadableVersion(versionInfo.Version));
5685 dialog.DetailsText = versionInfo.ReleaseNote;
5687 if (dialog.ShowDialog(this) == DialogResult.Yes)
5689 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5695 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5698 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5699 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5700 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5705 private async Task Colorize()
5708 await this.DispSelectedPost();
5709 //件数関連の場合、タイトル即時書き換え
5710 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
5711 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5712 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5713 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5715 SetMainWindowTitle();
5717 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5718 SetStatusLabelUrl();
5719 foreach (TabPage tb in ListTab.TabPages)
5721 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5723 if (this._cfgCommon.TabIconDisp)
5725 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5729 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
5732 public string createDetailHtml(string orgdata)
5734 if (this._cfgLocal.UseTwemoji)
5735 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5737 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5740 private Task DispSelectedPost()
5742 return this.DispSelectedPost(false);
5745 private PostClass displayPost = new PostClass();
5748 /// サムネイル表示に使用する CancellationToken の生成元
5750 private CancellationTokenSource thumbnailTokenSource = null;
5752 private async Task DispSelectedPost(bool forceupdate)
5754 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5757 var oldDisplayPost = this.displayPost;
5758 this.displayPost = this._curPost;
5760 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5763 var loadTasks = new List<Task>
5765 this.tweetDetailsView.ShowPostDetails(this._curPost),
5768 this.SplitContainer3.Panel2Collapsed = true;
5770 if (this._cfgCommon.PreviewEnable)
5772 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5773 oldTokenSource?.Cancel();
5775 var token = this.thumbnailTokenSource.Token;
5776 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5781 await Task.WhenAll(loadTasks);
5783 catch (OperationCanceledException) { }
5786 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5788 await this.OpenApplicationWebsite();
5791 private async Task OpenApplicationWebsite()
5793 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5796 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5798 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5801 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5803 if (ListTab.SelectedTab != null)
5805 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
5807 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
5808 if (pnl.Controls["comboSearch"].Focused ||
5809 pnl.Controls["comboLang"].Focused ||
5810 pnl.Controls["buttonSearch"].Focused) return;
5813 if (e.Control || e.Shift || e.Alt)
5814 this._anchorFlag = false;
5817 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
5820 e.SuppressKeyPress = true;
5823 if (asyncTask != null)
5828 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
5830 private void InitializeShortcuts()
5832 this.shortcutCommands = new[]
5834 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5835 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5836 .FocusedOn(FocusedControl.ListTab)
5837 .Do(() => SendKeys.Send("{DOWN}")),
5839 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5840 .FocusedOn(FocusedControl.ListTab)
5841 .Do(() => SendKeys.Send("{UP}")),
5843 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5844 .FocusedOn(FocusedControl.ListTab)
5845 .Do(() => SendKeys.Send("{PGDN}")),
5847 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5848 .FocusedOn(FocusedControl.ListTab)
5849 .Do(() => SendKeys.Send("{PGUP}")),
5851 ShortcutCommand.Create(Keys.F1)
5852 .Do(() => this.OpenApplicationWebsite()),
5854 ShortcutCommand.Create(Keys.F3)
5855 .Do(() => this.MenuItemSearchNext_Click(null, null)),
5857 ShortcutCommand.Create(Keys.F5)
5858 .Do(() => this.DoRefresh()),
5860 ShortcutCommand.Create(Keys.F6)
5861 .Do(() => this.GetReplyAsync()),
5863 ShortcutCommand.Create(Keys.F7)
5864 .Do(() => this.GetDirectMessagesAsync()),
5866 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5867 .NotFocusedOn(FocusedControl.StatusText)
5868 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5870 ShortcutCommand.Create(Keys.G)
5871 .NotFocusedOn(FocusedControl.StatusText)
5872 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5874 ShortcutCommand.Create(Keys.Right, Keys.N)
5875 .FocusedOn(FocusedControl.ListTab)
5876 .Do(() => this.GoRelPost(forward: true)),
5878 ShortcutCommand.Create(Keys.Left, Keys.P)
5879 .FocusedOn(FocusedControl.ListTab)
5880 .Do(() => this.GoRelPost(forward: false)),
5882 ShortcutCommand.Create(Keys.OemPeriod)
5883 .FocusedOn(FocusedControl.ListTab)
5884 .Do(() => this.GoAnchor()),
5886 ShortcutCommand.Create(Keys.I)
5887 .FocusedOn(FocusedControl.ListTab)
5888 .OnlyWhen(() => this.StatusText.Enabled)
5889 .Do(() => this.StatusText.Focus()),
5891 ShortcutCommand.Create(Keys.Enter)
5892 .FocusedOn(FocusedControl.ListTab)
5893 .Do(() => this.MakeReplyOrDirectStatus()),
5895 ShortcutCommand.Create(Keys.R)
5896 .FocusedOn(FocusedControl.ListTab)
5897 .Do(() => this.DoRefresh()),
5899 ShortcutCommand.Create(Keys.L)
5900 .FocusedOn(FocusedControl.ListTab)
5901 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5903 ShortcutCommand.Create(Keys.H)
5904 .FocusedOn(FocusedControl.ListTab)
5905 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5907 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5908 .FocusedOn(FocusedControl.ListTab)
5909 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5911 ShortcutCommand.Create(Keys.S)
5912 .FocusedOn(FocusedControl.ListTab)
5913 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5915 ShortcutCommand.Create(Keys.A)
5916 .FocusedOn(FocusedControl.ListTab)
5917 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5919 // ] in_reply_to参照元へ戻る
5920 ShortcutCommand.Create(Keys.Oem4)
5921 .FocusedOn(FocusedControl.ListTab)
5922 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5924 // [ in_reply_toへジャンプ
5925 ShortcutCommand.Create(Keys.Oem6)
5926 .FocusedOn(FocusedControl.ListTab)
5927 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5929 ShortcutCommand.Create(Keys.Escape)
5930 .FocusedOn(FocusedControl.ListTab)
5932 this._anchorFlag = false;
5933 if (ListTab.SelectedTab != null)
5935 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
5936 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5938 var relTp = ListTab.SelectedTab;
5939 RemoveSpecifiedTab(relTp.Text, false);
5945 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5946 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5947 .FocusedOn(FocusedControl.ListTab)
5948 .Do(() => this._anchorFlag = false, preventDefault: false),
5950 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5951 ShortcutCommand.Create(Keys.Up, Keys.Down)
5952 .FocusedOn(FocusedControl.PostBrowser)
5955 ShortcutCommand.Create(Keys.Control | Keys.R)
5956 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5958 ShortcutCommand.Create(Keys.Control | Keys.D)
5959 .Do(() => this.doStatusDelete()),
5961 ShortcutCommand.Create(Keys.Control | Keys.M)
5962 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5964 ShortcutCommand.Create(Keys.Control | Keys.S)
5965 .Do(() => this.FavoriteChange(FavAdd: true)),
5967 ShortcutCommand.Create(Keys.Control | Keys.I)
5968 .Do(() => this.doRepliedStatusOpen()),
5970 ShortcutCommand.Create(Keys.Control | Keys.Q)
5971 .Do(() => this.doQuoteOfficial()),
5973 ShortcutCommand.Create(Keys.Control | Keys.B)
5974 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5976 ShortcutCommand.Create(Keys.Control | Keys.T)
5977 .Do(() => this.HashManageMenuItem_Click(null, null)),
5979 ShortcutCommand.Create(Keys.Control | Keys.L)
5980 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5982 ShortcutCommand.Create(Keys.Control | Keys.Y)
5983 .NotFocusedOn(FocusedControl.PostBrowser)
5984 .Do(() => this.MultiLineMenuItem_Click(null, null)),
5986 ShortcutCommand.Create(Keys.Control | Keys.F)
5987 .Do(() => this.MenuItemSubSearch_Click(null, null)),
5989 ShortcutCommand.Create(Keys.Control | Keys.U)
5990 .Do(() => this.ShowUserTimeline()),
5992 ShortcutCommand.Create(Keys.Control | Keys.H)
5993 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5995 ShortcutCommand.Create(Keys.Control | Keys.G)
5996 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
5998 ShortcutCommand.Create(Keys.Control | Keys.O)
5999 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6001 ShortcutCommand.Create(Keys.Control | Keys.E)
6002 .Do(() => this.OpenURLMenuItem_Click(null, null)),
6004 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6005 .FocusedOn(FocusedControl.ListTab)
6006 .Do(() => this._colorize = true, preventDefault: false),
6008 ShortcutCommand.Create(Keys.Control | Keys.N)
6009 .FocusedOn(FocusedControl.ListTab)
6010 .Do(() => this.GoNextTab(forward: true)),
6012 ShortcutCommand.Create(Keys.Control | Keys.P)
6013 .FocusedOn(FocusedControl.ListTab)
6014 .Do(() => this.GoNextTab(forward: false)),
6016 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6017 .FocusedOn(FocusedControl.ListTab)
6018 .Do(() => this.CopyStot()),
6020 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6021 ShortcutCommand.Create(Keys.Control | Keys.D1)
6022 .FocusedOn(FocusedControl.ListTab)
6023 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6024 .Do(() => this.ListTab.SelectedIndex = 0),
6026 ShortcutCommand.Create(Keys.Control | Keys.D2)
6027 .FocusedOn(FocusedControl.ListTab)
6028 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6029 .Do(() => this.ListTab.SelectedIndex = 1),
6031 ShortcutCommand.Create(Keys.Control | Keys.D3)
6032 .FocusedOn(FocusedControl.ListTab)
6033 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6034 .Do(() => this.ListTab.SelectedIndex = 2),
6036 ShortcutCommand.Create(Keys.Control | Keys.D4)
6037 .FocusedOn(FocusedControl.ListTab)
6038 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6039 .Do(() => this.ListTab.SelectedIndex = 3),
6041 ShortcutCommand.Create(Keys.Control | Keys.D5)
6042 .FocusedOn(FocusedControl.ListTab)
6043 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6044 .Do(() => this.ListTab.SelectedIndex = 4),
6046 ShortcutCommand.Create(Keys.Control | Keys.D6)
6047 .FocusedOn(FocusedControl.ListTab)
6048 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6049 .Do(() => this.ListTab.SelectedIndex = 5),
6051 ShortcutCommand.Create(Keys.Control | Keys.D7)
6052 .FocusedOn(FocusedControl.ListTab)
6053 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6054 .Do(() => this.ListTab.SelectedIndex = 6),
6056 ShortcutCommand.Create(Keys.Control | Keys.D8)
6057 .FocusedOn(FocusedControl.ListTab)
6058 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6059 .Do(() => this.ListTab.SelectedIndex = 7),
6061 ShortcutCommand.Create(Keys.Control | Keys.D9)
6062 .FocusedOn(FocusedControl.ListTab)
6063 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6065 ShortcutCommand.Create(Keys.Control | Keys.A)
6066 .FocusedOn(FocusedControl.StatusText)
6067 .Do(() => this.StatusText.SelectAll()),
6069 ShortcutCommand.Create(Keys.Control | Keys.V)
6070 .FocusedOn(FocusedControl.StatusText)
6071 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6073 ShortcutCommand.Create(Keys.Control | Keys.Up)
6074 .FocusedOn(FocusedControl.StatusText)
6076 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6078 var inReplyToStatusId = this.inReplyTo?.Item1;
6079 var inReplyToScreenName = this.inReplyTo?.Item2;
6080 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6083 if (_hisIdx < 0) _hisIdx = 0;
6085 var historyItem = this._history[this._hisIdx];
6086 StatusText.Text = historyItem.status;
6087 StatusText.SelectionStart = StatusText.Text.Length;
6088 if (historyItem.inReplyToId != null)
6089 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6091 this.inReplyTo = null;
6094 ShortcutCommand.Create(Keys.Control | Keys.Down)
6095 .FocusedOn(FocusedControl.StatusText)
6097 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6099 var inReplyToStatusId = this.inReplyTo?.Item1;
6100 var inReplyToScreenName = this.inReplyTo?.Item2;
6101 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6104 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6106 var historyItem = this._history[this._hisIdx];
6107 StatusText.Text = historyItem.status;
6108 StatusText.SelectionStart = StatusText.Text.Length;
6109 if (historyItem.inReplyToId != null)
6110 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6112 this.inReplyTo = null;
6115 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6116 .FocusedOn(FocusedControl.StatusText)
6118 if (ListTab.SelectedIndex == 0)
6120 ListTab.SelectedIndex = ListTab.TabCount - 1;
6124 ListTab.SelectedIndex -= 1;
6129 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6130 .FocusedOn(FocusedControl.StatusText)
6132 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6134 ListTab.SelectedIndex = 0;
6138 ListTab.SelectedIndex += 1;
6143 ShortcutCommand.Create(Keys.Control | Keys.Y)
6144 .FocusedOn(FocusedControl.PostBrowser)
6146 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6147 MultiLineMenuItem_Click(null, null);
6150 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6151 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6153 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6154 .Do(() => this.DoRefreshMore()),
6156 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6157 .Do(() => this.GetReplyAsync(loadMore: true)),
6159 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6160 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6162 ShortcutCommand.Create(Keys.Shift | Keys.R)
6163 .NotFocusedOn(FocusedControl.StatusText)
6164 .Do(() => this.DoRefreshMore()),
6166 ShortcutCommand.Create(Keys.Shift | Keys.H)
6167 .FocusedOn(FocusedControl.ListTab)
6168 .Do(() => this.GoTopEnd(GoTop: true)),
6170 ShortcutCommand.Create(Keys.Shift | Keys.L)
6171 .FocusedOn(FocusedControl.ListTab)
6172 .Do(() => this.GoTopEnd(GoTop: false)),
6174 ShortcutCommand.Create(Keys.Shift | Keys.M)
6175 .FocusedOn(FocusedControl.ListTab)
6176 .Do(() => this.GoMiddle()),
6178 ShortcutCommand.Create(Keys.Shift | Keys.G)
6179 .FocusedOn(FocusedControl.ListTab)
6180 .Do(() => this.GoLast()),
6182 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6183 .FocusedOn(FocusedControl.ListTab)
6184 .Do(() => this.MoveMiddle()),
6186 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6187 .FocusedOn(FocusedControl.ListTab)
6188 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6190 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6191 .FocusedOn(FocusedControl.ListTab)
6192 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6194 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6195 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6196 .FocusedOn(FocusedControl.ListTab)
6197 .Do(() => this.GoFav(forward: true)),
6199 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6200 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6201 .FocusedOn(FocusedControl.ListTab)
6202 .Do(() => this.GoFav(forward: false)),
6204 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6205 .FocusedOn(FocusedControl.ListTab)
6206 .Do(() => this.GoBackSelectPostChain()),
6208 ShortcutCommand.Create(Keys.Alt | Keys.R)
6209 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6211 ShortcutCommand.Create(Keys.Alt | Keys.P)
6212 .OnlyWhen(() => this._curPost != null)
6213 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6215 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6216 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6218 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6219 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6221 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6222 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6224 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6225 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6227 // 別タブの同じ書き込みへ(ALT+←/→)
6228 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6229 .FocusedOn(FocusedControl.ListTab)
6230 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6232 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6233 .FocusedOn(FocusedControl.ListTab)
6234 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6236 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6237 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6239 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6240 .Do(() => this.CopyIdUri()),
6242 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6243 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6244 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6245 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6247 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6248 .Do(() => this.FavoriteChange(FavAdd: false)),
6250 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6251 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6253 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6254 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6256 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6257 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6259 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6260 .Do(() => this.doMoveToRTHome()),
6262 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6263 .Do(() => this.FavorareMenuItem_Click(null, null)),
6265 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6266 .FocusedOn(FocusedControl.StatusText)
6268 if (_curList != null && _curList.VirtualListSize != 0 &&
6269 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6271 var idx = _curList.SelectedIndices[0] - 1;
6272 SelectListItem(_curList, idx);
6273 _curList.EnsureVisible(idx);
6277 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6278 .FocusedOn(FocusedControl.StatusText)
6280 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6281 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6283 var idx = _curList.SelectedIndices[0] + 1;
6284 SelectListItem(_curList, idx);
6285 _curList.EnsureVisible(idx);
6289 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6290 .FocusedOn(FocusedControl.StatusText)
6292 if (StatusText.SelectionStart > 0)
6294 int endidx = StatusText.SelectionStart - 1;
6295 string startstr = "";
6296 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6298 char c = StatusText.Text[i];
6299 if (Char.IsLetterOrDigit(c) || c == '_')
6305 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6306 int cnt = AtIdSupl.ItemCount;
6307 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6308 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6312 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6313 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6323 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6324 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6325 .FocusedOn(FocusedControl.ListTab)
6326 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6328 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6329 .FocusedOn(FocusedControl.ListTab)
6330 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6332 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6333 .FocusedOn(FocusedControl.ListTab)
6334 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6336 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6337 .FocusedOn(FocusedControl.ListTab)
6338 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6340 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6341 .FocusedOn(FocusedControl.ListTab)
6342 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6344 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6345 .FocusedOn(FocusedControl.ListTab)
6346 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6348 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6349 .FocusedOn(FocusedControl.ListTab)
6350 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6352 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6353 .FocusedOn(FocusedControl.ListTab)
6354 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6356 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6357 .FocusedOn(FocusedControl.ListTab)
6358 .Do(() => this.SetSortLastColumn()),
6360 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6361 .Do(() => this.FavoritesRetweetOfficial()),
6363 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6364 .Do(() => this.FavoritesRetweetUnofficial()),
6366 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6367 .Do(() => this.OpenUserAppointUrl()),
6369 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6370 .FocusedOn(FocusedControl.PostBrowser)
6371 .Do(() => this.doReTweetUnofficial()),
6373 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6374 .OnlyWhen(() => this.ExistCurrentPost)
6375 .Do(() => this.tweetDetailsView.DoTranslation()),
6377 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6378 .Do(() => this.doReTweetUnofficial()),
6380 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6381 .Do(() => this.CopyUserId()),
6383 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6384 .Do(() => this.tweetThumbnail1.ScrollUp()),
6386 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6387 .Do(() => this.tweetThumbnail1.ScrollDown()),
6389 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6390 .FocusedOn(FocusedControl.ListTab)
6391 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6392 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6396 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6398 // Task を返す非同期処理があれば asyncTask に代入する
6401 // ShortcutCommand に対応しているコマンドはここで処理される
6402 foreach (var command in this.shortcutCommands)
6404 if (command.IsMatch(keyData, focusedOn))
6406 asyncTask = command.RunCommand();
6407 return command.PreventDefault;
6414 private void GoNextTab(bool forward)
6416 int idx = ListTab.SelectedIndex;
6420 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6425 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6427 ListTab.SelectedIndex = idx;
6430 private void CopyStot()
6433 StringBuilder sb = new StringBuilder();
6434 bool IsProtected = false;
6436 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6437 foreach (int idx in _curList.SelectedIndices)
6439 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6440 if (post.IsDeleted) continue;
6443 if (post.RetweetedId != null)
6444 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6446 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6450 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6455 MessageBox.Show(Properties.Resources.CopyStotText1);
6459 clstr = sb.ToString();
6462 Clipboard.SetDataObject(clstr, false, 5, 100);
6464 catch (Exception ex)
6466 MessageBox.Show(ex.Message);
6471 private void CopyIdUri()
6473 if (this._curTab == null)
6476 var tab = this._statuses.GetTabByName(this._curTab.Text);
6477 if (tab == null || tab is DirectMessagesTabModel)
6480 var copyUrls = new List<string>();
6481 foreach (int idx in _curList.SelectedIndices)
6483 var post = tab[idx];
6484 copyUrls.Add(MyCommon.GetStatusUrl(post));
6487 if (copyUrls.Count == 0)
6492 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6494 catch (ExternalException ex)
6496 MessageBox.Show(ex.Message);
6500 private void GoFav(bool forward)
6502 if (_curList.VirtualListSize == 0) return;
6509 if (_curList.SelectedIndices.Count == 0)
6515 fIdx = _curList.SelectedIndices[0] + 1;
6516 if (fIdx > _curList.VirtualListSize - 1) return;
6518 toIdx = _curList.VirtualListSize;
6523 if (_curList.SelectedIndices.Count == 0)
6525 fIdx = _curList.VirtualListSize - 1;
6529 fIdx = _curList.SelectedIndices[0] - 1;
6530 if (fIdx < 0) return;
6536 for (int idx = fIdx; idx != toIdx; idx += stp)
6538 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6540 SelectListItem(_curList, idx);
6541 _curList.EnsureVisible(idx);
6547 private void GoSamePostToAnotherTab(bool left)
6549 if (this._curList.SelectedIndices.Count == 0)
6552 var tab = this._statuses.Tabs[this._curTab.Text];
6554 // Directタブは対象外(見つかるはずがない)
6555 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6558 var selectedIndex = this._curList.SelectedIndices[0];
6559 var selectedStatusId = tab.GetStatusIdAt(selectedIndex);
6561 int fIdx, toIdx, stp;
6566 if (ListTab.SelectedIndex == 0)
6572 fIdx = ListTab.SelectedIndex - 1;
6580 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6586 fIdx = ListTab.SelectedIndex + 1;
6588 toIdx = ListTab.TabCount;
6592 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6594 var targetTab = this._statuses.Tabs[this.ListTab.TabPages[tabidx].Text];
6597 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6600 var foundIndex = targetTab.IndexOf(selectedStatusId);
6601 if (foundIndex != -1)
6603 ListTab.SelectedIndex = tabidx;
6604 SelectListItem(_curList, foundIndex);
6605 _curList.EnsureVisible(foundIndex);
6611 private void GoPost(bool forward)
6613 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6616 var tab = this._statuses.Tabs[this._curTab.Text];
6617 var selectedIndex = this._curList.SelectedIndices[0];
6619 int fIdx, toIdx, stp;
6623 fIdx = selectedIndex + 1;
6624 if (fIdx > tab.AllCount - 1) return;
6625 toIdx = tab.AllCount;
6630 fIdx = selectedIndex - 1;
6631 if (fIdx < 0) return;
6637 if (_curPost.RetweetedId == null)
6639 name = _curPost.ScreenName;
6643 name = _curPost.RetweetedBy;
6645 for (int idx = fIdx; idx != toIdx; idx += stp)
6647 var post = tab[idx];
6648 if (post.RetweetedId == null)
6650 if (post.ScreenName == name)
6652 SelectListItem(_curList, idx);
6653 _curList.EnsureVisible(idx);
6659 if (post.RetweetedBy == name)
6661 SelectListItem(_curList, idx);
6662 _curList.EnsureVisible(idx);
6669 private void GoRelPost(bool forward)
6671 if (this._curList.SelectedIndices.Count == 0)
6674 var tab = this._statuses.Tabs[this._curTab.Text];
6675 var selectedIndex = this._curList.SelectedIndices[0];
6677 int fIdx, toIdx, stp;
6681 fIdx = selectedIndex + 1;
6682 if (fIdx > tab.AllCount - 1) return;
6683 toIdx = tab.AllCount;
6688 fIdx = selectedIndex - 1;
6689 if (fIdx < 0) return;
6696 if (_curPost == null) return;
6697 _anchorPost = _curPost;
6702 if (_anchorPost == null) return;
6705 for (int idx = fIdx; idx != toIdx; idx += stp)
6707 var post = tab[idx];
6708 if (post.ScreenName == _anchorPost.ScreenName ||
6709 post.RetweetedBy == _anchorPost.ScreenName ||
6710 post.ScreenName == _anchorPost.RetweetedBy ||
6711 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6712 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
6713 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
6714 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
6715 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
6717 SelectListItem(_curList, idx);
6718 _curList.EnsureVisible(idx);
6724 private void GoAnchor()
6726 if (_anchorPost == null) return;
6727 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6728 if (idx == -1) return;
6730 SelectListItem(_curList, idx);
6731 _curList.EnsureVisible(idx);
6734 private void GoTopEnd(bool GoTop)
6736 if (_curList.VirtualListSize == 0)
6744 _item = _curList.GetItemAt(0, 25);
6752 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6754 idx = _curList.VirtualListSize - 1;
6758 SelectListItem(_curList, idx);
6761 private void GoMiddle()
6763 if (_curList.VirtualListSize == 0)
6771 _item = _curList.GetItemAt(0, 0);
6781 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6784 idx2 = _curList.VirtualListSize - 1;
6790 idx3 = (idx1 + idx2) / 2;
6792 SelectListItem(_curList, idx3);
6795 private void GoLast()
6797 if (_curList.VirtualListSize == 0) return;
6799 if (_statuses.SortOrder == SortOrder.Ascending)
6801 SelectListItem(_curList, _curList.VirtualListSize - 1);
6802 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6806 SelectListItem(_curList, 0);
6807 _curList.EnsureVisible(0);
6811 private void MoveTop()
6813 if (_curList.SelectedIndices.Count == 0) return;
6814 int idx = _curList.SelectedIndices[0];
6815 if (_statuses.SortOrder == SortOrder.Ascending)
6817 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6821 _curList.EnsureVisible(0);
6823 _curList.EnsureVisible(idx);
6826 private async Task GoInReplyToPostTree()
6828 if (_curPost == null) return;
6830 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6832 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
6836 var post = await tw.GetStatusApi(false, _curPost.StatusId);
6838 _curPost.InReplyToStatusId = post.InReplyToStatusId;
6839 _curPost.InReplyToUser = post.InReplyToUser;
6840 _curPost.IsReply = post.IsReply;
6841 this.PurgeListViewItemCache();
6842 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
6844 catch (WebApiException ex)
6846 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6850 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
6852 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
6854 replyChains = new Stack<ReplyChain>();
6856 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
6859 string inReplyToTabName;
6860 long inReplyToId = _curPost.InReplyToStatusId.Value;
6861 string inReplyToUser = _curPost.InReplyToUser;
6862 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6864 var inReplyToPosts = from tab in _statuses.Tabs.Values
6865 orderby tab != curTabClass
6866 from post in tab.Posts.Values
6867 where post.StatusId == inReplyToId
6868 let index = tab.IndexOf(post.StatusId)
6870 select new {Tab = tab, Index = index};
6872 var inReplyPost = inReplyToPosts.FirstOrDefault();
6873 if (inReplyPost == null)
6877 await Task.Run(async () =>
6879 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
6880 .ConfigureAwait(false);
6883 _statuses.AddPost(post);
6884 _statuses.DistributePosts();
6887 catch (WebApiException ex)
6889 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6890 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6894 this.RefreshTimeline();
6896 inReplyPost = inReplyToPosts.FirstOrDefault();
6897 if (inReplyPost == null)
6899 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6903 inReplyToTabName = inReplyPost.Tab.TabName;
6904 inReplyToIndex = inReplyPost.Index;
6906 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
6907 DetailsListView listView = (DetailsListView)tabPage.Tag;
6909 if (_curTab != tabPage)
6911 this.ListTab.SelectTab(tabPage);
6914 this.SelectListItem(listView, inReplyToIndex);
6915 listView.EnsureVisible(inReplyToIndex);
6918 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6920 if (_curPost == null) return;
6922 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6923 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6927 if (_curPost.InReplyToStatusId != null)
6929 var posts = from t in _statuses.Tabs
6930 from p in t.Value.Posts
6931 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
6932 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6934 orderby isForward ? indexOf : indexOf * -1
6935 orderby t.Value != curTabClass
6936 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
6939 var postList = posts.ToList();
6940 for (int i = postList.Count - 1; i >= 0; i--)
6943 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
6945 postList.RemoveAt(index);
6948 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
6949 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
6950 if (post == null) post = postList.First();
6951 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6952 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6953 SelectListItem(listView, post.Index);
6954 listView.EnsureVisible(post.Index);
6956 catch (InvalidOperationException)
6964 if (replyChains == null || replyChains.Count < 1)
6966 var posts = from t in _statuses.Tabs
6967 from p in t.Value.Posts
6968 where p.Value.InReplyToStatusId == _curPost.StatusId
6969 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6972 orderby t.Value != curTabClass
6973 select new {Tab = t.Value, Index = indexOf};
6976 var post = posts.First();
6977 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6978 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6979 SelectListItem(listView, post.Index);
6980 listView.EnsureVisible(post.Index);
6982 catch (InvalidOperationException)
6989 ReplyChain chainHead = replyChains.Pop();
6990 if (chainHead.InReplyToId == _curPost.StatusId)
6992 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7001 ListTab.SelectTab(chainHead.OriginalTab);
7007 SelectListItem(_curList, idx);
7008 _curList.EnsureVisible(idx);
7014 this.GoBackInReplyToPostTree(parallel);
7020 private void GoBackSelectPostChain()
7022 if (this.selectPostChains.Count > 1)
7031 this.selectPostChains.Pop();
7032 var tabPostPair = this.selectPostChains.Peek();
7034 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7036 if (tabPostPair.Item2 != null)
7038 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7039 if (idx == -1) continue; //該当ポストが存在しないので無視
7042 tp = tabPostPair.Item1;
7044 this.selectPostChains.Pop();
7046 catch (InvalidOperationException)
7052 while (this.selectPostChains.Count > 1);
7057 //履歴が残り1つであればクリアしておく
7058 if (this.selectPostChains.Count == 1)
7059 this.selectPostChains.Clear();
7063 DetailsListView lst = (DetailsListView)tp.Tag;
7064 this.ListTab.SelectedTab = tp;
7067 SelectListItem(lst, idx);
7068 lst.EnsureVisible(idx);
7074 private void PushSelectPostChain()
7076 int count = this.selectPostChains.Count;
7079 var p = this.selectPostChains.Peek();
7080 if (p.Item1 == this._curTab)
7082 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7083 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7086 if (count >= 2500) TrimPostChain();
7087 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7090 private void TrimPostChain()
7092 if (this.selectPostChains.Count <= 2000) return;
7093 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7094 for (int i = 0; i < 2000; i++)
7096 p.Push(this.selectPostChains.Pop());
7098 this.selectPostChains.Clear();
7099 for (int i = 0; i < 2000; i++)
7101 this.selectPostChains.Push(p.Pop());
7105 private bool GoStatus(long statusId)
7107 if (statusId == 0) return false;
7108 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7110 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7112 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7113 ListTab.SelectedIndex = tabidx;
7114 SelectListItem(_curList, idx);
7115 _curList.EnsureVisible(idx);
7122 private bool GoDirectMessage(long statusId)
7124 if (statusId == 0) return false;
7125 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7127 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7129 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7130 ListTab.SelectedIndex = tabidx;
7131 SelectListItem(_curList, idx);
7132 _curList.EnsureVisible(idx);
7139 private void MyList_MouseClick(object sender, MouseEventArgs e)
7141 _anchorFlag = false;
7144 private void StatusText_Enter(object sender, EventArgs e)
7146 // フォーカスの戻り先を StatusText に設定
7147 this.Tag = StatusText;
7148 StatusText.BackColor = _clInputBackcolor;
7151 public Color InputBackColor
7153 get { return _clInputBackcolor; }
7154 set { _clInputBackcolor = value; }
7157 private void StatusText_Leave(object sender, EventArgs e)
7159 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7160 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7161 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7164 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7167 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7170 e.SuppressKeyPress = true;
7173 this.StatusText_TextChanged(null, null);
7175 if (asyncTask != null)
7179 private void SaveConfigsAll(bool ifModified)
7183 SaveConfigsCommon();
7190 if (ModifySettingCommon) SaveConfigsCommon();
7191 if (ModifySettingLocal) SaveConfigsLocal();
7192 if (ModifySettingAtId) SaveConfigsAtId();
7196 private void SaveConfigsAtId()
7198 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7200 ModifySettingAtId = false;
7201 SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7202 SettingManager.SaveAtIdList();
7205 private void SaveConfigsCommon()
7207 if (_ignoreConfigSave) return;
7209 ModifySettingCommon = false;
7212 _cfgCommon.UserName = tw.Username;
7213 _cfgCommon.UserId = tw.UserId;
7214 _cfgCommon.Token = tw.AccessToken;
7215 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7217 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7218 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7220 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7223 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7224 switch (_statuses.SortMode)
7226 case ComparerMode.Nickname: //ニックネーム
7227 _cfgCommon.SortColumn = 1;
7229 case ComparerMode.Data: //本文
7230 _cfgCommon.SortColumn = 2;
7232 case ComparerMode.Id: //時刻=発言Id
7233 _cfgCommon.SortColumn = 3;
7235 case ComparerMode.Name: //名前
7236 _cfgCommon.SortColumn = 4;
7238 case ComparerMode.Source: //Source
7239 _cfgCommon.SortColumn = 7;
7243 _cfgCommon.HashTags = HashMgr.HashHistories;
7244 if (HashMgr.IsPermanent)
7246 _cfgCommon.HashSelected = HashMgr.UseHash;
7250 _cfgCommon.HashSelected = "";
7252 _cfgCommon.HashIsHead = HashMgr.IsHead;
7253 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7254 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7255 if (ToolStripFocusLockMenuItem != null &&
7256 ToolStripFocusLockMenuItem.IsDisposed == false)
7258 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7260 _cfgCommon.TrackWord = tw.TrackWord;
7261 _cfgCommon.AllAtReply = tw.AllAtReply;
7262 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7263 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7265 SettingManager.SaveCommon();
7269 private void SaveConfigsLocal()
7271 if (_ignoreConfigSave) return;
7274 ModifySettingLocal = false;
7275 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7276 _cfgLocal.FormSize = _mySize;
7277 _cfgLocal.FormLocation = _myLoc;
7278 _cfgLocal.SplitterDistance = _mySpDis;
7279 _cfgLocal.PreviewDistance = _mySpDis3;
7280 _cfgLocal.StatusMultiline = StatusText.Multiline;
7281 _cfgLocal.StatusTextHeight = _mySpDis2;
7283 _cfgLocal.FontUnread = _fntUnread;
7284 _cfgLocal.ColorUnread = _clUnread;
7285 _cfgLocal.FontRead = _fntReaded;
7286 _cfgLocal.ColorRead = _clReaded;
7287 _cfgLocal.FontDetail = _fntDetail;
7288 _cfgLocal.ColorDetail = _clDetail;
7289 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7290 _cfgLocal.ColorDetailLink = _clDetailLink;
7291 _cfgLocal.ColorFav = _clFav;
7292 _cfgLocal.ColorOWL = _clOWL;
7293 _cfgLocal.ColorRetweet = _clRetweet;
7294 _cfgLocal.ColorSelf = _clSelf;
7295 _cfgLocal.ColorAtSelf = _clAtSelf;
7296 _cfgLocal.ColorTarget = _clTarget;
7297 _cfgLocal.ColorAtTarget = _clAtTarget;
7298 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7299 _cfgLocal.ColorAtTo = _clAtTo;
7300 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7301 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7302 _cfgLocal.ColorInputFont = _clInputFont;
7303 _cfgLocal.FontInputFont = _fntInputFont;
7305 if (_ignoreConfigSave) return;
7306 SettingManager.SaveLocal();
7310 private void SaveConfigsTabs()
7312 var tabSettingList = new List<SettingTabs.SettingTabItem>();
7314 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7315 .Select(x => this._statuses.Tabs[x.Text])
7316 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7318 foreach (var tab in tabs)
7320 if (!tab.IsPermanentTabType)
7323 var tabSetting = new SettingTabs.SettingTabItem
7325 TabName = tab.TabName,
7326 TabType = tab.TabType,
7327 UnreadManage = tab.UnreadManage,
7328 Protected = tab.Protected,
7329 Notify = tab.Notify,
7330 SoundFile = tab.SoundFile,
7333 var filterTab = tab as FilterTabModel;
7334 if (filterTab != null)
7335 tabSetting.FilterArray = filterTab.FilterArray;
7337 var userTab = tab as UserTimelineTabModel;
7338 if (userTab != null)
7339 tabSetting.User = userTab.ScreenName;
7341 var searchTab = tab as PublicSearchTabModel;
7342 if (searchTab != null)
7344 tabSetting.SearchWords = searchTab.SearchWords;
7345 tabSetting.SearchLang = searchTab.SearchLang;
7348 var listTab = tab as ListTimelineTabModel;
7349 if (listTab != null)
7350 tabSetting.ListInfo = listTab.ListInfo;
7352 tabSettingList.Add(tabSetting);
7355 SettingManager.Tabs.Tabs = tabSettingList;
7356 SettingManager.SaveTabs();
7359 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7362 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7363 if (ret != DialogResult.OK)
7366 var match = Twitter.StatusUrlRegex.Match(inputText);
7369 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7370 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7376 var statusId = long.Parse(match.Groups["StatusId"].Value);
7377 await this.OpenRelatedTab(statusId);
7379 catch (TabException ex)
7381 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7385 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7387 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7388 Properties.Resources.SaveLogMenuItem_ClickText2,
7389 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7390 if (rslt == DialogResult.Cancel) return;
7392 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7393 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7394 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7395 SaveFileDialog1.FilterIndex = 0;
7396 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7397 SaveFileDialog1.RestoreDirectory = true;
7399 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7401 if (!SaveFileDialog1.ValidateNames) return;
7402 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7404 if (rslt == DialogResult.Yes)
7407 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7409 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7410 string protect = "";
7411 if (post.IsProtect) protect = "Protect";
7412 sw.WriteLine(post.Nickname + "\t" +
7413 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7414 post.CreatedAt + "\t" +
7415 post.ScreenName + "\t" +
7416 post.StatusId + "\t" +
7417 post.ImageUrl + "\t" +
7418 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7424 foreach (int idx in _curList.SelectedIndices)
7426 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7427 string protect = "";
7428 if (post.IsProtect) protect = "Protect";
7429 sw.WriteLine(post.Nickname + "\t" +
7430 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7431 post.CreatedAt + "\t" +
7432 post.ScreenName + "\t" +
7433 post.StatusId + "\t" +
7434 post.ImageUrl + "\t" +
7435 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7441 this.TopMost = this._cfgCommon.AlwaysTop;
7444 public bool TabRename(string origTabName, out string newTabName)
7448 using (InputTabName inputName = new InputTabName())
7450 inputName.TabName = origTabName;
7451 inputName.ShowDialog();
7452 if (inputName.DialogResult == DialogResult.Cancel) return false;
7453 newTabName = inputName.TabName;
7455 this.TopMost = this._cfgCommon.AlwaysTop;
7456 if (!string.IsNullOrEmpty(newTabName))
7459 for (int i = 0; i < ListTab.TabCount; i++)
7461 if (ListTab.TabPages[i].Text == newTabName)
7463 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7464 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7469 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
7470 .FirstOrDefault(x => x.Text == origTabName);
7473 if (tabPage != null)
7474 tabPage.Text = newTabName;
7476 _statuses.RenameTab(origTabName, newTabName);
7478 SaveConfigsCommon();
7480 _rclickTabName = newTabName;
7489 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7491 if (e.Button == MouseButtons.Middle)
7493 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7495 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7497 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7498 this.SaveConfigsTabs();
7505 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7508 TabRename(this.ListTab.SelectedTab.Text, out _);
7511 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7513 if (this._cfgCommon.TabMouseLock) return;
7514 if (e.Button == MouseButtons.Left)
7516 for (int i = 0; i < ListTab.TabPages.Count; i++)
7518 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7521 _tabMouseDownPoint = e.Location;
7532 private void ListTab_DragEnter(object sender, DragEventArgs e)
7534 if (e.Data.GetDataPresent(typeof(TabPage)))
7535 e.Effect = DragDropEffects.Move;
7537 e.Effect = DragDropEffects.None;
7540 private void ListTab_DragDrop(object sender, DragEventArgs e)
7542 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7547 Point cpos = new Point(e.X, e.Y);
7548 Point spos = ListTab.PointToClient(cpos);
7550 for (i = 0; i < ListTab.TabPages.Count; i++)
7552 Rectangle rect = ListTab.GetTabRect(i);
7553 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7554 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7556 tn = ListTab.TabPages[i].Text;
7557 if (spos.X <= (rect.Left + rect.Right) / 2)
7566 //タブのないところにドロップ->最後尾へ移動
7567 if (string.IsNullOrEmpty(tn))
7569 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7571 i = ListTab.TabPages.Count - 1;
7574 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7575 if (tp.Text == tn) return;
7577 ReOrderTab(tp.Text, tn, bef);
7580 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7582 var baseIndex = this.GetTabPageIndex(baseTabText);
7583 if (baseIndex == -1)
7586 var targetIndex = this.GetTabPageIndex(targetTabText);
7587 if (targetIndex == -1)
7590 using (ControlTransaction.Layout(this.ListTab))
7592 var mTp = this.ListTab.TabPages[targetIndex];
7593 this.ListTab.TabPages.Remove(mTp);
7595 if (targetIndex < baseIndex)
7598 if (isBeforeBaseTab)
7599 ListTab.TabPages.Insert(baseIndex, mTp);
7601 ListTab.TabPages.Insert(baseIndex + 1, mTp);
7607 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7609 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7610 //isReply:true=@,false=DM
7611 if (!StatusText.Enabled) return;
7612 if (_curList == null) return;
7613 if (_curTab == null) return;
7614 if (!this.ExistCurrentPost) return;
7616 // 複数あてリプライはReplyではなく通常ポスト
7617 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7618 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7619 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7621 if (_curList.SelectedIndices.Count > 0)
7624 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7627 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7630 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7631 StatusText.SelectionStart = StatusText.Text.Length;
7633 this.inReplyTo = null;
7636 if (string.IsNullOrEmpty(StatusText.Text))
7640 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7641 StatusText.Text = "@" + _curPost.ScreenName + " ";
7643 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7644 var inReplyToScreenName = this._curPost.ScreenName;
7645 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7653 //1件選んでEnter or DoubleClick
7654 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7656 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7659 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7660 var inReplyToScreenName = this._curPost.ScreenName;
7661 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7665 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7668 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7671 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7672 this.inReplyTo = null;
7677 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7678 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7679 var inReplyToScreenName = this._curPost.ScreenName;
7680 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7687 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7688 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7689 this.inReplyTo = null;
7694 //1件選んでCtrl-Rの場合(返信先操作せず)
7695 int sidx = StatusText.SelectionStart;
7696 string id = "@" + _curPost.ScreenName + " ";
7699 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7704 StatusText.Text = StatusText.Text.Insert(sidx, id);
7706 //if (StatusText.Text.StartsWith("@"))
7709 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7710 // sidx += 5 + _curPost.ScreenName.Length;
7715 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7716 // sidx += 3 + _curPost.ScreenName.Length;
7718 StatusText.SelectionStart = sidx;
7721 //_reply_to_name = null;
7729 if (!isAuto && !isReply) return;
7731 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7735 //Enter or DoubleClick
7737 string sTxt = StatusText.Text;
7738 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7741 this.inReplyTo = null;
7743 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7745 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7746 if (!sTxt.Contains("@" + post.ScreenName + " "))
7748 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7749 //sTxt = "@" + post.ScreenName + " " + sTxt;
7752 StatusText.Text = sTxt;
7757 if (_curList.SelectedIndices.Count > 1)
7762 int sidx = StatusText.SelectionStart;
7763 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7765 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7766 if (!ids.Contains("@" + post.ScreenName + " ") &&
7767 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7769 ids += "@" + post.ScreenName + " ";
7773 foreach (string nm in post.ReplyToList)
7775 if (!ids.Contains("@" + nm + " ") &&
7776 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7778 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7780 ids += "@" + m.Result("${id}") + " ";
7782 ids += "@" + nm + " ";
7787 if (ids.Length == 0) return;
7788 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7790 StatusText.Text = ". " + StatusText.Text;
7792 this.inReplyTo = null;
7796 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7801 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7803 //if (StatusText.Text.StartsWith("@"))
7805 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7806 // sidx += 2 + ids.Length;
7810 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7811 // sidx += 1 + ids.Length;
7813 StatusText.SelectionStart = sidx;
7819 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7822 int sidx = StatusText.SelectionStart;
7823 PostClass post = _curPost;
7824 if (!ids.Contains("@" + post.ScreenName + " ") &&
7825 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7827 ids += "@" + post.ScreenName + " ";
7829 foreach (string nm in post.ReplyToList)
7831 if (!ids.Contains("@" + nm + " ") &&
7832 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7834 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7836 ids += "@" + m.Result("${id}") + " ";
7838 ids += "@" + nm + " ";
7841 if (!string.IsNullOrEmpty(post.RetweetedBy))
7843 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
7844 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7846 ids += "@" + post.RetweetedBy + " ";
7849 if (ids.Length == 0) return;
7850 if (string.IsNullOrEmpty(StatusText.Text))
7853 StatusText.Text = ids;
7854 StatusText.SelectionStart = ids.Length;
7857 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7858 var inReplyToScreenName = this._curPost.ScreenName;
7859 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7865 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7870 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7872 StatusText.SelectionStart = sidx;
7878 StatusText.SelectionStart = StatusText.Text.Length;
7883 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7888 private static int iconCnt = 0;
7889 private static int blinkCnt = 0;
7890 private static bool blink = false;
7891 private static bool idle = false;
7893 private async Task RefreshTasktrayIcon()
7896 await this.Colorize();
7898 if (!TimerRefreshIcon.Enabled) return;
7899 //Static usCheckCnt As int = 0
7901 //Static iconDlListTopItem As ListViewItem = null
7903 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7904 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7906 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7908 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7914 //if (usCheckCnt > 300) //1min
7917 // if (!this.IsReceivedUserStream)
7919 // TraceOut("ReconnectUserStream");
7920 // tw.ReconnectUserStream();
7924 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7926 if (iconCnt >= this.NIconRefresh.Length)
7934 SaveConfigsAll(true);
7939 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7941 _myStatusError = false;
7945 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
7946 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
7948 if (blinkCnt > 0) return;
7950 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
7952 NotifyIcon1.Icon = ReplyIcon;
7956 NotifyIcon1.Icon = ReplyIconBlink;
7964 //優先度:エラー→オフライン→アイドル
7968 NotifyIcon1.Icon = NIconAtRed;
7971 if (_myStatusOnline)
7973 NotifyIcon1.Icon = NIconAt;
7977 NotifyIcon1.Icon = NIconAtSmoke;
7981 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
7984 await this.RefreshTasktrayIcon();
7987 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7989 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7990 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7992 if (ListTab != null && ListTab.SelectedTab != null)
7993 _rclickTabName = ListTab.SelectedTab.Text;
7998 if (_statuses == null) return;
7999 if (_statuses.Tabs == null) return;
8002 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out tb))
8005 NotifyDispMenuItem.Checked = tb.Notify;
8006 this.NotifyTbMenuItem.Checked = tb.Notify;
8008 soundfileListup = true;
8009 SoundFileComboBox.Items.Clear();
8010 this.SoundFileTbComboBox.Items.Clear();
8011 SoundFileComboBox.Items.Add("");
8012 this.SoundFileTbComboBox.Items.Add("");
8013 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8014 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8016 oDir = oDir.GetDirectories("Sounds")[0];
8018 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8020 SoundFileComboBox.Items.Add(oFile.Name);
8021 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8023 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8024 if (idx == -1) idx = 0;
8025 SoundFileComboBox.SelectedIndex = idx;
8026 this.SoundFileTbComboBox.SelectedIndex = idx;
8027 soundfileListup = false;
8028 UreadManageMenuItem.Checked = tb.UnreadManage;
8029 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8031 TabMenuControl(_rclickTabName);
8034 private void TabMenuControl(string tabName)
8036 var tabInfo = _statuses.GetTabByName(tabName);
8038 this.FilterEditMenuItem.Enabled = true;
8039 this.EditRuleTbMenuItem.Enabled = true;
8041 if (tabInfo.IsDefaultTabType)
8043 this.ProtectTabMenuItem.Enabled = false;
8044 this.ProtectTbMenuItem.Enabled = false;
8048 this.ProtectTabMenuItem.Enabled = true;
8049 this.ProtectTbMenuItem.Enabled = true;
8052 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8054 this.ProtectTabMenuItem.Checked = true;
8055 this.ProtectTbMenuItem.Checked = true;
8056 this.DeleteTabMenuItem.Enabled = false;
8057 this.DeleteTbMenuItem.Enabled = false;
8061 this.ProtectTabMenuItem.Checked = false;
8062 this.ProtectTbMenuItem.Checked = false;
8063 this.DeleteTabMenuItem.Enabled = true;
8064 this.DeleteTbMenuItem.Enabled = true;
8068 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8070 var checkState = ((ToolStripMenuItem)sender).Checked;
8073 this.ProtectTbMenuItem.Checked = checkState;
8074 this.ProtectTabMenuItem.Checked = checkState;
8077 this.DeleteTabMenuItem.Enabled = !checkState;
8078 this.DeleteTbMenuItem.Enabled = !checkState;
8080 if (string.IsNullOrEmpty(_rclickTabName)) return;
8081 _statuses.Tabs[_rclickTabName].Protected = checkState;
8086 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8088 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8089 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8091 if (string.IsNullOrEmpty(_rclickTabName)) return;
8092 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8097 public void ChangeTabUnreadManage(string tabName, bool isManage)
8099 var idx = this.GetTabPageIndex(tabName);
8103 _statuses.Tabs[tabName].UnreadManage = isManage;
8104 if (this._cfgCommon.TabIconDisp)
8106 if (_statuses.Tabs[tabName].UnreadCount > 0)
8107 ListTab.TabPages[idx].ImageIndex = 0;
8109 ListTab.TabPages[idx].ImageIndex = -1;
8112 if (_curTab.Text == tabName)
8114 this.PurgeListViewItemCache();
8118 SetMainWindowTitle();
8119 SetStatusLabelUrl();
8120 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8123 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8125 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8126 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8128 if (string.IsNullOrEmpty(_rclickTabName)) return;
8130 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8135 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8137 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8139 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8144 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8146 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8148 RemoveSpecifiedTab(_rclickTabName, true);
8152 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8154 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8156 using (var fltDialog = new FilterDialog())
8158 fltDialog.Owner = this;
8159 fltDialog.SetCurrent(_rclickTabName);
8160 fltDialog.ShowDialog(this);
8162 this.TopMost = this._cfgCommon.AlwaysTop;
8164 this.ApplyPostFilters();
8168 private void AddTabMenuItem_Click(object sender, EventArgs e)
8170 string tabName = null;
8171 MyCommon.TabUsageType tabUsage;
8172 using (InputTabName inputName = new InputTabName())
8174 inputName.TabName = _statuses.MakeTabName("MyTab");
8175 inputName.IsShowUsage = true;
8176 inputName.ShowDialog();
8177 if (inputName.DialogResult == DialogResult.Cancel) return;
8178 tabName = inputName.TabName;
8179 tabUsage = inputName.Usage;
8181 this.TopMost = this._cfgCommon.AlwaysTop;
8182 if (!string.IsNullOrEmpty(tabName))
8185 ListElement list = null;
8186 if (tabUsage == MyCommon.TabUsageType.Lists)
8188 using (ListAvailable listAvail = new ListAvailable())
8190 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8191 if (listAvail.SelectedList == null) return;
8192 list = listAvail.SelectedList;
8199 case MyCommon.TabUsageType.UserDefined:
8200 tab = new FilterTabModel(tabName);
8202 case MyCommon.TabUsageType.PublicSearch:
8203 tab = new PublicSearchTabModel(tabName);
8205 case MyCommon.TabUsageType.Lists:
8206 tab = new ListTimelineTabModel(tabName, list);
8212 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8214 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8215 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8221 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8223 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8224 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8226 if (tabUsage == MyCommon.TabUsageType.Lists)
8228 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8229 var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8230 this.GetListTimelineAsync(listTab);
8236 private void TabMenuItem_Click(object sender, EventArgs e)
8238 using (var fltDialog = new FilterDialog())
8240 fltDialog.Owner = this;
8243 foreach (int idx in _curList.SelectedIndices)
8247 if (!SelectTab(out tabName)) return;
8249 fltDialog.SetCurrent(tabName);
8250 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8252 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8256 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8258 fltDialog.ShowDialog(this);
8259 this.TopMost = this._cfgCommon.AlwaysTop;
8263 this.ApplyPostFilters();
8265 if (this.ListTab.SelectedTab != null &&
8266 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8268 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8272 protected override bool ProcessDialogKey(Keys keyData)
8274 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8275 if ((keyData & Keys.KeyCode) == Keys.Enter)
8277 if (StatusText.Focused)
8279 bool _NewLine = false;
8282 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8284 if (StatusText.Multiline)
8286 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8288 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8292 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8296 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8298 if (StatusText.Multiline)
8300 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8302 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8306 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8312 if (StatusText.Multiline)
8314 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8316 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8317 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8321 if (((keyData & Keys.Shift) == Keys.Shift) ||
8322 (((keyData & Keys.Control) != Keys.Control) &&
8323 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8329 int pos1 = StatusText.SelectionStart;
8330 if (StatusText.SelectionLength > 0)
8332 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8334 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8335 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8340 PostButton_Click(null, null);
8344 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8345 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8346 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8348 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8353 return base.ProcessDialogKey(keyData);
8356 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8358 MakeReplyOrDirectStatus(false, true, true);
8361 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8364 if (_curList.SelectedIndices.Count == 0) return;
8366 var tab = this._statuses.Tabs[this._curTab.Text];
8367 var screenNameArray = this._curList.SelectedIndices.Cast<int>()
8368 .Select(x => tab[x])
8369 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8372 this.AddFilterRuleByScreenName(screenNameArray);
8374 if (screenNameArray.Length != 0)
8376 List<string> atids = new List<string>();
8377 foreach (var screenName in screenNameArray)
8379 atids.Add("@" + screenName);
8381 int cnt = AtIdSupl.ItemCount;
8382 AtIdSupl.AddRangeItem(atids.ToArray());
8383 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8387 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8389 if (this._curList.SelectedIndices.Count == 0)
8392 var tab = this._statuses.Tabs[this._curTab.Text];
8393 var sourceArray = this._curList.SelectedIndices.Cast<int>()
8394 .Select(x => tab[x].Source).ToArray();
8396 this.AddFilterRuleBySource(sourceArray);
8399 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8403 if (!SelectTab(out tabName)) return;
8405 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8409 if (tab.TabType != MyCommon.TabUsageType.Mute)
8411 this.MoveOrCopy(out mv, out mk);
8415 // ミュートタブでは常に MoveMatches を true にする
8420 foreach (var screenName in screenNameArray)
8422 tab.AddFilter(new PostFilterRule
8424 FilterName = screenName,
8425 UseNameField = true,
8429 FilterByUrl = false,
8433 this.ApplyPostFilters();
8437 public void AddFilterRuleBySource(params string[] sourceArray)
8439 // タブ選択ダイアログを表示(or追加)
8441 if (!this.SelectTab(out tabName))
8444 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8448 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8450 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8451 this.MoveOrCopy(out mv, out mk);
8455 // ミュートタブでは常に MoveMatches を true にする
8460 // 振り分けルールに追加するSource
8461 foreach (var source in sourceArray)
8463 filterTab.AddFilter(new PostFilterRule
8465 FilterSource = source,
8469 FilterByUrl = false,
8473 this.ApplyPostFilters();
8474 this.SaveConfigsTabs();
8477 private bool SelectTab(out string tabName)
8484 using (var dialog = new TabsDialog(_statuses))
8486 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8488 var selectedTab = dialog.SelectedTab;
8489 tabName = selectedTab == null ? null : selectedTab.TabName;
8492 ListTab.SelectedTab.Focus();
8494 if (tabName == null)
8496 using (InputTabName inputName = new InputTabName())
8498 inputName.TabName = _statuses.MakeTabName("MyTab");
8499 inputName.ShowDialog();
8500 if (inputName.DialogResult == DialogResult.Cancel) return false;
8501 tabName = inputName.TabName;
8503 this.TopMost = this._cfgCommon.AlwaysTop;
8504 if (!string.IsNullOrEmpty(tabName))
8506 var tab = new FilterTabModel(tabName);
8507 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8509 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8510 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8528 private void MoveOrCopy(out bool move, out bool mark)
8532 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8533 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8541 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8542 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8552 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8557 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8562 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8564 if (StatusText.Focused)
8567 StatusText.SelectAll();
8571 // ListView上でのCtrl+A
8572 NativeMethods.SelectAllItems(this._curList);
8576 private void MoveMiddle()
8582 if (_curList.SelectedIndices.Count == 0) return;
8584 int idx = _curList.SelectedIndices[0];
8586 _item = _curList.GetItemAt(0, 25);
8592 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8594 idx2 = _curList.VirtualListSize - 1;
8598 idx -= Math.Abs(idx1 - idx2) / 2;
8599 if (idx < 0) idx = 0;
8601 _curList.EnsureVisible(_curList.VirtualListSize - 1);
8602 _curList.EnsureVisible(idx);
8605 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8607 var linkElements = this.tweetDetailsView.GetLinkElements();
8609 if (linkElements.Length > 0)
8611 UrlDialog.ClearUrl();
8613 string openUrlStr = "";
8615 if (linkElements.Length == 1)
8617 // ツイートに含まれる URL が 1 つのみの場合
8618 // => OpenURL ダイアログを表示せずにリンクを開く
8623 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8625 catch (ArgumentException)
8634 if (string.IsNullOrEmpty(urlStr)) return;
8635 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8637 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8638 await this.OpenUriAsync(new Uri(openUrlStr));
8642 // ツイートに含まれる URL が複数ある場合
8643 // => OpenURL を表示しユーザーが選択したリンクを開く
8645 foreach (var linkElm in linkElements)
8648 string linkText = "";
8652 urlStr = linkElm.GetAttribute("title");
8653 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8654 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8655 linkText = linkElm.InnerText;
8657 catch (ArgumentException)
8666 if (string.IsNullOrEmpty(urlStr)) continue;
8667 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8671 if (UrlDialog.ShowDialog() == DialogResult.OK)
8673 openUrlStr = UrlDialog.SelectedUrl;
8675 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8676 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8683 this.TopMost = this._cfgCommon.AlwaysTop;
8688 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8690 if (string.IsNullOrEmpty(_rclickTabName)) return;
8691 ClearTab(_rclickTabName, true);
8694 private void ClearTab(string tabName, bool showWarning)
8698 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8699 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8705 _statuses.ClearTabIds(tabName);
8706 if (ListTab.SelectedTab.Text == tabName)
8709 _anchorFlag = false;
8710 this.PurgeListViewItemCache();
8714 foreach (TabPage tb in ListTab.TabPages)
8716 if (tb.Text == tabName)
8718 ((DetailsListView)tb.Tag).VirtualListSize = 0;
8723 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8725 SetMainWindowTitle();
8726 SetStatusLabelUrl();
8729 private static long followers = 0;
8731 private void SetMainWindowTitle()
8734 StringBuilder ttl = new StringBuilder(256);
8737 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
8738 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8739 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8740 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8742 foreach (var tab in _statuses.Tabs.Values)
8744 ur += tab.UnreadCount;
8749 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
8750 ttl.Append(Application.ProductName);
8752 switch (this._cfgCommon.DispLatestPost)
8754 case MyCommon.DispTitleEnum.Ver:
8755 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8757 case MyCommon.DispTitleEnum.Post:
8758 if (_history != null && _history.Count > 1)
8759 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8761 case MyCommon.DispTitleEnum.UnreadRepCount:
8762 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8764 case MyCommon.DispTitleEnum.UnreadAllCount:
8765 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8767 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8768 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8770 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8771 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8773 case MyCommon.DispTitleEnum.OwnStatus:
8774 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8775 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8781 this.Text = ttl.ToString();
8783 catch (AccessViolationException)
8785 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8789 private string GetStatusLabelText()
8792 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8793 if (_statuses == null) return "";
8794 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8795 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8796 if (tbRep == null || tbDm == null) return "";
8797 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8802 StringBuilder slbl = new StringBuilder(256);
8805 foreach (var tab in _statuses.Tabs.Values)
8807 ur += tab.UnreadCount;
8809 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
8811 tur = tab.UnreadCount;
8822 UnreadAtCounter = urat;
8824 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8826 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8827 if (this._cfgCommon.TimelinePeriod == 0)
8829 slbl.Append(Properties.Resources.SetStatusLabelText2);
8833 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8835 return slbl.ToString();
8838 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8842 if (this.InvokeRequired && !this.IsDisposed)
8844 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8848 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8849 SetApiStatusLabel(endpointName);
8852 catch (ObjectDisposedException)
8856 catch (InvalidOperationException)
8862 private void SetApiStatusLabel(string endpointName = null)
8864 if (_curTab == null)
8866 this.toolStripApiGauge.ApiEndpoint = null;
8870 var tabType = _statuses.Tabs[_curTab.Text].TabType;
8872 if (endpointName == null)
8877 case MyCommon.TabUsageType.Home:
8878 case MyCommon.TabUsageType.UserDefined:
8879 endpointName = "/statuses/home_timeline";
8882 case MyCommon.TabUsageType.Mentions:
8883 endpointName = "/statuses/mentions_timeline";
8886 case MyCommon.TabUsageType.Favorites:
8887 endpointName = "/favorites/list";
8890 case MyCommon.TabUsageType.DirectMessage:
8891 endpointName = "/direct_messages";
8894 case MyCommon.TabUsageType.UserTimeline:
8895 endpointName = "/statuses/user_timeline";
8898 case MyCommon.TabUsageType.Lists:
8899 endpointName = "/lists/statuses";
8902 case MyCommon.TabUsageType.PublicSearch:
8903 endpointName = "/search/tweets";
8906 case MyCommon.TabUsageType.Related:
8907 endpointName = "/statuses/show/:id";
8914 this.toolStripApiGauge.ApiEndpoint = endpointName;
8918 // 表示中のタブに関連する endpoint であれば更新
8921 switch (endpointName)
8923 case "/statuses/home_timeline":
8924 update = tabType == MyCommon.TabUsageType.Home ||
8925 tabType == MyCommon.TabUsageType.UserDefined;
8928 case "/statuses/mentions_timeline":
8929 update = tabType == MyCommon.TabUsageType.Mentions;
8932 case "/favorites/list":
8933 update = tabType == MyCommon.TabUsageType.Favorites;
8936 case "/direct_messages:":
8937 update = tabType == MyCommon.TabUsageType.DirectMessage;
8940 case "/statuses/user_timeline":
8941 update = tabType == MyCommon.TabUsageType.UserTimeline;
8944 case "/lists/statuses":
8945 update = tabType == MyCommon.TabUsageType.Lists;
8948 case "/search/tweets":
8949 update = tabType == MyCommon.TabUsageType.PublicSearch;
8952 case "/statuses/show/:id":
8953 update = tabType == MyCommon.TabUsageType.Related;
8962 this.toolStripApiGauge.ApiEndpoint = endpointName;
8968 private void SetStatusLabelUrl()
8970 StatusLabelUrl.Text = GetStatusLabelText();
8973 public void SetStatusLabel(string text)
8975 StatusLabel.Text = text;
8978 private void SetNotifyIconText()
8980 var ur = new StringBuilder(64);
8982 // タスクトレイアイコンのツールチップテキスト書き換え
8984 ur.Remove(0, ur.Length);
8985 if (this._cfgCommon.DispUsername)
8987 ur.Append(tw.Username);
8990 ur.Append(Application.ProductName);
8992 ur.Append("(Debug Build)");
8994 if (UnreadCounter != -1 && UnreadAtCounter != -1)
8997 ur.Append(UnreadCounter);
8999 ur.Append(UnreadAtCounter);
9002 NotifyIcon1.Text = ur.ToString();
9005 internal void CheckReplyTo(string StatusText)
9009 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9011 foreach (Match hm in m)
9013 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9015 hstr += "#" + hm.Result("$3") + " ";
9016 HashSupl.AddItem("#" + hm.Result("$3"));
9019 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9021 hstr += HashMgr.UseHash;
9023 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9025 // 本当にリプライ先指定すべきかどうかの判定
9026 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9028 if (this._cfgCommon.UseAtIdSupplement)
9030 int bCnt = AtIdSupl.ItemCount;
9031 foreach (Match mid in m)
9033 AtIdSupl.AddItem(mid.Result("${id}"));
9035 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9038 // リプライ先ステータスIDの指定がない場合は指定しない
9039 if (this.inReplyTo == null)
9043 // 次の条件を満たす場合に in_reply_to_status_id 指定
9044 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9045 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9046 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9050 var inReplyToScreenName = this.inReplyTo.Item2;
9051 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9053 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9057 foreach (Match mid in m)
9059 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9064 this.inReplyTo = null;
9067 private void TweenMain_Resize(object sender, EventArgs e)
9069 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9071 this.Visible = false;
9073 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9075 // 現在の DPI と設定保存時の DPI との比を取得する
9076 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9078 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9079 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9080 this.DesktopLocation = _cfgLocal.FormLocation;
9081 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9084 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9085 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9086 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9088 this.SplitContainer1.SplitterDistance = splitterDistance;
9092 StatusText.Multiline = _cfgLocal.StatusMultiline;
9093 if (StatusText.Multiline)
9095 var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9096 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9097 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9099 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9101 StatusText.Height = statusTextHeight;
9105 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9107 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9111 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9112 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9114 this.SplitContainer3.SplitterDistance = previewDistance;
9117 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9118 this.SplitContainer3.Panel2Collapsed = true;
9120 _initialLayout = false;
9122 if (this.WindowState != FormWindowState.Minimized)
9124 _formWindowState = this.WindowState;
9128 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9130 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9131 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9132 if (PlaySoundMenuItem.Checked)
9134 this._cfgCommon.PlaySound = true;
9138 this._cfgCommon.PlaySound = false;
9140 ModifySettingCommon = true;
9143 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9145 if (this._initialLayout)
9148 int splitterDistance;
9149 switch (this.WindowState)
9151 case FormWindowState.Normal:
9152 splitterDistance = this.SplitContainer1.SplitterDistance;
9154 case FormWindowState.Maximized:
9155 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9156 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9157 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9158 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9164 this._mySpDis = splitterDistance;
9165 this.ModifySettingLocal = true;
9168 private async Task doRepliedStatusOpen()
9170 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9172 if (MyCommon.IsKeyDown(Keys.Shift))
9174 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9177 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9179 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9180 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9184 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9186 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9187 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9188 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9191 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9196 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9198 await this.doRepliedStatusOpen();
9201 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9203 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9204 if (multiline != this.StatusText.Multiline)
9206 this.StatusText.Multiline = multiline;
9207 MultiLineMenuItem.Checked = multiline;
9208 ModifySettingLocal = true;
9212 private void StatusText_MultilineChanged(object sender, EventArgs e)
9214 if (this.StatusText.Multiline)
9215 this.StatusText.ScrollBars = ScrollBars.Vertical;
9217 this.StatusText.ScrollBars = ScrollBars.None;
9219 ModifySettingLocal = true;
9222 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9225 StatusText.Multiline = MultiLineMenuItem.Checked;
9226 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
9227 if (MultiLineMenuItem.Checked)
9229 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9230 SplitContainer2.SplitterDistance = 0;
9232 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9236 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9238 ModifySettingLocal = true;
9241 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9243 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9244 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9246 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9247 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9248 //Appendix A. Collected ABNF for URI
9249 //http://www.ietf.org/rfc/rfc3986.txt
9253 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9255 if (StatusText.SelectionLength > 0)
9257 string tmp = StatusText.SelectedText;
9258 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9259 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9261 // 文字列が選択されている場合はその文字列について処理
9263 //nico.ms使用、nicovideoにマッチしたら変換
9264 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
9266 result = nicoms.Shorten(tmp);
9268 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9270 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9273 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9274 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9275 result = resultUri.AbsoluteUri;
9277 catch (WebApiException e)
9279 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9282 catch (UriFormatException e)
9284 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9293 if (!string.IsNullOrEmpty(result))
9295 urlUndo undotmp = new urlUndo();
9297 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
9298 StatusText.SelectedText = result;
9301 undotmp.Before = tmp;
9302 undotmp.After = result;
9304 if (urlUndoBuffer == null)
9306 urlUndoBuffer = new List<urlUndo>();
9307 UrlUndoToolStripMenuItem.Enabled = true;
9310 urlUndoBuffer.Add(undotmp);
9316 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9317 @"(?<url>(?<protocol>https?://)" +
9318 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9319 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9320 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9321 // 正規表現にマッチしたURL文字列をtinyurl化
9322 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9324 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9325 string tmp = mt.Result("${url}");
9326 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9327 urlUndo undotmp = new urlUndo();
9330 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9332 //nico.ms使用、nicovideoにマッチしたら変換
9333 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
9335 result = nicoms.Shorten(tmp);
9337 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9339 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9342 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9343 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9344 result = resultUri.AbsoluteUri;
9346 catch (HttpRequestException e)
9348 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9349 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9350 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9352 this.StatusLabel.Text = Converter_Type + ":" + message;
9355 catch (WebApiException e)
9357 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9360 catch (UriFormatException e)
9362 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9371 if (!string.IsNullOrEmpty(result))
9373 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9374 StatusText.SelectedText = result;
9376 undotmp.Before = mt.Result("${url}");
9377 undotmp.After = result;
9379 if (urlUndoBuffer == null)
9381 urlUndoBuffer = new List<urlUndo>();
9382 UrlUndoToolStripMenuItem.Enabled = true;
9385 urlUndoBuffer.Add(undotmp);
9393 private void doUrlUndo()
9395 if (urlUndoBuffer != null)
9397 string tmp = StatusText.Text;
9398 foreach (urlUndo data in urlUndoBuffer)
9400 tmp = tmp.Replace(data.After, data.Before);
9402 StatusText.Text = tmp;
9403 urlUndoBuffer = null;
9404 UrlUndoToolStripMenuItem.Enabled = false;
9405 StatusText.SelectionStart = 0;
9406 StatusText.SelectionLength = 0;
9410 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9412 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9415 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9417 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9420 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9422 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9425 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9427 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9430 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9432 if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
9434 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
9435 Random rnd = new Random();
9436 // 前回使用した短縮URLサービス以外を選択する
9439 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9441 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9442 await UrlConvertAsync(svc);
9446 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9451 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9453 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9454 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9455 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
9456 ModifySettingCommon = true;
9459 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9461 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9462 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9463 _cfgCommon.ListLock = ListLockMenuItem.Checked;
9464 ModifySettingCommon = true;
9467 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9469 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9470 MenuStrip1.Tag = new Object();
9471 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9474 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9476 if (this.Tag != null) // 設定された戻り先へ遷移
9478 if (this.Tag == this.ListTab.SelectedTab)
9479 ((Control)this.ListTab.SelectedTab.Tag).Select();
9481 ((Control)this.Tag).Select();
9483 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9485 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9487 this.Tag = ListTab.SelectedTab.Tag;
9488 ((Control)this.Tag).Select();
9491 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9492 MenuStrip1.Tag = null;
9495 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9497 DetailsListView lst = (DetailsListView)sender;
9498 if (_cfgLocal == null) return;
9502 _cfgLocal.Width1 = lst.Columns[0].Width;
9503 _cfgLocal.Width3 = lst.Columns[1].Width;
9507 int[] darr = new int[lst.Columns.Count];
9508 for (int i = 0; i < lst.Columns.Count; i++)
9510 darr[lst.Columns[i].DisplayIndex] = i;
9512 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9514 for (int i = 0; i < lst.Columns.Count; i++)
9519 _cfgLocal.DisplayIndex1 = i;
9522 _cfgLocal.DisplayIndex2 = i;
9525 _cfgLocal.DisplayIndex3 = i;
9528 _cfgLocal.DisplayIndex4 = i;
9531 _cfgLocal.DisplayIndex5 = i;
9534 _cfgLocal.DisplayIndex6 = i;
9537 _cfgLocal.DisplayIndex7 = i;
9540 _cfgLocal.DisplayIndex8 = i;
9544 _cfgLocal.Width1 = lst.Columns[0].Width;
9545 _cfgLocal.Width2 = lst.Columns[1].Width;
9546 _cfgLocal.Width3 = lst.Columns[2].Width;
9547 _cfgLocal.Width4 = lst.Columns[3].Width;
9548 _cfgLocal.Width5 = lst.Columns[4].Width;
9549 _cfgLocal.Width6 = lst.Columns[5].Width;
9550 _cfgLocal.Width7 = lst.Columns[6].Width;
9551 _cfgLocal.Width8 = lst.Columns[7].Width;
9553 ModifySettingLocal = true;
9554 _isColumnChanged = true;
9557 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9559 DetailsListView lst = (DetailsListView)sender;
9560 if (_cfgLocal == null) return;
9563 if (_cfgLocal.Width1 != lst.Columns[0].Width)
9565 _cfgLocal.Width1 = lst.Columns[0].Width;
9566 ModifySettingLocal = true;
9567 _isColumnChanged = true;
9569 if (_cfgLocal.Width3 != lst.Columns[1].Width)
9571 _cfgLocal.Width3 = lst.Columns[1].Width;
9572 ModifySettingLocal = true;
9573 _isColumnChanged = true;
9578 if (_cfgLocal.Width1 != lst.Columns[0].Width)
9580 _cfgLocal.Width1 = lst.Columns[0].Width;
9581 ModifySettingLocal = true;
9582 _isColumnChanged = true;
9584 if (_cfgLocal.Width2 != lst.Columns[1].Width)
9586 _cfgLocal.Width2 = lst.Columns[1].Width;
9587 ModifySettingLocal = true;
9588 _isColumnChanged = true;
9590 if (_cfgLocal.Width3 != lst.Columns[2].Width)
9592 _cfgLocal.Width3 = lst.Columns[2].Width;
9593 ModifySettingLocal = true;
9594 _isColumnChanged = true;
9596 if (_cfgLocal.Width4 != lst.Columns[3].Width)
9598 _cfgLocal.Width4 = lst.Columns[3].Width;
9599 ModifySettingLocal = true;
9600 _isColumnChanged = true;
9602 if (_cfgLocal.Width5 != lst.Columns[4].Width)
9604 _cfgLocal.Width5 = lst.Columns[4].Width;
9605 ModifySettingLocal = true;
9606 _isColumnChanged = true;
9608 if (_cfgLocal.Width6 != lst.Columns[5].Width)
9610 _cfgLocal.Width6 = lst.Columns[5].Width;
9611 ModifySettingLocal = true;
9612 _isColumnChanged = true;
9614 if (_cfgLocal.Width7 != lst.Columns[6].Width)
9616 _cfgLocal.Width7 = lst.Columns[6].Width;
9617 ModifySettingLocal = true;
9618 _isColumnChanged = true;
9620 if (_cfgLocal.Width8 != lst.Columns[7].Width)
9622 _cfgLocal.Width8 = lst.Columns[7].Width;
9623 ModifySettingLocal = true;
9624 _isColumnChanged = true;
9627 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9630 // SaveConfigsLocal();
9634 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9636 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9637 ModifySettingLocal = true;
9640 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9642 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9644 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9646 SelectMedia_DragDrop(e);
9649 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9651 var url = GetUrlFromDataObject(e.Data);
9654 if (url.Item2 == null)
9655 appendText = url.Item1;
9657 appendText = url.Item2 + " " + url.Item1;
9659 if (this.StatusText.TextLength == 0)
9660 this.StatusText.Text = appendText;
9662 this.StatusText.Text += " " + appendText;
9664 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9666 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9668 this.StatusText.Text += text;
9670 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9672 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9673 if (data != null) StatusText.Text += data;
9678 /// IDataObject から URL とタイトルの対を取得します
9681 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9683 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9684 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9685 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
9687 if (data.GetDataPresent("text/x-moz-url"))
9689 // Firefox, Google Chrome で利用可能
9690 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9692 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9694 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9695 if (lines.Length < 2)
9696 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9698 return new Tuple<string, string>(lines[0], lines[1]);
9701 else if (data.GetDataPresent("IESiteModeToUrl"))
9703 // Internet Exproler 用
9704 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9706 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9708 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9709 if (lines.Length < 2)
9710 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9712 return new Tuple<string, string>(lines[0], lines[1]);
9715 else if (data.GetDataPresent("UniformResourceLocatorW"))
9719 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9721 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9722 return new Tuple<string, string>(url, null);
9726 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9729 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9731 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9733 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9735 SelectMedia_DragEnter(e);
9739 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9741 e.Effect = DragDropEffects.Copy;
9744 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9746 e.Effect = DragDropEffects.Copy;
9749 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9751 e.Effect = DragDropEffects.Copy;
9755 e.Effect = DragDropEffects.None;
9758 private void TweenMain_DragOver(object sender, DragEventArgs e)
9762 public bool IsNetworkAvailable()
9765 nw = MyCommon.IsNetworkAvailable();
9766 _myStatusOnline = nw;
9770 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9772 var uriStr = uri.AbsoluteUri;
9774 // OpenTween 内部で使用する URL
9775 if (uri.Authority == "opentween")
9777 await this.OpenInternalUriAsync(uri);
9781 // ハッシュタグを含む Twitter 検索
9782 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9785 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9786 var pos = unescapedQuery.IndexOf('#');
9787 if (pos == -1) return;
9789 var hash = unescapedQuery.Substring(pos);
9790 this.HashSupl.AddItem(hash);
9791 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9792 this.AddNewTabForSearch(hash);
9797 // フラグが立っている場合は設定と逆の動作をする
9798 if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
9799 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
9801 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9802 if (userUriMatch.Success)
9804 var screenName = userUriMatch.Groups["ScreenName"].Value;
9805 if (this.IsTwitterId(screenName))
9807 this.AddNewTabForUserTimeline(screenName);
9814 await this.OpenUriInBrowserAsync(uriStr);
9818 /// OpenTween 内部の機能を呼び出すための URL を開きます
9820 private async Task OpenInternalUriAsync(Uri uri)
9822 // ツイートを開く (//opentween/status/:status_id)
9823 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9826 var statusId = long.Parse(match.Groups[1].Value);
9827 await this.OpenRelatedTab(statusId);
9832 public Task OpenUriInBrowserAsync(string UriString)
9834 return Task.Run(() =>
9836 string myPath = UriString;
9840 var configBrowserPath = this._cfgLocal.BrowserPath;
9841 if (!string.IsNullOrEmpty(configBrowserPath))
9843 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9845 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9846 string browserPath = configBrowserPath.Substring(1, sep - 1);
9848 if (sep < configBrowserPath.Length - 1)
9850 arg = configBrowserPath.Substring(sep + 1);
9852 myPath = arg + " " + myPath;
9853 System.Diagnostics.Process.Start(browserPath, myPath);
9857 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9862 System.Diagnostics.Process.Start(myPath);
9867 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9872 private void ListTabSelect(TabPage _tab)
9876 this.PurgeListViewItemCache();
9879 _curList = (DetailsListView)_tab.Tag;
9881 if (_curList.SelectedIndices.Count > 0)
9883 _curItemIndex = _curList.SelectedIndices[0];
9884 _curPost = GetCurTabPost(_curItemIndex);
9893 _anchorFlag = false;
9897 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
9901 for (int i = 0; i < _curList.Columns.Count; i++)
9903 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
9908 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9910 ListTabSelect(e.TabPage);
9913 private void SelectListItem(DetailsListView LView, int Index)
9916 Rectangle bnd = new Rectangle();
9918 var item = LView.FocusedItem;
9927 LView.SelectedIndices.Clear();
9929 while (LView.SelectedIndices.Count > 0);
9930 item = LView.Items[Index];
9931 item.Selected = true;
9932 item.Focused = true;
9934 if (flg) LView.Invalidate(bnd);
9937 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9940 Rectangle bnd = new Rectangle();
9942 var item = LView.FocusedItem;
9953 LView.SelectedIndices.Clear();
9955 while (LView.SelectedIndices.Count > 0);
9956 LView.SelectItems(Index);
9958 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9960 LView.SelectionMark = selectionMarkIndex;
9962 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9964 LView.Items[focusedIndex].Focused = true;
9966 else if (Index != null && Index.Length != 0)
9968 LView.Items[Index.Last()].Focused = true;
9971 if (flg) LView.Invalidate(bnd);
9974 private void StartUserStream()
9976 tw.NewPostFromStream += tw_NewPostFromStream;
9977 tw.UserStreamStarted += tw_UserStreamStarted;
9978 tw.UserStreamStopped += tw_UserStreamStopped;
9979 tw.PostDeleted += tw_PostDeleted;
9980 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9982 this.RefreshUserStreamsMenu();
9984 if (this._cfgCommon.UserstreamStartup)
9985 tw.StartUserStream();
9988 private async void TweenMain_Shown(object sender, EventArgs e)
9990 NotifyIcon1.Visible = true;
9992 if (this.IsNetworkAvailable())
9996 var loadTasks = new List<Task>
9998 this.RefreshMuteUserIdsAsync(),
9999 this.RefreshBlockIdsAsync(),
10000 this.RefreshNoRetweetIdsAsync(),
10001 this.RefreshTwitterConfigurationAsync(),
10002 this.GetHomeTimelineAsync(),
10003 this.GetReplyAsync(),
10004 this.GetDirectMessagesAsync(),
10005 this.GetPublicSearchAllAsync(),
10006 this.GetUserTimelineAllAsync(),
10007 this.GetListTimelineAllAsync(),
10010 if (this._cfgCommon.StartupFollowers)
10011 loadTasks.Add(this.RefreshFollowerIdsAsync());
10013 if (this._cfgCommon.GetFav)
10014 loadTasks.Add(this.GetFavoritesAsync());
10016 var allTasks = Task.WhenAll(loadTasks);
10021 var timeout = Task.Delay(5000);
10022 if (await Task.WhenAny(allTasks, timeout) != timeout)
10026 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10028 if (MyCommon._endingFlag)
10032 if (MyCommon._endingFlag) return;
10034 if (ApplicationSettings.VersionInfoUrl != null)
10036 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10037 if (this._cfgCommon.StartupVersion)
10038 await this.CheckNewVersion(true);
10042 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10043 this.VerUpMenuItem.Enabled = false;
10044 this.VerUpMenuItem.Available = false;
10045 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10048 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10049 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10051 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10052 SettingStripMenuItem_Click(null, null);
10056 var reloadTasks = new List<Task>();
10058 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
10059 reloadTasks.Add(this.RefreshFollowerIdsAsync());
10061 if (!tw.GetNoRetweetSuccess)
10062 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10064 if (this.tw.Configuration.PhotoSizeLimit == 0)
10065 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10067 await Task.WhenAll(reloadTasks);
10072 TimerTimeline.Enabled = true;
10075 private async Task doGetFollowersMenu()
10077 await this.RefreshFollowerIdsAsync();
10078 await this.DispSelectedPost(true);
10081 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10083 await this.doGetFollowersMenu();
10086 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10088 doReTweetUnofficial();
10091 private async Task doReTweetOfficial(bool isConfirm)
10094 if (this.ExistCurrentPost)
10096 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10098 if (this._curPost.IsProtect)
10099 MessageBox.Show("Protected.");
10101 _DoFavRetweetFlags = false;
10104 if (_curList.SelectedIndices.Count > 15)
10106 MessageBox.Show(Properties.Resources.RetweetLimitText);
10107 _DoFavRetweetFlags = false;
10110 else if (_curList.SelectedIndices.Count > 1)
10112 string QuestionText = Properties.Resources.RetweetQuestion2;
10113 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10114 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10116 case DialogResult.Cancel:
10117 case DialogResult.No:
10118 _DoFavRetweetFlags = false;
10124 if (!this._cfgCommon.RetweetNoConfirm)
10126 string Questiontext = Properties.Resources.RetweetQuestion1;
10127 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10128 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10130 _DoFavRetweetFlags = false;
10136 var statusIds = new List<long>();
10137 foreach (int idx in _curList.SelectedIndices)
10139 PostClass post = GetCurTabPost(idx);
10140 if (post.CanRetweetBy(this.twitterApi.CurrentUserId))
10141 statusIds.Add(post.StatusId);
10144 await this.RetweetAsync(statusIds);
10148 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10150 await this.doReTweetOfficial(true);
10153 private async Task FavoritesRetweetOfficial()
10155 if (!this.ExistCurrentPost) return;
10156 _DoFavRetweetFlags = true;
10157 var retweetTask = this.doReTweetOfficial(true);
10158 if (_DoFavRetweetFlags)
10160 _DoFavRetweetFlags = false;
10161 var favoriteTask = this.FavoriteChange(true, false);
10163 await Task.WhenAll(retweetTask, favoriteTask);
10171 private async Task FavoritesRetweetUnofficial()
10173 if (this.ExistCurrentPost && !_curPost.IsDm)
10175 _DoFavRetweetFlags = true;
10176 var favoriteTask = this.FavoriteChange(true);
10177 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10179 _DoFavRetweetFlags = false;
10180 doReTweetUnofficial();
10183 await favoriteTask;
10188 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10190 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10191 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10192 /// <returns>復元されたツイート本文</returns>
10193 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10195 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10198 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10200 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10202 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10206 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10208 statusHtml = statusHtml.Replace("<br>", " ");
10210 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10211 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10212 statusHtml = statusHtml.Replace(" ", " ");
10214 return WebUtility.HtmlDecode(statusHtml);
10217 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10219 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10221 if (_curPost != null)
10222 await this.DispSelectedPost(true);
10225 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10227 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10228 DebugModeToolStripMenuItem.Visible = true;
10230 DebugModeToolStripMenuItem.Visible = false;
10233 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
10235 this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
10238 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10240 ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
10243 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10245 if (TraceOutToolStripMenuItem.Checked)
10246 MyCommon.TraceFlag = true;
10248 MyCommon.TraceFlag = false;
10251 private void TweenMain_Deactivate(object sender, EventArgs e)
10253 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10254 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10257 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10259 if (string.IsNullOrEmpty(_rclickTabName)) return;
10262 TabRename(_rclickTabName, out _);
10265 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10267 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10270 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10272 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10275 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10277 TwitterApiStatus apiStatus;
10279 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10281 var cancellationToken = dialog.EnableCancellation();
10285 var task = this.tw.GetInfoApi();
10286 apiStatus = await dialog.WaitForAsync(this, task);
10288 catch (WebApiException)
10293 if (cancellationToken.IsCancellationRequested)
10296 if (apiStatus == null)
10298 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10303 using (var apiDlg = new ApiInfoDialog())
10305 apiDlg.ShowDialog(this);
10309 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10311 var id = _curPost?.ScreenName ?? "";
10313 await this.FollowCommand(id);
10316 internal async Task FollowCommand(string id)
10318 using (var inputName = new InputTabName())
10320 inputName.FormTitle = "Follow";
10321 inputName.FormDescription = Properties.Resources.FRMessage1;
10322 inputName.TabName = id;
10324 if (inputName.ShowDialog(this) != DialogResult.OK)
10326 if (string.IsNullOrWhiteSpace(inputName.TabName))
10329 id = inputName.TabName.Trim();
10332 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10336 var task = this.twitterApi.FriendshipsCreate(id);
10337 await dialog.WaitForAsync(this, task);
10339 catch (WebApiException ex)
10341 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10346 MessageBox.Show(Properties.Resources.FRMessage3);
10349 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10351 var id = _curPost?.ScreenName ?? "";
10353 await this.RemoveCommand(id, false);
10356 internal async Task RemoveCommand(string id, bool skipInput)
10360 using (var inputName = new InputTabName())
10362 inputName.FormTitle = "Unfollow";
10363 inputName.FormDescription = Properties.Resources.FRMessage1;
10364 inputName.TabName = id;
10366 if (inputName.ShowDialog(this) != DialogResult.OK)
10368 if (string.IsNullOrWhiteSpace(inputName.TabName))
10371 id = inputName.TabName.Trim();
10375 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10379 var task = this.twitterApi.FriendshipsDestroy(id);
10380 await dialog.WaitForAsync(this, task);
10382 catch (WebApiException ex)
10384 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10389 MessageBox.Show(Properties.Resources.FRMessage3);
10392 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10394 var id = _curPost?.ScreenName ?? "";
10396 await this.ShowFriendship(id);
10399 internal async Task ShowFriendship(string id)
10401 using (var inputName = new InputTabName())
10403 inputName.FormTitle = "Show Friendships";
10404 inputName.FormDescription = Properties.Resources.FRMessage1;
10405 inputName.TabName = id;
10407 if (inputName.ShowDialog(this) != DialogResult.OK)
10409 if (string.IsNullOrWhiteSpace(inputName.TabName))
10412 id = inputName.TabName.Trim();
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 = "";
10443 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10447 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10451 result += Properties.Resources.GetFriendshipInfo3;
10455 result += Properties.Resources.GetFriendshipInfo4;
10457 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10458 MessageBox.Show(result);
10461 internal async Task ShowFriendship(string[] ids)
10463 foreach (string id in ids)
10465 bool isFollowing, isFollowed;
10467 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10469 var cancellationToken = dialog.EnableCancellation();
10473 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10474 var friendship = await dialog.WaitForAsync(this, task);
10476 isFollowing = friendship.Relationship.Source.Following;
10477 isFollowed = friendship.Relationship.Source.FollowedBy;
10479 catch (WebApiException ex)
10481 if (!cancellationToken.IsCancellationRequested)
10482 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10486 if (cancellationToken.IsCancellationRequested)
10490 string result = "";
10496 ff += Properties.Resources.GetFriendshipInfo1;
10500 ff += Properties.Resources.GetFriendshipInfo2;
10503 ff += System.Environment.NewLine + " ";
10506 ff += Properties.Resources.GetFriendshipInfo3;
10510 ff += Properties.Resources.GetFriendshipInfo4;
10512 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10515 if (MessageBox.Show(
10516 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10517 MessageBoxButtons.YesNo,
10518 MessageBoxIcon.Question,
10519 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10521 await this.RemoveCommand(id, true);
10526 MessageBox.Show(result);
10531 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10533 await this.doShowUserStatus(tw.Username, false);
10534 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
10536 // doShowUserStatus(tw.Username, false);
10540 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
10545 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10546 // URLから切り出した文字列を渡す
10548 public bool IsTwitterId(string name)
10550 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10551 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10553 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
10556 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
10558 ModifySettingCommon = true;
10561 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10563 ModifySettingCommon = true;
10566 private void doQuoteOfficial()
10568 if (this.ExistCurrentPost)
10570 if (_curPost.IsDm ||
10571 !StatusText.Enabled) return;
10573 if (_curPost.IsProtect)
10575 MessageBox.Show("Protected.");
10579 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
10581 this.inReplyTo = null;
10583 StatusText.SelectionStart = 0;
10584 StatusText.Focus();
10588 private void doReTweetUnofficial()
10591 if (this.ExistCurrentPost)
10593 if (_curPost.IsDm || !StatusText.Enabled)
10596 if (_curPost.IsProtect)
10598 MessageBox.Show("Protected.");
10601 string rtdata = _curPost.Text;
10602 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10604 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
10606 // 投稿時に in_reply_to_status_id を付加する
10607 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
10608 var inReplyToScreenName = this._curPost.ScreenName;
10609 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
10611 StatusText.SelectionStart = 0;
10612 StatusText.Focus();
10616 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
10621 private void SearchButton_Click(object sender, EventArgs e)
10624 Control pnl = ((Control)sender).Parent;
10625 if (pnl == null) return;
10626 string tbName = pnl.Parent.Text;
10627 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10628 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10629 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10630 cmb.Text = cmb.Text.Trim();
10631 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10632 bool Quote = false;
10633 StringBuilder buf = new StringBuilder();
10634 char[] c = cmb.Text.ToCharArray();
10635 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10637 if (cnt > cmb.Text.Length - 4)
10639 buf.Append(cmb.Text.Substring(cnt));
10648 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10650 buf.Append(" OR ");
10655 buf.Append(c[cnt]);
10657 cmb.Text = buf.ToString();
10659 var listView = (DetailsListView)pnl.Parent.Tag;
10661 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10663 tb.SearchWords = cmb.Text;
10664 tb.SearchLang = cmbLang.Text;
10665 if (string.IsNullOrEmpty(cmb.Text))
10673 int idx = cmb.Items.IndexOf(tb.SearchWords);
10674 if (idx > -1) cmb.Items.RemoveAt(idx);
10675 cmb.Items.Insert(0, tb.SearchWords);
10676 cmb.Text = tb.SearchWords;
10678 this.PurgeListViewItemCache();
10679 listView.VirtualListSize = 0;
10680 _statuses.ClearTabIds(tbName);
10681 SaveConfigsTabs(); //検索条件の保存
10684 this.GetPublicSearchAsync(tb);
10688 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10691 await this.DoRefreshMore();
10695 /// 指定されたタブのListTabにおける位置を返します
10698 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10700 public int GetTabPageIndex(string tabName)
10703 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
10705 if (tabPage.Text == tabName)
10714 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10716 if (_statuses.RemovedTab.Count == 0)
10718 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10723 DetailsListView listView = null;
10725 TabModel tb = _statuses.RemovedTab.Pop();
10726 if (tb.TabType == MyCommon.TabUsageType.Related)
10728 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10729 if (relatedTab != null)
10731 // 関連発言なら既存のタブを置き換える
10732 tb.TabName = relatedTab.TabName;
10733 this.ClearTab(tb.TabName, false);
10734 _statuses.Tabs[tb.TabName] = tb;
10736 for (int i = 0; i < ListTab.TabPages.Count; i++)
10738 var tabPage = ListTab.TabPages[i];
10739 if (tb.TabName == tabPage.Text)
10741 listView = (DetailsListView)tabPage.Tag;
10742 ListTab.SelectedIndex = i;
10749 const string TabName = "Related Tweets";
10750 string renamed = TabName;
10751 for (int i = 2; i <= 100; i++)
10753 if (!_statuses.ContainsTab(renamed)) break;
10754 renamed = TabName + i;
10756 tb.TabName = renamed;
10758 _statuses.AddTab(tb);
10759 AddNewTab(tb, startup: false);
10761 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10762 listView = (DetailsListView)tabPage.Tag;
10763 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10768 string renamed = tb.TabName;
10769 for (int i = 1; i < int.MaxValue; i++)
10771 if (!_statuses.ContainsTab(renamed)) break;
10772 renamed = tb.TabName + "(" + i + ")";
10774 tb.TabName = renamed;
10776 _statuses.AddTab(tb);
10777 AddNewTab(tb, startup: false);
10779 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10780 listView = (DetailsListView)tabPage.Tag;
10781 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10785 if (listView != null)
10787 using (ControlTransaction.Update(listView))
10789 listView.VirtualListSize = tb.AllCount;
10795 private async Task doMoveToRTHome()
10797 if (_curList.SelectedIndices.Count > 0)
10799 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
10800 if (post.RetweetedId != null)
10802 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
10807 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10809 await this.doMoveToRTHome();
10812 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10814 var screenName = this._curPost?.ScreenName;
10815 if (screenName != null)
10816 this.ListManageUserContext(screenName);
10819 public void ListManageUserContext(string screenName)
10821 using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10823 listSelectForm.ShowDialog(this);
10827 private void SearchControls_Enter(object sender, EventArgs e)
10829 Control pnl = (Control)sender;
10830 foreach (Control ctl in pnl.Controls)
10832 ctl.TabStop = true;
10836 private void SearchControls_Leave(object sender, EventArgs e)
10838 Control pnl = (Control)sender;
10839 foreach (Control ctl in pnl.Controls)
10841 ctl.TabStop = false;
10845 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10847 if (ListTab.SelectedTab != null)
10849 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
10850 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
10854 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10856 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10859 private void HashManageMenuItem_Click(object sender, EventArgs e)
10861 DialogResult rslt = DialogResult.Cancel;
10864 rslt = HashMgr.ShowDialog();
10870 this.TopMost = this._cfgCommon.AlwaysTop;
10871 if (rslt == DialogResult.Cancel) return;
10872 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10874 HashStripSplitButton.Text = HashMgr.UseHash;
10875 HashToggleMenuItem.Checked = true;
10876 HashToggleToolStripMenuItem.Checked = true;
10880 HashStripSplitButton.Text = "#[-]";
10881 HashToggleMenuItem.Checked = false;
10882 HashToggleToolStripMenuItem.Checked = false;
10884 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10886 // int sidx = StatusText.SelectionStart;
10887 // string hash = HashMgr.UseHash + " ";
10890 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10891 // hash = " " + hash;
10893 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
10894 // sidx += hash.Length;
10895 // StatusText.SelectionStart = sidx;
10896 // StatusText.Focus();
10898 ModifySettingCommon = true;
10899 this.StatusText_TextChanged(null, null);
10902 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10904 HashMgr.ToggleHash();
10905 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10907 HashStripSplitButton.Text = HashMgr.UseHash;
10908 HashToggleMenuItem.Checked = true;
10909 HashToggleToolStripMenuItem.Checked = true;
10913 HashStripSplitButton.Text = "#[-]";
10914 HashToggleMenuItem.Checked = false;
10915 HashToggleToolStripMenuItem.Checked = false;
10917 ModifySettingCommon = true;
10918 this.StatusText_TextChanged(null, null);
10921 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10923 HashToggleMenuItem_Click(null, null);
10926 public void SetPermanentHashtag(string hashtag)
10928 HashMgr.SetPermanentHash("#" + hashtag);
10929 HashStripSplitButton.Text = HashMgr.UseHash;
10930 HashToggleMenuItem.Checked = true;
10931 HashToggleToolStripMenuItem.Checked = true;
10933 ModifySettingCommon = true;
10936 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10938 if (ListTab.SelectedTab == null) return;
10939 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
10940 if (!this.ExistCurrentPost)
10942 this.ReplyOpMenuItem.Enabled = false;
10943 this.ReplyAllOpMenuItem.Enabled = false;
10944 this.DmOpMenuItem.Enabled = false;
10945 this.ShowProfMenuItem.Enabled = false;
10946 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10947 this.ListManageMenuItem.Enabled = false;
10948 this.OpenFavOpMenuItem.Enabled = false;
10949 this.CreateTabRuleOpMenuItem.Enabled = false;
10950 this.CreateIdRuleOpMenuItem.Enabled = false;
10951 this.CreateSourceRuleOpMenuItem.Enabled = false;
10952 this.ReadOpMenuItem.Enabled = false;
10953 this.UnreadOpMenuItem.Enabled = false;
10957 this.ReplyOpMenuItem.Enabled = true;
10958 this.ReplyAllOpMenuItem.Enabled = true;
10959 this.DmOpMenuItem.Enabled = true;
10960 this.ShowProfMenuItem.Enabled = true;
10961 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10962 this.ListManageMenuItem.Enabled = true;
10963 this.OpenFavOpMenuItem.Enabled = true;
10964 this.CreateTabRuleOpMenuItem.Enabled = true;
10965 this.CreateIdRuleOpMenuItem.Enabled = true;
10966 this.CreateSourceRuleOpMenuItem.Enabled = true;
10967 this.ReadOpMenuItem.Enabled = true;
10968 this.UnreadOpMenuItem.Enabled = true;
10971 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
10973 this.FavOpMenuItem.Enabled = false;
10974 this.UnFavOpMenuItem.Enabled = false;
10975 this.OpenStatusOpMenuItem.Enabled = false;
10976 this.OpenFavotterOpMenuItem.Enabled = false;
10977 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10978 this.RtOpMenuItem.Enabled = false;
10979 this.RtUnOpMenuItem.Enabled = false;
10980 this.QtOpMenuItem.Enabled = false;
10981 this.FavoriteRetweetMenuItem.Enabled = false;
10982 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10986 this.FavOpMenuItem.Enabled = true;
10987 this.UnFavOpMenuItem.Enabled = true;
10988 this.OpenStatusOpMenuItem.Enabled = true;
10989 this.OpenFavotterOpMenuItem.Enabled = true;
10990 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
10992 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10994 this.RtOpMenuItem.Enabled = false;
10995 this.RtUnOpMenuItem.Enabled = false;
10996 this.QtOpMenuItem.Enabled = false;
10997 this.FavoriteRetweetMenuItem.Enabled = false;
10998 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11002 this.RtOpMenuItem.Enabled = true;
11003 this.RtUnOpMenuItem.Enabled = true;
11004 this.QtOpMenuItem.Enabled = true;
11005 this.FavoriteRetweetMenuItem.Enabled = true;
11006 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11010 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11012 this.RefreshPrevOpMenuItem.Enabled = true;
11016 this.RefreshPrevOpMenuItem.Enabled = false;
11018 if (!this.ExistCurrentPost
11019 || _curPost.InReplyToStatusId == null)
11021 OpenRepSourceOpMenuItem.Enabled = false;
11025 OpenRepSourceOpMenuItem.Enabled = true;
11027 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11029 OpenRterHomeMenuItem.Enabled = false;
11033 OpenRterHomeMenuItem.Enabled = true;
11036 if (this.ExistCurrentPost)
11038 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11042 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11044 ContextMenuTabProperty_Opening(sender, null);
11047 public Twitter TwitterInstance
11052 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11054 if (this._initialLayout)
11057 int splitterDistance;
11058 switch (this.WindowState)
11060 case FormWindowState.Normal:
11061 splitterDistance = this.SplitContainer3.SplitterDistance;
11063 case FormWindowState.Maximized:
11064 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11065 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11066 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11067 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11073 this._mySpDis3 = splitterDistance;
11074 this.ModifySettingLocal = true;
11077 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11079 if (_statuses.RemovedTab.Count == 0)
11081 UndoRemoveTabMenuItem.Enabled = false;
11085 UndoRemoveTabMenuItem.Enabled = true;
11087 if (ListTab.SelectedTab != null)
11089 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11090 PublicSearchQueryMenuItem.Enabled = true;
11092 PublicSearchQueryMenuItem.Enabled = false;
11096 PublicSearchQueryMenuItem.Enabled = false;
11098 if (!this.ExistCurrentPost)
11100 this.CopySTOTMenuItem.Enabled = false;
11101 this.CopyURLMenuItem.Enabled = false;
11102 this.CopyUserIdStripMenuItem.Enabled = false;
11106 this.CopySTOTMenuItem.Enabled = true;
11107 this.CopyURLMenuItem.Enabled = true;
11108 this.CopyUserIdStripMenuItem.Enabled = true;
11109 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11110 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11114 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11116 SetNotifyIconText();
11119 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11121 var id = _curPost?.ScreenName ?? "";
11123 await this.ShowUserStatus(id);
11126 private async Task doShowUserStatus(string id, bool ShowInputDialog)
11128 TwitterUser user = null;
11130 if (ShowInputDialog)
11132 using (var inputName = new InputTabName())
11134 inputName.FormTitle = "Show UserStatus";
11135 inputName.FormDescription = Properties.Resources.FRMessage1;
11136 inputName.TabName = id;
11138 if (inputName.ShowDialog(this) != DialogResult.OK)
11140 if (string.IsNullOrWhiteSpace(inputName.TabName))
11143 id = inputName.TabName.Trim();
11147 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11149 var cancellationToken = dialog.EnableCancellation();
11153 var task = this.twitterApi.UsersShow(id);
11154 user = await dialog.WaitForAsync(this, task);
11156 catch (WebApiException ex)
11158 if (!cancellationToken.IsCancellationRequested)
11159 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11163 if (cancellationToken.IsCancellationRequested)
11167 await this.doShowUserStatus(user);
11170 private async Task doShowUserStatus(TwitterUser user)
11172 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
11174 var showUserTask = userDialog.ShowUserAsync(user);
11175 userDialog.ShowDialog(this);
11178 this.BringToFront();
11180 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11181 await showUserTask;
11185 internal Task ShowUserStatus(string id, bool ShowInputDialog)
11187 return this.doShowUserStatus(id, ShowInputDialog);
11190 internal Task ShowUserStatus(string id)
11192 return this.doShowUserStatus(id, true);
11195 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
11197 if (_curPost != null)
11199 await this.ShowUserStatus(_curPost.ScreenName, false);
11203 private async void RtCountMenuItem_Click(object sender, EventArgs e)
11205 if (!this.ExistCurrentPost)
11208 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11209 TwitterStatus status;
11211 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11213 var cancellationToken = dialog.EnableCancellation();
11217 var task = this.twitterApi.StatusesShow(statusId);
11218 status = await dialog.WaitForAsync(this, task);
11220 catch (WebApiException ex)
11222 if (!cancellationToken.IsCancellationRequested)
11223 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11227 if (cancellationToken.IsCancellationRequested)
11231 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11234 private HookGlobalHotkey _hookGlobalHotkey;
11237 _hookGlobalHotkey = new HookGlobalHotkey(this);
11239 // この呼び出しは、Windows フォーム デザイナで必要です。
11240 InitializeComponent();
11242 // InitializeComponent() 呼び出しの後で初期化を追加します。
11244 if (!this.DesignMode)
11246 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11247 this.StatusText.Dock = DockStyle.Fill;
11250 this.tweetDetailsView.Owner = this;
11252 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11253 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11254 this.gh.NotifyClicked += GrowlHelper_Callback;
11256 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11257 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11259 this.ImageSelector.Visible = false;
11260 this.ImageSelector.Enabled = false;
11261 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11263 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11265 this.ReplaceAppName();
11266 this.InitializeShortcuts();
11269 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11271 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11274 this.Visible = false;
11276 else if (Form.ActiveForm == null)
11278 this.Visible = true;
11279 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11281 this.BringToFront();
11282 this.StatusText.Focus();
11286 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11288 this.MultiLineMenuItem.PerformClick();
11291 public PostClass CurPost
11293 get { return _curPost; }
11297 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11299 if (ImageSelector.Visible)
11300 ImageSelector.EndSelection();
11302 ImageSelector.BeginSelection();
11305 private void SelectMedia_DragEnter(DragEventArgs e)
11307 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11309 e.Effect = DragDropEffects.Copy;
11312 e.Effect = DragDropEffects.None;
11315 private void SelectMedia_DragDrop(DragEventArgs e)
11318 this.BringToFront();
11319 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11320 StatusText.Focus();
11323 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11325 TimelinePanel.Visible = false;
11326 TimelinePanel.Enabled = false;
11329 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11331 TimelinePanel.Visible = true;
11332 TimelinePanel.Enabled = true;
11333 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11336 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11338 this.AllowDrop = false;
11341 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11343 this.AllowDrop = true;
11346 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11348 if (ImageSelector.Visible)
11350 ModifySettingCommon = true;
11351 SaveConfigsAll(true);
11353 this.StatusText_TextChanged(null, null);
11357 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11359 this.StatusText_TextChanged(null, null);
11363 /// StatusTextでCtrl+Vが押下された時の処理
11365 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11369 if (Clipboard.ContainsText())
11371 // clipboardにテキストがある場合は貼り付け処理
11372 this.StatusText.Paste(Clipboard.GetText());
11374 else if (Clipboard.ContainsImage())
11377 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11378 Properties.Resources.PostPictureWarn4,
11379 MessageBoxButtons.OKCancel,
11380 MessageBoxIcon.Question,
11381 MessageBoxDefaultButton.Button2)
11382 == DialogResult.OK)
11384 // clipboardから画像を取得
11385 using (var image = Clipboard.GetImage())
11387 this.ImageSelector.BeginSelection(image);
11392 catch (ExternalException ex)
11394 MessageBox.Show(ex.Message);
11399 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11401 using (ListManage form = new ListManage(tw))
11403 form.ShowDialog(this);
11407 public bool ModifySettingCommon { get; set; }
11408 public bool ModifySettingLocal { get; set; }
11409 public bool ModifySettingAtId { get; set; }
11411 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11413 if (this.ExistCurrentPost && !_curPost.IsDm)
11414 RtCountMenuItem.Enabled = true;
11416 RtCountMenuItem.Enabled = false;
11418 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11419 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11421 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11424 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11429 private void CopyUserId()
11431 if (_curPost == null) return;
11432 string clstr = _curPost.ScreenName;
11435 Clipboard.SetDataObject(clstr, false, 5, 100);
11437 catch (Exception ex)
11439 MessageBox.Show(ex.Message);
11443 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11445 if (this.ExistCurrentPost && !_curPost.IsDm)
11449 await this.OpenRelatedTab(this._curPost);
11451 catch (TabException ex)
11453 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11459 /// 指定されたツイートに対する関連発言タブを開きます
11461 /// <param name="statusId">表示するツイートのID</param>
11462 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11463 private async Task OpenRelatedTab(long statusId)
11465 var post = this._statuses[statusId];
11470 post = await this.tw.GetStatusApi(false, statusId);
11472 catch (WebApiException ex)
11474 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11479 await this.OpenRelatedTab(post);
11483 /// 指定されたツイートに対する関連発言タブを開きます
11485 /// <param name="post">表示する対象となるツイート</param>
11486 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11487 private async Task OpenRelatedTab(PostClass post)
11489 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11490 if (tabRelated != null)
11492 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11495 var tabName = this._statuses.MakeTabName("Related Tweets");
11497 tabRelated = new RelatedPostsTabModel(tabName, post);
11498 tabRelated.UnreadManage = false;
11499 tabRelated.Notify = false;
11501 this._statuses.AddTab(tabRelated);
11502 this.AddNewTab(tabRelated, startup: false);
11505 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
11507 tabPage = this.ListTab.TabPages[i];
11508 if (tabName == tabPage.Text)
11510 this.ListTab.SelectedIndex = i;
11515 await this.GetRelatedTweetsAsync(tabRelated);
11517 tabPage = this.ListTab.TabPages.Cast<TabPage>()
11518 .FirstOrDefault(x => x.Text == tabRelated.TabName);
11520 if (tabPage != null)
11522 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11524 var listView = (DetailsListView)tabPage.Tag;
11525 var targetPost = tabRelated.TargetPost;
11526 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11528 if (index != -1 && index < listView.Items.Count)
11530 listView.SelectedIndices.Add(index);
11531 listView.Items[index].Focused = true;
11536 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11538 StringBuilder buf = new StringBuilder();
11539 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11540 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11541 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11542 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11543 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11546 private void tw_UserIdChanged()
11548 this.ModifySettingCommon = true;
11551 #region "Userstream"
11552 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11556 if (InvokeRequired && !IsDisposed)
11558 await this.InvokeAsync(async () =>
11560 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11561 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
11563 this.PurgeListViewItemCache();
11564 ((DetailsListView)_curTab.Tag).Update();
11565 if (_curPost != null && _curPost.StatusId == e.StatusId)
11566 await this.DispSelectedPost(true);
11572 catch (ObjectDisposedException)
11576 catch (InvalidOperationException)
11582 private int userStreamsRefreshing = 0;
11584 private async void tw_NewPostFromStream(object sender, EventArgs e)
11586 if (this._cfgCommon.ReadOldPosts)
11588 _statuses.SetReadHomeTab(); //新着時未読クリア
11591 this._statuses.DistributePosts();
11593 if (this._cfgCommon.UserstreamPeriod > 0) return;
11595 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
11596 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
11600 await this.InvokeAsync(() => this.RefreshTimeline())
11601 .ConfigureAwait(false);
11605 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
11610 private async void tw_UserStreamStarted(object sender, EventArgs e)
11614 if (InvokeRequired && !IsDisposed)
11616 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11620 catch (ObjectDisposedException)
11624 catch (InvalidOperationException)
11629 this.RefreshUserStreamsMenu();
11630 this.MenuItemUserStream.Enabled = true;
11632 StatusLabel.Text = "UserStream Started.";
11635 private async void tw_UserStreamStopped(object sender, EventArgs e)
11639 if (InvokeRequired && !IsDisposed)
11641 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11645 catch (ObjectDisposedException)
11649 catch (InvalidOperationException)
11654 this.RefreshUserStreamsMenu();
11655 this.MenuItemUserStream.Enabled = true;
11657 StatusLabel.Text = "UserStream Stopped.";
11660 private void RefreshUserStreamsMenu()
11662 if (this.tw.UserStreamActive)
11664 this.MenuItemUserStream.Text = "&UserStream ▶";
11665 this.StopToolStripMenuItem.Text = "&Stop";
11669 this.MenuItemUserStream.Text = "&UserStream ■";
11670 this.StopToolStripMenuItem.Text = "&Start";
11674 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11678 if (InvokeRequired && !IsDisposed)
11680 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11684 catch (ObjectDisposedException)
11688 catch (InvalidOperationException)
11692 var ev = e.EventData;
11693 StatusLabel.Text = "Event: " + ev.Event;
11694 //if (ev.Event == "favorite")
11696 // NotifyFavorite(ev);
11699 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11701 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
11703 this.PurgeListViewItemCache();
11704 ((DetailsListView)_curTab.Tag).Update();
11706 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
11708 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11709 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11714 private void NotifyEvent(Twitter.FormattedEvent ev)
11717 if (BalloonRequired(ev))
11719 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11720 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11721 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11722 StringBuilder title = new StringBuilder();
11723 if (this._cfgCommon.DispUsername)
11725 title.Append(tw.Username);
11726 title.Append(" - ");
11732 title.Append(Application.ProductName);
11733 title.Append(" [");
11734 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11735 title.Append("] by ");
11736 if (!string.IsNullOrEmpty(ev.Username))
11738 title.Append(ev.Username);
11742 //title.Append("");
11745 if (!string.IsNullOrEmpty(ev.Target))
11747 //NotifyIcon1.BalloonTipText = ev.Target;
11752 //NotifyIcon1.BalloonTipText = " ";
11755 //NotifyIcon1.ShowBalloonTip(500);
11756 if (this._cfgCommon.IsUseNotifyGrowl)
11758 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11759 ev.Id.ToString(), title.ToString(), text);
11763 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11764 NotifyIcon1.BalloonTipTitle = title.ToString();
11765 NotifyIcon1.BalloonTipText = text;
11766 NotifyIcon1.ShowBalloonTip(500);
11771 string snd = this._cfgCommon.EventSoundFile;
11772 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
11774 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11778 string dir = Application.StartupPath;
11779 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11781 dir = Path.Combine(dir, "Sounds");
11783 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11795 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11797 MenuItemUserStream.Enabled = false;
11798 if (StopRefreshAllMenuItem.Checked)
11800 StopRefreshAllMenuItem.Checked = false;
11803 if (this.tw.UserStreamActive)
11805 tw.StopUserStream();
11809 tw.StartUserStream();
11813 private static string inputTrack = "";
11815 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11817 if (TrackToolStripMenuItem.Checked)
11819 using (InputTabName inputForm = new InputTabName())
11821 inputForm.TabName = inputTrack;
11822 inputForm.FormTitle = "Input track word";
11823 inputForm.FormDescription = "Track word";
11824 if (inputForm.ShowDialog() != DialogResult.OK)
11826 TrackToolStripMenuItem.Checked = false;
11829 inputTrack = inputForm.TabName.Trim();
11831 if (!inputTrack.Equals(tw.TrackWord))
11833 tw.TrackWord = inputTrack;
11834 this.ModifySettingCommon = true;
11835 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11836 tw.ReconnectUserStream();
11842 tw.ReconnectUserStream();
11844 this.ModifySettingCommon = true;
11847 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11849 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11850 this.ModifySettingCommon = true;
11851 tw.ReconnectUserStream();
11854 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11856 if (evtDialog == null || evtDialog.IsDisposed)
11859 evtDialog = new EventViewerDialog();
11860 evtDialog.Owner = this;
11862 Point pos = evtDialog.Location;
11863 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
11864 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
11865 evtDialog.Location = pos;
11867 evtDialog.EventSource = tw.StoredEvent;
11868 if (!evtDialog.Visible)
11870 evtDialog.Show(this);
11874 evtDialog.Activate();
11876 this.TopMost = this._cfgCommon.AlwaysTop;
11880 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11882 MyCommon._endingFlag = true;
11886 Application.Restart();
11890 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
11894 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
11896 if (!string.IsNullOrEmpty(tw.Username))
11897 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
11900 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11902 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11905 private bool ExistCurrentPost
11909 if (_curPost == null) return false;
11910 if (_curPost.IsDeleted) return false;
11915 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11917 ShowUserTimeline();
11920 private string GetUserIdFromCurPostOrInput(string caption)
11922 var id = _curPost?.ScreenName ?? "";
11924 using (InputTabName inputName = new InputTabName())
11926 inputName.FormTitle = caption;
11927 inputName.FormDescription = Properties.Resources.FRMessage1;
11928 inputName.TabName = id;
11929 if (inputName.ShowDialog() == DialogResult.OK &&
11930 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11932 id = inputName.TabName.Trim();
11942 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11944 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11945 if (!string.IsNullOrEmpty(id))
11947 AddNewTabForUserTimeline(id);
11951 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
11953 string id = GetUserIdFromCurPostOrInput("Show Favstar");
11954 if (!string.IsNullOrEmpty(id))
11956 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
11960 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11962 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
11965 private void TimelineRefreshEnableChange(bool isEnable)
11969 tw.StartUserStream();
11973 tw.StopUserStream();
11975 TimerTimeline.Enabled = isEnable;
11978 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11980 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
11983 private async Task OpenUserAppointUrl()
11985 if (this._cfgCommon.UserAppointUrl != null)
11987 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
11989 if (_curPost != null)
11991 string xUrl = this._cfgCommon.UserAppointUrl;
11992 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
11994 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
11995 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
11997 await this.OpenUriInBrowserAsync(xUrl);
12002 await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
12007 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12009 await this.OpenUserAppointUrl();
12012 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
12014 if (Form.ActiveForm == null)
12016 await this.InvokeAsync(() =>
12018 this.Visible = true;
12019 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12021 this.BringToFront();
12022 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
12024 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12028 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12034 private void ReplaceAppName()
12036 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12037 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12040 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12042 this.SplitContainer3.Panel2Collapsed = false;
12045 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12047 await this.OpenThumbnailPicture(e.Thumbnail);
12050 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
12052 await this.OpenUriInBrowserAsync(e.ImageUrl);
12055 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
12057 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
12059 await this.OpenUriInBrowserAsync(url);
12062 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
12064 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
12067 private void PostButton_KeyDown(object sender, KeyEventArgs e)
12069 if (e.KeyCode == Keys.Space)
12071 this.JumpUnreadMenuItem_Click(null, null);
12073 e.SuppressKeyPress = true;
12077 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
12079 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
12080 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
12081 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
12082 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
12083 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
12085 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
12088 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
12090 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
12093 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
12095 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
12098 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
12100 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
12103 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
12105 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
12108 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
12110 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
12113 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
12115 if (this._cfgCommon.IconSize == iconSize) return;
12117 var oldIconCol = _iconCol;
12119 this._cfgCommon.IconSize = iconSize;
12120 ApplyListViewIconSize(iconSize);
12122 if (_iconCol != oldIconCol)
12124 foreach (TabPage tp in ListTab.TabPages)
12126 ResetColumns((DetailsListView)tp.Tag);
12130 _curList?.Refresh();
12132 ModifySettingCommon = true;
12135 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
12137 var state = this.LockListSortOrderToolStripMenuItem.Checked;
12138 if (this._cfgCommon.SortOrderLock == state) return;
12140 this._cfgCommon.SortOrderLock = state;
12142 ModifySettingCommon = true;
12145 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
12147 if (!string.IsNullOrEmpty(e.StatusText))
12149 this.StatusLabelUrl.Text = e.StatusText;
12153 this.SetStatusLabelUrl();