1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
28 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
29 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
32 using System.Collections.Concurrent;
33 using System.Collections.Generic;
34 using System.ComponentModel;
35 using System.Diagnostics;
37 using System.Globalization;
42 using System.Net.Http;
43 using System.Reflection;
45 using System.Text.RegularExpressions;
46 using System.Threading;
47 using System.Threading.Tasks;
48 using System.Windows.Forms;
50 using OpenTween.Api.DataModel;
51 using OpenTween.Connection;
52 using OpenTween.OpenTweenCustomControl;
53 using OpenTween.Thumbnail;
57 public partial class TweenMain : OTBaseForm
60 private Size _mySize; //画面サイズ
61 private Point _myLoc; //画面位置
62 private int _mySpDis; //区切り位置
63 private int _mySpDis2; //発言欄区切り位置
64 private int _mySpDis3; //プレビュー区切り位置
65 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
66 private bool _iconCol; //1列表示の時true(48サイズのとき)
69 private bool _initial; //true:起動時処理中
70 private bool _initialLayout = true;
71 private bool _ignoreConfigSave; //true:起動時処理中
72 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
73 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
74 private Point _tabMouseDownPoint;
75 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
76 private readonly object _syncObject = new object(); //ロック用
78 private const string detailHtmlFormatHeaderMono =
79 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
80 + "<style type=\"text/css\"><!-- "
81 + "body, p, pre {margin: 0;} "
82 + "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%);} "
83 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
84 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
85 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
86 + ".quote-tweet.reply {border-color: #f33;} "
87 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
89 + "</head><body><pre>";
90 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
91 private const string detailHtmlFormatHeaderColor =
92 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
93 + "<style type=\"text/css\"><!-- "
94 + "body, p, pre {margin: 0;} "
95 + "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%);} "
96 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
97 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
98 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
99 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
100 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
102 + "</head><body><p>";
103 private const string detailHtmlFormatFooterColor = "</p></body></html>";
104 private string detailHtmlFormatHeader;
105 private string detailHtmlFormatFooter;
107 private bool _myStatusError = false;
108 private bool _myStatusOnline = false;
109 private bool soundfileListup = false;
110 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
113 //private SettingToConfig _cfg; //旧
114 private SettingLocal _cfgLocal;
115 private SettingCommon _cfgCommon;
118 private TwitterApi twitterApi = new TwitterApi();
122 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
125 private SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
126 private OpenURL UrlDialog = new OpenURL();
127 public AtIdSupplement AtIdSupl; //@id補助
128 public AtIdSupplement HashSupl; //Hashtag補助
129 public HashtagManage HashMgr;
130 private EventViewerDialog evtDialog;
133 private Font _fntUnread; //未読用フォント
134 private Color _clUnread; //未読用文字色
135 private Font _fntReaded; //既読用フォント
136 private Color _clReaded; //既読用文字色
137 private Color _clFav; //Fav用文字色
138 private Color _clOWL; //片思い用文字色
139 private Color _clRetweet; //Retweet用文字色
140 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
141 private Font _fntDetail; //発言詳細部用フォント
142 private Color _clDetail; //発言詳細部用色
143 private Color _clDetailLink; //発言詳細部用リンク文字色
144 private Color _clDetailBackcolor; //発言詳細部用背景色
145 private Color _clSelf; //自分の発言用背景色
146 private Color _clAtSelf; //自分宛返信用背景色
147 private Color _clTarget; //選択発言者の他の発言用背景色
148 private Color _clAtTarget; //選択発言中の返信先用背景色
149 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
150 private Color _clAtTo; //選択発言の唯一@先
151 private Color _clListBackcolor; //リスト部通常発言背景色
152 private Color _clInputBackcolor; //入力欄背景色
153 private Color _clInputFont; //入力欄文字色
154 private Font _fntInputFont; //入力欄フォント
155 private ImageCache IconCache; //アイコン画像リスト
156 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
157 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
158 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
159 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
160 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
161 private Icon MainIcon; //Main.ico 画面左上のアイコン
162 private Icon ReplyIcon; //5g
163 private Icon ReplyIconBlink; //6g
165 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
167 private PostClass _anchorPost;
168 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
170 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
171 private int _hisIdx; //発言履歴カレントインデックス
173 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
174 private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
177 private List<DateTime> _postTimestamps = new List<DateTime>();
178 private List<DateTime> _favTimestamps = new List<DateTime>();
179 private ConcurrentDictionary<DateTime, int> _tlTimestamps = new ConcurrentDictionary<DateTime, int>();
180 private int _tlCount;
183 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
184 private SolidBrush _brsBackColorMine;
185 private SolidBrush _brsBackColorAt;
186 private SolidBrush _brsBackColorYou;
187 private SolidBrush _brsBackColorAtYou;
188 private SolidBrush _brsBackColorAtFromTarget;
189 private SolidBrush _brsBackColorAtTo;
190 private SolidBrush _brsBackColorNone;
191 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
192 private StringFormat sfTab = new StringFormat();
194 //////////////////////////////////////////////////////////////////////////////////////////////////////////
195 private TabInformations _statuses;
198 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
201 /// キャッシュクリアのために null が代入されることがあるため、
202 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
203 /// 一旦ローカル変数に代入してから参照すること。
205 private ListViewItemCache _listItemCache = null;
207 internal class ListViewItemCache
209 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
210 public ListView TargetList { get; set; }
212 /// <summary>キャッシュする範囲の開始インデックス</summary>
213 public int StartIndex { get; set; }
215 /// <summary>キャッシュする範囲の終了インデックス</summary>
216 public int EndIndex { get; set; }
218 /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
219 public ListViewItem[] ListItem { get; set; }
221 /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
222 public PostClass[] Post { get; set; }
224 /// <summary>キャッシュされたアイテムの件数</summary>
226 => this.EndIndex - this.StartIndex + 1;
228 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
229 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
230 public bool Contains(int index)
231 => index >= this.StartIndex && index <= this.EndIndex;
233 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
234 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
235 public bool IsSupersetOf(int rangeStart, int rangeEnd)
236 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
238 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
239 /// <returns>取得に成功すれば true、それ以外は false</returns>
240 public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
242 if (this.Contains(index))
244 item = this.ListItem[index - this.StartIndex];
245 post = this.Post[index - this.StartIndex];
257 private TabPage _curTab;
258 private int _curItemIndex;
259 private DetailsListView _curList;
260 private PostClass _curPost;
261 private bool _isColumnChanged = false;
263 private const int MAX_WORKER_THREADS = 20;
264 private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
265 private CancellationTokenSource workerCts = new CancellationTokenSource();
267 private int UnreadCounter = -1;
268 private int UnreadAtCounter = -1;
270 private string[] ColumnOrgText = new string[9];
271 private string[] ColumnText = new string[9];
273 private bool _DoFavRetweetFlags = false;
274 private bool osResumed = false;
276 //////////////////////////////////////////////////////////////////////////////////////////////////////////
277 private string _postBrowserStatusText = "";
279 private bool _colorize = false;
281 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
283 private ImageListViewItem displayItem;
285 private string recommendedStatusFooter;
288 private struct urlUndo
290 public string Before;
294 private List<urlUndo> urlUndoBuffer = null;
296 private struct ReplyChain
298 public long OriginalId;
299 public long InReplyToId;
300 public TabPage OriginalTab;
302 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
304 this.OriginalId = originalId;
305 this.InReplyToId = inReplyToId;
306 this.OriginalTab = originalTab;
310 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
311 private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
314 private enum SEARCHTYPE
321 private class PostingStatus
323 public string status = "";
324 public long? inReplyToId = null;
325 public string inReplyToName = null;
326 public string imageService = ""; //画像投稿サービス名
327 public IMediaItem[] mediaItems = null;
328 public PostingStatus()
331 public PostingStatus(string status, long? replyToId, string replyToName)
333 this.status = status;
334 this.inReplyToId = replyToId;
335 this.inReplyToName = replyToName;
339 private void TweenMain_Activated(object sender, EventArgs e)
341 //画面がアクティブになったら、発言欄の背景色戻す
342 if (StatusText.Focused)
344 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
348 private bool disposed = false;
351 /// 使用中のリソースをすべてクリーンアップします。
353 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
354 protected override void Dispose(bool disposing)
356 base.Dispose(disposing);
363 this.components?.Dispose();
366 SearchDialog.Dispose();
369 NIconAtRed?.Dispose();
370 NIconAtSmoke?.Dispose();
371 foreach (var iconRefresh in this.NIconRefresh)
373 iconRefresh?.Dispose();
377 ReplyIcon?.Dispose();
378 ReplyIconBlink?.Dispose();
379 _listViewImageList.Dispose();
380 _brsHighLight.Dispose();
381 _brsBackColorMine?.Dispose();
382 _brsBackColorAt?.Dispose();
383 _brsBackColorYou?.Dispose();
384 _brsBackColorAtYou?.Dispose();
385 _brsBackColorAtFromTarget?.Dispose();
386 _brsBackColorAtTo?.Dispose();
387 _brsBackColorNone?.Dispose();
388 _brsDeactiveSelection?.Dispose();
392 this.workerCts.Cancel();
394 if (IconCache != null)
396 this.IconCache.CancelAsync();
397 this.IconCache.Dispose();
400 this.thumbnailTokenSource?.Dispose();
403 this.twitterApi.Dispose();
404 this._hookGlobalHotkey.Dispose();
407 // 終了時にRemoveHandlerしておかないとメモリリークする
408 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
409 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
411 this.disposed = true;
414 private void LoadIcons()
416 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
417 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
420 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
423 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
426 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
429 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
431 // タスクトレイ: オフライン時アイコン
432 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
434 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
435 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
436 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
438 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
439 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
440 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
441 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
442 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
444 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
446 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
447 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
448 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
449 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
450 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
452 if (iconReply != null && iconReplyBlink != null)
454 this.ReplyIcon = iconReply;
455 this.ReplyIconBlink = iconReplyBlink;
459 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
460 this.ReplyIconBlink = this.NIconAt;
463 if (iconRefresh1 == null)
465 this.NIconRefresh = new[] {
466 Properties.Resources.Refresh, Properties.Resources.Refresh2,
467 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
470 else if (iconRefresh2 == null)
472 this.NIconRefresh = new[] { iconRefresh1 };
474 else if (iconRefresh3 == null)
476 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
478 else if (iconRefresh4 == null)
480 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
482 else // iconRefresh1 から iconRefresh4 まで全て揃っている
484 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
488 private Icon LoadIcon(string filePath)
490 if (!File.Exists(filePath))
495 return new Icon(filePath);
503 private void InitColumns(ListView list, bool startup)
505 this.InitColumnText();
507 ColumnHeader[] columns = null;
514 new ColumnHeader(), // アイコン
515 new ColumnHeader(), // 本文
518 columns[0].Text = this.ColumnText[0];
519 columns[1].Text = this.ColumnText[2];
523 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
525 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
526 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
527 columns[0].DisplayIndex = 0;
528 columns[1].DisplayIndex = 1;
533 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
535 columns[idx].Width = curListColumn.Width;
536 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
545 new ColumnHeader(), // アイコン
546 new ColumnHeader(), // ニックネーム
547 new ColumnHeader(), // 本文
548 new ColumnHeader(), // 日付
549 new ColumnHeader(), // ユーザID
550 new ColumnHeader(), // 未読
551 new ColumnHeader(), // マーク&プロテクト
552 new ColumnHeader(), // ソース
555 foreach (var i in Enumerable.Range(0, columns.Length))
556 columns[i].Text = this.ColumnText[i];
560 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
562 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
563 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
564 columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
565 columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
566 columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
567 columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
568 columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
569 columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
571 var displayIndex = new[] {
572 this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
573 this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
574 this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
575 this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
578 foreach (var i in Enumerable.Range(0, displayIndex.Length))
580 columns[i].DisplayIndex = displayIndex[i];
586 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
588 columns[idx].Width = curListColumn.Width;
589 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
595 list.Columns.AddRange(columns);
603 foreach (var column in columns)
609 private void InitColumnText()
612 ColumnText[1] = Properties.Resources.AddNewTabText2;
613 ColumnText[2] = Properties.Resources.AddNewTabText3;
614 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
615 ColumnText[4] = Properties.Resources.AddNewTabText5;
618 ColumnText[7] = "Source";
620 ColumnOrgText[0] = "";
621 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
622 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
623 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
624 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
625 ColumnOrgText[5] = "";
626 ColumnOrgText[6] = "";
627 ColumnOrgText[7] = "Source";
630 switch (_statuses.SortMode)
632 case ComparerMode.Nickname: //ニックネーム
635 case ComparerMode.Data: //本文
638 case ComparerMode.Id: //時刻=発言Id
641 case ComparerMode.Name: //名前
644 case ComparerMode.Source: //Source
651 if (_statuses.SortOrder == SortOrder.Descending)
653 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
654 ColumnText[2] = ColumnOrgText[2] + "▾";
658 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
659 ColumnText[2] = ColumnOrgText[2] + "▴";
664 if (_statuses.SortOrder == SortOrder.Descending)
666 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
667 ColumnText[c] = ColumnOrgText[c] + "▾";
671 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
672 ColumnText[c] = ColumnOrgText[c] + "▴";
677 private void InitializeTraceFrag()
680 TraceOutToolStripMenuItem.Checked = true;
681 MyCommon.TraceFlag = true;
683 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
685 TraceOutToolStripMenuItem.Checked = true;
686 MyCommon.TraceFlag = true;
690 private void TweenMain_Load(object sender, EventArgs e)
692 _ignoreConfigSave = true;
693 this.Visible = false;
695 if (MyApplication.StartupOptions.ContainsKey("d"))
696 MyCommon.TraceFlag = true;
698 InitializeTraceFrag();
700 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
702 new InternetSecurityManager(PostBrowser);
703 this.PostBrowser.AllowWebBrowserDrop = false; // COMException を回避するため、ActiveX の初期化が終わってから設定する
705 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
706 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
708 Regex.CacheSize = 100;
711 _statuses = TabInformations.GetInstance();
715 this.Icon = MainIcon; //メインフォーム(TweenMain)
716 NotifyIcon1.Icon = NIconAt; //タスクトレイ
717 TabImage.Images.Add(TabIcon); //タブ見出し
719 //<<<<<<<<<設定関連>>>>>>>>>
723 // 現在の DPI と設定保存時の DPI との比を取得する
724 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
727 var fontUIGlobal = this._cfgLocal.FontUIGlobal;
728 if (fontUIGlobal != null)
730 OTBaseForm.GlobalFont = fontUIGlobal;
731 this.Font = fontUIGlobal;
735 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
737 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
738 this._cfgCommon.TimelinePeriod = 15;
740 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
741 this._cfgCommon.ReplyPeriod = 15;
743 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
744 this._cfgCommon.DMPeriod = 15;
746 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
747 this._cfgCommon.PubSearchPeriod = 30;
749 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
750 this._cfgCommon.UserTimelinePeriod = 15;
752 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
753 this._cfgCommon.ListsPeriod = 15;
756 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
757 this._cfgCommon.CountApi = 60;
758 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
759 this._cfgCommon.CountApiReply = 40;
761 if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
762 this._cfgCommon.MoreCountApi = 200;
763 if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
764 this._cfgCommon.FirstCountApi = 100;
766 if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
767 this._cfgCommon.FavoritesCountApi = 40;
768 if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
769 this._cfgCommon.ListCountApi = 100;
770 if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
771 this._cfgCommon.SearchCountApi = 100;
772 if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
773 this._cfgCommon.UserTimelineCountApi = 20;
775 //廃止サービスが選択されていた場合ux.nuへ読み替え
776 if (this._cfgCommon.AutoShortUrlFirst < 0)
777 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
779 TwitterApiConnection.RestApiBase = new Uri(this._cfgCommon.TwitterUrl);
780 this.tw = new Twitter(this.twitterApi);
783 if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
784 tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
788 Networking.Initialize();
790 bool saveRequired = false;
791 bool firstRun = false;
793 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
794 if (string.IsNullOrEmpty(tw.Username))
799 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
800 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
801 string.IsNullOrEmpty(tw.Username))
803 Application.Exit(); //強制終了
809 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
810 Networking.SetWebProxy(this._cfgLocal.ProxyType,
811 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
812 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
813 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
815 TwitterApiConnection.RestApiBase = new Uri(this._cfgCommon.TwitterUrl);
816 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
817 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
818 tw.TrackWord = this._cfgCommon.TrackWord;
819 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
820 tw.AllAtReply = this._cfgCommon.AllAtReply;
821 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
822 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
823 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
824 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
826 // アクセストークンが有効であるか確認する
827 // ここが Twitter API への最初のアクセスになるようにすること
830 this.tw.VerifyCredentials();
832 catch (WebApiException ex)
834 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
835 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
839 //プロキシ設定等の通信まわりの初期化が済んでから処理する
840 ThumbnailGenerator.InitializeGenerator();
842 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
843 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
844 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
846 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
849 ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
852 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
853 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
854 HashMgr = new HashtagManage(HashSupl,
855 _cfgCommon.HashTags.ToArray(),
856 _cfgCommon.HashSelected,
857 _cfgCommon.HashIsPermanent,
858 _cfgCommon.HashIsHead,
859 _cfgCommon.HashIsNotAddToAtReply);
860 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
863 this.IconCache = new ImageCache();
866 _fntUnread = this._cfgLocal.FontUnread;
867 _clUnread = this._cfgLocal.ColorUnread;
868 _fntReaded = this._cfgLocal.FontRead;
869 _clReaded = this._cfgLocal.ColorRead;
870 _clFav = this._cfgLocal.ColorFav;
871 _clOWL = this._cfgLocal.ColorOWL;
872 _clRetweet = this._cfgLocal.ColorRetweet;
873 _fntDetail = this._cfgLocal.FontDetail;
874 _clDetail = this._cfgLocal.ColorDetail;
875 _clDetailLink = this._cfgLocal.ColorDetailLink;
876 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
877 _clSelf = this._cfgLocal.ColorSelf;
878 _clAtSelf = this._cfgLocal.ColorAtSelf;
879 _clTarget = this._cfgLocal.ColorTarget;
880 _clAtTarget = this._cfgLocal.ColorAtTarget;
881 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
882 _clAtTo = this._cfgLocal.ColorAtTo;
883 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
884 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
885 _clInputFont = this._cfgLocal.ColorInputFont;
886 _fntInputFont = this._cfgLocal.FontInputFont;
888 _brsBackColorMine = new SolidBrush(_clSelf);
889 _brsBackColorAt = new SolidBrush(_clAtSelf);
890 _brsBackColorYou = new SolidBrush(_clTarget);
891 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
892 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
893 _brsBackColorAtTo = new SolidBrush(_clAtTo);
894 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
895 _brsBackColorNone = new SolidBrush(_clListBackcolor);
897 // StringFormatオブジェクトへの事前設定
898 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
899 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
900 //sf.FormatFlags = StringFormatFlags.LineLimit; //
901 sfTab.Alignment = StringAlignment.Center;
902 sfTab.LineAlignment = StringAlignment.Center;
904 InitDetailHtmlFormat();
906 //Regex statregex = new Regex("^0*");
907 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
909 _history.Add(new PostingStatus());
911 this.inReplyTo = null;
914 SearchDialog.Owner = this;
915 UrlDialog.Owner = this;
918 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
919 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
921 //新着取得時のリストスクロールをするか。trueならスクロールしない
922 ListLockMenuItem.Checked = _cfgCommon.ListLock;
923 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
925 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
926 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
928 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
929 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
932 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
933 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
934 _myLoc = _cfgLocal.FormLocation;
936 if (this.WindowState != FormWindowState.Minimized)
938 this.DesktopLocation = _cfgLocal.FormLocation;
939 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
940 bool outOfScreen = true;
941 if (Screen.AllScreens.Length == 1) //ハングするとの報告
943 foreach (Screen scr in Screen.AllScreens)
945 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
953 this.DesktopLocation = new Point(0, 0);
954 _myLoc = this.DesktopLocation;
958 this.TopMost = this._cfgCommon.AlwaysTop;
959 _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
960 _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
961 if (_cfgLocal.PreviewDistance == -1)
963 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
964 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
965 _cfgLocal.PreviewDistance = _mySpDis3;
969 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
971 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
972 //this.Tween_ClientSizeChanged(this, null);
973 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
974 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
976 StatusText.Font = _fntInputFont;
977 StatusText.ForeColor = _clInputFont;
979 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
980 this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
981 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
983 // NameLabel のフォントを OTBaseForm.GlobalFont に変更
984 this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
986 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
987 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
989 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
990 if (this._cfgCommon.UnreadManage == false)
992 ReadedStripMenuItem.Enabled = false;
993 UnreadStripMenuItem.Enabled = false;
998 DateTimeLabel.Text = "";
999 SourceLinkLabel.Text = "";
1001 //リンク先URL表示部の初期化(画面左下)
1002 StatusLabelUrl.Text = "";
1004 StatusLabel.Text = "";
1005 StatusLabel.AutoToolTip = false;
1006 StatusLabel.ToolTipText = "";
1008 lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
1010 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1011 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1012 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1013 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1015 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1016 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1017 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1018 this.SplitContainer2.Panel2.AccessibleName = "";
1020 ////////////////////////////////////////////////////////////////////////////////
1021 var sortOrder = (SortOrder)_cfgCommon.SortOrder;
1022 var mode = ComparerMode.Id;
1023 switch (_cfgCommon.SortColumn)
1025 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1029 mode = ComparerMode.Id; //Idソートに読み替え
1032 mode = ComparerMode.Nickname;
1035 mode = ComparerMode.Data;
1038 mode = ComparerMode.Id;
1041 mode = ComparerMode.Name;
1044 mode = ComparerMode.Source;
1047 _statuses.SetSortMode(mode, sortOrder);
1048 ////////////////////////////////////////////////////////////////////////////////
1050 ApplyListViewIconSize(this._cfgCommon.IconSize);
1052 //<<<<<<<<タブ関連>>>>>>>
1056 //デフォルトタブの存在チェック、ない場合には追加
1057 if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1060 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1062 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1066 tab.TabType = MyCommon.TabUsageType.Home;
1069 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1072 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1074 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1078 tab.TabType = MyCommon.TabUsageType.Mentions;
1081 if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1084 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1086 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1090 tab.TabType = MyCommon.TabUsageType.DirectMessage;
1093 if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1096 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1098 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1102 tab.TabType = MyCommon.TabUsageType.Favorites;
1105 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mute) == null)
1108 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.MUTE, out tab))
1110 _statuses.AddTab(MyCommon.DEFAULTTAB.MUTE, MyCommon.TabUsageType.Mute, null);
1114 tab.TabType = MyCommon.TabUsageType.Mute;
1118 foreach (var tab in _statuses.Tabs.Values)
1121 if (tab.TabType == MyCommon.TabUsageType.Mute)
1124 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1126 tab.TabType = MyCommon.TabUsageType.UserDefined;
1128 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo))
1129 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1132 _curTab = ListTab.SelectedTab;
1134 _curList = (DetailsListView)_curTab.Tag;
1136 if (this._cfgCommon.TabIconDisp)
1138 ListTab.DrawMode = TabDrawMode.Normal;
1142 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1143 ListTab.DrawItem += ListTab_DrawItem;
1144 ListTab.ImageList = null;
1147 if (this._cfgCommon.HotkeyEnabled)
1150 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1151 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1152 modKey |= HookGlobalHotkey.ModKeys.Alt;
1153 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1154 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1155 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1156 modKey |= HookGlobalHotkey.ModKeys.Shift;
1157 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1158 modKey |= HookGlobalHotkey.ModKeys.Win;
1160 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1163 if (this._cfgCommon.IsUseNotifyGrowl)
1166 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1168 SetMainWindowTitle();
1169 SetNotifyIconText();
1171 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1173 this.Visible = true;
1177 TimerTimeline.AutoReset = true;
1178 TimerTimeline.SynchronizingObject = this;
1180 TimerTimeline.Interval = 1000;
1181 TimerTimeline.Enabled = true;
1183 TimerRefreshIcon.Interval = 200;
1184 TimerRefreshIcon.Enabled = true;
1186 _ignoreConfigSave = false;
1187 this.TweenMain_Resize(null, null);
1188 if (saveRequired) SaveConfigsAll(false);
1190 foreach (var ua in this._cfgCommon.UserAccounts)
1192 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1194 ua.UserId = tw.UserId;
1201 // 初回起動時だけ右下のメニューを目立たせる
1202 HashStripSplitButton.ShowDropDown();
1206 private void InitDetailHtmlFormat()
1208 if (this._cfgCommon.IsMonospace)
1210 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1211 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1215 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1216 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1219 detailHtmlFormatHeader = detailHtmlFormatHeader
1220 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1221 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1222 .Replace("%FONT_COLOR%", _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString())
1223 .Replace("%LINK_COLOR%", _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString())
1224 .Replace("%BG_COLOR%", _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString())
1225 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1228 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1233 txt = ListTab.TabPages[e.Index].Text;
1240 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1241 if (e.State == DrawItemState.Selected)
1243 e.DrawFocusRectangle();
1248 if (_statuses.Tabs[txt].UnreadCount > 0)
1251 fore = System.Drawing.SystemBrushes.ControlText;
1255 fore = System.Drawing.SystemBrushes.ControlText;
1257 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1260 private void LoadConfig()
1262 _cfgCommon = SettingCommon.Load();
1263 SettingCommon.Instance = this._cfgCommon;
1264 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1266 _cfgCommon.UserAccounts = new List<UserAccount>();
1267 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1269 UserAccount account = new UserAccount();
1270 account.Username = _cfgCommon.UserName;
1271 account.UserId = _cfgCommon.UserId;
1272 account.Token = _cfgCommon.Token;
1273 account.TokenSecret = _cfgCommon.TokenSecret;
1275 _cfgCommon.UserAccounts.Add(account);
1279 _cfgLocal = SettingLocal.Load();
1281 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1282 if (_cfgLocal.ScaleDimension.IsEmpty)
1283 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1285 List<TabClass> tabs = SettingTabs.Load().Tabs;
1286 foreach (TabClass tb in tabs)
1290 tb.FilterModified = false;
1291 _statuses.Tabs.Add(tb.TabName, tb);
1295 tb.TabName = _statuses.MakeTabName("MyTab");
1296 _statuses.Tabs.Add(tb.TabName, tb);
1299 if (_statuses.Tabs.Count == 0)
1301 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1302 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1303 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1304 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1308 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1310 if (!TimerTimeline.Enabled) return;
1314 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1316 private static int homeCounter = 0;
1317 private static int mentionCounter = 0;
1318 private static int dmCounter = 0;
1319 private static int pubSearchCounter = 0;
1320 private static int userTimelineCounter = 0;
1321 private static int listsCounter = 0;
1322 private static int usCounter = 0;
1323 private static int ResumeWait = 0;
1324 private static int refreshFollowers = 0;
1326 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1328 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1329 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1330 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1331 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1332 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1333 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1334 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1335 Interlocked.Increment(ref refreshFollowers);
1337 var refreshTasks = new List<Task>();
1340 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1342 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1343 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1344 refreshTasks.Add(this.GetHomeTimelineAsync());
1345 ResetTimers.Timeline = false;
1347 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1349 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1350 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1351 refreshTasks.Add(this.GetReplyAsync());
1352 ResetTimers.Reply = false;
1354 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1356 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1357 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1358 refreshTasks.Add(this.GetDirectMessagesAsync());
1359 ResetTimers.DirectMessage = false;
1361 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1363 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1364 if (!ResetTimers.PublicSearch)
1365 refreshTasks.Add(this.GetPublicSearchAllAsync());
1366 ResetTimers.PublicSearch = false;
1368 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1370 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1371 if (!ResetTimers.UserTimeline)
1372 refreshTasks.Add(this.GetUserTimelineAllAsync());
1373 ResetTimers.UserTimeline = false;
1375 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1377 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1378 if (!ResetTimers.Lists)
1379 refreshTasks.Add(this.GetListTimelineAllAsync());
1380 ResetTimers.Lists = false;
1382 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1384 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1385 if (this.tw.UserStreamActive)
1386 this.RefreshTimeline();
1387 ResetTimers.UserStream = false;
1389 if (refreshFollowers > 6 * 3600)
1391 Interlocked.Exchange(ref refreshFollowers, 0);
1392 refreshTasks.AddRange(new[]
1394 this.doGetFollowersMenu(),
1395 this.RefreshNoRetweetIdsAsync(),
1396 this.RefreshTwitterConfigurationAsync(),
1401 Interlocked.Increment(ref ResumeWait);
1402 if (ResumeWait > 30)
1405 Interlocked.Exchange(ref ResumeWait, 0);
1406 refreshTasks.AddRange(new[]
1408 this.GetHomeTimelineAsync(),
1409 this.GetReplyAsync(),
1410 this.GetDirectMessagesAsync(),
1411 this.GetPublicSearchAllAsync(),
1412 this.GetUserTimelineAllAsync(),
1413 this.GetListTimelineAllAsync(),
1414 this.doGetFollowersMenu(),
1415 this.RefreshTwitterConfigurationAsync(),
1420 await Task.WhenAll(refreshTasks);
1423 private void RefreshTimeline()
1425 // 現在表示中のタブのスクロール位置を退避
1426 var curListScroll = this.SaveListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text]);
1428 // 各タブのリスト上の選択位置などを退避
1429 var listSelections = this.SaveListViewSelection();
1432 PostClass[] notifyPosts;
1435 bool newMentionOrDm;
1437 addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1439 if (MyCommon._endingFlag) return;
1444 foreach (TabPage tab in ListTab.TabPages)
1446 DetailsListView lst = (DetailsListView)tab.Tag;
1447 TabClass tabInfo = _statuses.Tabs[tab.Text];
1448 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1450 using (ControlTransaction.Update(lst))
1452 if (lst.Equals(_curList))
1454 this.PurgeListViewItemCache();
1458 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1466 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
1469 if (tabInfo.UnreadCount > 0)
1470 if (this._cfgCommon.TabIconDisp)
1471 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1473 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1477 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1482 this.RestoreListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text], curListScroll);
1485 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1487 SetMainWindowTitle();
1488 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1490 HashSupl.AddRangeItem(tw.GetHashList());
1494 internal struct ListViewScroll
1496 public ScrollLockMode ScrollLockMode { get; set; }
1497 public long? TopItemStatusId { get; set; }
1500 internal enum ScrollLockMode
1502 /// <summary>固定しない</summary>
1505 /// <summary>最上部に固定する</summary>
1508 /// <summary>最下部に固定する</summary>
1511 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1516 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1518 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabClass tab)
1520 var listScroll = new ListViewScroll
1522 ScrollLockMode = this.GetScrollLockMode(listView),
1525 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1527 var topItem = listView.TopItem;
1528 if (topItem != null)
1529 listScroll.TopItemStatusId = tab.GetId(topItem.Index);
1535 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1537 if (this._statuses.SortMode == ComparerMode.Id)
1539 if (this._statuses.SortOrder == SortOrder.Ascending)
1542 if (this.ListLockMenuItem.Checked)
1543 return ScrollLockMode.None;
1545 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1548 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1549 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1550 return ScrollLockMode.FixedToBottom;
1552 return ScrollLockMode.None;
1557 if (this.ListLockMenuItem.Checked)
1558 return ScrollLockMode.FixedToItem;
1560 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1561 var topItem = listView.TopItem;
1562 if (topItem == null || topItem.Index == 0)
1563 return ScrollLockMode.FixedToTop;
1565 return ScrollLockMode.FixedToItem;
1570 return ScrollLockMode.FixedToItem;
1574 internal struct ListViewSelection
1576 public long[] SelectedStatusIds { get; set; }
1577 public long? SelectionMarkStatusId { get; set; }
1578 public long? FocusedStatusId { get; set; }
1582 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1584 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1586 var listsDict = new Dictionary<string, ListViewSelection>();
1588 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1590 var listView = (DetailsListView)tabPage.Tag;
1591 var tab = _statuses.Tabs[tabPage.Text];
1593 ListViewSelection listStatus;
1594 if (listView.VirtualListSize != 0)
1596 listStatus = new ListViewSelection
1598 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1599 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1600 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1605 listStatus = new ListViewSelection
1607 SelectedStatusIds = new long[0],
1608 SelectionMarkStatusId = null,
1609 FocusedStatusId = null,
1613 listsDict[tab.TabName] = listStatus;
1619 private long[] GetSelectedStatusIds(DetailsListView listView, TabClass tab)
1621 var selectedIndices = listView.SelectedIndices;
1622 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1623 return tab.GetId(selectedIndices);
1628 private long? GetFocusedStatusId(DetailsListView listView, TabClass tab)
1630 var focusedItem = listView.FocusedItem;
1632 return focusedItem != null ? tab.GetId(focusedItem.Index) : (long?)null;
1635 private long? GetSelectionMarkStatusId(DetailsListView listView, TabClass tab)
1637 var selectionMarkIndex = listView.SelectionMark;
1639 return selectionMarkIndex != -1 ? tab.GetId(selectionMarkIndex) : (long?)null;
1643 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1645 private void RestoreListViewScroll(DetailsListView listView, TabClass tab, ListViewScroll listScroll)
1647 if (listView.VirtualListSize == 0)
1650 switch (listScroll.ScrollLockMode)
1652 case ScrollLockMode.FixedToTop:
1653 listView.EnsureVisible(0);
1655 case ScrollLockMode.FixedToBottom:
1656 listView.EnsureVisible(listView.VirtualListSize - 1);
1658 case ScrollLockMode.FixedToItem:
1659 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1661 listView.TopItem = listView.Items[topIndex];
1663 case ScrollLockMode.None:
1670 /// <see cref="SaveListViewStatus"/> によって保存された選択状態を復元します
1672 private void RestoreListViewSelection(DetailsListView listView, TabClass tab, ListViewSelection listSelection)
1674 // status_id から ListView 上のインデックスに変換
1675 int[] selectedIndices = null;
1676 if (listSelection.SelectedStatusIds != null)
1677 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1679 var focusedIndex = -1;
1680 if (listSelection.FocusedStatusId != null)
1681 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1683 var selectionMarkIndex = -1;
1684 if (listSelection.SelectionMarkStatusId != null)
1685 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1687 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1690 private bool BalloonRequired()
1692 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1693 ev.Eventtype = MyCommon.EVENTTYPE.None;
1695 return BalloonRequired(ev);
1698 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1700 if (type == MyCommon.EVENTTYPE.None)
1703 if (!this._cfgCommon.EventNotifyEnabled)
1706 return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1709 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1714 return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1717 private bool BalloonRequired(Twitter.FormattedEvent ev)
1722 if (NativeMethods.IsScreenSaverRunning())
1726 if (!this.NewPostPopMenuItem.Checked)
1728 // 「新着通知が無効でもイベントを通知する」にも該当しない
1729 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1733 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1734 if (this._cfgCommon.LimitBalloon)
1736 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1740 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1743 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1745 if (this._cfgCommon.ReadOwnPost)
1747 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1752 if (BalloonRequired())
1754 if (notifyPosts != null && notifyPosts.Length > 0)
1756 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1757 if (this._cfgCommon.IsUseNotifyGrowl)
1759 StringBuilder sb = new StringBuilder();
1763 foreach (PostClass post in notifyPosts)
1765 if (!(notifyPosts.Length > 3))
1771 if (post.IsReply && !post.IsExcludeReply) reply = true;
1772 if (post.IsDm) dm = true;
1773 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1774 switch (this._cfgCommon.NameBalloon)
1776 case MyCommon.NameBalloonEnum.UserID:
1777 sb.Append(post.ScreenName).Append(" : ");
1779 case MyCommon.NameBalloonEnum.NickName:
1780 sb.Append(post.Nickname).Append(" : ");
1783 sb.Append(post.TextFromApi);
1784 if (notifyPosts.Length > 3)
1786 if (notifyPosts.Last() != post) continue;
1789 StringBuilder title = new StringBuilder();
1790 GrowlHelper.NotifyType nt;
1791 if (this._cfgCommon.DispUsername)
1793 title.Append(tw.Username);
1794 title.Append(" - ");
1802 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1803 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1804 title.Append(Application.ProductName);
1805 title.Append(" [DM] ");
1806 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1807 nt = GrowlHelper.NotifyType.DirectMessage;
1811 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1812 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1813 title.Append(Application.ProductName);
1814 title.Append(" [Reply!] ");
1815 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1816 nt = GrowlHelper.NotifyType.Reply;
1820 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1821 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1822 title.Append(Application.ProductName);
1824 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1825 nt = GrowlHelper.NotifyType.Notify;
1827 string bText = sb.ToString();
1828 if (string.IsNullOrEmpty(bText)) return;
1830 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1831 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1836 StringBuilder sb = new StringBuilder();
1839 foreach (PostClass post in notifyPosts)
1841 if (post.IsReply && !post.IsExcludeReply) reply = true;
1842 if (post.IsDm) dm = true;
1843 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1844 switch (this._cfgCommon.NameBalloon)
1846 case MyCommon.NameBalloonEnum.UserID:
1847 sb.Append(post.ScreenName).Append(" : ");
1849 case MyCommon.NameBalloonEnum.NickName:
1850 sb.Append(post.Nickname).Append(" : ");
1853 sb.Append(post.TextFromApi);
1856 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1857 StringBuilder title = new StringBuilder();
1859 if (this._cfgCommon.DispUsername)
1861 title.Append(tw.Username);
1862 title.Append(" - ");
1870 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1871 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1872 ntIcon = ToolTipIcon.Warning;
1873 title.Append(Application.ProductName);
1874 title.Append(" [DM] ");
1875 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1879 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1880 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1881 ntIcon = ToolTipIcon.Warning;
1882 title.Append(Application.ProductName);
1883 title.Append(" [Reply!] ");
1884 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1888 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1889 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1890 ntIcon = ToolTipIcon.Info;
1891 title.Append(Application.ProductName);
1893 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1895 string bText = sb.ToString();
1896 if (string.IsNullOrEmpty(bText)) return;
1897 //NotifyIcon1.BalloonTipText = sb.ToString();
1898 //NotifyIcon1.ShowBalloonTip(500);
1899 NotifyIcon1.BalloonTipTitle = title.ToString();
1900 NotifyIcon1.BalloonTipText = bText;
1901 NotifyIcon1.BalloonTipIcon = ntIcon;
1902 NotifyIcon1.ShowBalloonTip(500);
1908 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1912 string dir = Application.StartupPath;
1913 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1915 dir = Path.Combine(dir, "Sounds");
1917 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1927 //mentions新着時に画面ブリンク
1928 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1930 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1934 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1936 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1938 _curItemIndex = _curList.SelectedIndices[0];
1939 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1943 this._curPost = GetCurTabPost(_curItemIndex);
1945 catch (ArgumentException)
1950 this.PushSelectPostChain();
1952 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1954 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1960 private void ChangeCacheStyleRead(bool Read, int Index)
1962 var tabInfo = _statuses.Tabs[_curTab.Text];
1963 //Read:true=既読 false=未読
1964 //未読管理していなかったら既読として扱う
1965 if (!tabInfo.UnreadManage ||
1966 !this._cfgCommon.UnreadManage) Read = true;
1968 var listCache = this._listItemCache;
1969 if (listCache == null)
1972 // キャッシュに含まれていないアイテムは対象外
1975 if (!listCache.TryGetValue(Index, out itm, out post))
1978 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1981 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1988 Item.SubItems[5].Text = "";
1993 Item.SubItems[5].Text = "★";
1999 else if (Post.RetweetedId != null)
2001 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
2003 else if (Read || !this._cfgCommon.UseUnreadStyle)
2008 if (DList == null || Item.Index == -1)
2010 Item.ForeColor = cl;
2011 if (this._cfgCommon.UseUnreadStyle)
2017 if (this._cfgCommon.UseUnreadStyle)
2018 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2020 DList.ChangeItemForeColor(Item.Index, cl);
2021 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2025 private void ColorizeList()
2027 //Index:更新対象のListviewItem.Index。Colorを返す。
2028 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2031 _post = _anchorPost;
2035 if (_post == null) return;
2037 var listCache = this._listItemCache;
2038 if (listCache == null)
2041 var index = listCache.StartIndex;
2042 foreach (var cachedPost in listCache.Post)
2044 var backColor = this.JudgeColor(_post, cachedPost);
2045 this._curList.ChangeItemBackColor(index++, backColor);
2049 private void ColorizeList(ListViewItem Item, int Index)
2051 //Index:更新対象のListviewItem.Index。Colorを返す。
2052 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2055 _post = _anchorPost;
2059 PostClass tPost = GetCurTabPost(Index);
2061 if (_post == null) return;
2063 if (Item.Index == -1)
2064 Item.BackColor = JudgeColor(_post, tPost);
2066 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2069 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2072 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2075 else if (TargetPost.IsMe)
2078 else if (TargetPost.IsReply)
2081 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2083 cl = _clAtFromTarget;
2084 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2087 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2092 cl = _clListBackcolor;
2097 private async void PostButton_Click(object sender, EventArgs e)
2099 if (StatusText.Text.Trim().Length == 0)
2101 if (!ImageSelector.Enabled)
2103 await this.DoRefresh();
2108 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2110 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2112 MessageBoxButtons.YesNoCancel,
2113 MessageBoxIcon.Question);
2116 case DialogResult.Yes:
2117 StatusText.Text = "";
2118 await this.doReTweetOfficial(false);
2120 case DialogResult.Cancel:
2125 var inReplyToStatusId = this.inReplyTo?.Item1;
2126 var inReplyToScreenName = this.inReplyTo?.Item2;
2127 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2129 if (this._cfgCommon.Nicoms)
2131 StatusText.SelectionStart = StatusText.Text.Length;
2132 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2134 //if (SettingDialog.UrlConvertAuto)
2136 // StatusText.SelectionStart = StatusText.Text.Length;
2137 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2139 //else if (SettingDialog.Nicoms)
2141 // StatusText.SelectionStart = StatusText.Text.Length;
2142 // UrlConvert(UrlConverter.Nicoms);
2144 StatusText.SelectionStart = StatusText.Text.Length;
2145 CheckReplyTo(StatusText.Text);
2147 var statusText = this.FormatStatusText(this.StatusText.Text);
2149 if (this.GetRestStatusCount(statusText) < 0)
2151 // 文字数制限を超えているが強制的に投稿するか
2152 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2153 if (ret != DialogResult.OK)
2157 var status = new PostingStatus();
2158 status.status = statusText;
2160 status.inReplyToId = this.inReplyTo?.Item1;
2161 status.inReplyToName = this.inReplyTo?.Item2;
2162 if (ImageSelector.Visible)
2165 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2169 this.inReplyTo = null;
2170 StatusText.Text = "";
2171 _history.Add(new PostingStatus());
2172 _hisIdx = _history.Count - 1;
2173 if (!ToolStripFocusLockMenuItem.Checked)
2174 ((Control)ListTab.SelectedTab.Tag).Focus();
2175 urlUndoBuffer = null;
2176 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2179 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2181 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2182 await this.OpenUriInBrowserAsync(tmp);
2185 await this.PostMessageAsync(status);
2188 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2190 MyCommon._endingFlag = true;
2194 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2196 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2198 //_endingFlag=false:フォームの×ボタン
2200 this.Visible = false;
2204 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2205 _ignoreConfigSave = true;
2206 MyCommon._endingFlag = true;
2207 TimerTimeline.Enabled = false;
2208 TimerRefreshIcon.Enabled = false;
2212 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2214 this.Visible = true;
2215 if (this.WindowState == FormWindowState.Minimized)
2217 this.WindowState = FormWindowState.Normal;
2220 this.BringToFront();
2223 private static int errorCount = 0;
2225 private static bool CheckAccountValid()
2227 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2233 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2242 private Task GetHomeTimelineAsync()
2244 return this.GetHomeTimelineAsync(loadMore: false);
2247 private async Task GetHomeTimelineAsync(bool loadMore)
2249 await this.workerSemaphore.WaitAsync();
2253 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2255 await this.GetHomeTimelineAsyncInternal(progress, this.workerCts.Token, loadMore);
2257 catch (WebApiException ex)
2259 this._myStatusError = true;
2260 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2264 this.workerSemaphore.Release();
2268 private async Task GetHomeTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2270 if (ct.IsCancellationRequested)
2273 if (!CheckAccountValid())
2274 throw new WebApiException("Auth error. Check your account");
2277 if (!this._cfgCommon.UnreadManage)
2280 read = this._initial && this._cfgCommon.Read;
2282 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5, loadMore ? -1 : 1));
2284 await Task.Run(async () =>
2286 await this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Timeline, loadMore, this._initial)
2287 .ConfigureAwait(false);
2290 if (this._cfgCommon.ReadOldPosts)
2291 this._statuses.SetReadHomeTab();
2293 var addCount = this._statuses.DistributePosts();
2296 this.UpdateTimelineSpeed(addCount);
2299 if (ct.IsCancellationRequested)
2302 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1);
2304 this.RefreshTimeline();
2308 /// タイムラインに追加された発言件数を反映し、タイムラインの流速を更新します
2310 /// <param name="addCount">直前にタイムラインに追加した発言件数</param>
2311 private void UpdateTimelineSpeed(int addCount)
2313 var now = DateTime.Now;
2314 this._tlTimestamps.AddOrUpdate(now, addCount, (k, v) => v + addCount);
2316 var removeKeys = new List<DateTime>();
2317 var oneHour = TimeSpan.FromHours(1);
2319 foreach (var pair in this._tlTimestamps)
2321 if (now - pair.Key > oneHour)
2322 removeKeys.Add(pair.Key);
2324 tlCount += pair.Value;
2326 Interlocked.Exchange(ref this._tlCount, tlCount);
2329 foreach (var key in removeKeys)
2330 this._tlTimestamps.TryRemove(key, out _);
2333 private Task GetReplyAsync()
2335 return this.GetReplyAsync(loadMore: false);
2338 private async Task GetReplyAsync(bool loadMore)
2340 await this.workerSemaphore.WaitAsync();
2344 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2346 await this.GetReplyAsyncInternal(progress, this.workerCts.Token, loadMore);
2348 catch (WebApiException ex)
2350 this._myStatusError = true;
2351 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2355 this.workerSemaphore.Release();
2359 private async Task GetReplyAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2361 if (ct.IsCancellationRequested)
2364 if (!CheckAccountValid())
2365 throw new WebApiException("Auth error. Check your account");
2368 if (!this._cfgCommon.UnreadManage)
2371 read = this._initial && this._cfgCommon.Read;
2373 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4, loadMore ? -1 : 1));
2375 await Task.Run(async () =>
2377 await this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Reply, loadMore, this._initial)
2378 .ConfigureAwait(false);
2380 this._statuses.DistributePosts();
2383 if (ct.IsCancellationRequested)
2386 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9);
2388 this.RefreshTimeline();
2391 private Task GetDirectMessagesAsync()
2393 return this.GetDirectMessagesAsync(loadMore: false);
2396 private async Task GetDirectMessagesAsync(bool loadMore)
2398 await this.workerSemaphore.WaitAsync();
2402 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2404 await this.GetDirectMessagesAsyncInternal(progress, this.workerCts.Token, loadMore);
2406 catch (WebApiException ex)
2408 this._myStatusError = true;
2409 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2413 this.workerSemaphore.Release();
2417 private async Task GetDirectMessagesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2419 if (ct.IsCancellationRequested)
2422 if (!CheckAccountValid())
2423 throw new WebApiException("Auth error. Check your account");
2426 if (!this._cfgCommon.UnreadManage)
2429 read = this._initial && this._cfgCommon.Read;
2431 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8, loadMore ? -1 : 1));
2433 await Task.Run(async () =>
2435 await this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, loadMore)
2436 .ConfigureAwait(false);
2437 await this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, loadMore)
2438 .ConfigureAwait(false);
2440 this._statuses.DistributePosts();
2443 if (ct.IsCancellationRequested)
2446 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11);
2448 this.RefreshTimeline();
2451 private Task GetFavoritesAsync()
2453 return this.GetFavoritesAsync(loadMore: false);
2456 private async Task GetFavoritesAsync(bool loadMore)
2458 await this.workerSemaphore.WaitAsync();
2462 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2464 await this.GetFavoritesAsyncInternal(progress, this.workerCts.Token, loadMore);
2466 catch (WebApiException ex)
2468 this._myStatusError = true;
2469 this.StatusLabel.Text = ex.Message;
2473 this.workerSemaphore.Release();
2477 private async Task GetFavoritesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2479 if (ct.IsCancellationRequested)
2482 if (!CheckAccountValid())
2483 throw new WebApiException("Auth error. Check your account");
2486 if (!this._cfgCommon.UnreadManage)
2489 read = this._initial && this._cfgCommon.Read;
2491 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19);
2493 await Task.Run(async () =>
2495 await this.tw.GetFavoritesApi(read, loadMore)
2496 .ConfigureAwait(false);
2498 this._statuses.DistributePosts();
2501 if (ct.IsCancellationRequested)
2504 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20);
2506 this.RefreshTimeline();
2509 private Task GetPublicSearchAllAsync()
2511 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch);
2513 return this.GetPublicSearchAsync(tabs, loadMore: false);
2516 private Task GetPublicSearchAsync(TabClass tab)
2518 return this.GetPublicSearchAsync(tab, loadMore: false);
2521 private Task GetPublicSearchAsync(TabClass tab, bool loadMore)
2523 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2526 private async Task GetPublicSearchAsync(IEnumerable<TabClass> tabs, bool loadMore)
2528 await this.workerSemaphore.WaitAsync();
2532 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2534 await this.GetPublicSearchAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2536 catch (WebApiException ex)
2538 this._myStatusError = true;
2539 this.StatusLabel.Text = ex.Message;
2543 this.workerSemaphore.Release();
2547 private async Task GetPublicSearchAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2549 if (ct.IsCancellationRequested)
2552 if (!CheckAccountValid())
2553 throw new WebApiException("Auth error. Check your account");
2556 if (!this._cfgCommon.UnreadManage)
2559 read = this._initial && this._cfgCommon.Read;
2561 p.Report("Search refreshing...");
2563 await Task.Run(async () =>
2565 WebApiException lastException = null;
2567 foreach (var tab in tabs)
2571 if (string.IsNullOrEmpty(tab.SearchWords))
2574 await this.tw.GetSearch(read, tab, false)
2575 .ConfigureAwait(false);
2578 await this.tw.GetSearch(read, tab, true)
2579 .ConfigureAwait(false);
2581 catch (WebApiException ex)
2587 this._statuses.DistributePosts();
2589 if (lastException != null)
2590 throw new WebApiException(lastException.Message, lastException);
2593 if (ct.IsCancellationRequested)
2596 p.Report("Search refreshed");
2598 this.RefreshTimeline();
2601 private Task GetUserTimelineAllAsync()
2603 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline);
2605 return this.GetUserTimelineAsync(tabs, loadMore: false);
2608 private Task GetUserTimelineAsync(TabClass tab)
2610 return this.GetUserTimelineAsync(tab, loadMore: false);
2613 private Task GetUserTimelineAsync(TabClass tab, bool loadMore)
2615 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2618 private async Task GetUserTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2620 await this.workerSemaphore.WaitAsync();
2624 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2626 await this.GetUserTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2628 catch (WebApiException ex)
2630 this._myStatusError = true;
2631 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2635 this.workerSemaphore.Release();
2639 private async Task GetUserTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2641 if (ct.IsCancellationRequested)
2644 if (!CheckAccountValid())
2645 throw new WebApiException("Auth error. Check your account");
2648 if (!this._cfgCommon.UnreadManage)
2651 read = this._initial && this._cfgCommon.Read;
2653 p.Report("UserTimeline refreshing...");
2655 await Task.Run(async () =>
2657 WebApiException lastException = null;
2659 foreach (var tab in tabs)
2663 if (string.IsNullOrEmpty(tab.User))
2666 await this.tw.GetUserTimelineApi(read, tab.User, tab, loadMore)
2667 .ConfigureAwait(false);
2669 catch (WebApiException ex)
2675 this._statuses.DistributePosts();
2677 if (lastException != null)
2678 throw new WebApiException(lastException.Message, lastException);
2681 if (ct.IsCancellationRequested)
2684 p.Report("UserTimeline refreshed");
2686 this.RefreshTimeline();
2689 private Task GetListTimelineAllAsync()
2691 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.Lists);
2693 return this.GetListTimelineAsync(tabs, loadMore: false);
2696 private Task GetListTimelineAsync(TabClass tab)
2698 return this.GetListTimelineAsync(tab, loadMore: false);
2701 private Task GetListTimelineAsync(TabClass tab, bool loadMore)
2703 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2706 private async Task GetListTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2708 await this.workerSemaphore.WaitAsync();
2712 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2714 await this.GetListTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2716 catch (WebApiException ex)
2718 this._myStatusError = true;
2719 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2723 this.workerSemaphore.Release();
2727 private async Task GetListTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2729 if (ct.IsCancellationRequested)
2732 if (!CheckAccountValid())
2733 throw new WebApiException("Auth error. Check your account");
2736 if (!this._cfgCommon.UnreadManage)
2739 read = this._initial && this._cfgCommon.Read;
2741 p.Report("List refreshing...");
2743 await Task.Run(async () =>
2745 WebApiException lastException = null;
2747 foreach (var tab in tabs)
2751 if (tab.ListInfo == null || tab.ListInfo.Id == 0)
2754 await this.tw.GetListStatus(read, tab, loadMore, this._initial)
2755 .ConfigureAwait(false);
2757 catch (WebApiException ex)
2763 this._statuses.DistributePosts();
2765 if (lastException != null)
2766 throw new WebApiException(lastException.Message, lastException);
2769 if (ct.IsCancellationRequested)
2772 p.Report("List refreshed");
2774 this.RefreshTimeline();
2777 private async Task GetRelatedTweetsAsync(TabClass tab)
2779 await this.workerSemaphore.WaitAsync();
2783 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2785 await this.GetRelatedTweetsAsyncInternal(progress, this.workerCts.Token, tab);
2787 catch (WebApiException ex)
2789 this._myStatusError = true;
2790 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2794 this.workerSemaphore.Release();
2798 private async Task GetRelatedTweetsAsyncInternal(IProgress<string> p, CancellationToken ct, TabClass tab)
2800 if (ct.IsCancellationRequested)
2803 if (!CheckAccountValid())
2804 throw new WebApiException("Auth error. Check your account");
2807 if (!this._cfgCommon.UnreadManage)
2810 read = this._initial && this._cfgCommon.Read;
2812 p.Report("Related refreshing...");
2814 await Task.Run(async () =>
2816 await this.tw.GetRelatedResult(read, tab)
2817 .ConfigureAwait(false);
2819 this._statuses.DistributePosts();
2822 if (ct.IsCancellationRequested)
2825 p.Report("Related refreshed");
2827 this.RefreshTimeline();
2829 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
2830 .FirstOrDefault(x => x.Text == tab.TabName);
2832 if (tabPage != null)
2834 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
2836 var listView = (DetailsListView)tabPage.Tag;
2837 var index = tab.IndexOf(tab.RelationTargetPost.RetweetedId ?? tab.RelationTargetPost.StatusId);
2839 if (index != -1 && index < listView.Items.Count)
2841 listView.SelectedIndices.Add(index);
2842 listView.Items[index].Focused = true;
2847 private async Task FavAddAsync(long statusId, TabClass tab)
2849 await this.workerSemaphore.WaitAsync();
2853 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2855 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2857 catch (WebApiException ex)
2859 this._myStatusError = true;
2860 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2864 this.workerSemaphore.Release();
2868 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabClass tab)
2870 if (ct.IsCancellationRequested)
2873 if (!CheckAccountValid())
2874 throw new WebApiException("Auth error. Check your account");
2877 if (!tab.Posts.TryGetValue(statusId, out post))
2883 await Task.Run(async () =>
2885 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2889 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2891 .ConfigureAwait(false);
2893 if (this._cfgCommon.RestrictFavCheck)
2895 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2896 .ConfigureAwait(false);
2898 if (status.Favorited != true)
2899 throw new WebApiException("NG(Restricted?)");
2902 this._favTimestamps.Add(DateTime.Now);
2905 if (this._statuses.ContainsKey(statusId))
2907 var postTl = this._statuses[statusId];
2908 postTl.IsFav = true;
2910 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2911 favTab.AddPostQueue(statusId, postTl.IsRead);
2914 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2915 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2917 if (tb.Contains(statusId))
2918 tb.Posts[statusId].IsFav = true;
2921 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2923 catch (WebApiException)
2925 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2930 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2931 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2933 if (this._favTimestamps[i] < oneHour)
2934 this._favTimestamps.RemoveAt(i);
2937 this._statuses.DistributePosts();
2940 if (ct.IsCancellationRequested)
2943 this.RefreshTimeline();
2945 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2947 using (ControlTransaction.Update(this._curList))
2949 var idx = tab.IndexOf(statusId);
2951 this.ChangeCacheStyleRead(post.IsRead, idx);
2954 if (statusId == this._curPost.StatusId)
2955 await this.DispSelectedPost(true); // 選択アイテム再表示
2959 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabClass tab)
2961 await this.workerSemaphore.WaitAsync();
2965 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2967 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2969 catch (WebApiException ex)
2971 this._myStatusError = true;
2972 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2976 this.workerSemaphore.Release();
2980 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2982 if (ct.IsCancellationRequested)
2985 if (!CheckAccountValid())
2986 throw new WebApiException("Auth error. Check your account");
2988 var successIds = new List<long>();
2990 await Task.Run(async () =>
2994 var failedCount = 0;
2995 foreach (var statusId in statusIds)
2999 var post = tab.Posts[statusId];
3001 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
3008 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
3010 .ConfigureAwait(false);
3012 catch (WebApiException)
3018 successIds.Add(statusId);
3019 post.IsFav = false; // リスト再描画必要
3021 if (this._statuses.ContainsKey(statusId))
3023 this._statuses[statusId].IsFav = false;
3026 // 検索,リスト,UserTimeline,Relatedの各タブに反映
3027 foreach (var tb in this._statuses.GetTabsInnerStorageType())
3029 if (tb.Contains(statusId))
3030 tb.Posts[statusId].IsFav = false;
3035 if (ct.IsCancellationRequested)
3038 this.RemovePostFromFavTab(successIds.ToArray());
3040 this.RefreshTimeline();
3042 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
3044 if (tab.TabType == MyCommon.TabUsageType.Favorites)
3050 using (ControlTransaction.Update(this._curList))
3052 foreach (var statusId in successIds)
3054 var idx = tab.IndexOf(statusId);
3058 var post = tab.Posts[statusId];
3059 this.ChangeCacheStyleRead(post.IsRead, idx);
3063 if (successIds.Contains(this._curPost.StatusId))
3064 await this.DispSelectedPost(true); // 選択アイテム再表示
3069 private async Task PostMessageAsync(PostingStatus status)
3071 await this.workerSemaphore.WaitAsync();
3075 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3077 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
3079 catch (WebApiException ex)
3081 this._myStatusError = true;
3082 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
3086 this.workerSemaphore.Release();
3090 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
3092 if (ct.IsCancellationRequested)
3095 if (!CheckAccountValid())
3096 throw new WebApiException("Auth error. Check your account");
3098 p.Report("Posting...");
3104 await Task.Run(async () =>
3106 if (status.mediaItems == null || status.mediaItems.Length == 0)
3108 await this.tw.PostStatus(status.status, status.inReplyToId)
3109 .ConfigureAwait(false);
3113 var service = ImageSelector.GetService(status.imageService);
3114 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
3115 .ConfigureAwait(false);
3119 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3121 catch (WebApiException ex)
3123 // 処理は中断せずエラーの表示のみ行う
3124 errMsg = $"Err:{ex.Message}(PostMessage)";
3126 this._myStatusError = true;
3130 // 使い終わった MediaItem は破棄する
3131 if (status.mediaItems != null)
3133 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
3135 disposableItem.Dispose();
3140 if (ct.IsCancellationRequested)
3143 if (!string.IsNullOrEmpty(errMsg) &&
3144 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
3145 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
3147 var ret = MessageBox.Show(
3149 "{0} ---> [ " + errMsg + " ]" + Environment.NewLine +
3150 "\"" + status.status + "\"" + Environment.NewLine +
3152 Properties.Resources.StatusUpdateFailed1,
3153 Properties.Resources.StatusUpdateFailed2),
3154 "Failed to update status",
3155 MessageBoxButtons.RetryCancel,
3156 MessageBoxIcon.Question);
3158 if (ret == DialogResult.Retry)
3160 await this.PostMessageAsync(status);
3164 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3165 if (this.ToolStripFocusLockMenuItem.Checked)
3166 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
3171 this._postTimestamps.Add(DateTime.Now);
3173 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3174 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3176 if (this._postTimestamps[i] < oneHour)
3177 this._postTimestamps.RemoveAt(i);
3180 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
3182 this.HashMgr.ClearHashtag();
3183 this.HashStripSplitButton.Text = "#[-]";
3184 this.HashToggleMenuItem.Checked = false;
3185 this.HashToggleToolStripMenuItem.Checked = false;
3188 this.SetMainWindowTitle();
3190 if (this._cfgCommon.PostAndGet)
3192 if (this.tw.UserStreamActive)
3193 this.RefreshTimeline();
3195 await this.GetHomeTimelineAsync();
3199 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
3201 await this.workerSemaphore.WaitAsync();
3205 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3207 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
3209 catch (WebApiException ex)
3211 this._myStatusError = true;
3212 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
3216 this.workerSemaphore.Release();
3220 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
3222 if (ct.IsCancellationRequested)
3225 if (!CheckAccountValid())
3226 throw new WebApiException("Auth error. Check your account");
3229 if (!this._cfgCommon.UnreadManage)
3232 read = this._initial && this._cfgCommon.Read;
3234 p.Report("Posting...");
3236 var retweetTasks = from statusId in statusIds
3237 select this.tw.PostRetweet(statusId, read);
3239 await Task.WhenAll(retweetTasks)
3240 .ConfigureAwait(false);
3242 if (ct.IsCancellationRequested)
3245 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3247 this._postTimestamps.Add(DateTime.Now);
3249 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3250 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3252 if (this._postTimestamps[i] < oneHour)
3253 this._postTimestamps.RemoveAt(i);
3256 if (this._cfgCommon.PostAndGet && !this.tw.UserStreamActive)
3257 await this.GetHomeTimelineAsync();
3260 private async Task RefreshFollowerIdsAsync()
3262 await this.workerSemaphore.WaitAsync();
3265 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
3267 await this.tw.RefreshFollowerIds();
3269 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
3271 this.RefreshTimeline();
3272 this.PurgeListViewItemCache();
3273 this._curList?.Refresh();
3275 catch (WebApiException ex)
3277 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
3281 this.workerSemaphore.Release();
3285 private async Task RefreshNoRetweetIdsAsync()
3287 await this.workerSemaphore.WaitAsync();
3290 await this.tw.RefreshNoRetweetIds();
3292 this.StatusLabel.Text = "NoRetweetIds refreshed";
3294 catch (WebApiException ex)
3296 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
3300 this.workerSemaphore.Release();
3304 private async Task RefreshBlockIdsAsync()
3306 await this.workerSemaphore.WaitAsync();
3309 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
3311 await this.tw.RefreshBlockIds();
3313 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
3315 catch (WebApiException ex)
3317 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
3321 this.workerSemaphore.Release();
3325 private async Task RefreshTwitterConfigurationAsync()
3327 await this.workerSemaphore.WaitAsync();
3330 await this.tw.RefreshConfiguration();
3332 if (this.tw.Configuration.PhotoSizeLimit != 0)
3334 foreach (var service in this.ImageSelector.GetServices())
3336 service.UpdateTwitterConfiguration(this.tw.Configuration);
3340 this.PurgeListViewItemCache();
3342 this._curList?.Refresh();
3344 catch (WebApiException ex)
3346 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
3350 this.workerSemaphore.Release();
3354 private async Task RefreshMuteUserIdsAsync()
3356 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3360 await tw.RefreshMuteUserIdsAsync();
3362 catch (WebApiException ex)
3364 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3368 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3371 private void RemovePostFromFavTab(Int64[] ids)
3373 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
3374 string favTabName = favTab.TabName;
3376 if (_curTab.Text.Equals(favTabName))
3378 fidx = _curList.FocusedItem?.Index ?? _curList.TopItem?.Index ?? 0;
3381 foreach (long i in ids)
3385 _statuses.RemoveFavPost(i);
3392 if (_curTab != null && _curTab.Text.Equals(favTabName))
3394 this.PurgeListViewItemCache();
3396 //_curItemIndex = -1;
3398 foreach (TabPage tp in ListTab.TabPages)
3400 if (tp.Text == favTabName)
3402 ((DetailsListView)tp.Tag).VirtualListSize = favTab.AllCount;
3406 if (_curTab.Text.Equals(favTabName))
3410 _curList.SelectedIndices.Clear();
3412 while (_curList.SelectedIndices.Count > 0);
3414 if (favTab.AllCount > 0)
3416 if (favTab.AllCount - 1 > fidx && fidx > -1)
3418 _curList.SelectedIndices.Add(fidx);
3422 _curList.SelectedIndices.Add(favTab.AllCount - 1);
3424 if (_curList.SelectedIndices.Count > 0)
3426 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3427 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3433 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3435 if (e.Button == MouseButtons.Left)
3437 this.Visible = true;
3438 if (this.WindowState == FormWindowState.Minimized)
3440 this.WindowState = _formWindowState;
3443 this.BringToFront();
3447 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3449 switch (this._cfgCommon.ListDoubleClickAction)
3452 MakeReplyOrDirectStatus();
3455 await this.FavoriteChange(true);
3458 if (_curPost != null)
3459 await this.ShowUserStatus(_curPost.ScreenName, false);
3465 ShowRelatedStatusesMenuItem_Click(null, null);
3468 MoveToHomeToolStripMenuItem_Click(null, null);
3471 StatusOpenMenuItem_Click(null, null);
3479 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3481 await this.FavoriteChange(true);
3484 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3486 await this.FavoriteChange(false);
3490 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3492 await this.FavoritesRetweetOfficial();
3495 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3497 await this.FavoritesRetweetUnofficial();
3500 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3503 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3506 //trueでFavAdd,falseでFavRemove
3507 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3508 || !this.ExistCurrentPost) return;
3510 if (this._curList.SelectedIndices.Count > 1)
3515 // https://support.twitter.com/articles/76915#favoriting
3516 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3517 _DoFavRetweetFlags = false;
3522 if (multiFavoriteChangeDialogEnable)
3524 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3525 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3526 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3528 if (confirm == DialogResult.Cancel)
3536 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3537 if (selectedPost.IsFav)
3539 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3543 await this.FavAddAsync(selectedPost.StatusId, tab);
3547 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3548 .Select(x => this.GetCurTabPost(x))
3549 .Where(x => x.IsFav);
3551 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3552 if (statusIds.Length == 0)
3554 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3558 await this.FavRemoveAsync(statusIds, tab);
3562 private PostClass GetCurTabPost(int Index)
3564 var listCache = this._listItemCache;
3565 if (listCache != null)
3569 if (listCache.TryGetValue(Index, out item, out post))
3573 return _statuses.Tabs[_curTab.Text][Index];
3576 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3578 if (_curList.SelectedIndices.Count > 0)
3579 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3580 else if (_curList.SelectedIndices.Count == 0)
3581 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3584 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3586 if (_curList.SelectedIndices.Count > 0)
3587 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3590 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3592 if ((!_initialLayout) && this.Visible)
3594 if (this.WindowState == FormWindowState.Normal)
3596 _mySize = this.ClientSize;
3597 _mySpDis = this.SplitContainer1.SplitterDistance;
3598 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3599 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3600 ModifySettingLocal = true;
3605 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3607 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3608 if (comparerMode == null)
3611 this.SetSortColumn(comparerMode.Value);
3615 /// 列インデックスからソートを行う ComparerMode を求める
3617 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3618 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3619 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3622 return ComparerMode.Id;
3624 switch (columnIndex)
3627 return ComparerMode.Nickname;
3629 return ComparerMode.Data;
3631 return ComparerMode.Id;
3633 return ComparerMode.Name;
3635 return ComparerMode.Source;
3637 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3643 /// 発言一覧の指定した位置の列でソートする
3645 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3646 private void SetSortColumnByDisplayIndex(int columnIndex)
3648 // 表示上の列の位置から ColumnHeader を求める
3649 var col = this._curList.Columns.Cast<ColumnHeader>()
3650 .Where(x => x.DisplayIndex == columnIndex)
3656 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3657 if (comparerMode == null)
3660 this.SetSortColumn(comparerMode.Value);
3664 /// 発言一覧の最後列の項目でソートする
3666 private void SetSortLastColumn()
3668 // 表示上の最後列にある ColumnHeader を求める
3669 var col = this._curList.Columns.Cast<ColumnHeader>()
3670 .OrderByDescending(x => x.DisplayIndex)
3673 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3674 if (comparerMode == null)
3677 this.SetSortColumn(comparerMode.Value);
3681 /// 発言一覧を指定された ComparerMode に基づいてソートする
3683 private void SetSortColumn(ComparerMode sortColumn)
3685 if (this._cfgCommon.SortOrderLock)
3688 this._statuses.ToggleSortOrder(sortColumn);
3689 this.InitColumnText();
3691 var list = this._curList;
3694 list.Columns[0].Text = this.ColumnText[0];
3695 list.Columns[1].Text = this.ColumnText[2];
3699 for (var i = 0; i <= 7; i++)
3701 list.Columns[i].Text = this.ColumnText[i];
3705 this.PurgeListViewItemCache();
3707 var tab = this._statuses.Tabs[this._curTab.Text];
3708 if (tab.AllCount > 0 && this._curPost != null)
3710 var idx = tab.IndexOf(this._curPost.StatusId);
3713 this.SelectListItem(list, idx);
3714 list.EnsureVisible(idx);
3719 this.ModifySettingCommon = true;
3722 private void TweenMain_LocationChanged(object sender, EventArgs e)
3724 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3726 _myLoc = this.DesktopLocation;
3727 ModifySettingLocal = true;
3731 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3733 if (ListTab.SelectedTab == null) return;
3734 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3735 if (!this.ExistCurrentPost)
3737 ReplyStripMenuItem.Enabled = false;
3738 ReplyAllStripMenuItem.Enabled = false;
3739 DMStripMenuItem.Enabled = false;
3740 ShowProfileMenuItem.Enabled = false;
3741 ShowUserTimelineContextMenuItem.Enabled = false;
3742 ListManageUserContextToolStripMenuItem2.Enabled = false;
3743 MoveToFavToolStripMenuItem.Enabled = false;
3744 TabMenuItem.Enabled = false;
3745 IDRuleMenuItem.Enabled = false;
3746 SourceRuleMenuItem.Enabled = false;
3747 ReadedStripMenuItem.Enabled = false;
3748 UnreadStripMenuItem.Enabled = false;
3752 ShowProfileMenuItem.Enabled = true;
3753 ListManageUserContextToolStripMenuItem2.Enabled = true;
3754 ReplyStripMenuItem.Enabled = true;
3755 ReplyAllStripMenuItem.Enabled = true;
3756 DMStripMenuItem.Enabled = true;
3757 ShowUserTimelineContextMenuItem.Enabled = true;
3758 MoveToFavToolStripMenuItem.Enabled = true;
3759 TabMenuItem.Enabled = true;
3760 IDRuleMenuItem.Enabled = true;
3761 SourceRuleMenuItem.Enabled = true;
3762 ReadedStripMenuItem.Enabled = true;
3763 UnreadStripMenuItem.Enabled = true;
3765 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3767 FavAddToolStripMenuItem.Enabled = false;
3768 FavRemoveToolStripMenuItem.Enabled = false;
3769 StatusOpenMenuItem.Enabled = false;
3770 FavorareMenuItem.Enabled = false;
3771 ShowRelatedStatusesMenuItem.Enabled = false;
3773 ReTweetStripMenuItem.Enabled = false;
3774 ReTweetUnofficialStripMenuItem.Enabled = false;
3775 QuoteStripMenuItem.Enabled = false;
3776 FavoriteRetweetContextMenu.Enabled = false;
3777 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3781 FavAddToolStripMenuItem.Enabled = true;
3782 FavRemoveToolStripMenuItem.Enabled = true;
3783 StatusOpenMenuItem.Enabled = true;
3784 FavorareMenuItem.Enabled = true;
3785 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3789 ReTweetStripMenuItem.Enabled = false; //公式RTは無効に
3790 ReTweetUnofficialStripMenuItem.Enabled = true;
3791 QuoteStripMenuItem.Enabled = true;
3792 FavoriteRetweetContextMenu.Enabled = false; //公式RTは無効に
3793 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3797 if (_curPost.IsProtect)
3799 ReTweetStripMenuItem.Enabled = false;
3800 ReTweetUnofficialStripMenuItem.Enabled = false;
3801 QuoteStripMenuItem.Enabled = false;
3802 FavoriteRetweetContextMenu.Enabled = false;
3803 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3807 ReTweetStripMenuItem.Enabled = true;
3808 ReTweetUnofficialStripMenuItem.Enabled = true;
3809 QuoteStripMenuItem.Enabled = true;
3810 FavoriteRetweetContextMenu.Enabled = true;
3811 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3815 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3817 // RefreshMoreStripMenuItem.Enabled = true;
3821 // RefreshMoreStripMenuItem.Enabled = false;
3823 if (!this.ExistCurrentPost
3824 || _curPost.InReplyToStatusId == null)
3826 RepliedStatusOpenMenuItem.Enabled = false;
3830 RepliedStatusOpenMenuItem.Enabled = true;
3832 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3834 MoveToRTHomeMenuItem.Enabled = false;
3838 MoveToRTHomeMenuItem.Enabled = true;
3841 if (this.ExistCurrentPost)
3843 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3844 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3845 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3847 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3851 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3853 MakeReplyOrDirectStatus(false, true);
3856 private void DMStripMenuItem_Click(object sender, EventArgs e)
3858 MakeReplyOrDirectStatus(false, false);
3861 private async Task doStatusDelete()
3863 if (this._curTab == null || this._curList == null)
3866 if (this._curList.SelectedIndices.Count == 0)
3869 var posts = this._curList.SelectedIndices.Cast<int>()
3870 .Select(x => this.GetCurTabPost(x))
3873 // 選択されたツイートの中に削除可能なものが一つでもあるか
3874 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3877 var ret = MessageBox.Show(this,
3878 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3879 Properties.Resources.DeleteStripMenuItem_ClickText2,
3880 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3882 if (ret != DialogResult.OK)
3885 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3887 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3889 Exception lastException = null;
3890 foreach (var post in posts)
3892 if (!post.CanDeleteBy(this.tw.UserId))
3899 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3904 if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3905 // 他人に RT された自分のツイート
3906 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3909 // 自分のツイート or 自分が RT したツイート
3910 await this.twitterApi.StatusesDestroy(post.StatusId)
3914 catch (WebApiException ex)
3920 this._statuses.RemovePost(post.StatusId);
3923 if (lastException == null)
3924 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3926 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3928 this.PurgeListViewItemCache();
3929 this._curPost = null;
3930 this._curItemIndex = -1;
3932 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3934 var listView = (DetailsListView)tabPage.Tag;
3935 var tab = this._statuses.Tabs[tabPage.Text];
3937 using (ControlTransaction.Update(listView))
3939 listView.VirtualListSize = tab.AllCount;
3941 if (tabPage == this._curTab)
3943 listView.SelectedIndices.Clear();
3945 if (tab.AllCount != 0)
3948 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3949 selectedIndex = focusedIndex;
3951 selectedIndex = tab.AllCount - 1;
3953 listView.SelectedIndices.Add(selectedIndex);
3954 listView.EnsureVisible(selectedIndex);
3955 listView.FocusedItem = listView.Items[selectedIndex];
3960 if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3962 if (tabPage.ImageIndex == 0)
3963 tabPage.ImageIndex = -1; // タブアイコン
3967 if (!this._cfgCommon.TabIconDisp)
3968 this.ListTab.Refresh();
3972 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3974 await this.doStatusDelete();
3977 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3979 using (ControlTransaction.Update(this._curList))
3981 foreach (int idx in _curList.SelectedIndices)
3983 var post = this._statuses.Tabs[this._curTab.Text][idx];
3984 this._statuses.SetReadAllTab(post.StatusId, read: true);
3985 ChangeCacheStyleRead(true, idx);
3989 foreach (TabPage tb in ListTab.TabPages)
3991 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3993 if (this._cfgCommon.TabIconDisp)
3995 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3999 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
4002 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
4004 using (ControlTransaction.Update(this._curList))
4006 foreach (int idx in _curList.SelectedIndices)
4008 var post = this._statuses.Tabs[this._curTab.Text][idx];
4009 this._statuses.SetReadAllTab(post.StatusId, read: false);
4010 ChangeCacheStyleRead(false, idx);
4014 foreach (TabPage tb in ListTab.TabPages)
4016 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
4018 if (this._cfgCommon.TabIconDisp)
4020 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
4024 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
4027 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
4029 await this.DoRefresh();
4032 private async Task DoRefresh()
4034 if (_curTab != null)
4037 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4040 switch (_statuses.Tabs[_curTab.Text].TabType)
4042 case MyCommon.TabUsageType.Mentions:
4043 await this.GetReplyAsync();
4045 case MyCommon.TabUsageType.DirectMessage:
4046 await this.GetDirectMessagesAsync();
4048 case MyCommon.TabUsageType.Favorites:
4049 await this.GetFavoritesAsync();
4051 //case MyCommon.TabUsageType.Profile:
4053 case MyCommon.TabUsageType.PublicSearch:
4055 if (string.IsNullOrEmpty(tab.SearchWords)) return;
4056 await this.GetPublicSearchAsync(tab);
4058 case MyCommon.TabUsageType.UserTimeline:
4059 await this.GetUserTimelineAsync(tab);
4061 case MyCommon.TabUsageType.Lists:
4063 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4064 await this.GetListTimelineAsync(tab);
4067 await this.GetHomeTimelineAsync();
4073 await this.GetHomeTimelineAsync();
4077 private async Task DoRefreshMore()
4080 if (_curTab != null)
4083 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4086 switch (_statuses.Tabs[_curTab.Text].TabType)
4088 case MyCommon.TabUsageType.Mentions:
4089 await this.GetReplyAsync(loadMore: true);
4091 case MyCommon.TabUsageType.DirectMessage:
4092 await this.GetDirectMessagesAsync(loadMore: true);
4094 case MyCommon.TabUsageType.Favorites:
4095 await this.GetFavoritesAsync(loadMore: true);
4097 case MyCommon.TabUsageType.Profile:
4100 case MyCommon.TabUsageType.PublicSearch:
4102 if (string.IsNullOrEmpty(tab.SearchWords)) return;
4103 await this.GetPublicSearchAsync(tab, loadMore: true);
4105 case MyCommon.TabUsageType.UserTimeline:
4106 await this.GetUserTimelineAsync(tab, loadMore: true);
4108 case MyCommon.TabUsageType.Lists:
4110 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4111 await this.GetListTimelineAsync(tab, loadMore: true);
4114 await this.GetHomeTimelineAsync(loadMore: true);
4120 await this.GetHomeTimelineAsync(loadMore: true);
4124 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
4126 DialogResult result = DialogResult.Abort;
4128 using (var settingDialog = new AppendSettingDialog())
4130 settingDialog.Icon = this.MainIcon;
4131 settingDialog.Owner = this;
4132 settingDialog.ShowInTaskbar = showTaskbarIcon;
4133 settingDialog.IntervalChanged += this.TimerInterval_Changed;
4135 settingDialog.tw = this.tw;
4136 settingDialog.twitterApi = this.twitterApi;
4138 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
4142 result = settingDialog.ShowDialog(this);
4146 return DialogResult.Abort;
4149 if (result == DialogResult.OK)
4153 settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
4161 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
4164 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
4166 var oldIconSz = this._cfgCommon.IconSize;
4168 if (ShowSettingDialog() == DialogResult.OK)
4172 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
4173 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
4174 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
4175 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
4176 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
4177 TwitterApiConnection.RestApiBase = new Uri(this._cfgCommon.TwitterUrl);
4179 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
4180 Networking.SetWebProxy(this._cfgLocal.ProxyType,
4181 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
4182 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
4183 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
4185 ImageSelector.Reset(tw, this.tw.Configuration);
4189 if (this._cfgCommon.TabIconDisp)
4191 ListTab.DrawItem -= ListTab_DrawItem;
4192 ListTab.DrawMode = TabDrawMode.Normal;
4193 ListTab.ImageList = this.TabImage;
4197 ListTab.DrawItem -= ListTab_DrawItem;
4198 ListTab.DrawItem += ListTab_DrawItem;
4199 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
4200 ListTab.ImageList = null;
4203 catch (Exception ex)
4205 ex.Data["Instance"] = "ListTab(TabIconDisp)";
4206 ex.Data["IsTerminatePermission"] = false;
4212 if (!this._cfgCommon.UnreadManage)
4214 ReadedStripMenuItem.Enabled = false;
4215 UnreadStripMenuItem.Enabled = false;
4216 if (this._cfgCommon.TabIconDisp)
4218 foreach (TabPage myTab in ListTab.TabPages)
4220 myTab.ImageIndex = -1;
4226 ReadedStripMenuItem.Enabled = true;
4227 UnreadStripMenuItem.Enabled = true;
4230 catch (Exception ex)
4232 ex.Data["Instance"] = "ListTab(UnreadManage)";
4233 ex.Data["IsTerminatePermission"] = false;
4240 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
4242 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
4243 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
4244 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
4246 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
4247 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
4248 _fntUnread = this._cfgLocal.FontUnread;
4249 _clUnread = this._cfgLocal.ColorUnread;
4250 _fntReaded = this._cfgLocal.FontRead;
4251 _clReaded = this._cfgLocal.ColorRead;
4252 _clFav = this._cfgLocal.ColorFav;
4253 _clOWL = this._cfgLocal.ColorOWL;
4254 _clRetweet = this._cfgLocal.ColorRetweet;
4255 _fntDetail = this._cfgLocal.FontDetail;
4256 _clDetail = this._cfgLocal.ColorDetail;
4257 _clDetailLink = this._cfgLocal.ColorDetailLink;
4258 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
4259 _clSelf = this._cfgLocal.ColorSelf;
4260 _clAtSelf = this._cfgLocal.ColorAtSelf;
4261 _clTarget = this._cfgLocal.ColorTarget;
4262 _clAtTarget = this._cfgLocal.ColorAtTarget;
4263 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
4264 _clAtTo = this._cfgLocal.ColorAtTo;
4265 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
4266 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
4267 _clInputFont = this._cfgLocal.ColorInputFont;
4268 _fntInputFont = this._cfgLocal.FontInputFont;
4269 _brsBackColorMine.Dispose();
4270 _brsBackColorAt.Dispose();
4271 _brsBackColorYou.Dispose();
4272 _brsBackColorAtYou.Dispose();
4273 _brsBackColorAtFromTarget.Dispose();
4274 _brsBackColorAtTo.Dispose();
4275 _brsBackColorNone.Dispose();
4276 _brsBackColorMine = new SolidBrush(_clSelf);
4277 _brsBackColorAt = new SolidBrush(_clAtSelf);
4278 _brsBackColorYou = new SolidBrush(_clTarget);
4279 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4280 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4281 _brsBackColorAtTo = new SolidBrush(_clAtTo);
4282 _brsBackColorNone = new SolidBrush(_clListBackcolor);
4286 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4287 StatusText.Font = _fntInputFont;
4288 StatusText.ForeColor = _clInputFont;
4290 catch (Exception ex)
4292 MessageBox.Show(ex.Message);
4297 InitDetailHtmlFormat();
4299 catch (Exception ex)
4301 ex.Data["Instance"] = "Font";
4302 ex.Data["IsTerminatePermission"] = false;
4308 foreach (TabPage tb in ListTab.TabPages)
4310 if (this._cfgCommon.TabIconDisp)
4312 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4319 catch (Exception ex)
4321 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4322 ex.Data["IsTerminatePermission"] = false;
4328 var oldIconCol = _iconCol;
4330 if (this._cfgCommon.IconSize != oldIconSz)
4331 ApplyListViewIconSize(this._cfgCommon.IconSize);
4333 foreach (TabPage tp in ListTab.TabPages)
4335 DetailsListView lst = (DetailsListView)tp.Tag;
4337 using (ControlTransaction.Update(lst))
4339 lst.GridLines = this._cfgCommon.ShowGrid;
4340 lst.Font = _fntReaded;
4341 lst.BackColor = _clListBackcolor;
4343 if (_iconCol != oldIconCol)
4348 catch (Exception ex)
4350 ex.Data["Instance"] = "ListView(IconSize)";
4351 ex.Data["IsTerminatePermission"] = false;
4355 SetMainWindowTitle();
4356 SetNotifyIconText();
4358 this.PurgeListViewItemCache();
4359 _curList?.Refresh();
4362 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4363 if (this._cfgCommon.HotkeyEnabled)
4365 ///グローバルホットキーの登録。設定で変更可能にするかも
4366 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4367 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4368 modKey |= HookGlobalHotkey.ModKeys.Alt;
4369 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4370 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4371 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4372 modKey |= HookGlobalHotkey.ModKeys.Shift;
4373 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4374 modKey |= HookGlobalHotkey.ModKeys.Win;
4376 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4379 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4382 StatusText_TextChanged(null, null);
4391 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
4392 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
4395 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4397 this.TopMost = this._cfgCommon.AlwaysTop;
4398 SaveConfigsAll(false);
4400 if (tw.Username != oldUser.Username)
4401 await this.doGetFollowersMenu();
4407 private void SetTabAlignment()
4409 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4410 if (ListTab.Alignment == newAlignment) return;
4412 // 各タブのリスト上の選択位置などを退避
4413 var listSelections = this.SaveListViewSelection();
4415 ListTab.Alignment = newAlignment;
4417 foreach (TabPage tab in ListTab.TabPages)
4419 DetailsListView lst = (DetailsListView)tab.Tag;
4420 TabClass tabInfo = _statuses.Tabs[tab.Text];
4421 using (ControlTransaction.Update(lst))
4424 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4429 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4435 case MyCommon.IconSizes.IconNone:
4438 case MyCommon.IconSizes.Icon16:
4441 case MyCommon.IconSizes.Icon24:
4444 case MyCommon.IconSizes.Icon48:
4447 case MyCommon.IconSizes.Icon48_2:
4455 // ディスプレイの DPI 設定を考慮したサイズを設定する
4456 _listViewImageList.ImageSize = new Size(
4458 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4462 _listViewImageList.ImageSize = new Size(1, 1);
4466 private void ResetColumns(DetailsListView list)
4468 using (ControlTransaction.Update(list))
4469 using (ControlTransaction.Layout(list, false))
4472 list.ColumnClick -= MyList_ColumnClick;
4473 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4474 list.ColumnReordered -= MyList_ColumnReordered;
4475 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4477 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4478 list.Columns.Clear();
4479 cols.ForEach(col => col.Dispose());
4482 InitColumns(list, true);
4484 list.ColumnClick += MyList_ColumnClick;
4485 list.DrawColumnHeader += MyList_DrawColumnHeader;
4486 list.ColumnReordered += MyList_ColumnReordered;
4487 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4491 private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4493 if (e.Url.AbsoluteUri != "about:blank")
4495 await this.DispSelectedPost();
4496 await this.OpenUriInBrowserAsync(e.Url.OriginalString);
4500 private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4502 if (e.Url.Scheme == "data")
4504 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4506 else if (e.Url.AbsoluteUri != "about:blank")
4509 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
4510 await this.OpenUriAsync( e.Url, MyCommon.IsKeyDown( Keys.Control ) );
4514 public void AddNewTabForSearch(string searchWord)
4516 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4517 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4519 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4521 foreach (TabPage tp in ListTab.TabPages)
4523 if (tb.TabName == tp.Text)
4525 ListTab.SelectedTab = tp;
4532 string tabName = searchWord;
4533 for (int i = 0; i <= 100; i++)
4535 if (_statuses.ContainsTab(tabName))
4541 _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4542 AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4544 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4546 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4547 cmb.Items.Add(searchWord);
4548 cmb.Text = searchWord;
4551 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4554 private void ShowUserTimeline()
4556 if (!this.ExistCurrentPost) return;
4557 AddNewTabForUserTimeline(_curPost.ScreenName);
4560 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4562 if (e.KeyCode == Keys.Escape)
4564 TabPage relTp = ListTab.SelectedTab;
4565 RemoveSpecifiedTab(relTp.Text, false);
4567 e.SuppressKeyPress = true;
4571 public void AddNewTabForUserTimeline(string user)
4573 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4574 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4576 if (tb.User == user)
4578 foreach (TabPage tp in ListTab.TabPages)
4580 if (tb.TabName == tp.Text)
4582 ListTab.SelectedTab = tp;
4589 string tabName = "user:" + user;
4590 while (_statuses.ContainsTab(tabName))
4595 _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4596 var tab = this._statuses.Tabs[tabName];
4598 AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4600 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4603 this.GetUserTimelineAsync(tab);
4606 public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4609 foreach (TabPage tb in ListTab.TabPages)
4611 if (tb.Text == tabName) return false;
4615 if (tabName == Properties.Resources.AddNewTabText1) return false;
4620 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4621 tabType == MyCommon.TabUsageType.Favorites ||
4622 tabType == MyCommon.TabUsageType.Home ||
4623 tabType == MyCommon.TabUsageType.Mentions ||
4624 tabType == MyCommon.TabUsageType.Related)
4626 if (_statuses.GetTabByType(tabType) != null) return false;
4630 var _tabPage = new TabPage();
4631 var _listCustom = new DetailsListView();
4633 int cnt = ListTab.TabPages.Count;
4635 ///ToDo:Create and set controls follow tabtypes
4637 using (ControlTransaction.Update(_listCustom))
4638 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4639 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4640 using (ControlTransaction.Layout(this.SplitContainer1, false))
4641 using (ControlTransaction.Layout(this.ListTab, false))
4642 using (ControlTransaction.Layout(this))
4643 using (ControlTransaction.Layout(_tabPage, false))
4645 _tabPage.Controls.Add(_listCustom);
4648 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4650 var label = new Label();
4651 label.Dock = DockStyle.Top;
4652 label.Name = "labelUser";
4654 if (tabType == MyCommon.TabUsageType.Lists)
4656 label.Text = listInfo.ToString();
4660 label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4662 label.TextAlign = ContentAlignment.MiddleLeft;
4663 using (ComboBox tmpComboBox = new ComboBox())
4665 label.Height = tmpComboBox.Height;
4667 _tabPage.Controls.Add(label);
4670 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4672 var pnl = new Panel();
4674 var lbl = new Label();
4675 var cmb = new ComboBox();
4676 var btn = new Button();
4677 var cmbLang = new ComboBox();
4679 using (ControlTransaction.Layout(pnl, false))
4681 pnl.Controls.Add(cmb);
4682 pnl.Controls.Add(cmbLang);
4683 pnl.Controls.Add(btn);
4684 pnl.Controls.Add(lbl);
4685 pnl.Name = "panelSearch";
4687 pnl.Dock = DockStyle.Top;
4688 pnl.Height = cmb.Height;
4689 pnl.Enter += SearchControls_Enter;
4690 pnl.Leave += SearchControls_Leave;
4693 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4694 cmb.Dock = DockStyle.Fill;
4695 cmb.Name = "comboSearch";
4696 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4697 cmb.ImeMode = ImeMode.NoControl;
4698 cmb.TabStop = false;
4700 cmb.AutoCompleteMode = AutoCompleteMode.None;
4701 cmb.KeyDown += SearchComboBox_KeyDown;
4704 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4705 cmbLang.Dock = DockStyle.Right;
4707 cmbLang.Name = "comboLang";
4708 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4709 cmbLang.TabStop = false;
4710 cmbLang.TabIndex = 2;
4711 cmbLang.Items.Add("");
4712 cmbLang.Items.Add("ja");
4713 cmbLang.Items.Add("en");
4714 cmbLang.Items.Add("ar");
4715 cmbLang.Items.Add("da");
4716 cmbLang.Items.Add("nl");
4717 cmbLang.Items.Add("fa");
4718 cmbLang.Items.Add("fi");
4719 cmbLang.Items.Add("fr");
4720 cmbLang.Items.Add("de");
4721 cmbLang.Items.Add("hu");
4722 cmbLang.Items.Add("is");
4723 cmbLang.Items.Add("it");
4724 cmbLang.Items.Add("no");
4725 cmbLang.Items.Add("pl");
4726 cmbLang.Items.Add("pt");
4727 cmbLang.Items.Add("ru");
4728 cmbLang.Items.Add("es");
4729 cmbLang.Items.Add("sv");
4730 cmbLang.Items.Add("th");
4732 lbl.Text = "Search(C-S-f)";
4733 lbl.Name = "label1";
4734 lbl.Dock = DockStyle.Left;
4736 lbl.Height = cmb.Height;
4737 lbl.TextAlign = ContentAlignment.MiddleLeft;
4740 btn.Text = "Search";
4741 btn.Name = "buttonSearch";
4742 btn.UseVisualStyleBackColor = true;
4743 btn.Dock = DockStyle.Right;
4744 btn.TabStop = false;
4746 btn.Click += SearchButton_Click;
4749 if (_statuses.Tabs.TryGetValue(tabName, out tab))
4751 if (!string.IsNullOrEmpty(tab.SearchWords))
4753 cmb.Items.Add(tab.SearchWords);
4754 cmb.Text = tab.SearchWords;
4757 cmbLang.Text = tab.SearchLang;
4760 _tabPage.Controls.Add(pnl);
4764 _tabPage.Tag = _listCustom;
4765 this.ListTab.Controls.Add(_tabPage);
4767 _tabPage.Location = new Point(4, 4);
4768 _tabPage.Name = "CTab" + cnt.ToString();
4769 _tabPage.Size = new Size(380, 260);
4770 _tabPage.TabIndex = 2 + cnt;
4771 _tabPage.Text = tabName;
4772 _tabPage.UseVisualStyleBackColor = true;
4773 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4775 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4776 _listCustom.TabIndex = 1;
4777 _listCustom.AllowColumnReorder = true;
4778 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4779 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4780 _listCustom.Dock = DockStyle.Fill;
4781 _listCustom.FullRowSelect = true;
4782 _listCustom.HideSelection = false;
4783 _listCustom.Location = new Point(0, 0);
4784 _listCustom.Margin = new Padding(0);
4785 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4786 _listCustom.ShowItemToolTips = true;
4787 _listCustom.Size = new Size(380, 260);
4788 _listCustom.UseCompatibleStateImageBehavior = false;
4789 _listCustom.View = View.Details;
4790 _listCustom.OwnerDraw = true;
4791 _listCustom.VirtualMode = true;
4792 _listCustom.Font = _fntReaded;
4793 _listCustom.BackColor = _clListBackcolor;
4795 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4796 _listCustom.AllowDrop = true;
4798 _listCustom.SmallImageList = _listViewImageList;
4800 InitColumns(_listCustom, startup);
4802 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4803 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4804 _listCustom.ColumnClick += MyList_ColumnClick;
4805 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4806 _listCustom.DragDrop += TweenMain_DragDrop;
4807 _listCustom.DragEnter += TweenMain_DragEnter;
4808 _listCustom.DragOver += TweenMain_DragOver;
4809 _listCustom.DrawItem += MyList_DrawItem;
4810 _listCustom.MouseClick += MyList_MouseClick;
4811 _listCustom.ColumnReordered += MyList_ColumnReordered;
4812 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4813 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4814 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4815 _listCustom.DrawSubItem += MyList_DrawSubItem;
4816 _listCustom.HScrolled += MyList_HScrolled;
4822 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4824 var tabInfo = _statuses.GetTabByName(TabName);
4825 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4829 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4830 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4831 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4837 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4838 if (_tabPage == null) return false;
4840 SetListProperty(); //他のタブに列幅等を反映
4843 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4844 _tabPage.Tag = null;
4846 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4847 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4848 using (ControlTransaction.Layout(this.SplitContainer1, false))
4849 using (ControlTransaction.Layout(this.ListTab, false))
4850 using (ControlTransaction.Layout(this))
4851 using (ControlTransaction.Layout(_tabPage, false))
4853 if (this.ListTab.SelectedTab == _tabPage)
4855 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4856 this._beforeSelectedTab = null;
4858 this.ListTab.Controls.Remove(_tabPage);
4861 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4863 using (Control label = _tabPage.Controls["labelUser"])
4865 _tabPage.Controls.Remove(label);
4868 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4870 using (Control pnl = _tabPage.Controls["panelSearch"])
4872 pnl.Enter -= SearchControls_Enter;
4873 pnl.Leave -= SearchControls_Leave;
4874 _tabPage.Controls.Remove(pnl);
4876 foreach (Control ctrl in pnl.Controls)
4878 if (ctrl.Name == "buttonSearch")
4880 ctrl.Click -= SearchButton_Click;
4882 else if (ctrl.Name == "comboSearch")
4884 ctrl.KeyDown -= SearchComboBox_KeyDown;
4886 pnl.Controls.Remove(ctrl);
4892 _tabPage.Controls.Remove(_listCustom);
4894 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4895 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4896 _listCustom.ColumnClick -= MyList_ColumnClick;
4897 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4898 _listCustom.DragDrop -= TweenMain_DragDrop;
4899 _listCustom.DragEnter -= TweenMain_DragEnter;
4900 _listCustom.DragOver -= TweenMain_DragOver;
4901 _listCustom.DrawItem -= MyList_DrawItem;
4902 _listCustom.MouseClick -= MyList_MouseClick;
4903 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4904 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4905 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4906 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4907 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4908 _listCustom.HScrolled -= MyList_HScrolled;
4910 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4911 _listCustom.Columns.Clear();
4912 cols.ForEach(col => col.Dispose());
4915 _listCustom.ContextMenuStrip = null;
4916 _listCustom.ColumnHeaderContextMenuStrip = null;
4917 _listCustom.Font = null;
4919 _listCustom.SmallImageList = null;
4920 _listCustom.ListViewItemSorter = null;
4923 if (_curTab.Equals(_tabPage))
4930 this.PurgeListViewItemCache();
4934 _listCustom.Dispose();
4935 _statuses.RemoveTab(TabName);
4937 foreach (TabPage tp in ListTab.TabPages)
4939 DetailsListView lst = (DetailsListView)tp.Tag;
4940 var count = _statuses.Tabs[tp.Text].AllCount;
4941 if (lst.VirtualListSize != count)
4943 lst.VirtualListSize = count;
4950 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4952 this.PurgeListViewItemCache();
4953 _beforeSelectedTab = e.TabPage;
4956 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4960 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4963 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4964 if (!dragEnableRectangle.Contains(e.Location))
4966 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4967 tn = ListTab.SelectedTab.Text;
4970 if (string.IsNullOrEmpty(tn)) return;
4972 foreach (TabPage tb in ListTab.TabPages)
4976 ListTab.DoDragDrop(tb, DragDropEffects.All);
4986 Point cpos = new Point(e.X, e.Y);
4987 for (int i = 0; i < ListTab.TabPages.Count; i++)
4989 Rectangle rect = ListTab.GetTabRect(i);
4990 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4991 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4993 _rclickTabName = ListTab.TabPages[i].Text;
4999 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
5001 //_curList.Refresh();
5002 SetMainWindowTitle();
5003 SetStatusLabelUrl();
5004 SetApiStatusLabel();
5005 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
5006 TabMenuControl(ListTab.SelectedTab.Text);
5007 this.PushSelectPostChain();
5008 await DispSelectedPost();
5011 private void SetListProperty()
5013 //削除などで見つからない場合は処理せず
5014 if (_curList == null) return;
5015 if (!_isColumnChanged) return;
5017 int[] dispOrder = new int[_curList.Columns.Count];
5018 for (int i = 0; i < _curList.Columns.Count; i++)
5020 for (int j = 0; j < _curList.Columns.Count; j++)
5022 if (_curList.Columns[j].DisplayIndex == i)
5031 foreach (TabPage tb in ListTab.TabPages)
5033 if (!tb.Equals(_curTab))
5035 if (tb.Tag != null && tb.Controls.Count > 0)
5037 DetailsListView lst = (DetailsListView)tb.Tag;
5038 for (int i = 0; i < lst.Columns.Count; i++)
5040 lst.Columns[dispOrder[i]].DisplayIndex = i;
5041 lst.Columns[i].Width = _curList.Columns[i].Width;
5047 _isColumnChanged = false;
5050 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
5054 if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal)
5055 || PostBrowser.StatusText.StartsWith("ftp", StringComparison.Ordinal)
5056 || PostBrowser.StatusText.StartsWith("data", StringComparison.Ordinal))
5058 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
5060 if (string.IsNullOrEmpty(PostBrowser.StatusText))
5062 SetStatusLabelUrl();
5070 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
5072 if (e.KeyChar == '@')
5074 if (!this._cfgCommon.UseAtIdSupplement) return;
5076 int cnt = AtIdSupl.ItemCount;
5077 ShowSuplDialog(StatusText, AtIdSupl);
5078 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
5081 else if (e.KeyChar == '#')
5083 if (!this._cfgCommon.UseHashSupplement) return;
5084 ShowSuplDialog(StatusText, HashSupl);
5089 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
5091 ShowSuplDialog(owner, dialog, 0, "");
5094 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
5096 ShowSuplDialog(owner, dialog, offset, "");
5099 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
5101 dialog.StartsWith = startswith;
5108 dialog.ShowDialog();
5110 this.TopMost = this._cfgCommon.AlwaysTop;
5111 int selStart = owner.SelectionStart;
5114 if (dialog.DialogResult == DialogResult.OK)
5116 if (!string.IsNullOrEmpty(dialog.inputText))
5120 fHalf = owner.Text.Substring(0, selStart - offset);
5122 if (selStart < owner.Text.Length)
5124 eHalf = owner.Text.Substring(selStart);
5126 owner.Text = fHalf + dialog.inputText + eHalf;
5127 owner.SelectionStart = selStart + dialog.inputText.Length;
5134 fHalf = owner.Text.Substring(0, selStart);
5136 if (selStart < owner.Text.Length)
5138 eHalf = owner.Text.Substring(selStart);
5140 owner.Text = fHalf + eHalf;
5143 owner.SelectionStart = selStart;
5149 private void StatusText_KeyUp(object sender, KeyEventArgs e)
5152 if (!e.Alt && !e.Control && !e.Shift)
5154 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
5156 bool isSpace = false;
5157 foreach (char c in StatusText.Text.ToCharArray())
5159 if (c == ' ' || c == ' ')
5172 StatusText.Text = "";
5173 JumpUnreadMenuItem_Click(null, null);
5177 this.StatusText_TextChanged(null, null);
5180 private void StatusText_TextChanged(object sender, EventArgs e)
5183 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
5184 lblLen.Text = pLen.ToString();
5187 StatusText.ForeColor = Color.Red;
5191 StatusText.ForeColor = _clInputFont;
5193 if (string.IsNullOrEmpty(StatusText.Text))
5195 this.inReplyTo = null;
5200 /// ツイート投稿前のフッター付与などの前処理を行います
5202 private string FormatStatusText(string statusText)
5204 statusText = statusText.Replace("\r\n", "\n");
5206 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
5209 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
5212 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
5214 // 文中の全角スペースを半角スペース1個にする
5215 statusText = statusText.Replace(" ", " ");
5218 // DM の場合はこれ以降の処理を行わない
5219 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
5223 if (this._cfgCommon.PostShiftEnter)
5225 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5229 if (this.StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
5230 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5232 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
5235 if (statusText.Contains("RT @"))
5236 disableFooter = true;
5241 var hashtag = this.HashMgr.UseHash;
5242 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
5245 header = HashMgr.UseHash + " ";
5247 footer = " " + HashMgr.UseHash;
5252 if (this._cfgLocal.UseRecommendStatus)
5255 footer += this.recommendedStatusFooter;
5257 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
5259 // テキストボックスに入力されている文字列を使用する
5260 footer += " " + this._cfgLocal.StatusText.Trim();
5264 statusText = header + statusText + footer;
5266 if (this.ToolStripMenuItemPreventSmsCommand.Checked)
5268 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
5269 // 参照: https://support.twitter.com/articles/14020
5271 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
5272 && !Twitter.DMSendTextRegex.IsMatch(statusText))
5274 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
5275 statusText = '\u200b' + statusText;
5283 /// 投稿欄に表示する入力可能な文字数を計算します
5285 private int GetRestStatusCount(string statusText)
5288 var remainCount = this.tw.GetTextLengthRemain(statusText);
5290 if (this.ImageSelector.Visible && !string.IsNullOrEmpty(this.ImageSelector.ServiceName))
5292 remainCount -= this.tw.Configuration.CharactersReservedPerMedia;
5298 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5300 if (sender != this._curList)
5303 var listCache = this._listItemCache;
5304 if (listCache != null && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
5306 // If the newly requested cache is a subset of the old cache,
5307 // no need to rebuild everything, so do nothing.
5311 // Now we need to rebuild the cache.
5312 this.CreateCache(e.StartIndex, e.EndIndex);
5315 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5317 var listCache = this._listItemCache;
5318 if (listCache != null && listCache.TargetList == sender)
5321 PostClass cacheItemPost;
5322 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
5329 // A cache miss, so create a new ListViewItem and pass it back.
5330 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5333 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
5337 // 不正な要求に対する間に合わせの応答
5338 string[] sitem = {"", "", "", "", "", "", "", ""};
5339 e.Item = new ImageListViewItem(sitem);
5343 private void CreateCache(int startIndex, int endIndex)
5345 var tabInfo = this._statuses.Tabs[this._curTab.Text];
5347 if (tabInfo.AllCount == 0)
5350 // キャッシュ要求(要求範囲±30を作成)
5351 startIndex = Math.Max(startIndex - 30, 0);
5352 endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
5354 var cacheLength = endIndex - startIndex + 1;
5356 var posts = tabInfo[startIndex, endIndex]; //配列で取得
5357 var listItems = Enumerable.Range(0, cacheLength)
5358 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
5361 var listCache = new ListViewItemCache
5363 TargetList = this._curList,
5364 StartIndex = startIndex,
5365 EndIndex = endIndex,
5367 ListItem = listItems,
5370 Interlocked.Exchange(ref this._listItemCache, listCache);
5374 /// DetailsListView のための ListViewItem のキャッシュを消去する
5376 private void PurgeListViewItemCache()
5378 Interlocked.Exchange(ref this._listItemCache, null);
5381 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5383 StringBuilder mk = new StringBuilder();
5384 //if (Post.IsDeleted) mk.Append("×");
5385 //if (Post.IsMark) mk.Append("♪");
5386 //if (Post.IsProtect) mk.Append("Ю");
5387 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5388 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5389 ImageListViewItem itm;
5390 if (Post.RetweetedId == null)
5392 string[] sitem= {"",
5394 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5395 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5400 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5404 string[] sitem = {"",
5406 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5407 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5408 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5412 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5414 itm.StateIndex = Post.StateIndex;
5416 bool read = Post.IsRead;
5417 //未読管理していなかったら既読として扱う
5418 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5419 ChangeItemStyleRead(read, itm, Post, null);
5420 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5425 /// 全てのタブの振り分けルールを反映し直します
5427 private void ApplyPostFilters()
5429 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5431 this.PurgeListViewItemCache();
5432 this._curPost = null;
5433 this._curItemIndex = -1;
5434 this._statuses.FilterAll();
5436 foreach (TabPage tabPage in this.ListTab.TabPages)
5438 var tab = this._statuses.Tabs[tabPage.Text];
5440 var listview = (DetailsListView)tabPage.Tag;
5441 using (ControlTransaction.Update(listview))
5443 listview.VirtualListSize = tab.AllCount;
5446 if (this._cfgCommon.TabIconDisp)
5448 if (tab.UnreadCount > 0)
5449 tabPage.ImageIndex = 0;
5451 tabPage.ImageIndex = -1;
5455 if (!this._cfgCommon.TabIconDisp)
5456 this.ListTab.Refresh();
5458 SetMainWindowTitle();
5459 SetStatusLabelUrl();
5463 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5465 e.DrawDefault = true;
5468 private void MyList_HScrolled(object sender, EventArgs e)
5470 DetailsListView listView = (DetailsListView)sender;
5474 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5476 if (e.State == 0) return;
5477 e.DrawDefault = false;
5479 SolidBrush brs2 = null;
5480 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5482 if (e.Item.BackColor == _clSelf)
5483 brs2 = _brsBackColorMine;
5484 else if (e.Item.BackColor == _clAtSelf)
5485 brs2 = _brsBackColorAt;
5486 else if (e.Item.BackColor == _clTarget)
5487 brs2 = _brsBackColorYou;
5488 else if (e.Item.BackColor == _clAtTarget)
5489 brs2 = _brsBackColorAtYou;
5490 else if (e.Item.BackColor == _clAtFromTarget)
5491 brs2 = _brsBackColorAtFromTarget;
5492 else if (e.Item.BackColor == _clAtTo)
5493 brs2 = _brsBackColorAtTo;
5495 brs2 = _brsBackColorNone;
5500 if (((Control)sender).Focused)
5501 brs2 = _brsHighLight;
5503 brs2 = _brsDeactiveSelection;
5505 e.Graphics.FillRectangle(brs2, e.Bounds);
5506 e.DrawFocusRectangle();
5507 this.DrawListViewItemIcon(e);
5510 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5512 if (e.ItemState == 0) return;
5514 if (e.ColumnIndex > 0)
5517 RectangleF rct = e.Bounds;
5518 rct.Width = e.Header.Width;
5519 int fontHeight = e.Item.Font.Height;
5522 rct.Y += fontHeight;
5523 rct.Height -= fontHeight;
5527 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5529 //if (heightDiff > fontHeight * 0.7)
5531 // rct.Height += fontHeight;
5532 // drawLineCount += 1;
5535 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5536 if (!_iconCol && drawLineCount <= 1)
5538 //rct.Inflate(0, heightDiff / -2);
5539 //rct.Height += fontHeight / 2;
5541 else if (heightDiff < fontHeight * 0.7)
5543 //最終行が70%以上欠けていたら、最終行は表示しない
5544 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5545 rct.Height = (fontHeight * drawLineCount) - 1;
5552 //if (!_iconCol && drawLineCount > 1)
5554 // rct.Y += fontHeight * 0.2;
5555 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5560 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5561 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5566 Rectangle rctB = e.Bounds;
5567 rctB.Width = e.Header.Width;
5568 rctB.Height = fontHeight;
5570 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5572 TextRenderer.DrawText(e.Graphics,
5573 e.Item.SubItems[2].Text,
5575 Rectangle.Round(rct),
5577 TextFormatFlags.WordBreak |
5578 TextFormatFlags.EndEllipsis |
5579 TextFormatFlags.GlyphOverhangPadding |
5580 TextFormatFlags.NoPrefix);
5581 TextRenderer.DrawText(e.Graphics,
5582 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 + "]",
5586 TextFormatFlags.SingleLine |
5587 TextFormatFlags.EndEllipsis |
5588 TextFormatFlags.GlyphOverhangPadding |
5589 TextFormatFlags.NoPrefix);
5592 else if (drawLineCount == 1)
5594 TextRenderer.DrawText(e.Graphics,
5597 Rectangle.Round(rct),
5599 TextFormatFlags.SingleLine |
5600 TextFormatFlags.EndEllipsis |
5601 TextFormatFlags.GlyphOverhangPadding |
5602 TextFormatFlags.NoPrefix |
5603 TextFormatFlags.VerticalCenter);
5607 TextRenderer.DrawText(e.Graphics,
5610 Rectangle.Round(rct),
5612 TextFormatFlags.WordBreak |
5613 TextFormatFlags.EndEllipsis |
5614 TextFormatFlags.GlyphOverhangPadding |
5615 TextFormatFlags.NoPrefix);
5617 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5622 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5624 if (_iconSz == 0) return;
5626 ImageListViewItem item = (ImageListViewItem)e.Item;
5628 //e.Bounds.Leftが常に0を指すから自前で計算
5629 Rectangle itemRect = item.Bounds;
5630 var col0 = e.Item.ListView.Columns[0];
5631 itemRect.Width = col0.Width;
5633 if (col0.DisplayIndex > 0)
5635 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5637 if (clm.DisplayIndex < col0.DisplayIndex)
5638 itemRect.X += clm.Width;
5642 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5643 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5644 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5647 var img = item.Image;
5650 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5651 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5653 if (iconRect.Width > 0)
5655 e.Graphics.FillRectangle(Brushes.White, iconRect);
5656 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5659 e.Graphics.DrawImage(img.Image, iconRect);
5661 catch (ArgumentException)
5663 item.RefreshImageAsync();
5669 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5670 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5672 item.GetImageAsync();
5675 if (item.StateIndex > -1)
5677 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5678 if (stateRect.Width > 0)
5680 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5681 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5682 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5687 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5689 base.ScaleControl(factor, specified);
5691 ScaleChildControl(this.TabImage, factor);
5693 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5694 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5696 foreach (var listview in listviews)
5698 ScaleChildControl(listview, factor);
5702 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5704 // ImageListViewItem item = (ImageListViewItem)e.Item;
5705 // if (item.StateImageIndex > -1)
5707 // ////e.Bounds.Leftが常に0を指すから自前で計算
5708 // //Rectangle itemRect = item.Bounds;
5709 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5711 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5713 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5715 // // itemRect.X += clm.Width;
5719 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5720 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5722 // if (rct.Width > 0)
5724 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5725 // //e.Graphics.FillRectangle(Brushes.White, rct);
5726 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5727 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5732 private void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5734 var tab = this._statuses.Tabs[this._curTab.Text];
5736 if (tab.AllCount == 0)
5738 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5742 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5747 case SEARCHTYPE.NextSearch: // 次を検索
5748 if (selectedIndex != -1)
5749 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5753 case SEARCHTYPE.PrevSearch: // 前を検索
5754 if (selectedIndex != -1)
5755 startIndex = Math.Max(selectedIndex - 1, 0);
5757 startIndex = tab.AllCount - 1;
5759 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5761 if (selectedIndex != -1)
5762 startIndex = selectedIndex;
5768 Func<string, bool> stringComparer;
5771 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5773 catch (ArgumentException)
5775 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5779 var reverse = searchType == SEARCHTYPE.PrevSearch;
5780 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5781 .DefaultIfEmpty(-1).First();
5783 if (foundIndex == -1)
5785 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5789 this.SelectListItem(this._curList, foundIndex);
5790 this._curList.EnsureVisible(foundIndex);
5793 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5796 this.ShowSearchDialog();
5799 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5801 var previousSearch = this.SearchDialog.ResultOptions;
5802 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5804 this.SearchDialog.Reset();
5805 this.ShowSearchDialog();
5811 previousSearch.Query,
5812 previousSearch.CaseSensitive,
5813 previousSearch.UseRegex,
5814 SEARCHTYPE.NextSearch);
5817 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5819 var previousSearch = this.SearchDialog.ResultOptions;
5820 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5822 this.SearchDialog.Reset();
5823 this.ShowSearchDialog();
5829 previousSearch.Query,
5830 previousSearch.CaseSensitive,
5831 previousSearch.UseRegex,
5832 SEARCHTYPE.PrevSearch);
5836 /// 検索ダイアログを表示し、検索を実行します
5838 private void ShowSearchDialog()
5840 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5842 this.TopMost = this._cfgCommon.AlwaysTop;
5845 this.TopMost = this._cfgCommon.AlwaysTop;
5847 var searchOptions = this.SearchDialog.ResultOptions;
5848 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5850 if (searchOptions.NewTab)
5852 var tabName = Properties.Resources.SearchResults_TabName;
5856 tabName = this._statuses.MakeTabName(tabName);
5858 catch (TabException ex)
5860 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5863 this.AddNewTab(tabName, false, MyCommon.TabUsageType.SearchResults);
5864 this._statuses.AddTab(tabName, MyCommon.TabUsageType.SearchResults, null);
5866 var targetTab = this._statuses.Tabs[this._curTab.Text];
5868 Func<string, bool> stringComparer;
5871 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5873 catch (ArgumentException)
5875 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5879 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5880 if (foundIndices.Length == 0)
5882 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5886 var foundPosts = foundIndices.Select(x => targetTab[x]);
5888 var resultTab = this._statuses.Tabs[tabName];
5889 foreach (var post in foundPosts)
5891 resultTab.AddPostToInnerStorage(post);
5894 this._statuses.DistributePosts();
5895 this.RefreshTimeline();
5897 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5898 .First(x => x.Text == tabName);
5900 this.ListTab.SelectedTab = tabPage;
5905 searchOptions.Query,
5906 searchOptions.CaseSensitive,
5907 searchOptions.UseRegex,
5908 SEARCHTYPE.DialogSearch);
5911 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5913 this.AddNewTabForSearch(searchOptions.Query);
5917 /// <summary>発言検索に使用するメソッドを生成します</summary>
5918 /// <exception cref="ArgumentException">
5919 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"> が不正な正規表現な場合
5921 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5925 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5926 var regex = new Regex(query, regexOption);
5928 return x => regex.IsMatch(x);
5932 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5934 return x => x.IndexOf(query, comparisonType) != -1;
5938 private void AboutMenuItem_Click(object sender, EventArgs e)
5940 using (TweenAboutBox about = new TweenAboutBox())
5942 about.ShowDialog(this);
5944 this.TopMost = this._cfgCommon.AlwaysTop;
5947 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5949 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5951 DetailsListView lst = null;
5953 if (ImageSelector.Enabled)
5957 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5960 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5963 ListTab.SelectedIndex = i;
5964 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5965 //_curTab = ListTab.TabPages[i];
5970 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5971 if (idx == -1 && bgnIdx > 0)
5973 for (int i = 0; i < bgnIdx; i++)
5975 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5978 ListTab.SelectedIndex = i;
5979 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5980 //_curTab = ListTab.TabPages[i];
5986 //全部調べたが未読見つからず→先頭タブの最新発言へ
5989 ListTab.SelectedIndex = 0;
5990 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5991 //_curTab = ListTab.TabPages[0];
5992 if (_statuses.SortOrder == SortOrder.Ascending)
5993 idx = lst.VirtualListSize - 1;
5998 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
6000 SelectListItem(lst, idx);
6001 if (_statuses.SortMode == ComparerMode.Id)
6003 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
6004 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
6010 lst.EnsureVisible(idx);
6015 lst.EnsureVisible(idx);
6021 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
6023 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
6025 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6026 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
6030 private async void FavorareMenuItem_Click(object sender, EventArgs e)
6032 if (_curList.SelectedIndices.Count > 0)
6034 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6035 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
6039 private async void VerUpMenuItem_Click(object sender, EventArgs e)
6041 await this.CheckNewVersion(false);
6044 private void RunTweenUp()
6046 ProcessStartInfo pinfo = new ProcessStartInfo();
6047 pinfo.UseShellExecute = true;
6048 pinfo.WorkingDirectory = MyCommon.settingPath;
6049 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
6050 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
6053 Process.Start(pinfo);
6057 MessageBox.Show("Failed to execute TweenUp3.exe.");
6061 public class VersionInfo
6063 public Version Version { get; set; }
6064 public Uri DownloadUri { get; set; }
6065 public string ReleaseNote { get; set; }
6069 /// OpenTween の最新バージョンの情報を取得します
6071 public async Task<VersionInfo> GetVersionInfoAsync()
6073 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
6074 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
6076 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
6077 .ConfigureAwait(false);
6079 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
6080 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
6082 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
6083 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
6085 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
6087 return new VersionInfo
6089 Version = Version.Parse(msgHeader[0]),
6090 DownloadUri = new Uri(msgHeader[1]),
6091 ReleaseNote = msgBody,
6095 private async Task CheckNewVersion(bool startup = false)
6097 if (ApplicationSettings.VersionInfoUrl == null)
6098 return; // 更新チェック無効化
6102 var versionInfo = await this.GetVersionInfoAsync();
6104 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
6109 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
6110 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
6111 msgtext = MyCommon.ReplaceAppName(msgtext);
6113 MessageBox.Show(msgtext,
6114 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6115 MessageBoxButtons.OK, MessageBoxIcon.Information);
6120 using (var dialog = new UpdateDialog())
6122 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
6123 MyCommon.GetReadableVersion(versionInfo.Version));
6124 dialog.DetailsText = versionInfo.ReleaseNote;
6126 if (dialog.ShowDialog(this) == DialogResult.Yes)
6128 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
6134 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
6137 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
6138 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6139 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
6144 private async Task Colorize()
6147 await this.DispSelectedPost();
6148 //件数関連の場合、タイトル即時書き換え
6149 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
6150 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6151 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6152 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6154 SetMainWindowTitle();
6156 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6157 foreach (TabPage tb in ListTab.TabPages)
6159 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6161 if (this._cfgCommon.TabIconDisp)
6163 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6167 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
6170 public string createDetailHtml(string orgdata)
6172 if (this._cfgLocal.UseTwemoji)
6173 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
6175 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6178 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6180 if (sender.Equals(displayItem))
6182 this.ClearUserPicture();
6184 var img = displayItem.Image;
6188 img = await img.CloneAsync();
6190 UserPicture.Image = img;
6194 UserPicture.ShowErrorImage();
6199 private Task DispSelectedPost()
6201 return this.DispSelectedPost(false);
6204 private PostClass displayPost = new PostClass();
6207 /// サムネイル表示に使用する CancellationToken の生成元
6209 private CancellationTokenSource thumbnailTokenSource = null;
6211 private async Task DispSelectedPost(bool forceupdate)
6213 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6216 var oldDisplayPost = this.displayPost;
6217 this.displayPost = this._curPost;
6219 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6222 if (displayItem != null)
6224 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6227 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6228 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6230 using (ControlTransaction.Update(this.TableLayoutPanel1))
6232 SourceLinkLabel.Text = this._curPost.Source;
6233 SourceLinkLabel.Tag = this._curPost.SourceUri;
6234 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6240 nameText = "DM FROM <- ";
6242 nameText = "DM TO -> ";
6248 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6249 if (_curPost.RetweetedId != null)
6250 nameText += " (RT:" + _curPost.RetweetedBy + ")";
6252 NameLabel.Text = nameText;
6253 NameLabel.Tag = _curPost.ScreenName;
6255 var nameForeColor = SystemColors.ControlText;
6256 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6257 nameForeColor = this._clOWL;
6258 if (_curPost.RetweetedId != null)
6259 nameForeColor = this._clRetweet;
6261 nameForeColor = this._clFav;
6262 NameLabel.ForeColor = nameForeColor;
6264 this.ClearUserPicture();
6266 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6268 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6271 UserPicture.Image = image?.Clone();
6275 UserPicture.ShowErrorImage();
6279 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6282 if (DumpPostClassToolStripMenuItem.Checked)
6284 StringBuilder sb = new StringBuilder(512);
6286 sb.Append("-----Start PostClass Dump<br>");
6287 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
6288 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6289 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
6290 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
6291 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
6292 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
6293 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
6294 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
6295 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
6296 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
6297 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
6298 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
6299 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
6300 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
6301 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
6303 foreach (string nm in _curPost.ReplyToList)
6305 sb.AppendFormat("ReplyToList : {0}<br>", nm);
6308 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
6309 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
6310 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
6311 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
6312 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
6313 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
6314 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
6315 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
6316 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
6317 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
6319 sb.AppendFormat("Media.Count : {0}<br>", _curPost.Media.Count);
6320 if (_curPost.Media.Count > 0)
6322 for (int i = 0; i < _curPost.Media.Count; i++)
6324 var info = _curPost.Media[i];
6325 sb.AppendFormat("Media[{0}].Url : {1}<br>", i, info.Url);
6326 sb.AppendFormat("Media[{0}].VideoUrl : {1}<br>", i, info.VideoUrl ?? "---");
6329 sb.Append("-----End PostClass Dump<br>");
6331 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6335 var loadTasks = new List<Task>();
6337 // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6338 // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6339 if (_curPost.StatusId != oldDisplayPost.StatusId)
6341 using (ControlTransaction.Update(this.PostBrowser))
6343 this.PostBrowser.DocumentText =
6344 this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6346 this.PostBrowser.Document.Window.ScrollTo(0, 0);
6349 this.SplitContainer3.Panel2Collapsed = true;
6351 if (this._cfgCommon.PreviewEnable)
6353 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
6354 oldTokenSource?.Cancel();
6356 var token = this.thumbnailTokenSource.Token;
6357 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
6360 loadTasks.Add(this.AppendQuoteTweetAsync(this._curPost));
6365 await Task.WhenAll(loadTasks);
6367 catch (OperationCanceledException) { }
6371 /// 発言詳細欄のツイートURLを展開する
6373 private async Task AppendQuoteTweetAsync(PostClass post)
6375 var quoteStatusIds = post.QuoteStatusIds;
6376 if (quoteStatusIds.Length == 0 && post.InReplyToStatusId == null)
6380 var loadingQuoteHtml = quoteStatusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText, isReply: false));
6382 var loadingReplyHtml = string.Empty;
6383 if (post.InReplyToStatusId != null)
6384 loadingReplyHtml = FormatQuoteTweetHtml(post.InReplyToStatusId.Value, Properties.Resources.LoadingText, isReply: true);
6386 var body = post.Text + string.Concat(loadingQuoteHtml) + loadingReplyHtml;
6388 using (ControlTransaction.Update(this.PostBrowser))
6389 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6392 var loadTweetTasks = quoteStatusIds.Select(x => this.CreateQuoteTweetHtml(x, isReply: false)).ToList();
6394 if (post.InReplyToStatusId != null)
6395 loadTweetTasks.Add(this.CreateQuoteTweetHtml(post.InReplyToStatusId.Value, isReply: true));
6397 var quoteHtmls = await Task.WhenAll(loadTweetTasks);
6399 // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
6400 if (this._curPost != post || this._curPost.IsDeleted)
6403 body = post.Text + string.Concat(quoteHtmls);
6405 using (ControlTransaction.Update(this.PostBrowser))
6406 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6409 private async Task<string> CreateQuoteTweetHtml(long statusId, bool isReply)
6411 PostClass post = this._statuses[statusId];
6416 post = await this.tw.GetStatusApi(false, statusId)
6417 .ConfigureAwait(false);
6419 catch (WebApiException ex)
6421 return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode($"Err:{ex.Message}(GetStatus)"), isReply);
6425 if (!this._statuses.AddQuoteTweet(post))
6426 return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.", isReply);
6429 return FormatQuoteTweetHtml(post, isReply);
6432 internal static string FormatQuoteTweetHtml(PostClass post, bool isReply)
6434 var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
6435 " — " + WebUtility.HtmlEncode(post.Nickname) +
6436 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
6437 WebUtility.HtmlEncode(post.CreatedAt.ToString());
6439 return FormatQuoteTweetHtml(post.StatusId, innerHtml, isReply);
6442 internal static string FormatQuoteTweetHtml(long statusId, string innerHtml, bool isReply)
6444 var blockClassName = "quote-tweet";
6447 blockClassName += " reply";
6449 return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
6450 $"<blockquote class=\"{blockClassName}\">{innerHtml}</blockquote>" +
6455 /// 指定されたHTMLからリンクを除去します
6457 internal static string StripLinkTagHtml(string html)
6459 // a 要素はネストされていない前提の正規表現パターン
6460 return Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1");
6463 private async void MatomeMenuItem_Click(object sender, EventArgs e)
6465 await this.OpenApplicationWebsite();
6468 private async Task OpenApplicationWebsite()
6470 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
6473 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6475 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
6478 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
6480 if (ListTab.SelectedTab != null)
6482 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6484 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6485 if (pnl.Controls["comboSearch"].Focused ||
6486 pnl.Controls["comboLang"].Focused ||
6487 pnl.Controls["buttonSearch"].Focused) return;
6490 if (e.Control || e.Shift || e.Alt)
6491 this._anchorFlag = false;
6494 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
6497 e.SuppressKeyPress = true;
6500 if (asyncTask != null)
6505 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
6507 private void InitializeShortcuts()
6509 this.shortcutCommands = new[]
6511 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6512 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
6513 .FocusedOn(FocusedControl.ListTab)
6514 .Do(() => SendKeys.Send("{DOWN}")),
6516 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
6517 .FocusedOn(FocusedControl.ListTab)
6518 .Do(() => SendKeys.Send("{UP}")),
6520 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
6521 .FocusedOn(FocusedControl.ListTab)
6522 .Do(() => SendKeys.Send("{PGDN}")),
6524 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
6525 .FocusedOn(FocusedControl.ListTab)
6526 .Do(() => SendKeys.Send("{PGUP}")),
6528 ShortcutCommand.Create(Keys.F1)
6529 .Do(() => this.OpenApplicationWebsite()),
6531 ShortcutCommand.Create(Keys.F3)
6532 .Do(() => this.MenuItemSearchNext_Click(null, null)),
6534 ShortcutCommand.Create(Keys.F5)
6535 .Do(() => this.DoRefresh()),
6537 ShortcutCommand.Create(Keys.F6)
6538 .Do(() => this.GetReplyAsync()),
6540 ShortcutCommand.Create(Keys.F7)
6541 .Do(() => this.GetDirectMessagesAsync()),
6543 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
6544 .NotFocusedOn(FocusedControl.StatusText)
6545 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
6547 ShortcutCommand.Create(Keys.G)
6548 .NotFocusedOn(FocusedControl.StatusText)
6549 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
6551 ShortcutCommand.Create(Keys.Right, Keys.N)
6552 .FocusedOn(FocusedControl.ListTab)
6553 .Do(() => this.GoRelPost(forward: true)),
6555 ShortcutCommand.Create(Keys.Left, Keys.P)
6556 .FocusedOn(FocusedControl.ListTab)
6557 .Do(() => this.GoRelPost(forward: false)),
6559 ShortcutCommand.Create(Keys.OemPeriod)
6560 .FocusedOn(FocusedControl.ListTab)
6561 .Do(() => this.GoAnchor()),
6563 ShortcutCommand.Create(Keys.I)
6564 .FocusedOn(FocusedControl.ListTab)
6565 .OnlyWhen(() => this.StatusText.Enabled)
6566 .Do(() => this.StatusText.Focus()),
6568 ShortcutCommand.Create(Keys.Enter)
6569 .FocusedOn(FocusedControl.ListTab)
6570 .Do(() => this.MakeReplyOrDirectStatus()),
6572 ShortcutCommand.Create(Keys.R)
6573 .FocusedOn(FocusedControl.ListTab)
6574 .Do(() => this.DoRefresh()),
6576 ShortcutCommand.Create(Keys.L)
6577 .FocusedOn(FocusedControl.ListTab)
6578 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
6580 ShortcutCommand.Create(Keys.H)
6581 .FocusedOn(FocusedControl.ListTab)
6582 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6584 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6585 .FocusedOn(FocusedControl.ListTab)
6586 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6588 ShortcutCommand.Create(Keys.S)
6589 .FocusedOn(FocusedControl.ListTab)
6590 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6592 ShortcutCommand.Create(Keys.A)
6593 .FocusedOn(FocusedControl.ListTab)
6594 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6596 // ] in_reply_to参照元へ戻る
6597 ShortcutCommand.Create(Keys.Oem4)
6598 .FocusedOn(FocusedControl.ListTab)
6599 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6601 // [ in_reply_toへジャンプ
6602 ShortcutCommand.Create(Keys.Oem6)
6603 .FocusedOn(FocusedControl.ListTab)
6604 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6606 ShortcutCommand.Create(Keys.Escape)
6607 .FocusedOn(FocusedControl.ListTab)
6609 this._anchorFlag = false;
6610 if (ListTab.SelectedTab != null)
6612 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6613 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6615 var relTp = ListTab.SelectedTab;
6616 RemoveSpecifiedTab(relTp.Text, false);
6622 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
6623 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
6624 .FocusedOn(FocusedControl.ListTab)
6625 .Do(() => this._anchorFlag = false, preventDefault: false),
6627 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6628 ShortcutCommand.Create(Keys.Up, Keys.Down)
6629 .FocusedOn(FocusedControl.PostBrowser)
6632 ShortcutCommand.Create(Keys.Control | Keys.R)
6633 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6635 ShortcutCommand.Create(Keys.Control | Keys.D)
6636 .Do(() => this.doStatusDelete()),
6638 ShortcutCommand.Create(Keys.Control | Keys.M)
6639 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6641 ShortcutCommand.Create(Keys.Control | Keys.S)
6642 .Do(() => this.FavoriteChange(FavAdd: true)),
6644 ShortcutCommand.Create(Keys.Control | Keys.I)
6645 .Do(() => this.doRepliedStatusOpen()),
6647 ShortcutCommand.Create(Keys.Control | Keys.Q)
6648 .Do(() => this.doQuoteOfficial()),
6650 ShortcutCommand.Create(Keys.Control | Keys.B)
6651 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6653 ShortcutCommand.Create(Keys.Control | Keys.T)
6654 .Do(() => this.HashManageMenuItem_Click(null, null)),
6656 ShortcutCommand.Create(Keys.Control | Keys.L)
6657 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6659 ShortcutCommand.Create(Keys.Control | Keys.Y)
6660 .NotFocusedOn(FocusedControl.PostBrowser)
6661 .Do(() => this.MultiLineMenuItem_Click(null, null)),
6663 ShortcutCommand.Create(Keys.Control | Keys.F)
6664 .Do(() => this.MenuItemSubSearch_Click(null, null)),
6666 ShortcutCommand.Create(Keys.Control | Keys.U)
6667 .Do(() => this.ShowUserTimeline()),
6669 ShortcutCommand.Create(Keys.Control | Keys.H)
6670 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6672 ShortcutCommand.Create(Keys.Control | Keys.G)
6673 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6675 ShortcutCommand.Create(Keys.Control | Keys.O)
6676 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6678 ShortcutCommand.Create(Keys.Control | Keys.E)
6679 .Do(() => this.OpenURLMenuItem_Click(null, null)),
6681 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6682 .FocusedOn(FocusedControl.ListTab)
6683 .Do(() => this._colorize = true, preventDefault: false),
6685 ShortcutCommand.Create(Keys.Control | Keys.N)
6686 .FocusedOn(FocusedControl.ListTab)
6687 .Do(() => this.GoNextTab(forward: true)),
6689 ShortcutCommand.Create(Keys.Control | Keys.P)
6690 .FocusedOn(FocusedControl.ListTab)
6691 .Do(() => this.GoNextTab(forward: false)),
6693 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6694 .FocusedOn(FocusedControl.ListTab)
6695 .Do(() => this.CopyStot()),
6697 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6698 ShortcutCommand.Create(Keys.Control | Keys.D1)
6699 .FocusedOn(FocusedControl.ListTab)
6700 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6701 .Do(() => this.ListTab.SelectedIndex = 0),
6703 ShortcutCommand.Create(Keys.Control | Keys.D2)
6704 .FocusedOn(FocusedControl.ListTab)
6705 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6706 .Do(() => this.ListTab.SelectedIndex = 1),
6708 ShortcutCommand.Create(Keys.Control | Keys.D3)
6709 .FocusedOn(FocusedControl.ListTab)
6710 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6711 .Do(() => this.ListTab.SelectedIndex = 2),
6713 ShortcutCommand.Create(Keys.Control | Keys.D4)
6714 .FocusedOn(FocusedControl.ListTab)
6715 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6716 .Do(() => this.ListTab.SelectedIndex = 3),
6718 ShortcutCommand.Create(Keys.Control | Keys.D5)
6719 .FocusedOn(FocusedControl.ListTab)
6720 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6721 .Do(() => this.ListTab.SelectedIndex = 4),
6723 ShortcutCommand.Create(Keys.Control | Keys.D6)
6724 .FocusedOn(FocusedControl.ListTab)
6725 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6726 .Do(() => this.ListTab.SelectedIndex = 5),
6728 ShortcutCommand.Create(Keys.Control | Keys.D7)
6729 .FocusedOn(FocusedControl.ListTab)
6730 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6731 .Do(() => this.ListTab.SelectedIndex = 6),
6733 ShortcutCommand.Create(Keys.Control | Keys.D8)
6734 .FocusedOn(FocusedControl.ListTab)
6735 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6736 .Do(() => this.ListTab.SelectedIndex = 7),
6738 ShortcutCommand.Create(Keys.Control | Keys.D9)
6739 .FocusedOn(FocusedControl.ListTab)
6740 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6742 ShortcutCommand.Create(Keys.Control | Keys.A)
6743 .FocusedOn(FocusedControl.StatusText)
6744 .Do(() => this.StatusText.SelectAll()),
6746 ShortcutCommand.Create(Keys.Control | Keys.V)
6747 .FocusedOn(FocusedControl.StatusText)
6748 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6750 ShortcutCommand.Create(Keys.Control | Keys.Up)
6751 .FocusedOn(FocusedControl.StatusText)
6753 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6755 var inReplyToStatusId = this.inReplyTo?.Item1;
6756 var inReplyToScreenName = this.inReplyTo?.Item2;
6757 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6760 if (_hisIdx < 0) _hisIdx = 0;
6762 var historyItem = this._history[this._hisIdx];
6763 StatusText.Text = historyItem.status;
6764 StatusText.SelectionStart = StatusText.Text.Length;
6765 if (historyItem.inReplyToId != null)
6766 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6768 this.inReplyTo = null;
6771 ShortcutCommand.Create(Keys.Control | Keys.Down)
6772 .FocusedOn(FocusedControl.StatusText)
6774 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6776 var inReplyToStatusId = this.inReplyTo?.Item1;
6777 var inReplyToScreenName = this.inReplyTo?.Item2;
6778 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6781 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6783 var historyItem = this._history[this._hisIdx];
6784 StatusText.Text = historyItem.status;
6785 StatusText.SelectionStart = StatusText.Text.Length;
6786 if (historyItem.inReplyToId != null)
6787 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6789 this.inReplyTo = null;
6792 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6793 .FocusedOn(FocusedControl.StatusText)
6795 if (ListTab.SelectedIndex == 0)
6797 ListTab.SelectedIndex = ListTab.TabCount - 1;
6801 ListTab.SelectedIndex -= 1;
6806 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6807 .FocusedOn(FocusedControl.StatusText)
6809 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6811 ListTab.SelectedIndex = 0;
6815 ListTab.SelectedIndex += 1;
6820 ShortcutCommand.Create(Keys.Control | Keys.Y)
6821 .FocusedOn(FocusedControl.PostBrowser)
6823 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6824 MultiLineMenuItem_Click(null, null);
6827 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6828 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6830 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6831 .Do(() => this.DoRefreshMore()),
6833 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6834 .Do(() => this.GetReplyAsync(loadMore: true)),
6836 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6837 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6839 ShortcutCommand.Create(Keys.Shift | Keys.R)
6840 .NotFocusedOn(FocusedControl.StatusText)
6841 .Do(() => this.DoRefreshMore()),
6843 ShortcutCommand.Create(Keys.Shift | Keys.H)
6844 .FocusedOn(FocusedControl.ListTab)
6845 .Do(() => this.GoTopEnd(GoTop: true)),
6847 ShortcutCommand.Create(Keys.Shift | Keys.L)
6848 .FocusedOn(FocusedControl.ListTab)
6849 .Do(() => this.GoTopEnd(GoTop: false)),
6851 ShortcutCommand.Create(Keys.Shift | Keys.M)
6852 .FocusedOn(FocusedControl.ListTab)
6853 .Do(() => this.GoMiddle()),
6855 ShortcutCommand.Create(Keys.Shift | Keys.G)
6856 .FocusedOn(FocusedControl.ListTab)
6857 .Do(() => this.GoLast()),
6859 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6860 .FocusedOn(FocusedControl.ListTab)
6861 .Do(() => this.MoveMiddle()),
6863 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6864 .FocusedOn(FocusedControl.ListTab)
6865 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6867 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6868 .FocusedOn(FocusedControl.ListTab)
6869 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6871 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6872 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6873 .FocusedOn(FocusedControl.ListTab)
6874 .Do(() => this.GoFav(forward: true)),
6876 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6877 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6878 .FocusedOn(FocusedControl.ListTab)
6879 .Do(() => this.GoFav(forward: false)),
6881 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6882 .FocusedOn(FocusedControl.ListTab)
6883 .Do(() => this.GoBackSelectPostChain()),
6885 ShortcutCommand.Create(Keys.Alt | Keys.R)
6886 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6888 ShortcutCommand.Create(Keys.Alt | Keys.P)
6889 .OnlyWhen(() => this._curPost != null)
6890 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6892 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6893 .Do(() => this.ScrollDownPostBrowser(forward: false)),
6895 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6896 .Do(() => this.ScrollDownPostBrowser(forward: true)),
6898 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6899 .Do(() => this.PageDownPostBrowser(forward: false)),
6901 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6902 .Do(() => this.PageDownPostBrowser(forward: true)),
6904 // 別タブの同じ書き込みへ(ALT+←/→)
6905 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6906 .FocusedOn(FocusedControl.ListTab)
6907 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6909 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6910 .FocusedOn(FocusedControl.ListTab)
6911 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6913 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6914 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6916 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6917 .Do(() => this.CopyIdUri()),
6919 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6920 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6921 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6922 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6924 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6925 .Do(() => this.FavoriteChange(FavAdd: false)),
6927 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6928 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6930 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6931 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6933 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6934 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6936 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6937 .Do(() => this.doMoveToRTHome()),
6939 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6940 .Do(() => this.FavorareMenuItem_Click(null, null)),
6942 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6943 .FocusedOn(FocusedControl.StatusText)
6945 if (_curList != null && _curList.VirtualListSize != 0 &&
6946 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6948 var idx = _curList.SelectedIndices[0] - 1;
6949 SelectListItem(_curList, idx);
6950 _curList.EnsureVisible(idx);
6954 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6955 .FocusedOn(FocusedControl.StatusText)
6957 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6958 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6960 var idx = _curList.SelectedIndices[0] + 1;
6961 SelectListItem(_curList, idx);
6962 _curList.EnsureVisible(idx);
6966 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6967 .FocusedOn(FocusedControl.StatusText)
6969 if (StatusText.SelectionStart > 0)
6971 int endidx = StatusText.SelectionStart - 1;
6972 string startstr = "";
6973 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6975 char c = StatusText.Text[i];
6976 if (Char.IsLetterOrDigit(c) || c == '_')
6982 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6983 int cnt = AtIdSupl.ItemCount;
6984 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6985 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6989 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6990 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
7000 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
7001 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
7002 .FocusedOn(FocusedControl.ListTab)
7003 .Do(() => this.SetSortColumnByDisplayIndex(0)),
7005 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
7006 .FocusedOn(FocusedControl.ListTab)
7007 .Do(() => this.SetSortColumnByDisplayIndex(1)),
7009 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
7010 .FocusedOn(FocusedControl.ListTab)
7011 .Do(() => this.SetSortColumnByDisplayIndex(2)),
7013 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
7014 .FocusedOn(FocusedControl.ListTab)
7015 .Do(() => this.SetSortColumnByDisplayIndex(3)),
7017 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
7018 .FocusedOn(FocusedControl.ListTab)
7019 .Do(() => this.SetSortColumnByDisplayIndex(4)),
7021 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
7022 .FocusedOn(FocusedControl.ListTab)
7023 .Do(() => this.SetSortColumnByDisplayIndex(5)),
7025 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
7026 .FocusedOn(FocusedControl.ListTab)
7027 .Do(() => this.SetSortColumnByDisplayIndex(6)),
7029 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
7030 .FocusedOn(FocusedControl.ListTab)
7031 .Do(() => this.SetSortColumnByDisplayIndex(7)),
7033 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
7034 .FocusedOn(FocusedControl.ListTab)
7035 .Do(() => this.SetSortLastColumn()),
7037 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
7038 .Do(() => this.FavoritesRetweetOfficial()),
7040 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
7041 .Do(() => this.FavoritesRetweetUnofficial()),
7043 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
7044 .Do(() => this.OpenUserAppointUrl()),
7046 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7047 .FocusedOn(FocusedControl.PostBrowser)
7048 .Do(() => this.doReTweetUnofficial()),
7050 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
7051 .OnlyWhen(() => this.ExistCurrentPost)
7052 .Do(() => this.doTranslation(_curPost.TextFromApi)),
7054 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7055 .Do(() => this.doReTweetUnofficial()),
7057 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
7058 .Do(() => this.CopyUserId()),
7060 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
7061 .Do(() => this.tweetThumbnail1.ScrollUp()),
7063 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
7064 .Do(() => this.tweetThumbnail1.ScrollDown()),
7066 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
7067 .FocusedOn(FocusedControl.ListTab)
7068 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
7069 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
7073 private bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
7075 // Task を返す非同期処理があれば asyncTask に代入する
7078 // ShortcutCommand に対応しているコマンドはここで処理される
7079 foreach (var command in this.shortcutCommands)
7081 if (command.IsMatch(keyData, focusedOn))
7083 asyncTask = command.RunCommand();
7084 return command.PreventDefault;
7091 private void ScrollDownPostBrowser(bool forward)
7093 var doc = PostBrowser.Document;
7094 if (doc == null) return;
7096 var tags = doc.GetElementsByTagName("html");
7100 tags[0].ScrollTop += this._fntDetail.Height;
7102 tags[0].ScrollTop -= this._fntDetail.Height;
7106 private void PageDownPostBrowser(bool forward)
7108 var doc = PostBrowser.Document;
7109 if (doc == null) return;
7111 var tags = doc.GetElementsByTagName("html");
7115 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7117 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7121 private void GoNextTab(bool forward)
7123 int idx = ListTab.SelectedIndex;
7127 if (idx > ListTab.TabPages.Count - 1) idx = 0;
7132 if (idx < 0) idx = ListTab.TabPages.Count - 1;
7134 ListTab.SelectedIndex = idx;
7137 private void CopyStot()
7140 StringBuilder sb = new StringBuilder();
7141 bool IsProtected = false;
7143 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7144 foreach (int idx in _curList.SelectedIndices)
7146 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7152 if (post.IsDeleted) continue;
7155 if (post.RetweetedId != null)
7156 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7158 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7162 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7167 MessageBox.Show(Properties.Resources.CopyStotText1);
7171 clstr = sb.ToString();
7174 Clipboard.SetDataObject(clstr, false, 5, 100);
7176 catch (Exception ex)
7178 MessageBox.Show(ex.Message);
7183 private void CopyIdUri()
7186 StringBuilder sb = new StringBuilder();
7187 if (this._curTab == null) return;
7188 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7189 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7190 foreach (int idx in _curList.SelectedIndices)
7192 var post = _statuses.Tabs[_curTab.Text][idx];
7193 sb.Append(MyCommon.GetStatusUrl(post));
7194 sb.Append(Environment.NewLine);
7198 clstr = sb.ToString();
7201 Clipboard.SetDataObject(clstr, false, 5, 100);
7203 catch (Exception ex)
7205 MessageBox.Show(ex.Message);
7210 private void GoFav(bool forward)
7212 if (_curList.VirtualListSize == 0) return;
7219 if (_curList.SelectedIndices.Count == 0)
7225 fIdx = _curList.SelectedIndices[0] + 1;
7226 if (fIdx > _curList.VirtualListSize - 1) return;
7228 toIdx = _curList.VirtualListSize;
7233 if (_curList.SelectedIndices.Count == 0)
7235 fIdx = _curList.VirtualListSize - 1;
7239 fIdx = _curList.SelectedIndices[0] - 1;
7240 if (fIdx < 0) return;
7246 for (int idx = fIdx; idx != toIdx; idx += stp)
7248 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
7250 SelectListItem(_curList, idx);
7251 _curList.EnsureVisible(idx);
7257 private void GoSamePostToAnotherTab(bool left)
7259 if (_curList.VirtualListSize == 0) return;
7265 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7266 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7268 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7273 if (ListTab.SelectedIndex == 0)
7279 fIdx = ListTab.SelectedIndex - 1;
7287 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7293 fIdx = ListTab.SelectedIndex + 1;
7295 toIdx = ListTab.TabCount;
7300 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7302 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7303 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7305 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
7307 ListTab.SelectedIndex = tabidx;
7308 SelectListItem(_curList, idx);
7309 _curList.EnsureVisible(idx);
7318 private void GoPost(bool forward)
7320 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7327 fIdx = _curList.SelectedIndices[0] + 1;
7328 if (fIdx > _curList.VirtualListSize - 1) return;
7329 toIdx = _curList.VirtualListSize;
7334 fIdx = _curList.SelectedIndices[0] - 1;
7335 if (fIdx < 0) return;
7341 if (_curPost.RetweetedId == null)
7343 name = _curPost.ScreenName;
7347 name = _curPost.RetweetedBy;
7349 for (int idx = fIdx; idx != toIdx; idx += stp)
7351 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
7353 if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
7355 SelectListItem(_curList, idx);
7356 _curList.EnsureVisible(idx);
7362 if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
7364 SelectListItem(_curList, idx);
7365 _curList.EnsureVisible(idx);
7372 private void GoRelPost(bool forward)
7374 if (_curList.SelectedIndices.Count == 0) return;
7381 fIdx = _curList.SelectedIndices[0] + 1;
7382 if (fIdx > _curList.VirtualListSize - 1) return;
7383 toIdx = _curList.VirtualListSize;
7388 fIdx = _curList.SelectedIndices[0] - 1;
7389 if (fIdx < 0) return;
7396 if (_curPost == null) return;
7397 _anchorPost = _curPost;
7402 if (_anchorPost == null) return;
7405 for (int idx = fIdx; idx != toIdx; idx += stp)
7407 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7408 if (post.ScreenName == _anchorPost.ScreenName ||
7409 post.RetweetedBy == _anchorPost.ScreenName ||
7410 post.ScreenName == _anchorPost.RetweetedBy ||
7411 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7412 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
7413 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
7414 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
7415 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
7417 SelectListItem(_curList, idx);
7418 _curList.EnsureVisible(idx);
7424 private void GoAnchor()
7426 if (_anchorPost == null) return;
7427 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7428 if (idx == -1) return;
7430 SelectListItem(_curList, idx);
7431 _curList.EnsureVisible(idx);
7434 private void GoTopEnd(bool GoTop)
7436 if (_curList.VirtualListSize == 0)
7444 _item = _curList.GetItemAt(0, 25);
7452 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7454 idx = _curList.VirtualListSize - 1;
7458 SelectListItem(_curList, idx);
7461 private void GoMiddle()
7463 if (_curList.VirtualListSize == 0)
7471 _item = _curList.GetItemAt(0, 0);
7481 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7484 idx2 = _curList.VirtualListSize - 1;
7490 idx3 = (idx1 + idx2) / 2;
7492 SelectListItem(_curList, idx3);
7495 private void GoLast()
7497 if (_curList.VirtualListSize == 0) return;
7499 if (_statuses.SortOrder == SortOrder.Ascending)
7501 SelectListItem(_curList, _curList.VirtualListSize - 1);
7502 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7506 SelectListItem(_curList, 0);
7507 _curList.EnsureVisible(0);
7511 private void MoveTop()
7513 if (_curList.SelectedIndices.Count == 0) return;
7514 int idx = _curList.SelectedIndices[0];
7515 if (_statuses.SortOrder == SortOrder.Ascending)
7517 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7521 _curList.EnsureVisible(0);
7523 _curList.EnsureVisible(idx);
7526 private async Task GoInReplyToPostTree()
7528 if (_curPost == null) return;
7530 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7532 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7536 var post = await tw.GetStatusApi(false, _curPost.StatusId);
7538 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7539 _curPost.InReplyToUser = post.InReplyToUser;
7540 _curPost.IsReply = post.IsReply;
7541 this.PurgeListViewItemCache();
7542 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7544 catch (WebApiException ex)
7546 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
7550 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7552 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7554 replyChains = new Stack<ReplyChain>();
7556 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7559 string inReplyToTabName;
7560 long inReplyToId = _curPost.InReplyToStatusId.Value;
7561 string inReplyToUser = _curPost.InReplyToUser;
7562 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7564 var inReplyToPosts = from tab in _statuses.Tabs.Values
7565 orderby tab != curTabClass
7566 from post in tab.Posts.Values
7567 where post.StatusId == inReplyToId
7568 let index = tab.IndexOf(post.StatusId)
7570 select new {Tab = tab, Index = index};
7572 var inReplyPost = inReplyToPosts.FirstOrDefault();
7573 if (inReplyPost == null)
7577 await Task.Run(async () =>
7579 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
7580 .ConfigureAwait(false);
7583 _statuses.AddPost(post);
7584 _statuses.DistributePosts();
7587 catch (WebApiException ex)
7589 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
7590 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7594 this.RefreshTimeline();
7596 inReplyPost = inReplyToPosts.FirstOrDefault();
7597 if (inReplyPost == null)
7599 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7603 inReplyToTabName = inReplyPost.Tab.TabName;
7604 inReplyToIndex = inReplyPost.Index;
7606 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7607 DetailsListView listView = (DetailsListView)tabPage.Tag;
7609 if (_curTab != tabPage)
7611 this.ListTab.SelectTab(tabPage);
7614 this.SelectListItem(listView, inReplyToIndex);
7615 listView.EnsureVisible(inReplyToIndex);
7618 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7620 if (_curPost == null) return;
7622 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7623 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7627 if (_curPost.InReplyToStatusId != null)
7629 var posts = from t in _statuses.Tabs
7630 from p in t.Value.Posts
7631 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7632 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7634 orderby isForward ? indexOf : indexOf * -1
7635 orderby t.Value != curTabClass
7636 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7639 var postList = posts.ToList();
7640 for (int i = postList.Count - 1; i >= 0; i--)
7643 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7645 postList.RemoveAt(index);
7648 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7649 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7650 if (post == null) post = postList.First();
7651 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7652 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7653 SelectListItem(listView, post.Index);
7654 listView.EnsureVisible(post.Index);
7656 catch (InvalidOperationException)
7664 if (replyChains == null || replyChains.Count < 1)
7666 var posts = from t in _statuses.Tabs
7667 from p in t.Value.Posts
7668 where p.Value.InReplyToStatusId == _curPost.StatusId
7669 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7672 orderby t.Value != curTabClass
7673 select new {Tab = t.Value, Index = indexOf};
7676 var post = posts.First();
7677 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7678 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7679 SelectListItem(listView, post.Index);
7680 listView.EnsureVisible(post.Index);
7682 catch (InvalidOperationException)
7689 ReplyChain chainHead = replyChains.Pop();
7690 if (chainHead.InReplyToId == _curPost.StatusId)
7692 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7701 ListTab.SelectTab(chainHead.OriginalTab);
7707 SelectListItem(_curList, idx);
7708 _curList.EnsureVisible(idx);
7714 this.GoBackInReplyToPostTree(parallel);
7720 private void GoBackSelectPostChain()
7722 if (this.selectPostChains.Count > 1)
7731 this.selectPostChains.Pop();
7732 var tabPostPair = this.selectPostChains.Peek();
7734 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7736 if (tabPostPair.Item2 != null)
7738 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7739 if (idx == -1) continue; //該当ポストが存在しないので無視
7742 tp = tabPostPair.Item1;
7744 this.selectPostChains.Pop();
7746 catch (InvalidOperationException)
7752 while (this.selectPostChains.Count > 1);
7757 //履歴が残り1つであればクリアしておく
7758 if (this.selectPostChains.Count == 1)
7759 this.selectPostChains.Clear();
7763 DetailsListView lst = (DetailsListView)tp.Tag;
7764 this.ListTab.SelectedTab = tp;
7767 SelectListItem(lst, idx);
7768 lst.EnsureVisible(idx);
7774 private void PushSelectPostChain()
7776 int count = this.selectPostChains.Count;
7779 var p = this.selectPostChains.Peek();
7780 if (p.Item1 == this._curTab)
7782 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7783 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7786 if (count >= 2500) TrimPostChain();
7787 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7790 private void TrimPostChain()
7792 if (this.selectPostChains.Count <= 2000) return;
7793 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7794 for (int i = 0; i < 2000; i++)
7796 p.Push(this.selectPostChains.Pop());
7798 this.selectPostChains.Clear();
7799 for (int i = 0; i < 2000; i++)
7801 this.selectPostChains.Push(p.Pop());
7805 private bool GoStatus(long statusId)
7807 if (statusId == 0) return false;
7808 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7810 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7812 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7813 ListTab.SelectedIndex = tabidx;
7814 SelectListItem(_curList, idx);
7815 _curList.EnsureVisible(idx);
7822 private bool GoDirectMessage(long statusId)
7824 if (statusId == 0) return false;
7825 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7827 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7829 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7830 ListTab.SelectedIndex = tabidx;
7831 SelectListItem(_curList, idx);
7832 _curList.EnsureVisible(idx);
7839 private void MyList_MouseClick(object sender, MouseEventArgs e)
7841 _anchorFlag = false;
7844 private void StatusText_Enter(object sender, EventArgs e)
7846 // フォーカスの戻り先を StatusText に設定
7847 this.Tag = StatusText;
7848 StatusText.BackColor = _clInputBackcolor;
7851 public Color InputBackColor
7853 get { return _clInputBackcolor; }
7854 set { _clInputBackcolor = value; }
7857 private void StatusText_Leave(object sender, EventArgs e)
7859 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7860 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7861 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7864 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7867 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7870 e.SuppressKeyPress = true;
7873 this.StatusText_TextChanged(null, null);
7875 if (asyncTask != null)
7879 private void SaveConfigsAll(bool ifModified)
7883 SaveConfigsCommon();
7890 if (ModifySettingCommon) SaveConfigsCommon();
7891 if (ModifySettingLocal) SaveConfigsLocal();
7892 if (ModifySettingAtId) SaveConfigsAtId();
7896 private void SaveConfigsAtId()
7898 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7900 ModifySettingAtId = false;
7901 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7905 private void SaveConfigsCommon()
7907 if (_ignoreConfigSave) return;
7909 ModifySettingCommon = false;
7912 _cfgCommon.UserName = tw.Username;
7913 _cfgCommon.UserId = tw.UserId;
7914 _cfgCommon.Password = tw.Password;
7915 _cfgCommon.Token = tw.AccessToken;
7916 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7918 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7919 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7921 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7924 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7925 switch (_statuses.SortMode)
7927 case ComparerMode.Nickname: //ニックネーム
7928 _cfgCommon.SortColumn = 1;
7930 case ComparerMode.Data: //本文
7931 _cfgCommon.SortColumn = 2;
7933 case ComparerMode.Id: //時刻=発言Id
7934 _cfgCommon.SortColumn = 3;
7936 case ComparerMode.Name: //名前
7937 _cfgCommon.SortColumn = 4;
7939 case ComparerMode.Source: //Source
7940 _cfgCommon.SortColumn = 7;
7944 _cfgCommon.HashTags = HashMgr.HashHistories;
7945 if (HashMgr.IsPermanent)
7947 _cfgCommon.HashSelected = HashMgr.UseHash;
7951 _cfgCommon.HashSelected = "";
7953 _cfgCommon.HashIsHead = HashMgr.IsHead;
7954 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7955 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7956 if (ToolStripFocusLockMenuItem != null &&
7957 ToolStripFocusLockMenuItem.IsDisposed == false)
7959 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7961 _cfgCommon.TrackWord = tw.TrackWord;
7962 _cfgCommon.AllAtReply = tw.AllAtReply;
7963 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7964 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7970 private void SaveConfigsLocal()
7972 if (_ignoreConfigSave) return;
7975 ModifySettingLocal = false;
7976 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7977 _cfgLocal.FormSize = _mySize;
7978 _cfgLocal.FormLocation = _myLoc;
7979 _cfgLocal.SplitterDistance = _mySpDis;
7980 _cfgLocal.PreviewDistance = _mySpDis3;
7981 _cfgLocal.StatusMultiline = StatusText.Multiline;
7982 _cfgLocal.StatusTextHeight = _mySpDis2;
7984 _cfgLocal.FontUnread = _fntUnread;
7985 _cfgLocal.ColorUnread = _clUnread;
7986 _cfgLocal.FontRead = _fntReaded;
7987 _cfgLocal.ColorRead = _clReaded;
7988 _cfgLocal.FontDetail = _fntDetail;
7989 _cfgLocal.ColorDetail = _clDetail;
7990 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7991 _cfgLocal.ColorDetailLink = _clDetailLink;
7992 _cfgLocal.ColorFav = _clFav;
7993 _cfgLocal.ColorOWL = _clOWL;
7994 _cfgLocal.ColorRetweet = _clRetweet;
7995 _cfgLocal.ColorSelf = _clSelf;
7996 _cfgLocal.ColorAtSelf = _clAtSelf;
7997 _cfgLocal.ColorTarget = _clTarget;
7998 _cfgLocal.ColorAtTarget = _clAtTarget;
7999 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
8000 _cfgLocal.ColorAtTo = _clAtTo;
8001 _cfgLocal.ColorListBackcolor = _clListBackcolor;
8002 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
8003 _cfgLocal.ColorInputFont = _clInputFont;
8004 _cfgLocal.FontInputFont = _fntInputFont;
8006 if (_ignoreConfigSave) return;
8011 private void SaveConfigsTabs()
8013 SettingTabs tabSetting = new SettingTabs();
8014 for (int i = 0; i < ListTab.TabPages.Count; i++)
8016 var tab = _statuses.Tabs[ListTab.TabPages[i].Text];
8017 if (tab.TabType != MyCommon.TabUsageType.Related && tab.TabType != MyCommon.TabUsageType.SearchResults)
8018 tabSetting.Tabs.Add(tab);
8020 tabSetting.Tabs.Add(this._statuses.GetTabByType(MyCommon.TabUsageType.Mute));
8024 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
8027 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
8028 if (ret != DialogResult.OK)
8031 var match = Twitter.StatusUrlRegex.Match(inputText);
8034 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
8035 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8041 var statusId = long.Parse(match.Groups["StatusId"].Value);
8042 await this.OpenRelatedTab(statusId);
8044 catch (TabException ex)
8046 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8050 private void SaveLogMenuItem_Click(object sender, EventArgs e)
8052 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8053 Properties.Resources.SaveLogMenuItem_ClickText2,
8054 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8055 if (rslt == DialogResult.Cancel) return;
8057 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8058 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8059 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8060 SaveFileDialog1.FilterIndex = 0;
8061 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8062 SaveFileDialog1.RestoreDirectory = true;
8064 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8066 if (!SaveFileDialog1.ValidateNames) return;
8067 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8069 if (rslt == DialogResult.Yes)
8072 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8074 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8075 string protect = "";
8076 if (post.IsProtect) protect = "Protect";
8077 sw.WriteLine(post.Nickname + "\t" +
8078 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8079 post.CreatedAt.ToString() + "\t" +
8080 post.ScreenName + "\t" +
8081 post.StatusId.ToString() + "\t" +
8082 post.ImageUrl + "\t" +
8083 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8089 foreach (int idx in _curList.SelectedIndices)
8091 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8092 string protect = "";
8093 if (post.IsProtect) protect = "Protect";
8094 sw.WriteLine(post.Nickname + "\t" +
8095 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8096 post.CreatedAt.ToString() + "\t" +
8097 post.ScreenName + "\t" +
8098 post.StatusId.ToString() + "\t" +
8099 post.ImageUrl + "\t" +
8100 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8106 this.TopMost = this._cfgCommon.AlwaysTop;
8109 private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8112 bool KeyRes = CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out asyncTask);
8115 e.IsInputKey = true;
8119 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
8121 var shortcut = (Shortcut)e.KeyData;
8124 case Shortcut.CtrlA:
8125 case Shortcut.CtrlC:
8126 case Shortcut.CtrlIns:
8130 // その他のショートカットキーは無効にする
8131 e.IsInputKey = true;
8137 if (asyncTask != null)
8140 public bool TabRename(ref string tabName)
8143 string newTabText = null;
8144 using (InputTabName inputName = new InputTabName())
8146 inputName.TabName = tabName;
8147 inputName.ShowDialog();
8148 if (inputName.DialogResult == DialogResult.Cancel) return false;
8149 newTabText = inputName.TabName;
8151 this.TopMost = this._cfgCommon.AlwaysTop;
8152 if (!string.IsNullOrEmpty(newTabText))
8155 for (int i = 0; i < ListTab.TabCount; i++)
8157 if (ListTab.TabPages[i].Text == newTabText)
8159 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8160 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8165 for (int i = 0; i < ListTab.TabCount; i++)
8167 if (ListTab.TabPages[i].Text == tabName)
8169 ListTab.TabPages[i].Text = newTabText;
8173 _statuses.RenameTab(tabName, newTabText);
8175 SaveConfigsCommon();
8177 _rclickTabName = newTabText;
8178 tabName = newTabText;
8187 private void ListTab_MouseClick(object sender, MouseEventArgs e)
8189 if (e.Button == MouseButtons.Middle)
8191 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8193 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8195 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8196 this.SaveConfigsTabs();
8203 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8205 string tn = ListTab.SelectedTab.Text;
8209 private void ListTab_MouseDown(object sender, MouseEventArgs e)
8211 if (this._cfgCommon.TabMouseLock) return;
8212 Point cpos = new Point(e.X, e.Y);
8213 if (e.Button == MouseButtons.Left)
8215 for (int i = 0; i < ListTab.TabPages.Count; i++)
8217 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8220 _tabMouseDownPoint = e.Location;
8231 private void ListTab_DragEnter(object sender, DragEventArgs e)
8233 if (e.Data.GetDataPresent(typeof(TabPage)))
8234 e.Effect = DragDropEffects.Move;
8236 e.Effect = DragDropEffects.None;
8239 private void ListTab_DragDrop(object sender, DragEventArgs e)
8241 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8246 Point cpos = new Point(e.X, e.Y);
8247 Point spos = ListTab.PointToClient(cpos);
8249 for (i = 0; i < ListTab.TabPages.Count; i++)
8251 Rectangle rect = ListTab.GetTabRect(i);
8252 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8253 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8255 tn = ListTab.TabPages[i].Text;
8256 if (spos.X <= (rect.Left + rect.Right) / 2)
8265 //タブのないところにドロップ->最後尾へ移動
8266 if (string.IsNullOrEmpty(tn))
8268 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8270 i = ListTab.TabPages.Count - 1;
8273 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8274 if (tp.Text == tn) return;
8276 ReOrderTab(tp.Text, tn, bef);
8279 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8281 var baseIndex = this.GetTabPageIndex(baseTabText);
8282 if (baseIndex == -1)
8285 var targetIndex = this.GetTabPageIndex(targetTabText);
8286 if (targetIndex == -1)
8289 using (ControlTransaction.Layout(this.ListTab))
8291 var mTp = this.ListTab.TabPages[targetIndex];
8292 this.ListTab.TabPages.Remove(mTp);
8294 if (targetIndex < baseIndex)
8297 if (isBeforeBaseTab)
8298 ListTab.TabPages.Insert(baseIndex, mTp);
8300 ListTab.TabPages.Insert(baseIndex + 1, mTp);
8306 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8308 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8309 //isReply:true=@,false=DM
8310 if (!StatusText.Enabled) return;
8311 if (_curList == null) return;
8312 if (_curTab == null) return;
8313 if (!this.ExistCurrentPost) return;
8315 // 複数あてリプライはReplyではなく通常ポスト
8316 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8317 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8318 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8320 if (_curList.SelectedIndices.Count > 0)
8323 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8326 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8329 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8330 StatusText.SelectionStart = StatusText.Text.Length;
8332 this.inReplyTo = null;
8335 if (string.IsNullOrEmpty(StatusText.Text))
8339 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8340 StatusText.Text = "@" + _curPost.ScreenName + " ";
8342 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8343 var inReplyToScreenName = this._curPost.ScreenName;
8344 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8352 //1件選んでEnter or DoubleClick
8353 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8355 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
8358 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8359 var inReplyToScreenName = this._curPost.ScreenName;
8360 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8364 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
8367 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8370 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8371 this.inReplyTo = null;
8376 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8377 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8378 var inReplyToScreenName = this._curPost.ScreenName;
8379 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8386 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8387 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8388 this.inReplyTo = null;
8393 //1件選んでCtrl-Rの場合(返信先操作せず)
8394 int sidx = StatusText.SelectionStart;
8395 string id = "@" + _curPost.ScreenName + " ";
8398 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8403 StatusText.Text = StatusText.Text.Insert(sidx, id);
8405 //if (StatusText.Text.StartsWith("@"))
8408 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8409 // sidx += 5 + _curPost.ScreenName.Length;
8414 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8415 // sidx += 3 + _curPost.ScreenName.Length;
8417 StatusText.SelectionStart = sidx;
8420 //_reply_to_name = null;
8428 if (!isAuto && !isReply) return;
8430 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8434 //Enter or DoubleClick
8436 string sTxt = StatusText.Text;
8437 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
8440 this.inReplyTo = null;
8442 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8444 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8445 if (!sTxt.Contains("@" + post.ScreenName + " "))
8447 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8448 //sTxt = "@" + post.ScreenName + " " + sTxt;
8451 StatusText.Text = sTxt;
8456 if (_curList.SelectedIndices.Count > 1)
8461 int sidx = StatusText.SelectionStart;
8462 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8464 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8465 if (!ids.Contains("@" + post.ScreenName + " ") &&
8466 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8468 ids += "@" + post.ScreenName + " ";
8472 foreach (string nm in post.ReplyToList)
8474 if (!ids.Contains("@" + nm + " ") &&
8475 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8477 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8479 ids += "@" + m.Result("${id}") + " ";
8481 ids += "@" + nm + " ";
8486 if (ids.Length == 0) return;
8487 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8489 StatusText.Text = ". " + StatusText.Text;
8491 this.inReplyTo = null;
8495 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8500 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8502 //if (StatusText.Text.StartsWith("@"))
8504 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8505 // sidx += 2 + ids.Length;
8509 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8510 // sidx += 1 + ids.Length;
8512 StatusText.SelectionStart = sidx;
8518 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8521 int sidx = StatusText.SelectionStart;
8522 PostClass post = _curPost;
8523 if (!ids.Contains("@" + post.ScreenName + " ") &&
8524 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8526 ids += "@" + post.ScreenName + " ";
8528 foreach (string nm in post.ReplyToList)
8530 if (!ids.Contains("@" + nm + " ") &&
8531 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8533 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8535 ids += "@" + m.Result("${id}") + " ";
8537 ids += "@" + nm + " ";
8540 if (!string.IsNullOrEmpty(post.RetweetedBy))
8542 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8543 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8545 ids += "@" + post.RetweetedBy + " ";
8548 if (ids.Length == 0) return;
8549 if (string.IsNullOrEmpty(StatusText.Text))
8552 StatusText.Text = ids;
8553 StatusText.SelectionStart = ids.Length;
8556 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8557 var inReplyToScreenName = this._curPost.ScreenName;
8558 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8564 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8569 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8571 StatusText.SelectionStart = sidx;
8577 StatusText.SelectionStart = StatusText.Text.Length;
8582 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8587 private static int iconCnt = 0;
8588 private static int blinkCnt = 0;
8589 private static bool blink = false;
8590 private static bool idle = false;
8592 private async Task RefreshTasktrayIcon()
8595 await this.Colorize();
8597 if (!TimerRefreshIcon.Enabled) return;
8598 //Static usCheckCnt As int = 0
8600 //Static iconDlListTopItem As ListViewItem = null
8602 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8603 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8605 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8607 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8613 //if (usCheckCnt > 300) //1min
8616 // if (!this.IsReceivedUserStream)
8618 // TraceOut("ReconnectUserStream");
8619 // tw.ReconnectUserStream();
8623 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8625 if (iconCnt >= this.NIconRefresh.Length)
8633 SaveConfigsAll(true);
8638 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8640 _myStatusError = false;
8644 TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8645 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8647 if (blinkCnt > 0) return;
8649 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8651 NotifyIcon1.Icon = ReplyIcon;
8655 NotifyIcon1.Icon = ReplyIconBlink;
8663 //優先度:エラー→オフライン→アイドル
8667 NotifyIcon1.Icon = NIconAtRed;
8670 if (_myStatusOnline)
8672 NotifyIcon1.Icon = NIconAt;
8676 NotifyIcon1.Icon = NIconAtSmoke;
8680 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8683 await this.RefreshTasktrayIcon();
8686 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8688 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8689 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8691 if (ListTab != null && ListTab.SelectedTab != null)
8692 _rclickTabName = ListTab.SelectedTab.Text;
8697 if (_statuses == null) return;
8698 if (_statuses.Tabs == null) return;
8700 TabClass tb = _statuses.Tabs[_rclickTabName];
8701 if (tb == null) return;
8703 NotifyDispMenuItem.Checked = tb.Notify;
8704 this.NotifyTbMenuItem.Checked = tb.Notify;
8706 soundfileListup = true;
8707 SoundFileComboBox.Items.Clear();
8708 this.SoundFileTbComboBox.Items.Clear();
8709 SoundFileComboBox.Items.Add("");
8710 this.SoundFileTbComboBox.Items.Add("");
8711 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8712 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8714 oDir = oDir.GetDirectories("Sounds")[0];
8716 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8718 SoundFileComboBox.Items.Add(oFile.Name);
8719 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8721 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8722 if (idx == -1) idx = 0;
8723 SoundFileComboBox.SelectedIndex = idx;
8724 this.SoundFileTbComboBox.SelectedIndex = idx;
8725 soundfileListup = false;
8726 UreadManageMenuItem.Checked = tb.UnreadManage;
8727 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8729 TabMenuControl(_rclickTabName);
8732 private void TabMenuControl(string tabName)
8734 var tabInfo = _statuses.GetTabByName(tabName);
8736 this.FilterEditMenuItem.Enabled = true;
8737 this.EditRuleTbMenuItem.Enabled = true;
8739 if (tabInfo.IsDefaultTabType)
8741 this.ProtectTabMenuItem.Enabled = false;
8742 this.ProtectTbMenuItem.Enabled = false;
8746 this.ProtectTabMenuItem.Enabled = true;
8747 this.ProtectTbMenuItem.Enabled = true;
8750 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8752 this.ProtectTabMenuItem.Checked = true;
8753 this.ProtectTbMenuItem.Checked = true;
8754 this.DeleteTabMenuItem.Enabled = false;
8755 this.DeleteTbMenuItem.Enabled = false;
8759 this.ProtectTabMenuItem.Checked = false;
8760 this.ProtectTbMenuItem.Checked = false;
8761 this.DeleteTabMenuItem.Enabled = true;
8762 this.DeleteTbMenuItem.Enabled = true;
8766 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8768 var checkState = ((ToolStripMenuItem)sender).Checked;
8771 this.ProtectTbMenuItem.Checked = checkState;
8772 this.ProtectTabMenuItem.Checked = checkState;
8775 this.DeleteTabMenuItem.Enabled = !checkState;
8776 this.DeleteTbMenuItem.Enabled = !checkState;
8778 if (string.IsNullOrEmpty(_rclickTabName)) return;
8779 _statuses.Tabs[_rclickTabName].Protected = checkState;
8784 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8786 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8787 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8789 if (string.IsNullOrEmpty(_rclickTabName)) return;
8790 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8795 public void ChangeTabUnreadManage(string tabName, bool isManage)
8797 var idx = this.GetTabPageIndex(tabName);
8801 _statuses.Tabs[tabName].UnreadManage = isManage;
8802 if (this._cfgCommon.TabIconDisp)
8804 if (_statuses.Tabs[tabName].UnreadCount > 0)
8805 ListTab.TabPages[idx].ImageIndex = 0;
8807 ListTab.TabPages[idx].ImageIndex = -1;
8810 if (_curTab.Text == tabName)
8812 this.PurgeListViewItemCache();
8816 SetMainWindowTitle();
8817 SetStatusLabelUrl();
8818 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8821 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8823 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8824 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8826 if (string.IsNullOrEmpty(_rclickTabName)) return;
8828 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8833 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8835 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8837 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8842 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8844 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8846 RemoveSpecifiedTab(_rclickTabName, true);
8850 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8852 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8854 using (var fltDialog = new FilterDialog())
8856 fltDialog.Owner = this;
8857 fltDialog.SetCurrent(_rclickTabName);
8858 fltDialog.ShowDialog(this);
8860 this.TopMost = this._cfgCommon.AlwaysTop;
8862 this.ApplyPostFilters();
8866 private void AddTabMenuItem_Click(object sender, EventArgs e)
8868 string tabName = null;
8869 MyCommon.TabUsageType tabUsage;
8870 using (InputTabName inputName = new InputTabName())
8872 inputName.TabName = _statuses.MakeTabName("MyTab");
8873 inputName.IsShowUsage = true;
8874 inputName.ShowDialog();
8875 if (inputName.DialogResult == DialogResult.Cancel) return;
8876 tabName = inputName.TabName;
8877 tabUsage = inputName.Usage;
8879 this.TopMost = this._cfgCommon.AlwaysTop;
8880 if (!string.IsNullOrEmpty(tabName))
8883 ListElement list = null;
8884 if (tabUsage == MyCommon.TabUsageType.Lists)
8886 using (ListAvailable listAvail = new ListAvailable())
8888 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8889 if (listAvail.SelectedList == null) return;
8890 list = listAvail.SelectedList;
8893 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8895 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8896 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8902 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8904 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8905 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8907 if (tabUsage == MyCommon.TabUsageType.Lists)
8909 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8910 var tab = this._statuses.Tabs[this._curTab.Text];
8911 this.GetListTimelineAsync(tab);
8917 private void TabMenuItem_Click(object sender, EventArgs e)
8919 using (var fltDialog = new FilterDialog())
8921 fltDialog.Owner = this;
8924 foreach (int idx in _curList.SelectedIndices)
8928 if (!SelectTab(out tabName)) return;
8930 fltDialog.SetCurrent(tabName);
8931 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8933 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8937 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8939 fltDialog.ShowDialog(this);
8940 this.TopMost = this._cfgCommon.AlwaysTop;
8944 this.ApplyPostFilters();
8946 if (this.ListTab.SelectedTab != null &&
8947 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8949 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8953 protected override bool ProcessDialogKey(Keys keyData)
8955 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8956 if ((keyData & Keys.KeyCode) == Keys.Enter)
8958 if (StatusText.Focused)
8960 bool _NewLine = false;
8963 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8965 if (StatusText.Multiline)
8967 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8969 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8973 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8977 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8979 if (StatusText.Multiline)
8981 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8983 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8987 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8993 if (StatusText.Multiline)
8995 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8997 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8998 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
9002 if (((keyData & Keys.Shift) == Keys.Shift) ||
9003 (((keyData & Keys.Control) != Keys.Control) &&
9004 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
9010 int pos1 = StatusText.SelectionStart;
9011 if (StatusText.SelectionLength > 0)
9013 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
9015 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
9016 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
9021 PostButton_Click(null, null);
9025 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
9026 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
9027 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
9029 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
9034 return base.ProcessDialogKey(keyData);
9037 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9039 MakeReplyOrDirectStatus(false, true, true);
9042 private void IDRuleMenuItem_Click(object sender, EventArgs e)
9047 if (_curList.SelectedIndices.Count == 0) return;
9050 if (!SelectTab(out tabName)) return;
9052 var tab = this._statuses.Tabs[tabName];
9056 if (tab.TabType != MyCommon.TabUsageType.Mute)
9058 this.MoveOrCopy(out mv, out mk);
9062 // ミュートタブでは常に MoveMatches を true にする
9067 List<string> ids = new List<string>();
9068 foreach (int idx in _curList.SelectedIndices)
9070 PostClass post = _statuses.Tabs[_curTab.Text][idx];
9071 if (!ids.Contains(post.ScreenName))
9073 PostFilterRule fc = new PostFilterRule();
9074 ids.Add(post.ScreenName);
9075 if (post.RetweetedId == null)
9077 fc.FilterName = post.ScreenName;
9081 fc.FilterName = post.RetweetedBy;
9083 fc.UseNameField = true;
9084 fc.MoveMatches = mv;
9085 fc.MarkMatches = mk;
9086 fc.UseRegex = false;
9087 fc.FilterByUrl = false;
9093 List<string> atids = new List<string>();
9094 foreach (string id in ids)
9096 atids.Add("@" + id);
9098 int cnt = AtIdSupl.ItemCount;
9099 AtIdSupl.AddRangeItem(atids.ToArray());
9100 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
9103 this.ApplyPostFilters();
9107 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
9109 if (this._curList.SelectedIndices.Count == 0)
9112 // タブ選択ダイアログを表示(or追加)
9114 if (!this.SelectTab(out tabName))
9117 var currentTab = this._statuses.Tabs[this._curTab.Text];
9118 var filterTab = this._statuses.Tabs[tabName];
9122 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
9124 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
9125 this.MoveOrCopy(out mv, out mk);
9129 // ミュートタブでは常に MoveMatches を true にする
9134 // 振り分けルールに追加するSource
9135 var sources = new HashSet<string>();
9137 foreach (var idx in this._curList.SelectedIndices.Cast<int>())
9139 var post = currentTab[idx];
9140 var filterSource = post.Source;
9142 if (sources.Add(filterSource))
9144 var filter = new PostFilterRule
9146 FilterSource = filterSource,
9150 FilterByUrl = false,
9152 filterTab.AddFilter(filter);
9156 this.ApplyPostFilters();
9157 this.SaveConfigsTabs();
9160 private bool SelectTab(out string tabName)
9167 using (var dialog = new TabsDialog(_statuses))
9169 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9171 var selectedTab = dialog.SelectedTab;
9172 tabName = selectedTab == null ? null : selectedTab.TabName;
9175 ListTab.SelectedTab.Focus();
9177 if (tabName == null)
9179 using (InputTabName inputName = new InputTabName())
9181 inputName.TabName = _statuses.MakeTabName("MyTab");
9182 inputName.ShowDialog();
9183 if (inputName.DialogResult == DialogResult.Cancel) return false;
9184 tabName = inputName.TabName;
9186 this.TopMost = this._cfgCommon.AlwaysTop;
9187 if (!string.IsNullOrEmpty(tabName))
9189 if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9191 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9192 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9210 private void MoveOrCopy(out bool move, out bool mark)
9214 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9215 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9223 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9224 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9234 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9239 private void CopyURLMenuItem_Click(object sender, EventArgs e)
9244 private void SelectAllMenuItem_Click(object sender, EventArgs e)
9246 if (StatusText.Focused)
9249 StatusText.SelectAll();
9253 // ListView上でのCtrl+A
9254 NativeMethods.SelectAllItems(this._curList);
9258 private void MoveMiddle()
9264 if (_curList.SelectedIndices.Count == 0) return;
9266 int idx = _curList.SelectedIndices[0];
9268 _item = _curList.GetItemAt(0, 25);
9274 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9276 idx2 = _curList.VirtualListSize - 1;
9280 idx -= Math.Abs(idx1 - idx2) / 2;
9281 if (idx < 0) idx = 0;
9283 _curList.EnsureVisible(_curList.VirtualListSize - 1);
9284 _curList.EnsureVisible(idx);
9287 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
9289 var linkElements = this.PostBrowser.Document.Links.Cast<HtmlElement>()
9290 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
9293 if (linkElements.Length > 0)
9295 UrlDialog.ClearUrl();
9297 string openUrlStr = "";
9299 if (linkElements.Length == 1)
9301 // ツイートに含まれる URL が 1 つのみの場合
9302 // => OpenURL ダイアログを表示せずにリンクを開く
9307 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
9309 catch (ArgumentException)
9318 if (string.IsNullOrEmpty(urlStr)) return;
9319 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9321 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
9322 await this.OpenUriAsync(new Uri(openUrlStr));
9326 // ツイートに含まれる URL が複数ある場合
9327 // => OpenURL を表示しユーザーが選択したリンクを開く
9329 foreach (var linkElm in linkElements)
9332 string linkText = "";
9336 urlStr = linkElm.GetAttribute("title");
9337 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9338 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9339 linkText = linkElm.InnerText;
9341 catch (ArgumentException)
9350 if (string.IsNullOrEmpty(urlStr)) continue;
9351 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9355 if (UrlDialog.ShowDialog() == DialogResult.OK)
9357 openUrlStr = UrlDialog.SelectedUrl;
9359 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
9360 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
9367 this.TopMost = this._cfgCommon.AlwaysTop;
9372 private void ClearTabMenuItem_Click(object sender, EventArgs e)
9374 if (string.IsNullOrEmpty(_rclickTabName)) return;
9375 ClearTab(_rclickTabName, true);
9378 private void ClearTab(string tabName, bool showWarning)
9382 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9383 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9389 _statuses.ClearTabIds(tabName);
9390 if (ListTab.SelectedTab.Text == tabName)
9393 _anchorFlag = false;
9394 this.PurgeListViewItemCache();
9398 foreach (TabPage tb in ListTab.TabPages)
9400 if (tb.Text == tabName)
9403 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9407 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9409 SetMainWindowTitle();
9410 SetStatusLabelUrl();
9413 private static long followers = 0;
9415 private void SetMainWindowTitle()
9418 StringBuilder ttl = new StringBuilder(256);
9421 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9422 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9423 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9424 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9426 foreach (var tab in _statuses.Tabs.Values)
9428 ur += tab.UnreadCount;
9433 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9434 ttl.Append(Application.ProductName);
9436 switch (this._cfgCommon.DispLatestPost)
9438 case MyCommon.DispTitleEnum.Ver:
9439 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9441 case MyCommon.DispTitleEnum.Post:
9442 if (_history != null && _history.Count > 1)
9443 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9445 case MyCommon.DispTitleEnum.UnreadRepCount:
9446 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9448 case MyCommon.DispTitleEnum.UnreadAllCount:
9449 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9451 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9452 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9454 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9455 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9457 case MyCommon.DispTitleEnum.OwnStatus:
9458 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9459 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9465 this.Text = ttl.ToString();
9467 catch (AccessViolationException)
9469 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9473 private string GetStatusLabelText()
9476 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9477 if (_statuses == null) return "";
9478 TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9479 TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9480 if (tbRep == null || tbDm == null) return "";
9481 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9486 StringBuilder slbl = new StringBuilder(256);
9489 foreach (var tab in _statuses.Tabs.Values)
9491 ur += tab.UnreadCount;
9493 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9495 tur = tab.UnreadCount;
9506 UnreadAtCounter = urat;
9508 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9509 if (this._cfgCommon.TimelinePeriod == 0)
9511 slbl.Append(Properties.Resources.SetStatusLabelText2);
9515 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9517 return slbl.ToString();
9520 private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9524 if (this.InvokeRequired && !this.IsDisposed)
9526 this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9530 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9531 SetApiStatusLabel(endpointName);
9534 catch (ObjectDisposedException)
9538 catch (InvalidOperationException)
9544 private void SetApiStatusLabel(string endpointName = null)
9546 if (_curTab == null)
9548 this.toolStripApiGauge.ApiEndpoint = null;
9552 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9554 if (endpointName == null)
9559 case MyCommon.TabUsageType.Home:
9560 case MyCommon.TabUsageType.UserDefined:
9561 endpointName = "/statuses/home_timeline";
9564 case MyCommon.TabUsageType.Mentions:
9565 endpointName = "/statuses/mentions_timeline";
9568 case MyCommon.TabUsageType.Favorites:
9569 endpointName = "/favorites/list";
9572 case MyCommon.TabUsageType.DirectMessage:
9573 endpointName = "/direct_messages";
9576 case MyCommon.TabUsageType.UserTimeline:
9577 endpointName = "/statuses/user_timeline";
9580 case MyCommon.TabUsageType.Lists:
9581 endpointName = "/lists/statuses";
9584 case MyCommon.TabUsageType.PublicSearch:
9585 endpointName = "/search/tweets";
9588 case MyCommon.TabUsageType.Related:
9589 endpointName = "/statuses/show/:id";
9596 this.toolStripApiGauge.ApiEndpoint = endpointName;
9600 // 表示中のタブに関連する endpoint であれば更新
9603 switch (endpointName)
9605 case "/statuses/home_timeline":
9606 update = tabType == MyCommon.TabUsageType.Home ||
9607 tabType == MyCommon.TabUsageType.UserDefined;
9610 case "/statuses/mentions_timeline":
9611 update = tabType == MyCommon.TabUsageType.Mentions;
9614 case "/favorites/list":
9615 update = tabType == MyCommon.TabUsageType.Favorites;
9618 case "/direct_messages:":
9619 update = tabType == MyCommon.TabUsageType.DirectMessage;
9622 case "/statuses/user_timeline":
9623 update = tabType == MyCommon.TabUsageType.UserTimeline;
9626 case "/lists/statuses":
9627 update = tabType == MyCommon.TabUsageType.Lists;
9630 case "/search/tweets":
9631 update = tabType == MyCommon.TabUsageType.PublicSearch;
9634 case "/statuses/show/:id":
9635 update = tabType == MyCommon.TabUsageType.Related;
9644 this.toolStripApiGauge.ApiEndpoint = endpointName;
9650 private void SetStatusLabelUrl()
9652 StatusLabelUrl.Text = GetStatusLabelText();
9655 public void SetStatusLabel(string text)
9657 StatusLabel.Text = text;
9660 private static StringBuilder ur = new StringBuilder(64);
9662 private void SetNotifyIconText()
9664 // タスクトレイアイコンのツールチップテキスト書き換え
9666 ur.Remove(0, ur.Length);
9667 if (this._cfgCommon.DispUsername)
9669 ur.Append(tw.Username);
9672 ur.Append(Application.ProductName);
9674 ur.Append("(Debug Build)");
9676 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9679 ur.Append(UnreadCounter);
9681 ur.Append(UnreadAtCounter);
9684 NotifyIcon1.Text = ur.ToString();
9687 internal void CheckReplyTo(string StatusText)
9691 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9693 foreach (Match hm in m)
9695 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9697 hstr += "#" + hm.Result("$3") + " ";
9698 HashSupl.AddItem("#" + hm.Result("$3"));
9701 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9703 hstr += HashMgr.UseHash;
9705 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9707 // 本当にリプライ先指定すべきかどうかの判定
9708 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9710 if (this._cfgCommon.UseAtIdSupplement)
9712 int bCnt = AtIdSupl.ItemCount;
9713 foreach (Match mid in m)
9715 AtIdSupl.AddItem(mid.Result("${id}"));
9717 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9720 // リプライ先ステータスIDの指定がない場合は指定しない
9721 if (this.inReplyTo == null)
9725 // 次の条件を満たす場合に in_reply_to_status_id 指定
9726 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9727 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9728 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9732 var inReplyToScreenName = this.inReplyTo.Item2;
9733 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9735 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9739 foreach (Match mid in m)
9741 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9746 this.inReplyTo = null;
9749 private void TweenMain_Resize(object sender, EventArgs e)
9751 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9753 this.Visible = false;
9755 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9757 // 現在の DPI と設定保存時の DPI との比を取得する
9758 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9760 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9761 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9762 this.DesktopLocation = _cfgLocal.FormLocation;
9763 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9766 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9767 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9768 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9770 this.SplitContainer1.SplitterDistance = splitterDistance;
9774 StatusText.Multiline = _cfgLocal.StatusMultiline;
9775 if (StatusText.Multiline)
9777 var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9778 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9779 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9781 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9783 StatusText.Height = statusTextHeight;
9787 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9789 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9793 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9794 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9796 this.SplitContainer3.SplitterDistance = previewDistance;
9799 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9800 this.SplitContainer3.Panel2Collapsed = true;
9802 _initialLayout = false;
9804 if (this.WindowState != FormWindowState.Minimized)
9806 _formWindowState = this.WindowState;
9810 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9812 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9813 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9814 if (PlaySoundMenuItem.Checked)
9816 this._cfgCommon.PlaySound = true;
9820 this._cfgCommon.PlaySound = false;
9822 ModifySettingCommon = true;
9825 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9827 if (this._initialLayout)
9830 int splitterDistance;
9831 switch (this.WindowState)
9833 case FormWindowState.Normal:
9834 splitterDistance = this.SplitContainer1.SplitterDistance;
9836 case FormWindowState.Maximized:
9837 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9838 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9839 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9840 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9846 this._mySpDis = splitterDistance;
9847 this.ModifySettingLocal = true;
9850 private async Task doRepliedStatusOpen()
9852 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9854 if (MyCommon.IsKeyDown(Keys.Shift))
9856 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9859 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9861 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9862 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9866 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9868 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9869 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9870 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9873 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9878 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9880 await this.doRepliedStatusOpen();
9884 /// UserPicture.Image に設定されている画像を破棄します。
9886 private void ClearUserPicture()
9888 if (this.UserPicture.Image != null)
9890 var oldImage = this.UserPicture.Image;
9891 this.UserPicture.Image = null;
9896 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9898 //発言詳細のアイコン右クリック時のメニュー制御
9899 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9901 string name = _curPost.ImageUrl;
9902 if (name != null && name.Length > 0)
9904 int idx = name.LastIndexOf('/');
9907 name = Path.GetFileName(name.Substring(idx));
9908 if (name.Contains("_normal.") || name.EndsWith("_normal", StringComparison.Ordinal))
9910 name = name.Replace("_normal", "");
9911 this.IconNameToolStripMenuItem.Text = name;
9912 this.IconNameToolStripMenuItem.Enabled = true;
9916 this.IconNameToolStripMenuItem.Enabled = false;
9917 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9922 this.IconNameToolStripMenuItem.Enabled = false;
9923 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9926 this.ReloadIconToolStripMenuItem.Enabled = true;
9928 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9930 this.SaveIconPictureToolStripMenuItem.Enabled = true;
9934 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9939 this.IconNameToolStripMenuItem.Enabled = false;
9940 this.ReloadIconToolStripMenuItem.Enabled = false;
9941 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9942 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9947 this.IconNameToolStripMenuItem.Enabled = false;
9948 this.ReloadIconToolStripMenuItem.Enabled = false;
9949 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9950 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9952 if (NameLabel.Tag != null)
9954 string id = (string)NameLabel.Tag;
9955 if (id == tw.Username)
9957 FollowToolStripMenuItem.Enabled = false;
9958 UnFollowToolStripMenuItem.Enabled = false;
9959 ShowFriendShipToolStripMenuItem.Enabled = false;
9960 ShowUserStatusToolStripMenuItem.Enabled = true;
9961 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9962 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9963 ListManageUserContextToolStripMenuItem3.Enabled = true;
9967 FollowToolStripMenuItem.Enabled = true;
9968 UnFollowToolStripMenuItem.Enabled = true;
9969 ShowFriendShipToolStripMenuItem.Enabled = true;
9970 ShowUserStatusToolStripMenuItem.Enabled = true;
9971 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9972 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9973 ListManageUserContextToolStripMenuItem3.Enabled = true;
9978 FollowToolStripMenuItem.Enabled = false;
9979 UnFollowToolStripMenuItem.Enabled = false;
9980 ShowFriendShipToolStripMenuItem.Enabled = false;
9981 ShowUserStatusToolStripMenuItem.Enabled = false;
9982 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9983 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9984 ListManageUserContextToolStripMenuItem3.Enabled = false;
9988 private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9990 if (_curPost == null) return;
9991 string name = _curPost.ImageUrl;
9992 await this.OpenUriInBrowserAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9995 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9997 if (this._curPost == null) return;
9999 await this.UserPicture.SetImageFromTask(async () =>
10001 var imageUrl = this._curPost.ImageUrl;
10003 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
10004 .ConfigureAwait(false);
10006 return await image.CloneAsync()
10007 .ConfigureAwait(false);
10011 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10013 if (_curPost == null) return;
10014 string name = _curPost.ImageUrl;
10015 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
10017 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
10019 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10025 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10027 if (_curPost == null) return;
10028 string name = _curPost.ImageUrl;
10030 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
10032 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10036 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
10038 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
10040 using (Graphics g = Graphics.FromImage(bmp2))
10042 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
10043 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
10045 bmp2.Save(this.SaveFileDialog1.FileName);
10051 //処理中にキャッシュアウトする可能性あり
10056 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
10058 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
10059 if (multiline != this.StatusText.Multiline)
10061 this.StatusText.Multiline = multiline;
10062 MultiLineMenuItem.Checked = multiline;
10063 ModifySettingLocal = true;
10067 private void StatusText_MultilineChanged(object sender, EventArgs e)
10069 if (this.StatusText.Multiline)
10070 this.StatusText.ScrollBars = ScrollBars.Vertical;
10072 this.StatusText.ScrollBars = ScrollBars.None;
10074 ModifySettingLocal = true;
10077 private void MultiLineMenuItem_Click(object sender, EventArgs e)
10080 StatusText.Multiline = MultiLineMenuItem.Checked;
10081 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
10082 if (MultiLineMenuItem.Checked)
10084 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
10085 SplitContainer2.SplitterDistance = 0;
10087 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
10091 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
10093 ModifySettingLocal = true;
10096 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
10098 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
10099 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
10101 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
10102 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
10103 //Appendix A. Collected ABNF for URI
10104 //http://www.ietf.org/rfc/rfc3986.txt
10106 string result = "";
10108 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
10110 if (StatusText.SelectionLength > 0)
10112 string tmp = StatusText.SelectedText;
10113 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
10114 if (tmp.StartsWith("http"))
10116 // 文字列が選択されている場合はその文字列について処理
10118 //nico.ms使用、nicovideoにマッチしたら変換
10119 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10121 result = nicoms.Shorten(tmp);
10123 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10125 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10128 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10129 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10130 result = resultUri.AbsoluteUri;
10132 catch (WebApiException e)
10134 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10137 catch (UriFormatException e)
10139 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10148 if (!string.IsNullOrEmpty(result))
10150 urlUndo undotmp = new urlUndo();
10152 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
10153 StatusText.SelectedText = result;
10156 undotmp.Before = tmp;
10157 undotmp.After = result;
10159 if (urlUndoBuffer == null)
10161 urlUndoBuffer = new List<urlUndo>();
10162 UrlUndoToolStripMenuItem.Enabled = true;
10165 urlUndoBuffer.Add(undotmp);
10171 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
10172 @"(?<url>(?<protocol>https?://)" +
10173 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
10174 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
10175 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
10176 // 正規表現にマッチしたURL文字列をtinyurl化
10177 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
10179 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
10180 string tmp = mt.Result("${url}");
10181 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
10182 urlUndo undotmp = new urlUndo();
10185 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10187 //nico.ms使用、nicovideoにマッチしたら変換
10188 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10190 result = nicoms.Shorten(tmp);
10192 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10194 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10197 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10198 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10199 result = resultUri.AbsoluteUri;
10201 catch (HttpRequestException e)
10203 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
10204 // のように長いので「:」が含まれていればそれ以降のみを抽出する
10205 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
10207 this.StatusLabel.Text = Converter_Type + ":" + message;
10210 catch (WebApiException e)
10212 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10215 catch (UriFormatException e)
10217 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10226 if (!string.IsNullOrEmpty(result))
10228 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10229 StatusText.SelectedText = result;
10231 undotmp.Before = mt.Result("${url}");
10232 undotmp.After = result;
10234 if (urlUndoBuffer == null)
10236 urlUndoBuffer = new List<urlUndo>();
10237 UrlUndoToolStripMenuItem.Enabled = true;
10240 urlUndoBuffer.Add(undotmp);
10248 private void doUrlUndo()
10250 if (urlUndoBuffer != null)
10252 string tmp = StatusText.Text;
10253 foreach (urlUndo data in urlUndoBuffer)
10255 tmp = tmp.Replace(data.After, data.Before);
10257 StatusText.Text = tmp;
10258 urlUndoBuffer = null;
10259 UrlUndoToolStripMenuItem.Enabled = false;
10260 StatusText.SelectionStart = 0;
10261 StatusText.SelectionLength = 0;
10265 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10267 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10270 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10272 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10275 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10277 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10280 private async void UxnuMenuItem_Click(object sender, EventArgs e)
10282 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10285 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10287 if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
10289 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
10290 Random rnd = new Random();
10291 // 前回使用した短縮URLサービス以外を選択する
10294 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10296 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10297 await UrlConvertAsync(svc);
10301 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10306 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10308 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10309 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10310 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10311 ModifySettingCommon = true;
10314 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10316 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10317 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10318 _cfgCommon.ListLock = ListLockMenuItem.Checked;
10319 ModifySettingCommon = true;
10322 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10324 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10325 MenuStrip1.Tag = new Object();
10326 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10329 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10331 if (this.Tag != null) // 設定された戻り先へ遷移
10333 if (this.Tag == this.ListTab.SelectedTab)
10334 ((Control)this.ListTab.SelectedTab.Tag).Select();
10336 ((Control)this.Tag).Select();
10338 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10340 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10342 this.Tag = ListTab.SelectedTab.Tag;
10343 ((Control)this.Tag).Select();
10346 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10347 MenuStrip1.Tag = null;
10350 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10352 DetailsListView lst = (DetailsListView)sender;
10353 if (_cfgLocal == null) return;
10357 _cfgLocal.Width1 = lst.Columns[0].Width;
10358 _cfgLocal.Width3 = lst.Columns[1].Width;
10362 int[] darr = new int[lst.Columns.Count];
10363 for (int i = 0; i < lst.Columns.Count; i++)
10365 darr[lst.Columns[i].DisplayIndex] = i;
10367 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10369 for (int i = 0; i < lst.Columns.Count; i++)
10374 _cfgLocal.DisplayIndex1 = i;
10377 _cfgLocal.DisplayIndex2 = i;
10380 _cfgLocal.DisplayIndex3 = i;
10383 _cfgLocal.DisplayIndex4 = i;
10386 _cfgLocal.DisplayIndex5 = i;
10389 _cfgLocal.DisplayIndex6 = i;
10392 _cfgLocal.DisplayIndex7 = i;
10395 _cfgLocal.DisplayIndex8 = i;
10399 _cfgLocal.Width1 = lst.Columns[0].Width;
10400 _cfgLocal.Width2 = lst.Columns[1].Width;
10401 _cfgLocal.Width3 = lst.Columns[2].Width;
10402 _cfgLocal.Width4 = lst.Columns[3].Width;
10403 _cfgLocal.Width5 = lst.Columns[4].Width;
10404 _cfgLocal.Width6 = lst.Columns[5].Width;
10405 _cfgLocal.Width7 = lst.Columns[6].Width;
10406 _cfgLocal.Width8 = lst.Columns[7].Width;
10408 ModifySettingLocal = true;
10409 _isColumnChanged = true;
10412 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10414 DetailsListView lst = (DetailsListView)sender;
10415 if (_cfgLocal == null) return;
10418 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10420 _cfgLocal.Width1 = lst.Columns[0].Width;
10421 ModifySettingLocal = true;
10422 _isColumnChanged = true;
10424 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10426 _cfgLocal.Width3 = lst.Columns[1].Width;
10427 ModifySettingLocal = true;
10428 _isColumnChanged = true;
10433 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10435 _cfgLocal.Width1 = lst.Columns[0].Width;
10436 ModifySettingLocal = true;
10437 _isColumnChanged = true;
10439 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10441 _cfgLocal.Width2 = lst.Columns[1].Width;
10442 ModifySettingLocal = true;
10443 _isColumnChanged = true;
10445 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10447 _cfgLocal.Width3 = lst.Columns[2].Width;
10448 ModifySettingLocal = true;
10449 _isColumnChanged = true;
10451 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10453 _cfgLocal.Width4 = lst.Columns[3].Width;
10454 ModifySettingLocal = true;
10455 _isColumnChanged = true;
10457 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10459 _cfgLocal.Width5 = lst.Columns[4].Width;
10460 ModifySettingLocal = true;
10461 _isColumnChanged = true;
10463 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10465 _cfgLocal.Width6 = lst.Columns[5].Width;
10466 ModifySettingLocal = true;
10467 _isColumnChanged = true;
10469 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10471 _cfgLocal.Width7 = lst.Columns[6].Width;
10472 ModifySettingLocal = true;
10473 _isColumnChanged = true;
10475 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10477 _cfgLocal.Width8 = lst.Columns[7].Width;
10478 ModifySettingLocal = true;
10479 _isColumnChanged = true;
10482 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10485 // SaveConfigsLocal();
10489 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10492 string _selText = this.PostBrowser.GetSelectedText();
10495 Clipboard.SetDataObject(_selText, false, 5, 100);
10497 catch (Exception ex)
10499 MessageBox.Show(ex.Message);
10503 private async Task doSearchToolStrip(string url)
10505 //発言詳細で「選択文字列で検索」(選択文字列取得)
10506 string _selText = this.PostBrowser.GetSelectedText();
10508 if (_selText != null)
10510 if (url == Properties.Resources.SearchItem4Url)
10513 AddNewTabForSearch(_selText);
10517 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10518 await this.OpenUriInBrowserAsync(tmp);
10522 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10525 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10528 private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10530 await this.doSearchToolStrip(Properties.Resources.SearchItem1Url);
10533 private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10535 await this.doSearchToolStrip(Properties.Resources.SearchItem2Url);
10538 private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10540 await this.doSearchToolStrip(Properties.Resources.SearchItem4Url);
10543 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10547 foreach (var link in this.PostBrowser.Document.Links.Cast<HtmlElement>())
10549 if (link.GetAttribute("href") == this._postBrowserStatusText)
10551 var linkStr = link.GetAttribute("title");
10552 if (string.IsNullOrEmpty(linkStr))
10553 linkStr = link.GetAttribute("href");
10555 Clipboard.SetDataObject(linkStr, false, 5, 100);
10560 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10562 catch (Exception ex)
10564 MessageBox.Show(ex.Message);
10568 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10570 // URLコピーの項目の表示/非表示
10571 if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal))
10573 this._postBrowserStatusText = PostBrowser.StatusText;
10574 string name = GetUserId();
10575 UrlCopyContextMenuItem.Enabled = true;
10578 FollowContextMenuItem.Enabled = true;
10579 RemoveContextMenuItem.Enabled = true;
10580 FriendshipContextMenuItem.Enabled = true;
10581 ShowUserStatusContextMenuItem.Enabled = true;
10582 SearchPostsDetailToolStripMenuItem.Enabled = true;
10583 IdFilterAddMenuItem.Enabled = true;
10584 ListManageUserContextToolStripMenuItem.Enabled = true;
10585 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10589 FollowContextMenuItem.Enabled = false;
10590 RemoveContextMenuItem.Enabled = false;
10591 FriendshipContextMenuItem.Enabled = false;
10592 ShowUserStatusContextMenuItem.Enabled = false;
10593 SearchPostsDetailToolStripMenuItem.Enabled = false;
10594 IdFilterAddMenuItem.Enabled = false;
10595 ListManageUserContextToolStripMenuItem.Enabled = false;
10596 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10599 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10600 UseHashtagMenuItem.Enabled = true;
10602 UseHashtagMenuItem.Enabled = false;
10606 this._postBrowserStatusText = "";
10607 UrlCopyContextMenuItem.Enabled = false;
10608 FollowContextMenuItem.Enabled = false;
10609 RemoveContextMenuItem.Enabled = false;
10610 FriendshipContextMenuItem.Enabled = false;
10611 ShowUserStatusContextMenuItem.Enabled = false;
10612 SearchPostsDetailToolStripMenuItem.Enabled = false;
10613 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10614 UseHashtagMenuItem.Enabled = false;
10615 IdFilterAddMenuItem.Enabled = false;
10616 ListManageUserContextToolStripMenuItem.Enabled = false;
10618 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10619 string _selText = this.PostBrowser.GetSelectedText();
10620 if (_selText == null)
10622 SelectionSearchContextMenuItem.Enabled = false;
10623 SelectionCopyContextMenuItem.Enabled = false;
10624 SelectionTranslationToolStripMenuItem.Enabled = false;
10628 SelectionSearchContextMenuItem.Enabled = true;
10629 SelectionCopyContextMenuItem.Enabled = true;
10630 SelectionTranslationToolStripMenuItem.Enabled = true;
10632 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10633 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10634 bool fAllFlag = false;
10635 foreach (Match mu in ma)
10637 if (mu.Result("${ScreenName}").ToLowerInvariant() != tw.Username.ToLowerInvariant())
10643 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10645 if (_curPost == null)
10646 TranslationToolStripMenuItem.Enabled = false;
10648 TranslationToolStripMenuItem.Enabled = true;
10653 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10655 //発言詳細の選択文字列で現在のタブを検索
10656 string _selText = this.PostBrowser.GetSelectedText();
10658 if (_selText != null)
10660 var searchOptions = new SearchWordDialog.SearchOptions(
10661 SearchWordDialog.SearchType.Timeline,
10664 caseSensitive: false,
10667 this.SearchDialog.ResultOptions = searchOptions;
10670 searchOptions.Query,
10671 searchOptions.CaseSensitive,
10672 searchOptions.UseRegex,
10673 SEARCHTYPE.NextSearch);
10677 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10679 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10680 ModifySettingLocal = true;
10683 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10685 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10687 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10689 SelectMedia_DragDrop(e);
10692 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10694 var url = GetUrlFromDataObject(e.Data);
10697 if (url.Item2 == null)
10698 appendText = url.Item1;
10700 appendText = url.Item2 + " " + url.Item1;
10702 if (this.StatusText.TextLength == 0)
10703 this.StatusText.Text = appendText;
10705 this.StatusText.Text += " " + appendText;
10707 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10709 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10711 this.StatusText.Text += text;
10713 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10715 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10716 if (data != null) StatusText.Text += data;
10721 /// IDataObject から URL とタイトルの対を取得します
10724 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10726 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10727 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10728 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10730 if (data.GetDataPresent("text/x-moz-url"))
10732 // Firefox, Google Chrome で利用可能
10733 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10735 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10737 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10738 if (lines.Length < 2)
10739 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
10741 return new Tuple<string, string>(lines[0], lines[1]);
10744 else if (data.GetDataPresent("IESiteModeToUrl"))
10746 // Internet Exproler 用
10747 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10749 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10751 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10752 if (lines.Length < 2)
10753 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
10755 return new Tuple<string, string>(lines[0], lines[1]);
10758 else if (data.GetDataPresent("UniformResourceLocatorW"))
10762 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10764 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10765 return new Tuple<string, string>(url, null);
10769 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10772 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10774 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10776 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10778 SelectMedia_DragEnter(e);
10782 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10784 e.Effect = DragDropEffects.Copy;
10787 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10789 e.Effect = DragDropEffects.Copy;
10792 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10794 e.Effect = DragDropEffects.Copy;
10798 e.Effect = DragDropEffects.None;
10801 private void TweenMain_DragOver(object sender, DragEventArgs e)
10805 public bool IsNetworkAvailable()
10808 nw = MyCommon.IsNetworkAvailable();
10809 _myStatusOnline = nw;
10813 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
10815 var uriStr = uri.AbsoluteUri;
10817 // OpenTween 内部で使用する URL
10818 if (uri.Authority == "opentween")
10820 await this.OpenInternalUriAsync(uri);
10824 // ハッシュタグを含む Twitter 検索
10825 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
10827 // ハッシュタグの場合は、タブで開く
10828 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
10829 var pos = unescapedQuery.IndexOf('#');
10830 if (pos == -1) return;
10832 var hash = unescapedQuery.Substring(pos);
10833 this.HashSupl.AddItem(hash);
10834 this.HashMgr.AddHashToHistory(hash.Trim(), false);
10835 this.AddNewTabForSearch(hash);
10840 // フラグが立っている場合は設定と逆の動作をする
10841 if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
10842 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
10844 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
10845 if (userUriMatch.Success)
10847 var screenName = userUriMatch.Groups["ScreenName"].Value;
10848 if (this.IsTwitterId(screenName))
10850 this.AddNewTabForUserTimeline(screenName);
10856 // どのパターンにも該当しないURL
10857 await this.OpenUriInBrowserAsync(uriStr);
10861 /// OpenTween 内部の機能を呼び出すための URL を開きます
10863 private async Task OpenInternalUriAsync(Uri uri)
10865 // ツイートを開く (//opentween/status/:status_id)
10866 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
10869 var statusId = long.Parse(match.Groups[1].Value);
10870 await this.OpenRelatedTab(statusId);
10875 public Task OpenUriInBrowserAsync(string UriString)
10877 return Task.Run(() =>
10879 string myPath = UriString;
10883 var configBrowserPath = this._cfgLocal.BrowserPath;
10884 if (!string.IsNullOrEmpty(configBrowserPath))
10886 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
10888 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
10889 string browserPath = configBrowserPath.Substring(1, sep - 1);
10891 if (sep < configBrowserPath.Length - 1)
10893 arg = configBrowserPath.Substring(sep + 1);
10895 myPath = arg + " " + myPath;
10896 System.Diagnostics.Process.Start(browserPath, myPath);
10900 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10905 System.Diagnostics.Process.Start(myPath);
10910 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10915 private void ListTabSelect(TabPage _tab)
10919 this.PurgeListViewItemCache();
10922 _curList = (DetailsListView)_tab.Tag;
10923 if (_curList.SelectedIndices.Count > 0)
10925 _curItemIndex = _curList.SelectedIndices[0];
10926 _curPost = GetCurTabPost(_curItemIndex);
10930 _curItemIndex = -1;
10934 _anchorPost = null;
10935 _anchorFlag = false;
10939 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10943 for (int i = 0; i < _curList.Columns.Count; i++)
10945 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10950 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10952 ListTabSelect(e.TabPage);
10955 private void SelectListItem(DetailsListView LView, int Index)
10958 Rectangle bnd = new Rectangle();
10960 var item = LView.FocusedItem;
10969 LView.SelectedIndices.Clear();
10971 while (LView.SelectedIndices.Count > 0);
10972 item = LView.Items[Index];
10973 item.Selected = true;
10974 item.Focused = true;
10976 if (flg) LView.Invalidate(bnd);
10979 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
10982 Rectangle bnd = new Rectangle();
10984 var item = LView.FocusedItem;
10995 LView.SelectedIndices.Clear();
10997 while (LView.SelectedIndices.Count > 0);
10998 LView.SelectItems(Index);
11000 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
11002 LView.SelectionMark = selectionMarkIndex;
11004 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
11006 LView.Items[focusedIndex].Focused = true;
11008 else if (Index != null && Index.Length != 0)
11010 LView.Items[Index.Last()].Focused = true;
11013 if (flg) LView.Invalidate(bnd);
11016 private void StartUserStream()
11018 tw.NewPostFromStream += tw_NewPostFromStream;
11019 tw.UserStreamStarted += tw_UserStreamStarted;
11020 tw.UserStreamStopped += tw_UserStreamStopped;
11021 tw.PostDeleted += tw_PostDeleted;
11022 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
11024 this.RefreshUserStreamsMenu();
11026 if (this._cfgCommon.UserstreamStartup)
11027 tw.StartUserStream();
11030 private async void TweenMain_Shown(object sender, EventArgs e)
11034 using (ControlTransaction.Update(this.PostBrowser))
11036 PostBrowser.Url = new Uri("about:blank");
11037 PostBrowser.DocumentText = ""; //発言詳細部初期化
11044 NotifyIcon1.Visible = true;
11046 if (this.IsNetworkAvailable())
11050 var loadTasks = new List<Task>
11052 this.RefreshMuteUserIdsAsync(),
11053 this.RefreshBlockIdsAsync(),
11054 this.RefreshNoRetweetIdsAsync(),
11055 this.RefreshTwitterConfigurationAsync(),
11056 this.GetHomeTimelineAsync(),
11057 this.GetReplyAsync(),
11058 this.GetDirectMessagesAsync(),
11059 this.GetPublicSearchAllAsync(),
11060 this.GetUserTimelineAllAsync(),
11061 this.GetListTimelineAllAsync(),
11064 if (this._cfgCommon.StartupFollowers)
11065 loadTasks.Add(this.RefreshFollowerIdsAsync());
11067 if (this._cfgCommon.GetFav)
11068 loadTasks.Add(this.GetFavoritesAsync());
11070 var allTasks = Task.WhenAll(loadTasks);
11075 var timeout = Task.Delay(5000);
11076 if (await Task.WhenAny(allTasks, timeout) != timeout)
11080 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
11082 if (MyCommon._endingFlag)
11086 if (MyCommon._endingFlag) return;
11088 if (ApplicationSettings.VersionInfoUrl != null)
11090 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
11091 if (this._cfgCommon.StartupVersion)
11092 await this.CheckNewVersion(true);
11096 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
11097 this.VerUpMenuItem.Enabled = false;
11098 this.VerUpMenuItem.Available = false;
11099 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
11102 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
11103 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
11105 MessageBox.Show(Properties.Resources.ReAuthorizeText);
11106 SettingStripMenuItem_Click(null, null);
11110 var reloadTasks = new List<Task>();
11112 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
11113 reloadTasks.Add(this.RefreshFollowerIdsAsync());
11115 if (!tw.GetNoRetweetSuccess)
11116 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
11118 if (this.tw.Configuration.PhotoSizeLimit == 0)
11119 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
11121 await Task.WhenAll(reloadTasks);
11126 TimerTimeline.Enabled = true;
11129 private async Task doGetFollowersMenu()
11131 await this.RefreshFollowerIdsAsync();
11132 await this.DispSelectedPost(true);
11135 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
11137 await this.doGetFollowersMenu();
11140 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
11142 doReTweetUnofficial();
11145 private async Task doReTweetOfficial(bool isConfirm)
11148 if (this.ExistCurrentPost)
11150 if (_curPost.IsProtect)
11152 MessageBox.Show("Protected.");
11153 _DoFavRetweetFlags = false;
11156 if (_curList.SelectedIndices.Count > 15)
11158 MessageBox.Show(Properties.Resources.RetweetLimitText);
11159 _DoFavRetweetFlags = false;
11162 else if (_curList.SelectedIndices.Count > 1)
11164 string QuestionText = Properties.Resources.RetweetQuestion2;
11165 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
11166 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
11168 case DialogResult.Cancel:
11169 case DialogResult.No:
11170 _DoFavRetweetFlags = false;
11176 if (_curPost.IsDm || _curPost.IsMe)
11178 _DoFavRetweetFlags = false;
11181 if (!this._cfgCommon.RetweetNoConfirm)
11183 string Questiontext = Properties.Resources.RetweetQuestion1;
11184 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11185 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11187 _DoFavRetweetFlags = false;
11193 var statusIds = new List<long>();
11194 foreach (int idx in _curList.SelectedIndices)
11196 PostClass post = GetCurTabPost(idx);
11197 if (!post.IsMe && !post.IsProtect && !post.IsDm)
11198 statusIds.Add(post.StatusId);
11201 await this.RetweetAsync(statusIds);
11205 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
11207 await this.doReTweetOfficial(true);
11210 private async Task FavoritesRetweetOfficial()
11212 if (!this.ExistCurrentPost) return;
11213 _DoFavRetweetFlags = true;
11214 var retweetTask = this.doReTweetOfficial(true);
11215 if (_DoFavRetweetFlags)
11217 _DoFavRetweetFlags = false;
11218 var favoriteTask = this.FavoriteChange(true, false);
11220 await Task.WhenAll(retweetTask, favoriteTask);
11228 private async Task FavoritesRetweetUnofficial()
11230 if (this.ExistCurrentPost && !_curPost.IsDm)
11232 _DoFavRetweetFlags = true;
11233 var favoriteTask = this.FavoriteChange(true);
11234 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11236 _DoFavRetweetFlags = false;
11237 doReTweetUnofficial();
11240 await favoriteTask;
11245 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11247 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11248 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11249 /// <returns>復元されたツイート本文</returns>
11250 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11252 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11255 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11257 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11259 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11263 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11265 statusHtml = statusHtml.Replace("<br>", " ");
11267 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11268 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
11269 statusHtml = statusHtml.Replace(" ", " ");
11271 return WebUtility.HtmlDecode(statusHtml);
11274 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11276 if (_curPost != null)
11277 await this.DispSelectedPost(true);
11280 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11282 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11283 DebugModeToolStripMenuItem.Visible = true;
11285 DebugModeToolStripMenuItem.Visible = false;
11288 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11290 this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11293 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11295 ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
11298 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11300 if (TraceOutToolStripMenuItem.Checked)
11301 MyCommon.TraceFlag = true;
11303 MyCommon.TraceFlag = false;
11306 private void TweenMain_Deactivate(object sender, EventArgs e)
11308 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11309 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11312 private void TabRenameMenuItem_Click(object sender, EventArgs e)
11314 if (string.IsNullOrEmpty(_rclickTabName)) return;
11315 TabRename(ref _rclickTabName);
11318 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11320 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11323 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11325 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11328 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11330 TwitterApiStatus apiStatus;
11332 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
11334 var cancellationToken = dialog.EnableCancellation();
11338 var task = this.tw.GetInfoApi();
11339 apiStatus = await dialog.WaitForAsync(this, task);
11341 catch (WebApiException)
11346 if (cancellationToken.IsCancellationRequested)
11349 if (apiStatus == null)
11351 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11356 using (var apiDlg = new ApiInfoDialog())
11358 apiDlg.ShowDialog(this);
11362 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
11364 var id = _curPost?.ScreenName ?? "";
11366 await this.FollowCommand(id);
11369 private async Task FollowCommand(string id)
11371 using (var inputName = new InputTabName())
11373 inputName.FormTitle = "Follow";
11374 inputName.FormDescription = Properties.Resources.FRMessage1;
11375 inputName.TabName = id;
11377 if (inputName.ShowDialog(this) != DialogResult.OK)
11379 if (string.IsNullOrWhiteSpace(inputName.TabName))
11382 id = inputName.TabName.Trim();
11385 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
11389 var task = this.twitterApi.FriendshipsCreate(id);
11390 await dialog.WaitForAsync(this, task);
11392 catch (WebApiException ex)
11394 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11399 MessageBox.Show(Properties.Resources.FRMessage3);
11402 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11404 var id = _curPost?.ScreenName ?? "";
11406 await this.RemoveCommand(id, false);
11409 private async Task RemoveCommand(string id, bool skipInput)
11413 using (var inputName = new InputTabName())
11415 inputName.FormTitle = "Unfollow";
11416 inputName.FormDescription = Properties.Resources.FRMessage1;
11417 inputName.TabName = id;
11419 if (inputName.ShowDialog(this) != DialogResult.OK)
11421 if (string.IsNullOrWhiteSpace(inputName.TabName))
11424 id = inputName.TabName.Trim();
11428 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
11432 var task = this.twitterApi.FriendshipsDestroy(id);
11433 await dialog.WaitForAsync(this, task);
11435 catch (WebApiException ex)
11437 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11442 MessageBox.Show(Properties.Resources.FRMessage3);
11445 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
11447 var id = _curPost?.ScreenName ?? "";
11449 await this.ShowFriendship(id);
11452 private async Task ShowFriendship(string id)
11454 using (var inputName = new InputTabName())
11456 inputName.FormTitle = "Show Friendships";
11457 inputName.FormDescription = Properties.Resources.FRMessage1;
11458 inputName.TabName = id;
11460 if (inputName.ShowDialog(this) != DialogResult.OK)
11462 if (string.IsNullOrWhiteSpace(inputName.TabName))
11465 id = inputName.TabName.Trim();
11468 bool isFollowing, isFollowed;
11470 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11472 var cancellationToken = dialog.EnableCancellation();
11476 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11477 var friendship = await dialog.WaitForAsync(this, task);
11479 isFollowing = friendship.Relationship.Source.Following;
11480 isFollowed = friendship.Relationship.Source.FollowedBy;
11482 catch (WebApiException ex)
11484 if (!cancellationToken.IsCancellationRequested)
11485 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
11489 if (cancellationToken.IsCancellationRequested)
11493 string result = "";
11496 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11500 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11504 result += Properties.Resources.GetFriendshipInfo3;
11508 result += Properties.Resources.GetFriendshipInfo4;
11510 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11511 MessageBox.Show(result);
11514 private async Task ShowFriendship(string[] ids)
11516 foreach (string id in ids)
11518 bool isFollowing, isFollowed;
11520 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11522 var cancellationToken = dialog.EnableCancellation();
11526 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11527 var friendship = await dialog.WaitForAsync(this, task);
11529 isFollowing = friendship.Relationship.Source.Following;
11530 isFollowed = friendship.Relationship.Source.FollowedBy;
11532 catch (WebApiException ex)
11534 if (!cancellationToken.IsCancellationRequested)
11535 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
11539 if (cancellationToken.IsCancellationRequested)
11543 string result = "";
11549 ff += Properties.Resources.GetFriendshipInfo1;
11553 ff += Properties.Resources.GetFriendshipInfo2;
11556 ff += System.Environment.NewLine + " ";
11559 ff += Properties.Resources.GetFriendshipInfo3;
11563 ff += Properties.Resources.GetFriendshipInfo4;
11565 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11568 if (MessageBox.Show(
11569 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11570 MessageBoxButtons.YesNo,
11571 MessageBoxIcon.Question,
11572 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11574 await this.RemoveCommand(id, true);
11579 MessageBox.Show(result);
11584 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
11586 await this.doShowUserStatus(tw.Username, false);
11587 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11589 // doShowUserStatus(tw.Username, false);
11593 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11598 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11599 // URLから切り出した文字列を渡す
11601 public bool IsTwitterId(string name)
11603 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11604 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11606 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
11609 private string GetUserId()
11611 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11612 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11613 return m.Result("${ScreenName}");
11618 private async void FollowContextMenuItem_Click(object sender, EventArgs e)
11620 string name = GetUserId();
11622 await this.FollowCommand(name);
11625 private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
11627 string name = GetUserId();
11629 await this.RemoveCommand(name, false);
11632 private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11634 string name = GetUserId();
11636 await this.ShowFriendship(name);
11639 private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11641 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11642 List<string> ids = new List<string>();
11643 foreach (Match mu in ma)
11645 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11647 ids.Add(mu.Result("${ScreenName}"));
11651 await this.ShowFriendship(ids.ToArray());
11654 private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11656 string name = GetUserId();
11658 await this.ShowUserStatus(name);
11661 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11663 string name = GetUserId();
11664 if (name != null) AddNewTabForUserTimeline(name);
11667 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11669 string name = GetUserId();
11670 if (name != null) AddNewTabForSearch("@" + name);
11673 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11675 ModifySettingCommon = true;
11678 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11680 ModifySettingCommon = true;
11683 private void doQuoteOfficial()
11685 if (this.ExistCurrentPost)
11687 if (_curPost.IsDm ||
11688 !StatusText.Enabled) return;
11690 if (_curPost.IsProtect)
11692 MessageBox.Show("Protected.");
11696 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
11698 this.inReplyTo = null;
11700 StatusText.SelectionStart = 0;
11701 StatusText.Focus();
11705 private void doReTweetUnofficial()
11708 if (this.ExistCurrentPost)
11710 if (_curPost.IsDm || !StatusText.Enabled)
11713 if (_curPost.IsProtect)
11715 MessageBox.Show("Protected.");
11718 string rtdata = _curPost.Text;
11719 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11721 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
11723 // 投稿時に in_reply_to_status_id を付加する
11724 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11725 var inReplyToScreenName = this._curPost.ScreenName;
11726 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
11728 StatusText.SelectionStart = 0;
11729 StatusText.Focus();
11733 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11738 private void SearchButton_Click(object sender, EventArgs e)
11741 Control pnl = ((Control)sender).Parent;
11742 if (pnl == null) return;
11743 string tbName = pnl.Parent.Text;
11744 TabClass tb = _statuses.Tabs[tbName];
11745 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11746 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11747 cmb.Text = cmb.Text.Trim();
11748 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11749 bool Quote = false;
11750 StringBuilder buf = new StringBuilder();
11751 char[] c = cmb.Text.ToCharArray();
11752 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11754 if (cnt > cmb.Text.Length - 4)
11756 buf.Append(cmb.Text.Substring(cnt));
11765 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11767 buf.Append(" OR ");
11772 buf.Append(c[cnt]);
11774 cmb.Text = buf.ToString();
11776 var listView = (DetailsListView)pnl.Parent.Tag;
11778 tb.SearchWords = cmb.Text;
11779 tb.SearchLang = cmbLang.Text;
11780 if (string.IsNullOrEmpty(cmb.Text))
11786 if (tb.IsSearchQueryChanged)
11788 int idx = cmb.Items.IndexOf(tb.SearchWords);
11789 if (idx > -1) cmb.Items.RemoveAt(idx);
11790 cmb.Items.Insert(0, tb.SearchWords);
11791 cmb.Text = tb.SearchWords;
11793 this.PurgeListViewItemCache();
11794 listView.VirtualListSize = 0;
11795 _statuses.ClearTabIds(tbName);
11796 SaveConfigsTabs(); //検索条件の保存
11799 this.GetPublicSearchAsync(tb);
11803 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11806 await this.DoRefreshMore();
11810 /// 指定されたタブのListTabにおける位置を返します
11813 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
11815 public int GetTabPageIndex(string tabName)
11818 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
11820 if (tabPage.Text == tabName)
11829 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11831 if (_statuses.RemovedTab.Count == 0)
11833 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11838 DetailsListView listView = null;
11840 TabClass tb = _statuses.RemovedTab.Pop();
11841 if (tb.TabType == MyCommon.TabUsageType.Related)
11843 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11844 if (relatedTab != null)
11846 // 関連発言なら既存のタブを置き換える
11847 tb.TabName = relatedTab.TabName;
11848 this.ClearTab(tb.TabName, false);
11849 _statuses.Tabs[tb.TabName] = tb;
11851 for (int i = 0; i < ListTab.TabPages.Count; i++)
11853 var tabPage = ListTab.TabPages[i];
11854 if (tb.TabName == tabPage.Text)
11856 listView = (DetailsListView)tabPage.Tag;
11857 ListTab.SelectedIndex = i;
11864 const string TabName = "Related Tweets";
11865 string renamed = TabName;
11866 for (int i = 2; i <= 100; i++)
11868 if (!_statuses.ContainsTab(renamed)) break;
11869 renamed = TabName + i.ToString();
11871 tb.TabName = renamed;
11872 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11873 _statuses.Tabs.Add(renamed, tb); // 後に
11875 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11876 listView = (DetailsListView)tabPage.Tag;
11877 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11882 string renamed = tb.TabName;
11883 for (int i = 1; i < int.MaxValue; i++)
11885 if (!_statuses.ContainsTab(renamed)) break;
11886 renamed = tb.TabName + "(" + i.ToString() + ")";
11888 tb.TabName = renamed;
11889 _statuses.Tabs.Add(renamed, tb); // 先に
11890 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11892 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11893 listView = (DetailsListView)tabPage.Tag;
11894 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11898 if (listView != null)
11900 using (ControlTransaction.Update(listView))
11902 listView.VirtualListSize = tb.AllCount;
11908 private async Task doMoveToRTHome()
11910 if (_curList.SelectedIndices.Count > 0)
11912 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11913 if (post.RetweetedId != null)
11915 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11920 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11922 await this.doMoveToRTHome();
11925 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11927 string name = GetUserId();
11933 if (_curList.SelectedIndices.Count == 0) return;
11936 if (!SelectTab(out tabName)) return;
11938 var tab = this._statuses.Tabs[tabName];
11942 if (tab.TabType != MyCommon.TabUsageType.Mute)
11944 this.MoveOrCopy(out mv, out mk);
11948 // ミュートタブでは常に MoveMatches を true にする
11953 PostFilterRule fc = new PostFilterRule();
11954 fc.FilterName = name;
11955 fc.UseNameField = true;
11956 fc.MoveMatches = mv;
11957 fc.MarkMatches = mk;
11958 fc.UseRegex = false;
11959 fc.FilterByUrl = false;
11962 this.ApplyPostFilters();
11967 private async void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11971 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11973 if (menuItem.Owner == this.ContextMenuPostBrowser)
11975 user = GetUserId();
11976 if (user == null) return;
11978 else if (this._curPost != null)
11980 user = this._curPost.ScreenName;
11987 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11991 using (var dialog = new WaitingDialog(Properties.Resources.ListsGetting))
11993 var cancellationToken = dialog.EnableCancellation();
11995 var task = this.tw.GetListsApi();
11996 await dialog.WaitForAsync(this, task);
11998 cancellationToken.ThrowIfCancellationRequested();
12001 catch (OperationCanceledException) { return; }
12002 catch (WebApiException ex)
12004 MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
12009 using (MyLists listSelectForm = new MyLists(user, this.tw))
12011 listSelectForm.ShowDialog(this);
12015 private void SearchControls_Enter(object sender, EventArgs e)
12017 Control pnl = (Control)sender;
12018 foreach (Control ctl in pnl.Controls)
12020 ctl.TabStop = true;
12024 private void SearchControls_Leave(object sender, EventArgs e)
12026 Control pnl = (Control)sender;
12027 foreach (Control ctl in pnl.Controls)
12029 ctl.TabStop = false;
12033 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
12035 if (ListTab.SelectedTab != null)
12037 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
12038 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
12042 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
12044 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
12047 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
12048 HashStripSplitButton.Text = HashMgr.UseHash;
12049 HashToggleMenuItem.Checked = true;
12050 HashToggleToolStripMenuItem.Checked = true;
12052 ModifySettingCommon = true;
12056 private void StatusLabel_DoubleClick(object sender, EventArgs e)
12058 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
12061 private void HashManageMenuItem_Click(object sender, EventArgs e)
12063 DialogResult rslt = DialogResult.Cancel;
12066 rslt = HashMgr.ShowDialog();
12072 this.TopMost = this._cfgCommon.AlwaysTop;
12073 if (rslt == DialogResult.Cancel) return;
12074 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12076 HashStripSplitButton.Text = HashMgr.UseHash;
12077 HashToggleMenuItem.Checked = true;
12078 HashToggleToolStripMenuItem.Checked = true;
12082 HashStripSplitButton.Text = "#[-]";
12083 HashToggleMenuItem.Checked = false;
12084 HashToggleToolStripMenuItem.Checked = false;
12086 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
12088 // int sidx = StatusText.SelectionStart;
12089 // string hash = HashMgr.UseHash + " ";
12092 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
12093 // hash = " " + hash;
12095 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
12096 // sidx += hash.Length;
12097 // StatusText.SelectionStart = sidx;
12098 // StatusText.Focus();
12100 ModifySettingCommon = true;
12101 this.StatusText_TextChanged(null, null);
12104 private void HashToggleMenuItem_Click(object sender, EventArgs e)
12106 HashMgr.ToggleHash();
12107 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12109 HashStripSplitButton.Text = HashMgr.UseHash;
12110 HashToggleMenuItem.Checked = true;
12111 HashToggleToolStripMenuItem.Checked = true;
12115 HashStripSplitButton.Text = "#[-]";
12116 HashToggleMenuItem.Checked = false;
12117 HashToggleToolStripMenuItem.Checked = false;
12119 ModifySettingCommon = true;
12120 this.StatusText_TextChanged(null, null);
12123 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
12125 HashToggleMenuItem_Click(null, null);
12128 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
12130 if (ListTab.SelectedTab == null) return;
12131 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
12132 if (!this.ExistCurrentPost)
12134 this.ReplyOpMenuItem.Enabled = false;
12135 this.ReplyAllOpMenuItem.Enabled = false;
12136 this.DmOpMenuItem.Enabled = false;
12137 this.ShowProfMenuItem.Enabled = false;
12138 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
12139 this.ListManageMenuItem.Enabled = false;
12140 this.OpenFavOpMenuItem.Enabled = false;
12141 this.CreateTabRuleOpMenuItem.Enabled = false;
12142 this.CreateIdRuleOpMenuItem.Enabled = false;
12143 this.CreateSourceRuleOpMenuItem.Enabled = false;
12144 this.ReadOpMenuItem.Enabled = false;
12145 this.UnreadOpMenuItem.Enabled = false;
12149 this.ReplyOpMenuItem.Enabled = true;
12150 this.ReplyAllOpMenuItem.Enabled = true;
12151 this.DmOpMenuItem.Enabled = true;
12152 this.ShowProfMenuItem.Enabled = true;
12153 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
12154 this.ListManageMenuItem.Enabled = true;
12155 this.OpenFavOpMenuItem.Enabled = true;
12156 this.CreateTabRuleOpMenuItem.Enabled = true;
12157 this.CreateIdRuleOpMenuItem.Enabled = true;
12158 this.CreateSourceRuleOpMenuItem.Enabled = true;
12159 this.ReadOpMenuItem.Enabled = true;
12160 this.UnreadOpMenuItem.Enabled = true;
12163 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
12165 this.FavOpMenuItem.Enabled = false;
12166 this.UnFavOpMenuItem.Enabled = false;
12167 this.OpenStatusOpMenuItem.Enabled = false;
12168 this.OpenFavotterOpMenuItem.Enabled = false;
12169 this.ShowRelatedStatusesMenuItem2.Enabled = false;
12170 this.RtOpMenuItem.Enabled = false;
12171 this.RtUnOpMenuItem.Enabled = false;
12172 this.QtOpMenuItem.Enabled = false;
12173 this.FavoriteRetweetMenuItem.Enabled = false;
12174 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12178 this.FavOpMenuItem.Enabled = true;
12179 this.UnFavOpMenuItem.Enabled = true;
12180 this.OpenStatusOpMenuItem.Enabled = true;
12181 this.OpenFavotterOpMenuItem.Enabled = true;
12182 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
12186 this.RtOpMenuItem.Enabled = false; //公式RTは無効に
12187 this.RtUnOpMenuItem.Enabled = true;
12188 this.QtOpMenuItem.Enabled = true;
12189 this.FavoriteRetweetMenuItem.Enabled = false; //公式RTは無効に
12190 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12194 if (_curPost.IsProtect)
12196 this.RtOpMenuItem.Enabled = false;
12197 this.RtUnOpMenuItem.Enabled = false;
12198 this.QtOpMenuItem.Enabled = false;
12199 this.FavoriteRetweetMenuItem.Enabled = false;
12200 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12204 this.RtOpMenuItem.Enabled = true;
12205 this.RtUnOpMenuItem.Enabled = true;
12206 this.QtOpMenuItem.Enabled = true;
12207 this.FavoriteRetweetMenuItem.Enabled = true;
12208 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12213 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
12215 this.RefreshPrevOpMenuItem.Enabled = true;
12219 this.RefreshPrevOpMenuItem.Enabled = false;
12221 if (!this.ExistCurrentPost
12222 || _curPost.InReplyToStatusId == null)
12224 OpenRepSourceOpMenuItem.Enabled = false;
12228 OpenRepSourceOpMenuItem.Enabled = true;
12230 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12232 OpenRterHomeMenuItem.Enabled = false;
12236 OpenRterHomeMenuItem.Enabled = true;
12239 if (this.ExistCurrentPost)
12241 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
12245 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12247 ContextMenuTabProperty_Opening(sender, null);
12250 public Twitter TwitterInstance
12255 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12257 if (this._initialLayout)
12260 int splitterDistance;
12261 switch (this.WindowState)
12263 case FormWindowState.Normal:
12264 splitterDistance = this.SplitContainer3.SplitterDistance;
12266 case FormWindowState.Maximized:
12267 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
12268 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
12269 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
12270 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
12276 this._mySpDis3 = splitterDistance;
12277 this.ModifySettingLocal = true;
12280 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12282 if (_statuses.RemovedTab.Count == 0)
12284 UndoRemoveTabMenuItem.Enabled = false;
12288 UndoRemoveTabMenuItem.Enabled = true;
12290 if (ListTab.SelectedTab != null)
12292 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12293 PublicSearchQueryMenuItem.Enabled = true;
12295 PublicSearchQueryMenuItem.Enabled = false;
12299 PublicSearchQueryMenuItem.Enabled = false;
12301 if (!this.ExistCurrentPost)
12303 this.CopySTOTMenuItem.Enabled = false;
12304 this.CopyURLMenuItem.Enabled = false;
12305 this.CopyUserIdStripMenuItem.Enabled = false;
12309 this.CopySTOTMenuItem.Enabled = true;
12310 this.CopyURLMenuItem.Enabled = true;
12311 this.CopyUserIdStripMenuItem.Enabled = true;
12312 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12313 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12317 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12319 SetNotifyIconText();
12322 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12324 var id = _curPost?.ScreenName ?? "";
12326 await this.ShowUserStatus(id);
12329 private async Task doShowUserStatus(string id, bool ShowInputDialog)
12331 TwitterUser user = null;
12333 if (ShowInputDialog)
12335 using (var inputName = new InputTabName())
12337 inputName.FormTitle = "Show UserStatus";
12338 inputName.FormDescription = Properties.Resources.FRMessage1;
12339 inputName.TabName = id;
12341 if (inputName.ShowDialog(this) != DialogResult.OK)
12343 if (string.IsNullOrWhiteSpace(inputName.TabName))
12346 id = inputName.TabName.Trim();
12350 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
12352 var cancellationToken = dialog.EnableCancellation();
12356 var task = this.twitterApi.UsersShow(id);
12357 user = await dialog.WaitForAsync(this, task);
12359 catch (WebApiException ex)
12361 if (!cancellationToken.IsCancellationRequested)
12362 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
12366 if (cancellationToken.IsCancellationRequested)
12370 await this.doShowUserStatus(user);
12373 private async Task doShowUserStatus(TwitterUser user)
12375 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
12377 var showUserTask = userDialog.ShowUserAsync(user);
12378 userDialog.ShowDialog(this);
12381 this.BringToFront();
12383 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12384 await showUserTask;
12388 private Task ShowUserStatus(string id, bool ShowInputDialog)
12390 return this.doShowUserStatus(id, ShowInputDialog);
12393 private Task ShowUserStatus(string id)
12395 return this.doShowUserStatus(id, true);
12398 private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12400 if (NameLabel.Tag != null)
12402 string id = (string)NameLabel.Tag;
12403 if (id != tw.Username)
12405 await this.FollowCommand(id);
12410 private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12412 if (NameLabel.Tag != null)
12414 string id = (string)NameLabel.Tag;
12415 if (id != tw.Username)
12417 await this.RemoveCommand(id, false);
12422 private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12424 if (NameLabel.Tag != null)
12426 string id = (string)NameLabel.Tag;
12427 if (id != tw.Username)
12429 await this.ShowFriendship(id);
12434 private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12436 if (NameLabel.Tag != null)
12438 string id = (string)NameLabel.Tag;
12439 await this.ShowUserStatus(id, false);
12443 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12445 if (NameLabel.Tag != null)
12447 string id = (string)NameLabel.Tag;
12448 AddNewTabForUserTimeline(id);
12452 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12454 if (NameLabel.Tag != null)
12456 string id = (string)NameLabel.Tag;
12457 AddNewTabForSearch("@" + id);
12461 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
12463 if (_curPost != null)
12465 await this.ShowUserStatus(_curPost.ScreenName, false);
12469 private async void RtCountMenuItem_Click(object sender, EventArgs e)
12471 if (!this.ExistCurrentPost)
12474 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
12475 TwitterStatus status;
12477 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
12479 var cancellationToken = dialog.EnableCancellation();
12483 var task = this.twitterApi.StatusesShow(statusId);
12484 status = await dialog.WaitForAsync(this, task);
12486 catch (WebApiException ex)
12488 if (!cancellationToken.IsCancellationRequested)
12489 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
12493 if (cancellationToken.IsCancellationRequested)
12497 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
12500 private HookGlobalHotkey _hookGlobalHotkey;
12503 _hookGlobalHotkey = new HookGlobalHotkey(this);
12505 // この呼び出しは、Windows フォーム デザイナで必要です。
12506 InitializeComponent();
12508 // InitializeComponent() 呼び出しの後で初期化を追加します。
12510 if (!this.DesignMode)
12512 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12513 this.StatusText.Dock = DockStyle.Fill;
12516 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12517 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12518 this.gh.NotifyClicked += GrowlHelper_Callback;
12520 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12521 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12523 this.ImageSelector.Visible = false;
12524 this.ImageSelector.Enabled = false;
12525 this.ImageSelector.FilePickDialog = OpenFileDialog1;
12527 this.ReplaceAppName();
12528 this.InitializeShortcuts();
12531 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12533 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12536 this.Visible = false;
12538 else if (Form.ActiveForm == null)
12540 this.Visible = true;
12541 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12543 this.BringToFront();
12544 this.StatusText.Focus();
12548 private void UserPicture_MouseEnter(object sender, EventArgs e)
12550 this.UserPicture.Cursor = Cursors.Hand;
12553 private void UserPicture_MouseLeave(object sender, EventArgs e)
12555 this.UserPicture.Cursor = Cursors.Default;
12558 private async void UserPicture_DoubleClick(object sender, EventArgs e)
12560 if (NameLabel.Tag != null)
12562 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12566 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12568 this.MultiLineMenuItem.PerformClick();
12571 public PostClass CurPost
12573 get { return _curPost; }
12577 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12579 if (ImageSelector.Visible)
12580 ImageSelector.EndSelection();
12582 ImageSelector.BeginSelection();
12585 private void SelectMedia_DragEnter(DragEventArgs e)
12587 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12589 e.Effect = DragDropEffects.Copy;
12592 e.Effect = DragDropEffects.None;
12595 private void SelectMedia_DragDrop(DragEventArgs e)
12598 this.BringToFront();
12599 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12600 StatusText.Focus();
12603 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12605 TimelinePanel.Visible = false;
12606 TimelinePanel.Enabled = false;
12609 private void ImageSelector_EndSelecting(object sender, EventArgs e)
12611 TimelinePanel.Visible = true;
12612 TimelinePanel.Enabled = true;
12613 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12616 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12618 this.AllowDrop = false;
12621 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12623 this.AllowDrop = true;
12626 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12628 if (ImageSelector.Visible)
12630 ModifySettingCommon = true;
12631 SaveConfigsAll(true);
12633 if (ImageSelector.ServiceName.Equals("Twitter"))
12634 this.StatusText_TextChanged(null, null);
12638 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12640 this.StatusText_TextChanged(null, null);
12644 /// StatusTextでCtrl+Vが押下された時の処理
12646 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
12648 if (Clipboard.ContainsText())
12650 // clipboardにテキストがある場合は貼り付け処理
12651 this.StatusText.Paste(Clipboard.GetText());
12653 else if (Clipboard.ContainsImage())
12656 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
12657 Properties.Resources.PostPictureWarn4,
12658 MessageBoxButtons.OKCancel,
12659 MessageBoxIcon.Question,
12660 MessageBoxDefaultButton.Button2)
12661 == DialogResult.OK)
12663 // clipboardから画像を取得
12664 using (var image = Clipboard.GetImage())
12666 this.ImageSelector.BeginSelection(image);
12673 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12675 using (ListManage form = new ListManage(tw))
12677 form.ShowDialog(this);
12681 public bool ModifySettingCommon { get; set; }
12682 public bool ModifySettingLocal { get; set; }
12683 public bool ModifySettingAtId { get; set; }
12685 private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12687 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12688 if (sourceUri != null && e.Button == MouseButtons.Left)
12690 await this.OpenUriInBrowserAsync(sourceUri.AbsoluteUri);
12694 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12696 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12697 if (sourceUri != null)
12699 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri);
12703 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12705 SetStatusLabelUrl();
12708 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12710 if (this.ExistCurrentPost && !_curPost.IsDm)
12711 RtCountMenuItem.Enabled = true;
12713 RtCountMenuItem.Enabled = false;
12715 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12716 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12718 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12721 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12726 private void CopyUserId()
12728 if (_curPost == null) return;
12729 string clstr = _curPost.ScreenName;
12732 Clipboard.SetDataObject(clstr, false, 5, 100);
12734 catch (Exception ex)
12736 MessageBox.Show(ex.Message);
12740 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12742 if (this.ExistCurrentPost && !_curPost.IsDm)
12746 await this.OpenRelatedTab(this._curPost);
12748 catch (TabException ex)
12750 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12756 /// 指定されたツイートに対する関連発言タブを開きます
12758 /// <param name="statusId">表示するツイートのID</param>
12759 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12760 private async Task OpenRelatedTab(long statusId)
12762 var post = this._statuses[statusId];
12767 post = await this.tw.GetStatusApi(false, statusId);
12769 catch (WebApiException ex)
12771 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
12776 await this.OpenRelatedTab(post);
12780 /// 指定されたツイートに対する関連発言タブを開きます
12782 /// <param name="post">表示する対象となるツイート</param>
12783 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12784 private async Task OpenRelatedTab(PostClass post)
12786 var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12789 if (tabRelated == null)
12791 tabName = this._statuses.MakeTabName("Related Tweets");
12793 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12794 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12796 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12797 tabRelated.UnreadManage = false;
12798 tabRelated.Notify = false;
12802 tabName = tabRelated.TabName;
12805 tabRelated.RelationTargetPost = post;
12806 this.ClearTab(tabName, false);
12808 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12810 var tabPage = this.ListTab.TabPages[i];
12811 if (tabName == tabPage.Text)
12813 this.ListTab.SelectedIndex = i;
12818 await this.GetRelatedTweetsAsync(tabRelated);
12821 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12823 StringBuilder buf = new StringBuilder();
12824 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12825 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12826 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12827 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12828 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12831 private void tw_UserIdChanged()
12833 this.ModifySettingCommon = true;
12836 #region "Userstream"
12837 private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12841 if (InvokeRequired && !IsDisposed)
12843 Invoke((Action) (async () =>
12845 _statuses.RemovePostReserve(e.StatusId);
12846 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12848 this.PurgeListViewItemCache();
12849 ((DetailsListView)_curTab.Tag).Update();
12850 if (_curPost != null && _curPost.StatusId == e.StatusId)
12851 await this.DispSelectedPost(true);
12857 catch (ObjectDisposedException)
12861 catch (InvalidOperationException)
12867 private int userStreamsRefreshing = 0;
12869 private async void tw_NewPostFromStream(object sender, EventArgs e)
12871 if (this._cfgCommon.ReadOldPosts)
12873 _statuses.SetReadHomeTab(); //新着時未読クリア
12876 int rsltAddCount = _statuses.DistributePosts();
12878 this.UpdateTimelineSpeed(rsltAddCount);
12880 if (this._cfgCommon.UserstreamPeriod > 0) return;
12882 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
12883 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
12887 await this.InvokeAsync(() => this.RefreshTimeline())
12888 .ConfigureAwait(false);
12892 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
12897 private void tw_UserStreamStarted(object sender, EventArgs e)
12901 if (InvokeRequired && !IsDisposed)
12903 Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12907 catch (ObjectDisposedException)
12911 catch (InvalidOperationException)
12916 this.RefreshUserStreamsMenu();
12917 this.MenuItemUserStream.Enabled = true;
12919 StatusLabel.Text = "UserStream Started.";
12922 private void tw_UserStreamStopped(object sender, EventArgs e)
12926 if (InvokeRequired && !IsDisposed)
12928 Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12932 catch (ObjectDisposedException)
12936 catch (InvalidOperationException)
12941 this.RefreshUserStreamsMenu();
12942 this.MenuItemUserStream.Enabled = true;
12944 StatusLabel.Text = "UserStream Stopped.";
12947 private void RefreshUserStreamsMenu()
12949 if (this.tw.UserStreamActive)
12951 this.MenuItemUserStream.Text = "&UserStream ▶";
12952 this.StopToolStripMenuItem.Text = "&Stop";
12956 this.MenuItemUserStream.Text = "&UserStream ■";
12957 this.StopToolStripMenuItem.Text = "&Start";
12961 private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12965 if (InvokeRequired && !IsDisposed)
12967 Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12971 catch (ObjectDisposedException)
12975 catch (InvalidOperationException)
12979 var ev = e.EventData;
12980 StatusLabel.Text = "Event: " + ev.Event;
12981 //if (ev.Event == "favorite")
12983 // NotifyFavorite(ev);
12986 if (ev.Event == "favorite" || ev.Event == "unfavorite")
12988 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12990 this.PurgeListViewItemCache();
12991 ((DetailsListView)_curTab.Tag).Update();
12993 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
12995 RemovePostFromFavTab(new long[] {ev.Id});
13000 private void NotifyEvent(Twitter.FormattedEvent ev)
13003 if (BalloonRequired(ev))
13005 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13006 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
13007 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
13008 StringBuilder title = new StringBuilder();
13009 if (this._cfgCommon.DispUsername)
13011 title.Append(tw.Username);
13012 title.Append(" - ");
13018 title.Append(Application.ProductName);
13019 title.Append(" [");
13020 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
13021 title.Append("] by ");
13022 if (!string.IsNullOrEmpty(ev.Username))
13024 title.Append(ev.Username.ToString());
13028 //title.Append("");
13031 if (!string.IsNullOrEmpty(ev.Target))
13033 //NotifyIcon1.BalloonTipText = ev.Target;
13038 //NotifyIcon1.BalloonTipText = " ";
13041 //NotifyIcon1.ShowBalloonTip(500);
13042 if (this._cfgCommon.IsUseNotifyGrowl)
13044 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13045 ev.Id.ToString(), title.ToString(), text);
13049 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13050 NotifyIcon1.BalloonTipTitle = title.ToString();
13051 NotifyIcon1.BalloonTipText = text;
13052 NotifyIcon1.ShowBalloonTip(500);
13057 string snd = this._cfgCommon.EventSoundFile;
13058 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
13060 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13064 string dir = Application.StartupPath;
13065 if (Directory.Exists(Path.Combine(dir, "Sounds")))
13067 dir = Path.Combine(dir, "Sounds");
13069 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13081 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13083 MenuItemUserStream.Enabled = false;
13084 if (StopRefreshAllMenuItem.Checked)
13086 StopRefreshAllMenuItem.Checked = false;
13089 if (this.tw.UserStreamActive)
13091 tw.StopUserStream();
13095 tw.StartUserStream();
13099 private static string inputTrack = "";
13101 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13103 if (TrackToolStripMenuItem.Checked)
13105 using (InputTabName inputForm = new InputTabName())
13107 inputForm.TabName = inputTrack;
13108 inputForm.FormTitle = "Input track word";
13109 inputForm.FormDescription = "Track word";
13110 if (inputForm.ShowDialog() != DialogResult.OK)
13112 TrackToolStripMenuItem.Checked = false;
13115 inputTrack = inputForm.TabName.Trim();
13117 if (!inputTrack.Equals(tw.TrackWord))
13119 tw.TrackWord = inputTrack;
13120 this.ModifySettingCommon = true;
13121 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13122 tw.ReconnectUserStream();
13128 tw.ReconnectUserStream();
13130 this.ModifySettingCommon = true;
13133 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13135 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13136 this.ModifySettingCommon = true;
13137 tw.ReconnectUserStream();
13140 private void EventViewerMenuItem_Click(object sender, EventArgs e)
13142 if (evtDialog == null || evtDialog.IsDisposed)
13145 evtDialog = new EventViewerDialog();
13146 evtDialog.Owner = this;
13148 Point pos = evtDialog.Location;
13149 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13150 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13151 evtDialog.Location = pos;
13153 evtDialog.EventSource = tw.StoredEvent;
13154 if (!evtDialog.Visible)
13156 evtDialog.Show(this);
13160 evtDialog.Activate();
13162 this.TopMost = this._cfgCommon.AlwaysTop;
13166 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13168 MyCommon._endingFlag = true;
13172 Application.Restart();
13176 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13180 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13182 if (!string.IsNullOrEmpty(tw.Username))
13183 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13186 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13188 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
13191 private async Task doTranslation(string str)
13193 if (string.IsNullOrEmpty(str))
13196 var bing = new Bing();
13199 var translatedText = await bing.TranslateAsync(str,
13201 langTo: this._cfgCommon.TranslateLanguage);
13203 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
13205 catch (HttpRequestException e)
13207 this.StatusLabel.Text = "Err:" + e.Message;
13209 catch (OperationCanceledException)
13211 this.StatusLabel.Text = "Err:Timeout";
13215 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13217 if (!this.ExistCurrentPost)
13220 await this.doTranslation(this._curPost.TextFromApi);
13223 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13225 var text = this.PostBrowser.GetSelectedText();
13226 await this.doTranslation(text);
13229 private bool ExistCurrentPost
13233 if (_curPost == null) return false;
13234 if (_curPost.IsDeleted) return false;
13239 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13241 ShowUserTimeline();
13244 private string GetUserIdFromCurPostOrInput(string caption)
13246 var id = _curPost?.ScreenName ?? "";
13248 using (InputTabName inputName = new InputTabName())
13250 inputName.FormTitle = caption;
13251 inputName.FormDescription = Properties.Resources.FRMessage1;
13252 inputName.TabName = id;
13253 if (inputName.ShowDialog() == DialogResult.OK &&
13254 !string.IsNullOrEmpty(inputName.TabName.Trim()))
13256 id = inputName.TabName.Trim();
13266 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13268 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13269 if (!string.IsNullOrEmpty(id))
13271 AddNewTabForUserTimeline(id);
13275 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13277 string id = GetUserIdFromCurPostOrInput("Show Favstar");
13278 if (!string.IsNullOrEmpty(id))
13280 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13284 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13286 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13289 private void TimelineRefreshEnableChange(bool isEnable)
13293 tw.StartUserStream();
13297 tw.StopUserStream();
13299 TimerTimeline.Enabled = isEnable;
13302 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13304 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13307 private async Task OpenUserAppointUrl()
13309 if (this._cfgCommon.UserAppointUrl != null)
13311 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
13313 if (_curPost != null)
13315 string xUrl = this._cfgCommon.UserAppointUrl;
13316 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13318 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
13319 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
13321 await this.OpenUriInBrowserAsync(xUrl);
13326 await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
13331 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13333 await this.OpenUserAppointUrl();
13336 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13338 string selText = SourceLinkLabel.Text;
13341 Clipboard.SetDataObject(selText, false, 5, 100);
13343 catch (Exception ex)
13345 MessageBox.Show(ex.Message);
13349 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13351 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
13354 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
13356 catch (Exception ex)
13358 MessageBox.Show(ex.Message);
13362 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13364 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13366 SourceCopyMenuItem.Enabled = false;
13367 SourceUrlCopyMenuItem.Enabled = false;
13371 SourceCopyMenuItem.Enabled = true;
13372 SourceUrlCopyMenuItem.Enabled = true;
13376 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13378 if (Form.ActiveForm == null)
13380 this.BeginInvoke((Action) (() =>
13382 this.Visible = true;
13383 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13385 this.BringToFront();
13386 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13388 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13392 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13398 private void ReplaceAppName()
13400 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13401 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13404 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13406 this.SplitContainer3.Panel2Collapsed = false;
13409 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13411 await this.OpenThumbnailPicture(e.Thumbnail);
13414 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13416 await this.OpenUriInBrowserAsync(e.ImageUrl);
13419 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
13421 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
13423 await this.OpenUriInBrowserAsync(url);
13426 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13428 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
13431 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13433 if (e.KeyCode == Keys.Space)
13435 this.JumpUnreadMenuItem_Click(null, null);
13437 e.SuppressKeyPress = true;
13441 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13443 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13444 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13445 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13446 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13447 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13449 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13452 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13454 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13457 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13459 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13462 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13464 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13467 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13469 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13472 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13474 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13477 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13479 if (this._cfgCommon.IconSize == iconSize) return;
13481 var oldIconCol = _iconCol;
13483 this._cfgCommon.IconSize = iconSize;
13484 ApplyListViewIconSize(iconSize);
13486 if (_iconCol != oldIconCol)
13488 foreach (TabPage tp in ListTab.TabPages)
13490 ResetColumns((DetailsListView)tp.Tag);
13494 _curList?.Refresh();
13496 ModifySettingCommon = true;
13499 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13501 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13502 if (this._cfgCommon.SortOrderLock == state) return;
13504 this._cfgCommon.SortOrderLock = state;
13506 ModifySettingCommon = true;