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 = this._cfgCommon.TwitterApiBaseUri;
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 = this._cfgCommon.TwitterApiBaseUri;
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 var tabsSetting = SettingTabs.Load().Tabs;
1286 foreach (var tabSetting in tabsSetting)
1288 var tab = new TabClass(tabSetting.TabName, tabSetting.TabType, tabSetting.ListInfo)
1290 UnreadManage = tabSetting.UnreadManage,
1291 Protected = tabSetting.Protected,
1292 Notify = tabSetting.Notify,
1293 SoundFile = tabSetting.SoundFile,
1294 FilterArray = tabSetting.FilterArray,
1295 FilterModified = false,
1296 User = tabSetting.User,
1297 SearchWords = tabSetting.SearchWords,
1298 SearchLang = tabSetting.SearchLang,
1301 if (this._statuses.ContainsTab(tab.TabName))
1302 tab.TabName = this._statuses.MakeTabName("MyTab");
1304 this._statuses.AddTab(tab);
1306 if (_statuses.Tabs.Count == 0)
1308 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1309 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1310 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1311 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1315 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1317 if (!TimerTimeline.Enabled) return;
1321 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1323 private static int homeCounter = 0;
1324 private static int mentionCounter = 0;
1325 private static int dmCounter = 0;
1326 private static int pubSearchCounter = 0;
1327 private static int userTimelineCounter = 0;
1328 private static int listsCounter = 0;
1329 private static int usCounter = 0;
1330 private static int ResumeWait = 0;
1331 private static int refreshFollowers = 0;
1333 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1335 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1336 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1337 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1338 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1339 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1340 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1341 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1342 Interlocked.Increment(ref refreshFollowers);
1344 var refreshTasks = new List<Task>();
1347 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1349 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1350 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1351 refreshTasks.Add(this.GetHomeTimelineAsync());
1352 ResetTimers.Timeline = false;
1354 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1356 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1357 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1358 refreshTasks.Add(this.GetReplyAsync());
1359 ResetTimers.Reply = false;
1361 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1363 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1364 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1365 refreshTasks.Add(this.GetDirectMessagesAsync());
1366 ResetTimers.DirectMessage = false;
1368 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1370 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1371 if (!ResetTimers.PublicSearch)
1372 refreshTasks.Add(this.GetPublicSearchAllAsync());
1373 ResetTimers.PublicSearch = false;
1375 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1377 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1378 if (!ResetTimers.UserTimeline)
1379 refreshTasks.Add(this.GetUserTimelineAllAsync());
1380 ResetTimers.UserTimeline = false;
1382 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1384 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1385 if (!ResetTimers.Lists)
1386 refreshTasks.Add(this.GetListTimelineAllAsync());
1387 ResetTimers.Lists = false;
1389 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1391 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1392 if (this.tw.UserStreamActive)
1393 this.RefreshTimeline();
1394 ResetTimers.UserStream = false;
1396 if (refreshFollowers > 6 * 3600)
1398 Interlocked.Exchange(ref refreshFollowers, 0);
1399 refreshTasks.AddRange(new[]
1401 this.doGetFollowersMenu(),
1402 this.RefreshNoRetweetIdsAsync(),
1403 this.RefreshTwitterConfigurationAsync(),
1408 Interlocked.Increment(ref ResumeWait);
1409 if (ResumeWait > 30)
1412 Interlocked.Exchange(ref ResumeWait, 0);
1413 refreshTasks.AddRange(new[]
1415 this.GetHomeTimelineAsync(),
1416 this.GetReplyAsync(),
1417 this.GetDirectMessagesAsync(),
1418 this.GetPublicSearchAllAsync(),
1419 this.GetUserTimelineAllAsync(),
1420 this.GetListTimelineAllAsync(),
1421 this.doGetFollowersMenu(),
1422 this.RefreshTwitterConfigurationAsync(),
1427 await Task.WhenAll(refreshTasks);
1430 private void RefreshTimeline()
1432 // 現在表示中のタブのスクロール位置を退避
1433 var curListScroll = this.SaveListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text]);
1435 // 各タブのリスト上の選択位置などを退避
1436 var listSelections = this.SaveListViewSelection();
1439 PostClass[] notifyPosts;
1442 bool newMentionOrDm;
1444 addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1446 if (MyCommon._endingFlag) return;
1451 foreach (TabPage tab in ListTab.TabPages)
1453 DetailsListView lst = (DetailsListView)tab.Tag;
1454 TabClass tabInfo = _statuses.Tabs[tab.Text];
1455 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1457 using (ControlTransaction.Update(lst))
1459 if (lst.Equals(_curList))
1461 this.PurgeListViewItemCache();
1465 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1473 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
1476 if (tabInfo.UnreadCount > 0)
1477 if (this._cfgCommon.TabIconDisp)
1478 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1480 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1484 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1489 this.RestoreListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text], curListScroll);
1492 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1494 SetMainWindowTitle();
1495 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1497 HashSupl.AddRangeItem(tw.GetHashList());
1501 internal struct ListViewScroll
1503 public ScrollLockMode ScrollLockMode { get; set; }
1504 public long? TopItemStatusId { get; set; }
1507 internal enum ScrollLockMode
1509 /// <summary>固定しない</summary>
1512 /// <summary>最上部に固定する</summary>
1515 /// <summary>最下部に固定する</summary>
1518 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1523 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1525 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabClass tab)
1527 var listScroll = new ListViewScroll
1529 ScrollLockMode = this.GetScrollLockMode(listView),
1532 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1534 var topItem = listView.TopItem;
1535 if (topItem != null)
1536 listScroll.TopItemStatusId = tab.GetId(topItem.Index);
1542 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1544 if (this._statuses.SortMode == ComparerMode.Id)
1546 if (this._statuses.SortOrder == SortOrder.Ascending)
1549 if (this.ListLockMenuItem.Checked)
1550 return ScrollLockMode.None;
1552 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1555 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1556 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1557 return ScrollLockMode.FixedToBottom;
1559 return ScrollLockMode.None;
1564 if (this.ListLockMenuItem.Checked)
1565 return ScrollLockMode.FixedToItem;
1567 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1568 var topItem = listView.TopItem;
1569 if (topItem == null || topItem.Index == 0)
1570 return ScrollLockMode.FixedToTop;
1572 return ScrollLockMode.FixedToItem;
1577 return ScrollLockMode.FixedToItem;
1581 internal struct ListViewSelection
1583 public long[] SelectedStatusIds { get; set; }
1584 public long? SelectionMarkStatusId { get; set; }
1585 public long? FocusedStatusId { get; set; }
1589 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1591 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1593 var listsDict = new Dictionary<string, ListViewSelection>();
1595 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1597 var listView = (DetailsListView)tabPage.Tag;
1598 var tab = _statuses.Tabs[tabPage.Text];
1600 ListViewSelection listStatus;
1601 if (listView.VirtualListSize != 0)
1603 listStatus = new ListViewSelection
1605 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1606 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1607 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1612 listStatus = new ListViewSelection
1614 SelectedStatusIds = new long[0],
1615 SelectionMarkStatusId = null,
1616 FocusedStatusId = null,
1620 listsDict[tab.TabName] = listStatus;
1626 private long[] GetSelectedStatusIds(DetailsListView listView, TabClass tab)
1628 var selectedIndices = listView.SelectedIndices;
1629 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1630 return tab.GetId(selectedIndices);
1635 private long? GetFocusedStatusId(DetailsListView listView, TabClass tab)
1637 var focusedItem = listView.FocusedItem;
1639 return focusedItem != null ? tab.GetId(focusedItem.Index) : (long?)null;
1642 private long? GetSelectionMarkStatusId(DetailsListView listView, TabClass tab)
1644 var selectionMarkIndex = listView.SelectionMark;
1646 return selectionMarkIndex != -1 ? tab.GetId(selectionMarkIndex) : (long?)null;
1650 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1652 private void RestoreListViewScroll(DetailsListView listView, TabClass tab, ListViewScroll listScroll)
1654 if (listView.VirtualListSize == 0)
1657 switch (listScroll.ScrollLockMode)
1659 case ScrollLockMode.FixedToTop:
1660 listView.EnsureVisible(0);
1662 case ScrollLockMode.FixedToBottom:
1663 listView.EnsureVisible(listView.VirtualListSize - 1);
1665 case ScrollLockMode.FixedToItem:
1666 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1668 listView.TopItem = listView.Items[topIndex];
1670 case ScrollLockMode.None:
1677 /// <see cref="SaveListViewStatus"/> によって保存された選択状態を復元します
1679 private void RestoreListViewSelection(DetailsListView listView, TabClass tab, ListViewSelection listSelection)
1681 // status_id から ListView 上のインデックスに変換
1682 int[] selectedIndices = null;
1683 if (listSelection.SelectedStatusIds != null)
1684 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1686 var focusedIndex = -1;
1687 if (listSelection.FocusedStatusId != null)
1688 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1690 var selectionMarkIndex = -1;
1691 if (listSelection.SelectionMarkStatusId != null)
1692 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1694 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1697 private bool BalloonRequired()
1699 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1700 ev.Eventtype = MyCommon.EVENTTYPE.None;
1702 return BalloonRequired(ev);
1705 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1707 if (type == MyCommon.EVENTTYPE.None)
1710 if (!this._cfgCommon.EventNotifyEnabled)
1713 return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1716 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1721 return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1724 private bool BalloonRequired(Twitter.FormattedEvent ev)
1729 if (NativeMethods.IsScreenSaverRunning())
1733 if (!this.NewPostPopMenuItem.Checked)
1735 // 「新着通知が無効でもイベントを通知する」にも該当しない
1736 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1740 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1741 if (this._cfgCommon.LimitBalloon)
1743 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1747 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1750 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1752 if (this._cfgCommon.ReadOwnPost)
1754 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1759 if (BalloonRequired())
1761 if (notifyPosts != null && notifyPosts.Length > 0)
1763 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1764 if (this._cfgCommon.IsUseNotifyGrowl)
1766 StringBuilder sb = new StringBuilder();
1770 foreach (PostClass post in notifyPosts)
1772 if (!(notifyPosts.Length > 3))
1778 if (post.IsReply && !post.IsExcludeReply) reply = true;
1779 if (post.IsDm) dm = true;
1780 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1781 switch (this._cfgCommon.NameBalloon)
1783 case MyCommon.NameBalloonEnum.UserID:
1784 sb.Append(post.ScreenName).Append(" : ");
1786 case MyCommon.NameBalloonEnum.NickName:
1787 sb.Append(post.Nickname).Append(" : ");
1790 sb.Append(post.TextFromApi);
1791 if (notifyPosts.Length > 3)
1793 if (notifyPosts.Last() != post) continue;
1796 StringBuilder title = new StringBuilder();
1797 GrowlHelper.NotifyType nt;
1798 if (this._cfgCommon.DispUsername)
1800 title.Append(tw.Username);
1801 title.Append(" - ");
1809 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1810 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1811 title.Append(Application.ProductName);
1812 title.Append(" [DM] ");
1813 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1814 nt = GrowlHelper.NotifyType.DirectMessage;
1818 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1819 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1820 title.Append(Application.ProductName);
1821 title.Append(" [Reply!] ");
1822 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1823 nt = GrowlHelper.NotifyType.Reply;
1827 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1828 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1829 title.Append(Application.ProductName);
1831 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1832 nt = GrowlHelper.NotifyType.Notify;
1834 string bText = sb.ToString();
1835 if (string.IsNullOrEmpty(bText)) return;
1837 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1838 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1843 StringBuilder sb = new StringBuilder();
1846 foreach (PostClass post in notifyPosts)
1848 if (post.IsReply && !post.IsExcludeReply) reply = true;
1849 if (post.IsDm) dm = true;
1850 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1851 switch (this._cfgCommon.NameBalloon)
1853 case MyCommon.NameBalloonEnum.UserID:
1854 sb.Append(post.ScreenName).Append(" : ");
1856 case MyCommon.NameBalloonEnum.NickName:
1857 sb.Append(post.Nickname).Append(" : ");
1860 sb.Append(post.TextFromApi);
1863 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1864 StringBuilder title = new StringBuilder();
1866 if (this._cfgCommon.DispUsername)
1868 title.Append(tw.Username);
1869 title.Append(" - ");
1877 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1878 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1879 ntIcon = ToolTipIcon.Warning;
1880 title.Append(Application.ProductName);
1881 title.Append(" [DM] ");
1882 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1886 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1887 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1888 ntIcon = ToolTipIcon.Warning;
1889 title.Append(Application.ProductName);
1890 title.Append(" [Reply!] ");
1891 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1895 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1896 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1897 ntIcon = ToolTipIcon.Info;
1898 title.Append(Application.ProductName);
1900 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1902 string bText = sb.ToString();
1903 if (string.IsNullOrEmpty(bText)) return;
1904 //NotifyIcon1.BalloonTipText = sb.ToString();
1905 //NotifyIcon1.ShowBalloonTip(500);
1906 NotifyIcon1.BalloonTipTitle = title.ToString();
1907 NotifyIcon1.BalloonTipText = bText;
1908 NotifyIcon1.BalloonTipIcon = ntIcon;
1909 NotifyIcon1.ShowBalloonTip(500);
1915 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1919 string dir = Application.StartupPath;
1920 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1922 dir = Path.Combine(dir, "Sounds");
1924 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1934 //mentions新着時に画面ブリンク
1935 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1937 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1941 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1943 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1945 _curItemIndex = _curList.SelectedIndices[0];
1946 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1950 this._curPost = GetCurTabPost(_curItemIndex);
1952 catch (ArgumentException)
1957 this.PushSelectPostChain();
1959 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1961 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1967 private void ChangeCacheStyleRead(bool Read, int Index)
1969 var tabInfo = _statuses.Tabs[_curTab.Text];
1970 //Read:true=既読 false=未読
1971 //未読管理していなかったら既読として扱う
1972 if (!tabInfo.UnreadManage ||
1973 !this._cfgCommon.UnreadManage) Read = true;
1975 var listCache = this._listItemCache;
1976 if (listCache == null)
1979 // キャッシュに含まれていないアイテムは対象外
1982 if (!listCache.TryGetValue(Index, out itm, out post))
1985 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1988 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1995 Item.SubItems[5].Text = "";
2000 Item.SubItems[5].Text = "★";
2006 else if (Post.RetweetedId != null)
2008 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
2010 else if (Read || !this._cfgCommon.UseUnreadStyle)
2015 if (DList == null || Item.Index == -1)
2017 Item.ForeColor = cl;
2018 if (this._cfgCommon.UseUnreadStyle)
2024 if (this._cfgCommon.UseUnreadStyle)
2025 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2027 DList.ChangeItemForeColor(Item.Index, cl);
2028 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2032 private void ColorizeList()
2034 //Index:更新対象のListviewItem.Index。Colorを返す。
2035 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2038 _post = _anchorPost;
2042 if (_post == null) return;
2044 var listCache = this._listItemCache;
2045 if (listCache == null)
2048 var index = listCache.StartIndex;
2049 foreach (var cachedPost in listCache.Post)
2051 var backColor = this.JudgeColor(_post, cachedPost);
2052 this._curList.ChangeItemBackColor(index++, backColor);
2056 private void ColorizeList(ListViewItem Item, int Index)
2058 //Index:更新対象のListviewItem.Index。Colorを返す。
2059 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2062 _post = _anchorPost;
2066 PostClass tPost = GetCurTabPost(Index);
2068 if (_post == null) return;
2070 if (Item.Index == -1)
2071 Item.BackColor = JudgeColor(_post, tPost);
2073 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2076 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2079 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2082 else if (TargetPost.IsMe)
2085 else if (TargetPost.IsReply)
2088 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2090 cl = _clAtFromTarget;
2091 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2094 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2099 cl = _clListBackcolor;
2104 private async void PostButton_Click(object sender, EventArgs e)
2106 if (StatusText.Text.Trim().Length == 0)
2108 if (!ImageSelector.Enabled)
2110 await this.DoRefresh();
2115 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2117 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2119 MessageBoxButtons.YesNoCancel,
2120 MessageBoxIcon.Question);
2123 case DialogResult.Yes:
2124 StatusText.Text = "";
2125 await this.doReTweetOfficial(false);
2127 case DialogResult.Cancel:
2132 var inReplyToStatusId = this.inReplyTo?.Item1;
2133 var inReplyToScreenName = this.inReplyTo?.Item2;
2134 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2136 if (this._cfgCommon.Nicoms)
2138 StatusText.SelectionStart = StatusText.Text.Length;
2139 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2141 //if (SettingDialog.UrlConvertAuto)
2143 // StatusText.SelectionStart = StatusText.Text.Length;
2144 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2146 //else if (SettingDialog.Nicoms)
2148 // StatusText.SelectionStart = StatusText.Text.Length;
2149 // UrlConvert(UrlConverter.Nicoms);
2151 StatusText.SelectionStart = StatusText.Text.Length;
2152 CheckReplyTo(StatusText.Text);
2154 var statusText = this.FormatStatusText(this.StatusText.Text);
2156 if (this.GetRestStatusCount(statusText) < 0)
2158 // 文字数制限を超えているが強制的に投稿するか
2159 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2160 if (ret != DialogResult.OK)
2164 var status = new PostingStatus();
2165 status.status = statusText;
2167 status.inReplyToId = this.inReplyTo?.Item1;
2168 status.inReplyToName = this.inReplyTo?.Item2;
2169 if (ImageSelector.Visible)
2172 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2176 this.inReplyTo = null;
2177 StatusText.Text = "";
2178 _history.Add(new PostingStatus());
2179 _hisIdx = _history.Count - 1;
2180 if (!ToolStripFocusLockMenuItem.Checked)
2181 ((Control)ListTab.SelectedTab.Tag).Focus();
2182 urlUndoBuffer = null;
2183 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2186 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2188 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2189 await this.OpenUriInBrowserAsync(tmp);
2192 await this.PostMessageAsync(status);
2195 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2197 MyCommon._endingFlag = true;
2201 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2203 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2205 //_endingFlag=false:フォームの×ボタン
2207 this.Visible = false;
2211 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2212 _ignoreConfigSave = true;
2213 MyCommon._endingFlag = true;
2214 TimerTimeline.Enabled = false;
2215 TimerRefreshIcon.Enabled = false;
2219 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2221 this.Visible = true;
2222 if (this.WindowState == FormWindowState.Minimized)
2224 this.WindowState = FormWindowState.Normal;
2227 this.BringToFront();
2230 private static int errorCount = 0;
2232 private static bool CheckAccountValid()
2234 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2240 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2249 private Task GetHomeTimelineAsync()
2251 return this.GetHomeTimelineAsync(loadMore: false);
2254 private async Task GetHomeTimelineAsync(bool loadMore)
2256 await this.workerSemaphore.WaitAsync();
2260 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2262 await this.GetHomeTimelineAsyncInternal(progress, this.workerCts.Token, loadMore);
2264 catch (WebApiException ex)
2266 this._myStatusError = true;
2267 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2271 this.workerSemaphore.Release();
2275 private async Task GetHomeTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2277 if (ct.IsCancellationRequested)
2280 if (!CheckAccountValid())
2281 throw new WebApiException("Auth error. Check your account");
2284 if (!this._cfgCommon.UnreadManage)
2287 read = this._initial && this._cfgCommon.Read;
2289 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5, loadMore ? -1 : 1));
2291 await Task.Run(async () =>
2293 await this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Timeline, loadMore, this._initial)
2294 .ConfigureAwait(false);
2297 if (this._cfgCommon.ReadOldPosts)
2298 this._statuses.SetReadHomeTab();
2300 var addCount = this._statuses.DistributePosts();
2303 this.UpdateTimelineSpeed(addCount);
2306 if (ct.IsCancellationRequested)
2309 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1);
2311 this.RefreshTimeline();
2315 /// タイムラインに追加された発言件数を反映し、タイムラインの流速を更新します
2317 /// <param name="addCount">直前にタイムラインに追加した発言件数</param>
2318 private void UpdateTimelineSpeed(int addCount)
2320 var now = DateTime.Now;
2321 this._tlTimestamps.AddOrUpdate(now, addCount, (k, v) => v + addCount);
2323 var removeKeys = new List<DateTime>();
2324 var oneHour = TimeSpan.FromHours(1);
2326 foreach (var pair in this._tlTimestamps)
2328 if (now - pair.Key > oneHour)
2329 removeKeys.Add(pair.Key);
2331 tlCount += pair.Value;
2333 Interlocked.Exchange(ref this._tlCount, tlCount);
2336 foreach (var key in removeKeys)
2337 this._tlTimestamps.TryRemove(key, out _);
2340 private Task GetReplyAsync()
2342 return this.GetReplyAsync(loadMore: false);
2345 private async Task GetReplyAsync(bool loadMore)
2347 await this.workerSemaphore.WaitAsync();
2351 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2353 await this.GetReplyAsyncInternal(progress, this.workerCts.Token, loadMore);
2355 catch (WebApiException ex)
2357 this._myStatusError = true;
2358 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2362 this.workerSemaphore.Release();
2366 private async Task GetReplyAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2368 if (ct.IsCancellationRequested)
2371 if (!CheckAccountValid())
2372 throw new WebApiException("Auth error. Check your account");
2375 if (!this._cfgCommon.UnreadManage)
2378 read = this._initial && this._cfgCommon.Read;
2380 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4, loadMore ? -1 : 1));
2382 await Task.Run(async () =>
2384 await this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Reply, loadMore, this._initial)
2385 .ConfigureAwait(false);
2387 this._statuses.DistributePosts();
2390 if (ct.IsCancellationRequested)
2393 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9);
2395 this.RefreshTimeline();
2398 private Task GetDirectMessagesAsync()
2400 return this.GetDirectMessagesAsync(loadMore: false);
2403 private async Task GetDirectMessagesAsync(bool loadMore)
2405 await this.workerSemaphore.WaitAsync();
2409 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2411 await this.GetDirectMessagesAsyncInternal(progress, this.workerCts.Token, loadMore);
2413 catch (WebApiException ex)
2415 this._myStatusError = true;
2416 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2420 this.workerSemaphore.Release();
2424 private async Task GetDirectMessagesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2426 if (ct.IsCancellationRequested)
2429 if (!CheckAccountValid())
2430 throw new WebApiException("Auth error. Check your account");
2433 if (!this._cfgCommon.UnreadManage)
2436 read = this._initial && this._cfgCommon.Read;
2438 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8, loadMore ? -1 : 1));
2440 await Task.Run(async () =>
2442 await this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, loadMore)
2443 .ConfigureAwait(false);
2444 await this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, loadMore)
2445 .ConfigureAwait(false);
2447 this._statuses.DistributePosts();
2450 if (ct.IsCancellationRequested)
2453 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11);
2455 this.RefreshTimeline();
2458 private Task GetFavoritesAsync()
2460 return this.GetFavoritesAsync(loadMore: false);
2463 private async Task GetFavoritesAsync(bool loadMore)
2465 await this.workerSemaphore.WaitAsync();
2469 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2471 await this.GetFavoritesAsyncInternal(progress, this.workerCts.Token, loadMore);
2473 catch (WebApiException ex)
2475 this._myStatusError = true;
2476 this.StatusLabel.Text = ex.Message;
2480 this.workerSemaphore.Release();
2484 private async Task GetFavoritesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2486 if (ct.IsCancellationRequested)
2489 if (!CheckAccountValid())
2490 throw new WebApiException("Auth error. Check your account");
2493 if (!this._cfgCommon.UnreadManage)
2496 read = this._initial && this._cfgCommon.Read;
2498 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19);
2500 await Task.Run(async () =>
2502 await this.tw.GetFavoritesApi(read, loadMore)
2503 .ConfigureAwait(false);
2505 this._statuses.DistributePosts();
2508 if (ct.IsCancellationRequested)
2511 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20);
2513 this.RefreshTimeline();
2516 private Task GetPublicSearchAllAsync()
2518 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch);
2520 return this.GetPublicSearchAsync(tabs, loadMore: false);
2523 private Task GetPublicSearchAsync(TabClass tab)
2525 return this.GetPublicSearchAsync(tab, loadMore: false);
2528 private Task GetPublicSearchAsync(TabClass tab, bool loadMore)
2530 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2533 private async Task GetPublicSearchAsync(IEnumerable<TabClass> tabs, bool loadMore)
2535 await this.workerSemaphore.WaitAsync();
2539 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2541 await this.GetPublicSearchAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2543 catch (WebApiException ex)
2545 this._myStatusError = true;
2546 this.StatusLabel.Text = ex.Message;
2550 this.workerSemaphore.Release();
2554 private async Task GetPublicSearchAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2556 if (ct.IsCancellationRequested)
2559 if (!CheckAccountValid())
2560 throw new WebApiException("Auth error. Check your account");
2563 if (!this._cfgCommon.UnreadManage)
2566 read = this._initial && this._cfgCommon.Read;
2568 p.Report("Search refreshing...");
2570 await Task.Run(async () =>
2572 WebApiException lastException = null;
2574 foreach (var tab in tabs)
2578 if (string.IsNullOrEmpty(tab.SearchWords))
2581 await this.tw.GetSearch(read, tab, false)
2582 .ConfigureAwait(false);
2585 await this.tw.GetSearch(read, tab, true)
2586 .ConfigureAwait(false);
2588 catch (WebApiException ex)
2594 this._statuses.DistributePosts();
2596 if (lastException != null)
2597 throw new WebApiException(lastException.Message, lastException);
2600 if (ct.IsCancellationRequested)
2603 p.Report("Search refreshed");
2605 this.RefreshTimeline();
2608 private Task GetUserTimelineAllAsync()
2610 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline);
2612 return this.GetUserTimelineAsync(tabs, loadMore: false);
2615 private Task GetUserTimelineAsync(TabClass tab)
2617 return this.GetUserTimelineAsync(tab, loadMore: false);
2620 private Task GetUserTimelineAsync(TabClass tab, bool loadMore)
2622 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2625 private async Task GetUserTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2627 await this.workerSemaphore.WaitAsync();
2631 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2633 await this.GetUserTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2635 catch (WebApiException ex)
2637 this._myStatusError = true;
2638 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2642 this.workerSemaphore.Release();
2646 private async Task GetUserTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2648 if (ct.IsCancellationRequested)
2651 if (!CheckAccountValid())
2652 throw new WebApiException("Auth error. Check your account");
2655 if (!this._cfgCommon.UnreadManage)
2658 read = this._initial && this._cfgCommon.Read;
2660 p.Report("UserTimeline refreshing...");
2662 await Task.Run(async () =>
2664 WebApiException lastException = null;
2666 foreach (var tab in tabs)
2670 if (string.IsNullOrEmpty(tab.User))
2673 await this.tw.GetUserTimelineApi(read, tab.User, tab, loadMore)
2674 .ConfigureAwait(false);
2676 catch (WebApiException ex)
2682 this._statuses.DistributePosts();
2684 if (lastException != null)
2685 throw new WebApiException(lastException.Message, lastException);
2688 if (ct.IsCancellationRequested)
2691 p.Report("UserTimeline refreshed");
2693 this.RefreshTimeline();
2696 private Task GetListTimelineAllAsync()
2698 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.Lists);
2700 return this.GetListTimelineAsync(tabs, loadMore: false);
2703 private Task GetListTimelineAsync(TabClass tab)
2705 return this.GetListTimelineAsync(tab, loadMore: false);
2708 private Task GetListTimelineAsync(TabClass tab, bool loadMore)
2710 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2713 private async Task GetListTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2715 await this.workerSemaphore.WaitAsync();
2719 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2721 await this.GetListTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2723 catch (WebApiException ex)
2725 this._myStatusError = true;
2726 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2730 this.workerSemaphore.Release();
2734 private async Task GetListTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2736 if (ct.IsCancellationRequested)
2739 if (!CheckAccountValid())
2740 throw new WebApiException("Auth error. Check your account");
2743 if (!this._cfgCommon.UnreadManage)
2746 read = this._initial && this._cfgCommon.Read;
2748 p.Report("List refreshing...");
2750 await Task.Run(async () =>
2752 WebApiException lastException = null;
2754 foreach (var tab in tabs)
2758 if (tab.ListInfo == null || tab.ListInfo.Id == 0)
2761 await this.tw.GetListStatus(read, tab, loadMore, this._initial)
2762 .ConfigureAwait(false);
2764 catch (WebApiException ex)
2770 this._statuses.DistributePosts();
2772 if (lastException != null)
2773 throw new WebApiException(lastException.Message, lastException);
2776 if (ct.IsCancellationRequested)
2779 p.Report("List refreshed");
2781 this.RefreshTimeline();
2784 private async Task GetRelatedTweetsAsync(TabClass tab)
2786 await this.workerSemaphore.WaitAsync();
2790 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2792 await this.GetRelatedTweetsAsyncInternal(progress, this.workerCts.Token, tab);
2794 catch (WebApiException ex)
2796 this._myStatusError = true;
2797 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2801 this.workerSemaphore.Release();
2805 private async Task GetRelatedTweetsAsyncInternal(IProgress<string> p, CancellationToken ct, TabClass tab)
2807 if (ct.IsCancellationRequested)
2810 if (!CheckAccountValid())
2811 throw new WebApiException("Auth error. Check your account");
2814 if (!this._cfgCommon.UnreadManage)
2817 read = this._initial && this._cfgCommon.Read;
2819 p.Report("Related refreshing...");
2821 await Task.Run(async () =>
2823 await this.tw.GetRelatedResult(read, tab)
2824 .ConfigureAwait(false);
2826 this._statuses.DistributePosts();
2829 if (ct.IsCancellationRequested)
2832 p.Report("Related refreshed");
2834 this.RefreshTimeline();
2836 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
2837 .FirstOrDefault(x => x.Text == tab.TabName);
2839 if (tabPage != null)
2841 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
2843 var listView = (DetailsListView)tabPage.Tag;
2844 var index = tab.IndexOf(tab.RelationTargetPost.RetweetedId ?? tab.RelationTargetPost.StatusId);
2846 if (index != -1 && index < listView.Items.Count)
2848 listView.SelectedIndices.Add(index);
2849 listView.Items[index].Focused = true;
2854 private async Task FavAddAsync(long statusId, TabClass tab)
2856 await this.workerSemaphore.WaitAsync();
2860 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2862 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2864 catch (WebApiException ex)
2866 this._myStatusError = true;
2867 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2871 this.workerSemaphore.Release();
2875 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabClass tab)
2877 if (ct.IsCancellationRequested)
2880 if (!CheckAccountValid())
2881 throw new WebApiException("Auth error. Check your account");
2884 if (!tab.Posts.TryGetValue(statusId, out post))
2890 await Task.Run(async () =>
2892 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2896 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2898 .ConfigureAwait(false);
2900 if (this._cfgCommon.RestrictFavCheck)
2902 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2903 .ConfigureAwait(false);
2905 if (status.Favorited != true)
2906 throw new WebApiException("NG(Restricted?)");
2909 this._favTimestamps.Add(DateTime.Now);
2912 if (this._statuses.ContainsKey(statusId))
2914 var postTl = this._statuses[statusId];
2915 postTl.IsFav = true;
2917 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2918 favTab.AddPostQueue(statusId, postTl.IsRead);
2921 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2922 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2924 if (tb.Contains(statusId))
2925 tb.Posts[statusId].IsFav = true;
2928 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2930 catch (WebApiException)
2932 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2937 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2938 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2940 if (this._favTimestamps[i] < oneHour)
2941 this._favTimestamps.RemoveAt(i);
2944 this._statuses.DistributePosts();
2947 if (ct.IsCancellationRequested)
2950 this.RefreshTimeline();
2952 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2954 using (ControlTransaction.Update(this._curList))
2956 var idx = tab.IndexOf(statusId);
2958 this.ChangeCacheStyleRead(post.IsRead, idx);
2961 if (statusId == this._curPost.StatusId)
2962 await this.DispSelectedPost(true); // 選択アイテム再表示
2966 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabClass tab)
2968 await this.workerSemaphore.WaitAsync();
2972 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2974 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2976 catch (WebApiException ex)
2978 this._myStatusError = true;
2979 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2983 this.workerSemaphore.Release();
2987 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2989 if (ct.IsCancellationRequested)
2992 if (!CheckAccountValid())
2993 throw new WebApiException("Auth error. Check your account");
2995 var successIds = new List<long>();
2997 await Task.Run(async () =>
3001 var failedCount = 0;
3002 foreach (var statusId in statusIds)
3006 var post = tab.Posts[statusId];
3008 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
3015 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
3017 .ConfigureAwait(false);
3019 catch (WebApiException)
3025 successIds.Add(statusId);
3026 post.IsFav = false; // リスト再描画必要
3028 if (this._statuses.ContainsKey(statusId))
3030 this._statuses[statusId].IsFav = false;
3033 // 検索,リスト,UserTimeline,Relatedの各タブに反映
3034 foreach (var tb in this._statuses.GetTabsInnerStorageType())
3036 if (tb.Contains(statusId))
3037 tb.Posts[statusId].IsFav = false;
3042 if (ct.IsCancellationRequested)
3045 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
3046 foreach (var statusId in successIds)
3048 // ツイートが削除された訳ではないので IsDeleted はセットしない
3049 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
3052 this.RefreshTimeline();
3054 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
3056 if (tab.TabType == MyCommon.TabUsageType.Favorites)
3062 using (ControlTransaction.Update(this._curList))
3064 foreach (var statusId in successIds)
3066 var idx = tab.IndexOf(statusId);
3070 var post = tab.Posts[statusId];
3071 this.ChangeCacheStyleRead(post.IsRead, idx);
3075 if (successIds.Contains(this._curPost.StatusId))
3076 await this.DispSelectedPost(true); // 選択アイテム再表示
3081 private async Task PostMessageAsync(PostingStatus status)
3083 await this.workerSemaphore.WaitAsync();
3087 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3089 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
3091 catch (WebApiException ex)
3093 this._myStatusError = true;
3094 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
3098 this.workerSemaphore.Release();
3102 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
3104 if (ct.IsCancellationRequested)
3107 if (!CheckAccountValid())
3108 throw new WebApiException("Auth error. Check your account");
3110 p.Report("Posting...");
3116 await Task.Run(async () =>
3118 if (status.mediaItems == null || status.mediaItems.Length == 0)
3120 await this.tw.PostStatus(status.status, status.inReplyToId)
3121 .ConfigureAwait(false);
3125 var service = ImageSelector.GetService(status.imageService);
3126 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
3127 .ConfigureAwait(false);
3131 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3133 catch (WebApiException ex)
3135 // 処理は中断せずエラーの表示のみ行う
3136 errMsg = $"Err:{ex.Message}(PostMessage)";
3138 this._myStatusError = true;
3142 // 使い終わった MediaItem は破棄する
3143 if (status.mediaItems != null)
3145 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
3147 disposableItem.Dispose();
3152 if (ct.IsCancellationRequested)
3155 if (!string.IsNullOrEmpty(errMsg) &&
3156 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
3157 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
3159 var ret = MessageBox.Show(
3161 "{0} ---> [ " + errMsg + " ]" + Environment.NewLine +
3162 "\"" + status.status + "\"" + Environment.NewLine +
3164 Properties.Resources.StatusUpdateFailed1,
3165 Properties.Resources.StatusUpdateFailed2),
3166 "Failed to update status",
3167 MessageBoxButtons.RetryCancel,
3168 MessageBoxIcon.Question);
3170 if (ret == DialogResult.Retry)
3172 await this.PostMessageAsync(status);
3176 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3177 if (this.ToolStripFocusLockMenuItem.Checked)
3178 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
3183 this._postTimestamps.Add(DateTime.Now);
3185 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3186 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3188 if (this._postTimestamps[i] < oneHour)
3189 this._postTimestamps.RemoveAt(i);
3192 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
3194 this.HashMgr.ClearHashtag();
3195 this.HashStripSplitButton.Text = "#[-]";
3196 this.HashToggleMenuItem.Checked = false;
3197 this.HashToggleToolStripMenuItem.Checked = false;
3200 this.SetMainWindowTitle();
3202 if (this._cfgCommon.PostAndGet)
3204 if (this.tw.UserStreamActive)
3205 this.RefreshTimeline();
3207 await this.GetHomeTimelineAsync();
3211 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
3213 await this.workerSemaphore.WaitAsync();
3217 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3219 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
3221 catch (WebApiException ex)
3223 this._myStatusError = true;
3224 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
3228 this.workerSemaphore.Release();
3232 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
3234 if (ct.IsCancellationRequested)
3237 if (!CheckAccountValid())
3238 throw new WebApiException("Auth error. Check your account");
3241 if (!this._cfgCommon.UnreadManage)
3244 read = this._initial && this._cfgCommon.Read;
3246 p.Report("Posting...");
3248 var retweetTasks = from statusId in statusIds
3249 select this.tw.PostRetweet(statusId, read);
3251 await Task.WhenAll(retweetTasks)
3252 .ConfigureAwait(false);
3254 if (ct.IsCancellationRequested)
3257 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3259 this._postTimestamps.Add(DateTime.Now);
3261 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3262 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3264 if (this._postTimestamps[i] < oneHour)
3265 this._postTimestamps.RemoveAt(i);
3268 if (this._cfgCommon.PostAndGet && !this.tw.UserStreamActive)
3269 await this.GetHomeTimelineAsync();
3272 private async Task RefreshFollowerIdsAsync()
3274 await this.workerSemaphore.WaitAsync();
3277 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
3279 await this.tw.RefreshFollowerIds();
3281 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
3283 this.RefreshTimeline();
3284 this.PurgeListViewItemCache();
3285 this._curList?.Refresh();
3287 catch (WebApiException ex)
3289 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
3293 this.workerSemaphore.Release();
3297 private async Task RefreshNoRetweetIdsAsync()
3299 await this.workerSemaphore.WaitAsync();
3302 await this.tw.RefreshNoRetweetIds();
3304 this.StatusLabel.Text = "NoRetweetIds refreshed";
3306 catch (WebApiException ex)
3308 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
3312 this.workerSemaphore.Release();
3316 private async Task RefreshBlockIdsAsync()
3318 await this.workerSemaphore.WaitAsync();
3321 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
3323 await this.tw.RefreshBlockIds();
3325 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
3327 catch (WebApiException ex)
3329 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
3333 this.workerSemaphore.Release();
3337 private async Task RefreshTwitterConfigurationAsync()
3339 await this.workerSemaphore.WaitAsync();
3342 await this.tw.RefreshConfiguration();
3344 if (this.tw.Configuration.PhotoSizeLimit != 0)
3346 foreach (var service in this.ImageSelector.GetServices())
3348 service.UpdateTwitterConfiguration(this.tw.Configuration);
3352 this.PurgeListViewItemCache();
3354 this._curList?.Refresh();
3356 catch (WebApiException ex)
3358 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
3362 this.workerSemaphore.Release();
3366 private async Task RefreshMuteUserIdsAsync()
3368 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3372 await tw.RefreshMuteUserIdsAsync();
3374 catch (WebApiException ex)
3376 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3380 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3383 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3385 if (e.Button == MouseButtons.Left)
3387 this.Visible = true;
3388 if (this.WindowState == FormWindowState.Minimized)
3390 this.WindowState = _formWindowState;
3393 this.BringToFront();
3397 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3399 switch (this._cfgCommon.ListDoubleClickAction)
3402 MakeReplyOrDirectStatus();
3405 await this.FavoriteChange(true);
3408 if (_curPost != null)
3409 await this.ShowUserStatus(_curPost.ScreenName, false);
3415 ShowRelatedStatusesMenuItem_Click(null, null);
3418 MoveToHomeToolStripMenuItem_Click(null, null);
3421 StatusOpenMenuItem_Click(null, null);
3429 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3431 await this.FavoriteChange(true);
3434 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3436 await this.FavoriteChange(false);
3440 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3442 await this.FavoritesRetweetOfficial();
3445 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3447 await this.FavoritesRetweetUnofficial();
3450 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3453 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3456 //trueでFavAdd,falseでFavRemove
3457 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3458 || !this.ExistCurrentPost) return;
3460 if (this._curList.SelectedIndices.Count > 1)
3465 // https://support.twitter.com/articles/76915#favoriting
3466 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3467 _DoFavRetweetFlags = false;
3472 if (multiFavoriteChangeDialogEnable)
3474 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3475 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3476 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3478 if (confirm == DialogResult.Cancel)
3486 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3487 if (selectedPost.IsFav)
3489 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3493 await this.FavAddAsync(selectedPost.StatusId, tab);
3497 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3498 .Select(x => this.GetCurTabPost(x))
3499 .Where(x => x.IsFav);
3501 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3502 if (statusIds.Length == 0)
3504 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3508 await this.FavRemoveAsync(statusIds, tab);
3512 private PostClass GetCurTabPost(int Index)
3514 var listCache = this._listItemCache;
3515 if (listCache != null)
3519 if (listCache.TryGetValue(Index, out item, out post))
3523 return _statuses.Tabs[_curTab.Text][Index];
3526 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3528 if (_curList.SelectedIndices.Count > 0)
3529 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3530 else if (_curList.SelectedIndices.Count == 0)
3531 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3534 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3536 if (_curList.SelectedIndices.Count > 0)
3537 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3540 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3542 if ((!_initialLayout) && this.Visible)
3544 if (this.WindowState == FormWindowState.Normal)
3546 _mySize = this.ClientSize;
3547 _mySpDis = this.SplitContainer1.SplitterDistance;
3548 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3549 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3550 ModifySettingLocal = true;
3555 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3557 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3558 if (comparerMode == null)
3561 this.SetSortColumn(comparerMode.Value);
3565 /// 列インデックスからソートを行う ComparerMode を求める
3567 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3568 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3569 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3572 return ComparerMode.Id;
3574 switch (columnIndex)
3577 return ComparerMode.Nickname;
3579 return ComparerMode.Data;
3581 return ComparerMode.Id;
3583 return ComparerMode.Name;
3585 return ComparerMode.Source;
3587 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3593 /// 発言一覧の指定した位置の列でソートする
3595 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3596 private void SetSortColumnByDisplayIndex(int columnIndex)
3598 // 表示上の列の位置から ColumnHeader を求める
3599 var col = this._curList.Columns.Cast<ColumnHeader>()
3600 .Where(x => x.DisplayIndex == columnIndex)
3606 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3607 if (comparerMode == null)
3610 this.SetSortColumn(comparerMode.Value);
3614 /// 発言一覧の最後列の項目でソートする
3616 private void SetSortLastColumn()
3618 // 表示上の最後列にある ColumnHeader を求める
3619 var col = this._curList.Columns.Cast<ColumnHeader>()
3620 .OrderByDescending(x => x.DisplayIndex)
3623 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3624 if (comparerMode == null)
3627 this.SetSortColumn(comparerMode.Value);
3631 /// 発言一覧を指定された ComparerMode に基づいてソートする
3633 private void SetSortColumn(ComparerMode sortColumn)
3635 if (this._cfgCommon.SortOrderLock)
3638 this._statuses.ToggleSortOrder(sortColumn);
3639 this.InitColumnText();
3641 var list = this._curList;
3644 list.Columns[0].Text = this.ColumnText[0];
3645 list.Columns[1].Text = this.ColumnText[2];
3649 for (var i = 0; i <= 7; i++)
3651 list.Columns[i].Text = this.ColumnText[i];
3655 this.PurgeListViewItemCache();
3657 var tab = this._statuses.Tabs[this._curTab.Text];
3658 if (tab.AllCount > 0 && this._curPost != null)
3660 var idx = tab.IndexOf(this._curPost.StatusId);
3663 this.SelectListItem(list, idx);
3664 list.EnsureVisible(idx);
3669 this.ModifySettingCommon = true;
3672 private void TweenMain_LocationChanged(object sender, EventArgs e)
3674 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3676 _myLoc = this.DesktopLocation;
3677 ModifySettingLocal = true;
3681 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3683 if (ListTab.SelectedTab == null) return;
3684 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3685 if (!this.ExistCurrentPost)
3687 ReplyStripMenuItem.Enabled = false;
3688 ReplyAllStripMenuItem.Enabled = false;
3689 DMStripMenuItem.Enabled = false;
3690 ShowProfileMenuItem.Enabled = false;
3691 ShowUserTimelineContextMenuItem.Enabled = false;
3692 ListManageUserContextToolStripMenuItem2.Enabled = false;
3693 MoveToFavToolStripMenuItem.Enabled = false;
3694 TabMenuItem.Enabled = false;
3695 IDRuleMenuItem.Enabled = false;
3696 SourceRuleMenuItem.Enabled = false;
3697 ReadedStripMenuItem.Enabled = false;
3698 UnreadStripMenuItem.Enabled = false;
3702 ShowProfileMenuItem.Enabled = true;
3703 ListManageUserContextToolStripMenuItem2.Enabled = true;
3704 ReplyStripMenuItem.Enabled = true;
3705 ReplyAllStripMenuItem.Enabled = true;
3706 DMStripMenuItem.Enabled = true;
3707 ShowUserTimelineContextMenuItem.Enabled = true;
3708 MoveToFavToolStripMenuItem.Enabled = true;
3709 TabMenuItem.Enabled = true;
3710 IDRuleMenuItem.Enabled = true;
3711 SourceRuleMenuItem.Enabled = true;
3712 ReadedStripMenuItem.Enabled = true;
3713 UnreadStripMenuItem.Enabled = true;
3715 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3717 FavAddToolStripMenuItem.Enabled = false;
3718 FavRemoveToolStripMenuItem.Enabled = false;
3719 StatusOpenMenuItem.Enabled = false;
3720 FavorareMenuItem.Enabled = false;
3721 ShowRelatedStatusesMenuItem.Enabled = false;
3723 ReTweetStripMenuItem.Enabled = false;
3724 ReTweetUnofficialStripMenuItem.Enabled = false;
3725 QuoteStripMenuItem.Enabled = false;
3726 FavoriteRetweetContextMenu.Enabled = false;
3727 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3731 FavAddToolStripMenuItem.Enabled = true;
3732 FavRemoveToolStripMenuItem.Enabled = true;
3733 StatusOpenMenuItem.Enabled = true;
3734 FavorareMenuItem.Enabled = true;
3735 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3739 ReTweetStripMenuItem.Enabled = false; //公式RTは無効に
3740 ReTweetUnofficialStripMenuItem.Enabled = true;
3741 QuoteStripMenuItem.Enabled = true;
3742 FavoriteRetweetContextMenu.Enabled = false; //公式RTは無効に
3743 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3747 if (_curPost.IsProtect)
3749 ReTweetStripMenuItem.Enabled = false;
3750 ReTweetUnofficialStripMenuItem.Enabled = false;
3751 QuoteStripMenuItem.Enabled = false;
3752 FavoriteRetweetContextMenu.Enabled = false;
3753 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3757 ReTweetStripMenuItem.Enabled = true;
3758 ReTweetUnofficialStripMenuItem.Enabled = true;
3759 QuoteStripMenuItem.Enabled = true;
3760 FavoriteRetweetContextMenu.Enabled = true;
3761 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3765 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3767 // RefreshMoreStripMenuItem.Enabled = true;
3771 // RefreshMoreStripMenuItem.Enabled = false;
3773 if (!this.ExistCurrentPost
3774 || _curPost.InReplyToStatusId == null)
3776 RepliedStatusOpenMenuItem.Enabled = false;
3780 RepliedStatusOpenMenuItem.Enabled = true;
3782 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3784 MoveToRTHomeMenuItem.Enabled = false;
3788 MoveToRTHomeMenuItem.Enabled = true;
3791 if (this.ExistCurrentPost)
3793 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3794 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3795 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3797 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3801 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3803 MakeReplyOrDirectStatus(false, true);
3806 private void DMStripMenuItem_Click(object sender, EventArgs e)
3808 MakeReplyOrDirectStatus(false, false);
3811 private async Task doStatusDelete()
3813 if (this._curTab == null || this._curList == null)
3816 if (this._curList.SelectedIndices.Count == 0)
3819 var posts = this._curList.SelectedIndices.Cast<int>()
3820 .Select(x => this.GetCurTabPost(x))
3823 // 選択されたツイートの中に削除可能なものが一つでもあるか
3824 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3827 var ret = MessageBox.Show(this,
3828 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3829 Properties.Resources.DeleteStripMenuItem_ClickText2,
3830 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3832 if (ret != DialogResult.OK)
3835 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3837 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3839 Exception lastException = null;
3840 foreach (var post in posts)
3842 if (!post.CanDeleteBy(this.tw.UserId))
3849 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3854 if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3855 // 他人に RT された自分のツイート
3856 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3859 // 自分のツイート or 自分が RT したツイート
3860 await this.twitterApi.StatusesDestroy(post.StatusId)
3864 catch (WebApiException ex)
3870 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3873 if (lastException == null)
3874 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3876 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3878 this.PurgeListViewItemCache();
3879 this._curPost = null;
3880 this._curItemIndex = -1;
3882 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3884 var listView = (DetailsListView)tabPage.Tag;
3885 var tab = this._statuses.Tabs[tabPage.Text];
3887 using (ControlTransaction.Update(listView))
3889 listView.VirtualListSize = tab.AllCount;
3891 if (tabPage == this._curTab)
3893 listView.SelectedIndices.Clear();
3895 if (tab.AllCount != 0)
3898 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3899 selectedIndex = focusedIndex;
3901 selectedIndex = tab.AllCount - 1;
3903 listView.SelectedIndices.Add(selectedIndex);
3904 listView.EnsureVisible(selectedIndex);
3905 listView.FocusedItem = listView.Items[selectedIndex];
3910 if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3912 if (tabPage.ImageIndex == 0)
3913 tabPage.ImageIndex = -1; // タブアイコン
3917 if (!this._cfgCommon.TabIconDisp)
3918 this.ListTab.Refresh();
3922 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3924 await this.doStatusDelete();
3927 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3929 using (ControlTransaction.Update(this._curList))
3931 foreach (int idx in _curList.SelectedIndices)
3933 var post = this._statuses.Tabs[this._curTab.Text][idx];
3934 this._statuses.SetReadAllTab(post.StatusId, read: true);
3935 ChangeCacheStyleRead(true, idx);
3939 foreach (TabPage tb in ListTab.TabPages)
3941 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3943 if (this._cfgCommon.TabIconDisp)
3945 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3949 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3952 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3954 using (ControlTransaction.Update(this._curList))
3956 foreach (int idx in _curList.SelectedIndices)
3958 var post = this._statuses.Tabs[this._curTab.Text][idx];
3959 this._statuses.SetReadAllTab(post.StatusId, read: false);
3960 ChangeCacheStyleRead(false, idx);
3964 foreach (TabPage tb in ListTab.TabPages)
3966 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3968 if (this._cfgCommon.TabIconDisp)
3970 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3974 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3977 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3979 await this.DoRefresh();
3982 private async Task DoRefresh()
3984 if (_curTab != null)
3987 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3990 switch (_statuses.Tabs[_curTab.Text].TabType)
3992 case MyCommon.TabUsageType.Mentions:
3993 await this.GetReplyAsync();
3995 case MyCommon.TabUsageType.DirectMessage:
3996 await this.GetDirectMessagesAsync();
3998 case MyCommon.TabUsageType.Favorites:
3999 await this.GetFavoritesAsync();
4001 //case MyCommon.TabUsageType.Profile:
4003 case MyCommon.TabUsageType.PublicSearch:
4005 if (string.IsNullOrEmpty(tab.SearchWords)) return;
4006 await this.GetPublicSearchAsync(tab);
4008 case MyCommon.TabUsageType.UserTimeline:
4009 await this.GetUserTimelineAsync(tab);
4011 case MyCommon.TabUsageType.Lists:
4013 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4014 await this.GetListTimelineAsync(tab);
4017 await this.GetHomeTimelineAsync();
4023 await this.GetHomeTimelineAsync();
4027 private async Task DoRefreshMore()
4030 if (_curTab != null)
4033 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4036 switch (_statuses.Tabs[_curTab.Text].TabType)
4038 case MyCommon.TabUsageType.Mentions:
4039 await this.GetReplyAsync(loadMore: true);
4041 case MyCommon.TabUsageType.DirectMessage:
4042 await this.GetDirectMessagesAsync(loadMore: true);
4044 case MyCommon.TabUsageType.Favorites:
4045 await this.GetFavoritesAsync(loadMore: true);
4047 case MyCommon.TabUsageType.Profile:
4050 case MyCommon.TabUsageType.PublicSearch:
4052 if (string.IsNullOrEmpty(tab.SearchWords)) return;
4053 await this.GetPublicSearchAsync(tab, loadMore: true);
4055 case MyCommon.TabUsageType.UserTimeline:
4056 await this.GetUserTimelineAsync(tab, loadMore: true);
4058 case MyCommon.TabUsageType.Lists:
4060 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4061 await this.GetListTimelineAsync(tab, loadMore: true);
4064 await this.GetHomeTimelineAsync(loadMore: true);
4070 await this.GetHomeTimelineAsync(loadMore: true);
4074 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
4076 DialogResult result = DialogResult.Abort;
4078 using (var settingDialog = new AppendSettingDialog())
4080 settingDialog.Icon = this.MainIcon;
4081 settingDialog.Owner = this;
4082 settingDialog.ShowInTaskbar = showTaskbarIcon;
4083 settingDialog.IntervalChanged += this.TimerInterval_Changed;
4085 settingDialog.tw = this.tw;
4086 settingDialog.twitterApi = this.twitterApi;
4088 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
4092 result = settingDialog.ShowDialog(this);
4096 return DialogResult.Abort;
4099 if (result == DialogResult.OK)
4103 settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
4111 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
4114 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
4116 var oldIconSz = this._cfgCommon.IconSize;
4118 if (ShowSettingDialog() == DialogResult.OK)
4122 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
4123 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
4124 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
4125 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
4126 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
4127 TwitterApiConnection.RestApiBase = this._cfgCommon.TwitterApiBaseUri;
4129 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
4130 Networking.SetWebProxy(this._cfgLocal.ProxyType,
4131 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
4132 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
4133 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
4135 ImageSelector.Reset(tw, this.tw.Configuration);
4139 if (this._cfgCommon.TabIconDisp)
4141 ListTab.DrawItem -= ListTab_DrawItem;
4142 ListTab.DrawMode = TabDrawMode.Normal;
4143 ListTab.ImageList = this.TabImage;
4147 ListTab.DrawItem -= ListTab_DrawItem;
4148 ListTab.DrawItem += ListTab_DrawItem;
4149 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
4150 ListTab.ImageList = null;
4153 catch (Exception ex)
4155 ex.Data["Instance"] = "ListTab(TabIconDisp)";
4156 ex.Data["IsTerminatePermission"] = false;
4162 if (!this._cfgCommon.UnreadManage)
4164 ReadedStripMenuItem.Enabled = false;
4165 UnreadStripMenuItem.Enabled = false;
4166 if (this._cfgCommon.TabIconDisp)
4168 foreach (TabPage myTab in ListTab.TabPages)
4170 myTab.ImageIndex = -1;
4176 ReadedStripMenuItem.Enabled = true;
4177 UnreadStripMenuItem.Enabled = true;
4180 catch (Exception ex)
4182 ex.Data["Instance"] = "ListTab(UnreadManage)";
4183 ex.Data["IsTerminatePermission"] = false;
4190 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
4192 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
4193 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
4194 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
4196 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
4197 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
4198 _fntUnread = this._cfgLocal.FontUnread;
4199 _clUnread = this._cfgLocal.ColorUnread;
4200 _fntReaded = this._cfgLocal.FontRead;
4201 _clReaded = this._cfgLocal.ColorRead;
4202 _clFav = this._cfgLocal.ColorFav;
4203 _clOWL = this._cfgLocal.ColorOWL;
4204 _clRetweet = this._cfgLocal.ColorRetweet;
4205 _fntDetail = this._cfgLocal.FontDetail;
4206 _clDetail = this._cfgLocal.ColorDetail;
4207 _clDetailLink = this._cfgLocal.ColorDetailLink;
4208 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
4209 _clSelf = this._cfgLocal.ColorSelf;
4210 _clAtSelf = this._cfgLocal.ColorAtSelf;
4211 _clTarget = this._cfgLocal.ColorTarget;
4212 _clAtTarget = this._cfgLocal.ColorAtTarget;
4213 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
4214 _clAtTo = this._cfgLocal.ColorAtTo;
4215 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
4216 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
4217 _clInputFont = this._cfgLocal.ColorInputFont;
4218 _fntInputFont = this._cfgLocal.FontInputFont;
4219 _brsBackColorMine.Dispose();
4220 _brsBackColorAt.Dispose();
4221 _brsBackColorYou.Dispose();
4222 _brsBackColorAtYou.Dispose();
4223 _brsBackColorAtFromTarget.Dispose();
4224 _brsBackColorAtTo.Dispose();
4225 _brsBackColorNone.Dispose();
4226 _brsBackColorMine = new SolidBrush(_clSelf);
4227 _brsBackColorAt = new SolidBrush(_clAtSelf);
4228 _brsBackColorYou = new SolidBrush(_clTarget);
4229 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4230 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4231 _brsBackColorAtTo = new SolidBrush(_clAtTo);
4232 _brsBackColorNone = new SolidBrush(_clListBackcolor);
4236 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4237 StatusText.Font = _fntInputFont;
4238 StatusText.ForeColor = _clInputFont;
4240 catch (Exception ex)
4242 MessageBox.Show(ex.Message);
4247 InitDetailHtmlFormat();
4249 catch (Exception ex)
4251 ex.Data["Instance"] = "Font";
4252 ex.Data["IsTerminatePermission"] = false;
4258 foreach (TabPage tb in ListTab.TabPages)
4260 if (this._cfgCommon.TabIconDisp)
4262 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4269 catch (Exception ex)
4271 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4272 ex.Data["IsTerminatePermission"] = false;
4278 var oldIconCol = _iconCol;
4280 if (this._cfgCommon.IconSize != oldIconSz)
4281 ApplyListViewIconSize(this._cfgCommon.IconSize);
4283 foreach (TabPage tp in ListTab.TabPages)
4285 DetailsListView lst = (DetailsListView)tp.Tag;
4287 using (ControlTransaction.Update(lst))
4289 lst.GridLines = this._cfgCommon.ShowGrid;
4290 lst.Font = _fntReaded;
4291 lst.BackColor = _clListBackcolor;
4293 if (_iconCol != oldIconCol)
4298 catch (Exception ex)
4300 ex.Data["Instance"] = "ListView(IconSize)";
4301 ex.Data["IsTerminatePermission"] = false;
4305 SetMainWindowTitle();
4306 SetNotifyIconText();
4308 this.PurgeListViewItemCache();
4309 _curList?.Refresh();
4312 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4313 if (this._cfgCommon.HotkeyEnabled)
4315 ///グローバルホットキーの登録。設定で変更可能にするかも
4316 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4317 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4318 modKey |= HookGlobalHotkey.ModKeys.Alt;
4319 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4320 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4321 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4322 modKey |= HookGlobalHotkey.ModKeys.Shift;
4323 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4324 modKey |= HookGlobalHotkey.ModKeys.Win;
4326 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4329 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4332 StatusText_TextChanged(null, null);
4341 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
4342 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
4345 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4347 this.TopMost = this._cfgCommon.AlwaysTop;
4348 SaveConfigsAll(false);
4350 if (tw.Username != oldUser.Username)
4351 await this.doGetFollowersMenu();
4357 private void SetTabAlignment()
4359 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4360 if (ListTab.Alignment == newAlignment) return;
4362 // 各タブのリスト上の選択位置などを退避
4363 var listSelections = this.SaveListViewSelection();
4365 ListTab.Alignment = newAlignment;
4367 foreach (TabPage tab in ListTab.TabPages)
4369 DetailsListView lst = (DetailsListView)tab.Tag;
4370 TabClass tabInfo = _statuses.Tabs[tab.Text];
4371 using (ControlTransaction.Update(lst))
4374 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4379 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4385 case MyCommon.IconSizes.IconNone:
4388 case MyCommon.IconSizes.Icon16:
4391 case MyCommon.IconSizes.Icon24:
4394 case MyCommon.IconSizes.Icon48:
4397 case MyCommon.IconSizes.Icon48_2:
4405 // ディスプレイの DPI 設定を考慮したサイズを設定する
4406 _listViewImageList.ImageSize = new Size(
4408 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4412 _listViewImageList.ImageSize = new Size(1, 1);
4416 private void ResetColumns(DetailsListView list)
4418 using (ControlTransaction.Update(list))
4419 using (ControlTransaction.Layout(list, false))
4422 list.ColumnClick -= MyList_ColumnClick;
4423 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4424 list.ColumnReordered -= MyList_ColumnReordered;
4425 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4427 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4428 list.Columns.Clear();
4429 cols.ForEach(col => col.Dispose());
4432 InitColumns(list, true);
4434 list.ColumnClick += MyList_ColumnClick;
4435 list.DrawColumnHeader += MyList_DrawColumnHeader;
4436 list.ColumnReordered += MyList_ColumnReordered;
4437 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4441 private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4443 if (e.Url.AbsoluteUri != "about:blank")
4445 await this.DispSelectedPost();
4446 await this.OpenUriInBrowserAsync(e.Url.OriginalString);
4450 private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4452 if (e.Url.Scheme == "data")
4454 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4456 else if (e.Url.AbsoluteUri != "about:blank")
4459 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
4460 await this.OpenUriAsync( e.Url, MyCommon.IsKeyDown( Keys.Control ) );
4464 public void AddNewTabForSearch(string searchWord)
4466 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4467 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4469 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4471 foreach (TabPage tp in ListTab.TabPages)
4473 if (tb.TabName == tp.Text)
4475 ListTab.SelectedTab = tp;
4482 string tabName = searchWord;
4483 for (int i = 0; i <= 100; i++)
4485 if (_statuses.ContainsTab(tabName))
4491 _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4492 AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4494 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4496 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4497 cmb.Items.Add(searchWord);
4498 cmb.Text = searchWord;
4501 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4504 private void ShowUserTimeline()
4506 if (!this.ExistCurrentPost) return;
4507 AddNewTabForUserTimeline(_curPost.ScreenName);
4510 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4512 if (e.KeyCode == Keys.Escape)
4514 TabPage relTp = ListTab.SelectedTab;
4515 RemoveSpecifiedTab(relTp.Text, false);
4517 e.SuppressKeyPress = true;
4521 public void AddNewTabForUserTimeline(string user)
4523 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4524 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4526 if (tb.User == user)
4528 foreach (TabPage tp in ListTab.TabPages)
4530 if (tb.TabName == tp.Text)
4532 ListTab.SelectedTab = tp;
4539 string tabName = "user:" + user;
4540 while (_statuses.ContainsTab(tabName))
4545 var tab = new TabClass(tabName, MyCommon.TabUsageType.UserTimeline);
4546 this._statuses.AddTab(tab);
4548 AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4550 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4553 this.GetUserTimelineAsync(tab);
4556 public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4559 foreach (TabPage tb in ListTab.TabPages)
4561 if (tb.Text == tabName) return false;
4565 if (tabName == Properties.Resources.AddNewTabText1) return false;
4570 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4571 tabType == MyCommon.TabUsageType.Favorites ||
4572 tabType == MyCommon.TabUsageType.Home ||
4573 tabType == MyCommon.TabUsageType.Mentions ||
4574 tabType == MyCommon.TabUsageType.Related)
4576 if (_statuses.GetTabByType(tabType) != null) return false;
4580 var _tabPage = new TabPage();
4581 var _listCustom = new DetailsListView();
4583 int cnt = ListTab.TabPages.Count;
4585 ///ToDo:Create and set controls follow tabtypes
4587 using (ControlTransaction.Update(_listCustom))
4588 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4589 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4590 using (ControlTransaction.Layout(this.SplitContainer1, false))
4591 using (ControlTransaction.Layout(this.ListTab, false))
4592 using (ControlTransaction.Layout(this))
4593 using (ControlTransaction.Layout(_tabPage, false))
4595 _tabPage.Controls.Add(_listCustom);
4598 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4600 var label = new Label();
4601 label.Dock = DockStyle.Top;
4602 label.Name = "labelUser";
4604 if (tabType == MyCommon.TabUsageType.Lists)
4606 label.Text = listInfo.ToString();
4610 label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4612 label.TextAlign = ContentAlignment.MiddleLeft;
4613 using (ComboBox tmpComboBox = new ComboBox())
4615 label.Height = tmpComboBox.Height;
4617 _tabPage.Controls.Add(label);
4620 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4622 var pnl = new Panel();
4624 var lbl = new Label();
4625 var cmb = new ComboBox();
4626 var btn = new Button();
4627 var cmbLang = new ComboBox();
4629 using (ControlTransaction.Layout(pnl, false))
4631 pnl.Controls.Add(cmb);
4632 pnl.Controls.Add(cmbLang);
4633 pnl.Controls.Add(btn);
4634 pnl.Controls.Add(lbl);
4635 pnl.Name = "panelSearch";
4637 pnl.Dock = DockStyle.Top;
4638 pnl.Height = cmb.Height;
4639 pnl.Enter += SearchControls_Enter;
4640 pnl.Leave += SearchControls_Leave;
4643 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4644 cmb.Dock = DockStyle.Fill;
4645 cmb.Name = "comboSearch";
4646 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4647 cmb.ImeMode = ImeMode.NoControl;
4648 cmb.TabStop = false;
4650 cmb.AutoCompleteMode = AutoCompleteMode.None;
4651 cmb.KeyDown += SearchComboBox_KeyDown;
4654 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4655 cmbLang.Dock = DockStyle.Right;
4657 cmbLang.Name = "comboLang";
4658 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4659 cmbLang.TabStop = false;
4660 cmbLang.TabIndex = 2;
4661 cmbLang.Items.Add("");
4662 cmbLang.Items.Add("ja");
4663 cmbLang.Items.Add("en");
4664 cmbLang.Items.Add("ar");
4665 cmbLang.Items.Add("da");
4666 cmbLang.Items.Add("nl");
4667 cmbLang.Items.Add("fa");
4668 cmbLang.Items.Add("fi");
4669 cmbLang.Items.Add("fr");
4670 cmbLang.Items.Add("de");
4671 cmbLang.Items.Add("hu");
4672 cmbLang.Items.Add("is");
4673 cmbLang.Items.Add("it");
4674 cmbLang.Items.Add("no");
4675 cmbLang.Items.Add("pl");
4676 cmbLang.Items.Add("pt");
4677 cmbLang.Items.Add("ru");
4678 cmbLang.Items.Add("es");
4679 cmbLang.Items.Add("sv");
4680 cmbLang.Items.Add("th");
4682 lbl.Text = "Search(C-S-f)";
4683 lbl.Name = "label1";
4684 lbl.Dock = DockStyle.Left;
4686 lbl.Height = cmb.Height;
4687 lbl.TextAlign = ContentAlignment.MiddleLeft;
4690 btn.Text = "Search";
4691 btn.Name = "buttonSearch";
4692 btn.UseVisualStyleBackColor = true;
4693 btn.Dock = DockStyle.Right;
4694 btn.TabStop = false;
4696 btn.Click += SearchButton_Click;
4699 if (_statuses.Tabs.TryGetValue(tabName, out tab))
4701 if (!string.IsNullOrEmpty(tab.SearchWords))
4703 cmb.Items.Add(tab.SearchWords);
4704 cmb.Text = tab.SearchWords;
4707 cmbLang.Text = tab.SearchLang;
4710 _tabPage.Controls.Add(pnl);
4714 _tabPage.Tag = _listCustom;
4715 this.ListTab.Controls.Add(_tabPage);
4717 _tabPage.Location = new Point(4, 4);
4718 _tabPage.Name = "CTab" + cnt.ToString();
4719 _tabPage.Size = new Size(380, 260);
4720 _tabPage.TabIndex = 2 + cnt;
4721 _tabPage.Text = tabName;
4722 _tabPage.UseVisualStyleBackColor = true;
4723 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4725 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4726 _listCustom.TabIndex = 1;
4727 _listCustom.AllowColumnReorder = true;
4728 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4729 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4730 _listCustom.Dock = DockStyle.Fill;
4731 _listCustom.FullRowSelect = true;
4732 _listCustom.HideSelection = false;
4733 _listCustom.Location = new Point(0, 0);
4734 _listCustom.Margin = new Padding(0);
4735 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4736 _listCustom.ShowItemToolTips = true;
4737 _listCustom.Size = new Size(380, 260);
4738 _listCustom.UseCompatibleStateImageBehavior = false;
4739 _listCustom.View = View.Details;
4740 _listCustom.OwnerDraw = true;
4741 _listCustom.VirtualMode = true;
4742 _listCustom.Font = _fntReaded;
4743 _listCustom.BackColor = _clListBackcolor;
4745 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4746 _listCustom.AllowDrop = true;
4748 _listCustom.SmallImageList = _listViewImageList;
4750 InitColumns(_listCustom, startup);
4752 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4753 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4754 _listCustom.ColumnClick += MyList_ColumnClick;
4755 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4756 _listCustom.DragDrop += TweenMain_DragDrop;
4757 _listCustom.DragEnter += TweenMain_DragEnter;
4758 _listCustom.DragOver += TweenMain_DragOver;
4759 _listCustom.DrawItem += MyList_DrawItem;
4760 _listCustom.MouseClick += MyList_MouseClick;
4761 _listCustom.ColumnReordered += MyList_ColumnReordered;
4762 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4763 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4764 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4765 _listCustom.DrawSubItem += MyList_DrawSubItem;
4766 _listCustom.HScrolled += MyList_HScrolled;
4772 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4774 var tabInfo = _statuses.GetTabByName(TabName);
4775 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4779 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4780 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4781 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4787 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4788 if (_tabPage == null) return false;
4790 SetListProperty(); //他のタブに列幅等を反映
4793 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4794 _tabPage.Tag = null;
4796 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4797 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4798 using (ControlTransaction.Layout(this.SplitContainer1, false))
4799 using (ControlTransaction.Layout(this.ListTab, false))
4800 using (ControlTransaction.Layout(this))
4801 using (ControlTransaction.Layout(_tabPage, false))
4803 if (this.ListTab.SelectedTab == _tabPage)
4805 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4806 this._beforeSelectedTab = null;
4808 this.ListTab.Controls.Remove(_tabPage);
4811 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4813 using (Control label = _tabPage.Controls["labelUser"])
4815 _tabPage.Controls.Remove(label);
4818 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4820 using (Control pnl = _tabPage.Controls["panelSearch"])
4822 pnl.Enter -= SearchControls_Enter;
4823 pnl.Leave -= SearchControls_Leave;
4824 _tabPage.Controls.Remove(pnl);
4826 foreach (Control ctrl in pnl.Controls)
4828 if (ctrl.Name == "buttonSearch")
4830 ctrl.Click -= SearchButton_Click;
4832 else if (ctrl.Name == "comboSearch")
4834 ctrl.KeyDown -= SearchComboBox_KeyDown;
4836 pnl.Controls.Remove(ctrl);
4842 _tabPage.Controls.Remove(_listCustom);
4844 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4845 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4846 _listCustom.ColumnClick -= MyList_ColumnClick;
4847 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4848 _listCustom.DragDrop -= TweenMain_DragDrop;
4849 _listCustom.DragEnter -= TweenMain_DragEnter;
4850 _listCustom.DragOver -= TweenMain_DragOver;
4851 _listCustom.DrawItem -= MyList_DrawItem;
4852 _listCustom.MouseClick -= MyList_MouseClick;
4853 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4854 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4855 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4856 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4857 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4858 _listCustom.HScrolled -= MyList_HScrolled;
4860 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4861 _listCustom.Columns.Clear();
4862 cols.ForEach(col => col.Dispose());
4865 _listCustom.ContextMenuStrip = null;
4866 _listCustom.ColumnHeaderContextMenuStrip = null;
4867 _listCustom.Font = null;
4869 _listCustom.SmallImageList = null;
4870 _listCustom.ListViewItemSorter = null;
4873 if (_curTab.Equals(_tabPage))
4880 this.PurgeListViewItemCache();
4884 _listCustom.Dispose();
4885 _statuses.RemoveTab(TabName);
4887 foreach (TabPage tp in ListTab.TabPages)
4889 DetailsListView lst = (DetailsListView)tp.Tag;
4890 var count = _statuses.Tabs[tp.Text].AllCount;
4891 if (lst.VirtualListSize != count)
4893 lst.VirtualListSize = count;
4900 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4902 this.PurgeListViewItemCache();
4903 _beforeSelectedTab = e.TabPage;
4906 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4910 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4913 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4914 if (!dragEnableRectangle.Contains(e.Location))
4916 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4917 tn = ListTab.SelectedTab.Text;
4920 if (string.IsNullOrEmpty(tn)) return;
4922 foreach (TabPage tb in ListTab.TabPages)
4926 ListTab.DoDragDrop(tb, DragDropEffects.All);
4936 Point cpos = new Point(e.X, e.Y);
4937 for (int i = 0; i < ListTab.TabPages.Count; i++)
4939 Rectangle rect = ListTab.GetTabRect(i);
4940 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4941 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4943 _rclickTabName = ListTab.TabPages[i].Text;
4949 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4951 //_curList.Refresh();
4952 SetMainWindowTitle();
4953 SetStatusLabelUrl();
4954 SetApiStatusLabel();
4955 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4956 TabMenuControl(ListTab.SelectedTab.Text);
4957 this.PushSelectPostChain();
4958 await DispSelectedPost();
4961 private void SetListProperty()
4963 //削除などで見つからない場合は処理せず
4964 if (_curList == null) return;
4965 if (!_isColumnChanged) return;
4967 int[] dispOrder = new int[_curList.Columns.Count];
4968 for (int i = 0; i < _curList.Columns.Count; i++)
4970 for (int j = 0; j < _curList.Columns.Count; j++)
4972 if (_curList.Columns[j].DisplayIndex == i)
4981 foreach (TabPage tb in ListTab.TabPages)
4983 if (!tb.Equals(_curTab))
4985 if (tb.Tag != null && tb.Controls.Count > 0)
4987 DetailsListView lst = (DetailsListView)tb.Tag;
4988 for (int i = 0; i < lst.Columns.Count; i++)
4990 lst.Columns[dispOrder[i]].DisplayIndex = i;
4991 lst.Columns[i].Width = _curList.Columns[i].Width;
4997 _isColumnChanged = false;
5000 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
5004 if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal)
5005 || PostBrowser.StatusText.StartsWith("ftp", StringComparison.Ordinal)
5006 || PostBrowser.StatusText.StartsWith("data", StringComparison.Ordinal))
5008 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
5010 if (string.IsNullOrEmpty(PostBrowser.StatusText))
5012 SetStatusLabelUrl();
5020 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
5022 if (e.KeyChar == '@')
5024 if (!this._cfgCommon.UseAtIdSupplement) return;
5026 int cnt = AtIdSupl.ItemCount;
5027 ShowSuplDialog(StatusText, AtIdSupl);
5028 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
5031 else if (e.KeyChar == '#')
5033 if (!this._cfgCommon.UseHashSupplement) return;
5034 ShowSuplDialog(StatusText, HashSupl);
5039 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
5041 ShowSuplDialog(owner, dialog, 0, "");
5044 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
5046 ShowSuplDialog(owner, dialog, offset, "");
5049 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
5051 dialog.StartsWith = startswith;
5058 dialog.ShowDialog();
5060 this.TopMost = this._cfgCommon.AlwaysTop;
5061 int selStart = owner.SelectionStart;
5064 if (dialog.DialogResult == DialogResult.OK)
5066 if (!string.IsNullOrEmpty(dialog.inputText))
5070 fHalf = owner.Text.Substring(0, selStart - offset);
5072 if (selStart < owner.Text.Length)
5074 eHalf = owner.Text.Substring(selStart);
5076 owner.Text = fHalf + dialog.inputText + eHalf;
5077 owner.SelectionStart = selStart + dialog.inputText.Length;
5084 fHalf = owner.Text.Substring(0, selStart);
5086 if (selStart < owner.Text.Length)
5088 eHalf = owner.Text.Substring(selStart);
5090 owner.Text = fHalf + eHalf;
5093 owner.SelectionStart = selStart;
5099 private void StatusText_KeyUp(object sender, KeyEventArgs e)
5102 if (!e.Alt && !e.Control && !e.Shift)
5104 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
5106 bool isSpace = false;
5107 foreach (char c in StatusText.Text.ToCharArray())
5109 if (c == ' ' || c == ' ')
5122 StatusText.Text = "";
5123 JumpUnreadMenuItem_Click(null, null);
5127 this.StatusText_TextChanged(null, null);
5130 private void StatusText_TextChanged(object sender, EventArgs e)
5133 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
5134 lblLen.Text = pLen.ToString();
5137 StatusText.ForeColor = Color.Red;
5141 StatusText.ForeColor = _clInputFont;
5143 if (string.IsNullOrEmpty(StatusText.Text))
5145 this.inReplyTo = null;
5150 /// ツイート投稿前のフッター付与などの前処理を行います
5152 private string FormatStatusText(string statusText)
5154 statusText = statusText.Replace("\r\n", "\n");
5156 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
5159 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
5162 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
5164 // 文中の全角スペースを半角スペース1個にする
5165 statusText = statusText.Replace(" ", " ");
5168 // DM の場合はこれ以降の処理を行わない
5169 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
5173 if (this._cfgCommon.PostShiftEnter)
5175 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5179 if (this.StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
5180 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5182 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
5185 if (statusText.Contains("RT @"))
5186 disableFooter = true;
5191 var hashtag = this.HashMgr.UseHash;
5192 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
5195 header = HashMgr.UseHash + " ";
5197 footer = " " + HashMgr.UseHash;
5202 if (this._cfgLocal.UseRecommendStatus)
5205 footer += this.recommendedStatusFooter;
5207 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
5209 // テキストボックスに入力されている文字列を使用する
5210 footer += " " + this._cfgLocal.StatusText.Trim();
5214 statusText = header + statusText + footer;
5216 if (this.ToolStripMenuItemPreventSmsCommand.Checked)
5218 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
5219 // 参照: https://support.twitter.com/articles/14020
5221 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
5222 && !Twitter.DMSendTextRegex.IsMatch(statusText))
5224 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
5225 statusText = '\u200b' + statusText;
5233 /// 投稿欄に表示する入力可能な文字数を計算します
5235 private int GetRestStatusCount(string statusText)
5238 var remainCount = this.tw.GetTextLengthRemain(statusText);
5240 if (this.ImageSelector.Visible && !string.IsNullOrEmpty(this.ImageSelector.ServiceName))
5242 remainCount -= this.tw.Configuration.CharactersReservedPerMedia;
5248 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5250 if (sender != this._curList)
5253 var listCache = this._listItemCache;
5254 if (listCache != null && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
5256 // If the newly requested cache is a subset of the old cache,
5257 // no need to rebuild everything, so do nothing.
5261 // Now we need to rebuild the cache.
5262 this.CreateCache(e.StartIndex, e.EndIndex);
5265 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5267 var listCache = this._listItemCache;
5268 if (listCache != null && listCache.TargetList == sender)
5271 PostClass cacheItemPost;
5272 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
5279 // A cache miss, so create a new ListViewItem and pass it back.
5280 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5283 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
5287 // 不正な要求に対する間に合わせの応答
5288 string[] sitem = {"", "", "", "", "", "", "", ""};
5289 e.Item = new ImageListViewItem(sitem);
5293 private void CreateCache(int startIndex, int endIndex)
5295 var tabInfo = this._statuses.Tabs[this._curTab.Text];
5297 if (tabInfo.AllCount == 0)
5300 // キャッシュ要求(要求範囲±30を作成)
5301 startIndex = Math.Max(startIndex - 30, 0);
5302 endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
5304 var cacheLength = endIndex - startIndex + 1;
5306 var posts = tabInfo[startIndex, endIndex]; //配列で取得
5307 var listItems = Enumerable.Range(0, cacheLength)
5308 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
5311 var listCache = new ListViewItemCache
5313 TargetList = this._curList,
5314 StartIndex = startIndex,
5315 EndIndex = endIndex,
5317 ListItem = listItems,
5320 Interlocked.Exchange(ref this._listItemCache, listCache);
5324 /// DetailsListView のための ListViewItem のキャッシュを消去する
5326 private void PurgeListViewItemCache()
5328 Interlocked.Exchange(ref this._listItemCache, null);
5331 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5333 StringBuilder mk = new StringBuilder();
5334 //if (Post.IsDeleted) mk.Append("×");
5335 //if (Post.IsMark) mk.Append("♪");
5336 //if (Post.IsProtect) mk.Append("Ю");
5337 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5338 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5339 ImageListViewItem itm;
5340 if (Post.RetweetedId == null)
5342 string[] sitem= {"",
5344 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5345 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5350 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5354 string[] sitem = {"",
5356 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5357 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5358 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5362 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5364 itm.StateIndex = Post.StateIndex;
5366 bool read = Post.IsRead;
5367 //未読管理していなかったら既読として扱う
5368 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5369 ChangeItemStyleRead(read, itm, Post, null);
5370 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5375 /// 全てのタブの振り分けルールを反映し直します
5377 private void ApplyPostFilters()
5379 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5381 this.PurgeListViewItemCache();
5382 this._curPost = null;
5383 this._curItemIndex = -1;
5384 this._statuses.FilterAll();
5386 foreach (TabPage tabPage in this.ListTab.TabPages)
5388 var tab = this._statuses.Tabs[tabPage.Text];
5390 var listview = (DetailsListView)tabPage.Tag;
5391 using (ControlTransaction.Update(listview))
5393 listview.VirtualListSize = tab.AllCount;
5396 if (this._cfgCommon.TabIconDisp)
5398 if (tab.UnreadCount > 0)
5399 tabPage.ImageIndex = 0;
5401 tabPage.ImageIndex = -1;
5405 if (!this._cfgCommon.TabIconDisp)
5406 this.ListTab.Refresh();
5408 SetMainWindowTitle();
5409 SetStatusLabelUrl();
5413 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5415 e.DrawDefault = true;
5418 private void MyList_HScrolled(object sender, EventArgs e)
5420 DetailsListView listView = (DetailsListView)sender;
5424 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5426 if (e.State == 0) return;
5427 e.DrawDefault = false;
5429 SolidBrush brs2 = null;
5430 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5432 if (e.Item.BackColor == _clSelf)
5433 brs2 = _brsBackColorMine;
5434 else if (e.Item.BackColor == _clAtSelf)
5435 brs2 = _brsBackColorAt;
5436 else if (e.Item.BackColor == _clTarget)
5437 brs2 = _brsBackColorYou;
5438 else if (e.Item.BackColor == _clAtTarget)
5439 brs2 = _brsBackColorAtYou;
5440 else if (e.Item.BackColor == _clAtFromTarget)
5441 brs2 = _brsBackColorAtFromTarget;
5442 else if (e.Item.BackColor == _clAtTo)
5443 brs2 = _brsBackColorAtTo;
5445 brs2 = _brsBackColorNone;
5450 if (((Control)sender).Focused)
5451 brs2 = _brsHighLight;
5453 brs2 = _brsDeactiveSelection;
5455 e.Graphics.FillRectangle(brs2, e.Bounds);
5456 e.DrawFocusRectangle();
5457 this.DrawListViewItemIcon(e);
5460 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5462 if (e.ItemState == 0) return;
5464 if (e.ColumnIndex > 0)
5467 RectangleF rct = e.Bounds;
5468 rct.Width = e.Header.Width;
5469 int fontHeight = e.Item.Font.Height;
5472 rct.Y += fontHeight;
5473 rct.Height -= fontHeight;
5477 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5479 //if (heightDiff > fontHeight * 0.7)
5481 // rct.Height += fontHeight;
5482 // drawLineCount += 1;
5485 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5486 if (!_iconCol && drawLineCount <= 1)
5488 //rct.Inflate(0, heightDiff / -2);
5489 //rct.Height += fontHeight / 2;
5491 else if (heightDiff < fontHeight * 0.7)
5493 //最終行が70%以上欠けていたら、最終行は表示しない
5494 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5495 rct.Height = (fontHeight * drawLineCount) - 1;
5502 //if (!_iconCol && drawLineCount > 1)
5504 // rct.Y += fontHeight * 0.2;
5505 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5510 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5511 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5516 Rectangle rctB = e.Bounds;
5517 rctB.Width = e.Header.Width;
5518 rctB.Height = fontHeight;
5520 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5522 TextRenderer.DrawText(e.Graphics,
5523 e.Item.SubItems[2].Text,
5525 Rectangle.Round(rct),
5527 TextFormatFlags.WordBreak |
5528 TextFormatFlags.EndEllipsis |
5529 TextFormatFlags.GlyphOverhangPadding |
5530 TextFormatFlags.NoPrefix);
5531 TextRenderer.DrawText(e.Graphics,
5532 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 + "]",
5536 TextFormatFlags.SingleLine |
5537 TextFormatFlags.EndEllipsis |
5538 TextFormatFlags.GlyphOverhangPadding |
5539 TextFormatFlags.NoPrefix);
5542 else if (drawLineCount == 1)
5544 TextRenderer.DrawText(e.Graphics,
5547 Rectangle.Round(rct),
5549 TextFormatFlags.SingleLine |
5550 TextFormatFlags.EndEllipsis |
5551 TextFormatFlags.GlyphOverhangPadding |
5552 TextFormatFlags.NoPrefix |
5553 TextFormatFlags.VerticalCenter);
5557 TextRenderer.DrawText(e.Graphics,
5560 Rectangle.Round(rct),
5562 TextFormatFlags.WordBreak |
5563 TextFormatFlags.EndEllipsis |
5564 TextFormatFlags.GlyphOverhangPadding |
5565 TextFormatFlags.NoPrefix);
5567 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5572 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5574 if (_iconSz == 0) return;
5576 ImageListViewItem item = (ImageListViewItem)e.Item;
5578 //e.Bounds.Leftが常に0を指すから自前で計算
5579 Rectangle itemRect = item.Bounds;
5580 var col0 = e.Item.ListView.Columns[0];
5581 itemRect.Width = col0.Width;
5583 if (col0.DisplayIndex > 0)
5585 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5587 if (clm.DisplayIndex < col0.DisplayIndex)
5588 itemRect.X += clm.Width;
5592 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5593 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5594 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5597 var img = item.Image;
5600 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5601 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5603 if (iconRect.Width > 0)
5605 e.Graphics.FillRectangle(Brushes.White, iconRect);
5606 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5609 e.Graphics.DrawImage(img.Image, iconRect);
5611 catch (ArgumentException)
5613 item.RefreshImageAsync();
5619 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5620 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5622 item.GetImageAsync();
5625 if (item.StateIndex > -1)
5627 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5628 if (stateRect.Width > 0)
5630 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5631 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5632 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5637 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5639 base.ScaleControl(factor, specified);
5641 ScaleChildControl(this.TabImage, factor);
5643 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5644 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5646 foreach (var listview in listviews)
5648 ScaleChildControl(listview, factor);
5652 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5654 // ImageListViewItem item = (ImageListViewItem)e.Item;
5655 // if (item.StateImageIndex > -1)
5657 // ////e.Bounds.Leftが常に0を指すから自前で計算
5658 // //Rectangle itemRect = item.Bounds;
5659 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5661 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5663 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5665 // // itemRect.X += clm.Width;
5669 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5670 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5672 // if (rct.Width > 0)
5674 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5675 // //e.Graphics.FillRectangle(Brushes.White, rct);
5676 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5677 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5682 private void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5684 var tab = this._statuses.Tabs[this._curTab.Text];
5686 if (tab.AllCount == 0)
5688 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5692 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5697 case SEARCHTYPE.NextSearch: // 次を検索
5698 if (selectedIndex != -1)
5699 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5703 case SEARCHTYPE.PrevSearch: // 前を検索
5704 if (selectedIndex != -1)
5705 startIndex = Math.Max(selectedIndex - 1, 0);
5707 startIndex = tab.AllCount - 1;
5709 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5711 if (selectedIndex != -1)
5712 startIndex = selectedIndex;
5718 Func<string, bool> stringComparer;
5721 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5723 catch (ArgumentException)
5725 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5729 var reverse = searchType == SEARCHTYPE.PrevSearch;
5730 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5731 .DefaultIfEmpty(-1).First();
5733 if (foundIndex == -1)
5735 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5739 this.SelectListItem(this._curList, foundIndex);
5740 this._curList.EnsureVisible(foundIndex);
5743 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5746 this.ShowSearchDialog();
5749 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5751 var previousSearch = this.SearchDialog.ResultOptions;
5752 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5754 this.SearchDialog.Reset();
5755 this.ShowSearchDialog();
5761 previousSearch.Query,
5762 previousSearch.CaseSensitive,
5763 previousSearch.UseRegex,
5764 SEARCHTYPE.NextSearch);
5767 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5769 var previousSearch = this.SearchDialog.ResultOptions;
5770 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5772 this.SearchDialog.Reset();
5773 this.ShowSearchDialog();
5779 previousSearch.Query,
5780 previousSearch.CaseSensitive,
5781 previousSearch.UseRegex,
5782 SEARCHTYPE.PrevSearch);
5786 /// 検索ダイアログを表示し、検索を実行します
5788 private void ShowSearchDialog()
5790 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5792 this.TopMost = this._cfgCommon.AlwaysTop;
5795 this.TopMost = this._cfgCommon.AlwaysTop;
5797 var searchOptions = this.SearchDialog.ResultOptions;
5798 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5800 if (searchOptions.NewTab)
5802 var tabName = Properties.Resources.SearchResults_TabName;
5806 tabName = this._statuses.MakeTabName(tabName);
5808 catch (TabException ex)
5810 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5813 var resultTab = new TabClass(tabName, MyCommon.TabUsageType.SearchResults);
5814 this.AddNewTab(tabName, false, MyCommon.TabUsageType.SearchResults);
5815 this._statuses.AddTab(resultTab);
5817 var targetTab = this._statuses.Tabs[this._curTab.Text];
5819 Func<string, bool> stringComparer;
5822 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5824 catch (ArgumentException)
5826 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5830 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5831 if (foundIndices.Length == 0)
5833 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5837 var foundPosts = foundIndices.Select(x => targetTab[x]);
5838 foreach (var post in foundPosts)
5840 resultTab.AddPostToInnerStorage(post);
5843 this._statuses.DistributePosts();
5844 this.RefreshTimeline();
5846 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5847 .First(x => x.Text == tabName);
5849 this.ListTab.SelectedTab = tabPage;
5854 searchOptions.Query,
5855 searchOptions.CaseSensitive,
5856 searchOptions.UseRegex,
5857 SEARCHTYPE.DialogSearch);
5860 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5862 this.AddNewTabForSearch(searchOptions.Query);
5866 /// <summary>発言検索に使用するメソッドを生成します</summary>
5867 /// <exception cref="ArgumentException">
5868 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"> が不正な正規表現な場合
5870 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5874 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5875 var regex = new Regex(query, regexOption);
5877 return x => regex.IsMatch(x);
5881 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5883 return x => x.IndexOf(query, comparisonType) != -1;
5887 private void AboutMenuItem_Click(object sender, EventArgs e)
5889 using (TweenAboutBox about = new TweenAboutBox())
5891 about.ShowDialog(this);
5893 this.TopMost = this._cfgCommon.AlwaysTop;
5896 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5898 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5900 DetailsListView lst = null;
5902 if (ImageSelector.Enabled)
5906 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5909 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5912 ListTab.SelectedIndex = i;
5913 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5914 //_curTab = ListTab.TabPages[i];
5919 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5920 if (idx == -1 && bgnIdx > 0)
5922 for (int i = 0; i < bgnIdx; i++)
5924 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5927 ListTab.SelectedIndex = i;
5928 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5929 //_curTab = ListTab.TabPages[i];
5935 //全部調べたが未読見つからず→先頭タブの最新発言へ
5938 ListTab.SelectedIndex = 0;
5939 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5940 //_curTab = ListTab.TabPages[0];
5941 if (_statuses.SortOrder == SortOrder.Ascending)
5942 idx = lst.VirtualListSize - 1;
5947 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5949 SelectListItem(lst, idx);
5950 if (_statuses.SortMode == ComparerMode.Id)
5952 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5953 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5959 lst.EnsureVisible(idx);
5964 lst.EnsureVisible(idx);
5970 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5972 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5974 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5975 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5979 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5981 if (_curList.SelectedIndices.Count > 0)
5983 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5984 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5988 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5990 await this.CheckNewVersion(false);
5993 private void RunTweenUp()
5995 ProcessStartInfo pinfo = new ProcessStartInfo();
5996 pinfo.UseShellExecute = true;
5997 pinfo.WorkingDirectory = MyCommon.settingPath;
5998 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5999 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
6002 Process.Start(pinfo);
6006 MessageBox.Show("Failed to execute TweenUp3.exe.");
6010 public class VersionInfo
6012 public Version Version { get; set; }
6013 public Uri DownloadUri { get; set; }
6014 public string ReleaseNote { get; set; }
6018 /// OpenTween の最新バージョンの情報を取得します
6020 public async Task<VersionInfo> GetVersionInfoAsync()
6022 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
6023 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
6025 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
6026 .ConfigureAwait(false);
6028 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
6029 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
6031 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
6032 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
6034 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
6036 return new VersionInfo
6038 Version = Version.Parse(msgHeader[0]),
6039 DownloadUri = new Uri(msgHeader[1]),
6040 ReleaseNote = msgBody,
6044 private async Task CheckNewVersion(bool startup = false)
6046 if (ApplicationSettings.VersionInfoUrl == null)
6047 return; // 更新チェック無効化
6051 var versionInfo = await this.GetVersionInfoAsync();
6053 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
6058 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
6059 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
6060 msgtext = MyCommon.ReplaceAppName(msgtext);
6062 MessageBox.Show(msgtext,
6063 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6064 MessageBoxButtons.OK, MessageBoxIcon.Information);
6069 using (var dialog = new UpdateDialog())
6071 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
6072 MyCommon.GetReadableVersion(versionInfo.Version));
6073 dialog.DetailsText = versionInfo.ReleaseNote;
6075 if (dialog.ShowDialog(this) == DialogResult.Yes)
6077 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
6083 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
6086 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
6087 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6088 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
6093 private async Task Colorize()
6096 await this.DispSelectedPost();
6097 //件数関連の場合、タイトル即時書き換え
6098 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
6099 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6100 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6101 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6103 SetMainWindowTitle();
6105 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6106 foreach (TabPage tb in ListTab.TabPages)
6108 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6110 if (this._cfgCommon.TabIconDisp)
6112 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6116 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
6119 public string createDetailHtml(string orgdata)
6121 if (this._cfgLocal.UseTwemoji)
6122 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
6124 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6127 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6129 if (sender.Equals(displayItem))
6131 this.ClearUserPicture();
6133 var img = displayItem.Image;
6137 img = await img.CloneAsync();
6139 UserPicture.Image = img;
6143 UserPicture.ShowErrorImage();
6148 private Task DispSelectedPost()
6150 return this.DispSelectedPost(false);
6153 private PostClass displayPost = new PostClass();
6156 /// サムネイル表示に使用する CancellationToken の生成元
6158 private CancellationTokenSource thumbnailTokenSource = null;
6160 private async Task DispSelectedPost(bool forceupdate)
6162 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6165 var oldDisplayPost = this.displayPost;
6166 this.displayPost = this._curPost;
6168 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6171 if (displayItem != null)
6173 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6176 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6177 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6179 using (ControlTransaction.Update(this.TableLayoutPanel1))
6181 SourceLinkLabel.Text = this._curPost.Source;
6182 SourceLinkLabel.Tag = this._curPost.SourceUri;
6183 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6189 nameText = "DM FROM <- ";
6191 nameText = "DM TO -> ";
6197 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6198 if (_curPost.RetweetedId != null)
6199 nameText += " (RT:" + _curPost.RetweetedBy + ")";
6201 NameLabel.Text = nameText;
6202 NameLabel.Tag = _curPost.ScreenName;
6204 var nameForeColor = SystemColors.ControlText;
6205 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6206 nameForeColor = this._clOWL;
6207 if (_curPost.RetweetedId != null)
6208 nameForeColor = this._clRetweet;
6210 nameForeColor = this._clFav;
6211 NameLabel.ForeColor = nameForeColor;
6213 this.ClearUserPicture();
6215 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6217 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6220 UserPicture.Image = image?.Clone();
6224 UserPicture.ShowErrorImage();
6228 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6231 if (DumpPostClassToolStripMenuItem.Checked)
6233 StringBuilder sb = new StringBuilder(512);
6235 sb.Append("-----Start PostClass Dump<br>");
6236 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
6237 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6238 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
6239 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
6240 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
6241 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
6242 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
6243 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
6244 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
6245 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
6246 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
6247 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
6248 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
6249 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
6250 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
6252 foreach (string nm in _curPost.ReplyToList)
6254 sb.AppendFormat("ReplyToList : {0}<br>", nm);
6257 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
6258 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
6259 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
6260 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
6261 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
6262 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
6263 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
6264 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
6265 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
6266 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
6268 sb.AppendFormat("Media.Count : {0}<br>", _curPost.Media.Count);
6269 if (_curPost.Media.Count > 0)
6271 for (int i = 0; i < _curPost.Media.Count; i++)
6273 var info = _curPost.Media[i];
6274 sb.AppendFormat("Media[{0}].Url : {1}<br>", i, info.Url);
6275 sb.AppendFormat("Media[{0}].VideoUrl : {1}<br>", i, info.VideoUrl ?? "---");
6278 sb.Append("-----End PostClass Dump<br>");
6280 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6284 var loadTasks = new List<Task>();
6286 // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6287 // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6288 if (_curPost.StatusId != oldDisplayPost.StatusId)
6290 using (ControlTransaction.Update(this.PostBrowser))
6292 this.PostBrowser.DocumentText =
6293 this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6295 this.PostBrowser.Document.Window.ScrollTo(0, 0);
6298 this.SplitContainer3.Panel2Collapsed = true;
6300 if (this._cfgCommon.PreviewEnable)
6302 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
6303 oldTokenSource?.Cancel();
6305 var token = this.thumbnailTokenSource.Token;
6306 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
6309 loadTasks.Add(this.AppendQuoteTweetAsync(this._curPost));
6314 await Task.WhenAll(loadTasks);
6316 catch (OperationCanceledException) { }
6320 /// 発言詳細欄のツイートURLを展開する
6322 private async Task AppendQuoteTweetAsync(PostClass post)
6324 var quoteStatusIds = post.QuoteStatusIds;
6325 if (quoteStatusIds.Length == 0 && post.InReplyToStatusId == null)
6329 var loadingQuoteHtml = quoteStatusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText, isReply: false));
6331 var loadingReplyHtml = string.Empty;
6332 if (post.InReplyToStatusId != null)
6333 loadingReplyHtml = FormatQuoteTweetHtml(post.InReplyToStatusId.Value, Properties.Resources.LoadingText, isReply: true);
6335 var body = post.Text + string.Concat(loadingQuoteHtml) + loadingReplyHtml;
6337 using (ControlTransaction.Update(this.PostBrowser))
6338 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6341 var loadTweetTasks = quoteStatusIds.Select(x => this.CreateQuoteTweetHtml(x, isReply: false)).ToList();
6343 if (post.InReplyToStatusId != null)
6344 loadTweetTasks.Add(this.CreateQuoteTweetHtml(post.InReplyToStatusId.Value, isReply: true));
6346 var quoteHtmls = await Task.WhenAll(loadTweetTasks);
6348 // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
6349 if (this._curPost != post || this._curPost.IsDeleted)
6352 body = post.Text + string.Concat(quoteHtmls);
6354 using (ControlTransaction.Update(this.PostBrowser))
6355 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6358 private async Task<string> CreateQuoteTweetHtml(long statusId, bool isReply)
6360 PostClass post = this._statuses[statusId];
6365 post = await this.tw.GetStatusApi(false, statusId)
6366 .ConfigureAwait(false);
6368 catch (WebApiException ex)
6370 return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode($"Err:{ex.Message}(GetStatus)"), isReply);
6374 if (!this._statuses.AddQuoteTweet(post))
6375 return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.", isReply);
6378 return FormatQuoteTweetHtml(post, isReply);
6381 internal static string FormatQuoteTweetHtml(PostClass post, bool isReply)
6383 var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
6384 " — " + WebUtility.HtmlEncode(post.Nickname) +
6385 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
6386 WebUtility.HtmlEncode(post.CreatedAt.ToString());
6388 return FormatQuoteTweetHtml(post.StatusId, innerHtml, isReply);
6391 internal static string FormatQuoteTweetHtml(long statusId, string innerHtml, bool isReply)
6393 var blockClassName = "quote-tweet";
6396 blockClassName += " reply";
6398 return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
6399 $"<blockquote class=\"{blockClassName}\">{innerHtml}</blockquote>" +
6404 /// 指定されたHTMLからリンクを除去します
6406 internal static string StripLinkTagHtml(string html)
6408 // a 要素はネストされていない前提の正規表現パターン
6409 return Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1");
6412 private async void MatomeMenuItem_Click(object sender, EventArgs e)
6414 await this.OpenApplicationWebsite();
6417 private async Task OpenApplicationWebsite()
6419 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
6422 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6424 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
6427 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
6429 if (ListTab.SelectedTab != null)
6431 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6433 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6434 if (pnl.Controls["comboSearch"].Focused ||
6435 pnl.Controls["comboLang"].Focused ||
6436 pnl.Controls["buttonSearch"].Focused) return;
6439 if (e.Control || e.Shift || e.Alt)
6440 this._anchorFlag = false;
6443 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
6446 e.SuppressKeyPress = true;
6449 if (asyncTask != null)
6454 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
6456 private void InitializeShortcuts()
6458 this.shortcutCommands = new[]
6460 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6461 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
6462 .FocusedOn(FocusedControl.ListTab)
6463 .Do(() => SendKeys.Send("{DOWN}")),
6465 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
6466 .FocusedOn(FocusedControl.ListTab)
6467 .Do(() => SendKeys.Send("{UP}")),
6469 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
6470 .FocusedOn(FocusedControl.ListTab)
6471 .Do(() => SendKeys.Send("{PGDN}")),
6473 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
6474 .FocusedOn(FocusedControl.ListTab)
6475 .Do(() => SendKeys.Send("{PGUP}")),
6477 ShortcutCommand.Create(Keys.F1)
6478 .Do(() => this.OpenApplicationWebsite()),
6480 ShortcutCommand.Create(Keys.F3)
6481 .Do(() => this.MenuItemSearchNext_Click(null, null)),
6483 ShortcutCommand.Create(Keys.F5)
6484 .Do(() => this.DoRefresh()),
6486 ShortcutCommand.Create(Keys.F6)
6487 .Do(() => this.GetReplyAsync()),
6489 ShortcutCommand.Create(Keys.F7)
6490 .Do(() => this.GetDirectMessagesAsync()),
6492 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
6493 .NotFocusedOn(FocusedControl.StatusText)
6494 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
6496 ShortcutCommand.Create(Keys.G)
6497 .NotFocusedOn(FocusedControl.StatusText)
6498 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
6500 ShortcutCommand.Create(Keys.Right, Keys.N)
6501 .FocusedOn(FocusedControl.ListTab)
6502 .Do(() => this.GoRelPost(forward: true)),
6504 ShortcutCommand.Create(Keys.Left, Keys.P)
6505 .FocusedOn(FocusedControl.ListTab)
6506 .Do(() => this.GoRelPost(forward: false)),
6508 ShortcutCommand.Create(Keys.OemPeriod)
6509 .FocusedOn(FocusedControl.ListTab)
6510 .Do(() => this.GoAnchor()),
6512 ShortcutCommand.Create(Keys.I)
6513 .FocusedOn(FocusedControl.ListTab)
6514 .OnlyWhen(() => this.StatusText.Enabled)
6515 .Do(() => this.StatusText.Focus()),
6517 ShortcutCommand.Create(Keys.Enter)
6518 .FocusedOn(FocusedControl.ListTab)
6519 .Do(() => this.MakeReplyOrDirectStatus()),
6521 ShortcutCommand.Create(Keys.R)
6522 .FocusedOn(FocusedControl.ListTab)
6523 .Do(() => this.DoRefresh()),
6525 ShortcutCommand.Create(Keys.L)
6526 .FocusedOn(FocusedControl.ListTab)
6527 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
6529 ShortcutCommand.Create(Keys.H)
6530 .FocusedOn(FocusedControl.ListTab)
6531 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6533 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6534 .FocusedOn(FocusedControl.ListTab)
6535 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6537 ShortcutCommand.Create(Keys.S)
6538 .FocusedOn(FocusedControl.ListTab)
6539 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6541 ShortcutCommand.Create(Keys.A)
6542 .FocusedOn(FocusedControl.ListTab)
6543 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6545 // ] in_reply_to参照元へ戻る
6546 ShortcutCommand.Create(Keys.Oem4)
6547 .FocusedOn(FocusedControl.ListTab)
6548 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6550 // [ in_reply_toへジャンプ
6551 ShortcutCommand.Create(Keys.Oem6)
6552 .FocusedOn(FocusedControl.ListTab)
6553 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6555 ShortcutCommand.Create(Keys.Escape)
6556 .FocusedOn(FocusedControl.ListTab)
6558 this._anchorFlag = false;
6559 if (ListTab.SelectedTab != null)
6561 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6562 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6564 var relTp = ListTab.SelectedTab;
6565 RemoveSpecifiedTab(relTp.Text, false);
6571 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
6572 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
6573 .FocusedOn(FocusedControl.ListTab)
6574 .Do(() => this._anchorFlag = false, preventDefault: false),
6576 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6577 ShortcutCommand.Create(Keys.Up, Keys.Down)
6578 .FocusedOn(FocusedControl.PostBrowser)
6581 ShortcutCommand.Create(Keys.Control | Keys.R)
6582 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6584 ShortcutCommand.Create(Keys.Control | Keys.D)
6585 .Do(() => this.doStatusDelete()),
6587 ShortcutCommand.Create(Keys.Control | Keys.M)
6588 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6590 ShortcutCommand.Create(Keys.Control | Keys.S)
6591 .Do(() => this.FavoriteChange(FavAdd: true)),
6593 ShortcutCommand.Create(Keys.Control | Keys.I)
6594 .Do(() => this.doRepliedStatusOpen()),
6596 ShortcutCommand.Create(Keys.Control | Keys.Q)
6597 .Do(() => this.doQuoteOfficial()),
6599 ShortcutCommand.Create(Keys.Control | Keys.B)
6600 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6602 ShortcutCommand.Create(Keys.Control | Keys.T)
6603 .Do(() => this.HashManageMenuItem_Click(null, null)),
6605 ShortcutCommand.Create(Keys.Control | Keys.L)
6606 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6608 ShortcutCommand.Create(Keys.Control | Keys.Y)
6609 .NotFocusedOn(FocusedControl.PostBrowser)
6610 .Do(() => this.MultiLineMenuItem_Click(null, null)),
6612 ShortcutCommand.Create(Keys.Control | Keys.F)
6613 .Do(() => this.MenuItemSubSearch_Click(null, null)),
6615 ShortcutCommand.Create(Keys.Control | Keys.U)
6616 .Do(() => this.ShowUserTimeline()),
6618 ShortcutCommand.Create(Keys.Control | Keys.H)
6619 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6621 ShortcutCommand.Create(Keys.Control | Keys.G)
6622 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6624 ShortcutCommand.Create(Keys.Control | Keys.O)
6625 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6627 ShortcutCommand.Create(Keys.Control | Keys.E)
6628 .Do(() => this.OpenURLMenuItem_Click(null, null)),
6630 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6631 .FocusedOn(FocusedControl.ListTab)
6632 .Do(() => this._colorize = true, preventDefault: false),
6634 ShortcutCommand.Create(Keys.Control | Keys.N)
6635 .FocusedOn(FocusedControl.ListTab)
6636 .Do(() => this.GoNextTab(forward: true)),
6638 ShortcutCommand.Create(Keys.Control | Keys.P)
6639 .FocusedOn(FocusedControl.ListTab)
6640 .Do(() => this.GoNextTab(forward: false)),
6642 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6643 .FocusedOn(FocusedControl.ListTab)
6644 .Do(() => this.CopyStot()),
6646 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6647 ShortcutCommand.Create(Keys.Control | Keys.D1)
6648 .FocusedOn(FocusedControl.ListTab)
6649 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6650 .Do(() => this.ListTab.SelectedIndex = 0),
6652 ShortcutCommand.Create(Keys.Control | Keys.D2)
6653 .FocusedOn(FocusedControl.ListTab)
6654 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6655 .Do(() => this.ListTab.SelectedIndex = 1),
6657 ShortcutCommand.Create(Keys.Control | Keys.D3)
6658 .FocusedOn(FocusedControl.ListTab)
6659 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6660 .Do(() => this.ListTab.SelectedIndex = 2),
6662 ShortcutCommand.Create(Keys.Control | Keys.D4)
6663 .FocusedOn(FocusedControl.ListTab)
6664 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6665 .Do(() => this.ListTab.SelectedIndex = 3),
6667 ShortcutCommand.Create(Keys.Control | Keys.D5)
6668 .FocusedOn(FocusedControl.ListTab)
6669 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6670 .Do(() => this.ListTab.SelectedIndex = 4),
6672 ShortcutCommand.Create(Keys.Control | Keys.D6)
6673 .FocusedOn(FocusedControl.ListTab)
6674 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6675 .Do(() => this.ListTab.SelectedIndex = 5),
6677 ShortcutCommand.Create(Keys.Control | Keys.D7)
6678 .FocusedOn(FocusedControl.ListTab)
6679 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6680 .Do(() => this.ListTab.SelectedIndex = 6),
6682 ShortcutCommand.Create(Keys.Control | Keys.D8)
6683 .FocusedOn(FocusedControl.ListTab)
6684 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6685 .Do(() => this.ListTab.SelectedIndex = 7),
6687 ShortcutCommand.Create(Keys.Control | Keys.D9)
6688 .FocusedOn(FocusedControl.ListTab)
6689 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6691 ShortcutCommand.Create(Keys.Control | Keys.A)
6692 .FocusedOn(FocusedControl.StatusText)
6693 .Do(() => this.StatusText.SelectAll()),
6695 ShortcutCommand.Create(Keys.Control | Keys.V)
6696 .FocusedOn(FocusedControl.StatusText)
6697 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6699 ShortcutCommand.Create(Keys.Control | Keys.Up)
6700 .FocusedOn(FocusedControl.StatusText)
6702 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6704 var inReplyToStatusId = this.inReplyTo?.Item1;
6705 var inReplyToScreenName = this.inReplyTo?.Item2;
6706 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6709 if (_hisIdx < 0) _hisIdx = 0;
6711 var historyItem = this._history[this._hisIdx];
6712 StatusText.Text = historyItem.status;
6713 StatusText.SelectionStart = StatusText.Text.Length;
6714 if (historyItem.inReplyToId != null)
6715 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6717 this.inReplyTo = null;
6720 ShortcutCommand.Create(Keys.Control | Keys.Down)
6721 .FocusedOn(FocusedControl.StatusText)
6723 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6725 var inReplyToStatusId = this.inReplyTo?.Item1;
6726 var inReplyToScreenName = this.inReplyTo?.Item2;
6727 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6730 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6732 var historyItem = this._history[this._hisIdx];
6733 StatusText.Text = historyItem.status;
6734 StatusText.SelectionStart = StatusText.Text.Length;
6735 if (historyItem.inReplyToId != null)
6736 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6738 this.inReplyTo = null;
6741 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6742 .FocusedOn(FocusedControl.StatusText)
6744 if (ListTab.SelectedIndex == 0)
6746 ListTab.SelectedIndex = ListTab.TabCount - 1;
6750 ListTab.SelectedIndex -= 1;
6755 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6756 .FocusedOn(FocusedControl.StatusText)
6758 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6760 ListTab.SelectedIndex = 0;
6764 ListTab.SelectedIndex += 1;
6769 ShortcutCommand.Create(Keys.Control | Keys.Y)
6770 .FocusedOn(FocusedControl.PostBrowser)
6772 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6773 MultiLineMenuItem_Click(null, null);
6776 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6777 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6779 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6780 .Do(() => this.DoRefreshMore()),
6782 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6783 .Do(() => this.GetReplyAsync(loadMore: true)),
6785 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6786 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6788 ShortcutCommand.Create(Keys.Shift | Keys.R)
6789 .NotFocusedOn(FocusedControl.StatusText)
6790 .Do(() => this.DoRefreshMore()),
6792 ShortcutCommand.Create(Keys.Shift | Keys.H)
6793 .FocusedOn(FocusedControl.ListTab)
6794 .Do(() => this.GoTopEnd(GoTop: true)),
6796 ShortcutCommand.Create(Keys.Shift | Keys.L)
6797 .FocusedOn(FocusedControl.ListTab)
6798 .Do(() => this.GoTopEnd(GoTop: false)),
6800 ShortcutCommand.Create(Keys.Shift | Keys.M)
6801 .FocusedOn(FocusedControl.ListTab)
6802 .Do(() => this.GoMiddle()),
6804 ShortcutCommand.Create(Keys.Shift | Keys.G)
6805 .FocusedOn(FocusedControl.ListTab)
6806 .Do(() => this.GoLast()),
6808 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6809 .FocusedOn(FocusedControl.ListTab)
6810 .Do(() => this.MoveMiddle()),
6812 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6813 .FocusedOn(FocusedControl.ListTab)
6814 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6816 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6817 .FocusedOn(FocusedControl.ListTab)
6818 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6820 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6821 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6822 .FocusedOn(FocusedControl.ListTab)
6823 .Do(() => this.GoFav(forward: true)),
6825 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6826 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6827 .FocusedOn(FocusedControl.ListTab)
6828 .Do(() => this.GoFav(forward: false)),
6830 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6831 .FocusedOn(FocusedControl.ListTab)
6832 .Do(() => this.GoBackSelectPostChain()),
6834 ShortcutCommand.Create(Keys.Alt | Keys.R)
6835 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6837 ShortcutCommand.Create(Keys.Alt | Keys.P)
6838 .OnlyWhen(() => this._curPost != null)
6839 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6841 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6842 .Do(() => this.ScrollDownPostBrowser(forward: false)),
6844 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6845 .Do(() => this.ScrollDownPostBrowser(forward: true)),
6847 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6848 .Do(() => this.PageDownPostBrowser(forward: false)),
6850 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6851 .Do(() => this.PageDownPostBrowser(forward: true)),
6853 // 別タブの同じ書き込みへ(ALT+←/→)
6854 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6855 .FocusedOn(FocusedControl.ListTab)
6856 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6858 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6859 .FocusedOn(FocusedControl.ListTab)
6860 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6862 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6863 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6865 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6866 .Do(() => this.CopyIdUri()),
6868 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6869 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6870 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6871 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6873 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6874 .Do(() => this.FavoriteChange(FavAdd: false)),
6876 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6877 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6879 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6880 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6882 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6883 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6885 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6886 .Do(() => this.doMoveToRTHome()),
6888 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6889 .Do(() => this.FavorareMenuItem_Click(null, null)),
6891 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6892 .FocusedOn(FocusedControl.StatusText)
6894 if (_curList != null && _curList.VirtualListSize != 0 &&
6895 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6897 var idx = _curList.SelectedIndices[0] - 1;
6898 SelectListItem(_curList, idx);
6899 _curList.EnsureVisible(idx);
6903 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6904 .FocusedOn(FocusedControl.StatusText)
6906 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6907 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6909 var idx = _curList.SelectedIndices[0] + 1;
6910 SelectListItem(_curList, idx);
6911 _curList.EnsureVisible(idx);
6915 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6916 .FocusedOn(FocusedControl.StatusText)
6918 if (StatusText.SelectionStart > 0)
6920 int endidx = StatusText.SelectionStart - 1;
6921 string startstr = "";
6922 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6924 char c = StatusText.Text[i];
6925 if (Char.IsLetterOrDigit(c) || c == '_')
6931 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6932 int cnt = AtIdSupl.ItemCount;
6933 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6934 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6938 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6939 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6949 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6950 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6951 .FocusedOn(FocusedControl.ListTab)
6952 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6954 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6955 .FocusedOn(FocusedControl.ListTab)
6956 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6958 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6959 .FocusedOn(FocusedControl.ListTab)
6960 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6962 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6963 .FocusedOn(FocusedControl.ListTab)
6964 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6966 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6967 .FocusedOn(FocusedControl.ListTab)
6968 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6970 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6971 .FocusedOn(FocusedControl.ListTab)
6972 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6974 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6975 .FocusedOn(FocusedControl.ListTab)
6976 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6978 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6979 .FocusedOn(FocusedControl.ListTab)
6980 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6982 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6983 .FocusedOn(FocusedControl.ListTab)
6984 .Do(() => this.SetSortLastColumn()),
6986 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6987 .Do(() => this.FavoritesRetweetOfficial()),
6989 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6990 .Do(() => this.FavoritesRetweetUnofficial()),
6992 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6993 .Do(() => this.OpenUserAppointUrl()),
6995 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6996 .FocusedOn(FocusedControl.PostBrowser)
6997 .Do(() => this.doReTweetUnofficial()),
6999 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
7000 .OnlyWhen(() => this.ExistCurrentPost)
7001 .Do(() => this.doTranslation(_curPost.TextFromApi)),
7003 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7004 .Do(() => this.doReTweetUnofficial()),
7006 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
7007 .Do(() => this.CopyUserId()),
7009 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
7010 .Do(() => this.tweetThumbnail1.ScrollUp()),
7012 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
7013 .Do(() => this.tweetThumbnail1.ScrollDown()),
7015 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
7016 .FocusedOn(FocusedControl.ListTab)
7017 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
7018 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
7022 private bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
7024 // Task を返す非同期処理があれば asyncTask に代入する
7027 // ShortcutCommand に対応しているコマンドはここで処理される
7028 foreach (var command in this.shortcutCommands)
7030 if (command.IsMatch(keyData, focusedOn))
7032 asyncTask = command.RunCommand();
7033 return command.PreventDefault;
7040 private void ScrollDownPostBrowser(bool forward)
7042 var doc = PostBrowser.Document;
7043 if (doc == null) return;
7045 var tags = doc.GetElementsByTagName("html");
7049 tags[0].ScrollTop += this._fntDetail.Height;
7051 tags[0].ScrollTop -= this._fntDetail.Height;
7055 private void PageDownPostBrowser(bool forward)
7057 var doc = PostBrowser.Document;
7058 if (doc == null) return;
7060 var tags = doc.GetElementsByTagName("html");
7064 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7066 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7070 private void GoNextTab(bool forward)
7072 int idx = ListTab.SelectedIndex;
7076 if (idx > ListTab.TabPages.Count - 1) idx = 0;
7081 if (idx < 0) idx = ListTab.TabPages.Count - 1;
7083 ListTab.SelectedIndex = idx;
7086 private void CopyStot()
7089 StringBuilder sb = new StringBuilder();
7090 bool IsProtected = false;
7092 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7093 foreach (int idx in _curList.SelectedIndices)
7095 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7101 if (post.IsDeleted) continue;
7104 if (post.RetweetedId != null)
7105 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7107 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7111 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7116 MessageBox.Show(Properties.Resources.CopyStotText1);
7120 clstr = sb.ToString();
7123 Clipboard.SetDataObject(clstr, false, 5, 100);
7125 catch (Exception ex)
7127 MessageBox.Show(ex.Message);
7132 private void CopyIdUri()
7135 StringBuilder sb = new StringBuilder();
7136 if (this._curTab == null) return;
7137 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7138 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7139 foreach (int idx in _curList.SelectedIndices)
7141 var post = _statuses.Tabs[_curTab.Text][idx];
7142 sb.Append(MyCommon.GetStatusUrl(post));
7143 sb.Append(Environment.NewLine);
7147 clstr = sb.ToString();
7150 Clipboard.SetDataObject(clstr, false, 5, 100);
7152 catch (Exception ex)
7154 MessageBox.Show(ex.Message);
7159 private void GoFav(bool forward)
7161 if (_curList.VirtualListSize == 0) return;
7168 if (_curList.SelectedIndices.Count == 0)
7174 fIdx = _curList.SelectedIndices[0] + 1;
7175 if (fIdx > _curList.VirtualListSize - 1) return;
7177 toIdx = _curList.VirtualListSize;
7182 if (_curList.SelectedIndices.Count == 0)
7184 fIdx = _curList.VirtualListSize - 1;
7188 fIdx = _curList.SelectedIndices[0] - 1;
7189 if (fIdx < 0) return;
7195 for (int idx = fIdx; idx != toIdx; idx += stp)
7197 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
7199 SelectListItem(_curList, idx);
7200 _curList.EnsureVisible(idx);
7206 private void GoSamePostToAnotherTab(bool left)
7208 if (_curList.VirtualListSize == 0) return;
7214 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7215 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7217 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7222 if (ListTab.SelectedIndex == 0)
7228 fIdx = ListTab.SelectedIndex - 1;
7236 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7242 fIdx = ListTab.SelectedIndex + 1;
7244 toIdx = ListTab.TabCount;
7249 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7251 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7252 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7254 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
7256 ListTab.SelectedIndex = tabidx;
7257 SelectListItem(_curList, idx);
7258 _curList.EnsureVisible(idx);
7267 private void GoPost(bool forward)
7269 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7276 fIdx = _curList.SelectedIndices[0] + 1;
7277 if (fIdx > _curList.VirtualListSize - 1) return;
7278 toIdx = _curList.VirtualListSize;
7283 fIdx = _curList.SelectedIndices[0] - 1;
7284 if (fIdx < 0) return;
7290 if (_curPost.RetweetedId == null)
7292 name = _curPost.ScreenName;
7296 name = _curPost.RetweetedBy;
7298 for (int idx = fIdx; idx != toIdx; idx += stp)
7300 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
7302 if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
7304 SelectListItem(_curList, idx);
7305 _curList.EnsureVisible(idx);
7311 if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
7313 SelectListItem(_curList, idx);
7314 _curList.EnsureVisible(idx);
7321 private void GoRelPost(bool forward)
7323 if (_curList.SelectedIndices.Count == 0) return;
7330 fIdx = _curList.SelectedIndices[0] + 1;
7331 if (fIdx > _curList.VirtualListSize - 1) return;
7332 toIdx = _curList.VirtualListSize;
7337 fIdx = _curList.SelectedIndices[0] - 1;
7338 if (fIdx < 0) return;
7345 if (_curPost == null) return;
7346 _anchorPost = _curPost;
7351 if (_anchorPost == null) return;
7354 for (int idx = fIdx; idx != toIdx; idx += stp)
7356 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7357 if (post.ScreenName == _anchorPost.ScreenName ||
7358 post.RetweetedBy == _anchorPost.ScreenName ||
7359 post.ScreenName == _anchorPost.RetweetedBy ||
7360 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7361 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
7362 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
7363 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
7364 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
7366 SelectListItem(_curList, idx);
7367 _curList.EnsureVisible(idx);
7373 private void GoAnchor()
7375 if (_anchorPost == null) return;
7376 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7377 if (idx == -1) return;
7379 SelectListItem(_curList, idx);
7380 _curList.EnsureVisible(idx);
7383 private void GoTopEnd(bool GoTop)
7385 if (_curList.VirtualListSize == 0)
7393 _item = _curList.GetItemAt(0, 25);
7401 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7403 idx = _curList.VirtualListSize - 1;
7407 SelectListItem(_curList, idx);
7410 private void GoMiddle()
7412 if (_curList.VirtualListSize == 0)
7420 _item = _curList.GetItemAt(0, 0);
7430 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7433 idx2 = _curList.VirtualListSize - 1;
7439 idx3 = (idx1 + idx2) / 2;
7441 SelectListItem(_curList, idx3);
7444 private void GoLast()
7446 if (_curList.VirtualListSize == 0) return;
7448 if (_statuses.SortOrder == SortOrder.Ascending)
7450 SelectListItem(_curList, _curList.VirtualListSize - 1);
7451 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7455 SelectListItem(_curList, 0);
7456 _curList.EnsureVisible(0);
7460 private void MoveTop()
7462 if (_curList.SelectedIndices.Count == 0) return;
7463 int idx = _curList.SelectedIndices[0];
7464 if (_statuses.SortOrder == SortOrder.Ascending)
7466 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7470 _curList.EnsureVisible(0);
7472 _curList.EnsureVisible(idx);
7475 private async Task GoInReplyToPostTree()
7477 if (_curPost == null) return;
7479 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7481 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7485 var post = await tw.GetStatusApi(false, _curPost.StatusId);
7487 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7488 _curPost.InReplyToUser = post.InReplyToUser;
7489 _curPost.IsReply = post.IsReply;
7490 this.PurgeListViewItemCache();
7491 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7493 catch (WebApiException ex)
7495 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
7499 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7501 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7503 replyChains = new Stack<ReplyChain>();
7505 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7508 string inReplyToTabName;
7509 long inReplyToId = _curPost.InReplyToStatusId.Value;
7510 string inReplyToUser = _curPost.InReplyToUser;
7511 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7513 var inReplyToPosts = from tab in _statuses.Tabs.Values
7514 orderby tab != curTabClass
7515 from post in tab.Posts.Values
7516 where post.StatusId == inReplyToId
7517 let index = tab.IndexOf(post.StatusId)
7519 select new {Tab = tab, Index = index};
7521 var inReplyPost = inReplyToPosts.FirstOrDefault();
7522 if (inReplyPost == null)
7526 await Task.Run(async () =>
7528 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
7529 .ConfigureAwait(false);
7532 _statuses.AddPost(post);
7533 _statuses.DistributePosts();
7536 catch (WebApiException ex)
7538 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
7539 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7543 this.RefreshTimeline();
7545 inReplyPost = inReplyToPosts.FirstOrDefault();
7546 if (inReplyPost == null)
7548 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7552 inReplyToTabName = inReplyPost.Tab.TabName;
7553 inReplyToIndex = inReplyPost.Index;
7555 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7556 DetailsListView listView = (DetailsListView)tabPage.Tag;
7558 if (_curTab != tabPage)
7560 this.ListTab.SelectTab(tabPage);
7563 this.SelectListItem(listView, inReplyToIndex);
7564 listView.EnsureVisible(inReplyToIndex);
7567 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7569 if (_curPost == null) return;
7571 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7572 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7576 if (_curPost.InReplyToStatusId != null)
7578 var posts = from t in _statuses.Tabs
7579 from p in t.Value.Posts
7580 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7581 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7583 orderby isForward ? indexOf : indexOf * -1
7584 orderby t.Value != curTabClass
7585 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7588 var postList = posts.ToList();
7589 for (int i = postList.Count - 1; i >= 0; i--)
7592 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7594 postList.RemoveAt(index);
7597 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7598 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7599 if (post == null) post = postList.First();
7600 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7601 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7602 SelectListItem(listView, post.Index);
7603 listView.EnsureVisible(post.Index);
7605 catch (InvalidOperationException)
7613 if (replyChains == null || replyChains.Count < 1)
7615 var posts = from t in _statuses.Tabs
7616 from p in t.Value.Posts
7617 where p.Value.InReplyToStatusId == _curPost.StatusId
7618 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7621 orderby t.Value != curTabClass
7622 select new {Tab = t.Value, Index = indexOf};
7625 var post = posts.First();
7626 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7627 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7628 SelectListItem(listView, post.Index);
7629 listView.EnsureVisible(post.Index);
7631 catch (InvalidOperationException)
7638 ReplyChain chainHead = replyChains.Pop();
7639 if (chainHead.InReplyToId == _curPost.StatusId)
7641 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7650 ListTab.SelectTab(chainHead.OriginalTab);
7656 SelectListItem(_curList, idx);
7657 _curList.EnsureVisible(idx);
7663 this.GoBackInReplyToPostTree(parallel);
7669 private void GoBackSelectPostChain()
7671 if (this.selectPostChains.Count > 1)
7680 this.selectPostChains.Pop();
7681 var tabPostPair = this.selectPostChains.Peek();
7683 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7685 if (tabPostPair.Item2 != null)
7687 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7688 if (idx == -1) continue; //該当ポストが存在しないので無視
7691 tp = tabPostPair.Item1;
7693 this.selectPostChains.Pop();
7695 catch (InvalidOperationException)
7701 while (this.selectPostChains.Count > 1);
7706 //履歴が残り1つであればクリアしておく
7707 if (this.selectPostChains.Count == 1)
7708 this.selectPostChains.Clear();
7712 DetailsListView lst = (DetailsListView)tp.Tag;
7713 this.ListTab.SelectedTab = tp;
7716 SelectListItem(lst, idx);
7717 lst.EnsureVisible(idx);
7723 private void PushSelectPostChain()
7725 int count = this.selectPostChains.Count;
7728 var p = this.selectPostChains.Peek();
7729 if (p.Item1 == this._curTab)
7731 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7732 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7735 if (count >= 2500) TrimPostChain();
7736 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7739 private void TrimPostChain()
7741 if (this.selectPostChains.Count <= 2000) return;
7742 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7743 for (int i = 0; i < 2000; i++)
7745 p.Push(this.selectPostChains.Pop());
7747 this.selectPostChains.Clear();
7748 for (int i = 0; i < 2000; i++)
7750 this.selectPostChains.Push(p.Pop());
7754 private bool GoStatus(long statusId)
7756 if (statusId == 0) return false;
7757 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7759 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7761 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7762 ListTab.SelectedIndex = tabidx;
7763 SelectListItem(_curList, idx);
7764 _curList.EnsureVisible(idx);
7771 private bool GoDirectMessage(long statusId)
7773 if (statusId == 0) return false;
7774 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7776 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7778 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7779 ListTab.SelectedIndex = tabidx;
7780 SelectListItem(_curList, idx);
7781 _curList.EnsureVisible(idx);
7788 private void MyList_MouseClick(object sender, MouseEventArgs e)
7790 _anchorFlag = false;
7793 private void StatusText_Enter(object sender, EventArgs e)
7795 // フォーカスの戻り先を StatusText に設定
7796 this.Tag = StatusText;
7797 StatusText.BackColor = _clInputBackcolor;
7800 public Color InputBackColor
7802 get { return _clInputBackcolor; }
7803 set { _clInputBackcolor = value; }
7806 private void StatusText_Leave(object sender, EventArgs e)
7808 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7809 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7810 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7813 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7816 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7819 e.SuppressKeyPress = true;
7822 this.StatusText_TextChanged(null, null);
7824 if (asyncTask != null)
7828 private void SaveConfigsAll(bool ifModified)
7832 SaveConfigsCommon();
7839 if (ModifySettingCommon) SaveConfigsCommon();
7840 if (ModifySettingLocal) SaveConfigsLocal();
7841 if (ModifySettingAtId) SaveConfigsAtId();
7845 private void SaveConfigsAtId()
7847 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7849 ModifySettingAtId = false;
7850 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7854 private void SaveConfigsCommon()
7856 if (_ignoreConfigSave) return;
7858 ModifySettingCommon = false;
7861 _cfgCommon.UserName = tw.Username;
7862 _cfgCommon.UserId = tw.UserId;
7863 _cfgCommon.Token = tw.AccessToken;
7864 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7866 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7867 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7869 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7872 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7873 switch (_statuses.SortMode)
7875 case ComparerMode.Nickname: //ニックネーム
7876 _cfgCommon.SortColumn = 1;
7878 case ComparerMode.Data: //本文
7879 _cfgCommon.SortColumn = 2;
7881 case ComparerMode.Id: //時刻=発言Id
7882 _cfgCommon.SortColumn = 3;
7884 case ComparerMode.Name: //名前
7885 _cfgCommon.SortColumn = 4;
7887 case ComparerMode.Source: //Source
7888 _cfgCommon.SortColumn = 7;
7892 _cfgCommon.HashTags = HashMgr.HashHistories;
7893 if (HashMgr.IsPermanent)
7895 _cfgCommon.HashSelected = HashMgr.UseHash;
7899 _cfgCommon.HashSelected = "";
7901 _cfgCommon.HashIsHead = HashMgr.IsHead;
7902 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7903 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7904 if (ToolStripFocusLockMenuItem != null &&
7905 ToolStripFocusLockMenuItem.IsDisposed == false)
7907 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7909 _cfgCommon.TrackWord = tw.TrackWord;
7910 _cfgCommon.AllAtReply = tw.AllAtReply;
7911 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7912 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7918 private void SaveConfigsLocal()
7920 if (_ignoreConfigSave) return;
7923 ModifySettingLocal = false;
7924 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7925 _cfgLocal.FormSize = _mySize;
7926 _cfgLocal.FormLocation = _myLoc;
7927 _cfgLocal.SplitterDistance = _mySpDis;
7928 _cfgLocal.PreviewDistance = _mySpDis3;
7929 _cfgLocal.StatusMultiline = StatusText.Multiline;
7930 _cfgLocal.StatusTextHeight = _mySpDis2;
7932 _cfgLocal.FontUnread = _fntUnread;
7933 _cfgLocal.ColorUnread = _clUnread;
7934 _cfgLocal.FontRead = _fntReaded;
7935 _cfgLocal.ColorRead = _clReaded;
7936 _cfgLocal.FontDetail = _fntDetail;
7937 _cfgLocal.ColorDetail = _clDetail;
7938 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7939 _cfgLocal.ColorDetailLink = _clDetailLink;
7940 _cfgLocal.ColorFav = _clFav;
7941 _cfgLocal.ColorOWL = _clOWL;
7942 _cfgLocal.ColorRetweet = _clRetweet;
7943 _cfgLocal.ColorSelf = _clSelf;
7944 _cfgLocal.ColorAtSelf = _clAtSelf;
7945 _cfgLocal.ColorTarget = _clTarget;
7946 _cfgLocal.ColorAtTarget = _clAtTarget;
7947 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7948 _cfgLocal.ColorAtTo = _clAtTo;
7949 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7950 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7951 _cfgLocal.ColorInputFont = _clInputFont;
7952 _cfgLocal.FontInputFont = _fntInputFont;
7954 if (_ignoreConfigSave) return;
7959 private void SaveConfigsTabs()
7961 var tabsSetting = new SettingTabs();
7963 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7964 .Select(x => this._statuses.Tabs[x.Text])
7965 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7967 foreach (var tab in tabs)
7969 if (tab.TabType == MyCommon.TabUsageType.Related || tab.TabType == MyCommon.TabUsageType.SearchResults)
7972 var tabSetting = new SettingTabs.SettingTabItem
7974 TabName = tab.TabName,
7975 TabType = tab.TabType,
7976 UnreadManage = tab.UnreadManage,
7977 Protected = tab.Protected,
7978 Notify = tab.Notify,
7979 SoundFile = tab.SoundFile,
7980 FilterArray = tab.FilterArray,
7982 SearchWords = tab.SearchWords,
7983 SearchLang = tab.SearchLang,
7984 ListInfo = tab.ListInfo,
7986 tabsSetting.Tabs.Add(tabSetting);
7992 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7995 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7996 if (ret != DialogResult.OK)
7999 var match = Twitter.StatusUrlRegex.Match(inputText);
8002 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
8003 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8009 var statusId = long.Parse(match.Groups["StatusId"].Value);
8010 await this.OpenRelatedTab(statusId);
8012 catch (TabException ex)
8014 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8018 private void SaveLogMenuItem_Click(object sender, EventArgs e)
8020 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8021 Properties.Resources.SaveLogMenuItem_ClickText2,
8022 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8023 if (rslt == DialogResult.Cancel) return;
8025 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8026 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8027 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8028 SaveFileDialog1.FilterIndex = 0;
8029 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8030 SaveFileDialog1.RestoreDirectory = true;
8032 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8034 if (!SaveFileDialog1.ValidateNames) return;
8035 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8037 if (rslt == DialogResult.Yes)
8040 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8042 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8043 string protect = "";
8044 if (post.IsProtect) protect = "Protect";
8045 sw.WriteLine(post.Nickname + "\t" +
8046 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8047 post.CreatedAt.ToString() + "\t" +
8048 post.ScreenName + "\t" +
8049 post.StatusId.ToString() + "\t" +
8050 post.ImageUrl + "\t" +
8051 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8057 foreach (int idx in _curList.SelectedIndices)
8059 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8060 string protect = "";
8061 if (post.IsProtect) protect = "Protect";
8062 sw.WriteLine(post.Nickname + "\t" +
8063 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8064 post.CreatedAt.ToString() + "\t" +
8065 post.ScreenName + "\t" +
8066 post.StatusId.ToString() + "\t" +
8067 post.ImageUrl + "\t" +
8068 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8074 this.TopMost = this._cfgCommon.AlwaysTop;
8077 private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8080 bool KeyRes = CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out asyncTask);
8083 e.IsInputKey = true;
8087 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
8089 var shortcut = (Shortcut)e.KeyData;
8092 case Shortcut.CtrlA:
8093 case Shortcut.CtrlC:
8094 case Shortcut.CtrlIns:
8098 // その他のショートカットキーは無効にする
8099 e.IsInputKey = true;
8105 if (asyncTask != null)
8108 public bool TabRename(ref string tabName)
8111 string newTabText = null;
8112 using (InputTabName inputName = new InputTabName())
8114 inputName.TabName = tabName;
8115 inputName.ShowDialog();
8116 if (inputName.DialogResult == DialogResult.Cancel) return false;
8117 newTabText = inputName.TabName;
8119 this.TopMost = this._cfgCommon.AlwaysTop;
8120 if (!string.IsNullOrEmpty(newTabText))
8123 for (int i = 0; i < ListTab.TabCount; i++)
8125 if (ListTab.TabPages[i].Text == newTabText)
8127 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8128 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8133 for (int i = 0; i < ListTab.TabCount; i++)
8135 if (ListTab.TabPages[i].Text == tabName)
8137 ListTab.TabPages[i].Text = newTabText;
8141 _statuses.RenameTab(tabName, newTabText);
8143 SaveConfigsCommon();
8145 _rclickTabName = newTabText;
8146 tabName = newTabText;
8155 private void ListTab_MouseClick(object sender, MouseEventArgs e)
8157 if (e.Button == MouseButtons.Middle)
8159 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8161 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8163 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8164 this.SaveConfigsTabs();
8171 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8173 string tn = ListTab.SelectedTab.Text;
8177 private void ListTab_MouseDown(object sender, MouseEventArgs e)
8179 if (this._cfgCommon.TabMouseLock) return;
8180 Point cpos = new Point(e.X, e.Y);
8181 if (e.Button == MouseButtons.Left)
8183 for (int i = 0; i < ListTab.TabPages.Count; i++)
8185 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8188 _tabMouseDownPoint = e.Location;
8199 private void ListTab_DragEnter(object sender, DragEventArgs e)
8201 if (e.Data.GetDataPresent(typeof(TabPage)))
8202 e.Effect = DragDropEffects.Move;
8204 e.Effect = DragDropEffects.None;
8207 private void ListTab_DragDrop(object sender, DragEventArgs e)
8209 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8214 Point cpos = new Point(e.X, e.Y);
8215 Point spos = ListTab.PointToClient(cpos);
8217 for (i = 0; i < ListTab.TabPages.Count; i++)
8219 Rectangle rect = ListTab.GetTabRect(i);
8220 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8221 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8223 tn = ListTab.TabPages[i].Text;
8224 if (spos.X <= (rect.Left + rect.Right) / 2)
8233 //タブのないところにドロップ->最後尾へ移動
8234 if (string.IsNullOrEmpty(tn))
8236 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8238 i = ListTab.TabPages.Count - 1;
8241 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8242 if (tp.Text == tn) return;
8244 ReOrderTab(tp.Text, tn, bef);
8247 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8249 var baseIndex = this.GetTabPageIndex(baseTabText);
8250 if (baseIndex == -1)
8253 var targetIndex = this.GetTabPageIndex(targetTabText);
8254 if (targetIndex == -1)
8257 using (ControlTransaction.Layout(this.ListTab))
8259 var mTp = this.ListTab.TabPages[targetIndex];
8260 this.ListTab.TabPages.Remove(mTp);
8262 if (targetIndex < baseIndex)
8265 if (isBeforeBaseTab)
8266 ListTab.TabPages.Insert(baseIndex, mTp);
8268 ListTab.TabPages.Insert(baseIndex + 1, mTp);
8274 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8276 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8277 //isReply:true=@,false=DM
8278 if (!StatusText.Enabled) return;
8279 if (_curList == null) return;
8280 if (_curTab == null) return;
8281 if (!this.ExistCurrentPost) return;
8283 // 複数あてリプライはReplyではなく通常ポスト
8284 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8285 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8286 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8288 if (_curList.SelectedIndices.Count > 0)
8291 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8294 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8297 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8298 StatusText.SelectionStart = StatusText.Text.Length;
8300 this.inReplyTo = null;
8303 if (string.IsNullOrEmpty(StatusText.Text))
8307 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8308 StatusText.Text = "@" + _curPost.ScreenName + " ";
8310 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8311 var inReplyToScreenName = this._curPost.ScreenName;
8312 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8320 //1件選んでEnter or DoubleClick
8321 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8323 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
8326 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8327 var inReplyToScreenName = this._curPost.ScreenName;
8328 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8332 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
8335 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8338 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8339 this.inReplyTo = null;
8344 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8345 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8346 var inReplyToScreenName = this._curPost.ScreenName;
8347 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8354 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8355 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8356 this.inReplyTo = null;
8361 //1件選んでCtrl-Rの場合(返信先操作せず)
8362 int sidx = StatusText.SelectionStart;
8363 string id = "@" + _curPost.ScreenName + " ";
8366 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8371 StatusText.Text = StatusText.Text.Insert(sidx, id);
8373 //if (StatusText.Text.StartsWith("@"))
8376 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8377 // sidx += 5 + _curPost.ScreenName.Length;
8382 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8383 // sidx += 3 + _curPost.ScreenName.Length;
8385 StatusText.SelectionStart = sidx;
8388 //_reply_to_name = null;
8396 if (!isAuto && !isReply) return;
8398 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8402 //Enter or DoubleClick
8404 string sTxt = StatusText.Text;
8405 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
8408 this.inReplyTo = null;
8410 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8412 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8413 if (!sTxt.Contains("@" + post.ScreenName + " "))
8415 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8416 //sTxt = "@" + post.ScreenName + " " + sTxt;
8419 StatusText.Text = sTxt;
8424 if (_curList.SelectedIndices.Count > 1)
8429 int sidx = StatusText.SelectionStart;
8430 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8432 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8433 if (!ids.Contains("@" + post.ScreenName + " ") &&
8434 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8436 ids += "@" + post.ScreenName + " ";
8440 foreach (string nm in post.ReplyToList)
8442 if (!ids.Contains("@" + nm + " ") &&
8443 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8445 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8447 ids += "@" + m.Result("${id}") + " ";
8449 ids += "@" + nm + " ";
8454 if (ids.Length == 0) return;
8455 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8457 StatusText.Text = ". " + StatusText.Text;
8459 this.inReplyTo = null;
8463 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8468 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8470 //if (StatusText.Text.StartsWith("@"))
8472 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8473 // sidx += 2 + ids.Length;
8477 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8478 // sidx += 1 + ids.Length;
8480 StatusText.SelectionStart = sidx;
8486 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8489 int sidx = StatusText.SelectionStart;
8490 PostClass post = _curPost;
8491 if (!ids.Contains("@" + post.ScreenName + " ") &&
8492 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8494 ids += "@" + post.ScreenName + " ";
8496 foreach (string nm in post.ReplyToList)
8498 if (!ids.Contains("@" + nm + " ") &&
8499 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8501 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8503 ids += "@" + m.Result("${id}") + " ";
8505 ids += "@" + nm + " ";
8508 if (!string.IsNullOrEmpty(post.RetweetedBy))
8510 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8511 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8513 ids += "@" + post.RetweetedBy + " ";
8516 if (ids.Length == 0) return;
8517 if (string.IsNullOrEmpty(StatusText.Text))
8520 StatusText.Text = ids;
8521 StatusText.SelectionStart = ids.Length;
8524 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8525 var inReplyToScreenName = this._curPost.ScreenName;
8526 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8532 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8537 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8539 StatusText.SelectionStart = sidx;
8545 StatusText.SelectionStart = StatusText.Text.Length;
8550 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8555 private static int iconCnt = 0;
8556 private static int blinkCnt = 0;
8557 private static bool blink = false;
8558 private static bool idle = false;
8560 private async Task RefreshTasktrayIcon()
8563 await this.Colorize();
8565 if (!TimerRefreshIcon.Enabled) return;
8566 //Static usCheckCnt As int = 0
8568 //Static iconDlListTopItem As ListViewItem = null
8570 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8571 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8573 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8575 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8581 //if (usCheckCnt > 300) //1min
8584 // if (!this.IsReceivedUserStream)
8586 // TraceOut("ReconnectUserStream");
8587 // tw.ReconnectUserStream();
8591 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8593 if (iconCnt >= this.NIconRefresh.Length)
8601 SaveConfigsAll(true);
8606 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8608 _myStatusError = false;
8612 TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8613 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8615 if (blinkCnt > 0) return;
8617 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8619 NotifyIcon1.Icon = ReplyIcon;
8623 NotifyIcon1.Icon = ReplyIconBlink;
8631 //優先度:エラー→オフライン→アイドル
8635 NotifyIcon1.Icon = NIconAtRed;
8638 if (_myStatusOnline)
8640 NotifyIcon1.Icon = NIconAt;
8644 NotifyIcon1.Icon = NIconAtSmoke;
8648 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8651 await this.RefreshTasktrayIcon();
8654 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8656 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8657 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8659 if (ListTab != null && ListTab.SelectedTab != null)
8660 _rclickTabName = ListTab.SelectedTab.Text;
8665 if (_statuses == null) return;
8666 if (_statuses.Tabs == null) return;
8668 TabClass tb = _statuses.Tabs[_rclickTabName];
8669 if (tb == null) return;
8671 NotifyDispMenuItem.Checked = tb.Notify;
8672 this.NotifyTbMenuItem.Checked = tb.Notify;
8674 soundfileListup = true;
8675 SoundFileComboBox.Items.Clear();
8676 this.SoundFileTbComboBox.Items.Clear();
8677 SoundFileComboBox.Items.Add("");
8678 this.SoundFileTbComboBox.Items.Add("");
8679 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8680 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8682 oDir = oDir.GetDirectories("Sounds")[0];
8684 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8686 SoundFileComboBox.Items.Add(oFile.Name);
8687 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8689 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8690 if (idx == -1) idx = 0;
8691 SoundFileComboBox.SelectedIndex = idx;
8692 this.SoundFileTbComboBox.SelectedIndex = idx;
8693 soundfileListup = false;
8694 UreadManageMenuItem.Checked = tb.UnreadManage;
8695 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8697 TabMenuControl(_rclickTabName);
8700 private void TabMenuControl(string tabName)
8702 var tabInfo = _statuses.GetTabByName(tabName);
8704 this.FilterEditMenuItem.Enabled = true;
8705 this.EditRuleTbMenuItem.Enabled = true;
8707 if (tabInfo.IsDefaultTabType)
8709 this.ProtectTabMenuItem.Enabled = false;
8710 this.ProtectTbMenuItem.Enabled = false;
8714 this.ProtectTabMenuItem.Enabled = true;
8715 this.ProtectTbMenuItem.Enabled = true;
8718 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8720 this.ProtectTabMenuItem.Checked = true;
8721 this.ProtectTbMenuItem.Checked = true;
8722 this.DeleteTabMenuItem.Enabled = false;
8723 this.DeleteTbMenuItem.Enabled = false;
8727 this.ProtectTabMenuItem.Checked = false;
8728 this.ProtectTbMenuItem.Checked = false;
8729 this.DeleteTabMenuItem.Enabled = true;
8730 this.DeleteTbMenuItem.Enabled = true;
8734 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8736 var checkState = ((ToolStripMenuItem)sender).Checked;
8739 this.ProtectTbMenuItem.Checked = checkState;
8740 this.ProtectTabMenuItem.Checked = checkState;
8743 this.DeleteTabMenuItem.Enabled = !checkState;
8744 this.DeleteTbMenuItem.Enabled = !checkState;
8746 if (string.IsNullOrEmpty(_rclickTabName)) return;
8747 _statuses.Tabs[_rclickTabName].Protected = checkState;
8752 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8754 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8755 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8757 if (string.IsNullOrEmpty(_rclickTabName)) return;
8758 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8763 public void ChangeTabUnreadManage(string tabName, bool isManage)
8765 var idx = this.GetTabPageIndex(tabName);
8769 _statuses.Tabs[tabName].UnreadManage = isManage;
8770 if (this._cfgCommon.TabIconDisp)
8772 if (_statuses.Tabs[tabName].UnreadCount > 0)
8773 ListTab.TabPages[idx].ImageIndex = 0;
8775 ListTab.TabPages[idx].ImageIndex = -1;
8778 if (_curTab.Text == tabName)
8780 this.PurgeListViewItemCache();
8784 SetMainWindowTitle();
8785 SetStatusLabelUrl();
8786 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8789 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8791 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8792 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8794 if (string.IsNullOrEmpty(_rclickTabName)) return;
8796 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8801 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8803 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8805 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8810 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8812 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8814 RemoveSpecifiedTab(_rclickTabName, true);
8818 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8820 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8822 using (var fltDialog = new FilterDialog())
8824 fltDialog.Owner = this;
8825 fltDialog.SetCurrent(_rclickTabName);
8826 fltDialog.ShowDialog(this);
8828 this.TopMost = this._cfgCommon.AlwaysTop;
8830 this.ApplyPostFilters();
8834 private void AddTabMenuItem_Click(object sender, EventArgs e)
8836 string tabName = null;
8837 MyCommon.TabUsageType tabUsage;
8838 using (InputTabName inputName = new InputTabName())
8840 inputName.TabName = _statuses.MakeTabName("MyTab");
8841 inputName.IsShowUsage = true;
8842 inputName.ShowDialog();
8843 if (inputName.DialogResult == DialogResult.Cancel) return;
8844 tabName = inputName.TabName;
8845 tabUsage = inputName.Usage;
8847 this.TopMost = this._cfgCommon.AlwaysTop;
8848 if (!string.IsNullOrEmpty(tabName))
8851 ListElement list = null;
8852 if (tabUsage == MyCommon.TabUsageType.Lists)
8854 using (ListAvailable listAvail = new ListAvailable())
8856 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8857 if (listAvail.SelectedList == null) return;
8858 list = listAvail.SelectedList;
8861 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8863 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8864 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8870 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8872 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8873 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8875 if (tabUsage == MyCommon.TabUsageType.Lists)
8877 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8878 var tab = this._statuses.Tabs[this._curTab.Text];
8879 this.GetListTimelineAsync(tab);
8885 private void TabMenuItem_Click(object sender, EventArgs e)
8887 using (var fltDialog = new FilterDialog())
8889 fltDialog.Owner = this;
8892 foreach (int idx in _curList.SelectedIndices)
8896 if (!SelectTab(out tabName)) return;
8898 fltDialog.SetCurrent(tabName);
8899 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8901 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8905 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8907 fltDialog.ShowDialog(this);
8908 this.TopMost = this._cfgCommon.AlwaysTop;
8912 this.ApplyPostFilters();
8914 if (this.ListTab.SelectedTab != null &&
8915 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8917 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8921 protected override bool ProcessDialogKey(Keys keyData)
8923 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8924 if ((keyData & Keys.KeyCode) == Keys.Enter)
8926 if (StatusText.Focused)
8928 bool _NewLine = false;
8931 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8933 if (StatusText.Multiline)
8935 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8937 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8941 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8945 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8947 if (StatusText.Multiline)
8949 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8951 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8955 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8961 if (StatusText.Multiline)
8963 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8965 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8966 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8970 if (((keyData & Keys.Shift) == Keys.Shift) ||
8971 (((keyData & Keys.Control) != Keys.Control) &&
8972 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8978 int pos1 = StatusText.SelectionStart;
8979 if (StatusText.SelectionLength > 0)
8981 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8983 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8984 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8989 PostButton_Click(null, null);
8993 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8994 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8995 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8997 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
9002 return base.ProcessDialogKey(keyData);
9005 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9007 MakeReplyOrDirectStatus(false, true, true);
9010 private void IDRuleMenuItem_Click(object sender, EventArgs e)
9015 if (_curList.SelectedIndices.Count == 0) return;
9018 if (!SelectTab(out tabName)) return;
9020 var tab = this._statuses.Tabs[tabName];
9024 if (tab.TabType != MyCommon.TabUsageType.Mute)
9026 this.MoveOrCopy(out mv, out mk);
9030 // ミュートタブでは常に MoveMatches を true にする
9035 List<string> ids = new List<string>();
9036 foreach (int idx in _curList.SelectedIndices)
9038 PostClass post = _statuses.Tabs[_curTab.Text][idx];
9039 if (!ids.Contains(post.ScreenName))
9041 PostFilterRule fc = new PostFilterRule();
9042 ids.Add(post.ScreenName);
9043 if (post.RetweetedId == null)
9045 fc.FilterName = post.ScreenName;
9049 fc.FilterName = post.RetweetedBy;
9051 fc.UseNameField = true;
9052 fc.MoveMatches = mv;
9053 fc.MarkMatches = mk;
9054 fc.UseRegex = false;
9055 fc.FilterByUrl = false;
9061 List<string> atids = new List<string>();
9062 foreach (string id in ids)
9064 atids.Add("@" + id);
9066 int cnt = AtIdSupl.ItemCount;
9067 AtIdSupl.AddRangeItem(atids.ToArray());
9068 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
9071 this.ApplyPostFilters();
9075 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
9077 if (this._curList.SelectedIndices.Count == 0)
9080 // タブ選択ダイアログを表示(or追加)
9082 if (!this.SelectTab(out tabName))
9085 var currentTab = this._statuses.Tabs[this._curTab.Text];
9086 var filterTab = this._statuses.Tabs[tabName];
9090 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
9092 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
9093 this.MoveOrCopy(out mv, out mk);
9097 // ミュートタブでは常に MoveMatches を true にする
9102 // 振り分けルールに追加するSource
9103 var sources = new HashSet<string>();
9105 foreach (var idx in this._curList.SelectedIndices.Cast<int>())
9107 var post = currentTab[idx];
9108 var filterSource = post.Source;
9110 if (sources.Add(filterSource))
9112 var filter = new PostFilterRule
9114 FilterSource = filterSource,
9118 FilterByUrl = false,
9120 filterTab.AddFilter(filter);
9124 this.ApplyPostFilters();
9125 this.SaveConfigsTabs();
9128 private bool SelectTab(out string tabName)
9135 using (var dialog = new TabsDialog(_statuses))
9137 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9139 var selectedTab = dialog.SelectedTab;
9140 tabName = selectedTab == null ? null : selectedTab.TabName;
9143 ListTab.SelectedTab.Focus();
9145 if (tabName == null)
9147 using (InputTabName inputName = new InputTabName())
9149 inputName.TabName = _statuses.MakeTabName("MyTab");
9150 inputName.ShowDialog();
9151 if (inputName.DialogResult == DialogResult.Cancel) return false;
9152 tabName = inputName.TabName;
9154 this.TopMost = this._cfgCommon.AlwaysTop;
9155 if (!string.IsNullOrEmpty(tabName))
9157 if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9159 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9160 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9178 private void MoveOrCopy(out bool move, out bool mark)
9182 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9183 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9191 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9192 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9202 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9207 private void CopyURLMenuItem_Click(object sender, EventArgs e)
9212 private void SelectAllMenuItem_Click(object sender, EventArgs e)
9214 if (StatusText.Focused)
9217 StatusText.SelectAll();
9221 // ListView上でのCtrl+A
9222 NativeMethods.SelectAllItems(this._curList);
9226 private void MoveMiddle()
9232 if (_curList.SelectedIndices.Count == 0) return;
9234 int idx = _curList.SelectedIndices[0];
9236 _item = _curList.GetItemAt(0, 25);
9242 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9244 idx2 = _curList.VirtualListSize - 1;
9248 idx -= Math.Abs(idx1 - idx2) / 2;
9249 if (idx < 0) idx = 0;
9251 _curList.EnsureVisible(_curList.VirtualListSize - 1);
9252 _curList.EnsureVisible(idx);
9255 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
9257 var linkElements = this.PostBrowser.Document.Links.Cast<HtmlElement>()
9258 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
9261 if (linkElements.Length > 0)
9263 UrlDialog.ClearUrl();
9265 string openUrlStr = "";
9267 if (linkElements.Length == 1)
9269 // ツイートに含まれる URL が 1 つのみの場合
9270 // => OpenURL ダイアログを表示せずにリンクを開く
9275 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
9277 catch (ArgumentException)
9286 if (string.IsNullOrEmpty(urlStr)) return;
9287 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9289 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
9290 await this.OpenUriAsync(new Uri(openUrlStr));
9294 // ツイートに含まれる URL が複数ある場合
9295 // => OpenURL を表示しユーザーが選択したリンクを開く
9297 foreach (var linkElm in linkElements)
9300 string linkText = "";
9304 urlStr = linkElm.GetAttribute("title");
9305 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9306 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9307 linkText = linkElm.InnerText;
9309 catch (ArgumentException)
9318 if (string.IsNullOrEmpty(urlStr)) continue;
9319 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9323 if (UrlDialog.ShowDialog() == DialogResult.OK)
9325 openUrlStr = UrlDialog.SelectedUrl;
9327 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
9328 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
9335 this.TopMost = this._cfgCommon.AlwaysTop;
9340 private void ClearTabMenuItem_Click(object sender, EventArgs e)
9342 if (string.IsNullOrEmpty(_rclickTabName)) return;
9343 ClearTab(_rclickTabName, true);
9346 private void ClearTab(string tabName, bool showWarning)
9350 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9351 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9357 _statuses.ClearTabIds(tabName);
9358 if (ListTab.SelectedTab.Text == tabName)
9361 _anchorFlag = false;
9362 this.PurgeListViewItemCache();
9366 foreach (TabPage tb in ListTab.TabPages)
9368 if (tb.Text == tabName)
9371 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9375 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9377 SetMainWindowTitle();
9378 SetStatusLabelUrl();
9381 private static long followers = 0;
9383 private void SetMainWindowTitle()
9386 StringBuilder ttl = new StringBuilder(256);
9389 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9390 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9391 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9392 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9394 foreach (var tab in _statuses.Tabs.Values)
9396 ur += tab.UnreadCount;
9401 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9402 ttl.Append(Application.ProductName);
9404 switch (this._cfgCommon.DispLatestPost)
9406 case MyCommon.DispTitleEnum.Ver:
9407 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9409 case MyCommon.DispTitleEnum.Post:
9410 if (_history != null && _history.Count > 1)
9411 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9413 case MyCommon.DispTitleEnum.UnreadRepCount:
9414 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9416 case MyCommon.DispTitleEnum.UnreadAllCount:
9417 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9419 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9420 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9422 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9423 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9425 case MyCommon.DispTitleEnum.OwnStatus:
9426 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9427 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9433 this.Text = ttl.ToString();
9435 catch (AccessViolationException)
9437 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9441 private string GetStatusLabelText()
9444 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9445 if (_statuses == null) return "";
9446 TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9447 TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9448 if (tbRep == null || tbDm == null) return "";
9449 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9454 StringBuilder slbl = new StringBuilder(256);
9457 foreach (var tab in _statuses.Tabs.Values)
9459 ur += tab.UnreadCount;
9461 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9463 tur = tab.UnreadCount;
9474 UnreadAtCounter = urat;
9476 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9477 if (this._cfgCommon.TimelinePeriod == 0)
9479 slbl.Append(Properties.Resources.SetStatusLabelText2);
9483 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9485 return slbl.ToString();
9488 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9492 if (this.InvokeRequired && !this.IsDisposed)
9494 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
9498 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9499 SetApiStatusLabel(endpointName);
9502 catch (ObjectDisposedException)
9506 catch (InvalidOperationException)
9512 private void SetApiStatusLabel(string endpointName = null)
9514 if (_curTab == null)
9516 this.toolStripApiGauge.ApiEndpoint = null;
9520 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9522 if (endpointName == null)
9527 case MyCommon.TabUsageType.Home:
9528 case MyCommon.TabUsageType.UserDefined:
9529 endpointName = "/statuses/home_timeline";
9532 case MyCommon.TabUsageType.Mentions:
9533 endpointName = "/statuses/mentions_timeline";
9536 case MyCommon.TabUsageType.Favorites:
9537 endpointName = "/favorites/list";
9540 case MyCommon.TabUsageType.DirectMessage:
9541 endpointName = "/direct_messages";
9544 case MyCommon.TabUsageType.UserTimeline:
9545 endpointName = "/statuses/user_timeline";
9548 case MyCommon.TabUsageType.Lists:
9549 endpointName = "/lists/statuses";
9552 case MyCommon.TabUsageType.PublicSearch:
9553 endpointName = "/search/tweets";
9556 case MyCommon.TabUsageType.Related:
9557 endpointName = "/statuses/show/:id";
9564 this.toolStripApiGauge.ApiEndpoint = endpointName;
9568 // 表示中のタブに関連する endpoint であれば更新
9571 switch (endpointName)
9573 case "/statuses/home_timeline":
9574 update = tabType == MyCommon.TabUsageType.Home ||
9575 tabType == MyCommon.TabUsageType.UserDefined;
9578 case "/statuses/mentions_timeline":
9579 update = tabType == MyCommon.TabUsageType.Mentions;
9582 case "/favorites/list":
9583 update = tabType == MyCommon.TabUsageType.Favorites;
9586 case "/direct_messages:":
9587 update = tabType == MyCommon.TabUsageType.DirectMessage;
9590 case "/statuses/user_timeline":
9591 update = tabType == MyCommon.TabUsageType.UserTimeline;
9594 case "/lists/statuses":
9595 update = tabType == MyCommon.TabUsageType.Lists;
9598 case "/search/tweets":
9599 update = tabType == MyCommon.TabUsageType.PublicSearch;
9602 case "/statuses/show/:id":
9603 update = tabType == MyCommon.TabUsageType.Related;
9612 this.toolStripApiGauge.ApiEndpoint = endpointName;
9618 private void SetStatusLabelUrl()
9620 StatusLabelUrl.Text = GetStatusLabelText();
9623 public void SetStatusLabel(string text)
9625 StatusLabel.Text = text;
9628 private static StringBuilder ur = new StringBuilder(64);
9630 private void SetNotifyIconText()
9632 // タスクトレイアイコンのツールチップテキスト書き換え
9634 ur.Remove(0, ur.Length);
9635 if (this._cfgCommon.DispUsername)
9637 ur.Append(tw.Username);
9640 ur.Append(Application.ProductName);
9642 ur.Append("(Debug Build)");
9644 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9647 ur.Append(UnreadCounter);
9649 ur.Append(UnreadAtCounter);
9652 NotifyIcon1.Text = ur.ToString();
9655 internal void CheckReplyTo(string StatusText)
9659 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9661 foreach (Match hm in m)
9663 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9665 hstr += "#" + hm.Result("$3") + " ";
9666 HashSupl.AddItem("#" + hm.Result("$3"));
9669 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9671 hstr += HashMgr.UseHash;
9673 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9675 // 本当にリプライ先指定すべきかどうかの判定
9676 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9678 if (this._cfgCommon.UseAtIdSupplement)
9680 int bCnt = AtIdSupl.ItemCount;
9681 foreach (Match mid in m)
9683 AtIdSupl.AddItem(mid.Result("${id}"));
9685 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9688 // リプライ先ステータスIDの指定がない場合は指定しない
9689 if (this.inReplyTo == null)
9693 // 次の条件を満たす場合に in_reply_to_status_id 指定
9694 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9695 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9696 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9700 var inReplyToScreenName = this.inReplyTo.Item2;
9701 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9703 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9707 foreach (Match mid in m)
9709 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9714 this.inReplyTo = null;
9717 private void TweenMain_Resize(object sender, EventArgs e)
9719 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9721 this.Visible = false;
9723 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9725 // 現在の DPI と設定保存時の DPI との比を取得する
9726 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9728 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9729 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9730 this.DesktopLocation = _cfgLocal.FormLocation;
9731 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9734 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9735 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9736 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9738 this.SplitContainer1.SplitterDistance = splitterDistance;
9742 StatusText.Multiline = _cfgLocal.StatusMultiline;
9743 if (StatusText.Multiline)
9745 var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9746 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9747 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9749 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9751 StatusText.Height = statusTextHeight;
9755 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9757 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9761 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9762 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9764 this.SplitContainer3.SplitterDistance = previewDistance;
9767 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9768 this.SplitContainer3.Panel2Collapsed = true;
9770 _initialLayout = false;
9772 if (this.WindowState != FormWindowState.Minimized)
9774 _formWindowState = this.WindowState;
9778 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9780 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9781 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9782 if (PlaySoundMenuItem.Checked)
9784 this._cfgCommon.PlaySound = true;
9788 this._cfgCommon.PlaySound = false;
9790 ModifySettingCommon = true;
9793 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9795 if (this._initialLayout)
9798 int splitterDistance;
9799 switch (this.WindowState)
9801 case FormWindowState.Normal:
9802 splitterDistance = this.SplitContainer1.SplitterDistance;
9804 case FormWindowState.Maximized:
9805 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9806 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9807 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9808 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9814 this._mySpDis = splitterDistance;
9815 this.ModifySettingLocal = true;
9818 private async Task doRepliedStatusOpen()
9820 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9822 if (MyCommon.IsKeyDown(Keys.Shift))
9824 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9827 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9829 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9830 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9834 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9836 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9837 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9838 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9841 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9846 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9848 await this.doRepliedStatusOpen();
9852 /// UserPicture.Image に設定されている画像を破棄します。
9854 private void ClearUserPicture()
9856 if (this.UserPicture.Image != null)
9858 var oldImage = this.UserPicture.Image;
9859 this.UserPicture.Image = null;
9864 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9866 //発言詳細のアイコン右クリック時のメニュー制御
9867 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9869 string name = _curPost.ImageUrl;
9870 if (name != null && name.Length > 0)
9872 int idx = name.LastIndexOf('/');
9875 name = Path.GetFileName(name.Substring(idx));
9876 if (name.Contains("_normal.") || name.EndsWith("_normal", StringComparison.Ordinal))
9878 name = name.Replace("_normal", "");
9879 this.IconNameToolStripMenuItem.Text = name;
9880 this.IconNameToolStripMenuItem.Enabled = true;
9884 this.IconNameToolStripMenuItem.Enabled = false;
9885 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9890 this.IconNameToolStripMenuItem.Enabled = false;
9891 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9894 this.ReloadIconToolStripMenuItem.Enabled = true;
9896 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9898 this.SaveIconPictureToolStripMenuItem.Enabled = true;
9902 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9907 this.IconNameToolStripMenuItem.Enabled = false;
9908 this.ReloadIconToolStripMenuItem.Enabled = false;
9909 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9910 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9915 this.IconNameToolStripMenuItem.Enabled = false;
9916 this.ReloadIconToolStripMenuItem.Enabled = false;
9917 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9918 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9920 if (NameLabel.Tag != null)
9922 string id = (string)NameLabel.Tag;
9923 if (id == tw.Username)
9925 FollowToolStripMenuItem.Enabled = false;
9926 UnFollowToolStripMenuItem.Enabled = false;
9927 ShowFriendShipToolStripMenuItem.Enabled = false;
9928 ShowUserStatusToolStripMenuItem.Enabled = true;
9929 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9930 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9931 ListManageUserContextToolStripMenuItem3.Enabled = true;
9935 FollowToolStripMenuItem.Enabled = true;
9936 UnFollowToolStripMenuItem.Enabled = true;
9937 ShowFriendShipToolStripMenuItem.Enabled = true;
9938 ShowUserStatusToolStripMenuItem.Enabled = true;
9939 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9940 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9941 ListManageUserContextToolStripMenuItem3.Enabled = true;
9946 FollowToolStripMenuItem.Enabled = false;
9947 UnFollowToolStripMenuItem.Enabled = false;
9948 ShowFriendShipToolStripMenuItem.Enabled = false;
9949 ShowUserStatusToolStripMenuItem.Enabled = false;
9950 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9951 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9952 ListManageUserContextToolStripMenuItem3.Enabled = false;
9956 private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9958 if (_curPost == null) return;
9959 string name = _curPost.ImageUrl;
9960 await this.OpenUriInBrowserAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9963 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9965 if (this._curPost == null) return;
9967 await this.UserPicture.SetImageFromTask(async () =>
9969 var imageUrl = this._curPost.ImageUrl;
9971 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
9972 .ConfigureAwait(false);
9974 return await image.CloneAsync()
9975 .ConfigureAwait(false);
9979 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9981 if (_curPost == null) return;
9982 string name = _curPost.ImageUrl;
9983 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
9985 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
9987 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9993 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9995 if (_curPost == null) return;
9996 string name = _curPost.ImageUrl;
9998 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
10000 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10004 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
10006 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
10008 using (Graphics g = Graphics.FromImage(bmp2))
10010 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
10011 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
10013 bmp2.Save(this.SaveFileDialog1.FileName);
10019 //処理中にキャッシュアウトする可能性あり
10024 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
10026 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
10027 if (multiline != this.StatusText.Multiline)
10029 this.StatusText.Multiline = multiline;
10030 MultiLineMenuItem.Checked = multiline;
10031 ModifySettingLocal = true;
10035 private void StatusText_MultilineChanged(object sender, EventArgs e)
10037 if (this.StatusText.Multiline)
10038 this.StatusText.ScrollBars = ScrollBars.Vertical;
10040 this.StatusText.ScrollBars = ScrollBars.None;
10042 ModifySettingLocal = true;
10045 private void MultiLineMenuItem_Click(object sender, EventArgs e)
10048 StatusText.Multiline = MultiLineMenuItem.Checked;
10049 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
10050 if (MultiLineMenuItem.Checked)
10052 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
10053 SplitContainer2.SplitterDistance = 0;
10055 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
10059 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
10061 ModifySettingLocal = true;
10064 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
10066 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
10067 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
10069 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
10070 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
10071 //Appendix A. Collected ABNF for URI
10072 //http://www.ietf.org/rfc/rfc3986.txt
10074 string result = "";
10076 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
10078 if (StatusText.SelectionLength > 0)
10080 string tmp = StatusText.SelectedText;
10081 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
10082 if (tmp.StartsWith("http"))
10084 // 文字列が選択されている場合はその文字列について処理
10086 //nico.ms使用、nicovideoにマッチしたら変換
10087 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10089 result = nicoms.Shorten(tmp);
10091 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10093 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10096 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10097 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10098 result = resultUri.AbsoluteUri;
10100 catch (WebApiException e)
10102 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10105 catch (UriFormatException e)
10107 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10116 if (!string.IsNullOrEmpty(result))
10118 urlUndo undotmp = new urlUndo();
10120 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
10121 StatusText.SelectedText = result;
10124 undotmp.Before = tmp;
10125 undotmp.After = result;
10127 if (urlUndoBuffer == null)
10129 urlUndoBuffer = new List<urlUndo>();
10130 UrlUndoToolStripMenuItem.Enabled = true;
10133 urlUndoBuffer.Add(undotmp);
10139 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
10140 @"(?<url>(?<protocol>https?://)" +
10141 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
10142 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
10143 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
10144 // 正規表現にマッチしたURL文字列をtinyurl化
10145 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
10147 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
10148 string tmp = mt.Result("${url}");
10149 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
10150 urlUndo undotmp = new urlUndo();
10153 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10155 //nico.ms使用、nicovideoにマッチしたら変換
10156 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10158 result = nicoms.Shorten(tmp);
10160 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10162 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10165 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10166 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10167 result = resultUri.AbsoluteUri;
10169 catch (HttpRequestException e)
10171 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
10172 // のように長いので「:」が含まれていればそれ以降のみを抽出する
10173 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
10175 this.StatusLabel.Text = Converter_Type + ":" + message;
10178 catch (WebApiException e)
10180 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10183 catch (UriFormatException e)
10185 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10194 if (!string.IsNullOrEmpty(result))
10196 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10197 StatusText.SelectedText = result;
10199 undotmp.Before = mt.Result("${url}");
10200 undotmp.After = result;
10202 if (urlUndoBuffer == null)
10204 urlUndoBuffer = new List<urlUndo>();
10205 UrlUndoToolStripMenuItem.Enabled = true;
10208 urlUndoBuffer.Add(undotmp);
10216 private void doUrlUndo()
10218 if (urlUndoBuffer != null)
10220 string tmp = StatusText.Text;
10221 foreach (urlUndo data in urlUndoBuffer)
10223 tmp = tmp.Replace(data.After, data.Before);
10225 StatusText.Text = tmp;
10226 urlUndoBuffer = null;
10227 UrlUndoToolStripMenuItem.Enabled = false;
10228 StatusText.SelectionStart = 0;
10229 StatusText.SelectionLength = 0;
10233 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10235 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10238 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10240 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10243 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10245 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10248 private async void UxnuMenuItem_Click(object sender, EventArgs e)
10250 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10253 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10255 if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
10257 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
10258 Random rnd = new Random();
10259 // 前回使用した短縮URLサービス以外を選択する
10262 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10264 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10265 await UrlConvertAsync(svc);
10269 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10274 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10276 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10277 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10278 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10279 ModifySettingCommon = true;
10282 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10284 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10285 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10286 _cfgCommon.ListLock = ListLockMenuItem.Checked;
10287 ModifySettingCommon = true;
10290 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10292 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10293 MenuStrip1.Tag = new Object();
10294 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10297 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10299 if (this.Tag != null) // 設定された戻り先へ遷移
10301 if (this.Tag == this.ListTab.SelectedTab)
10302 ((Control)this.ListTab.SelectedTab.Tag).Select();
10304 ((Control)this.Tag).Select();
10306 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10308 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10310 this.Tag = ListTab.SelectedTab.Tag;
10311 ((Control)this.Tag).Select();
10314 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10315 MenuStrip1.Tag = null;
10318 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10320 DetailsListView lst = (DetailsListView)sender;
10321 if (_cfgLocal == null) return;
10325 _cfgLocal.Width1 = lst.Columns[0].Width;
10326 _cfgLocal.Width3 = lst.Columns[1].Width;
10330 int[] darr = new int[lst.Columns.Count];
10331 for (int i = 0; i < lst.Columns.Count; i++)
10333 darr[lst.Columns[i].DisplayIndex] = i;
10335 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10337 for (int i = 0; i < lst.Columns.Count; i++)
10342 _cfgLocal.DisplayIndex1 = i;
10345 _cfgLocal.DisplayIndex2 = i;
10348 _cfgLocal.DisplayIndex3 = i;
10351 _cfgLocal.DisplayIndex4 = i;
10354 _cfgLocal.DisplayIndex5 = i;
10357 _cfgLocal.DisplayIndex6 = i;
10360 _cfgLocal.DisplayIndex7 = i;
10363 _cfgLocal.DisplayIndex8 = i;
10367 _cfgLocal.Width1 = lst.Columns[0].Width;
10368 _cfgLocal.Width2 = lst.Columns[1].Width;
10369 _cfgLocal.Width3 = lst.Columns[2].Width;
10370 _cfgLocal.Width4 = lst.Columns[3].Width;
10371 _cfgLocal.Width5 = lst.Columns[4].Width;
10372 _cfgLocal.Width6 = lst.Columns[5].Width;
10373 _cfgLocal.Width7 = lst.Columns[6].Width;
10374 _cfgLocal.Width8 = lst.Columns[7].Width;
10376 ModifySettingLocal = true;
10377 _isColumnChanged = true;
10380 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10382 DetailsListView lst = (DetailsListView)sender;
10383 if (_cfgLocal == null) return;
10386 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10388 _cfgLocal.Width1 = lst.Columns[0].Width;
10389 ModifySettingLocal = true;
10390 _isColumnChanged = true;
10392 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10394 _cfgLocal.Width3 = lst.Columns[1].Width;
10395 ModifySettingLocal = true;
10396 _isColumnChanged = true;
10401 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10403 _cfgLocal.Width1 = lst.Columns[0].Width;
10404 ModifySettingLocal = true;
10405 _isColumnChanged = true;
10407 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10409 _cfgLocal.Width2 = lst.Columns[1].Width;
10410 ModifySettingLocal = true;
10411 _isColumnChanged = true;
10413 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10415 _cfgLocal.Width3 = lst.Columns[2].Width;
10416 ModifySettingLocal = true;
10417 _isColumnChanged = true;
10419 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10421 _cfgLocal.Width4 = lst.Columns[3].Width;
10422 ModifySettingLocal = true;
10423 _isColumnChanged = true;
10425 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10427 _cfgLocal.Width5 = lst.Columns[4].Width;
10428 ModifySettingLocal = true;
10429 _isColumnChanged = true;
10431 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10433 _cfgLocal.Width6 = lst.Columns[5].Width;
10434 ModifySettingLocal = true;
10435 _isColumnChanged = true;
10437 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10439 _cfgLocal.Width7 = lst.Columns[6].Width;
10440 ModifySettingLocal = true;
10441 _isColumnChanged = true;
10443 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10445 _cfgLocal.Width8 = lst.Columns[7].Width;
10446 ModifySettingLocal = true;
10447 _isColumnChanged = true;
10450 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10453 // SaveConfigsLocal();
10457 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10460 string _selText = this.PostBrowser.GetSelectedText();
10463 Clipboard.SetDataObject(_selText, false, 5, 100);
10465 catch (Exception ex)
10467 MessageBox.Show(ex.Message);
10471 private async Task doSearchToolStrip(string url)
10473 //発言詳細で「選択文字列で検索」(選択文字列取得)
10474 string _selText = this.PostBrowser.GetSelectedText();
10476 if (_selText != null)
10478 if (url == Properties.Resources.SearchItem4Url)
10481 AddNewTabForSearch(_selText);
10485 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10486 await this.OpenUriInBrowserAsync(tmp);
10490 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10493 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10496 private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10498 await this.doSearchToolStrip(Properties.Resources.SearchItem1Url);
10501 private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10503 await this.doSearchToolStrip(Properties.Resources.SearchItem2Url);
10506 private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10508 await this.doSearchToolStrip(Properties.Resources.SearchItem4Url);
10511 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10515 foreach (var link in this.PostBrowser.Document.Links.Cast<HtmlElement>())
10517 if (link.GetAttribute("href") == this._postBrowserStatusText)
10519 var linkStr = link.GetAttribute("title");
10520 if (string.IsNullOrEmpty(linkStr))
10521 linkStr = link.GetAttribute("href");
10523 Clipboard.SetDataObject(linkStr, false, 5, 100);
10528 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10530 catch (Exception ex)
10532 MessageBox.Show(ex.Message);
10536 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10538 // URLコピーの項目の表示/非表示
10539 if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal))
10541 this._postBrowserStatusText = PostBrowser.StatusText;
10542 string name = GetUserId();
10543 UrlCopyContextMenuItem.Enabled = true;
10546 FollowContextMenuItem.Enabled = true;
10547 RemoveContextMenuItem.Enabled = true;
10548 FriendshipContextMenuItem.Enabled = true;
10549 ShowUserStatusContextMenuItem.Enabled = true;
10550 SearchPostsDetailToolStripMenuItem.Enabled = true;
10551 IdFilterAddMenuItem.Enabled = true;
10552 ListManageUserContextToolStripMenuItem.Enabled = true;
10553 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10557 FollowContextMenuItem.Enabled = false;
10558 RemoveContextMenuItem.Enabled = false;
10559 FriendshipContextMenuItem.Enabled = false;
10560 ShowUserStatusContextMenuItem.Enabled = false;
10561 SearchPostsDetailToolStripMenuItem.Enabled = false;
10562 IdFilterAddMenuItem.Enabled = false;
10563 ListManageUserContextToolStripMenuItem.Enabled = false;
10564 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10567 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10568 UseHashtagMenuItem.Enabled = true;
10570 UseHashtagMenuItem.Enabled = false;
10574 this._postBrowserStatusText = "";
10575 UrlCopyContextMenuItem.Enabled = false;
10576 FollowContextMenuItem.Enabled = false;
10577 RemoveContextMenuItem.Enabled = false;
10578 FriendshipContextMenuItem.Enabled = false;
10579 ShowUserStatusContextMenuItem.Enabled = false;
10580 SearchPostsDetailToolStripMenuItem.Enabled = false;
10581 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10582 UseHashtagMenuItem.Enabled = false;
10583 IdFilterAddMenuItem.Enabled = false;
10584 ListManageUserContextToolStripMenuItem.Enabled = false;
10586 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10587 string _selText = this.PostBrowser.GetSelectedText();
10588 if (_selText == null)
10590 SelectionSearchContextMenuItem.Enabled = false;
10591 SelectionCopyContextMenuItem.Enabled = false;
10592 SelectionTranslationToolStripMenuItem.Enabled = false;
10596 SelectionSearchContextMenuItem.Enabled = true;
10597 SelectionCopyContextMenuItem.Enabled = true;
10598 SelectionTranslationToolStripMenuItem.Enabled = true;
10600 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10601 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10602 bool fAllFlag = false;
10603 foreach (Match mu in ma)
10605 if (mu.Result("${ScreenName}").ToLowerInvariant() != tw.Username.ToLowerInvariant())
10611 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10613 if (_curPost == null)
10614 TranslationToolStripMenuItem.Enabled = false;
10616 TranslationToolStripMenuItem.Enabled = true;
10621 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10623 //発言詳細の選択文字列で現在のタブを検索
10624 string _selText = this.PostBrowser.GetSelectedText();
10626 if (_selText != null)
10628 var searchOptions = new SearchWordDialog.SearchOptions(
10629 SearchWordDialog.SearchType.Timeline,
10632 caseSensitive: false,
10635 this.SearchDialog.ResultOptions = searchOptions;
10638 searchOptions.Query,
10639 searchOptions.CaseSensitive,
10640 searchOptions.UseRegex,
10641 SEARCHTYPE.NextSearch);
10645 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10647 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10648 ModifySettingLocal = true;
10651 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10653 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10655 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10657 SelectMedia_DragDrop(e);
10660 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10662 var url = GetUrlFromDataObject(e.Data);
10665 if (url.Item2 == null)
10666 appendText = url.Item1;
10668 appendText = url.Item2 + " " + url.Item1;
10670 if (this.StatusText.TextLength == 0)
10671 this.StatusText.Text = appendText;
10673 this.StatusText.Text += " " + appendText;
10675 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10677 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10679 this.StatusText.Text += text;
10681 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10683 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10684 if (data != null) StatusText.Text += data;
10689 /// IDataObject から URL とタイトルの対を取得します
10692 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10694 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10695 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10696 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10698 if (data.GetDataPresent("text/x-moz-url"))
10700 // Firefox, Google Chrome で利用可能
10701 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10703 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10705 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10706 if (lines.Length < 2)
10707 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
10709 return new Tuple<string, string>(lines[0], lines[1]);
10712 else if (data.GetDataPresent("IESiteModeToUrl"))
10714 // Internet Exproler 用
10715 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10717 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10719 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10720 if (lines.Length < 2)
10721 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
10723 return new Tuple<string, string>(lines[0], lines[1]);
10726 else if (data.GetDataPresent("UniformResourceLocatorW"))
10730 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10732 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10733 return new Tuple<string, string>(url, null);
10737 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10740 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10742 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10744 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10746 SelectMedia_DragEnter(e);
10750 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10752 e.Effect = DragDropEffects.Copy;
10755 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10757 e.Effect = DragDropEffects.Copy;
10760 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10762 e.Effect = DragDropEffects.Copy;
10766 e.Effect = DragDropEffects.None;
10769 private void TweenMain_DragOver(object sender, DragEventArgs e)
10773 public bool IsNetworkAvailable()
10776 nw = MyCommon.IsNetworkAvailable();
10777 _myStatusOnline = nw;
10781 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
10783 var uriStr = uri.AbsoluteUri;
10785 // OpenTween 内部で使用する URL
10786 if (uri.Authority == "opentween")
10788 await this.OpenInternalUriAsync(uri);
10792 // ハッシュタグを含む Twitter 検索
10793 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
10795 // ハッシュタグの場合は、タブで開く
10796 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
10797 var pos = unescapedQuery.IndexOf('#');
10798 if (pos == -1) return;
10800 var hash = unescapedQuery.Substring(pos);
10801 this.HashSupl.AddItem(hash);
10802 this.HashMgr.AddHashToHistory(hash.Trim(), false);
10803 this.AddNewTabForSearch(hash);
10808 // フラグが立っている場合は設定と逆の動作をする
10809 if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
10810 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
10812 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
10813 if (userUriMatch.Success)
10815 var screenName = userUriMatch.Groups["ScreenName"].Value;
10816 if (this.IsTwitterId(screenName))
10818 this.AddNewTabForUserTimeline(screenName);
10824 // どのパターンにも該当しないURL
10825 await this.OpenUriInBrowserAsync(uriStr);
10829 /// OpenTween 内部の機能を呼び出すための URL を開きます
10831 private async Task OpenInternalUriAsync(Uri uri)
10833 // ツイートを開く (//opentween/status/:status_id)
10834 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
10837 var statusId = long.Parse(match.Groups[1].Value);
10838 await this.OpenRelatedTab(statusId);
10843 public Task OpenUriInBrowserAsync(string UriString)
10845 return Task.Run(() =>
10847 string myPath = UriString;
10851 var configBrowserPath = this._cfgLocal.BrowserPath;
10852 if (!string.IsNullOrEmpty(configBrowserPath))
10854 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
10856 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
10857 string browserPath = configBrowserPath.Substring(1, sep - 1);
10859 if (sep < configBrowserPath.Length - 1)
10861 arg = configBrowserPath.Substring(sep + 1);
10863 myPath = arg + " " + myPath;
10864 System.Diagnostics.Process.Start(browserPath, myPath);
10868 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10873 System.Diagnostics.Process.Start(myPath);
10878 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10883 private void ListTabSelect(TabPage _tab)
10887 this.PurgeListViewItemCache();
10890 _curList = (DetailsListView)_tab.Tag;
10891 if (_curList.SelectedIndices.Count > 0)
10893 _curItemIndex = _curList.SelectedIndices[0];
10894 _curPost = GetCurTabPost(_curItemIndex);
10898 _curItemIndex = -1;
10902 _anchorPost = null;
10903 _anchorFlag = false;
10907 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10911 for (int i = 0; i < _curList.Columns.Count; i++)
10913 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10918 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10920 ListTabSelect(e.TabPage);
10923 private void SelectListItem(DetailsListView LView, int Index)
10926 Rectangle bnd = new Rectangle();
10928 var item = LView.FocusedItem;
10937 LView.SelectedIndices.Clear();
10939 while (LView.SelectedIndices.Count > 0);
10940 item = LView.Items[Index];
10941 item.Selected = true;
10942 item.Focused = true;
10944 if (flg) LView.Invalidate(bnd);
10947 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
10950 Rectangle bnd = new Rectangle();
10952 var item = LView.FocusedItem;
10963 LView.SelectedIndices.Clear();
10965 while (LView.SelectedIndices.Count > 0);
10966 LView.SelectItems(Index);
10968 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
10970 LView.SelectionMark = selectionMarkIndex;
10972 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
10974 LView.Items[focusedIndex].Focused = true;
10976 else if (Index != null && Index.Length != 0)
10978 LView.Items[Index.Last()].Focused = true;
10981 if (flg) LView.Invalidate(bnd);
10984 private void StartUserStream()
10986 tw.NewPostFromStream += tw_NewPostFromStream;
10987 tw.UserStreamStarted += tw_UserStreamStarted;
10988 tw.UserStreamStopped += tw_UserStreamStopped;
10989 tw.PostDeleted += tw_PostDeleted;
10990 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
10992 this.RefreshUserStreamsMenu();
10994 if (this._cfgCommon.UserstreamStartup)
10995 tw.StartUserStream();
10998 private async void TweenMain_Shown(object sender, EventArgs e)
11002 using (ControlTransaction.Update(this.PostBrowser))
11004 PostBrowser.Url = new Uri("about:blank");
11005 PostBrowser.DocumentText = ""; //発言詳細部初期化
11012 NotifyIcon1.Visible = true;
11014 if (this.IsNetworkAvailable())
11018 var loadTasks = new List<Task>
11020 this.RefreshMuteUserIdsAsync(),
11021 this.RefreshBlockIdsAsync(),
11022 this.RefreshNoRetweetIdsAsync(),
11023 this.RefreshTwitterConfigurationAsync(),
11024 this.GetHomeTimelineAsync(),
11025 this.GetReplyAsync(),
11026 this.GetDirectMessagesAsync(),
11027 this.GetPublicSearchAllAsync(),
11028 this.GetUserTimelineAllAsync(),
11029 this.GetListTimelineAllAsync(),
11032 if (this._cfgCommon.StartupFollowers)
11033 loadTasks.Add(this.RefreshFollowerIdsAsync());
11035 if (this._cfgCommon.GetFav)
11036 loadTasks.Add(this.GetFavoritesAsync());
11038 var allTasks = Task.WhenAll(loadTasks);
11043 var timeout = Task.Delay(5000);
11044 if (await Task.WhenAny(allTasks, timeout) != timeout)
11048 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
11050 if (MyCommon._endingFlag)
11054 if (MyCommon._endingFlag) return;
11056 if (ApplicationSettings.VersionInfoUrl != null)
11058 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
11059 if (this._cfgCommon.StartupVersion)
11060 await this.CheckNewVersion(true);
11064 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
11065 this.VerUpMenuItem.Enabled = false;
11066 this.VerUpMenuItem.Available = false;
11067 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
11070 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
11071 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
11073 MessageBox.Show(Properties.Resources.ReAuthorizeText);
11074 SettingStripMenuItem_Click(null, null);
11078 var reloadTasks = new List<Task>();
11080 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
11081 reloadTasks.Add(this.RefreshFollowerIdsAsync());
11083 if (!tw.GetNoRetweetSuccess)
11084 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
11086 if (this.tw.Configuration.PhotoSizeLimit == 0)
11087 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
11089 await Task.WhenAll(reloadTasks);
11094 TimerTimeline.Enabled = true;
11097 private async Task doGetFollowersMenu()
11099 await this.RefreshFollowerIdsAsync();
11100 await this.DispSelectedPost(true);
11103 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
11105 await this.doGetFollowersMenu();
11108 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
11110 doReTweetUnofficial();
11113 private async Task doReTweetOfficial(bool isConfirm)
11116 if (this.ExistCurrentPost)
11118 if (_curPost.IsProtect)
11120 MessageBox.Show("Protected.");
11121 _DoFavRetweetFlags = false;
11124 if (_curList.SelectedIndices.Count > 15)
11126 MessageBox.Show(Properties.Resources.RetweetLimitText);
11127 _DoFavRetweetFlags = false;
11130 else if (_curList.SelectedIndices.Count > 1)
11132 string QuestionText = Properties.Resources.RetweetQuestion2;
11133 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
11134 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
11136 case DialogResult.Cancel:
11137 case DialogResult.No:
11138 _DoFavRetweetFlags = false;
11144 if (_curPost.IsDm || _curPost.IsMe)
11146 _DoFavRetweetFlags = false;
11149 if (!this._cfgCommon.RetweetNoConfirm)
11151 string Questiontext = Properties.Resources.RetweetQuestion1;
11152 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11153 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11155 _DoFavRetweetFlags = false;
11161 var statusIds = new List<long>();
11162 foreach (int idx in _curList.SelectedIndices)
11164 PostClass post = GetCurTabPost(idx);
11165 if (!post.IsMe && !post.IsProtect && !post.IsDm)
11166 statusIds.Add(post.StatusId);
11169 await this.RetweetAsync(statusIds);
11173 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
11175 await this.doReTweetOfficial(true);
11178 private async Task FavoritesRetweetOfficial()
11180 if (!this.ExistCurrentPost) return;
11181 _DoFavRetweetFlags = true;
11182 var retweetTask = this.doReTweetOfficial(true);
11183 if (_DoFavRetweetFlags)
11185 _DoFavRetweetFlags = false;
11186 var favoriteTask = this.FavoriteChange(true, false);
11188 await Task.WhenAll(retweetTask, favoriteTask);
11196 private async Task FavoritesRetweetUnofficial()
11198 if (this.ExistCurrentPost && !_curPost.IsDm)
11200 _DoFavRetweetFlags = true;
11201 var favoriteTask = this.FavoriteChange(true);
11202 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11204 _DoFavRetweetFlags = false;
11205 doReTweetUnofficial();
11208 await favoriteTask;
11213 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11215 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11216 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11217 /// <returns>復元されたツイート本文</returns>
11218 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11220 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11223 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11225 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11227 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11231 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11233 statusHtml = statusHtml.Replace("<br>", " ");
11235 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11236 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
11237 statusHtml = statusHtml.Replace(" ", " ");
11239 return WebUtility.HtmlDecode(statusHtml);
11242 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11244 if (_curPost != null)
11245 await this.DispSelectedPost(true);
11248 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11250 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11251 DebugModeToolStripMenuItem.Visible = true;
11253 DebugModeToolStripMenuItem.Visible = false;
11256 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11258 this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11261 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11263 ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
11266 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11268 if (TraceOutToolStripMenuItem.Checked)
11269 MyCommon.TraceFlag = true;
11271 MyCommon.TraceFlag = false;
11274 private void TweenMain_Deactivate(object sender, EventArgs e)
11276 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11277 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11280 private void TabRenameMenuItem_Click(object sender, EventArgs e)
11282 if (string.IsNullOrEmpty(_rclickTabName)) return;
11283 TabRename(ref _rclickTabName);
11286 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11288 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11291 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11293 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11296 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11298 TwitterApiStatus apiStatus;
11300 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
11302 var cancellationToken = dialog.EnableCancellation();
11306 var task = this.tw.GetInfoApi();
11307 apiStatus = await dialog.WaitForAsync(this, task);
11309 catch (WebApiException)
11314 if (cancellationToken.IsCancellationRequested)
11317 if (apiStatus == null)
11319 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11324 using (var apiDlg = new ApiInfoDialog())
11326 apiDlg.ShowDialog(this);
11330 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
11332 var id = _curPost?.ScreenName ?? "";
11334 await this.FollowCommand(id);
11337 private async Task FollowCommand(string id)
11339 using (var inputName = new InputTabName())
11341 inputName.FormTitle = "Follow";
11342 inputName.FormDescription = Properties.Resources.FRMessage1;
11343 inputName.TabName = id;
11345 if (inputName.ShowDialog(this) != DialogResult.OK)
11347 if (string.IsNullOrWhiteSpace(inputName.TabName))
11350 id = inputName.TabName.Trim();
11353 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
11357 var task = this.twitterApi.FriendshipsCreate(id);
11358 await dialog.WaitForAsync(this, task);
11360 catch (WebApiException ex)
11362 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11367 MessageBox.Show(Properties.Resources.FRMessage3);
11370 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11372 var id = _curPost?.ScreenName ?? "";
11374 await this.RemoveCommand(id, false);
11377 private async Task RemoveCommand(string id, bool skipInput)
11381 using (var inputName = new InputTabName())
11383 inputName.FormTitle = "Unfollow";
11384 inputName.FormDescription = Properties.Resources.FRMessage1;
11385 inputName.TabName = id;
11387 if (inputName.ShowDialog(this) != DialogResult.OK)
11389 if (string.IsNullOrWhiteSpace(inputName.TabName))
11392 id = inputName.TabName.Trim();
11396 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
11400 var task = this.twitterApi.FriendshipsDestroy(id);
11401 await dialog.WaitForAsync(this, task);
11403 catch (WebApiException ex)
11405 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11410 MessageBox.Show(Properties.Resources.FRMessage3);
11413 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
11415 var id = _curPost?.ScreenName ?? "";
11417 await this.ShowFriendship(id);
11420 private async Task ShowFriendship(string id)
11422 using (var inputName = new InputTabName())
11424 inputName.FormTitle = "Show Friendships";
11425 inputName.FormDescription = Properties.Resources.FRMessage1;
11426 inputName.TabName = id;
11428 if (inputName.ShowDialog(this) != DialogResult.OK)
11430 if (string.IsNullOrWhiteSpace(inputName.TabName))
11433 id = inputName.TabName.Trim();
11436 bool isFollowing, isFollowed;
11438 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11440 var cancellationToken = dialog.EnableCancellation();
11444 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11445 var friendship = await dialog.WaitForAsync(this, task);
11447 isFollowing = friendship.Relationship.Source.Following;
11448 isFollowed = friendship.Relationship.Source.FollowedBy;
11450 catch (WebApiException ex)
11452 if (!cancellationToken.IsCancellationRequested)
11453 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
11457 if (cancellationToken.IsCancellationRequested)
11461 string result = "";
11464 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11468 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11472 result += Properties.Resources.GetFriendshipInfo3;
11476 result += Properties.Resources.GetFriendshipInfo4;
11478 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11479 MessageBox.Show(result);
11482 private async Task ShowFriendship(string[] ids)
11484 foreach (string id in ids)
11486 bool isFollowing, isFollowed;
11488 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11490 var cancellationToken = dialog.EnableCancellation();
11494 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11495 var friendship = await dialog.WaitForAsync(this, task);
11497 isFollowing = friendship.Relationship.Source.Following;
11498 isFollowed = friendship.Relationship.Source.FollowedBy;
11500 catch (WebApiException ex)
11502 if (!cancellationToken.IsCancellationRequested)
11503 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
11507 if (cancellationToken.IsCancellationRequested)
11511 string result = "";
11517 ff += Properties.Resources.GetFriendshipInfo1;
11521 ff += Properties.Resources.GetFriendshipInfo2;
11524 ff += System.Environment.NewLine + " ";
11527 ff += Properties.Resources.GetFriendshipInfo3;
11531 ff += Properties.Resources.GetFriendshipInfo4;
11533 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11536 if (MessageBox.Show(
11537 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11538 MessageBoxButtons.YesNo,
11539 MessageBoxIcon.Question,
11540 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11542 await this.RemoveCommand(id, true);
11547 MessageBox.Show(result);
11552 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
11554 await this.doShowUserStatus(tw.Username, false);
11555 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11557 // doShowUserStatus(tw.Username, false);
11561 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11566 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11567 // URLから切り出した文字列を渡す
11569 public bool IsTwitterId(string name)
11571 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11572 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11574 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
11577 private string GetUserId()
11579 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11580 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11581 return m.Result("${ScreenName}");
11586 private async void FollowContextMenuItem_Click(object sender, EventArgs e)
11588 string name = GetUserId();
11590 await this.FollowCommand(name);
11593 private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
11595 string name = GetUserId();
11597 await this.RemoveCommand(name, false);
11600 private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11602 string name = GetUserId();
11604 await this.ShowFriendship(name);
11607 private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11609 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11610 List<string> ids = new List<string>();
11611 foreach (Match mu in ma)
11613 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11615 ids.Add(mu.Result("${ScreenName}"));
11619 await this.ShowFriendship(ids.ToArray());
11622 private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11624 string name = GetUserId();
11626 await this.ShowUserStatus(name);
11629 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11631 string name = GetUserId();
11632 if (name != null) AddNewTabForUserTimeline(name);
11635 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11637 string name = GetUserId();
11638 if (name != null) AddNewTabForSearch("@" + name);
11641 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11643 ModifySettingCommon = true;
11646 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11648 ModifySettingCommon = true;
11651 private void doQuoteOfficial()
11653 if (this.ExistCurrentPost)
11655 if (_curPost.IsDm ||
11656 !StatusText.Enabled) return;
11658 if (_curPost.IsProtect)
11660 MessageBox.Show("Protected.");
11664 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
11666 this.inReplyTo = null;
11668 StatusText.SelectionStart = 0;
11669 StatusText.Focus();
11673 private void doReTweetUnofficial()
11676 if (this.ExistCurrentPost)
11678 if (_curPost.IsDm || !StatusText.Enabled)
11681 if (_curPost.IsProtect)
11683 MessageBox.Show("Protected.");
11686 string rtdata = _curPost.Text;
11687 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11689 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
11691 // 投稿時に in_reply_to_status_id を付加する
11692 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11693 var inReplyToScreenName = this._curPost.ScreenName;
11694 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
11696 StatusText.SelectionStart = 0;
11697 StatusText.Focus();
11701 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11706 private void SearchButton_Click(object sender, EventArgs e)
11709 Control pnl = ((Control)sender).Parent;
11710 if (pnl == null) return;
11711 string tbName = pnl.Parent.Text;
11712 TabClass tb = _statuses.Tabs[tbName];
11713 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11714 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11715 cmb.Text = cmb.Text.Trim();
11716 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11717 bool Quote = false;
11718 StringBuilder buf = new StringBuilder();
11719 char[] c = cmb.Text.ToCharArray();
11720 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11722 if (cnt > cmb.Text.Length - 4)
11724 buf.Append(cmb.Text.Substring(cnt));
11733 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11735 buf.Append(" OR ");
11740 buf.Append(c[cnt]);
11742 cmb.Text = buf.ToString();
11744 var listView = (DetailsListView)pnl.Parent.Tag;
11746 tb.SearchWords = cmb.Text;
11747 tb.SearchLang = cmbLang.Text;
11748 if (string.IsNullOrEmpty(cmb.Text))
11754 if (tb.IsSearchQueryChanged)
11756 int idx = cmb.Items.IndexOf(tb.SearchWords);
11757 if (idx > -1) cmb.Items.RemoveAt(idx);
11758 cmb.Items.Insert(0, tb.SearchWords);
11759 cmb.Text = tb.SearchWords;
11761 this.PurgeListViewItemCache();
11762 listView.VirtualListSize = 0;
11763 _statuses.ClearTabIds(tbName);
11764 SaveConfigsTabs(); //検索条件の保存
11767 this.GetPublicSearchAsync(tb);
11771 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11774 await this.DoRefreshMore();
11778 /// 指定されたタブのListTabにおける位置を返します
11781 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
11783 public int GetTabPageIndex(string tabName)
11786 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
11788 if (tabPage.Text == tabName)
11797 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11799 if (_statuses.RemovedTab.Count == 0)
11801 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11806 DetailsListView listView = null;
11808 TabClass tb = _statuses.RemovedTab.Pop();
11809 if (tb.TabType == MyCommon.TabUsageType.Related)
11811 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11812 if (relatedTab != null)
11814 // 関連発言なら既存のタブを置き換える
11815 tb.TabName = relatedTab.TabName;
11816 this.ClearTab(tb.TabName, false);
11817 _statuses.Tabs[tb.TabName] = tb;
11819 for (int i = 0; i < ListTab.TabPages.Count; i++)
11821 var tabPage = ListTab.TabPages[i];
11822 if (tb.TabName == tabPage.Text)
11824 listView = (DetailsListView)tabPage.Tag;
11825 ListTab.SelectedIndex = i;
11832 const string TabName = "Related Tweets";
11833 string renamed = TabName;
11834 for (int i = 2; i <= 100; i++)
11836 if (!_statuses.ContainsTab(renamed)) break;
11837 renamed = TabName + i.ToString();
11839 tb.TabName = renamed;
11840 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11841 _statuses.Tabs.Add(renamed, tb); // 後に
11843 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11844 listView = (DetailsListView)tabPage.Tag;
11845 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11850 string renamed = tb.TabName;
11851 for (int i = 1; i < int.MaxValue; i++)
11853 if (!_statuses.ContainsTab(renamed)) break;
11854 renamed = tb.TabName + "(" + i.ToString() + ")";
11856 tb.TabName = renamed;
11857 _statuses.Tabs.Add(renamed, tb); // 先に
11858 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11860 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11861 listView = (DetailsListView)tabPage.Tag;
11862 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11866 if (listView != null)
11868 using (ControlTransaction.Update(listView))
11870 listView.VirtualListSize = tb.AllCount;
11876 private async Task doMoveToRTHome()
11878 if (_curList.SelectedIndices.Count > 0)
11880 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11881 if (post.RetweetedId != null)
11883 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11888 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11890 await this.doMoveToRTHome();
11893 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11895 string name = GetUserId();
11901 if (_curList.SelectedIndices.Count == 0) return;
11904 if (!SelectTab(out tabName)) return;
11906 var tab = this._statuses.Tabs[tabName];
11910 if (tab.TabType != MyCommon.TabUsageType.Mute)
11912 this.MoveOrCopy(out mv, out mk);
11916 // ミュートタブでは常に MoveMatches を true にする
11921 PostFilterRule fc = new PostFilterRule();
11922 fc.FilterName = name;
11923 fc.UseNameField = true;
11924 fc.MoveMatches = mv;
11925 fc.MarkMatches = mk;
11926 fc.UseRegex = false;
11927 fc.FilterByUrl = false;
11930 this.ApplyPostFilters();
11935 private async void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11939 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11941 if (menuItem.Owner == this.ContextMenuPostBrowser)
11943 user = GetUserId();
11944 if (user == null) return;
11946 else if (this._curPost != null)
11948 user = this._curPost.ScreenName;
11955 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11959 using (var dialog = new WaitingDialog(Properties.Resources.ListsGetting))
11961 var cancellationToken = dialog.EnableCancellation();
11963 var task = this.tw.GetListsApi();
11964 await dialog.WaitForAsync(this, task);
11966 cancellationToken.ThrowIfCancellationRequested();
11969 catch (OperationCanceledException) { return; }
11970 catch (WebApiException ex)
11972 MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
11977 using (MyLists listSelectForm = new MyLists(user, this.tw))
11979 listSelectForm.ShowDialog(this);
11983 private void SearchControls_Enter(object sender, EventArgs e)
11985 Control pnl = (Control)sender;
11986 foreach (Control ctl in pnl.Controls)
11988 ctl.TabStop = true;
11992 private void SearchControls_Leave(object sender, EventArgs e)
11994 Control pnl = (Control)sender;
11995 foreach (Control ctl in pnl.Controls)
11997 ctl.TabStop = false;
12001 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
12003 if (ListTab.SelectedTab != null)
12005 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
12006 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
12010 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
12012 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
12015 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
12016 HashStripSplitButton.Text = HashMgr.UseHash;
12017 HashToggleMenuItem.Checked = true;
12018 HashToggleToolStripMenuItem.Checked = true;
12020 ModifySettingCommon = true;
12024 private void StatusLabel_DoubleClick(object sender, EventArgs e)
12026 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
12029 private void HashManageMenuItem_Click(object sender, EventArgs e)
12031 DialogResult rslt = DialogResult.Cancel;
12034 rslt = HashMgr.ShowDialog();
12040 this.TopMost = this._cfgCommon.AlwaysTop;
12041 if (rslt == DialogResult.Cancel) return;
12042 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12044 HashStripSplitButton.Text = HashMgr.UseHash;
12045 HashToggleMenuItem.Checked = true;
12046 HashToggleToolStripMenuItem.Checked = true;
12050 HashStripSplitButton.Text = "#[-]";
12051 HashToggleMenuItem.Checked = false;
12052 HashToggleToolStripMenuItem.Checked = false;
12054 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
12056 // int sidx = StatusText.SelectionStart;
12057 // string hash = HashMgr.UseHash + " ";
12060 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
12061 // hash = " " + hash;
12063 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
12064 // sidx += hash.Length;
12065 // StatusText.SelectionStart = sidx;
12066 // StatusText.Focus();
12068 ModifySettingCommon = true;
12069 this.StatusText_TextChanged(null, null);
12072 private void HashToggleMenuItem_Click(object sender, EventArgs e)
12074 HashMgr.ToggleHash();
12075 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12077 HashStripSplitButton.Text = HashMgr.UseHash;
12078 HashToggleMenuItem.Checked = true;
12079 HashToggleToolStripMenuItem.Checked = true;
12083 HashStripSplitButton.Text = "#[-]";
12084 HashToggleMenuItem.Checked = false;
12085 HashToggleToolStripMenuItem.Checked = false;
12087 ModifySettingCommon = true;
12088 this.StatusText_TextChanged(null, null);
12091 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
12093 HashToggleMenuItem_Click(null, null);
12096 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
12098 if (ListTab.SelectedTab == null) return;
12099 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
12100 if (!this.ExistCurrentPost)
12102 this.ReplyOpMenuItem.Enabled = false;
12103 this.ReplyAllOpMenuItem.Enabled = false;
12104 this.DmOpMenuItem.Enabled = false;
12105 this.ShowProfMenuItem.Enabled = false;
12106 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
12107 this.ListManageMenuItem.Enabled = false;
12108 this.OpenFavOpMenuItem.Enabled = false;
12109 this.CreateTabRuleOpMenuItem.Enabled = false;
12110 this.CreateIdRuleOpMenuItem.Enabled = false;
12111 this.CreateSourceRuleOpMenuItem.Enabled = false;
12112 this.ReadOpMenuItem.Enabled = false;
12113 this.UnreadOpMenuItem.Enabled = false;
12117 this.ReplyOpMenuItem.Enabled = true;
12118 this.ReplyAllOpMenuItem.Enabled = true;
12119 this.DmOpMenuItem.Enabled = true;
12120 this.ShowProfMenuItem.Enabled = true;
12121 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
12122 this.ListManageMenuItem.Enabled = true;
12123 this.OpenFavOpMenuItem.Enabled = true;
12124 this.CreateTabRuleOpMenuItem.Enabled = true;
12125 this.CreateIdRuleOpMenuItem.Enabled = true;
12126 this.CreateSourceRuleOpMenuItem.Enabled = true;
12127 this.ReadOpMenuItem.Enabled = true;
12128 this.UnreadOpMenuItem.Enabled = true;
12131 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
12133 this.FavOpMenuItem.Enabled = false;
12134 this.UnFavOpMenuItem.Enabled = false;
12135 this.OpenStatusOpMenuItem.Enabled = false;
12136 this.OpenFavotterOpMenuItem.Enabled = false;
12137 this.ShowRelatedStatusesMenuItem2.Enabled = false;
12138 this.RtOpMenuItem.Enabled = false;
12139 this.RtUnOpMenuItem.Enabled = false;
12140 this.QtOpMenuItem.Enabled = false;
12141 this.FavoriteRetweetMenuItem.Enabled = false;
12142 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12146 this.FavOpMenuItem.Enabled = true;
12147 this.UnFavOpMenuItem.Enabled = true;
12148 this.OpenStatusOpMenuItem.Enabled = true;
12149 this.OpenFavotterOpMenuItem.Enabled = true;
12150 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
12154 this.RtOpMenuItem.Enabled = false; //公式RTは無効に
12155 this.RtUnOpMenuItem.Enabled = true;
12156 this.QtOpMenuItem.Enabled = true;
12157 this.FavoriteRetweetMenuItem.Enabled = false; //公式RTは無効に
12158 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12162 if (_curPost.IsProtect)
12164 this.RtOpMenuItem.Enabled = false;
12165 this.RtUnOpMenuItem.Enabled = false;
12166 this.QtOpMenuItem.Enabled = false;
12167 this.FavoriteRetweetMenuItem.Enabled = false;
12168 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12172 this.RtOpMenuItem.Enabled = true;
12173 this.RtUnOpMenuItem.Enabled = true;
12174 this.QtOpMenuItem.Enabled = true;
12175 this.FavoriteRetweetMenuItem.Enabled = true;
12176 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12181 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
12183 this.RefreshPrevOpMenuItem.Enabled = true;
12187 this.RefreshPrevOpMenuItem.Enabled = false;
12189 if (!this.ExistCurrentPost
12190 || _curPost.InReplyToStatusId == null)
12192 OpenRepSourceOpMenuItem.Enabled = false;
12196 OpenRepSourceOpMenuItem.Enabled = true;
12198 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12200 OpenRterHomeMenuItem.Enabled = false;
12204 OpenRterHomeMenuItem.Enabled = true;
12207 if (this.ExistCurrentPost)
12209 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
12213 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12215 ContextMenuTabProperty_Opening(sender, null);
12218 public Twitter TwitterInstance
12223 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12225 if (this._initialLayout)
12228 int splitterDistance;
12229 switch (this.WindowState)
12231 case FormWindowState.Normal:
12232 splitterDistance = this.SplitContainer3.SplitterDistance;
12234 case FormWindowState.Maximized:
12235 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
12236 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
12237 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
12238 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
12244 this._mySpDis3 = splitterDistance;
12245 this.ModifySettingLocal = true;
12248 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12250 if (_statuses.RemovedTab.Count == 0)
12252 UndoRemoveTabMenuItem.Enabled = false;
12256 UndoRemoveTabMenuItem.Enabled = true;
12258 if (ListTab.SelectedTab != null)
12260 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12261 PublicSearchQueryMenuItem.Enabled = true;
12263 PublicSearchQueryMenuItem.Enabled = false;
12267 PublicSearchQueryMenuItem.Enabled = false;
12269 if (!this.ExistCurrentPost)
12271 this.CopySTOTMenuItem.Enabled = false;
12272 this.CopyURLMenuItem.Enabled = false;
12273 this.CopyUserIdStripMenuItem.Enabled = false;
12277 this.CopySTOTMenuItem.Enabled = true;
12278 this.CopyURLMenuItem.Enabled = true;
12279 this.CopyUserIdStripMenuItem.Enabled = true;
12280 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12281 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12285 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12287 SetNotifyIconText();
12290 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12292 var id = _curPost?.ScreenName ?? "";
12294 await this.ShowUserStatus(id);
12297 private async Task doShowUserStatus(string id, bool ShowInputDialog)
12299 TwitterUser user = null;
12301 if (ShowInputDialog)
12303 using (var inputName = new InputTabName())
12305 inputName.FormTitle = "Show UserStatus";
12306 inputName.FormDescription = Properties.Resources.FRMessage1;
12307 inputName.TabName = id;
12309 if (inputName.ShowDialog(this) != DialogResult.OK)
12311 if (string.IsNullOrWhiteSpace(inputName.TabName))
12314 id = inputName.TabName.Trim();
12318 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
12320 var cancellationToken = dialog.EnableCancellation();
12324 var task = this.twitterApi.UsersShow(id);
12325 user = await dialog.WaitForAsync(this, task);
12327 catch (WebApiException ex)
12329 if (!cancellationToken.IsCancellationRequested)
12330 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
12334 if (cancellationToken.IsCancellationRequested)
12338 await this.doShowUserStatus(user);
12341 private async Task doShowUserStatus(TwitterUser user)
12343 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
12345 var showUserTask = userDialog.ShowUserAsync(user);
12346 userDialog.ShowDialog(this);
12349 this.BringToFront();
12351 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12352 await showUserTask;
12356 private Task ShowUserStatus(string id, bool ShowInputDialog)
12358 return this.doShowUserStatus(id, ShowInputDialog);
12361 private Task ShowUserStatus(string id)
12363 return this.doShowUserStatus(id, true);
12366 private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12368 if (NameLabel.Tag != null)
12370 string id = (string)NameLabel.Tag;
12371 if (id != tw.Username)
12373 await this.FollowCommand(id);
12378 private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12380 if (NameLabel.Tag != null)
12382 string id = (string)NameLabel.Tag;
12383 if (id != tw.Username)
12385 await this.RemoveCommand(id, false);
12390 private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12392 if (NameLabel.Tag != null)
12394 string id = (string)NameLabel.Tag;
12395 if (id != tw.Username)
12397 await this.ShowFriendship(id);
12402 private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12404 if (NameLabel.Tag != null)
12406 string id = (string)NameLabel.Tag;
12407 await this.ShowUserStatus(id, false);
12411 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12413 if (NameLabel.Tag != null)
12415 string id = (string)NameLabel.Tag;
12416 AddNewTabForUserTimeline(id);
12420 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12422 if (NameLabel.Tag != null)
12424 string id = (string)NameLabel.Tag;
12425 AddNewTabForSearch("@" + id);
12429 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
12431 if (_curPost != null)
12433 await this.ShowUserStatus(_curPost.ScreenName, false);
12437 private async void RtCountMenuItem_Click(object sender, EventArgs e)
12439 if (!this.ExistCurrentPost)
12442 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
12443 TwitterStatus status;
12445 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
12447 var cancellationToken = dialog.EnableCancellation();
12451 var task = this.twitterApi.StatusesShow(statusId);
12452 status = await dialog.WaitForAsync(this, task);
12454 catch (WebApiException ex)
12456 if (!cancellationToken.IsCancellationRequested)
12457 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
12461 if (cancellationToken.IsCancellationRequested)
12465 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
12468 private HookGlobalHotkey _hookGlobalHotkey;
12471 _hookGlobalHotkey = new HookGlobalHotkey(this);
12473 // この呼び出しは、Windows フォーム デザイナで必要です。
12474 InitializeComponent();
12476 // InitializeComponent() 呼び出しの後で初期化を追加します。
12478 if (!this.DesignMode)
12480 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12481 this.StatusText.Dock = DockStyle.Fill;
12484 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12485 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12486 this.gh.NotifyClicked += GrowlHelper_Callback;
12488 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12489 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12491 this.ImageSelector.Visible = false;
12492 this.ImageSelector.Enabled = false;
12493 this.ImageSelector.FilePickDialog = OpenFileDialog1;
12495 this.ReplaceAppName();
12496 this.InitializeShortcuts();
12499 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12501 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12504 this.Visible = false;
12506 else if (Form.ActiveForm == null)
12508 this.Visible = true;
12509 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12511 this.BringToFront();
12512 this.StatusText.Focus();
12516 private void UserPicture_MouseEnter(object sender, EventArgs e)
12518 this.UserPicture.Cursor = Cursors.Hand;
12521 private void UserPicture_MouseLeave(object sender, EventArgs e)
12523 this.UserPicture.Cursor = Cursors.Default;
12526 private async void UserPicture_DoubleClick(object sender, EventArgs e)
12528 if (NameLabel.Tag != null)
12530 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12534 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12536 this.MultiLineMenuItem.PerformClick();
12539 public PostClass CurPost
12541 get { return _curPost; }
12545 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12547 if (ImageSelector.Visible)
12548 ImageSelector.EndSelection();
12550 ImageSelector.BeginSelection();
12553 private void SelectMedia_DragEnter(DragEventArgs e)
12555 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12557 e.Effect = DragDropEffects.Copy;
12560 e.Effect = DragDropEffects.None;
12563 private void SelectMedia_DragDrop(DragEventArgs e)
12566 this.BringToFront();
12567 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12568 StatusText.Focus();
12571 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12573 TimelinePanel.Visible = false;
12574 TimelinePanel.Enabled = false;
12577 private void ImageSelector_EndSelecting(object sender, EventArgs e)
12579 TimelinePanel.Visible = true;
12580 TimelinePanel.Enabled = true;
12581 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12584 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12586 this.AllowDrop = false;
12589 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12591 this.AllowDrop = true;
12594 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12596 if (ImageSelector.Visible)
12598 ModifySettingCommon = true;
12599 SaveConfigsAll(true);
12601 if (ImageSelector.ServiceName.Equals("Twitter"))
12602 this.StatusText_TextChanged(null, null);
12606 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12608 this.StatusText_TextChanged(null, null);
12612 /// StatusTextでCtrl+Vが押下された時の処理
12614 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
12616 if (Clipboard.ContainsText())
12618 // clipboardにテキストがある場合は貼り付け処理
12619 this.StatusText.Paste(Clipboard.GetText());
12621 else if (Clipboard.ContainsImage())
12624 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
12625 Properties.Resources.PostPictureWarn4,
12626 MessageBoxButtons.OKCancel,
12627 MessageBoxIcon.Question,
12628 MessageBoxDefaultButton.Button2)
12629 == DialogResult.OK)
12631 // clipboardから画像を取得
12632 using (var image = Clipboard.GetImage())
12634 this.ImageSelector.BeginSelection(image);
12641 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12643 using (ListManage form = new ListManage(tw))
12645 form.ShowDialog(this);
12649 public bool ModifySettingCommon { get; set; }
12650 public bool ModifySettingLocal { get; set; }
12651 public bool ModifySettingAtId { get; set; }
12653 private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12655 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12656 if (sourceUri != null && e.Button == MouseButtons.Left)
12658 await this.OpenUriInBrowserAsync(sourceUri.AbsoluteUri);
12662 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12664 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12665 if (sourceUri != null)
12667 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri);
12671 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12673 SetStatusLabelUrl();
12676 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12678 if (this.ExistCurrentPost && !_curPost.IsDm)
12679 RtCountMenuItem.Enabled = true;
12681 RtCountMenuItem.Enabled = false;
12683 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12684 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12686 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12689 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12694 private void CopyUserId()
12696 if (_curPost == null) return;
12697 string clstr = _curPost.ScreenName;
12700 Clipboard.SetDataObject(clstr, false, 5, 100);
12702 catch (Exception ex)
12704 MessageBox.Show(ex.Message);
12708 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12710 if (this.ExistCurrentPost && !_curPost.IsDm)
12714 await this.OpenRelatedTab(this._curPost);
12716 catch (TabException ex)
12718 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12724 /// 指定されたツイートに対する関連発言タブを開きます
12726 /// <param name="statusId">表示するツイートのID</param>
12727 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12728 private async Task OpenRelatedTab(long statusId)
12730 var post = this._statuses[statusId];
12735 post = await this.tw.GetStatusApi(false, statusId);
12737 catch (WebApiException ex)
12739 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
12744 await this.OpenRelatedTab(post);
12748 /// 指定されたツイートに対する関連発言タブを開きます
12750 /// <param name="post">表示する対象となるツイート</param>
12751 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12752 private async Task OpenRelatedTab(PostClass post)
12754 var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12757 if (tabRelated == null)
12759 tabName = this._statuses.MakeTabName("Related Tweets");
12761 tabRelated = new TabClass(tabName, MyCommon.TabUsageType.Related);
12762 tabRelated.UnreadManage = false;
12763 tabRelated.Notify = false;
12765 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12766 this._statuses.AddTab(tabRelated);
12770 tabName = tabRelated.TabName;
12773 tabRelated.RelationTargetPost = post;
12774 this.ClearTab(tabName, false);
12776 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12778 var tabPage = this.ListTab.TabPages[i];
12779 if (tabName == tabPage.Text)
12781 this.ListTab.SelectedIndex = i;
12786 await this.GetRelatedTweetsAsync(tabRelated);
12789 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12791 StringBuilder buf = new StringBuilder();
12792 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12793 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12794 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12795 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12796 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12799 private void tw_UserIdChanged()
12801 this.ModifySettingCommon = true;
12804 #region "Userstream"
12805 private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12809 if (InvokeRequired && !IsDisposed)
12811 Invoke((Action) (async () =>
12813 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
12814 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12816 this.PurgeListViewItemCache();
12817 ((DetailsListView)_curTab.Tag).Update();
12818 if (_curPost != null && _curPost.StatusId == e.StatusId)
12819 await this.DispSelectedPost(true);
12825 catch (ObjectDisposedException)
12829 catch (InvalidOperationException)
12835 private int userStreamsRefreshing = 0;
12837 private async void tw_NewPostFromStream(object sender, EventArgs e)
12839 if (this._cfgCommon.ReadOldPosts)
12841 _statuses.SetReadHomeTab(); //新着時未読クリア
12844 int rsltAddCount = _statuses.DistributePosts();
12846 this.UpdateTimelineSpeed(rsltAddCount);
12848 if (this._cfgCommon.UserstreamPeriod > 0) return;
12850 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
12851 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
12855 await this.InvokeAsync(() => this.RefreshTimeline())
12856 .ConfigureAwait(false);
12860 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
12865 private void tw_UserStreamStarted(object sender, EventArgs e)
12869 if (InvokeRequired && !IsDisposed)
12871 Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12875 catch (ObjectDisposedException)
12879 catch (InvalidOperationException)
12884 this.RefreshUserStreamsMenu();
12885 this.MenuItemUserStream.Enabled = true;
12887 StatusLabel.Text = "UserStream Started.";
12890 private void tw_UserStreamStopped(object sender, EventArgs e)
12894 if (InvokeRequired && !IsDisposed)
12896 Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12900 catch (ObjectDisposedException)
12904 catch (InvalidOperationException)
12909 this.RefreshUserStreamsMenu();
12910 this.MenuItemUserStream.Enabled = true;
12912 StatusLabel.Text = "UserStream Stopped.";
12915 private void RefreshUserStreamsMenu()
12917 if (this.tw.UserStreamActive)
12919 this.MenuItemUserStream.Text = "&UserStream ▶";
12920 this.StopToolStripMenuItem.Text = "&Stop";
12924 this.MenuItemUserStream.Text = "&UserStream ■";
12925 this.StopToolStripMenuItem.Text = "&Start";
12929 private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12933 if (InvokeRequired && !IsDisposed)
12935 Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12939 catch (ObjectDisposedException)
12943 catch (InvalidOperationException)
12947 var ev = e.EventData;
12948 StatusLabel.Text = "Event: " + ev.Event;
12949 //if (ev.Event == "favorite")
12951 // NotifyFavorite(ev);
12954 if (ev.Event == "favorite" || ev.Event == "unfavorite")
12956 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12958 this.PurgeListViewItemCache();
12959 ((DetailsListView)_curTab.Tag).Update();
12961 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
12963 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
12964 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
12969 private void NotifyEvent(Twitter.FormattedEvent ev)
12972 if (BalloonRequired(ev))
12974 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
12975 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
12976 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
12977 StringBuilder title = new StringBuilder();
12978 if (this._cfgCommon.DispUsername)
12980 title.Append(tw.Username);
12981 title.Append(" - ");
12987 title.Append(Application.ProductName);
12988 title.Append(" [");
12989 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
12990 title.Append("] by ");
12991 if (!string.IsNullOrEmpty(ev.Username))
12993 title.Append(ev.Username.ToString());
12997 //title.Append("");
13000 if (!string.IsNullOrEmpty(ev.Target))
13002 //NotifyIcon1.BalloonTipText = ev.Target;
13007 //NotifyIcon1.BalloonTipText = " ";
13010 //NotifyIcon1.ShowBalloonTip(500);
13011 if (this._cfgCommon.IsUseNotifyGrowl)
13013 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13014 ev.Id.ToString(), title.ToString(), text);
13018 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13019 NotifyIcon1.BalloonTipTitle = title.ToString();
13020 NotifyIcon1.BalloonTipText = text;
13021 NotifyIcon1.ShowBalloonTip(500);
13026 string snd = this._cfgCommon.EventSoundFile;
13027 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
13029 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13033 string dir = Application.StartupPath;
13034 if (Directory.Exists(Path.Combine(dir, "Sounds")))
13036 dir = Path.Combine(dir, "Sounds");
13038 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13050 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13052 MenuItemUserStream.Enabled = false;
13053 if (StopRefreshAllMenuItem.Checked)
13055 StopRefreshAllMenuItem.Checked = false;
13058 if (this.tw.UserStreamActive)
13060 tw.StopUserStream();
13064 tw.StartUserStream();
13068 private static string inputTrack = "";
13070 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13072 if (TrackToolStripMenuItem.Checked)
13074 using (InputTabName inputForm = new InputTabName())
13076 inputForm.TabName = inputTrack;
13077 inputForm.FormTitle = "Input track word";
13078 inputForm.FormDescription = "Track word";
13079 if (inputForm.ShowDialog() != DialogResult.OK)
13081 TrackToolStripMenuItem.Checked = false;
13084 inputTrack = inputForm.TabName.Trim();
13086 if (!inputTrack.Equals(tw.TrackWord))
13088 tw.TrackWord = inputTrack;
13089 this.ModifySettingCommon = true;
13090 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13091 tw.ReconnectUserStream();
13097 tw.ReconnectUserStream();
13099 this.ModifySettingCommon = true;
13102 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13104 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13105 this.ModifySettingCommon = true;
13106 tw.ReconnectUserStream();
13109 private void EventViewerMenuItem_Click(object sender, EventArgs e)
13111 if (evtDialog == null || evtDialog.IsDisposed)
13114 evtDialog = new EventViewerDialog();
13115 evtDialog.Owner = this;
13117 Point pos = evtDialog.Location;
13118 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13119 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13120 evtDialog.Location = pos;
13122 evtDialog.EventSource = tw.StoredEvent;
13123 if (!evtDialog.Visible)
13125 evtDialog.Show(this);
13129 evtDialog.Activate();
13131 this.TopMost = this._cfgCommon.AlwaysTop;
13135 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13137 MyCommon._endingFlag = true;
13141 Application.Restart();
13145 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13149 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13151 if (!string.IsNullOrEmpty(tw.Username))
13152 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13155 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13157 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
13160 private async Task doTranslation(string str)
13162 if (string.IsNullOrEmpty(str))
13165 var bing = new Bing();
13168 var translatedText = await bing.TranslateAsync(str,
13170 langTo: this._cfgCommon.TranslateLanguage);
13172 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
13174 catch (HttpRequestException e)
13176 this.StatusLabel.Text = "Err:" + e.Message;
13178 catch (OperationCanceledException)
13180 this.StatusLabel.Text = "Err:Timeout";
13184 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13186 if (!this.ExistCurrentPost)
13189 await this.doTranslation(this._curPost.TextFromApi);
13192 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13194 var text = this.PostBrowser.GetSelectedText();
13195 await this.doTranslation(text);
13198 private bool ExistCurrentPost
13202 if (_curPost == null) return false;
13203 if (_curPost.IsDeleted) return false;
13208 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13210 ShowUserTimeline();
13213 private string GetUserIdFromCurPostOrInput(string caption)
13215 var id = _curPost?.ScreenName ?? "";
13217 using (InputTabName inputName = new InputTabName())
13219 inputName.FormTitle = caption;
13220 inputName.FormDescription = Properties.Resources.FRMessage1;
13221 inputName.TabName = id;
13222 if (inputName.ShowDialog() == DialogResult.OK &&
13223 !string.IsNullOrEmpty(inputName.TabName.Trim()))
13225 id = inputName.TabName.Trim();
13235 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13237 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13238 if (!string.IsNullOrEmpty(id))
13240 AddNewTabForUserTimeline(id);
13244 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13246 string id = GetUserIdFromCurPostOrInput("Show Favstar");
13247 if (!string.IsNullOrEmpty(id))
13249 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13253 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13255 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13258 private void TimelineRefreshEnableChange(bool isEnable)
13262 tw.StartUserStream();
13266 tw.StopUserStream();
13268 TimerTimeline.Enabled = isEnable;
13271 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13273 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13276 private async Task OpenUserAppointUrl()
13278 if (this._cfgCommon.UserAppointUrl != null)
13280 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
13282 if (_curPost != null)
13284 string xUrl = this._cfgCommon.UserAppointUrl;
13285 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13287 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
13288 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
13290 await this.OpenUriInBrowserAsync(xUrl);
13295 await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
13300 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13302 await this.OpenUserAppointUrl();
13305 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13307 string selText = SourceLinkLabel.Text;
13310 Clipboard.SetDataObject(selText, false, 5, 100);
13312 catch (Exception ex)
13314 MessageBox.Show(ex.Message);
13318 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13320 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
13323 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
13325 catch (Exception ex)
13327 MessageBox.Show(ex.Message);
13331 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13333 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13335 SourceCopyMenuItem.Enabled = false;
13336 SourceUrlCopyMenuItem.Enabled = false;
13340 SourceCopyMenuItem.Enabled = true;
13341 SourceUrlCopyMenuItem.Enabled = true;
13345 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13347 if (Form.ActiveForm == null)
13349 this.BeginInvoke((Action) (() =>
13351 this.Visible = true;
13352 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13354 this.BringToFront();
13355 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13357 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13361 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13367 private void ReplaceAppName()
13369 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13370 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13373 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13375 this.SplitContainer3.Panel2Collapsed = false;
13378 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13380 await this.OpenThumbnailPicture(e.Thumbnail);
13383 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13385 await this.OpenUriInBrowserAsync(e.ImageUrl);
13388 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
13390 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
13392 await this.OpenUriInBrowserAsync(url);
13395 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13397 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
13400 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13402 if (e.KeyCode == Keys.Space)
13404 this.JumpUnreadMenuItem_Click(null, null);
13406 e.SuppressKeyPress = true;
13410 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13412 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13413 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13414 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13415 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13416 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13418 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13421 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13423 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13426 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13428 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13431 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13433 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13436 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13438 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13441 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13443 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13446 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13448 if (this._cfgCommon.IconSize == iconSize) return;
13450 var oldIconCol = _iconCol;
13452 this._cfgCommon.IconSize = iconSize;
13453 ApplyListViewIconSize(iconSize);
13455 if (_iconCol != oldIconCol)
13457 foreach (TabPage tp in ListTab.TabPages)
13459 ResetColumns((DetailsListView)tp.Tag);
13463 _curList?.Refresh();
13465 ModifySettingCommon = true;
13468 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13470 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13471 if (this._cfgCommon.SortOrderLock == state) return;
13473 this._cfgCommon.SortOrderLock = state;
13475 ModifySettingCommon = true;