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 Twitter tw = new Twitter();
119 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 HttpTwitter.TwitterUrl = this._cfgCommon.TwitterUrl;
782 if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
783 tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
784 this.twitterApi.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserId, this._cfgCommon.UserName);
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 HttpTwitter.TwitterUrl = this._cfgCommon.TwitterUrl;
816 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
817 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
818 tw.TrackWord = this._cfgCommon.TrackWord;
819 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
820 tw.AllAtReply = this._cfgCommon.AllAtReply;
821 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
822 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
823 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
824 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
826 // アクセストークンが有効であるか確認する
827 // ここが Twitter API への最初のアクセスになるようにすること
830 this.tw.VerifyCredentials();
832 catch (WebApiException ex)
834 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
835 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
839 //プロキシ設定等の通信まわりの初期化が済んでから処理する
840 ThumbnailGenerator.InitializeGenerator();
842 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
843 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
844 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
846 Thumbnail.Services.TonTwitterCom.InitializeOAuthToken = x =>
847 x.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
848 this.tw.AccessToken, this.tw.AccessTokenSecret, "", "");
851 ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
854 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
855 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
856 HashMgr = new HashtagManage(HashSupl,
857 _cfgCommon.HashTags.ToArray(),
858 _cfgCommon.HashSelected,
859 _cfgCommon.HashIsPermanent,
860 _cfgCommon.HashIsHead,
861 _cfgCommon.HashIsNotAddToAtReply);
862 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
865 this.IconCache = new ImageCache();
868 _fntUnread = this._cfgLocal.FontUnread;
869 _clUnread = this._cfgLocal.ColorUnread;
870 _fntReaded = this._cfgLocal.FontRead;
871 _clReaded = this._cfgLocal.ColorRead;
872 _clFav = this._cfgLocal.ColorFav;
873 _clOWL = this._cfgLocal.ColorOWL;
874 _clRetweet = this._cfgLocal.ColorRetweet;
875 _fntDetail = this._cfgLocal.FontDetail;
876 _clDetail = this._cfgLocal.ColorDetail;
877 _clDetailLink = this._cfgLocal.ColorDetailLink;
878 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
879 _clSelf = this._cfgLocal.ColorSelf;
880 _clAtSelf = this._cfgLocal.ColorAtSelf;
881 _clTarget = this._cfgLocal.ColorTarget;
882 _clAtTarget = this._cfgLocal.ColorAtTarget;
883 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
884 _clAtTo = this._cfgLocal.ColorAtTo;
885 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
886 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
887 _clInputFont = this._cfgLocal.ColorInputFont;
888 _fntInputFont = this._cfgLocal.FontInputFont;
890 _brsBackColorMine = new SolidBrush(_clSelf);
891 _brsBackColorAt = new SolidBrush(_clAtSelf);
892 _brsBackColorYou = new SolidBrush(_clTarget);
893 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
894 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
895 _brsBackColorAtTo = new SolidBrush(_clAtTo);
896 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
897 _brsBackColorNone = new SolidBrush(_clListBackcolor);
899 // StringFormatオブジェクトへの事前設定
900 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
901 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
902 //sf.FormatFlags = StringFormatFlags.LineLimit; //
903 sfTab.Alignment = StringAlignment.Center;
904 sfTab.LineAlignment = StringAlignment.Center;
906 InitDetailHtmlFormat();
908 //Regex statregex = new Regex("^0*");
909 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
911 _history.Add(new PostingStatus());
913 this.inReplyTo = null;
916 SearchDialog.Owner = this;
917 UrlDialog.Owner = this;
920 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
921 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
923 //新着取得時のリストスクロールをするか。trueならスクロールしない
924 ListLockMenuItem.Checked = _cfgCommon.ListLock;
925 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
927 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
928 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
930 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
931 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
934 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
935 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
936 _myLoc = _cfgLocal.FormLocation;
938 if (this.WindowState != FormWindowState.Minimized)
940 this.DesktopLocation = _cfgLocal.FormLocation;
941 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
942 bool outOfScreen = true;
943 if (Screen.AllScreens.Length == 1) //ハングするとの報告
945 foreach (Screen scr in Screen.AllScreens)
947 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
955 this.DesktopLocation = new Point(0, 0);
956 _myLoc = this.DesktopLocation;
960 this.TopMost = this._cfgCommon.AlwaysTop;
961 _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
962 _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
963 if (_cfgLocal.PreviewDistance == -1)
965 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
966 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
967 _cfgLocal.PreviewDistance = _mySpDis3;
971 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
973 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
974 //this.Tween_ClientSizeChanged(this, null);
975 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
976 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
978 StatusText.Font = _fntInputFont;
979 StatusText.ForeColor = _clInputFont;
981 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
982 this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
983 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
985 // NameLabel のフォントを OTBaseForm.GlobalFont に変更
986 this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
988 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
989 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
991 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
992 if (this._cfgCommon.UnreadManage == false)
994 ReadedStripMenuItem.Enabled = false;
995 UnreadStripMenuItem.Enabled = false;
1000 DateTimeLabel.Text = "";
1001 SourceLinkLabel.Text = "";
1003 //リンク先URL表示部の初期化(画面左下)
1004 StatusLabelUrl.Text = "";
1006 StatusLabel.Text = "";
1007 StatusLabel.AutoToolTip = false;
1008 StatusLabel.ToolTipText = "";
1010 lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
1012 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1013 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1014 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1015 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1017 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1018 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1019 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1020 this.SplitContainer2.Panel2.AccessibleName = "";
1022 ////////////////////////////////////////////////////////////////////////////////
1023 var sortOrder = (SortOrder)_cfgCommon.SortOrder;
1024 var mode = ComparerMode.Id;
1025 switch (_cfgCommon.SortColumn)
1027 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1031 mode = ComparerMode.Id; //Idソートに読み替え
1034 mode = ComparerMode.Nickname;
1037 mode = ComparerMode.Data;
1040 mode = ComparerMode.Id;
1043 mode = ComparerMode.Name;
1046 mode = ComparerMode.Source;
1049 _statuses.SetSortMode(mode, sortOrder);
1050 ////////////////////////////////////////////////////////////////////////////////
1052 ApplyListViewIconSize(this._cfgCommon.IconSize);
1054 //<<<<<<<<タブ関連>>>>>>>
1058 //デフォルトタブの存在チェック、ない場合には追加
1059 if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1062 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1064 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1068 tab.TabType = MyCommon.TabUsageType.Home;
1071 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1074 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1076 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1080 tab.TabType = MyCommon.TabUsageType.Mentions;
1083 if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1086 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1088 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1092 tab.TabType = MyCommon.TabUsageType.DirectMessage;
1095 if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1098 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1100 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1104 tab.TabType = MyCommon.TabUsageType.Favorites;
1107 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mute) == null)
1110 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.MUTE, out tab))
1112 _statuses.AddTab(MyCommon.DEFAULTTAB.MUTE, MyCommon.TabUsageType.Mute, null);
1116 tab.TabType = MyCommon.TabUsageType.Mute;
1120 foreach (var tab in _statuses.Tabs.Values)
1123 if (tab.TabType == MyCommon.TabUsageType.Mute)
1126 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1128 tab.TabType = MyCommon.TabUsageType.UserDefined;
1130 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo))
1131 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1134 _curTab = ListTab.SelectedTab;
1136 _curList = (DetailsListView)_curTab.Tag;
1138 if (this._cfgCommon.TabIconDisp)
1140 ListTab.DrawMode = TabDrawMode.Normal;
1144 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1145 ListTab.DrawItem += ListTab_DrawItem;
1146 ListTab.ImageList = null;
1149 if (this._cfgCommon.HotkeyEnabled)
1152 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1153 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1154 modKey |= HookGlobalHotkey.ModKeys.Alt;
1155 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1156 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1157 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1158 modKey |= HookGlobalHotkey.ModKeys.Shift;
1159 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1160 modKey |= HookGlobalHotkey.ModKeys.Win;
1162 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1165 if (this._cfgCommon.IsUseNotifyGrowl)
1168 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1170 SetMainWindowTitle();
1171 SetNotifyIconText();
1173 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1175 this.Visible = true;
1179 TimerTimeline.AutoReset = true;
1180 TimerTimeline.SynchronizingObject = this;
1182 TimerTimeline.Interval = 1000;
1183 TimerTimeline.Enabled = true;
1185 TimerRefreshIcon.Interval = 200;
1186 TimerRefreshIcon.Enabled = true;
1188 _ignoreConfigSave = false;
1189 this.TweenMain_Resize(null, null);
1190 if (saveRequired) SaveConfigsAll(false);
1192 foreach (var ua in this._cfgCommon.UserAccounts)
1194 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1196 ua.UserId = tw.UserId;
1203 // 初回起動時だけ右下のメニューを目立たせる
1204 HashStripSplitButton.ShowDropDown();
1208 private void InitDetailHtmlFormat()
1210 if (this._cfgCommon.IsMonospace)
1212 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1213 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1217 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1218 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1221 detailHtmlFormatHeader = detailHtmlFormatHeader
1222 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1223 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1224 .Replace("%FONT_COLOR%", _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString())
1225 .Replace("%LINK_COLOR%", _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString())
1226 .Replace("%BG_COLOR%", _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString())
1227 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1230 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1235 txt = ListTab.TabPages[e.Index].Text;
1242 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1243 if (e.State == DrawItemState.Selected)
1245 e.DrawFocusRectangle();
1250 if (_statuses.Tabs[txt].UnreadCount > 0)
1253 fore = System.Drawing.SystemBrushes.ControlText;
1257 fore = System.Drawing.SystemBrushes.ControlText;
1259 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1262 private void LoadConfig()
1264 _cfgCommon = SettingCommon.Load();
1265 SettingCommon.Instance = this._cfgCommon;
1266 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1268 _cfgCommon.UserAccounts = new List<UserAccount>();
1269 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1271 UserAccount account = new UserAccount();
1272 account.Username = _cfgCommon.UserName;
1273 account.UserId = _cfgCommon.UserId;
1274 account.Token = _cfgCommon.Token;
1275 account.TokenSecret = _cfgCommon.TokenSecret;
1277 _cfgCommon.UserAccounts.Add(account);
1281 _cfgLocal = SettingLocal.Load();
1283 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1284 if (_cfgLocal.ScaleDimension.IsEmpty)
1285 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1287 List<TabClass> tabs = SettingTabs.Load().Tabs;
1288 foreach (TabClass tb in tabs)
1292 tb.FilterModified = false;
1293 _statuses.Tabs.Add(tb.TabName, tb);
1297 tb.TabName = _statuses.MakeTabName("MyTab");
1298 _statuses.Tabs.Add(tb.TabName, tb);
1301 if (_statuses.Tabs.Count == 0)
1303 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1304 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1305 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1306 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1310 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1312 if (!TimerTimeline.Enabled) return;
1316 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1318 private static int homeCounter = 0;
1319 private static int mentionCounter = 0;
1320 private static int dmCounter = 0;
1321 private static int pubSearchCounter = 0;
1322 private static int userTimelineCounter = 0;
1323 private static int listsCounter = 0;
1324 private static int usCounter = 0;
1325 private static int ResumeWait = 0;
1326 private static int refreshFollowers = 0;
1328 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1330 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1331 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1332 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1333 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1334 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1335 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1336 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1337 Interlocked.Increment(ref refreshFollowers);
1339 var refreshTasks = new List<Task>();
1342 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1344 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1345 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1346 refreshTasks.Add(this.GetHomeTimelineAsync());
1347 ResetTimers.Timeline = false;
1349 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1351 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1352 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1353 refreshTasks.Add(this.GetReplyAsync());
1354 ResetTimers.Reply = false;
1356 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1358 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1359 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1360 refreshTasks.Add(this.GetDirectMessagesAsync());
1361 ResetTimers.DirectMessage = false;
1363 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1365 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1366 if (!ResetTimers.PublicSearch)
1367 refreshTasks.Add(this.GetPublicSearchAllAsync());
1368 ResetTimers.PublicSearch = false;
1370 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1372 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1373 if (!ResetTimers.UserTimeline)
1374 refreshTasks.Add(this.GetUserTimelineAllAsync());
1375 ResetTimers.UserTimeline = false;
1377 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1379 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1380 if (!ResetTimers.Lists)
1381 refreshTasks.Add(this.GetListTimelineAllAsync());
1382 ResetTimers.Lists = false;
1384 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1386 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1387 if (this._isActiveUserstream)
1388 this.RefreshTimeline();
1389 ResetTimers.UserStream = false;
1391 if (refreshFollowers > 6 * 3600)
1393 Interlocked.Exchange(ref refreshFollowers, 0);
1394 refreshTasks.AddRange(new[]
1396 this.doGetFollowersMenu(),
1397 this.RefreshNoRetweetIdsAsync(),
1398 this.RefreshTwitterConfigurationAsync(),
1403 Interlocked.Increment(ref ResumeWait);
1404 if (ResumeWait > 30)
1407 Interlocked.Exchange(ref ResumeWait, 0);
1408 refreshTasks.AddRange(new[]
1410 this.GetHomeTimelineAsync(),
1411 this.GetReplyAsync(),
1412 this.GetDirectMessagesAsync(),
1413 this.GetPublicSearchAllAsync(),
1414 this.GetUserTimelineAllAsync(),
1415 this.GetListTimelineAllAsync(),
1416 this.doGetFollowersMenu(),
1417 this.RefreshTwitterConfigurationAsync(),
1422 await Task.WhenAll(refreshTasks);
1425 private void RefreshTimeline()
1427 // 現在表示中のタブのスクロール位置を退避
1428 var curListScroll = this.SaveListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text]);
1430 // 各タブのリスト上の選択位置などを退避
1431 var listSelections = this.SaveListViewSelection();
1434 PostClass[] notifyPosts;
1437 bool newMentionOrDm;
1439 addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1441 if (MyCommon._endingFlag) return;
1446 foreach (TabPage tab in ListTab.TabPages)
1448 DetailsListView lst = (DetailsListView)tab.Tag;
1449 TabClass tabInfo = _statuses.Tabs[tab.Text];
1450 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1452 using (ControlTransaction.Update(lst))
1454 if (lst.Equals(_curList))
1456 this.PurgeListViewItemCache();
1460 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1468 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
1471 if (tabInfo.UnreadCount > 0)
1472 if (this._cfgCommon.TabIconDisp)
1473 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1475 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1479 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1484 this.RestoreListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text], curListScroll);
1487 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1489 SetMainWindowTitle();
1490 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1492 HashSupl.AddRangeItem(tw.GetHashList());
1496 internal struct ListViewScroll
1498 public ScrollLockMode ScrollLockMode { get; set; }
1499 public long? TopItemStatusId { get; set; }
1502 internal enum ScrollLockMode
1504 /// <summary>固定しない</summary>
1507 /// <summary>最上部に固定する</summary>
1510 /// <summary>最下部に固定する</summary>
1513 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1518 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1520 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabClass tab)
1522 var listScroll = new ListViewScroll
1524 ScrollLockMode = this.GetScrollLockMode(listView),
1527 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1529 var topItem = listView.TopItem;
1530 if (topItem != null)
1531 listScroll.TopItemStatusId = tab.GetId(topItem.Index);
1537 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1539 if (this._statuses.SortMode == ComparerMode.Id)
1541 if (this._statuses.SortOrder == SortOrder.Ascending)
1544 if (this.ListLockMenuItem.Checked)
1545 return ScrollLockMode.None;
1547 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1550 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1551 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1552 return ScrollLockMode.FixedToBottom;
1554 return ScrollLockMode.None;
1559 if (this.ListLockMenuItem.Checked)
1560 return ScrollLockMode.FixedToItem;
1562 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1563 var topItem = listView.TopItem;
1564 if (topItem == null || topItem.Index == 0)
1565 return ScrollLockMode.FixedToTop;
1567 return ScrollLockMode.FixedToItem;
1572 return ScrollLockMode.FixedToItem;
1576 internal struct ListViewSelection
1578 public long[] SelectedStatusIds { get; set; }
1579 public long? SelectionMarkStatusId { get; set; }
1580 public long? FocusedStatusId { get; set; }
1584 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1586 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1588 var listsDict = new Dictionary<string, ListViewSelection>();
1590 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1592 var listView = (DetailsListView)tabPage.Tag;
1593 var tab = _statuses.Tabs[tabPage.Text];
1595 ListViewSelection listStatus;
1596 if (listView.VirtualListSize != 0)
1598 listStatus = new ListViewSelection
1600 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1601 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1602 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1607 listStatus = new ListViewSelection
1609 SelectedStatusIds = new long[0],
1610 SelectionMarkStatusId = null,
1611 FocusedStatusId = null,
1615 listsDict[tab.TabName] = listStatus;
1621 private long[] GetSelectedStatusIds(DetailsListView listView, TabClass tab)
1623 var selectedIndices = listView.SelectedIndices;
1624 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1625 return tab.GetId(selectedIndices);
1630 private long? GetFocusedStatusId(DetailsListView listView, TabClass tab)
1632 var focusedItem = listView.FocusedItem;
1634 return focusedItem != null ? tab.GetId(focusedItem.Index) : (long?)null;
1637 private long? GetSelectionMarkStatusId(DetailsListView listView, TabClass tab)
1639 var selectionMarkIndex = listView.SelectionMark;
1641 return selectionMarkIndex != -1 ? tab.GetId(selectionMarkIndex) : (long?)null;
1645 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1647 private void RestoreListViewScroll(DetailsListView listView, TabClass tab, ListViewScroll listScroll)
1649 if (listView.VirtualListSize == 0)
1652 switch (listScroll.ScrollLockMode)
1654 case ScrollLockMode.FixedToTop:
1655 listView.EnsureVisible(0);
1657 case ScrollLockMode.FixedToBottom:
1658 listView.EnsureVisible(listView.VirtualListSize - 1);
1660 case ScrollLockMode.FixedToItem:
1661 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1663 listView.TopItem = listView.Items[topIndex];
1665 case ScrollLockMode.None:
1672 /// <see cref="SaveListViewStatus"/> によって保存された選択状態を復元します
1674 private void RestoreListViewSelection(DetailsListView listView, TabClass tab, ListViewSelection listSelection)
1676 // status_id から ListView 上のインデックスに変換
1677 int[] selectedIndices = null;
1678 if (listSelection.SelectedStatusIds != null)
1679 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1681 var focusedIndex = -1;
1682 if (listSelection.FocusedStatusId != null)
1683 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1685 var selectionMarkIndex = -1;
1686 if (listSelection.SelectionMarkStatusId != null)
1687 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1689 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1692 private bool BalloonRequired()
1694 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1695 ev.Eventtype = MyCommon.EVENTTYPE.None;
1697 return BalloonRequired(ev);
1700 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1702 if (type == MyCommon.EVENTTYPE.None)
1705 if (!this._cfgCommon.EventNotifyEnabled)
1708 return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1711 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1716 return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1719 private bool BalloonRequired(Twitter.FormattedEvent ev)
1724 if (NativeMethods.IsScreenSaverRunning())
1728 if (!this.NewPostPopMenuItem.Checked)
1730 // 「新着通知が無効でもイベントを通知する」にも該当しない
1731 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1735 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1736 if (this._cfgCommon.LimitBalloon)
1738 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1742 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1745 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1747 if (this._cfgCommon.ReadOwnPost)
1749 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1754 if (BalloonRequired())
1756 if (notifyPosts != null && notifyPosts.Length > 0)
1758 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1759 if (this._cfgCommon.IsUseNotifyGrowl)
1761 StringBuilder sb = new StringBuilder();
1765 foreach (PostClass post in notifyPosts)
1767 if (!(notifyPosts.Length > 3))
1773 if (post.IsReply && !post.IsExcludeReply) reply = true;
1774 if (post.IsDm) dm = true;
1775 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1776 switch (this._cfgCommon.NameBalloon)
1778 case MyCommon.NameBalloonEnum.UserID:
1779 sb.Append(post.ScreenName).Append(" : ");
1781 case MyCommon.NameBalloonEnum.NickName:
1782 sb.Append(post.Nickname).Append(" : ");
1785 sb.Append(post.TextFromApi);
1786 if (notifyPosts.Length > 3)
1788 if (notifyPosts.Last() != post) continue;
1791 StringBuilder title = new StringBuilder();
1792 GrowlHelper.NotifyType nt;
1793 if (this._cfgCommon.DispUsername)
1795 title.Append(tw.Username);
1796 title.Append(" - ");
1804 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1805 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1806 title.Append(Application.ProductName);
1807 title.Append(" [DM] ");
1808 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1809 nt = GrowlHelper.NotifyType.DirectMessage;
1813 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1814 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1815 title.Append(Application.ProductName);
1816 title.Append(" [Reply!] ");
1817 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1818 nt = GrowlHelper.NotifyType.Reply;
1822 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1823 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1824 title.Append(Application.ProductName);
1826 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1827 nt = GrowlHelper.NotifyType.Notify;
1829 string bText = sb.ToString();
1830 if (string.IsNullOrEmpty(bText)) return;
1832 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1833 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1838 StringBuilder sb = new StringBuilder();
1841 foreach (PostClass post in notifyPosts)
1843 if (post.IsReply && !post.IsExcludeReply) reply = true;
1844 if (post.IsDm) dm = true;
1845 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1846 switch (this._cfgCommon.NameBalloon)
1848 case MyCommon.NameBalloonEnum.UserID:
1849 sb.Append(post.ScreenName).Append(" : ");
1851 case MyCommon.NameBalloonEnum.NickName:
1852 sb.Append(post.Nickname).Append(" : ");
1855 sb.Append(post.TextFromApi);
1858 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1859 StringBuilder title = new StringBuilder();
1861 if (this._cfgCommon.DispUsername)
1863 title.Append(tw.Username);
1864 title.Append(" - ");
1872 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1873 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1874 ntIcon = ToolTipIcon.Warning;
1875 title.Append(Application.ProductName);
1876 title.Append(" [DM] ");
1877 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1881 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1882 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1883 ntIcon = ToolTipIcon.Warning;
1884 title.Append(Application.ProductName);
1885 title.Append(" [Reply!] ");
1886 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1890 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1891 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1892 ntIcon = ToolTipIcon.Info;
1893 title.Append(Application.ProductName);
1895 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1897 string bText = sb.ToString();
1898 if (string.IsNullOrEmpty(bText)) return;
1899 //NotifyIcon1.BalloonTipText = sb.ToString();
1900 //NotifyIcon1.ShowBalloonTip(500);
1901 NotifyIcon1.BalloonTipTitle = title.ToString();
1902 NotifyIcon1.BalloonTipText = bText;
1903 NotifyIcon1.BalloonTipIcon = ntIcon;
1904 NotifyIcon1.ShowBalloonTip(500);
1910 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1914 string dir = Application.StartupPath;
1915 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1917 dir = Path.Combine(dir, "Sounds");
1919 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1929 //mentions新着時に画面ブリンク
1930 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1932 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1936 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1938 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1940 _curItemIndex = _curList.SelectedIndices[0];
1941 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1945 this._curPost = GetCurTabPost(_curItemIndex);
1947 catch (ArgumentException)
1952 this.PushSelectPostChain();
1954 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1956 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1962 private void ChangeCacheStyleRead(bool Read, int Index)
1964 var tabInfo = _statuses.Tabs[_curTab.Text];
1965 //Read:true=既読 false=未読
1966 //未読管理していなかったら既読として扱う
1967 if (!tabInfo.UnreadManage ||
1968 !this._cfgCommon.UnreadManage) Read = true;
1970 var listCache = this._listItemCache;
1971 if (listCache == null)
1974 // キャッシュに含まれていないアイテムは対象外
1977 if (!listCache.TryGetValue(Index, out itm, out post))
1980 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1983 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1990 Item.SubItems[5].Text = "";
1995 Item.SubItems[5].Text = "★";
2001 else if (Post.RetweetedId != null)
2003 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
2005 else if (Read || !this._cfgCommon.UseUnreadStyle)
2010 if (DList == null || Item.Index == -1)
2012 Item.ForeColor = cl;
2013 if (this._cfgCommon.UseUnreadStyle)
2019 if (this._cfgCommon.UseUnreadStyle)
2020 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2022 DList.ChangeItemForeColor(Item.Index, cl);
2023 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2027 private void ColorizeList()
2029 //Index:更新対象のListviewItem.Index。Colorを返す。
2030 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2033 _post = _anchorPost;
2037 if (_post == null) return;
2039 var listCache = this._listItemCache;
2040 if (listCache == null)
2043 var index = listCache.StartIndex;
2044 foreach (var cachedPost in listCache.Post)
2046 var backColor = this.JudgeColor(_post, cachedPost);
2047 this._curList.ChangeItemBackColor(index++, backColor);
2051 private void ColorizeList(ListViewItem Item, int Index)
2053 //Index:更新対象のListviewItem.Index。Colorを返す。
2054 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2057 _post = _anchorPost;
2061 PostClass tPost = GetCurTabPost(Index);
2063 if (_post == null) return;
2065 if (Item.Index == -1)
2066 Item.BackColor = JudgeColor(_post, tPost);
2068 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2071 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2074 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2077 else if (TargetPost.IsMe)
2080 else if (TargetPost.IsReply)
2083 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2085 cl = _clAtFromTarget;
2086 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2089 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2094 cl = _clListBackcolor;
2099 private async void PostButton_Click(object sender, EventArgs e)
2101 if (StatusText.Text.Trim().Length == 0)
2103 if (!ImageSelector.Enabled)
2105 await this.DoRefresh();
2110 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2112 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2114 MessageBoxButtons.YesNoCancel,
2115 MessageBoxIcon.Question);
2118 case DialogResult.Yes:
2119 StatusText.Text = "";
2120 await this.doReTweetOfficial(false);
2122 case DialogResult.Cancel:
2127 var inReplyToStatusId = this.inReplyTo?.Item1;
2128 var inReplyToScreenName = this.inReplyTo?.Item2;
2129 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2131 if (this._cfgCommon.Nicoms)
2133 StatusText.SelectionStart = StatusText.Text.Length;
2134 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2136 //if (SettingDialog.UrlConvertAuto)
2138 // StatusText.SelectionStart = StatusText.Text.Length;
2139 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2141 //else if (SettingDialog.Nicoms)
2143 // StatusText.SelectionStart = StatusText.Text.Length;
2144 // UrlConvert(UrlConverter.Nicoms);
2146 StatusText.SelectionStart = StatusText.Text.Length;
2147 CheckReplyTo(StatusText.Text);
2149 var statusText = this.FormatStatusText(this.StatusText.Text);
2151 if (this.GetRestStatusCount(statusText) < 0)
2153 // 文字数制限を超えているが強制的に投稿するか
2154 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2155 if (ret != DialogResult.OK)
2159 var status = new PostingStatus();
2160 status.status = statusText;
2162 status.inReplyToId = this.inReplyTo?.Item1;
2163 status.inReplyToName = this.inReplyTo?.Item2;
2164 if (ImageSelector.Visible)
2167 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2171 this.inReplyTo = null;
2172 StatusText.Text = "";
2173 _history.Add(new PostingStatus());
2174 _hisIdx = _history.Count - 1;
2175 if (!ToolStripFocusLockMenuItem.Checked)
2176 ((Control)ListTab.SelectedTab.Tag).Focus();
2177 urlUndoBuffer = null;
2178 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2181 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2183 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2184 await this.OpenUriInBrowserAsync(tmp);
2187 await this.PostMessageAsync(status);
2190 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2192 MyCommon._endingFlag = true;
2196 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2198 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2200 //_endingFlag=false:フォームの×ボタン
2202 this.Visible = false;
2206 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2207 _ignoreConfigSave = true;
2208 MyCommon._endingFlag = true;
2209 TimerTimeline.Enabled = false;
2210 TimerRefreshIcon.Enabled = false;
2214 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2216 this.Visible = true;
2217 if (this.WindowState == FormWindowState.Minimized)
2219 this.WindowState = FormWindowState.Normal;
2222 this.BringToFront();
2225 private static int errorCount = 0;
2227 private static bool CheckAccountValid()
2229 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2235 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2244 private Task GetHomeTimelineAsync()
2246 return this.GetHomeTimelineAsync(loadMore: false);
2249 private async Task GetHomeTimelineAsync(bool loadMore)
2251 await this.workerSemaphore.WaitAsync();
2255 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2257 await this.GetHomeTimelineAsyncInternal(progress, this.workerCts.Token, loadMore);
2259 catch (WebApiException ex)
2261 this._myStatusError = true;
2262 this.StatusLabel.Text = ex.Message;
2266 this.workerSemaphore.Release();
2270 private async Task GetHomeTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2272 if (ct.IsCancellationRequested)
2275 if (!CheckAccountValid())
2276 throw new WebApiException("Auth error. Check your account");
2279 if (!this._cfgCommon.UnreadManage)
2282 read = this._initial && this._cfgCommon.Read;
2284 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5, loadMore ? -1 : 1));
2286 await Task.Run(() =>
2288 this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Timeline, loadMore, this._initial);
2291 if (this._cfgCommon.ReadOldPosts)
2292 this._statuses.SetReadHomeTab();
2294 var addCount = this._statuses.DistributePosts();
2297 this.UpdateTimelineSpeed(addCount);
2300 if (ct.IsCancellationRequested)
2303 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1);
2305 this.RefreshTimeline();
2309 /// タイムラインに追加された発言件数を反映し、タイムラインの流速を更新します
2311 /// <param name="addCount">直前にタイムラインに追加した発言件数</param>
2312 private void UpdateTimelineSpeed(int addCount)
2314 var now = DateTime.Now;
2315 this._tlTimestamps.AddOrUpdate(now, addCount, (k, v) => v + addCount);
2317 var removeKeys = new List<DateTime>();
2318 var oneHour = TimeSpan.FromHours(1);
2320 foreach (var pair in this._tlTimestamps)
2322 if (now - pair.Key > oneHour)
2323 removeKeys.Add(pair.Key);
2325 tlCount += pair.Value;
2327 Interlocked.Exchange(ref this._tlCount, tlCount);
2330 foreach (var key in removeKeys)
2331 this._tlTimestamps.TryRemove(key, out _);
2334 private Task GetReplyAsync()
2336 return this.GetReplyAsync(loadMore: false);
2339 private async Task GetReplyAsync(bool loadMore)
2341 await this.workerSemaphore.WaitAsync();
2345 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2347 await this.GetReplyAsyncInternal(progress, this.workerCts.Token, loadMore);
2349 catch (WebApiException ex)
2351 this._myStatusError = true;
2352 this.StatusLabel.Text = ex.Message;
2356 this.workerSemaphore.Release();
2360 private async Task GetReplyAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2362 if (ct.IsCancellationRequested)
2365 if (!CheckAccountValid())
2366 throw new WebApiException("Auth error. Check your account");
2369 if (!this._cfgCommon.UnreadManage)
2372 read = this._initial && this._cfgCommon.Read;
2374 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4, loadMore ? -1 : 1));
2376 await Task.Run(() =>
2378 this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Reply, loadMore, this._initial);
2380 this._statuses.DistributePosts();
2383 if (ct.IsCancellationRequested)
2386 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9);
2388 this.RefreshTimeline();
2391 private Task GetDirectMessagesAsync()
2393 return this.GetDirectMessagesAsync(loadMore: false);
2396 private async Task GetDirectMessagesAsync(bool loadMore)
2398 await this.workerSemaphore.WaitAsync();
2402 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2404 await this.GetDirectMessagesAsyncInternal(progress, this.workerCts.Token, loadMore);
2406 catch (WebApiException ex)
2408 this._myStatusError = true;
2409 this.StatusLabel.Text = ex.Message;
2413 this.workerSemaphore.Release();
2417 private async Task GetDirectMessagesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2419 if (ct.IsCancellationRequested)
2422 if (!CheckAccountValid())
2423 throw new WebApiException("Auth error. Check your account");
2426 if (!this._cfgCommon.UnreadManage)
2429 read = this._initial && this._cfgCommon.Read;
2431 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8, loadMore ? -1 : 1));
2433 await Task.Run(() =>
2435 this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, loadMore);
2436 this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, loadMore);
2438 this._statuses.DistributePosts();
2441 if (ct.IsCancellationRequested)
2444 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11);
2446 this.RefreshTimeline();
2449 private Task GetFavoritesAsync()
2451 return this.GetFavoritesAsync(loadMore: false);
2454 private async Task GetFavoritesAsync(bool loadMore)
2456 await this.workerSemaphore.WaitAsync();
2460 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2462 await this.GetFavoritesAsyncInternal(progress, this.workerCts.Token, loadMore);
2464 catch (WebApiException ex)
2466 this._myStatusError = true;
2467 this.StatusLabel.Text = ex.Message;
2471 this.workerSemaphore.Release();
2475 private async Task GetFavoritesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2477 if (ct.IsCancellationRequested)
2480 if (!CheckAccountValid())
2481 throw new WebApiException("Auth error. Check your account");
2484 if (!this._cfgCommon.UnreadManage)
2487 read = this._initial && this._cfgCommon.Read;
2489 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19);
2491 await Task.Run(() =>
2493 this.tw.GetFavoritesApi(read, loadMore);
2495 this._statuses.DistributePosts();
2498 if (ct.IsCancellationRequested)
2501 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20);
2503 this.RefreshTimeline();
2506 private Task GetPublicSearchAllAsync()
2508 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch);
2510 return this.GetPublicSearchAsync(tabs, loadMore: false);
2513 private Task GetPublicSearchAsync(TabClass tab)
2515 return this.GetPublicSearchAsync(tab, loadMore: false);
2518 private Task GetPublicSearchAsync(TabClass tab, bool loadMore)
2520 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2523 private async Task GetPublicSearchAsync(IEnumerable<TabClass> tabs, bool loadMore)
2525 await this.workerSemaphore.WaitAsync();
2529 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2531 await this.GetPublicSearchAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2533 catch (WebApiException ex)
2535 this._myStatusError = true;
2536 this.StatusLabel.Text = ex.Message;
2540 this.workerSemaphore.Release();
2544 private async Task GetPublicSearchAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2546 if (ct.IsCancellationRequested)
2549 if (!CheckAccountValid())
2550 throw new WebApiException("Auth error. Check your account");
2553 if (!this._cfgCommon.UnreadManage)
2556 read = this._initial && this._cfgCommon.Read;
2558 p.Report("Search refreshing...");
2560 await Task.Run(() =>
2562 WebApiException lastException = null;
2564 foreach (var tab in tabs)
2568 if (string.IsNullOrEmpty(tab.SearchWords))
2571 this.tw.GetSearch(read, tab, false);
2574 this.tw.GetSearch(read, tab, true);
2576 catch (WebApiException ex)
2582 this._statuses.DistributePosts();
2584 if (lastException != null)
2585 throw new WebApiException(lastException.Message, lastException);
2588 if (ct.IsCancellationRequested)
2591 p.Report("Search refreshed");
2593 this.RefreshTimeline();
2596 private Task GetUserTimelineAllAsync()
2598 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline);
2600 return this.GetUserTimelineAsync(tabs, loadMore: false);
2603 private Task GetUserTimelineAsync(TabClass tab)
2605 return this.GetUserTimelineAsync(tab, loadMore: false);
2608 private Task GetUserTimelineAsync(TabClass tab, bool loadMore)
2610 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2613 private async Task GetUserTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2615 await this.workerSemaphore.WaitAsync();
2619 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2621 await this.GetUserTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2623 catch (WebApiException ex)
2625 this._myStatusError = true;
2626 this.StatusLabel.Text = ex.Message;
2630 this.workerSemaphore.Release();
2634 private async Task GetUserTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2636 if (ct.IsCancellationRequested)
2639 if (!CheckAccountValid())
2640 throw new WebApiException("Auth error. Check your account");
2643 if (!this._cfgCommon.UnreadManage)
2646 read = this._initial && this._cfgCommon.Read;
2648 p.Report("UserTimeline refreshing...");
2650 await Task.Run(() =>
2652 WebApiException lastException = null;
2654 foreach (var tab in tabs)
2658 if (string.IsNullOrEmpty(tab.User))
2661 this.tw.GetUserTimelineApi(read, tab.User, tab, loadMore);
2663 catch (WebApiException ex)
2669 this._statuses.DistributePosts();
2671 if (lastException != null)
2672 throw new WebApiException(lastException.Message, lastException);
2675 if (ct.IsCancellationRequested)
2678 p.Report("UserTimeline refreshed");
2680 this.RefreshTimeline();
2683 private Task GetListTimelineAllAsync()
2685 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.Lists);
2687 return this.GetListTimelineAsync(tabs, loadMore: false);
2690 private Task GetListTimelineAsync(TabClass tab)
2692 return this.GetListTimelineAsync(tab, loadMore: false);
2695 private Task GetListTimelineAsync(TabClass tab, bool loadMore)
2697 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2700 private async Task GetListTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2702 await this.workerSemaphore.WaitAsync();
2706 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2708 await this.GetListTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2710 catch (WebApiException ex)
2712 this._myStatusError = true;
2713 this.StatusLabel.Text = ex.Message;
2717 this.workerSemaphore.Release();
2721 private async Task GetListTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2723 if (ct.IsCancellationRequested)
2726 if (!CheckAccountValid())
2727 throw new WebApiException("Auth error. Check your account");
2730 if (!this._cfgCommon.UnreadManage)
2733 read = this._initial && this._cfgCommon.Read;
2735 p.Report("List refreshing...");
2737 await Task.Run(() =>
2739 WebApiException lastException = null;
2741 foreach (var tab in tabs)
2745 if (tab.ListInfo == null || tab.ListInfo.Id == 0)
2748 this.tw.GetListStatus(read, tab, loadMore, this._initial);
2750 catch (WebApiException ex)
2756 this._statuses.DistributePosts();
2758 if (lastException != null)
2759 throw new WebApiException(lastException.Message, lastException);
2762 if (ct.IsCancellationRequested)
2765 p.Report("List refreshed");
2767 this.RefreshTimeline();
2770 private async Task GetRelatedTweetsAsync(TabClass tab)
2772 await this.workerSemaphore.WaitAsync();
2776 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2778 await this.GetRelatedTweetsAsyncInternal(progress, this.workerCts.Token, tab);
2780 catch (WebApiException ex)
2782 this._myStatusError = true;
2783 this.StatusLabel.Text = ex.Message;
2787 this.workerSemaphore.Release();
2791 private async Task GetRelatedTweetsAsyncInternal(IProgress<string> p, CancellationToken ct, TabClass tab)
2793 if (ct.IsCancellationRequested)
2796 if (!CheckAccountValid())
2797 throw new WebApiException("Auth error. Check your account");
2800 if (!this._cfgCommon.UnreadManage)
2803 read = this._initial && this._cfgCommon.Read;
2805 p.Report("Related refreshing...");
2807 await Task.Run(() =>
2809 this.tw.GetRelatedResult(read, tab);
2811 this._statuses.DistributePosts();
2814 if (ct.IsCancellationRequested)
2817 p.Report("Related refreshed");
2819 this.RefreshTimeline();
2821 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
2822 .FirstOrDefault(x => x.Text == tab.TabName);
2824 if (tabPage != null)
2826 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
2828 var listView = (DetailsListView)tabPage.Tag;
2829 var index = tab.IndexOf(tab.RelationTargetPost.RetweetedId ?? tab.RelationTargetPost.StatusId);
2831 if (index != -1 && index < listView.Items.Count)
2833 listView.SelectedIndices.Add(index);
2834 listView.Items[index].Focused = true;
2839 private async Task FavAddAsync(long statusId, TabClass tab)
2841 await this.workerSemaphore.WaitAsync();
2845 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2847 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2849 catch (WebApiException ex)
2851 this._myStatusError = true;
2852 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2856 this.workerSemaphore.Release();
2860 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabClass tab)
2862 if (ct.IsCancellationRequested)
2865 if (!CheckAccountValid())
2866 throw new WebApiException("Auth error. Check your account");
2869 if (!tab.Posts.TryGetValue(statusId, out post))
2875 await Task.Run(async () =>
2877 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2881 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2883 .ConfigureAwait(false);
2885 if (this._cfgCommon.RestrictFavCheck)
2887 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2888 .ConfigureAwait(false);
2890 if (status.Favorited != true)
2891 throw new WebApiException("NG(Restricted?)");
2894 this._favTimestamps.Add(DateTime.Now);
2897 if (this._statuses.ContainsKey(statusId))
2899 var postTl = this._statuses[statusId];
2900 postTl.IsFav = true;
2902 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2903 favTab.AddPostQueue(statusId, postTl.IsRead);
2906 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2907 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2909 if (tb.Contains(statusId))
2910 tb.Posts[statusId].IsFav = true;
2913 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2915 catch (WebApiException)
2917 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2922 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2923 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2925 if (this._favTimestamps[i] < oneHour)
2926 this._favTimestamps.RemoveAt(i);
2929 this._statuses.DistributePosts();
2932 if (ct.IsCancellationRequested)
2935 this.RefreshTimeline();
2937 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2939 using (ControlTransaction.Update(this._curList))
2941 var idx = tab.IndexOf(statusId);
2943 this.ChangeCacheStyleRead(post.IsRead, idx);
2946 if (statusId == this._curPost.StatusId)
2947 await this.DispSelectedPost(true); // 選択アイテム再表示
2951 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabClass tab)
2953 await this.workerSemaphore.WaitAsync();
2957 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2959 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2961 catch (WebApiException ex)
2963 this._myStatusError = true;
2964 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2968 this.workerSemaphore.Release();
2972 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2974 if (ct.IsCancellationRequested)
2977 if (!CheckAccountValid())
2978 throw new WebApiException("Auth error. Check your account");
2980 var successIds = new List<long>();
2982 await Task.Run(async () =>
2986 var failedCount = 0;
2987 foreach (var statusId in statusIds)
2991 var post = tab.Posts[statusId];
2993 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
3000 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
3002 .ConfigureAwait(false);
3004 catch (WebApiException)
3010 successIds.Add(statusId);
3011 post.IsFav = false; // リスト再描画必要
3013 if (this._statuses.ContainsKey(statusId))
3015 this._statuses[statusId].IsFav = false;
3018 // 検索,リスト,UserTimeline,Relatedの各タブに反映
3019 foreach (var tb in this._statuses.GetTabsInnerStorageType())
3021 if (tb.Contains(statusId))
3022 tb.Posts[statusId].IsFav = false;
3027 if (ct.IsCancellationRequested)
3030 this.RemovePostFromFavTab(successIds.ToArray());
3032 this.RefreshTimeline();
3034 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
3036 if (tab.TabType == MyCommon.TabUsageType.Favorites)
3042 using (ControlTransaction.Update(this._curList))
3044 foreach (var statusId in successIds)
3046 var idx = tab.IndexOf(statusId);
3050 var post = tab.Posts[statusId];
3051 this.ChangeCacheStyleRead(post.IsRead, idx);
3055 if (successIds.Contains(this._curPost.StatusId))
3056 await this.DispSelectedPost(true); // 選択アイテム再表示
3061 private async Task PostMessageAsync(PostingStatus status)
3063 await this.workerSemaphore.WaitAsync();
3067 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3069 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
3071 catch (WebApiException ex)
3073 this._myStatusError = true;
3074 this.StatusLabel.Text = ex.Message;
3078 this.workerSemaphore.Release();
3082 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
3084 if (ct.IsCancellationRequested)
3087 if (!CheckAccountValid())
3088 throw new WebApiException("Auth error. Check your account");
3090 p.Report("Posting...");
3096 await Task.Run(async () =>
3098 if (status.mediaItems == null || status.mediaItems.Length == 0)
3100 this.tw.PostStatus(status.status, status.inReplyToId);
3104 var service = ImageSelector.GetService(status.imageService);
3105 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
3106 .ConfigureAwait(false);
3110 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3112 catch (WebApiException ex)
3114 // 処理は中断せずエラーの表示のみ行う
3115 errMsg = ex.Message;
3117 this._myStatusError = true;
3121 // 使い終わった MediaItem は破棄する
3122 if (status.mediaItems != null)
3124 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
3126 disposableItem.Dispose();
3131 if (ct.IsCancellationRequested)
3134 if (!string.IsNullOrEmpty(errMsg) &&
3135 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
3136 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
3138 var ret = MessageBox.Show(
3140 "{0} ---> [ " + errMsg + " ]" + Environment.NewLine +
3141 "\"" + status.status + "\"" + Environment.NewLine +
3143 Properties.Resources.StatusUpdateFailed1,
3144 Properties.Resources.StatusUpdateFailed2),
3145 "Failed to update status",
3146 MessageBoxButtons.RetryCancel,
3147 MessageBoxIcon.Question);
3149 if (ret == DialogResult.Retry)
3151 await this.PostMessageAsync(status);
3155 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3156 if (this.ToolStripFocusLockMenuItem.Checked)
3157 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
3162 this._postTimestamps.Add(DateTime.Now);
3164 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3165 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3167 if (this._postTimestamps[i] < oneHour)
3168 this._postTimestamps.RemoveAt(i);
3171 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
3173 this.HashMgr.ClearHashtag();
3174 this.HashStripSplitButton.Text = "#[-]";
3175 this.HashToggleMenuItem.Checked = false;
3176 this.HashToggleToolStripMenuItem.Checked = false;
3179 this.SetMainWindowTitle();
3181 if (this._cfgCommon.PostAndGet)
3183 if (this._isActiveUserstream)
3184 this.RefreshTimeline();
3186 await this.GetHomeTimelineAsync();
3190 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
3192 await this.workerSemaphore.WaitAsync();
3196 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3198 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
3200 catch (WebApiException ex)
3202 this._myStatusError = true;
3203 this.StatusLabel.Text = ex.Message;
3207 this.workerSemaphore.Release();
3211 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
3213 if (ct.IsCancellationRequested)
3216 if (!CheckAccountValid())
3217 throw new WebApiException("Auth error. Check your account");
3220 if (!this._cfgCommon.UnreadManage)
3223 read = this._initial && this._cfgCommon.Read;
3225 p.Report("Posting...");
3227 await Task.Run(() =>
3229 foreach (var statusId in statusIds)
3231 this.tw.PostRetweet(statusId, read);
3235 if (ct.IsCancellationRequested)
3238 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3240 this._postTimestamps.Add(DateTime.Now);
3242 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3243 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3245 if (this._postTimestamps[i] < oneHour)
3246 this._postTimestamps.RemoveAt(i);
3249 if (this._cfgCommon.PostAndGet && !this._isActiveUserstream)
3250 await this.GetHomeTimelineAsync();
3253 private async Task RefreshFollowerIdsAsync()
3255 await this.workerSemaphore.WaitAsync();
3258 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
3260 await Task.Run(() => tw.RefreshFollowerIds());
3262 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
3264 this.RefreshTimeline();
3265 this.PurgeListViewItemCache();
3266 this._curList?.Refresh();
3268 catch (WebApiException ex)
3270 this.StatusLabel.Text = ex.Message;
3274 this.workerSemaphore.Release();
3278 private async Task RefreshNoRetweetIdsAsync()
3280 await this.workerSemaphore.WaitAsync();
3283 await Task.Run(() => tw.RefreshNoRetweetIds());
3285 this.StatusLabel.Text = "NoRetweetIds refreshed";
3287 catch (WebApiException ex)
3289 this.StatusLabel.Text = ex.Message;
3293 this.workerSemaphore.Release();
3297 private async Task RefreshBlockIdsAsync()
3299 await this.workerSemaphore.WaitAsync();
3302 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
3304 await Task.Run(() => tw.RefreshBlockIds());
3306 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
3308 catch (WebApiException ex)
3310 this.StatusLabel.Text = ex.Message;
3314 this.workerSemaphore.Release();
3318 private async Task RefreshTwitterConfigurationAsync()
3320 await this.workerSemaphore.WaitAsync();
3323 await Task.Run(() => tw.RefreshConfiguration());
3325 if (this.tw.Configuration.PhotoSizeLimit != 0)
3327 foreach (var service in this.ImageSelector.GetServices())
3329 service.UpdateTwitterConfiguration(this.tw.Configuration);
3333 this.PurgeListViewItemCache();
3335 this._curList?.Refresh();
3337 catch (WebApiException ex)
3339 this.StatusLabel.Text = ex.Message;
3343 this.workerSemaphore.Release();
3347 private async Task RefreshMuteUserIdsAsync()
3349 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3353 await tw.RefreshMuteUserIdsAsync();
3355 catch (WebApiException ex)
3357 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3361 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3364 private void RemovePostFromFavTab(Int64[] ids)
3366 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
3367 string favTabName = favTab.TabName;
3369 if (_curTab.Text.Equals(favTabName))
3371 fidx = _curList.FocusedItem?.Index ?? _curList.TopItem?.Index ?? 0;
3374 foreach (long i in ids)
3378 _statuses.RemoveFavPost(i);
3385 if (_curTab != null && _curTab.Text.Equals(favTabName))
3387 this.PurgeListViewItemCache();
3389 //_curItemIndex = -1;
3391 foreach (TabPage tp in ListTab.TabPages)
3393 if (tp.Text == favTabName)
3395 ((DetailsListView)tp.Tag).VirtualListSize = favTab.AllCount;
3399 if (_curTab.Text.Equals(favTabName))
3403 _curList.SelectedIndices.Clear();
3405 while (_curList.SelectedIndices.Count > 0);
3407 if (favTab.AllCount > 0)
3409 if (favTab.AllCount - 1 > fidx && fidx > -1)
3411 _curList.SelectedIndices.Add(fidx);
3415 _curList.SelectedIndices.Add(favTab.AllCount - 1);
3417 if (_curList.SelectedIndices.Count > 0)
3419 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3420 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3426 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3428 if (e.Button == MouseButtons.Left)
3430 this.Visible = true;
3431 if (this.WindowState == FormWindowState.Minimized)
3433 this.WindowState = _formWindowState;
3436 this.BringToFront();
3440 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3442 switch (this._cfgCommon.ListDoubleClickAction)
3445 MakeReplyOrDirectStatus();
3448 await this.FavoriteChange(true);
3451 if (_curPost != null)
3452 await this.ShowUserStatus(_curPost.ScreenName, false);
3458 ShowRelatedStatusesMenuItem_Click(null, null);
3461 MoveToHomeToolStripMenuItem_Click(null, null);
3464 StatusOpenMenuItem_Click(null, null);
3472 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3474 await this.FavoriteChange(true);
3477 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3479 await this.FavoriteChange(false);
3483 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3485 await this.FavoritesRetweetOfficial();
3488 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3490 await this.FavoritesRetweetUnofficial();
3493 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3496 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3499 //trueでFavAdd,falseでFavRemove
3500 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3501 || !this.ExistCurrentPost) return;
3503 if (this._curList.SelectedIndices.Count > 1)
3508 // https://support.twitter.com/articles/76915#favoriting
3509 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3510 _DoFavRetweetFlags = false;
3515 if (multiFavoriteChangeDialogEnable)
3517 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3518 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3519 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3521 if (confirm == DialogResult.Cancel)
3529 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3530 if (selectedPost.IsFav)
3532 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3536 await this.FavAddAsync(selectedPost.StatusId, tab);
3540 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3541 .Select(x => this.GetCurTabPost(x))
3542 .Where(x => x.IsFav);
3544 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3545 if (statusIds.Length == 0)
3547 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3551 await this.FavRemoveAsync(statusIds, tab);
3555 private PostClass GetCurTabPost(int Index)
3557 var listCache = this._listItemCache;
3558 if (listCache != null)
3562 if (listCache.TryGetValue(Index, out item, out post))
3566 return _statuses.Tabs[_curTab.Text][Index];
3569 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3571 if (_curList.SelectedIndices.Count > 0)
3572 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3573 else if (_curList.SelectedIndices.Count == 0)
3574 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3577 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3579 if (_curList.SelectedIndices.Count > 0)
3580 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3583 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3585 if ((!_initialLayout) && this.Visible)
3587 if (this.WindowState == FormWindowState.Normal)
3589 _mySize = this.ClientSize;
3590 _mySpDis = this.SplitContainer1.SplitterDistance;
3591 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3592 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3593 ModifySettingLocal = true;
3598 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3600 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3601 if (comparerMode == null)
3604 this.SetSortColumn(comparerMode.Value);
3608 /// 列インデックスからソートを行う ComparerMode を求める
3610 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3611 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3612 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3615 return ComparerMode.Id;
3617 switch (columnIndex)
3620 return ComparerMode.Nickname;
3622 return ComparerMode.Data;
3624 return ComparerMode.Id;
3626 return ComparerMode.Name;
3628 return ComparerMode.Source;
3630 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3636 /// 発言一覧の指定した位置の列でソートする
3638 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3639 private void SetSortColumnByDisplayIndex(int columnIndex)
3641 // 表示上の列の位置から ColumnHeader を求める
3642 var col = this._curList.Columns.Cast<ColumnHeader>()
3643 .Where(x => x.DisplayIndex == columnIndex)
3649 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3650 if (comparerMode == null)
3653 this.SetSortColumn(comparerMode.Value);
3657 /// 発言一覧の最後列の項目でソートする
3659 private void SetSortLastColumn()
3661 // 表示上の最後列にある ColumnHeader を求める
3662 var col = this._curList.Columns.Cast<ColumnHeader>()
3663 .OrderByDescending(x => x.DisplayIndex)
3666 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3667 if (comparerMode == null)
3670 this.SetSortColumn(comparerMode.Value);
3674 /// 発言一覧を指定された ComparerMode に基づいてソートする
3676 private void SetSortColumn(ComparerMode sortColumn)
3678 if (this._cfgCommon.SortOrderLock)
3681 this._statuses.ToggleSortOrder(sortColumn);
3682 this.InitColumnText();
3684 var list = this._curList;
3687 list.Columns[0].Text = this.ColumnText[0];
3688 list.Columns[1].Text = this.ColumnText[2];
3692 for (var i = 0; i <= 7; i++)
3694 list.Columns[i].Text = this.ColumnText[i];
3698 this.PurgeListViewItemCache();
3700 var tab = this._statuses.Tabs[this._curTab.Text];
3701 if (tab.AllCount > 0 && this._curPost != null)
3703 var idx = tab.IndexOf(this._curPost.StatusId);
3706 this.SelectListItem(list, idx);
3707 list.EnsureVisible(idx);
3712 this.ModifySettingCommon = true;
3715 private void TweenMain_LocationChanged(object sender, EventArgs e)
3717 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3719 _myLoc = this.DesktopLocation;
3720 ModifySettingLocal = true;
3724 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3726 if (ListTab.SelectedTab == null) return;
3727 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3728 if (!this.ExistCurrentPost)
3730 ReplyStripMenuItem.Enabled = false;
3731 ReplyAllStripMenuItem.Enabled = false;
3732 DMStripMenuItem.Enabled = false;
3733 ShowProfileMenuItem.Enabled = false;
3734 ShowUserTimelineContextMenuItem.Enabled = false;
3735 ListManageUserContextToolStripMenuItem2.Enabled = false;
3736 MoveToFavToolStripMenuItem.Enabled = false;
3737 TabMenuItem.Enabled = false;
3738 IDRuleMenuItem.Enabled = false;
3739 SourceRuleMenuItem.Enabled = false;
3740 ReadedStripMenuItem.Enabled = false;
3741 UnreadStripMenuItem.Enabled = false;
3745 ShowProfileMenuItem.Enabled = true;
3746 ListManageUserContextToolStripMenuItem2.Enabled = true;
3747 ReplyStripMenuItem.Enabled = true;
3748 ReplyAllStripMenuItem.Enabled = true;
3749 DMStripMenuItem.Enabled = true;
3750 ShowUserTimelineContextMenuItem.Enabled = true;
3751 MoveToFavToolStripMenuItem.Enabled = true;
3752 TabMenuItem.Enabled = true;
3753 IDRuleMenuItem.Enabled = true;
3754 SourceRuleMenuItem.Enabled = true;
3755 ReadedStripMenuItem.Enabled = true;
3756 UnreadStripMenuItem.Enabled = true;
3758 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3760 FavAddToolStripMenuItem.Enabled = false;
3761 FavRemoveToolStripMenuItem.Enabled = false;
3762 StatusOpenMenuItem.Enabled = false;
3763 FavorareMenuItem.Enabled = false;
3764 ShowRelatedStatusesMenuItem.Enabled = false;
3766 ReTweetStripMenuItem.Enabled = false;
3767 ReTweetUnofficialStripMenuItem.Enabled = false;
3768 QuoteStripMenuItem.Enabled = false;
3769 FavoriteRetweetContextMenu.Enabled = false;
3770 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3774 FavAddToolStripMenuItem.Enabled = true;
3775 FavRemoveToolStripMenuItem.Enabled = true;
3776 StatusOpenMenuItem.Enabled = true;
3777 FavorareMenuItem.Enabled = true;
3778 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3782 ReTweetStripMenuItem.Enabled = false; //公式RTは無効に
3783 ReTweetUnofficialStripMenuItem.Enabled = true;
3784 QuoteStripMenuItem.Enabled = true;
3785 FavoriteRetweetContextMenu.Enabled = false; //公式RTは無効に
3786 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3790 if (_curPost.IsProtect)
3792 ReTweetStripMenuItem.Enabled = false;
3793 ReTweetUnofficialStripMenuItem.Enabled = false;
3794 QuoteStripMenuItem.Enabled = false;
3795 FavoriteRetweetContextMenu.Enabled = false;
3796 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3800 ReTweetStripMenuItem.Enabled = true;
3801 ReTweetUnofficialStripMenuItem.Enabled = true;
3802 QuoteStripMenuItem.Enabled = true;
3803 FavoriteRetweetContextMenu.Enabled = true;
3804 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3808 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3810 // RefreshMoreStripMenuItem.Enabled = true;
3814 // RefreshMoreStripMenuItem.Enabled = false;
3816 if (!this.ExistCurrentPost
3817 || _curPost.InReplyToStatusId == null)
3819 RepliedStatusOpenMenuItem.Enabled = false;
3823 RepliedStatusOpenMenuItem.Enabled = true;
3825 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3827 MoveToRTHomeMenuItem.Enabled = false;
3831 MoveToRTHomeMenuItem.Enabled = true;
3834 if (this.ExistCurrentPost)
3836 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3837 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3838 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3840 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3844 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3846 MakeReplyOrDirectStatus(false, true);
3849 private void DMStripMenuItem_Click(object sender, EventArgs e)
3851 MakeReplyOrDirectStatus(false, false);
3854 private async Task doStatusDelete()
3856 if (this._curTab == null || this._curList == null)
3859 if (this._curList.SelectedIndices.Count == 0)
3862 var posts = this._curList.SelectedIndices.Cast<int>()
3863 .Select(x => this.GetCurTabPost(x))
3866 // 選択されたツイートの中に削除可能なものが一つでもあるか
3867 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3870 var ret = MessageBox.Show(this,
3871 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3872 Properties.Resources.DeleteStripMenuItem_ClickText2,
3873 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3875 if (ret != DialogResult.OK)
3878 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3880 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3882 Exception lastException = null;
3883 foreach (var post in posts)
3885 if (!post.CanDeleteBy(this.tw.UserId))
3892 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3897 if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3898 // 他人に RT された自分のツイート
3899 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3902 // 自分のツイート or 自分が RT したツイート
3903 await this.twitterApi.StatusesDestroy(post.StatusId)
3907 catch (WebApiException ex)
3913 this._statuses.RemovePost(post.StatusId);
3916 if (lastException == null)
3917 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3919 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3921 this.PurgeListViewItemCache();
3922 this._curPost = null;
3923 this._curItemIndex = -1;
3925 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3927 var listView = (DetailsListView)tabPage.Tag;
3928 var tab = this._statuses.Tabs[tabPage.Text];
3930 using (ControlTransaction.Update(listView))
3932 listView.VirtualListSize = tab.AllCount;
3934 if (tabPage == this._curTab)
3936 listView.SelectedIndices.Clear();
3938 if (tab.AllCount != 0)
3941 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3942 selectedIndex = focusedIndex;
3944 selectedIndex = tab.AllCount - 1;
3946 listView.SelectedIndices.Add(selectedIndex);
3947 listView.EnsureVisible(selectedIndex);
3948 listView.FocusedItem = listView.Items[selectedIndex];
3953 if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3955 if (tabPage.ImageIndex == 0)
3956 tabPage.ImageIndex = -1; // タブアイコン
3960 if (!this._cfgCommon.TabIconDisp)
3961 this.ListTab.Refresh();
3965 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3967 await this.doStatusDelete();
3970 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3972 using (ControlTransaction.Update(this._curList))
3974 foreach (int idx in _curList.SelectedIndices)
3976 var post = this._statuses.Tabs[this._curTab.Text][idx];
3977 this._statuses.SetReadAllTab(post.StatusId, read: true);
3978 ChangeCacheStyleRead(true, idx);
3982 foreach (TabPage tb in ListTab.TabPages)
3984 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3986 if (this._cfgCommon.TabIconDisp)
3988 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3992 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3995 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3997 using (ControlTransaction.Update(this._curList))
3999 foreach (int idx in _curList.SelectedIndices)
4001 var post = this._statuses.Tabs[this._curTab.Text][idx];
4002 this._statuses.SetReadAllTab(post.StatusId, read: false);
4003 ChangeCacheStyleRead(false, idx);
4007 foreach (TabPage tb in ListTab.TabPages)
4009 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
4011 if (this._cfgCommon.TabIconDisp)
4013 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
4017 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
4020 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
4022 await this.DoRefresh();
4025 private async Task DoRefresh()
4027 if (_curTab != null)
4030 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4033 switch (_statuses.Tabs[_curTab.Text].TabType)
4035 case MyCommon.TabUsageType.Mentions:
4036 await this.GetReplyAsync();
4038 case MyCommon.TabUsageType.DirectMessage:
4039 await this.GetDirectMessagesAsync();
4041 case MyCommon.TabUsageType.Favorites:
4042 await this.GetFavoritesAsync();
4044 //case MyCommon.TabUsageType.Profile:
4046 case MyCommon.TabUsageType.PublicSearch:
4048 if (string.IsNullOrEmpty(tab.SearchWords)) return;
4049 await this.GetPublicSearchAsync(tab);
4051 case MyCommon.TabUsageType.UserTimeline:
4052 await this.GetUserTimelineAsync(tab);
4054 case MyCommon.TabUsageType.Lists:
4056 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4057 await this.GetListTimelineAsync(tab);
4060 await this.GetHomeTimelineAsync();
4066 await this.GetHomeTimelineAsync();
4070 private async Task DoRefreshMore()
4073 if (_curTab != null)
4076 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4079 switch (_statuses.Tabs[_curTab.Text].TabType)
4081 case MyCommon.TabUsageType.Mentions:
4082 await this.GetReplyAsync(loadMore: true);
4084 case MyCommon.TabUsageType.DirectMessage:
4085 await this.GetDirectMessagesAsync(loadMore: true);
4087 case MyCommon.TabUsageType.Favorites:
4088 await this.GetFavoritesAsync(loadMore: true);
4090 case MyCommon.TabUsageType.Profile:
4093 case MyCommon.TabUsageType.PublicSearch:
4095 if (string.IsNullOrEmpty(tab.SearchWords)) return;
4096 await this.GetPublicSearchAsync(tab, loadMore: true);
4098 case MyCommon.TabUsageType.UserTimeline:
4099 await this.GetUserTimelineAsync(tab, loadMore: true);
4101 case MyCommon.TabUsageType.Lists:
4103 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4104 await this.GetListTimelineAsync(tab, loadMore: true);
4107 await this.GetHomeTimelineAsync(loadMore: true);
4113 await this.GetHomeTimelineAsync(loadMore: true);
4117 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
4119 DialogResult result = DialogResult.Abort;
4121 using (var settingDialog = new AppendSettingDialog())
4123 settingDialog.Icon = this.MainIcon;
4124 settingDialog.Owner = this;
4125 settingDialog.ShowInTaskbar = showTaskbarIcon;
4126 settingDialog.IntervalChanged += this.TimerInterval_Changed;
4128 settingDialog.tw = this.tw;
4129 settingDialog.twitterApi = this.twitterApi;
4131 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
4135 result = settingDialog.ShowDialog(this);
4139 return DialogResult.Abort;
4142 if (result == DialogResult.OK)
4146 settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
4154 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
4157 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
4159 var oldIconSz = this._cfgCommon.IconSize;
4161 if (ShowSettingDialog() == DialogResult.OK)
4165 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
4166 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
4167 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
4168 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
4169 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
4170 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
4172 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
4173 Networking.SetWebProxy(this._cfgLocal.ProxyType,
4174 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
4175 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
4176 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
4178 ImageSelector.Reset(tw, this.tw.Configuration);
4182 if (this._cfgCommon.TabIconDisp)
4184 ListTab.DrawItem -= ListTab_DrawItem;
4185 ListTab.DrawMode = TabDrawMode.Normal;
4186 ListTab.ImageList = this.TabImage;
4190 ListTab.DrawItem -= ListTab_DrawItem;
4191 ListTab.DrawItem += ListTab_DrawItem;
4192 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
4193 ListTab.ImageList = null;
4196 catch (Exception ex)
4198 ex.Data["Instance"] = "ListTab(TabIconDisp)";
4199 ex.Data["IsTerminatePermission"] = false;
4205 if (!this._cfgCommon.UnreadManage)
4207 ReadedStripMenuItem.Enabled = false;
4208 UnreadStripMenuItem.Enabled = false;
4209 if (this._cfgCommon.TabIconDisp)
4211 foreach (TabPage myTab in ListTab.TabPages)
4213 myTab.ImageIndex = -1;
4219 ReadedStripMenuItem.Enabled = true;
4220 UnreadStripMenuItem.Enabled = true;
4223 catch (Exception ex)
4225 ex.Data["Instance"] = "ListTab(UnreadManage)";
4226 ex.Data["IsTerminatePermission"] = false;
4233 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
4235 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
4236 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
4237 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
4239 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
4240 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
4241 _fntUnread = this._cfgLocal.FontUnread;
4242 _clUnread = this._cfgLocal.ColorUnread;
4243 _fntReaded = this._cfgLocal.FontRead;
4244 _clReaded = this._cfgLocal.ColorRead;
4245 _clFav = this._cfgLocal.ColorFav;
4246 _clOWL = this._cfgLocal.ColorOWL;
4247 _clRetweet = this._cfgLocal.ColorRetweet;
4248 _fntDetail = this._cfgLocal.FontDetail;
4249 _clDetail = this._cfgLocal.ColorDetail;
4250 _clDetailLink = this._cfgLocal.ColorDetailLink;
4251 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
4252 _clSelf = this._cfgLocal.ColorSelf;
4253 _clAtSelf = this._cfgLocal.ColorAtSelf;
4254 _clTarget = this._cfgLocal.ColorTarget;
4255 _clAtTarget = this._cfgLocal.ColorAtTarget;
4256 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
4257 _clAtTo = this._cfgLocal.ColorAtTo;
4258 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
4259 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
4260 _clInputFont = this._cfgLocal.ColorInputFont;
4261 _fntInputFont = this._cfgLocal.FontInputFont;
4262 _brsBackColorMine.Dispose();
4263 _brsBackColorAt.Dispose();
4264 _brsBackColorYou.Dispose();
4265 _brsBackColorAtYou.Dispose();
4266 _brsBackColorAtFromTarget.Dispose();
4267 _brsBackColorAtTo.Dispose();
4268 _brsBackColorNone.Dispose();
4269 _brsBackColorMine = new SolidBrush(_clSelf);
4270 _brsBackColorAt = new SolidBrush(_clAtSelf);
4271 _brsBackColorYou = new SolidBrush(_clTarget);
4272 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4273 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4274 _brsBackColorAtTo = new SolidBrush(_clAtTo);
4275 _brsBackColorNone = new SolidBrush(_clListBackcolor);
4279 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4280 StatusText.Font = _fntInputFont;
4281 StatusText.ForeColor = _clInputFont;
4283 catch (Exception ex)
4285 MessageBox.Show(ex.Message);
4290 InitDetailHtmlFormat();
4292 catch (Exception ex)
4294 ex.Data["Instance"] = "Font";
4295 ex.Data["IsTerminatePermission"] = false;
4301 foreach (TabPage tb in ListTab.TabPages)
4303 if (this._cfgCommon.TabIconDisp)
4305 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4312 catch (Exception ex)
4314 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4315 ex.Data["IsTerminatePermission"] = false;
4321 var oldIconCol = _iconCol;
4323 if (this._cfgCommon.IconSize != oldIconSz)
4324 ApplyListViewIconSize(this._cfgCommon.IconSize);
4326 foreach (TabPage tp in ListTab.TabPages)
4328 DetailsListView lst = (DetailsListView)tp.Tag;
4330 using (ControlTransaction.Update(lst))
4332 lst.GridLines = this._cfgCommon.ShowGrid;
4333 lst.Font = _fntReaded;
4334 lst.BackColor = _clListBackcolor;
4336 if (_iconCol != oldIconCol)
4341 catch (Exception ex)
4343 ex.Data["Instance"] = "ListView(IconSize)";
4344 ex.Data["IsTerminatePermission"] = false;
4348 SetMainWindowTitle();
4349 SetNotifyIconText();
4351 this.PurgeListViewItemCache();
4352 _curList?.Refresh();
4355 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4356 if (this._cfgCommon.HotkeyEnabled)
4358 ///グローバルホットキーの登録。設定で変更可能にするかも
4359 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4360 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4361 modKey |= HookGlobalHotkey.ModKeys.Alt;
4362 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4363 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4364 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4365 modKey |= HookGlobalHotkey.ModKeys.Shift;
4366 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4367 modKey |= HookGlobalHotkey.ModKeys.Win;
4369 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4372 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4375 StatusText_TextChanged(null, null);
4384 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
4385 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
4386 this.twitterApi.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.UserId, oldUser.Username);
4389 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4391 this.TopMost = this._cfgCommon.AlwaysTop;
4392 SaveConfigsAll(false);
4394 if (tw.Username != oldUser.Username)
4395 await this.doGetFollowersMenu();
4401 private void SetTabAlignment()
4403 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4404 if (ListTab.Alignment == newAlignment) return;
4406 // 各タブのリスト上の選択位置などを退避
4407 var listSelections = this.SaveListViewSelection();
4409 ListTab.Alignment = newAlignment;
4411 foreach (TabPage tab in ListTab.TabPages)
4413 DetailsListView lst = (DetailsListView)tab.Tag;
4414 TabClass tabInfo = _statuses.Tabs[tab.Text];
4415 using (ControlTransaction.Update(lst))
4418 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4423 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4429 case MyCommon.IconSizes.IconNone:
4432 case MyCommon.IconSizes.Icon16:
4435 case MyCommon.IconSizes.Icon24:
4438 case MyCommon.IconSizes.Icon48:
4441 case MyCommon.IconSizes.Icon48_2:
4449 // ディスプレイの DPI 設定を考慮したサイズを設定する
4450 _listViewImageList.ImageSize = new Size(
4452 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4456 _listViewImageList.ImageSize = new Size(1, 1);
4460 private void ResetColumns(DetailsListView list)
4462 using (ControlTransaction.Update(list))
4463 using (ControlTransaction.Layout(list, false))
4466 list.ColumnClick -= MyList_ColumnClick;
4467 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4468 list.ColumnReordered -= MyList_ColumnReordered;
4469 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4471 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4472 list.Columns.Clear();
4473 cols.ForEach(col => col.Dispose());
4476 InitColumns(list, true);
4478 list.ColumnClick += MyList_ColumnClick;
4479 list.DrawColumnHeader += MyList_DrawColumnHeader;
4480 list.ColumnReordered += MyList_ColumnReordered;
4481 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4485 private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4487 if (e.Url.AbsoluteUri != "about:blank")
4489 await this.DispSelectedPost();
4490 await this.OpenUriInBrowserAsync(e.Url.OriginalString);
4494 private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4496 if (e.Url.Scheme == "data")
4498 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4500 else if (e.Url.AbsoluteUri != "about:blank")
4503 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
4504 await this.OpenUriAsync( e.Url, MyCommon.IsKeyDown( Keys.Control ) );
4508 public void AddNewTabForSearch(string searchWord)
4510 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4511 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4513 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4515 foreach (TabPage tp in ListTab.TabPages)
4517 if (tb.TabName == tp.Text)
4519 ListTab.SelectedTab = tp;
4526 string tabName = searchWord;
4527 for (int i = 0; i <= 100; i++)
4529 if (_statuses.ContainsTab(tabName))
4535 _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4536 AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4538 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4540 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4541 cmb.Items.Add(searchWord);
4542 cmb.Text = searchWord;
4545 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4548 private void ShowUserTimeline()
4550 if (!this.ExistCurrentPost) return;
4551 AddNewTabForUserTimeline(_curPost.ScreenName);
4554 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4556 if (e.KeyCode == Keys.Escape)
4558 TabPage relTp = ListTab.SelectedTab;
4559 RemoveSpecifiedTab(relTp.Text, false);
4561 e.SuppressKeyPress = true;
4565 public void AddNewTabForUserTimeline(string user)
4567 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4568 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4570 if (tb.User == user)
4572 foreach (TabPage tp in ListTab.TabPages)
4574 if (tb.TabName == tp.Text)
4576 ListTab.SelectedTab = tp;
4583 string tabName = "user:" + user;
4584 while (_statuses.ContainsTab(tabName))
4589 _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4590 var tab = this._statuses.Tabs[tabName];
4592 AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4594 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4597 this.GetUserTimelineAsync(tab);
4600 public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4603 foreach (TabPage tb in ListTab.TabPages)
4605 if (tb.Text == tabName) return false;
4609 if (tabName == Properties.Resources.AddNewTabText1) return false;
4614 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4615 tabType == MyCommon.TabUsageType.Favorites ||
4616 tabType == MyCommon.TabUsageType.Home ||
4617 tabType == MyCommon.TabUsageType.Mentions ||
4618 tabType == MyCommon.TabUsageType.Related)
4620 if (_statuses.GetTabByType(tabType) != null) return false;
4624 var _tabPage = new TabPage();
4625 var _listCustom = new DetailsListView();
4627 int cnt = ListTab.TabPages.Count;
4629 ///ToDo:Create and set controls follow tabtypes
4631 using (ControlTransaction.Update(_listCustom))
4632 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4633 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4634 using (ControlTransaction.Layout(this.SplitContainer1, false))
4635 using (ControlTransaction.Layout(this.ListTab, false))
4636 using (ControlTransaction.Layout(this))
4637 using (ControlTransaction.Layout(_tabPage, false))
4639 _tabPage.Controls.Add(_listCustom);
4642 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4644 var label = new Label();
4645 label.Dock = DockStyle.Top;
4646 label.Name = "labelUser";
4648 if (tabType == MyCommon.TabUsageType.Lists)
4650 label.Text = listInfo.ToString();
4654 label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4656 label.TextAlign = ContentAlignment.MiddleLeft;
4657 using (ComboBox tmpComboBox = new ComboBox())
4659 label.Height = tmpComboBox.Height;
4661 _tabPage.Controls.Add(label);
4664 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4666 var pnl = new Panel();
4668 var lbl = new Label();
4669 var cmb = new ComboBox();
4670 var btn = new Button();
4671 var cmbLang = new ComboBox();
4673 using (ControlTransaction.Layout(pnl, false))
4675 pnl.Controls.Add(cmb);
4676 pnl.Controls.Add(cmbLang);
4677 pnl.Controls.Add(btn);
4678 pnl.Controls.Add(lbl);
4679 pnl.Name = "panelSearch";
4681 pnl.Dock = DockStyle.Top;
4682 pnl.Height = cmb.Height;
4683 pnl.Enter += SearchControls_Enter;
4684 pnl.Leave += SearchControls_Leave;
4687 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4688 cmb.Dock = DockStyle.Fill;
4689 cmb.Name = "comboSearch";
4690 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4691 cmb.ImeMode = ImeMode.NoControl;
4692 cmb.TabStop = false;
4694 cmb.AutoCompleteMode = AutoCompleteMode.None;
4695 cmb.KeyDown += SearchComboBox_KeyDown;
4698 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4699 cmbLang.Dock = DockStyle.Right;
4701 cmbLang.Name = "comboLang";
4702 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4703 cmbLang.TabStop = false;
4704 cmbLang.TabIndex = 2;
4705 cmbLang.Items.Add("");
4706 cmbLang.Items.Add("ja");
4707 cmbLang.Items.Add("en");
4708 cmbLang.Items.Add("ar");
4709 cmbLang.Items.Add("da");
4710 cmbLang.Items.Add("nl");
4711 cmbLang.Items.Add("fa");
4712 cmbLang.Items.Add("fi");
4713 cmbLang.Items.Add("fr");
4714 cmbLang.Items.Add("de");
4715 cmbLang.Items.Add("hu");
4716 cmbLang.Items.Add("is");
4717 cmbLang.Items.Add("it");
4718 cmbLang.Items.Add("no");
4719 cmbLang.Items.Add("pl");
4720 cmbLang.Items.Add("pt");
4721 cmbLang.Items.Add("ru");
4722 cmbLang.Items.Add("es");
4723 cmbLang.Items.Add("sv");
4724 cmbLang.Items.Add("th");
4726 lbl.Text = "Search(C-S-f)";
4727 lbl.Name = "label1";
4728 lbl.Dock = DockStyle.Left;
4730 lbl.Height = cmb.Height;
4731 lbl.TextAlign = ContentAlignment.MiddleLeft;
4734 btn.Text = "Search";
4735 btn.Name = "buttonSearch";
4736 btn.UseVisualStyleBackColor = true;
4737 btn.Dock = DockStyle.Right;
4738 btn.TabStop = false;
4740 btn.Click += SearchButton_Click;
4743 if (_statuses.Tabs.TryGetValue(tabName, out tab))
4745 if (!string.IsNullOrEmpty(tab.SearchWords))
4747 cmb.Items.Add(tab.SearchWords);
4748 cmb.Text = tab.SearchWords;
4751 cmbLang.Text = tab.SearchLang;
4754 _tabPage.Controls.Add(pnl);
4758 _tabPage.Tag = _listCustom;
4759 this.ListTab.Controls.Add(_tabPage);
4761 _tabPage.Location = new Point(4, 4);
4762 _tabPage.Name = "CTab" + cnt.ToString();
4763 _tabPage.Size = new Size(380, 260);
4764 _tabPage.TabIndex = 2 + cnt;
4765 _tabPage.Text = tabName;
4766 _tabPage.UseVisualStyleBackColor = true;
4767 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4769 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4770 _listCustom.TabIndex = 1;
4771 _listCustom.AllowColumnReorder = true;
4772 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4773 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4774 _listCustom.Dock = DockStyle.Fill;
4775 _listCustom.FullRowSelect = true;
4776 _listCustom.HideSelection = false;
4777 _listCustom.Location = new Point(0, 0);
4778 _listCustom.Margin = new Padding(0);
4779 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4780 _listCustom.ShowItemToolTips = true;
4781 _listCustom.Size = new Size(380, 260);
4782 _listCustom.UseCompatibleStateImageBehavior = false;
4783 _listCustom.View = View.Details;
4784 _listCustom.OwnerDraw = true;
4785 _listCustom.VirtualMode = true;
4786 _listCustom.Font = _fntReaded;
4787 _listCustom.BackColor = _clListBackcolor;
4789 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4790 _listCustom.AllowDrop = true;
4792 _listCustom.SmallImageList = _listViewImageList;
4794 InitColumns(_listCustom, startup);
4796 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4797 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4798 _listCustom.ColumnClick += MyList_ColumnClick;
4799 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4800 _listCustom.DragDrop += TweenMain_DragDrop;
4801 _listCustom.DragEnter += TweenMain_DragEnter;
4802 _listCustom.DragOver += TweenMain_DragOver;
4803 _listCustom.DrawItem += MyList_DrawItem;
4804 _listCustom.MouseClick += MyList_MouseClick;
4805 _listCustom.ColumnReordered += MyList_ColumnReordered;
4806 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4807 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4808 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4809 _listCustom.DrawSubItem += MyList_DrawSubItem;
4810 _listCustom.HScrolled += MyList_HScrolled;
4816 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4818 var tabInfo = _statuses.GetTabByName(TabName);
4819 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4823 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4824 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4825 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4831 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4832 if (_tabPage == null) return false;
4834 SetListProperty(); //他のタブに列幅等を反映
4837 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4838 _tabPage.Tag = null;
4840 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4841 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4842 using (ControlTransaction.Layout(this.SplitContainer1, false))
4843 using (ControlTransaction.Layout(this.ListTab, false))
4844 using (ControlTransaction.Layout(this))
4845 using (ControlTransaction.Layout(_tabPage, false))
4847 if (this.ListTab.SelectedTab == _tabPage)
4849 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4850 this._beforeSelectedTab = null;
4852 this.ListTab.Controls.Remove(_tabPage);
4855 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4857 using (Control label = _tabPage.Controls["labelUser"])
4859 _tabPage.Controls.Remove(label);
4862 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4864 using (Control pnl = _tabPage.Controls["panelSearch"])
4866 pnl.Enter -= SearchControls_Enter;
4867 pnl.Leave -= SearchControls_Leave;
4868 _tabPage.Controls.Remove(pnl);
4870 foreach (Control ctrl in pnl.Controls)
4872 if (ctrl.Name == "buttonSearch")
4874 ctrl.Click -= SearchButton_Click;
4876 else if (ctrl.Name == "comboSearch")
4878 ctrl.KeyDown -= SearchComboBox_KeyDown;
4880 pnl.Controls.Remove(ctrl);
4886 _tabPage.Controls.Remove(_listCustom);
4888 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4889 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4890 _listCustom.ColumnClick -= MyList_ColumnClick;
4891 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4892 _listCustom.DragDrop -= TweenMain_DragDrop;
4893 _listCustom.DragEnter -= TweenMain_DragEnter;
4894 _listCustom.DragOver -= TweenMain_DragOver;
4895 _listCustom.DrawItem -= MyList_DrawItem;
4896 _listCustom.MouseClick -= MyList_MouseClick;
4897 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4898 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4899 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4900 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4901 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4902 _listCustom.HScrolled -= MyList_HScrolled;
4904 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4905 _listCustom.Columns.Clear();
4906 cols.ForEach(col => col.Dispose());
4909 _listCustom.ContextMenuStrip = null;
4910 _listCustom.ColumnHeaderContextMenuStrip = null;
4911 _listCustom.Font = null;
4913 _listCustom.SmallImageList = null;
4914 _listCustom.ListViewItemSorter = null;
4917 if (_curTab.Equals(_tabPage))
4924 this.PurgeListViewItemCache();
4928 _listCustom.Dispose();
4929 _statuses.RemoveTab(TabName);
4931 foreach (TabPage tp in ListTab.TabPages)
4933 DetailsListView lst = (DetailsListView)tp.Tag;
4934 var count = _statuses.Tabs[tp.Text].AllCount;
4935 if (lst.VirtualListSize != count)
4937 lst.VirtualListSize = count;
4944 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4946 this.PurgeListViewItemCache();
4947 _beforeSelectedTab = e.TabPage;
4950 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4954 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4957 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4958 if (!dragEnableRectangle.Contains(e.Location))
4960 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4961 tn = ListTab.SelectedTab.Text;
4964 if (string.IsNullOrEmpty(tn)) return;
4966 foreach (TabPage tb in ListTab.TabPages)
4970 ListTab.DoDragDrop(tb, DragDropEffects.All);
4980 Point cpos = new Point(e.X, e.Y);
4981 for (int i = 0; i < ListTab.TabPages.Count; i++)
4983 Rectangle rect = ListTab.GetTabRect(i);
4984 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4985 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4987 _rclickTabName = ListTab.TabPages[i].Text;
4993 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4995 //_curList.Refresh();
4996 SetMainWindowTitle();
4997 SetStatusLabelUrl();
4998 SetApiStatusLabel();
4999 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
5000 TabMenuControl(ListTab.SelectedTab.Text);
5001 this.PushSelectPostChain();
5002 await DispSelectedPost();
5005 private void SetListProperty()
5007 //削除などで見つからない場合は処理せず
5008 if (_curList == null) return;
5009 if (!_isColumnChanged) return;
5011 int[] dispOrder = new int[_curList.Columns.Count];
5012 for (int i = 0; i < _curList.Columns.Count; i++)
5014 for (int j = 0; j < _curList.Columns.Count; j++)
5016 if (_curList.Columns[j].DisplayIndex == i)
5025 foreach (TabPage tb in ListTab.TabPages)
5027 if (!tb.Equals(_curTab))
5029 if (tb.Tag != null && tb.Controls.Count > 0)
5031 DetailsListView lst = (DetailsListView)tb.Tag;
5032 for (int i = 0; i < lst.Columns.Count; i++)
5034 lst.Columns[dispOrder[i]].DisplayIndex = i;
5035 lst.Columns[i].Width = _curList.Columns[i].Width;
5041 _isColumnChanged = false;
5044 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
5048 if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal)
5049 || PostBrowser.StatusText.StartsWith("ftp", StringComparison.Ordinal)
5050 || PostBrowser.StatusText.StartsWith("data", StringComparison.Ordinal))
5052 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
5054 if (string.IsNullOrEmpty(PostBrowser.StatusText))
5056 SetStatusLabelUrl();
5064 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
5066 if (e.KeyChar == '@')
5068 if (!this._cfgCommon.UseAtIdSupplement) return;
5070 int cnt = AtIdSupl.ItemCount;
5071 ShowSuplDialog(StatusText, AtIdSupl);
5072 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
5075 else if (e.KeyChar == '#')
5077 if (!this._cfgCommon.UseHashSupplement) return;
5078 ShowSuplDialog(StatusText, HashSupl);
5083 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
5085 ShowSuplDialog(owner, dialog, 0, "");
5088 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
5090 ShowSuplDialog(owner, dialog, offset, "");
5093 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
5095 dialog.StartsWith = startswith;
5102 dialog.ShowDialog();
5104 this.TopMost = this._cfgCommon.AlwaysTop;
5105 int selStart = owner.SelectionStart;
5108 if (dialog.DialogResult == DialogResult.OK)
5110 if (!string.IsNullOrEmpty(dialog.inputText))
5114 fHalf = owner.Text.Substring(0, selStart - offset);
5116 if (selStart < owner.Text.Length)
5118 eHalf = owner.Text.Substring(selStart);
5120 owner.Text = fHalf + dialog.inputText + eHalf;
5121 owner.SelectionStart = selStart + dialog.inputText.Length;
5128 fHalf = owner.Text.Substring(0, selStart);
5130 if (selStart < owner.Text.Length)
5132 eHalf = owner.Text.Substring(selStart);
5134 owner.Text = fHalf + eHalf;
5137 owner.SelectionStart = selStart;
5143 private void StatusText_KeyUp(object sender, KeyEventArgs e)
5146 if (!e.Alt && !e.Control && !e.Shift)
5148 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
5150 bool isSpace = false;
5151 foreach (char c in StatusText.Text.ToCharArray())
5153 if (c == ' ' || c == ' ')
5166 StatusText.Text = "";
5167 JumpUnreadMenuItem_Click(null, null);
5171 this.StatusText_TextChanged(null, null);
5174 private void StatusText_TextChanged(object sender, EventArgs e)
5177 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
5178 lblLen.Text = pLen.ToString();
5181 StatusText.ForeColor = Color.Red;
5185 StatusText.ForeColor = _clInputFont;
5187 if (string.IsNullOrEmpty(StatusText.Text))
5189 this.inReplyTo = null;
5194 /// ツイート投稿前のフッター付与などの前処理を行います
5196 private string FormatStatusText(string statusText)
5198 statusText = statusText.Replace("\r\n", "\n");
5200 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
5203 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
5206 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
5208 // 文中の全角スペースを半角スペース1個にする
5209 statusText = statusText.Replace(" ", " ");
5212 // DM の場合はこれ以降の処理を行わない
5213 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
5217 if (this._cfgCommon.PostShiftEnter)
5219 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5223 if (this.StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
5224 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5226 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
5229 if (statusText.Contains("RT @"))
5230 disableFooter = true;
5235 var hashtag = this.HashMgr.UseHash;
5236 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
5239 header = HashMgr.UseHash + " ";
5241 footer = " " + HashMgr.UseHash;
5246 if (this._cfgLocal.UseRecommendStatus)
5249 footer += this.recommendedStatusFooter;
5251 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
5253 // テキストボックスに入力されている文字列を使用する
5254 footer += " " + this._cfgLocal.StatusText.Trim();
5258 statusText = header + statusText + footer;
5260 if (this.ToolStripMenuItemPreventSmsCommand.Checked)
5262 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
5263 // 参照: https://support.twitter.com/articles/14020
5265 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
5266 && !Twitter.DMSendTextRegex.IsMatch(statusText))
5268 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
5269 statusText = '\u200b' + statusText;
5277 /// 投稿欄に表示する入力可能な文字数を計算します
5279 private int GetRestStatusCount(string statusText)
5282 var remainCount = this.tw.GetTextLengthRemain(statusText);
5284 if (this.ImageSelector.Visible && !string.IsNullOrEmpty(this.ImageSelector.ServiceName))
5286 remainCount -= this.tw.Configuration.CharactersReservedPerMedia;
5292 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5294 if (sender != this._curList)
5297 var listCache = this._listItemCache;
5298 if (listCache != null && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
5300 // If the newly requested cache is a subset of the old cache,
5301 // no need to rebuild everything, so do nothing.
5305 // Now we need to rebuild the cache.
5306 this.CreateCache(e.StartIndex, e.EndIndex);
5309 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5311 var listCache = this._listItemCache;
5312 if (listCache != null && listCache.TargetList == sender)
5315 PostClass cacheItemPost;
5316 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
5323 // A cache miss, so create a new ListViewItem and pass it back.
5324 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5327 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
5331 // 不正な要求に対する間に合わせの応答
5332 string[] sitem = {"", "", "", "", "", "", "", ""};
5333 e.Item = new ImageListViewItem(sitem);
5337 private void CreateCache(int startIndex, int endIndex)
5339 var tabInfo = this._statuses.Tabs[this._curTab.Text];
5341 if (tabInfo.AllCount == 0)
5344 // キャッシュ要求(要求範囲±30を作成)
5345 startIndex = Math.Max(startIndex - 30, 0);
5346 endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
5348 var cacheLength = endIndex - startIndex + 1;
5350 var posts = tabInfo[startIndex, endIndex]; //配列で取得
5351 var listItems = Enumerable.Range(0, cacheLength)
5352 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
5355 var listCache = new ListViewItemCache
5357 TargetList = this._curList,
5358 StartIndex = startIndex,
5359 EndIndex = endIndex,
5361 ListItem = listItems,
5364 Interlocked.Exchange(ref this._listItemCache, listCache);
5368 /// DetailsListView のための ListViewItem のキャッシュを消去する
5370 private void PurgeListViewItemCache()
5372 Interlocked.Exchange(ref this._listItemCache, null);
5375 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5377 StringBuilder mk = new StringBuilder();
5378 //if (Post.IsDeleted) mk.Append("×");
5379 //if (Post.IsMark) mk.Append("♪");
5380 //if (Post.IsProtect) mk.Append("Ю");
5381 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5382 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5383 ImageListViewItem itm;
5384 if (Post.RetweetedId == null)
5386 string[] sitem= {"",
5388 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5389 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5394 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5398 string[] sitem = {"",
5400 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5401 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5402 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5406 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5408 itm.StateIndex = Post.StateIndex;
5410 bool read = Post.IsRead;
5411 //未読管理していなかったら既読として扱う
5412 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5413 ChangeItemStyleRead(read, itm, Post, null);
5414 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5419 /// 全てのタブの振り分けルールを反映し直します
5421 private void ApplyPostFilters()
5423 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5425 this.PurgeListViewItemCache();
5426 this._curPost = null;
5427 this._curItemIndex = -1;
5428 this._statuses.FilterAll();
5430 foreach (TabPage tabPage in this.ListTab.TabPages)
5432 var tab = this._statuses.Tabs[tabPage.Text];
5434 var listview = (DetailsListView)tabPage.Tag;
5435 using (ControlTransaction.Update(listview))
5437 listview.VirtualListSize = tab.AllCount;
5440 if (this._cfgCommon.TabIconDisp)
5442 if (tab.UnreadCount > 0)
5443 tabPage.ImageIndex = 0;
5445 tabPage.ImageIndex = -1;
5449 if (!this._cfgCommon.TabIconDisp)
5450 this.ListTab.Refresh();
5452 SetMainWindowTitle();
5453 SetStatusLabelUrl();
5457 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5459 e.DrawDefault = true;
5462 private void MyList_HScrolled(object sender, EventArgs e)
5464 DetailsListView listView = (DetailsListView)sender;
5468 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5470 if (e.State == 0) return;
5471 e.DrawDefault = false;
5473 SolidBrush brs2 = null;
5474 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5476 if (e.Item.BackColor == _clSelf)
5477 brs2 = _brsBackColorMine;
5478 else if (e.Item.BackColor == _clAtSelf)
5479 brs2 = _brsBackColorAt;
5480 else if (e.Item.BackColor == _clTarget)
5481 brs2 = _brsBackColorYou;
5482 else if (e.Item.BackColor == _clAtTarget)
5483 brs2 = _brsBackColorAtYou;
5484 else if (e.Item.BackColor == _clAtFromTarget)
5485 brs2 = _brsBackColorAtFromTarget;
5486 else if (e.Item.BackColor == _clAtTo)
5487 brs2 = _brsBackColorAtTo;
5489 brs2 = _brsBackColorNone;
5494 if (((Control)sender).Focused)
5495 brs2 = _brsHighLight;
5497 brs2 = _brsDeactiveSelection;
5499 e.Graphics.FillRectangle(brs2, e.Bounds);
5500 e.DrawFocusRectangle();
5501 this.DrawListViewItemIcon(e);
5504 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5506 if (e.ItemState == 0) return;
5508 if (e.ColumnIndex > 0)
5511 RectangleF rct = e.Bounds;
5512 rct.Width = e.Header.Width;
5513 int fontHeight = e.Item.Font.Height;
5516 rct.Y += fontHeight;
5517 rct.Height -= fontHeight;
5521 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5523 //if (heightDiff > fontHeight * 0.7)
5525 // rct.Height += fontHeight;
5526 // drawLineCount += 1;
5529 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5530 if (!_iconCol && drawLineCount <= 1)
5532 //rct.Inflate(0, heightDiff / -2);
5533 //rct.Height += fontHeight / 2;
5535 else if (heightDiff < fontHeight * 0.7)
5537 //最終行が70%以上欠けていたら、最終行は表示しない
5538 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5539 rct.Height = (fontHeight * drawLineCount) - 1;
5546 //if (!_iconCol && drawLineCount > 1)
5548 // rct.Y += fontHeight * 0.2;
5549 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5554 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5555 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5560 Rectangle rctB = e.Bounds;
5561 rctB.Width = e.Header.Width;
5562 rctB.Height = fontHeight;
5564 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5566 TextRenderer.DrawText(e.Graphics,
5567 e.Item.SubItems[2].Text,
5569 Rectangle.Round(rct),
5571 TextFormatFlags.WordBreak |
5572 TextFormatFlags.EndEllipsis |
5573 TextFormatFlags.GlyphOverhangPadding |
5574 TextFormatFlags.NoPrefix);
5575 TextRenderer.DrawText(e.Graphics,
5576 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 + "]",
5580 TextFormatFlags.SingleLine |
5581 TextFormatFlags.EndEllipsis |
5582 TextFormatFlags.GlyphOverhangPadding |
5583 TextFormatFlags.NoPrefix);
5586 else if (drawLineCount == 1)
5588 TextRenderer.DrawText(e.Graphics,
5591 Rectangle.Round(rct),
5593 TextFormatFlags.SingleLine |
5594 TextFormatFlags.EndEllipsis |
5595 TextFormatFlags.GlyphOverhangPadding |
5596 TextFormatFlags.NoPrefix |
5597 TextFormatFlags.VerticalCenter);
5601 TextRenderer.DrawText(e.Graphics,
5604 Rectangle.Round(rct),
5606 TextFormatFlags.WordBreak |
5607 TextFormatFlags.EndEllipsis |
5608 TextFormatFlags.GlyphOverhangPadding |
5609 TextFormatFlags.NoPrefix);
5611 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5616 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5618 if (_iconSz == 0) return;
5620 ImageListViewItem item = (ImageListViewItem)e.Item;
5622 //e.Bounds.Leftが常に0を指すから自前で計算
5623 Rectangle itemRect = item.Bounds;
5624 var col0 = e.Item.ListView.Columns[0];
5625 itemRect.Width = col0.Width;
5627 if (col0.DisplayIndex > 0)
5629 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5631 if (clm.DisplayIndex < col0.DisplayIndex)
5632 itemRect.X += clm.Width;
5636 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5637 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5638 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5641 var img = item.Image;
5644 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5645 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5647 if (iconRect.Width > 0)
5649 e.Graphics.FillRectangle(Brushes.White, iconRect);
5650 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5653 e.Graphics.DrawImage(img.Image, iconRect);
5655 catch (ArgumentException)
5657 item.RefreshImageAsync();
5663 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5664 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5666 item.GetImageAsync();
5669 if (item.StateIndex > -1)
5671 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5672 if (stateRect.Width > 0)
5674 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5675 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5676 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5681 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5683 base.ScaleControl(factor, specified);
5685 ScaleChildControl(this.TabImage, factor);
5687 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5688 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5690 foreach (var listview in listviews)
5692 ScaleChildControl(listview, factor);
5696 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5698 // ImageListViewItem item = (ImageListViewItem)e.Item;
5699 // if (item.StateImageIndex > -1)
5701 // ////e.Bounds.Leftが常に0を指すから自前で計算
5702 // //Rectangle itemRect = item.Bounds;
5703 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5705 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5707 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5709 // // itemRect.X += clm.Width;
5713 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5714 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5716 // if (rct.Width > 0)
5718 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5719 // //e.Graphics.FillRectangle(Brushes.White, rct);
5720 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5721 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5726 private void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5728 var tab = this._statuses.Tabs[this._curTab.Text];
5730 if (tab.AllCount == 0)
5732 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5736 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5741 case SEARCHTYPE.NextSearch: // 次を検索
5742 if (selectedIndex != -1)
5743 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5747 case SEARCHTYPE.PrevSearch: // 前を検索
5748 if (selectedIndex != -1)
5749 startIndex = Math.Max(selectedIndex - 1, 0);
5751 startIndex = tab.AllCount - 1;
5753 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5755 if (selectedIndex != -1)
5756 startIndex = selectedIndex;
5762 Func<string, bool> stringComparer;
5765 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5767 catch (ArgumentException)
5769 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5773 var reverse = searchType == SEARCHTYPE.PrevSearch;
5774 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5775 .DefaultIfEmpty(-1).First();
5777 if (foundIndex == -1)
5779 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5783 this.SelectListItem(this._curList, foundIndex);
5784 this._curList.EnsureVisible(foundIndex);
5787 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5790 this.ShowSearchDialog();
5793 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5795 var previousSearch = this.SearchDialog.ResultOptions;
5796 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5798 this.SearchDialog.Reset();
5799 this.ShowSearchDialog();
5805 previousSearch.Query,
5806 previousSearch.CaseSensitive,
5807 previousSearch.UseRegex,
5808 SEARCHTYPE.NextSearch);
5811 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5813 var previousSearch = this.SearchDialog.ResultOptions;
5814 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5816 this.SearchDialog.Reset();
5817 this.ShowSearchDialog();
5823 previousSearch.Query,
5824 previousSearch.CaseSensitive,
5825 previousSearch.UseRegex,
5826 SEARCHTYPE.PrevSearch);
5830 /// 検索ダイアログを表示し、検索を実行します
5832 private void ShowSearchDialog()
5834 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5836 this.TopMost = this._cfgCommon.AlwaysTop;
5839 this.TopMost = this._cfgCommon.AlwaysTop;
5841 var searchOptions = this.SearchDialog.ResultOptions;
5842 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5844 if (searchOptions.NewTab)
5846 var tabName = Properties.Resources.SearchResults_TabName;
5850 tabName = this._statuses.MakeTabName(tabName);
5852 catch (TabException ex)
5854 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5857 this.AddNewTab(tabName, false, MyCommon.TabUsageType.SearchResults);
5858 this._statuses.AddTab(tabName, MyCommon.TabUsageType.SearchResults, null);
5860 var targetTab = this._statuses.Tabs[this._curTab.Text];
5862 Func<string, bool> stringComparer;
5865 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5867 catch (ArgumentException)
5869 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5873 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5874 if (foundIndices.Length == 0)
5876 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5880 var foundPosts = foundIndices.Select(x => targetTab[x]);
5882 var resultTab = this._statuses.Tabs[tabName];
5883 foreach (var post in foundPosts)
5885 resultTab.AddPostToInnerStorage(post);
5888 this._statuses.DistributePosts();
5889 this.RefreshTimeline();
5891 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5892 .First(x => x.Text == tabName);
5894 this.ListTab.SelectedTab = tabPage;
5899 searchOptions.Query,
5900 searchOptions.CaseSensitive,
5901 searchOptions.UseRegex,
5902 SEARCHTYPE.DialogSearch);
5905 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5907 this.AddNewTabForSearch(searchOptions.Query);
5911 /// <summary>発言検索に使用するメソッドを生成します</summary>
5912 /// <exception cref="ArgumentException">
5913 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"> が不正な正規表現な場合
5915 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5919 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5920 var regex = new Regex(query, regexOption);
5922 return x => regex.IsMatch(x);
5926 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5928 return x => x.IndexOf(query, comparisonType) != -1;
5932 private void AboutMenuItem_Click(object sender, EventArgs e)
5934 using (TweenAboutBox about = new TweenAboutBox())
5936 about.ShowDialog(this);
5938 this.TopMost = this._cfgCommon.AlwaysTop;
5941 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5943 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5945 DetailsListView lst = null;
5947 if (ImageSelector.Enabled)
5951 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5954 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5957 ListTab.SelectedIndex = i;
5958 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5959 //_curTab = ListTab.TabPages[i];
5964 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5965 if (idx == -1 && bgnIdx > 0)
5967 for (int i = 0; i < bgnIdx; i++)
5969 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5972 ListTab.SelectedIndex = i;
5973 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5974 //_curTab = ListTab.TabPages[i];
5980 //全部調べたが未読見つからず→先頭タブの最新発言へ
5983 ListTab.SelectedIndex = 0;
5984 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5985 //_curTab = ListTab.TabPages[0];
5986 if (_statuses.SortOrder == SortOrder.Ascending)
5987 idx = lst.VirtualListSize - 1;
5992 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5994 SelectListItem(lst, idx);
5995 if (_statuses.SortMode == ComparerMode.Id)
5997 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5998 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
6004 lst.EnsureVisible(idx);
6009 lst.EnsureVisible(idx);
6015 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
6017 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
6019 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6020 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
6024 private async void FavorareMenuItem_Click(object sender, EventArgs e)
6026 if (_curList.SelectedIndices.Count > 0)
6028 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6029 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
6033 private async void VerUpMenuItem_Click(object sender, EventArgs e)
6035 await this.CheckNewVersion(false);
6038 private void RunTweenUp()
6040 ProcessStartInfo pinfo = new ProcessStartInfo();
6041 pinfo.UseShellExecute = true;
6042 pinfo.WorkingDirectory = MyCommon.settingPath;
6043 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
6044 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
6047 Process.Start(pinfo);
6051 MessageBox.Show("Failed to execute TweenUp3.exe.");
6055 public class VersionInfo
6057 public Version Version { get; set; }
6058 public Uri DownloadUri { get; set; }
6059 public string ReleaseNote { get; set; }
6063 /// OpenTween の最新バージョンの情報を取得します
6065 public async Task<VersionInfo> GetVersionInfoAsync()
6067 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
6068 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
6070 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
6071 .ConfigureAwait(false);
6073 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
6074 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
6076 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
6077 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
6079 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
6081 return new VersionInfo
6083 Version = Version.Parse(msgHeader[0]),
6084 DownloadUri = new Uri(msgHeader[1]),
6085 ReleaseNote = msgBody,
6089 private async Task CheckNewVersion(bool startup = false)
6091 if (ApplicationSettings.VersionInfoUrl == null)
6092 return; // 更新チェック無効化
6096 var versionInfo = await this.GetVersionInfoAsync();
6098 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
6103 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
6104 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
6105 msgtext = MyCommon.ReplaceAppName(msgtext);
6107 MessageBox.Show(msgtext,
6108 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6109 MessageBoxButtons.OK, MessageBoxIcon.Information);
6114 using (var dialog = new UpdateDialog())
6116 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
6117 MyCommon.GetReadableVersion(versionInfo.Version));
6118 dialog.DetailsText = versionInfo.ReleaseNote;
6120 if (dialog.ShowDialog(this) == DialogResult.Yes)
6122 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
6128 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
6131 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
6132 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6133 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
6138 private async Task Colorize()
6141 await this.DispSelectedPost();
6142 //件数関連の場合、タイトル即時書き換え
6143 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
6144 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6145 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6146 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6148 SetMainWindowTitle();
6150 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6151 foreach (TabPage tb in ListTab.TabPages)
6153 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6155 if (this._cfgCommon.TabIconDisp)
6157 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6161 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
6164 public string createDetailHtml(string orgdata)
6166 if (this._cfgLocal.UseTwemoji)
6167 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
6169 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6172 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6174 if (sender.Equals(displayItem))
6176 this.ClearUserPicture();
6178 var img = displayItem.Image;
6182 img = await img.CloneAsync();
6184 UserPicture.Image = img;
6188 UserPicture.ShowErrorImage();
6193 private Task DispSelectedPost()
6195 return this.DispSelectedPost(false);
6198 private PostClass displayPost = new PostClass();
6201 /// サムネイル表示に使用する CancellationToken の生成元
6203 private CancellationTokenSource thumbnailTokenSource = null;
6205 private async Task DispSelectedPost(bool forceupdate)
6207 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6210 var oldDisplayPost = this.displayPost;
6211 this.displayPost = this._curPost;
6213 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6216 if (displayItem != null)
6218 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6221 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6222 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6224 using (ControlTransaction.Update(this.TableLayoutPanel1))
6226 SourceLinkLabel.Text = this._curPost.Source;
6227 SourceLinkLabel.Tag = this._curPost.SourceUri;
6228 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6234 nameText = "DM FROM <- ";
6236 nameText = "DM TO -> ";
6242 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6243 if (_curPost.RetweetedId != null)
6244 nameText += " (RT:" + _curPost.RetweetedBy + ")";
6246 NameLabel.Text = nameText;
6247 NameLabel.Tag = _curPost.ScreenName;
6249 var nameForeColor = SystemColors.ControlText;
6250 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6251 nameForeColor = this._clOWL;
6252 if (_curPost.RetweetedId != null)
6253 nameForeColor = this._clRetweet;
6255 nameForeColor = this._clFav;
6256 NameLabel.ForeColor = nameForeColor;
6258 this.ClearUserPicture();
6260 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6262 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6265 UserPicture.Image = image?.Clone();
6269 UserPicture.ShowErrorImage();
6273 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6276 if (DumpPostClassToolStripMenuItem.Checked)
6278 StringBuilder sb = new StringBuilder(512);
6280 sb.Append("-----Start PostClass Dump<br>");
6281 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
6282 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6283 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
6284 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
6285 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
6286 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
6287 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
6288 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
6289 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
6290 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
6291 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
6292 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
6293 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
6294 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
6295 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
6297 foreach (string nm in _curPost.ReplyToList)
6299 sb.AppendFormat("ReplyToList : {0}<br>", nm);
6302 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
6303 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
6304 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
6305 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
6306 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
6307 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
6308 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
6309 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
6310 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
6311 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
6313 sb.AppendFormat("Media.Count : {0}<br>", _curPost.Media.Count);
6314 if (_curPost.Media.Count > 0)
6316 for (int i = 0; i < _curPost.Media.Count; i++)
6318 var info = _curPost.Media[i];
6319 sb.AppendFormat("Media[{0}].Url : {1}<br>", i, info.Url);
6320 sb.AppendFormat("Media[{0}].VideoUrl : {1}<br>", i, info.VideoUrl ?? "---");
6323 sb.Append("-----End PostClass Dump<br>");
6325 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6329 var loadTasks = new List<Task>();
6331 // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6332 // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6333 if (_curPost.StatusId != oldDisplayPost.StatusId)
6335 using (ControlTransaction.Update(this.PostBrowser))
6337 this.PostBrowser.DocumentText =
6338 this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6340 this.PostBrowser.Document.Window.ScrollTo(0, 0);
6343 this.SplitContainer3.Panel2Collapsed = true;
6345 if (this._cfgCommon.PreviewEnable)
6347 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
6348 oldTokenSource?.Cancel();
6350 var token = this.thumbnailTokenSource.Token;
6351 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
6354 loadTasks.Add(this.AppendQuoteTweetAsync(this._curPost));
6359 await Task.WhenAll(loadTasks);
6361 catch (OperationCanceledException) { }
6365 /// 発言詳細欄のツイートURLを展開する
6367 private async Task AppendQuoteTweetAsync(PostClass post)
6369 var quoteStatusIds = post.QuoteStatusIds;
6370 if (quoteStatusIds.Length == 0 && post.InReplyToStatusId == null)
6374 var loadingQuoteHtml = quoteStatusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText, isReply: false));
6376 var loadingReplyHtml = string.Empty;
6377 if (post.InReplyToStatusId != null)
6378 loadingReplyHtml = FormatQuoteTweetHtml(post.InReplyToStatusId.Value, Properties.Resources.LoadingText, isReply: true);
6380 var body = post.Text + string.Concat(loadingQuoteHtml) + loadingReplyHtml;
6382 using (ControlTransaction.Update(this.PostBrowser))
6383 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6386 var loadTweetTasks = quoteStatusIds.Select(x => this.CreateQuoteTweetHtml(x, isReply: false)).ToList();
6388 if (post.InReplyToStatusId != null)
6389 loadTweetTasks.Add(this.CreateQuoteTweetHtml(post.InReplyToStatusId.Value, isReply: true));
6391 var quoteHtmls = await Task.WhenAll(loadTweetTasks);
6393 // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
6394 if (this._curPost != post || this._curPost.IsDeleted)
6397 body = post.Text + string.Concat(quoteHtmls);
6399 using (ControlTransaction.Update(this.PostBrowser))
6400 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6403 private async Task<string> CreateQuoteTweetHtml(long statusId, bool isReply)
6405 PostClass post = this._statuses[statusId];
6410 post = await Task.Run(() => this.tw.GetStatusApi(false, statusId))
6411 .ConfigureAwait(false);
6413 catch (WebApiException ex)
6415 return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode(ex.Message), isReply);
6419 if (!this._statuses.AddQuoteTweet(post))
6420 return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.", isReply);
6423 return FormatQuoteTweetHtml(post, isReply);
6426 internal static string FormatQuoteTweetHtml(PostClass post, bool isReply)
6428 var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
6429 " — " + WebUtility.HtmlEncode(post.Nickname) +
6430 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
6431 WebUtility.HtmlEncode(post.CreatedAt.ToString());
6433 return FormatQuoteTweetHtml(post.StatusId, innerHtml, isReply);
6436 internal static string FormatQuoteTweetHtml(long statusId, string innerHtml, bool isReply)
6438 var blockClassName = "quote-tweet";
6441 blockClassName += " reply";
6443 return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
6444 $"<blockquote class=\"{blockClassName}\">{innerHtml}</blockquote>" +
6449 /// 指定されたHTMLからリンクを除去します
6451 internal static string StripLinkTagHtml(string html)
6453 // a 要素はネストされていない前提の正規表現パターン
6454 return Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1");
6457 private async void MatomeMenuItem_Click(object sender, EventArgs e)
6459 await this.OpenApplicationWebsite();
6462 private async Task OpenApplicationWebsite()
6464 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
6467 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6469 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
6472 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
6474 if (ListTab.SelectedTab != null)
6476 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6478 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6479 if (pnl.Controls["comboSearch"].Focused ||
6480 pnl.Controls["comboLang"].Focused ||
6481 pnl.Controls["buttonSearch"].Focused) return;
6484 if (e.Control || e.Shift || e.Alt)
6485 this._anchorFlag = false;
6488 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
6491 e.SuppressKeyPress = true;
6494 if (asyncTask != null)
6499 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
6501 private void InitializeShortcuts()
6503 this.shortcutCommands = new[]
6505 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6506 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
6507 .FocusedOn(FocusedControl.ListTab)
6508 .Do(() => SendKeys.Send("{DOWN}")),
6510 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
6511 .FocusedOn(FocusedControl.ListTab)
6512 .Do(() => SendKeys.Send("{UP}")),
6514 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
6515 .FocusedOn(FocusedControl.ListTab)
6516 .Do(() => SendKeys.Send("{PGDN}")),
6518 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
6519 .FocusedOn(FocusedControl.ListTab)
6520 .Do(() => SendKeys.Send("{PGUP}")),
6522 ShortcutCommand.Create(Keys.F1)
6523 .Do(() => this.OpenApplicationWebsite()),
6525 ShortcutCommand.Create(Keys.F3)
6526 .Do(() => this.MenuItemSearchNext_Click(null, null)),
6528 ShortcutCommand.Create(Keys.F5)
6529 .Do(() => this.DoRefresh()),
6531 ShortcutCommand.Create(Keys.F6)
6532 .Do(() => this.GetReplyAsync()),
6534 ShortcutCommand.Create(Keys.F7)
6535 .Do(() => this.GetDirectMessagesAsync()),
6537 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
6538 .NotFocusedOn(FocusedControl.StatusText)
6539 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
6541 ShortcutCommand.Create(Keys.G)
6542 .NotFocusedOn(FocusedControl.StatusText)
6543 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
6545 ShortcutCommand.Create(Keys.Right, Keys.N)
6546 .FocusedOn(FocusedControl.ListTab)
6547 .Do(() => this.GoRelPost(forward: true)),
6549 ShortcutCommand.Create(Keys.Left, Keys.P)
6550 .FocusedOn(FocusedControl.ListTab)
6551 .Do(() => this.GoRelPost(forward: false)),
6553 ShortcutCommand.Create(Keys.OemPeriod)
6554 .FocusedOn(FocusedControl.ListTab)
6555 .Do(() => this.GoAnchor()),
6557 ShortcutCommand.Create(Keys.I)
6558 .FocusedOn(FocusedControl.ListTab)
6559 .OnlyWhen(() => this.StatusText.Enabled)
6560 .Do(() => this.StatusText.Focus()),
6562 ShortcutCommand.Create(Keys.Enter)
6563 .FocusedOn(FocusedControl.ListTab)
6564 .Do(() => this.MakeReplyOrDirectStatus()),
6566 ShortcutCommand.Create(Keys.R)
6567 .FocusedOn(FocusedControl.ListTab)
6568 .Do(() => this.DoRefresh()),
6570 ShortcutCommand.Create(Keys.L)
6571 .FocusedOn(FocusedControl.ListTab)
6572 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
6574 ShortcutCommand.Create(Keys.H)
6575 .FocusedOn(FocusedControl.ListTab)
6576 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6578 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6579 .FocusedOn(FocusedControl.ListTab)
6580 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6582 ShortcutCommand.Create(Keys.S)
6583 .FocusedOn(FocusedControl.ListTab)
6584 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6586 ShortcutCommand.Create(Keys.A)
6587 .FocusedOn(FocusedControl.ListTab)
6588 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6590 // ] in_reply_to参照元へ戻る
6591 ShortcutCommand.Create(Keys.Oem4)
6592 .FocusedOn(FocusedControl.ListTab)
6593 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6595 // [ in_reply_toへジャンプ
6596 ShortcutCommand.Create(Keys.Oem6)
6597 .FocusedOn(FocusedControl.ListTab)
6598 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6600 ShortcutCommand.Create(Keys.Escape)
6601 .FocusedOn(FocusedControl.ListTab)
6603 this._anchorFlag = false;
6604 if (ListTab.SelectedTab != null)
6606 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6607 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6609 var relTp = ListTab.SelectedTab;
6610 RemoveSpecifiedTab(relTp.Text, false);
6616 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
6617 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
6618 .FocusedOn(FocusedControl.ListTab)
6619 .Do(() => this._anchorFlag = false, preventDefault: false),
6621 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6622 ShortcutCommand.Create(Keys.Up, Keys.Down)
6623 .FocusedOn(FocusedControl.PostBrowser)
6626 ShortcutCommand.Create(Keys.Control | Keys.R)
6627 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6629 ShortcutCommand.Create(Keys.Control | Keys.D)
6630 .Do(() => this.doStatusDelete()),
6632 ShortcutCommand.Create(Keys.Control | Keys.M)
6633 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6635 ShortcutCommand.Create(Keys.Control | Keys.S)
6636 .Do(() => this.FavoriteChange(FavAdd: true)),
6638 ShortcutCommand.Create(Keys.Control | Keys.I)
6639 .Do(() => this.doRepliedStatusOpen()),
6641 ShortcutCommand.Create(Keys.Control | Keys.Q)
6642 .Do(() => this.doQuoteOfficial()),
6644 ShortcutCommand.Create(Keys.Control | Keys.B)
6645 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6647 ShortcutCommand.Create(Keys.Control | Keys.T)
6648 .Do(() => this.HashManageMenuItem_Click(null, null)),
6650 ShortcutCommand.Create(Keys.Control | Keys.L)
6651 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6653 ShortcutCommand.Create(Keys.Control | Keys.Y)
6654 .NotFocusedOn(FocusedControl.PostBrowser)
6655 .Do(() => this.MultiLineMenuItem_Click(null, null)),
6657 ShortcutCommand.Create(Keys.Control | Keys.F)
6658 .Do(() => this.MenuItemSubSearch_Click(null, null)),
6660 ShortcutCommand.Create(Keys.Control | Keys.U)
6661 .Do(() => this.ShowUserTimeline()),
6663 ShortcutCommand.Create(Keys.Control | Keys.H)
6664 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6666 ShortcutCommand.Create(Keys.Control | Keys.G)
6667 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6669 ShortcutCommand.Create(Keys.Control | Keys.O)
6670 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6672 ShortcutCommand.Create(Keys.Control | Keys.E)
6673 .Do(() => this.OpenURLMenuItem_Click(null, null)),
6675 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6676 .FocusedOn(FocusedControl.ListTab)
6677 .Do(() => this._colorize = true, preventDefault: false),
6679 ShortcutCommand.Create(Keys.Control | Keys.N)
6680 .FocusedOn(FocusedControl.ListTab)
6681 .Do(() => this.GoNextTab(forward: true)),
6683 ShortcutCommand.Create(Keys.Control | Keys.P)
6684 .FocusedOn(FocusedControl.ListTab)
6685 .Do(() => this.GoNextTab(forward: false)),
6687 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6688 .FocusedOn(FocusedControl.ListTab)
6689 .Do(() => this.CopyStot()),
6691 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6692 ShortcutCommand.Create(Keys.Control | Keys.D1)
6693 .FocusedOn(FocusedControl.ListTab)
6694 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6695 .Do(() => this.ListTab.SelectedIndex = 0),
6697 ShortcutCommand.Create(Keys.Control | Keys.D2)
6698 .FocusedOn(FocusedControl.ListTab)
6699 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6700 .Do(() => this.ListTab.SelectedIndex = 1),
6702 ShortcutCommand.Create(Keys.Control | Keys.D3)
6703 .FocusedOn(FocusedControl.ListTab)
6704 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6705 .Do(() => this.ListTab.SelectedIndex = 2),
6707 ShortcutCommand.Create(Keys.Control | Keys.D4)
6708 .FocusedOn(FocusedControl.ListTab)
6709 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6710 .Do(() => this.ListTab.SelectedIndex = 3),
6712 ShortcutCommand.Create(Keys.Control | Keys.D5)
6713 .FocusedOn(FocusedControl.ListTab)
6714 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6715 .Do(() => this.ListTab.SelectedIndex = 4),
6717 ShortcutCommand.Create(Keys.Control | Keys.D6)
6718 .FocusedOn(FocusedControl.ListTab)
6719 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6720 .Do(() => this.ListTab.SelectedIndex = 5),
6722 ShortcutCommand.Create(Keys.Control | Keys.D7)
6723 .FocusedOn(FocusedControl.ListTab)
6724 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6725 .Do(() => this.ListTab.SelectedIndex = 6),
6727 ShortcutCommand.Create(Keys.Control | Keys.D8)
6728 .FocusedOn(FocusedControl.ListTab)
6729 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6730 .Do(() => this.ListTab.SelectedIndex = 7),
6732 ShortcutCommand.Create(Keys.Control | Keys.D9)
6733 .FocusedOn(FocusedControl.ListTab)
6734 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6736 ShortcutCommand.Create(Keys.Control | Keys.A)
6737 .FocusedOn(FocusedControl.StatusText)
6738 .Do(() => this.StatusText.SelectAll()),
6740 ShortcutCommand.Create(Keys.Control | Keys.V)
6741 .FocusedOn(FocusedControl.StatusText)
6742 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6744 ShortcutCommand.Create(Keys.Control | Keys.Up)
6745 .FocusedOn(FocusedControl.StatusText)
6747 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6749 var inReplyToStatusId = this.inReplyTo?.Item1;
6750 var inReplyToScreenName = this.inReplyTo?.Item2;
6751 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6754 if (_hisIdx < 0) _hisIdx = 0;
6756 var historyItem = this._history[this._hisIdx];
6757 StatusText.Text = historyItem.status;
6758 StatusText.SelectionStart = StatusText.Text.Length;
6759 if (historyItem.inReplyToId != null)
6760 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6762 this.inReplyTo = null;
6765 ShortcutCommand.Create(Keys.Control | Keys.Down)
6766 .FocusedOn(FocusedControl.StatusText)
6768 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6770 var inReplyToStatusId = this.inReplyTo?.Item1;
6771 var inReplyToScreenName = this.inReplyTo?.Item2;
6772 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6775 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6777 var historyItem = this._history[this._hisIdx];
6778 StatusText.Text = historyItem.status;
6779 StatusText.SelectionStart = StatusText.Text.Length;
6780 if (historyItem.inReplyToId != null)
6781 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6783 this.inReplyTo = null;
6786 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6787 .FocusedOn(FocusedControl.StatusText)
6789 if (ListTab.SelectedIndex == 0)
6791 ListTab.SelectedIndex = ListTab.TabCount - 1;
6795 ListTab.SelectedIndex -= 1;
6800 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6801 .FocusedOn(FocusedControl.StatusText)
6803 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6805 ListTab.SelectedIndex = 0;
6809 ListTab.SelectedIndex += 1;
6814 ShortcutCommand.Create(Keys.Control | Keys.Y)
6815 .FocusedOn(FocusedControl.PostBrowser)
6817 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6818 MultiLineMenuItem_Click(null, null);
6821 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6822 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6824 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6825 .Do(() => this.DoRefreshMore()),
6827 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6828 .Do(() => this.GetReplyAsync(loadMore: true)),
6830 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6831 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6833 ShortcutCommand.Create(Keys.Shift | Keys.R)
6834 .NotFocusedOn(FocusedControl.StatusText)
6835 .Do(() => this.DoRefreshMore()),
6837 ShortcutCommand.Create(Keys.Shift | Keys.H)
6838 .FocusedOn(FocusedControl.ListTab)
6839 .Do(() => this.GoTopEnd(GoTop: true)),
6841 ShortcutCommand.Create(Keys.Shift | Keys.L)
6842 .FocusedOn(FocusedControl.ListTab)
6843 .Do(() => this.GoTopEnd(GoTop: false)),
6845 ShortcutCommand.Create(Keys.Shift | Keys.M)
6846 .FocusedOn(FocusedControl.ListTab)
6847 .Do(() => this.GoMiddle()),
6849 ShortcutCommand.Create(Keys.Shift | Keys.G)
6850 .FocusedOn(FocusedControl.ListTab)
6851 .Do(() => this.GoLast()),
6853 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6854 .FocusedOn(FocusedControl.ListTab)
6855 .Do(() => this.MoveMiddle()),
6857 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6858 .FocusedOn(FocusedControl.ListTab)
6859 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6861 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6862 .FocusedOn(FocusedControl.ListTab)
6863 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6865 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6866 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6867 .FocusedOn(FocusedControl.ListTab)
6868 .Do(() => this.GoFav(forward: true)),
6870 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6871 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6872 .FocusedOn(FocusedControl.ListTab)
6873 .Do(() => this.GoFav(forward: false)),
6875 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6876 .FocusedOn(FocusedControl.ListTab)
6877 .Do(() => this.GoBackSelectPostChain()),
6879 ShortcutCommand.Create(Keys.Alt | Keys.R)
6880 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6882 ShortcutCommand.Create(Keys.Alt | Keys.P)
6883 .OnlyWhen(() => this._curPost != null)
6884 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6886 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6887 .Do(() => this.ScrollDownPostBrowser(forward: false)),
6889 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6890 .Do(() => this.ScrollDownPostBrowser(forward: true)),
6892 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6893 .Do(() => this.PageDownPostBrowser(forward: false)),
6895 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6896 .Do(() => this.PageDownPostBrowser(forward: true)),
6898 // 別タブの同じ書き込みへ(ALT+←/→)
6899 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6900 .FocusedOn(FocusedControl.ListTab)
6901 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6903 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6904 .FocusedOn(FocusedControl.ListTab)
6905 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6907 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6908 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6910 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6911 .Do(() => this.CopyIdUri()),
6913 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6914 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6915 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6916 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6918 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6919 .Do(() => this.FavoriteChange(FavAdd: false)),
6921 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6922 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6924 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6925 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6927 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6928 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6930 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6931 .Do(() => this.doMoveToRTHome()),
6933 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6934 .Do(() => this.FavorareMenuItem_Click(null, null)),
6936 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6937 .FocusedOn(FocusedControl.StatusText)
6939 if (_curList != null && _curList.VirtualListSize != 0 &&
6940 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6942 var idx = _curList.SelectedIndices[0] - 1;
6943 SelectListItem(_curList, idx);
6944 _curList.EnsureVisible(idx);
6948 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6949 .FocusedOn(FocusedControl.StatusText)
6951 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6952 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6954 var idx = _curList.SelectedIndices[0] + 1;
6955 SelectListItem(_curList, idx);
6956 _curList.EnsureVisible(idx);
6960 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6961 .FocusedOn(FocusedControl.StatusText)
6963 if (StatusText.SelectionStart > 0)
6965 int endidx = StatusText.SelectionStart - 1;
6966 string startstr = "";
6967 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6969 char c = StatusText.Text[i];
6970 if (Char.IsLetterOrDigit(c) || c == '_')
6976 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6977 int cnt = AtIdSupl.ItemCount;
6978 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6979 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6983 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6984 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6994 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6995 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6996 .FocusedOn(FocusedControl.ListTab)
6997 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6999 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
7000 .FocusedOn(FocusedControl.ListTab)
7001 .Do(() => this.SetSortColumnByDisplayIndex(1)),
7003 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
7004 .FocusedOn(FocusedControl.ListTab)
7005 .Do(() => this.SetSortColumnByDisplayIndex(2)),
7007 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
7008 .FocusedOn(FocusedControl.ListTab)
7009 .Do(() => this.SetSortColumnByDisplayIndex(3)),
7011 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
7012 .FocusedOn(FocusedControl.ListTab)
7013 .Do(() => this.SetSortColumnByDisplayIndex(4)),
7015 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
7016 .FocusedOn(FocusedControl.ListTab)
7017 .Do(() => this.SetSortColumnByDisplayIndex(5)),
7019 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
7020 .FocusedOn(FocusedControl.ListTab)
7021 .Do(() => this.SetSortColumnByDisplayIndex(6)),
7023 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
7024 .FocusedOn(FocusedControl.ListTab)
7025 .Do(() => this.SetSortColumnByDisplayIndex(7)),
7027 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
7028 .FocusedOn(FocusedControl.ListTab)
7029 .Do(() => this.SetSortLastColumn()),
7031 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
7032 .Do(() => this.FavoritesRetweetOfficial()),
7034 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
7035 .Do(() => this.FavoritesRetweetUnofficial()),
7037 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
7038 .Do(() => this.OpenUserAppointUrl()),
7040 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7041 .FocusedOn(FocusedControl.PostBrowser)
7042 .Do(() => this.doReTweetUnofficial()),
7044 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
7045 .OnlyWhen(() => this.ExistCurrentPost)
7046 .Do(() => this.doTranslation(_curPost.TextFromApi)),
7048 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7049 .Do(() => this.doReTweetUnofficial()),
7051 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
7052 .Do(() => this.CopyUserId()),
7054 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
7055 .Do(() => this.tweetThumbnail1.ScrollUp()),
7057 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
7058 .Do(() => this.tweetThumbnail1.ScrollDown()),
7060 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
7061 .FocusedOn(FocusedControl.ListTab)
7062 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
7063 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
7067 private bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
7069 // Task を返す非同期処理があれば asyncTask に代入する
7072 // ShortcutCommand に対応しているコマンドはここで処理される
7073 foreach (var command in this.shortcutCommands)
7075 if (command.IsMatch(keyData, focusedOn))
7077 asyncTask = command.RunCommand();
7078 return command.PreventDefault;
7085 private void ScrollDownPostBrowser(bool forward)
7087 var doc = PostBrowser.Document;
7088 if (doc == null) return;
7090 var tags = doc.GetElementsByTagName("html");
7094 tags[0].ScrollTop += this._fntDetail.Height;
7096 tags[0].ScrollTop -= this._fntDetail.Height;
7100 private void PageDownPostBrowser(bool forward)
7102 var doc = PostBrowser.Document;
7103 if (doc == null) return;
7105 var tags = doc.GetElementsByTagName("html");
7109 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7111 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7115 private void GoNextTab(bool forward)
7117 int idx = ListTab.SelectedIndex;
7121 if (idx > ListTab.TabPages.Count - 1) idx = 0;
7126 if (idx < 0) idx = ListTab.TabPages.Count - 1;
7128 ListTab.SelectedIndex = idx;
7131 private void CopyStot()
7134 StringBuilder sb = new StringBuilder();
7135 bool IsProtected = false;
7137 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7138 foreach (int idx in _curList.SelectedIndices)
7140 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7146 if (post.IsDeleted) continue;
7149 if (post.RetweetedId != null)
7150 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7152 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7156 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7161 MessageBox.Show(Properties.Resources.CopyStotText1);
7165 clstr = sb.ToString();
7168 Clipboard.SetDataObject(clstr, false, 5, 100);
7170 catch (Exception ex)
7172 MessageBox.Show(ex.Message);
7177 private void CopyIdUri()
7180 StringBuilder sb = new StringBuilder();
7181 if (this._curTab == null) return;
7182 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7183 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7184 foreach (int idx in _curList.SelectedIndices)
7186 var post = _statuses.Tabs[_curTab.Text][idx];
7187 sb.Append(MyCommon.GetStatusUrl(post));
7188 sb.Append(Environment.NewLine);
7192 clstr = sb.ToString();
7195 Clipboard.SetDataObject(clstr, false, 5, 100);
7197 catch (Exception ex)
7199 MessageBox.Show(ex.Message);
7204 private void GoFav(bool forward)
7206 if (_curList.VirtualListSize == 0) return;
7213 if (_curList.SelectedIndices.Count == 0)
7219 fIdx = _curList.SelectedIndices[0] + 1;
7220 if (fIdx > _curList.VirtualListSize - 1) return;
7222 toIdx = _curList.VirtualListSize;
7227 if (_curList.SelectedIndices.Count == 0)
7229 fIdx = _curList.VirtualListSize - 1;
7233 fIdx = _curList.SelectedIndices[0] - 1;
7234 if (fIdx < 0) return;
7240 for (int idx = fIdx; idx != toIdx; idx += stp)
7242 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
7244 SelectListItem(_curList, idx);
7245 _curList.EnsureVisible(idx);
7251 private void GoSamePostToAnotherTab(bool left)
7253 if (_curList.VirtualListSize == 0) return;
7259 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7260 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7262 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7267 if (ListTab.SelectedIndex == 0)
7273 fIdx = ListTab.SelectedIndex - 1;
7281 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7287 fIdx = ListTab.SelectedIndex + 1;
7289 toIdx = ListTab.TabCount;
7294 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7296 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7297 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7299 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
7301 ListTab.SelectedIndex = tabidx;
7302 SelectListItem(_curList, idx);
7303 _curList.EnsureVisible(idx);
7312 private void GoPost(bool forward)
7314 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7321 fIdx = _curList.SelectedIndices[0] + 1;
7322 if (fIdx > _curList.VirtualListSize - 1) return;
7323 toIdx = _curList.VirtualListSize;
7328 fIdx = _curList.SelectedIndices[0] - 1;
7329 if (fIdx < 0) return;
7335 if (_curPost.RetweetedId == null)
7337 name = _curPost.ScreenName;
7341 name = _curPost.RetweetedBy;
7343 for (int idx = fIdx; idx != toIdx; idx += stp)
7345 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
7347 if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
7349 SelectListItem(_curList, idx);
7350 _curList.EnsureVisible(idx);
7356 if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
7358 SelectListItem(_curList, idx);
7359 _curList.EnsureVisible(idx);
7366 private void GoRelPost(bool forward)
7368 if (_curList.SelectedIndices.Count == 0) return;
7375 fIdx = _curList.SelectedIndices[0] + 1;
7376 if (fIdx > _curList.VirtualListSize - 1) return;
7377 toIdx = _curList.VirtualListSize;
7382 fIdx = _curList.SelectedIndices[0] - 1;
7383 if (fIdx < 0) return;
7390 if (_curPost == null) return;
7391 _anchorPost = _curPost;
7396 if (_anchorPost == null) return;
7399 for (int idx = fIdx; idx != toIdx; idx += stp)
7401 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7402 if (post.ScreenName == _anchorPost.ScreenName ||
7403 post.RetweetedBy == _anchorPost.ScreenName ||
7404 post.ScreenName == _anchorPost.RetweetedBy ||
7405 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7406 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
7407 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
7408 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
7409 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
7411 SelectListItem(_curList, idx);
7412 _curList.EnsureVisible(idx);
7418 private void GoAnchor()
7420 if (_anchorPost == null) return;
7421 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7422 if (idx == -1) return;
7424 SelectListItem(_curList, idx);
7425 _curList.EnsureVisible(idx);
7428 private void GoTopEnd(bool GoTop)
7430 if (_curList.VirtualListSize == 0)
7438 _item = _curList.GetItemAt(0, 25);
7446 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7448 idx = _curList.VirtualListSize - 1;
7452 SelectListItem(_curList, idx);
7455 private void GoMiddle()
7457 if (_curList.VirtualListSize == 0)
7465 _item = _curList.GetItemAt(0, 0);
7475 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7478 idx2 = _curList.VirtualListSize - 1;
7484 idx3 = (idx1 + idx2) / 2;
7486 SelectListItem(_curList, idx3);
7489 private void GoLast()
7491 if (_curList.VirtualListSize == 0) return;
7493 if (_statuses.SortOrder == SortOrder.Ascending)
7495 SelectListItem(_curList, _curList.VirtualListSize - 1);
7496 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7500 SelectListItem(_curList, 0);
7501 _curList.EnsureVisible(0);
7505 private void MoveTop()
7507 if (_curList.SelectedIndices.Count == 0) return;
7508 int idx = _curList.SelectedIndices[0];
7509 if (_statuses.SortOrder == SortOrder.Ascending)
7511 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7515 _curList.EnsureVisible(0);
7517 _curList.EnsureVisible(idx);
7520 private async Task GoInReplyToPostTree()
7522 if (_curPost == null) return;
7524 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7526 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7530 var post = tw.GetStatusApi(false, _curPost.StatusId);
7532 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7533 _curPost.InReplyToUser = post.InReplyToUser;
7534 _curPost.IsReply = post.IsReply;
7535 this.PurgeListViewItemCache();
7536 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7538 catch (WebApiException ex)
7540 this.StatusLabel.Text = ex.Message;
7544 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7546 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7548 replyChains = new Stack<ReplyChain>();
7550 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7553 string inReplyToTabName;
7554 long inReplyToId = _curPost.InReplyToStatusId.Value;
7555 string inReplyToUser = _curPost.InReplyToUser;
7556 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7558 var inReplyToPosts = from tab in _statuses.Tabs.Values
7559 orderby tab != curTabClass
7560 from post in tab.Posts.Values
7561 where post.StatusId == inReplyToId
7562 let index = tab.IndexOf(post.StatusId)
7564 select new {Tab = tab, Index = index};
7566 var inReplyPost = inReplyToPosts.FirstOrDefault();
7567 if (inReplyPost == null)
7571 await Task.Run(() =>
7573 var post = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value);
7576 _statuses.AddPost(post);
7577 _statuses.DistributePosts();
7580 catch (WebApiException ex)
7582 this.StatusLabel.Text = ex.Message;
7583 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7587 this.RefreshTimeline();
7589 inReplyPost = inReplyToPosts.FirstOrDefault();
7590 if (inReplyPost == null)
7592 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7596 inReplyToTabName = inReplyPost.Tab.TabName;
7597 inReplyToIndex = inReplyPost.Index;
7599 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7600 DetailsListView listView = (DetailsListView)tabPage.Tag;
7602 if (_curTab != tabPage)
7604 this.ListTab.SelectTab(tabPage);
7607 this.SelectListItem(listView, inReplyToIndex);
7608 listView.EnsureVisible(inReplyToIndex);
7611 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7613 if (_curPost == null) return;
7615 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7616 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7620 if (_curPost.InReplyToStatusId != null)
7622 var posts = from t in _statuses.Tabs
7623 from p in t.Value.Posts
7624 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7625 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7627 orderby isForward ? indexOf : indexOf * -1
7628 orderby t.Value != curTabClass
7629 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7632 var postList = posts.ToList();
7633 for (int i = postList.Count - 1; i >= 0; i--)
7636 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7638 postList.RemoveAt(index);
7641 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7642 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7643 if (post == null) post = postList.First();
7644 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7645 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7646 SelectListItem(listView, post.Index);
7647 listView.EnsureVisible(post.Index);
7649 catch (InvalidOperationException)
7657 if (replyChains == null || replyChains.Count < 1)
7659 var posts = from t in _statuses.Tabs
7660 from p in t.Value.Posts
7661 where p.Value.InReplyToStatusId == _curPost.StatusId
7662 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7665 orderby t.Value != curTabClass
7666 select new {Tab = t.Value, Index = indexOf};
7669 var post = posts.First();
7670 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7671 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7672 SelectListItem(listView, post.Index);
7673 listView.EnsureVisible(post.Index);
7675 catch (InvalidOperationException)
7682 ReplyChain chainHead = replyChains.Pop();
7683 if (chainHead.InReplyToId == _curPost.StatusId)
7685 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7694 ListTab.SelectTab(chainHead.OriginalTab);
7700 SelectListItem(_curList, idx);
7701 _curList.EnsureVisible(idx);
7707 this.GoBackInReplyToPostTree(parallel);
7713 private void GoBackSelectPostChain()
7715 if (this.selectPostChains.Count > 1)
7724 this.selectPostChains.Pop();
7725 var tabPostPair = this.selectPostChains.Peek();
7727 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7729 if (tabPostPair.Item2 != null)
7731 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7732 if (idx == -1) continue; //該当ポストが存在しないので無視
7735 tp = tabPostPair.Item1;
7737 this.selectPostChains.Pop();
7739 catch (InvalidOperationException)
7745 while (this.selectPostChains.Count > 1);
7750 //履歴が残り1つであればクリアしておく
7751 if (this.selectPostChains.Count == 1)
7752 this.selectPostChains.Clear();
7756 DetailsListView lst = (DetailsListView)tp.Tag;
7757 this.ListTab.SelectedTab = tp;
7760 SelectListItem(lst, idx);
7761 lst.EnsureVisible(idx);
7767 private void PushSelectPostChain()
7769 int count = this.selectPostChains.Count;
7772 var p = this.selectPostChains.Peek();
7773 if (p.Item1 == this._curTab)
7775 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7776 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7779 if (count >= 2500) TrimPostChain();
7780 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7783 private void TrimPostChain()
7785 if (this.selectPostChains.Count <= 2000) return;
7786 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7787 for (int i = 0; i < 2000; i++)
7789 p.Push(this.selectPostChains.Pop());
7791 this.selectPostChains.Clear();
7792 for (int i = 0; i < 2000; i++)
7794 this.selectPostChains.Push(p.Pop());
7798 private bool GoStatus(long statusId)
7800 if (statusId == 0) return false;
7801 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7803 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7805 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7806 ListTab.SelectedIndex = tabidx;
7807 SelectListItem(_curList, idx);
7808 _curList.EnsureVisible(idx);
7815 private bool GoDirectMessage(long statusId)
7817 if (statusId == 0) return false;
7818 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7820 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7822 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7823 ListTab.SelectedIndex = tabidx;
7824 SelectListItem(_curList, idx);
7825 _curList.EnsureVisible(idx);
7832 private void MyList_MouseClick(object sender, MouseEventArgs e)
7834 _anchorFlag = false;
7837 private void StatusText_Enter(object sender, EventArgs e)
7839 // フォーカスの戻り先を StatusText に設定
7840 this.Tag = StatusText;
7841 StatusText.BackColor = _clInputBackcolor;
7844 public Color InputBackColor
7846 get { return _clInputBackcolor; }
7847 set { _clInputBackcolor = value; }
7850 private void StatusText_Leave(object sender, EventArgs e)
7852 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7853 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7854 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7857 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7860 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7863 e.SuppressKeyPress = true;
7866 this.StatusText_TextChanged(null, null);
7868 if (asyncTask != null)
7872 private void SaveConfigsAll(bool ifModified)
7876 SaveConfigsCommon();
7883 if (ModifySettingCommon) SaveConfigsCommon();
7884 if (ModifySettingLocal) SaveConfigsLocal();
7885 if (ModifySettingAtId) SaveConfigsAtId();
7889 private void SaveConfigsAtId()
7891 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7893 ModifySettingAtId = false;
7894 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7898 private void SaveConfigsCommon()
7900 if (_ignoreConfigSave) return;
7902 ModifySettingCommon = false;
7905 _cfgCommon.UserName = tw.Username;
7906 _cfgCommon.UserId = tw.UserId;
7907 _cfgCommon.Password = tw.Password;
7908 _cfgCommon.Token = tw.AccessToken;
7909 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7911 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7912 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7914 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7917 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7918 switch (_statuses.SortMode)
7920 case ComparerMode.Nickname: //ニックネーム
7921 _cfgCommon.SortColumn = 1;
7923 case ComparerMode.Data: //本文
7924 _cfgCommon.SortColumn = 2;
7926 case ComparerMode.Id: //時刻=発言Id
7927 _cfgCommon.SortColumn = 3;
7929 case ComparerMode.Name: //名前
7930 _cfgCommon.SortColumn = 4;
7932 case ComparerMode.Source: //Source
7933 _cfgCommon.SortColumn = 7;
7937 _cfgCommon.HashTags = HashMgr.HashHistories;
7938 if (HashMgr.IsPermanent)
7940 _cfgCommon.HashSelected = HashMgr.UseHash;
7944 _cfgCommon.HashSelected = "";
7946 _cfgCommon.HashIsHead = HashMgr.IsHead;
7947 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7948 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7949 if (ToolStripFocusLockMenuItem != null &&
7950 ToolStripFocusLockMenuItem.IsDisposed == false)
7952 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7954 _cfgCommon.TrackWord = tw.TrackWord;
7955 _cfgCommon.AllAtReply = tw.AllAtReply;
7956 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7957 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7963 private void SaveConfigsLocal()
7965 if (_ignoreConfigSave) return;
7968 ModifySettingLocal = false;
7969 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7970 _cfgLocal.FormSize = _mySize;
7971 _cfgLocal.FormLocation = _myLoc;
7972 _cfgLocal.SplitterDistance = _mySpDis;
7973 _cfgLocal.PreviewDistance = _mySpDis3;
7974 _cfgLocal.StatusMultiline = StatusText.Multiline;
7975 _cfgLocal.StatusTextHeight = _mySpDis2;
7977 _cfgLocal.FontUnread = _fntUnread;
7978 _cfgLocal.ColorUnread = _clUnread;
7979 _cfgLocal.FontRead = _fntReaded;
7980 _cfgLocal.ColorRead = _clReaded;
7981 _cfgLocal.FontDetail = _fntDetail;
7982 _cfgLocal.ColorDetail = _clDetail;
7983 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7984 _cfgLocal.ColorDetailLink = _clDetailLink;
7985 _cfgLocal.ColorFav = _clFav;
7986 _cfgLocal.ColorOWL = _clOWL;
7987 _cfgLocal.ColorRetweet = _clRetweet;
7988 _cfgLocal.ColorSelf = _clSelf;
7989 _cfgLocal.ColorAtSelf = _clAtSelf;
7990 _cfgLocal.ColorTarget = _clTarget;
7991 _cfgLocal.ColorAtTarget = _clAtTarget;
7992 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7993 _cfgLocal.ColorAtTo = _clAtTo;
7994 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7995 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7996 _cfgLocal.ColorInputFont = _clInputFont;
7997 _cfgLocal.FontInputFont = _fntInputFont;
7999 if (_ignoreConfigSave) return;
8004 private void SaveConfigsTabs()
8006 SettingTabs tabSetting = new SettingTabs();
8007 for (int i = 0; i < ListTab.TabPages.Count; i++)
8009 var tab = _statuses.Tabs[ListTab.TabPages[i].Text];
8010 if (tab.TabType != MyCommon.TabUsageType.Related && tab.TabType != MyCommon.TabUsageType.SearchResults)
8011 tabSetting.Tabs.Add(tab);
8013 tabSetting.Tabs.Add(this._statuses.GetTabByType(MyCommon.TabUsageType.Mute));
8017 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
8020 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
8021 if (ret != DialogResult.OK)
8024 var match = Twitter.StatusUrlRegex.Match(inputText);
8027 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
8028 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8034 var statusId = long.Parse(match.Groups["StatusId"].Value);
8035 await this.OpenRelatedTab(statusId);
8037 catch (TabException ex)
8039 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8043 private void SaveLogMenuItem_Click(object sender, EventArgs e)
8045 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8046 Properties.Resources.SaveLogMenuItem_ClickText2,
8047 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8048 if (rslt == DialogResult.Cancel) return;
8050 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8051 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8052 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8053 SaveFileDialog1.FilterIndex = 0;
8054 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8055 SaveFileDialog1.RestoreDirectory = true;
8057 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8059 if (!SaveFileDialog1.ValidateNames) return;
8060 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8062 if (rslt == DialogResult.Yes)
8065 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8067 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8068 string protect = "";
8069 if (post.IsProtect) protect = "Protect";
8070 sw.WriteLine(post.Nickname + "\t" +
8071 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8072 post.CreatedAt.ToString() + "\t" +
8073 post.ScreenName + "\t" +
8074 post.StatusId.ToString() + "\t" +
8075 post.ImageUrl + "\t" +
8076 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8082 foreach (int idx in _curList.SelectedIndices)
8084 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8085 string protect = "";
8086 if (post.IsProtect) protect = "Protect";
8087 sw.WriteLine(post.Nickname + "\t" +
8088 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8089 post.CreatedAt.ToString() + "\t" +
8090 post.ScreenName + "\t" +
8091 post.StatusId.ToString() + "\t" +
8092 post.ImageUrl + "\t" +
8093 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8099 this.TopMost = this._cfgCommon.AlwaysTop;
8102 private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8105 bool KeyRes = CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out asyncTask);
8108 e.IsInputKey = true;
8112 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
8114 var shortcut = (Shortcut)e.KeyData;
8117 case Shortcut.CtrlA:
8118 case Shortcut.CtrlC:
8119 case Shortcut.CtrlIns:
8123 // その他のショートカットキーは無効にする
8124 e.IsInputKey = true;
8130 if (asyncTask != null)
8133 public bool TabRename(ref string tabName)
8136 string newTabText = null;
8137 using (InputTabName inputName = new InputTabName())
8139 inputName.TabName = tabName;
8140 inputName.ShowDialog();
8141 if (inputName.DialogResult == DialogResult.Cancel) return false;
8142 newTabText = inputName.TabName;
8144 this.TopMost = this._cfgCommon.AlwaysTop;
8145 if (!string.IsNullOrEmpty(newTabText))
8148 for (int i = 0; i < ListTab.TabCount; i++)
8150 if (ListTab.TabPages[i].Text == newTabText)
8152 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8153 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8158 for (int i = 0; i < ListTab.TabCount; i++)
8160 if (ListTab.TabPages[i].Text == tabName)
8162 ListTab.TabPages[i].Text = newTabText;
8166 _statuses.RenameTab(tabName, newTabText);
8168 SaveConfigsCommon();
8170 _rclickTabName = newTabText;
8171 tabName = newTabText;
8180 private void ListTab_MouseClick(object sender, MouseEventArgs e)
8182 if (e.Button == MouseButtons.Middle)
8184 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8186 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8188 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8189 this.SaveConfigsTabs();
8196 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8198 string tn = ListTab.SelectedTab.Text;
8202 private void ListTab_MouseDown(object sender, MouseEventArgs e)
8204 if (this._cfgCommon.TabMouseLock) return;
8205 Point cpos = new Point(e.X, e.Y);
8206 if (e.Button == MouseButtons.Left)
8208 for (int i = 0; i < ListTab.TabPages.Count; i++)
8210 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8213 _tabMouseDownPoint = e.Location;
8224 private void ListTab_DragEnter(object sender, DragEventArgs e)
8226 if (e.Data.GetDataPresent(typeof(TabPage)))
8227 e.Effect = DragDropEffects.Move;
8229 e.Effect = DragDropEffects.None;
8232 private void ListTab_DragDrop(object sender, DragEventArgs e)
8234 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8239 Point cpos = new Point(e.X, e.Y);
8240 Point spos = ListTab.PointToClient(cpos);
8242 for (i = 0; i < ListTab.TabPages.Count; i++)
8244 Rectangle rect = ListTab.GetTabRect(i);
8245 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8246 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8248 tn = ListTab.TabPages[i].Text;
8249 if (spos.X <= (rect.Left + rect.Right) / 2)
8258 //タブのないところにドロップ->最後尾へ移動
8259 if (string.IsNullOrEmpty(tn))
8261 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8263 i = ListTab.TabPages.Count - 1;
8266 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8267 if (tp.Text == tn) return;
8269 ReOrderTab(tp.Text, tn, bef);
8272 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8274 var baseIndex = this.GetTabPageIndex(baseTabText);
8275 if (baseIndex == -1)
8278 var targetIndex = this.GetTabPageIndex(targetTabText);
8279 if (targetIndex == -1)
8282 using (ControlTransaction.Layout(this.ListTab))
8284 var mTp = this.ListTab.TabPages[targetIndex];
8285 this.ListTab.TabPages.Remove(mTp);
8287 if (targetIndex < baseIndex)
8290 if (isBeforeBaseTab)
8291 ListTab.TabPages.Insert(baseIndex, mTp);
8293 ListTab.TabPages.Insert(baseIndex + 1, mTp);
8299 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8301 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8302 //isReply:true=@,false=DM
8303 if (!StatusText.Enabled) return;
8304 if (_curList == null) return;
8305 if (_curTab == null) return;
8306 if (!this.ExistCurrentPost) return;
8308 // 複数あてリプライはReplyではなく通常ポスト
8309 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8310 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8311 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8313 if (_curList.SelectedIndices.Count > 0)
8316 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8319 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8322 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8323 StatusText.SelectionStart = StatusText.Text.Length;
8325 this.inReplyTo = null;
8328 if (string.IsNullOrEmpty(StatusText.Text))
8332 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8333 StatusText.Text = "@" + _curPost.ScreenName + " ";
8335 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8336 var inReplyToScreenName = this._curPost.ScreenName;
8337 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8345 //1件選んでEnter or DoubleClick
8346 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8348 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
8351 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8352 var inReplyToScreenName = this._curPost.ScreenName;
8353 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8357 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
8360 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8363 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8364 this.inReplyTo = null;
8369 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8370 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8371 var inReplyToScreenName = this._curPost.ScreenName;
8372 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8379 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8380 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8381 this.inReplyTo = null;
8386 //1件選んでCtrl-Rの場合(返信先操作せず)
8387 int sidx = StatusText.SelectionStart;
8388 string id = "@" + _curPost.ScreenName + " ";
8391 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8396 StatusText.Text = StatusText.Text.Insert(sidx, id);
8398 //if (StatusText.Text.StartsWith("@"))
8401 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8402 // sidx += 5 + _curPost.ScreenName.Length;
8407 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8408 // sidx += 3 + _curPost.ScreenName.Length;
8410 StatusText.SelectionStart = sidx;
8413 //_reply_to_name = null;
8421 if (!isAuto && !isReply) return;
8423 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8427 //Enter or DoubleClick
8429 string sTxt = StatusText.Text;
8430 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
8433 this.inReplyTo = null;
8435 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8437 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8438 if (!sTxt.Contains("@" + post.ScreenName + " "))
8440 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8441 //sTxt = "@" + post.ScreenName + " " + sTxt;
8444 StatusText.Text = sTxt;
8449 if (_curList.SelectedIndices.Count > 1)
8454 int sidx = StatusText.SelectionStart;
8455 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8457 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8458 if (!ids.Contains("@" + post.ScreenName + " ") &&
8459 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8461 ids += "@" + post.ScreenName + " ";
8465 foreach (string nm in post.ReplyToList)
8467 if (!ids.Contains("@" + nm + " ") &&
8468 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8470 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8472 ids += "@" + m.Result("${id}") + " ";
8474 ids += "@" + nm + " ";
8479 if (ids.Length == 0) return;
8480 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8482 StatusText.Text = ". " + StatusText.Text;
8484 this.inReplyTo = null;
8488 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8493 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8495 //if (StatusText.Text.StartsWith("@"))
8497 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8498 // sidx += 2 + ids.Length;
8502 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8503 // sidx += 1 + ids.Length;
8505 StatusText.SelectionStart = sidx;
8511 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8514 int sidx = StatusText.SelectionStart;
8515 PostClass post = _curPost;
8516 if (!ids.Contains("@" + post.ScreenName + " ") &&
8517 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8519 ids += "@" + post.ScreenName + " ";
8521 foreach (string nm in post.ReplyToList)
8523 if (!ids.Contains("@" + nm + " ") &&
8524 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8526 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8528 ids += "@" + m.Result("${id}") + " ";
8530 ids += "@" + nm + " ";
8533 if (!string.IsNullOrEmpty(post.RetweetedBy))
8535 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8536 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8538 ids += "@" + post.RetweetedBy + " ";
8541 if (ids.Length == 0) return;
8542 if (string.IsNullOrEmpty(StatusText.Text))
8545 StatusText.Text = ids;
8546 StatusText.SelectionStart = ids.Length;
8549 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8550 var inReplyToScreenName = this._curPost.ScreenName;
8551 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8557 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8562 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8564 StatusText.SelectionStart = sidx;
8570 StatusText.SelectionStart = StatusText.Text.Length;
8575 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8580 private static int iconCnt = 0;
8581 private static int blinkCnt = 0;
8582 private static bool blink = false;
8583 private static bool idle = false;
8585 private async Task RefreshTasktrayIcon()
8588 await this.Colorize();
8590 if (!TimerRefreshIcon.Enabled) return;
8591 //Static usCheckCnt As int = 0
8593 //Static iconDlListTopItem As ListViewItem = null
8595 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8596 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8598 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8600 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8606 //if (usCheckCnt > 300) //1min
8609 // if (!this.IsReceivedUserStream)
8611 // TraceOut("ReconnectUserStream");
8612 // tw.ReconnectUserStream();
8616 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8618 if (iconCnt >= this.NIconRefresh.Length)
8626 SaveConfigsAll(true);
8631 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8633 _myStatusError = false;
8637 TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8638 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8640 if (blinkCnt > 0) return;
8642 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8644 NotifyIcon1.Icon = ReplyIcon;
8648 NotifyIcon1.Icon = ReplyIconBlink;
8656 //優先度:エラー→オフライン→アイドル
8660 NotifyIcon1.Icon = NIconAtRed;
8663 if (_myStatusOnline)
8665 NotifyIcon1.Icon = NIconAt;
8669 NotifyIcon1.Icon = NIconAtSmoke;
8673 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8676 await this.RefreshTasktrayIcon();
8679 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8681 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8682 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8684 if (ListTab != null && ListTab.SelectedTab != null)
8685 _rclickTabName = ListTab.SelectedTab.Text;
8690 if (_statuses == null) return;
8691 if (_statuses.Tabs == null) return;
8693 TabClass tb = _statuses.Tabs[_rclickTabName];
8694 if (tb == null) return;
8696 NotifyDispMenuItem.Checked = tb.Notify;
8697 this.NotifyTbMenuItem.Checked = tb.Notify;
8699 soundfileListup = true;
8700 SoundFileComboBox.Items.Clear();
8701 this.SoundFileTbComboBox.Items.Clear();
8702 SoundFileComboBox.Items.Add("");
8703 this.SoundFileTbComboBox.Items.Add("");
8704 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8705 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8707 oDir = oDir.GetDirectories("Sounds")[0];
8709 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8711 SoundFileComboBox.Items.Add(oFile.Name);
8712 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8714 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8715 if (idx == -1) idx = 0;
8716 SoundFileComboBox.SelectedIndex = idx;
8717 this.SoundFileTbComboBox.SelectedIndex = idx;
8718 soundfileListup = false;
8719 UreadManageMenuItem.Checked = tb.UnreadManage;
8720 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8722 TabMenuControl(_rclickTabName);
8725 private void TabMenuControl(string tabName)
8727 var tabInfo = _statuses.GetTabByName(tabName);
8729 this.FilterEditMenuItem.Enabled = true;
8730 this.EditRuleTbMenuItem.Enabled = true;
8732 if (tabInfo.IsDefaultTabType)
8734 this.ProtectTabMenuItem.Enabled = false;
8735 this.ProtectTbMenuItem.Enabled = false;
8739 this.ProtectTabMenuItem.Enabled = true;
8740 this.ProtectTbMenuItem.Enabled = true;
8743 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8745 this.ProtectTabMenuItem.Checked = true;
8746 this.ProtectTbMenuItem.Checked = true;
8747 this.DeleteTabMenuItem.Enabled = false;
8748 this.DeleteTbMenuItem.Enabled = false;
8752 this.ProtectTabMenuItem.Checked = false;
8753 this.ProtectTbMenuItem.Checked = false;
8754 this.DeleteTabMenuItem.Enabled = true;
8755 this.DeleteTbMenuItem.Enabled = true;
8759 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8761 var checkState = ((ToolStripMenuItem)sender).Checked;
8764 this.ProtectTbMenuItem.Checked = checkState;
8765 this.ProtectTabMenuItem.Checked = checkState;
8768 this.DeleteTabMenuItem.Enabled = !checkState;
8769 this.DeleteTbMenuItem.Enabled = !checkState;
8771 if (string.IsNullOrEmpty(_rclickTabName)) return;
8772 _statuses.Tabs[_rclickTabName].Protected = checkState;
8777 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8779 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8780 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8782 if (string.IsNullOrEmpty(_rclickTabName)) return;
8783 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8788 public void ChangeTabUnreadManage(string tabName, bool isManage)
8790 var idx = this.GetTabPageIndex(tabName);
8794 _statuses.Tabs[tabName].UnreadManage = isManage;
8795 if (this._cfgCommon.TabIconDisp)
8797 if (_statuses.Tabs[tabName].UnreadCount > 0)
8798 ListTab.TabPages[idx].ImageIndex = 0;
8800 ListTab.TabPages[idx].ImageIndex = -1;
8803 if (_curTab.Text == tabName)
8805 this.PurgeListViewItemCache();
8809 SetMainWindowTitle();
8810 SetStatusLabelUrl();
8811 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8814 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8816 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8817 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8819 if (string.IsNullOrEmpty(_rclickTabName)) return;
8821 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8826 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8828 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8830 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8835 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8837 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8839 RemoveSpecifiedTab(_rclickTabName, true);
8843 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8845 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8847 using (var fltDialog = new FilterDialog())
8849 fltDialog.Owner = this;
8850 fltDialog.SetCurrent(_rclickTabName);
8851 fltDialog.ShowDialog(this);
8853 this.TopMost = this._cfgCommon.AlwaysTop;
8855 this.ApplyPostFilters();
8859 private void AddTabMenuItem_Click(object sender, EventArgs e)
8861 string tabName = null;
8862 MyCommon.TabUsageType tabUsage;
8863 using (InputTabName inputName = new InputTabName())
8865 inputName.TabName = _statuses.MakeTabName("MyTab");
8866 inputName.IsShowUsage = true;
8867 inputName.ShowDialog();
8868 if (inputName.DialogResult == DialogResult.Cancel) return;
8869 tabName = inputName.TabName;
8870 tabUsage = inputName.Usage;
8872 this.TopMost = this._cfgCommon.AlwaysTop;
8873 if (!string.IsNullOrEmpty(tabName))
8876 ListElement list = null;
8877 if (tabUsage == MyCommon.TabUsageType.Lists)
8879 using (ListAvailable listAvail = new ListAvailable())
8881 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8882 if (listAvail.SelectedList == null) return;
8883 list = listAvail.SelectedList;
8886 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8888 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8889 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8895 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8897 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8898 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8900 if (tabUsage == MyCommon.TabUsageType.Lists)
8902 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8903 var tab = this._statuses.Tabs[this._curTab.Text];
8904 this.GetListTimelineAsync(tab);
8910 private void TabMenuItem_Click(object sender, EventArgs e)
8912 using (var fltDialog = new FilterDialog())
8914 fltDialog.Owner = this;
8917 foreach (int idx in _curList.SelectedIndices)
8921 if (!SelectTab(out tabName)) return;
8923 fltDialog.SetCurrent(tabName);
8924 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8926 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8930 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8932 fltDialog.ShowDialog(this);
8933 this.TopMost = this._cfgCommon.AlwaysTop;
8937 this.ApplyPostFilters();
8939 if (this.ListTab.SelectedTab != null &&
8940 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8942 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8946 protected override bool ProcessDialogKey(Keys keyData)
8948 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8949 if ((keyData & Keys.KeyCode) == Keys.Enter)
8951 if (StatusText.Focused)
8953 bool _NewLine = false;
8956 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8958 if (StatusText.Multiline)
8960 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8962 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8966 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8970 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8972 if (StatusText.Multiline)
8974 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8976 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8980 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8986 if (StatusText.Multiline)
8988 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8990 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8991 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8995 if (((keyData & Keys.Shift) == Keys.Shift) ||
8996 (((keyData & Keys.Control) != Keys.Control) &&
8997 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
9003 int pos1 = StatusText.SelectionStart;
9004 if (StatusText.SelectionLength > 0)
9006 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
9008 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
9009 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
9014 PostButton_Click(null, null);
9018 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
9019 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
9020 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
9022 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
9027 return base.ProcessDialogKey(keyData);
9030 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9032 MakeReplyOrDirectStatus(false, true, true);
9035 private void IDRuleMenuItem_Click(object sender, EventArgs e)
9040 if (_curList.SelectedIndices.Count == 0) return;
9043 if (!SelectTab(out tabName)) return;
9045 var tab = this._statuses.Tabs[tabName];
9049 if (tab.TabType != MyCommon.TabUsageType.Mute)
9051 this.MoveOrCopy(out mv, out mk);
9055 // ミュートタブでは常に MoveMatches を true にする
9060 List<string> ids = new List<string>();
9061 foreach (int idx in _curList.SelectedIndices)
9063 PostClass post = _statuses.Tabs[_curTab.Text][idx];
9064 if (!ids.Contains(post.ScreenName))
9066 PostFilterRule fc = new PostFilterRule();
9067 ids.Add(post.ScreenName);
9068 if (post.RetweetedId == null)
9070 fc.FilterName = post.ScreenName;
9074 fc.FilterName = post.RetweetedBy;
9076 fc.UseNameField = true;
9077 fc.MoveMatches = mv;
9078 fc.MarkMatches = mk;
9079 fc.UseRegex = false;
9080 fc.FilterByUrl = false;
9086 List<string> atids = new List<string>();
9087 foreach (string id in ids)
9089 atids.Add("@" + id);
9091 int cnt = AtIdSupl.ItemCount;
9092 AtIdSupl.AddRangeItem(atids.ToArray());
9093 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
9096 this.ApplyPostFilters();
9100 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
9102 if (this._curList.SelectedIndices.Count == 0)
9105 // タブ選択ダイアログを表示(or追加)
9107 if (!this.SelectTab(out tabName))
9110 var currentTab = this._statuses.Tabs[this._curTab.Text];
9111 var filterTab = this._statuses.Tabs[tabName];
9115 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
9117 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
9118 this.MoveOrCopy(out mv, out mk);
9122 // ミュートタブでは常に MoveMatches を true にする
9127 // 振り分けルールに追加するSource
9128 var sources = new HashSet<string>();
9130 foreach (var idx in this._curList.SelectedIndices.Cast<int>())
9132 var post = currentTab[idx];
9133 var filterSource = post.Source;
9135 if (sources.Add(filterSource))
9137 var filter = new PostFilterRule
9139 FilterSource = filterSource,
9143 FilterByUrl = false,
9145 filterTab.AddFilter(filter);
9149 this.ApplyPostFilters();
9150 this.SaveConfigsTabs();
9153 private bool SelectTab(out string tabName)
9160 using (var dialog = new TabsDialog(_statuses))
9162 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9164 var selectedTab = dialog.SelectedTab;
9165 tabName = selectedTab == null ? null : selectedTab.TabName;
9168 ListTab.SelectedTab.Focus();
9170 if (tabName == null)
9172 using (InputTabName inputName = new InputTabName())
9174 inputName.TabName = _statuses.MakeTabName("MyTab");
9175 inputName.ShowDialog();
9176 if (inputName.DialogResult == DialogResult.Cancel) return false;
9177 tabName = inputName.TabName;
9179 this.TopMost = this._cfgCommon.AlwaysTop;
9180 if (!string.IsNullOrEmpty(tabName))
9182 if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9184 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9185 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9203 private void MoveOrCopy(out bool move, out bool mark)
9207 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9208 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9216 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9217 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9227 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9232 private void CopyURLMenuItem_Click(object sender, EventArgs e)
9237 private void SelectAllMenuItem_Click(object sender, EventArgs e)
9239 if (StatusText.Focused)
9242 StatusText.SelectAll();
9246 // ListView上でのCtrl+A
9247 NativeMethods.SelectAllItems(this._curList);
9251 private void MoveMiddle()
9257 if (_curList.SelectedIndices.Count == 0) return;
9259 int idx = _curList.SelectedIndices[0];
9261 _item = _curList.GetItemAt(0, 25);
9267 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9269 idx2 = _curList.VirtualListSize - 1;
9273 idx -= Math.Abs(idx1 - idx2) / 2;
9274 if (idx < 0) idx = 0;
9276 _curList.EnsureVisible(_curList.VirtualListSize - 1);
9277 _curList.EnsureVisible(idx);
9280 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
9282 var linkElements = this.PostBrowser.Document.Links.Cast<HtmlElement>()
9283 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
9286 if (linkElements.Length > 0)
9288 UrlDialog.ClearUrl();
9290 string openUrlStr = "";
9292 if (linkElements.Length == 1)
9294 // ツイートに含まれる URL が 1 つのみの場合
9295 // => OpenURL ダイアログを表示せずにリンクを開く
9300 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
9302 catch (ArgumentException)
9311 if (string.IsNullOrEmpty(urlStr)) return;
9312 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9314 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
9315 await this.OpenUriAsync(new Uri(openUrlStr));
9319 // ツイートに含まれる URL が複数ある場合
9320 // => OpenURL を表示しユーザーが選択したリンクを開く
9322 foreach (var linkElm in linkElements)
9325 string linkText = "";
9329 urlStr = linkElm.GetAttribute("title");
9330 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9331 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9332 linkText = linkElm.InnerText;
9334 catch (ArgumentException)
9343 if (string.IsNullOrEmpty(urlStr)) continue;
9344 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9348 if (UrlDialog.ShowDialog() == DialogResult.OK)
9350 openUrlStr = UrlDialog.SelectedUrl;
9352 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
9353 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
9360 this.TopMost = this._cfgCommon.AlwaysTop;
9365 private void ClearTabMenuItem_Click(object sender, EventArgs e)
9367 if (string.IsNullOrEmpty(_rclickTabName)) return;
9368 ClearTab(_rclickTabName, true);
9371 private void ClearTab(string tabName, bool showWarning)
9375 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9376 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9382 _statuses.ClearTabIds(tabName);
9383 if (ListTab.SelectedTab.Text == tabName)
9386 _anchorFlag = false;
9387 this.PurgeListViewItemCache();
9391 foreach (TabPage tb in ListTab.TabPages)
9393 if (tb.Text == tabName)
9396 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9400 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9402 SetMainWindowTitle();
9403 SetStatusLabelUrl();
9406 private static long followers = 0;
9408 private void SetMainWindowTitle()
9411 StringBuilder ttl = new StringBuilder(256);
9414 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9415 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9416 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9417 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9419 foreach (var tab in _statuses.Tabs.Values)
9421 ur += tab.UnreadCount;
9426 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9427 ttl.Append(Application.ProductName);
9429 switch (this._cfgCommon.DispLatestPost)
9431 case MyCommon.DispTitleEnum.Ver:
9432 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9434 case MyCommon.DispTitleEnum.Post:
9435 if (_history != null && _history.Count > 1)
9436 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9438 case MyCommon.DispTitleEnum.UnreadRepCount:
9439 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9441 case MyCommon.DispTitleEnum.UnreadAllCount:
9442 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9444 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9445 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9447 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9448 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9450 case MyCommon.DispTitleEnum.OwnStatus:
9451 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9452 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9458 this.Text = ttl.ToString();
9460 catch (AccessViolationException)
9462 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9466 private string GetStatusLabelText()
9469 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9470 if (_statuses == null) return "";
9471 TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9472 TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9473 if (tbRep == null || tbDm == null) return "";
9474 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9479 StringBuilder slbl = new StringBuilder(256);
9482 foreach (var tab in _statuses.Tabs.Values)
9484 ur += tab.UnreadCount;
9486 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9488 tur = tab.UnreadCount;
9499 UnreadAtCounter = urat;
9501 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9502 if (this._cfgCommon.TimelinePeriod == 0)
9504 slbl.Append(Properties.Resources.SetStatusLabelText2);
9508 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9510 return slbl.ToString();
9513 private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9517 if (this.InvokeRequired && !this.IsDisposed)
9519 this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9523 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9524 SetApiStatusLabel(endpointName);
9527 catch (ObjectDisposedException)
9531 catch (InvalidOperationException)
9537 private void SetApiStatusLabel(string endpointName = null)
9539 if (_curTab == null)
9541 this.toolStripApiGauge.ApiEndpoint = null;
9545 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9547 if (endpointName == null)
9552 case MyCommon.TabUsageType.Home:
9553 case MyCommon.TabUsageType.UserDefined:
9554 endpointName = "/statuses/home_timeline";
9557 case MyCommon.TabUsageType.Mentions:
9558 endpointName = "/statuses/mentions_timeline";
9561 case MyCommon.TabUsageType.Favorites:
9562 endpointName = "/favorites/list";
9565 case MyCommon.TabUsageType.DirectMessage:
9566 endpointName = "/direct_messages";
9569 case MyCommon.TabUsageType.UserTimeline:
9570 endpointName = "/statuses/user_timeline";
9573 case MyCommon.TabUsageType.Lists:
9574 endpointName = "/lists/statuses";
9577 case MyCommon.TabUsageType.PublicSearch:
9578 endpointName = "/search/tweets";
9581 case MyCommon.TabUsageType.Related:
9582 endpointName = "/statuses/show/:id";
9589 this.toolStripApiGauge.ApiEndpoint = endpointName;
9593 // 表示中のタブに関連する endpoint であれば更新
9596 switch (endpointName)
9598 case "/statuses/home_timeline":
9599 update = tabType == MyCommon.TabUsageType.Home ||
9600 tabType == MyCommon.TabUsageType.UserDefined;
9603 case "/statuses/mentions_timeline":
9604 update = tabType == MyCommon.TabUsageType.Mentions;
9607 case "/favorites/list":
9608 update = tabType == MyCommon.TabUsageType.Favorites;
9611 case "/direct_messages:":
9612 update = tabType == MyCommon.TabUsageType.DirectMessage;
9615 case "/statuses/user_timeline":
9616 update = tabType == MyCommon.TabUsageType.UserTimeline;
9619 case "/lists/statuses":
9620 update = tabType == MyCommon.TabUsageType.Lists;
9623 case "/search/tweets":
9624 update = tabType == MyCommon.TabUsageType.PublicSearch;
9627 case "/statuses/show/:id":
9628 update = tabType == MyCommon.TabUsageType.Related;
9637 this.toolStripApiGauge.ApiEndpoint = endpointName;
9643 private void SetStatusLabelUrl()
9645 StatusLabelUrl.Text = GetStatusLabelText();
9648 public void SetStatusLabel(string text)
9650 StatusLabel.Text = text;
9653 private static StringBuilder ur = new StringBuilder(64);
9655 private void SetNotifyIconText()
9657 // タスクトレイアイコンのツールチップテキスト書き換え
9659 ur.Remove(0, ur.Length);
9660 if (this._cfgCommon.DispUsername)
9662 ur.Append(tw.Username);
9665 ur.Append(Application.ProductName);
9667 ur.Append("(Debug Build)");
9669 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9672 ur.Append(UnreadCounter);
9674 ur.Append(UnreadAtCounter);
9677 NotifyIcon1.Text = ur.ToString();
9680 internal void CheckReplyTo(string StatusText)
9684 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9686 foreach (Match hm in m)
9688 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9690 hstr += "#" + hm.Result("$3") + " ";
9691 HashSupl.AddItem("#" + hm.Result("$3"));
9694 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9696 hstr += HashMgr.UseHash;
9698 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9700 // 本当にリプライ先指定すべきかどうかの判定
9701 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9703 if (this._cfgCommon.UseAtIdSupplement)
9705 int bCnt = AtIdSupl.ItemCount;
9706 foreach (Match mid in m)
9708 AtIdSupl.AddItem(mid.Result("${id}"));
9710 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9713 // リプライ先ステータスIDの指定がない場合は指定しない
9714 if (this.inReplyTo == null)
9718 // 次の条件を満たす場合に in_reply_to_status_id 指定
9719 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9720 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9721 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9725 var inReplyToScreenName = this.inReplyTo.Item2;
9726 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9728 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9732 foreach (Match mid in m)
9734 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9739 this.inReplyTo = null;
9742 private void TweenMain_Resize(object sender, EventArgs e)
9744 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9746 this.Visible = false;
9748 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9750 // 現在の DPI と設定保存時の DPI との比を取得する
9751 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9753 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9754 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9755 this.DesktopLocation = _cfgLocal.FormLocation;
9756 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9759 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9760 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9761 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9763 this.SplitContainer1.SplitterDistance = splitterDistance;
9767 StatusText.Multiline = _cfgLocal.StatusMultiline;
9768 if (StatusText.Multiline)
9770 var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9771 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9772 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9774 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9776 StatusText.Height = statusTextHeight;
9780 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9782 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9786 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9787 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9789 this.SplitContainer3.SplitterDistance = previewDistance;
9792 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9793 this.SplitContainer3.Panel2Collapsed = true;
9795 _initialLayout = false;
9797 if (this.WindowState != FormWindowState.Minimized)
9799 _formWindowState = this.WindowState;
9803 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9805 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9806 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9807 if (PlaySoundMenuItem.Checked)
9809 this._cfgCommon.PlaySound = true;
9813 this._cfgCommon.PlaySound = false;
9815 ModifySettingCommon = true;
9818 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9820 if (this._initialLayout)
9823 int splitterDistance;
9824 switch (this.WindowState)
9826 case FormWindowState.Normal:
9827 splitterDistance = this.SplitContainer1.SplitterDistance;
9829 case FormWindowState.Maximized:
9830 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9831 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9832 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9833 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9839 this._mySpDis = splitterDistance;
9840 this.ModifySettingLocal = true;
9843 private async Task doRepliedStatusOpen()
9845 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9847 if (MyCommon.IsKeyDown(Keys.Shift))
9849 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9852 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9854 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9855 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9859 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9861 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9862 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9863 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9866 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9871 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9873 await this.doRepliedStatusOpen();
9877 /// UserPicture.Image に設定されている画像を破棄します。
9879 private void ClearUserPicture()
9881 if (this.UserPicture.Image != null)
9883 var oldImage = this.UserPicture.Image;
9884 this.UserPicture.Image = null;
9889 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9891 //発言詳細のアイコン右クリック時のメニュー制御
9892 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9894 string name = _curPost.ImageUrl;
9895 if (name != null && name.Length > 0)
9897 int idx = name.LastIndexOf('/');
9900 name = Path.GetFileName(name.Substring(idx));
9901 if (name.Contains("_normal.") || name.EndsWith("_normal", StringComparison.Ordinal))
9903 name = name.Replace("_normal", "");
9904 this.IconNameToolStripMenuItem.Text = name;
9905 this.IconNameToolStripMenuItem.Enabled = true;
9909 this.IconNameToolStripMenuItem.Enabled = false;
9910 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9915 this.IconNameToolStripMenuItem.Enabled = false;
9916 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9919 this.ReloadIconToolStripMenuItem.Enabled = true;
9921 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9923 this.SaveIconPictureToolStripMenuItem.Enabled = true;
9927 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9932 this.IconNameToolStripMenuItem.Enabled = false;
9933 this.ReloadIconToolStripMenuItem.Enabled = false;
9934 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9935 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9940 this.IconNameToolStripMenuItem.Enabled = false;
9941 this.ReloadIconToolStripMenuItem.Enabled = false;
9942 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9943 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9945 if (NameLabel.Tag != null)
9947 string id = (string)NameLabel.Tag;
9948 if (id == tw.Username)
9950 FollowToolStripMenuItem.Enabled = false;
9951 UnFollowToolStripMenuItem.Enabled = false;
9952 ShowFriendShipToolStripMenuItem.Enabled = false;
9953 ShowUserStatusToolStripMenuItem.Enabled = true;
9954 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9955 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9956 ListManageUserContextToolStripMenuItem3.Enabled = true;
9960 FollowToolStripMenuItem.Enabled = true;
9961 UnFollowToolStripMenuItem.Enabled = true;
9962 ShowFriendShipToolStripMenuItem.Enabled = true;
9963 ShowUserStatusToolStripMenuItem.Enabled = true;
9964 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9965 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9966 ListManageUserContextToolStripMenuItem3.Enabled = true;
9971 FollowToolStripMenuItem.Enabled = false;
9972 UnFollowToolStripMenuItem.Enabled = false;
9973 ShowFriendShipToolStripMenuItem.Enabled = false;
9974 ShowUserStatusToolStripMenuItem.Enabled = false;
9975 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9976 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9977 ListManageUserContextToolStripMenuItem3.Enabled = false;
9981 private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9983 if (_curPost == null) return;
9984 string name = _curPost.ImageUrl;
9985 await this.OpenUriInBrowserAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9988 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9990 if (this._curPost == null) return;
9992 await this.UserPicture.SetImageFromTask(async () =>
9994 var imageUrl = this._curPost.ImageUrl;
9996 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
9997 .ConfigureAwait(false);
9999 return await image.CloneAsync()
10000 .ConfigureAwait(false);
10004 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10006 if (_curPost == null) return;
10007 string name = _curPost.ImageUrl;
10008 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
10010 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
10012 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10018 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10020 if (_curPost == null) return;
10021 string name = _curPost.ImageUrl;
10023 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
10025 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10029 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
10031 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
10033 using (Graphics g = Graphics.FromImage(bmp2))
10035 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
10036 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
10038 bmp2.Save(this.SaveFileDialog1.FileName);
10044 //処理中にキャッシュアウトする可能性あり
10049 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
10051 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
10052 if (multiline != this.StatusText.Multiline)
10054 this.StatusText.Multiline = multiline;
10055 MultiLineMenuItem.Checked = multiline;
10056 ModifySettingLocal = true;
10060 private void StatusText_MultilineChanged(object sender, EventArgs e)
10062 if (this.StatusText.Multiline)
10063 this.StatusText.ScrollBars = ScrollBars.Vertical;
10065 this.StatusText.ScrollBars = ScrollBars.None;
10067 ModifySettingLocal = true;
10070 private void MultiLineMenuItem_Click(object sender, EventArgs e)
10073 StatusText.Multiline = MultiLineMenuItem.Checked;
10074 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
10075 if (MultiLineMenuItem.Checked)
10077 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
10078 SplitContainer2.SplitterDistance = 0;
10080 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
10084 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
10086 ModifySettingLocal = true;
10089 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
10091 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
10092 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
10094 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
10095 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
10096 //Appendix A. Collected ABNF for URI
10097 //http://www.ietf.org/rfc/rfc3986.txt
10099 string result = "";
10101 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
10103 if (StatusText.SelectionLength > 0)
10105 string tmp = StatusText.SelectedText;
10106 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
10107 if (tmp.StartsWith("http"))
10109 // 文字列が選択されている場合はその文字列について処理
10111 //nico.ms使用、nicovideoにマッチしたら変換
10112 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10114 result = nicoms.Shorten(tmp);
10116 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10118 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10121 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10122 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10123 result = resultUri.AbsoluteUri;
10125 catch (WebApiException e)
10127 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10130 catch (UriFormatException e)
10132 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10141 if (!string.IsNullOrEmpty(result))
10143 urlUndo undotmp = new urlUndo();
10145 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
10146 StatusText.SelectedText = result;
10149 undotmp.Before = tmp;
10150 undotmp.After = result;
10152 if (urlUndoBuffer == null)
10154 urlUndoBuffer = new List<urlUndo>();
10155 UrlUndoToolStripMenuItem.Enabled = true;
10158 urlUndoBuffer.Add(undotmp);
10164 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
10165 @"(?<url>(?<protocol>https?://)" +
10166 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
10167 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
10168 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
10169 // 正規表現にマッチしたURL文字列をtinyurl化
10170 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
10172 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
10173 string tmp = mt.Result("${url}");
10174 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
10175 urlUndo undotmp = new urlUndo();
10178 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10180 //nico.ms使用、nicovideoにマッチしたら変換
10181 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10183 result = nicoms.Shorten(tmp);
10185 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10187 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10190 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10191 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10192 result = resultUri.AbsoluteUri;
10194 catch (HttpRequestException e)
10196 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
10197 // のように長いので「:」が含まれていればそれ以降のみを抽出する
10198 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
10200 this.StatusLabel.Text = Converter_Type + ":" + message;
10203 catch (WebApiException e)
10205 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10208 catch (UriFormatException e)
10210 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10219 if (!string.IsNullOrEmpty(result))
10221 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10222 StatusText.SelectedText = result;
10224 undotmp.Before = mt.Result("${url}");
10225 undotmp.After = result;
10227 if (urlUndoBuffer == null)
10229 urlUndoBuffer = new List<urlUndo>();
10230 UrlUndoToolStripMenuItem.Enabled = true;
10233 urlUndoBuffer.Add(undotmp);
10241 private void doUrlUndo()
10243 if (urlUndoBuffer != null)
10245 string tmp = StatusText.Text;
10246 foreach (urlUndo data in urlUndoBuffer)
10248 tmp = tmp.Replace(data.After, data.Before);
10250 StatusText.Text = tmp;
10251 urlUndoBuffer = null;
10252 UrlUndoToolStripMenuItem.Enabled = false;
10253 StatusText.SelectionStart = 0;
10254 StatusText.SelectionLength = 0;
10258 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10260 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10263 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10265 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10268 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10270 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10273 private async void UxnuMenuItem_Click(object sender, EventArgs e)
10275 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10278 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10280 if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
10282 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
10283 Random rnd = new Random();
10284 // 前回使用した短縮URLサービス以外を選択する
10287 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10289 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10290 await UrlConvertAsync(svc);
10294 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10299 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10301 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10302 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10303 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10304 ModifySettingCommon = true;
10307 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10309 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10310 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10311 _cfgCommon.ListLock = ListLockMenuItem.Checked;
10312 ModifySettingCommon = true;
10315 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10317 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10318 MenuStrip1.Tag = new Object();
10319 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10322 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10324 if (this.Tag != null) // 設定された戻り先へ遷移
10326 if (this.Tag == this.ListTab.SelectedTab)
10327 ((Control)this.ListTab.SelectedTab.Tag).Select();
10329 ((Control)this.Tag).Select();
10331 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10333 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10335 this.Tag = ListTab.SelectedTab.Tag;
10336 ((Control)this.Tag).Select();
10339 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10340 MenuStrip1.Tag = null;
10343 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10345 DetailsListView lst = (DetailsListView)sender;
10346 if (_cfgLocal == null) return;
10350 _cfgLocal.Width1 = lst.Columns[0].Width;
10351 _cfgLocal.Width3 = lst.Columns[1].Width;
10355 int[] darr = new int[lst.Columns.Count];
10356 for (int i = 0; i < lst.Columns.Count; i++)
10358 darr[lst.Columns[i].DisplayIndex] = i;
10360 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10362 for (int i = 0; i < lst.Columns.Count; i++)
10367 _cfgLocal.DisplayIndex1 = i;
10370 _cfgLocal.DisplayIndex2 = i;
10373 _cfgLocal.DisplayIndex3 = i;
10376 _cfgLocal.DisplayIndex4 = i;
10379 _cfgLocal.DisplayIndex5 = i;
10382 _cfgLocal.DisplayIndex6 = i;
10385 _cfgLocal.DisplayIndex7 = i;
10388 _cfgLocal.DisplayIndex8 = i;
10392 _cfgLocal.Width1 = lst.Columns[0].Width;
10393 _cfgLocal.Width2 = lst.Columns[1].Width;
10394 _cfgLocal.Width3 = lst.Columns[2].Width;
10395 _cfgLocal.Width4 = lst.Columns[3].Width;
10396 _cfgLocal.Width5 = lst.Columns[4].Width;
10397 _cfgLocal.Width6 = lst.Columns[5].Width;
10398 _cfgLocal.Width7 = lst.Columns[6].Width;
10399 _cfgLocal.Width8 = lst.Columns[7].Width;
10401 ModifySettingLocal = true;
10402 _isColumnChanged = true;
10405 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10407 DetailsListView lst = (DetailsListView)sender;
10408 if (_cfgLocal == null) return;
10411 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10413 _cfgLocal.Width1 = lst.Columns[0].Width;
10414 ModifySettingLocal = true;
10415 _isColumnChanged = true;
10417 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10419 _cfgLocal.Width3 = lst.Columns[1].Width;
10420 ModifySettingLocal = true;
10421 _isColumnChanged = true;
10426 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10428 _cfgLocal.Width1 = lst.Columns[0].Width;
10429 ModifySettingLocal = true;
10430 _isColumnChanged = true;
10432 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10434 _cfgLocal.Width2 = lst.Columns[1].Width;
10435 ModifySettingLocal = true;
10436 _isColumnChanged = true;
10438 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10440 _cfgLocal.Width3 = lst.Columns[2].Width;
10441 ModifySettingLocal = true;
10442 _isColumnChanged = true;
10444 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10446 _cfgLocal.Width4 = lst.Columns[3].Width;
10447 ModifySettingLocal = true;
10448 _isColumnChanged = true;
10450 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10452 _cfgLocal.Width5 = lst.Columns[4].Width;
10453 ModifySettingLocal = true;
10454 _isColumnChanged = true;
10456 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10458 _cfgLocal.Width6 = lst.Columns[5].Width;
10459 ModifySettingLocal = true;
10460 _isColumnChanged = true;
10462 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10464 _cfgLocal.Width7 = lst.Columns[6].Width;
10465 ModifySettingLocal = true;
10466 _isColumnChanged = true;
10468 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10470 _cfgLocal.Width8 = lst.Columns[7].Width;
10471 ModifySettingLocal = true;
10472 _isColumnChanged = true;
10475 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10478 // SaveConfigsLocal();
10482 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10485 string _selText = this.PostBrowser.GetSelectedText();
10488 Clipboard.SetDataObject(_selText, false, 5, 100);
10490 catch (Exception ex)
10492 MessageBox.Show(ex.Message);
10496 private async Task doSearchToolStrip(string url)
10498 //発言詳細で「選択文字列で検索」(選択文字列取得)
10499 string _selText = this.PostBrowser.GetSelectedText();
10501 if (_selText != null)
10503 if (url == Properties.Resources.SearchItem4Url)
10506 AddNewTabForSearch(_selText);
10510 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10511 await this.OpenUriInBrowserAsync(tmp);
10515 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10518 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10521 private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10523 await this.doSearchToolStrip(Properties.Resources.SearchItem1Url);
10526 private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10528 await this.doSearchToolStrip(Properties.Resources.SearchItem2Url);
10531 private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10533 await this.doSearchToolStrip(Properties.Resources.SearchItem4Url);
10536 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10540 foreach (var link in this.PostBrowser.Document.Links.Cast<HtmlElement>())
10542 if (link.GetAttribute("href") == this._postBrowserStatusText)
10544 var linkStr = link.GetAttribute("title");
10545 if (string.IsNullOrEmpty(linkStr))
10546 linkStr = link.GetAttribute("href");
10548 Clipboard.SetDataObject(linkStr, false, 5, 100);
10553 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10555 catch (Exception ex)
10557 MessageBox.Show(ex.Message);
10561 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10563 // URLコピーの項目の表示/非表示
10564 if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal))
10566 this._postBrowserStatusText = PostBrowser.StatusText;
10567 string name = GetUserId();
10568 UrlCopyContextMenuItem.Enabled = true;
10571 FollowContextMenuItem.Enabled = true;
10572 RemoveContextMenuItem.Enabled = true;
10573 FriendshipContextMenuItem.Enabled = true;
10574 ShowUserStatusContextMenuItem.Enabled = true;
10575 SearchPostsDetailToolStripMenuItem.Enabled = true;
10576 IdFilterAddMenuItem.Enabled = true;
10577 ListManageUserContextToolStripMenuItem.Enabled = true;
10578 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10582 FollowContextMenuItem.Enabled = false;
10583 RemoveContextMenuItem.Enabled = false;
10584 FriendshipContextMenuItem.Enabled = false;
10585 ShowUserStatusContextMenuItem.Enabled = false;
10586 SearchPostsDetailToolStripMenuItem.Enabled = false;
10587 IdFilterAddMenuItem.Enabled = false;
10588 ListManageUserContextToolStripMenuItem.Enabled = false;
10589 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10592 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10593 UseHashtagMenuItem.Enabled = true;
10595 UseHashtagMenuItem.Enabled = false;
10599 this._postBrowserStatusText = "";
10600 UrlCopyContextMenuItem.Enabled = false;
10601 FollowContextMenuItem.Enabled = false;
10602 RemoveContextMenuItem.Enabled = false;
10603 FriendshipContextMenuItem.Enabled = false;
10604 ShowUserStatusContextMenuItem.Enabled = false;
10605 SearchPostsDetailToolStripMenuItem.Enabled = false;
10606 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10607 UseHashtagMenuItem.Enabled = false;
10608 IdFilterAddMenuItem.Enabled = false;
10609 ListManageUserContextToolStripMenuItem.Enabled = false;
10611 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10612 string _selText = this.PostBrowser.GetSelectedText();
10613 if (_selText == null)
10615 SelectionSearchContextMenuItem.Enabled = false;
10616 SelectionCopyContextMenuItem.Enabled = false;
10617 SelectionTranslationToolStripMenuItem.Enabled = false;
10621 SelectionSearchContextMenuItem.Enabled = true;
10622 SelectionCopyContextMenuItem.Enabled = true;
10623 SelectionTranslationToolStripMenuItem.Enabled = true;
10625 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10626 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10627 bool fAllFlag = false;
10628 foreach (Match mu in ma)
10630 if (mu.Result("${ScreenName}").ToLowerInvariant() != tw.Username.ToLowerInvariant())
10636 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10638 if (_curPost == null)
10639 TranslationToolStripMenuItem.Enabled = false;
10641 TranslationToolStripMenuItem.Enabled = true;
10646 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10648 //発言詳細の選択文字列で現在のタブを検索
10649 string _selText = this.PostBrowser.GetSelectedText();
10651 if (_selText != null)
10653 var searchOptions = new SearchWordDialog.SearchOptions(
10654 SearchWordDialog.SearchType.Timeline,
10657 caseSensitive: false,
10660 this.SearchDialog.ResultOptions = searchOptions;
10663 searchOptions.Query,
10664 searchOptions.CaseSensitive,
10665 searchOptions.UseRegex,
10666 SEARCHTYPE.NextSearch);
10670 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10672 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10673 ModifySettingLocal = true;
10676 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10678 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10680 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10682 SelectMedia_DragDrop(e);
10685 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10687 var url = GetUrlFromDataObject(e.Data);
10690 if (url.Item2 == null)
10691 appendText = url.Item1;
10693 appendText = url.Item2 + " " + url.Item1;
10695 if (this.StatusText.TextLength == 0)
10696 this.StatusText.Text = appendText;
10698 this.StatusText.Text += " " + appendText;
10700 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10702 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10704 this.StatusText.Text += text;
10706 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10708 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10709 if (data != null) StatusText.Text += data;
10714 /// IDataObject から URL とタイトルの対を取得します
10717 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10719 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10720 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10721 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10723 if (data.GetDataPresent("text/x-moz-url"))
10725 // Firefox, Google Chrome で利用可能
10726 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10728 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10730 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10731 if (lines.Length < 2)
10732 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
10734 return new Tuple<string, string>(lines[0], lines[1]);
10737 else if (data.GetDataPresent("IESiteModeToUrl"))
10739 // Internet Exproler 用
10740 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10742 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10744 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10745 if (lines.Length < 2)
10746 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
10748 return new Tuple<string, string>(lines[0], lines[1]);
10751 else if (data.GetDataPresent("UniformResourceLocatorW"))
10755 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10757 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10758 return new Tuple<string, string>(url, null);
10762 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10765 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10767 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10769 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10771 SelectMedia_DragEnter(e);
10775 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10777 e.Effect = DragDropEffects.Copy;
10780 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10782 e.Effect = DragDropEffects.Copy;
10785 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10787 e.Effect = DragDropEffects.Copy;
10791 e.Effect = DragDropEffects.None;
10794 private void TweenMain_DragOver(object sender, DragEventArgs e)
10798 public bool IsNetworkAvailable()
10801 nw = MyCommon.IsNetworkAvailable();
10802 _myStatusOnline = nw;
10806 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
10808 var uriStr = uri.AbsoluteUri;
10810 // OpenTween 内部で使用する URL
10811 if (uri.Authority == "opentween")
10813 await this.OpenInternalUriAsync(uri);
10817 // ハッシュタグを含む Twitter 検索
10818 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
10820 // ハッシュタグの場合は、タブで開く
10821 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
10822 var pos = unescapedQuery.IndexOf('#');
10823 if (pos == -1) return;
10825 var hash = unescapedQuery.Substring(pos);
10826 this.HashSupl.AddItem(hash);
10827 this.HashMgr.AddHashToHistory(hash.Trim(), false);
10828 this.AddNewTabForSearch(hash);
10833 // フラグが立っている場合は設定と逆の動作をする
10834 if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
10835 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
10837 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
10838 if (userUriMatch.Success)
10840 var screenName = userUriMatch.Groups["ScreenName"].Value;
10841 if (this.IsTwitterId(screenName))
10843 this.AddNewTabForUserTimeline(screenName);
10849 // どのパターンにも該当しないURL
10850 await this.OpenUriInBrowserAsync(uriStr);
10854 /// OpenTween 内部の機能を呼び出すための URL を開きます
10856 private async Task OpenInternalUriAsync(Uri uri)
10858 // ツイートを開く (//opentween/status/:status_id)
10859 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
10862 var statusId = long.Parse(match.Groups[1].Value);
10863 await this.OpenRelatedTab(statusId);
10868 public Task OpenUriInBrowserAsync(string UriString)
10870 return Task.Run(() =>
10872 string myPath = UriString;
10876 var configBrowserPath = this._cfgLocal.BrowserPath;
10877 if (!string.IsNullOrEmpty(configBrowserPath))
10879 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
10881 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
10882 string browserPath = configBrowserPath.Substring(1, sep - 1);
10884 if (sep < configBrowserPath.Length - 1)
10886 arg = configBrowserPath.Substring(sep + 1);
10888 myPath = arg + " " + myPath;
10889 System.Diagnostics.Process.Start(browserPath, myPath);
10893 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10898 System.Diagnostics.Process.Start(myPath);
10903 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10908 private void ListTabSelect(TabPage _tab)
10912 this.PurgeListViewItemCache();
10915 _curList = (DetailsListView)_tab.Tag;
10916 if (_curList.SelectedIndices.Count > 0)
10918 _curItemIndex = _curList.SelectedIndices[0];
10919 _curPost = GetCurTabPost(_curItemIndex);
10923 _curItemIndex = -1;
10927 _anchorPost = null;
10928 _anchorFlag = false;
10932 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10936 for (int i = 0; i < _curList.Columns.Count; i++)
10938 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10943 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10945 ListTabSelect(e.TabPage);
10948 private void SelectListItem(DetailsListView LView, int Index)
10951 Rectangle bnd = new Rectangle();
10953 var item = LView.FocusedItem;
10962 LView.SelectedIndices.Clear();
10964 while (LView.SelectedIndices.Count > 0);
10965 item = LView.Items[Index];
10966 item.Selected = true;
10967 item.Focused = true;
10969 if (flg) LView.Invalidate(bnd);
10972 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
10975 Rectangle bnd = new Rectangle();
10977 var item = LView.FocusedItem;
10988 LView.SelectedIndices.Clear();
10990 while (LView.SelectedIndices.Count > 0);
10991 LView.SelectItems(Index);
10993 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
10995 LView.SelectionMark = selectionMarkIndex;
10997 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
10999 LView.Items[focusedIndex].Focused = true;
11001 else if (Index != null && Index.Length != 0)
11003 LView.Items[Index.Last()].Focused = true;
11006 if (flg) LView.Invalidate(bnd);
11009 private void StartUserStream()
11011 tw.NewPostFromStream += tw_NewPostFromStream;
11012 tw.UserStreamStarted += tw_UserStreamStarted;
11013 tw.UserStreamStopped += tw_UserStreamStopped;
11014 tw.PostDeleted += tw_PostDeleted;
11015 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
11017 MenuItemUserStream.Text = "&UserStream ■";
11018 MenuItemUserStream.Enabled = true;
11019 StopToolStripMenuItem.Text = "&Start";
11020 StopToolStripMenuItem.Enabled = true;
11021 if (this._cfgCommon.UserstreamStartup) tw.StartUserStream();
11024 private async void TweenMain_Shown(object sender, EventArgs e)
11028 using (ControlTransaction.Update(this.PostBrowser))
11030 PostBrowser.Url = new Uri("about:blank");
11031 PostBrowser.DocumentText = ""; //発言詳細部初期化
11038 NotifyIcon1.Visible = true;
11040 if (this.IsNetworkAvailable())
11044 var loadTasks = new List<Task>
11046 this.RefreshMuteUserIdsAsync(),
11047 this.RefreshBlockIdsAsync(),
11048 this.RefreshNoRetweetIdsAsync(),
11049 this.RefreshTwitterConfigurationAsync(),
11050 this.GetHomeTimelineAsync(),
11051 this.GetReplyAsync(),
11052 this.GetDirectMessagesAsync(),
11053 this.GetPublicSearchAllAsync(),
11054 this.GetUserTimelineAllAsync(),
11055 this.GetListTimelineAllAsync(),
11058 if (this._cfgCommon.StartupFollowers)
11059 loadTasks.Add(this.RefreshFollowerIdsAsync());
11061 if (this._cfgCommon.GetFav)
11062 loadTasks.Add(this.GetFavoritesAsync());
11064 var allTasks = Task.WhenAll(loadTasks);
11069 var timeout = Task.Delay(5000);
11070 if (await Task.WhenAny(allTasks, timeout) != timeout)
11074 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
11076 if (MyCommon._endingFlag)
11080 if (MyCommon._endingFlag) return;
11082 if (ApplicationSettings.VersionInfoUrl != null)
11084 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
11085 if (this._cfgCommon.StartupVersion)
11086 await this.CheckNewVersion(true);
11090 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
11091 this.VerUpMenuItem.Enabled = false;
11092 this.VerUpMenuItem.Available = false;
11093 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
11096 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
11097 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
11099 MessageBox.Show(Properties.Resources.ReAuthorizeText);
11100 SettingStripMenuItem_Click(null, null);
11104 var reloadTasks = new List<Task>();
11106 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
11107 reloadTasks.Add(this.RefreshFollowerIdsAsync());
11109 if (!tw.GetNoRetweetSuccess)
11110 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
11112 if (this.tw.Configuration.PhotoSizeLimit == 0)
11113 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
11115 await Task.WhenAll(reloadTasks);
11120 TimerTimeline.Enabled = true;
11123 private async Task doGetFollowersMenu()
11125 await this.RefreshFollowerIdsAsync();
11126 await this.DispSelectedPost(true);
11129 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
11131 await this.doGetFollowersMenu();
11134 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
11136 doReTweetUnofficial();
11139 private async Task doReTweetOfficial(bool isConfirm)
11142 if (this.ExistCurrentPost)
11144 if (_curPost.IsProtect)
11146 MessageBox.Show("Protected.");
11147 _DoFavRetweetFlags = false;
11150 if (_curList.SelectedIndices.Count > 15)
11152 MessageBox.Show(Properties.Resources.RetweetLimitText);
11153 _DoFavRetweetFlags = false;
11156 else if (_curList.SelectedIndices.Count > 1)
11158 string QuestionText = Properties.Resources.RetweetQuestion2;
11159 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
11160 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
11162 case DialogResult.Cancel:
11163 case DialogResult.No:
11164 _DoFavRetweetFlags = false;
11170 if (_curPost.IsDm || _curPost.IsMe)
11172 _DoFavRetweetFlags = false;
11175 if (!this._cfgCommon.RetweetNoConfirm)
11177 string Questiontext = Properties.Resources.RetweetQuestion1;
11178 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11179 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11181 _DoFavRetweetFlags = false;
11187 var statusIds = new List<long>();
11188 foreach (int idx in _curList.SelectedIndices)
11190 PostClass post = GetCurTabPost(idx);
11191 if (!post.IsMe && !post.IsProtect && !post.IsDm)
11192 statusIds.Add(post.StatusId);
11195 await this.RetweetAsync(statusIds);
11199 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
11201 await this.doReTweetOfficial(true);
11204 private async Task FavoritesRetweetOfficial()
11206 if (!this.ExistCurrentPost) return;
11207 _DoFavRetweetFlags = true;
11208 var retweetTask = this.doReTweetOfficial(true);
11209 if (_DoFavRetweetFlags)
11211 _DoFavRetweetFlags = false;
11212 var favoriteTask = this.FavoriteChange(true, false);
11214 await Task.WhenAll(retweetTask, favoriteTask);
11222 private async Task FavoritesRetweetUnofficial()
11224 if (this.ExistCurrentPost && !_curPost.IsDm)
11226 _DoFavRetweetFlags = true;
11227 var favoriteTask = this.FavoriteChange(true);
11228 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11230 _DoFavRetweetFlags = false;
11231 doReTweetUnofficial();
11234 await favoriteTask;
11239 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11241 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11242 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11243 /// <returns>復元されたツイート本文</returns>
11244 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11246 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11249 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11251 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11253 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11257 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11259 statusHtml = statusHtml.Replace("<br>", " ");
11261 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11262 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
11263 statusHtml = statusHtml.Replace(" ", " ");
11265 return WebUtility.HtmlDecode(statusHtml);
11268 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11270 if (_curPost != null)
11271 await this.DispSelectedPost(true);
11274 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11276 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11277 DebugModeToolStripMenuItem.Visible = true;
11279 DebugModeToolStripMenuItem.Visible = false;
11282 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11284 this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11287 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11289 ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
11292 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11294 if (TraceOutToolStripMenuItem.Checked)
11295 MyCommon.TraceFlag = true;
11297 MyCommon.TraceFlag = false;
11300 private void TweenMain_Deactivate(object sender, EventArgs e)
11302 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11303 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11306 private void TabRenameMenuItem_Click(object sender, EventArgs e)
11308 if (string.IsNullOrEmpty(_rclickTabName)) return;
11309 TabRename(ref _rclickTabName);
11312 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11314 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11317 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11319 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11322 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11324 TwitterApiStatus apiStatus;
11326 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
11328 var cancellationToken = dialog.EnableCancellation();
11332 var task = Task.Run(() => this.tw.GetInfoApi());
11333 apiStatus = await dialog.WaitForAsync(this, task);
11335 catch (WebApiException)
11340 if (cancellationToken.IsCancellationRequested)
11343 if (apiStatus == null)
11345 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11350 using (var apiDlg = new ApiInfoDialog())
11352 apiDlg.ShowDialog(this);
11356 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
11358 var id = _curPost?.ScreenName ?? "";
11360 await this.FollowCommand(id);
11363 private async Task FollowCommand(string id)
11365 using (var inputName = new InputTabName())
11367 inputName.FormTitle = "Follow";
11368 inputName.FormDescription = Properties.Resources.FRMessage1;
11369 inputName.TabName = id;
11371 if (inputName.ShowDialog(this) != DialogResult.OK)
11373 if (string.IsNullOrWhiteSpace(inputName.TabName))
11376 id = inputName.TabName.Trim();
11379 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
11383 var task = this.twitterApi.FriendshipsCreate(id);
11384 await dialog.WaitForAsync(this, task);
11386 catch (WebApiException ex)
11388 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11393 MessageBox.Show(Properties.Resources.FRMessage3);
11396 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11398 var id = _curPost?.ScreenName ?? "";
11400 await this.RemoveCommand(id, false);
11403 private async Task RemoveCommand(string id, bool skipInput)
11407 using (var inputName = new InputTabName())
11409 inputName.FormTitle = "Unfollow";
11410 inputName.FormDescription = Properties.Resources.FRMessage1;
11411 inputName.TabName = id;
11413 if (inputName.ShowDialog(this) != DialogResult.OK)
11415 if (string.IsNullOrWhiteSpace(inputName.TabName))
11418 id = inputName.TabName.Trim();
11422 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
11426 var task = this.twitterApi.FriendshipsDestroy(id);
11427 await dialog.WaitForAsync(this, task);
11429 catch (WebApiException ex)
11431 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11436 MessageBox.Show(Properties.Resources.FRMessage3);
11439 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
11441 var id = _curPost?.ScreenName ?? "";
11443 await this.ShowFriendship(id);
11446 private async Task ShowFriendship(string id)
11448 using (var inputName = new InputTabName())
11450 inputName.FormTitle = "Show Friendships";
11451 inputName.FormDescription = Properties.Resources.FRMessage1;
11452 inputName.TabName = id;
11454 if (inputName.ShowDialog(this) != DialogResult.OK)
11456 if (string.IsNullOrWhiteSpace(inputName.TabName))
11459 id = inputName.TabName.Trim();
11462 bool isFollowing, isFollowed;
11464 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11466 var cancellationToken = dialog.EnableCancellation();
11470 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11471 var friendship = await dialog.WaitForAsync(this, task);
11473 isFollowing = friendship.Relationship.Source.Following;
11474 isFollowed = friendship.Relationship.Source.FollowedBy;
11476 catch (WebApiException ex)
11478 if (!cancellationToken.IsCancellationRequested)
11479 MessageBox.Show(ex.Message);
11483 if (cancellationToken.IsCancellationRequested)
11487 string result = "";
11490 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11494 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11498 result += Properties.Resources.GetFriendshipInfo3;
11502 result += Properties.Resources.GetFriendshipInfo4;
11504 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11505 MessageBox.Show(result);
11508 private async Task ShowFriendship(string[] ids)
11510 foreach (string id in ids)
11512 bool isFollowing, isFollowed;
11514 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11516 var cancellationToken = dialog.EnableCancellation();
11520 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11521 var friendship = await dialog.WaitForAsync(this, task);
11523 isFollowing = friendship.Relationship.Source.Following;
11524 isFollowed = friendship.Relationship.Source.FollowedBy;
11526 catch (WebApiException ex)
11528 if (!cancellationToken.IsCancellationRequested)
11529 MessageBox.Show(ex.Message);
11533 if (cancellationToken.IsCancellationRequested)
11537 string result = "";
11543 ff += Properties.Resources.GetFriendshipInfo1;
11547 ff += Properties.Resources.GetFriendshipInfo2;
11550 ff += System.Environment.NewLine + " ";
11553 ff += Properties.Resources.GetFriendshipInfo3;
11557 ff += Properties.Resources.GetFriendshipInfo4;
11559 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11562 if (MessageBox.Show(
11563 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11564 MessageBoxButtons.YesNo,
11565 MessageBoxIcon.Question,
11566 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11568 await this.RemoveCommand(id, true);
11573 MessageBox.Show(result);
11578 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
11580 await this.doShowUserStatus(tw.Username, false);
11581 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11583 // doShowUserStatus(tw.Username, false);
11587 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11592 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11593 // URLから切り出した文字列を渡す
11595 public bool IsTwitterId(string name)
11597 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11598 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11600 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
11603 private string GetUserId()
11605 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11606 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11607 return m.Result("${ScreenName}");
11612 private async void FollowContextMenuItem_Click(object sender, EventArgs e)
11614 string name = GetUserId();
11616 await this.FollowCommand(name);
11619 private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
11621 string name = GetUserId();
11623 await this.RemoveCommand(name, false);
11626 private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11628 string name = GetUserId();
11630 await this.ShowFriendship(name);
11633 private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11635 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11636 List<string> ids = new List<string>();
11637 foreach (Match mu in ma)
11639 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11641 ids.Add(mu.Result("${ScreenName}"));
11645 await this.ShowFriendship(ids.ToArray());
11648 private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11650 string name = GetUserId();
11652 await this.ShowUserStatus(name);
11655 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11657 string name = GetUserId();
11658 if (name != null) AddNewTabForUserTimeline(name);
11661 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11663 string name = GetUserId();
11664 if (name != null) AddNewTabForSearch("@" + name);
11667 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11669 ModifySettingCommon = true;
11672 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11674 ModifySettingCommon = true;
11677 private void doQuoteOfficial()
11679 if (this.ExistCurrentPost)
11681 if (_curPost.IsDm ||
11682 !StatusText.Enabled) return;
11684 if (_curPost.IsProtect)
11686 MessageBox.Show("Protected.");
11690 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
11692 this.inReplyTo = null;
11694 StatusText.SelectionStart = 0;
11695 StatusText.Focus();
11699 private void doReTweetUnofficial()
11702 if (this.ExistCurrentPost)
11704 if (_curPost.IsDm || !StatusText.Enabled)
11707 if (_curPost.IsProtect)
11709 MessageBox.Show("Protected.");
11712 string rtdata = _curPost.Text;
11713 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11715 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
11717 // 投稿時に in_reply_to_status_id を付加する
11718 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11719 var inReplyToScreenName = this._curPost.ScreenName;
11720 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
11722 StatusText.SelectionStart = 0;
11723 StatusText.Focus();
11727 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11732 private void SearchButton_Click(object sender, EventArgs e)
11735 Control pnl = ((Control)sender).Parent;
11736 if (pnl == null) return;
11737 string tbName = pnl.Parent.Text;
11738 TabClass tb = _statuses.Tabs[tbName];
11739 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11740 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11741 cmb.Text = cmb.Text.Trim();
11742 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11743 bool Quote = false;
11744 StringBuilder buf = new StringBuilder();
11745 char[] c = cmb.Text.ToCharArray();
11746 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11748 if (cnt > cmb.Text.Length - 4)
11750 buf.Append(cmb.Text.Substring(cnt));
11759 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11761 buf.Append(" OR ");
11766 buf.Append(c[cnt]);
11768 cmb.Text = buf.ToString();
11770 var listView = (DetailsListView)pnl.Parent.Tag;
11772 tb.SearchWords = cmb.Text;
11773 tb.SearchLang = cmbLang.Text;
11774 if (string.IsNullOrEmpty(cmb.Text))
11780 if (tb.IsSearchQueryChanged)
11782 int idx = cmb.Items.IndexOf(tb.SearchWords);
11783 if (idx > -1) cmb.Items.RemoveAt(idx);
11784 cmb.Items.Insert(0, tb.SearchWords);
11785 cmb.Text = tb.SearchWords;
11787 this.PurgeListViewItemCache();
11788 listView.VirtualListSize = 0;
11789 _statuses.ClearTabIds(tbName);
11790 SaveConfigsTabs(); //検索条件の保存
11793 this.GetPublicSearchAsync(tb);
11797 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11800 await this.DoRefreshMore();
11804 /// 指定されたタブのListTabにおける位置を返します
11807 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
11809 public int GetTabPageIndex(string tabName)
11812 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
11814 if (tabPage.Text == tabName)
11823 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11825 if (_statuses.RemovedTab.Count == 0)
11827 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11832 DetailsListView listView = null;
11834 TabClass tb = _statuses.RemovedTab.Pop();
11835 if (tb.TabType == MyCommon.TabUsageType.Related)
11837 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11838 if (relatedTab != null)
11840 // 関連発言なら既存のタブを置き換える
11841 tb.TabName = relatedTab.TabName;
11842 this.ClearTab(tb.TabName, false);
11843 _statuses.Tabs[tb.TabName] = tb;
11845 for (int i = 0; i < ListTab.TabPages.Count; i++)
11847 var tabPage = ListTab.TabPages[i];
11848 if (tb.TabName == tabPage.Text)
11850 listView = (DetailsListView)tabPage.Tag;
11851 ListTab.SelectedIndex = i;
11858 const string TabName = "Related Tweets";
11859 string renamed = TabName;
11860 for (int i = 2; i <= 100; i++)
11862 if (!_statuses.ContainsTab(renamed)) break;
11863 renamed = TabName + i.ToString();
11865 tb.TabName = renamed;
11866 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11867 _statuses.Tabs.Add(renamed, tb); // 後に
11869 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11870 listView = (DetailsListView)tabPage.Tag;
11871 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11876 string renamed = tb.TabName;
11877 for (int i = 1; i < int.MaxValue; i++)
11879 if (!_statuses.ContainsTab(renamed)) break;
11880 renamed = tb.TabName + "(" + i.ToString() + ")";
11882 tb.TabName = renamed;
11883 _statuses.Tabs.Add(renamed, tb); // 先に
11884 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11886 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11887 listView = (DetailsListView)tabPage.Tag;
11888 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11892 if (listView != null)
11894 using (ControlTransaction.Update(listView))
11896 listView.VirtualListSize = tb.AllCount;
11902 private async Task doMoveToRTHome()
11904 if (_curList.SelectedIndices.Count > 0)
11906 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11907 if (post.RetweetedId != null)
11909 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11914 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11916 await this.doMoveToRTHome();
11919 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11921 string name = GetUserId();
11927 if (_curList.SelectedIndices.Count == 0) return;
11930 if (!SelectTab(out tabName)) return;
11932 var tab = this._statuses.Tabs[tabName];
11936 if (tab.TabType != MyCommon.TabUsageType.Mute)
11938 this.MoveOrCopy(out mv, out mk);
11942 // ミュートタブでは常に MoveMatches を true にする
11947 PostFilterRule fc = new PostFilterRule();
11948 fc.FilterName = name;
11949 fc.UseNameField = true;
11950 fc.MoveMatches = mv;
11951 fc.MarkMatches = mk;
11952 fc.UseRegex = false;
11953 fc.FilterByUrl = false;
11956 this.ApplyPostFilters();
11961 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11965 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11967 if (menuItem.Owner == this.ContextMenuPostBrowser)
11969 user = GetUserId();
11970 if (user == null) return;
11972 else if (this._curPost != null)
11974 user = this._curPost.ScreenName;
11981 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11985 this.tw.GetListsApi();
11987 catch (WebApiException ex)
11989 MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
11994 using (MyLists listSelectForm = new MyLists(user, this.tw))
11996 listSelectForm.ShowDialog(this);
12000 private void SearchControls_Enter(object sender, EventArgs e)
12002 Control pnl = (Control)sender;
12003 foreach (Control ctl in pnl.Controls)
12005 ctl.TabStop = true;
12009 private void SearchControls_Leave(object sender, EventArgs e)
12011 Control pnl = (Control)sender;
12012 foreach (Control ctl in pnl.Controls)
12014 ctl.TabStop = false;
12018 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
12020 if (ListTab.SelectedTab != null)
12022 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
12023 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
12027 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
12029 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
12032 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
12033 HashStripSplitButton.Text = HashMgr.UseHash;
12034 HashToggleMenuItem.Checked = true;
12035 HashToggleToolStripMenuItem.Checked = true;
12037 ModifySettingCommon = true;
12041 private void StatusLabel_DoubleClick(object sender, EventArgs e)
12043 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
12046 private void HashManageMenuItem_Click(object sender, EventArgs e)
12048 DialogResult rslt = DialogResult.Cancel;
12051 rslt = HashMgr.ShowDialog();
12057 this.TopMost = this._cfgCommon.AlwaysTop;
12058 if (rslt == DialogResult.Cancel) return;
12059 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12061 HashStripSplitButton.Text = HashMgr.UseHash;
12062 HashToggleMenuItem.Checked = true;
12063 HashToggleToolStripMenuItem.Checked = true;
12067 HashStripSplitButton.Text = "#[-]";
12068 HashToggleMenuItem.Checked = false;
12069 HashToggleToolStripMenuItem.Checked = false;
12071 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
12073 // int sidx = StatusText.SelectionStart;
12074 // string hash = HashMgr.UseHash + " ";
12077 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
12078 // hash = " " + hash;
12080 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
12081 // sidx += hash.Length;
12082 // StatusText.SelectionStart = sidx;
12083 // StatusText.Focus();
12085 ModifySettingCommon = true;
12086 this.StatusText_TextChanged(null, null);
12089 private void HashToggleMenuItem_Click(object sender, EventArgs e)
12091 HashMgr.ToggleHash();
12092 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12094 HashStripSplitButton.Text = HashMgr.UseHash;
12095 HashToggleMenuItem.Checked = true;
12096 HashToggleToolStripMenuItem.Checked = true;
12100 HashStripSplitButton.Text = "#[-]";
12101 HashToggleMenuItem.Checked = false;
12102 HashToggleToolStripMenuItem.Checked = false;
12104 ModifySettingCommon = true;
12105 this.StatusText_TextChanged(null, null);
12108 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
12110 HashToggleMenuItem_Click(null, null);
12113 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
12115 if (ListTab.SelectedTab == null) return;
12116 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
12117 if (!this.ExistCurrentPost)
12119 this.ReplyOpMenuItem.Enabled = false;
12120 this.ReplyAllOpMenuItem.Enabled = false;
12121 this.DmOpMenuItem.Enabled = false;
12122 this.ShowProfMenuItem.Enabled = false;
12123 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
12124 this.ListManageMenuItem.Enabled = false;
12125 this.OpenFavOpMenuItem.Enabled = false;
12126 this.CreateTabRuleOpMenuItem.Enabled = false;
12127 this.CreateIdRuleOpMenuItem.Enabled = false;
12128 this.CreateSourceRuleOpMenuItem.Enabled = false;
12129 this.ReadOpMenuItem.Enabled = false;
12130 this.UnreadOpMenuItem.Enabled = false;
12134 this.ReplyOpMenuItem.Enabled = true;
12135 this.ReplyAllOpMenuItem.Enabled = true;
12136 this.DmOpMenuItem.Enabled = true;
12137 this.ShowProfMenuItem.Enabled = true;
12138 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
12139 this.ListManageMenuItem.Enabled = true;
12140 this.OpenFavOpMenuItem.Enabled = true;
12141 this.CreateTabRuleOpMenuItem.Enabled = true;
12142 this.CreateIdRuleOpMenuItem.Enabled = true;
12143 this.CreateSourceRuleOpMenuItem.Enabled = true;
12144 this.ReadOpMenuItem.Enabled = true;
12145 this.UnreadOpMenuItem.Enabled = true;
12148 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
12150 this.FavOpMenuItem.Enabled = false;
12151 this.UnFavOpMenuItem.Enabled = false;
12152 this.OpenStatusOpMenuItem.Enabled = false;
12153 this.OpenFavotterOpMenuItem.Enabled = false;
12154 this.ShowRelatedStatusesMenuItem2.Enabled = false;
12155 this.RtOpMenuItem.Enabled = false;
12156 this.RtUnOpMenuItem.Enabled = false;
12157 this.QtOpMenuItem.Enabled = false;
12158 this.FavoriteRetweetMenuItem.Enabled = false;
12159 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12163 this.FavOpMenuItem.Enabled = true;
12164 this.UnFavOpMenuItem.Enabled = true;
12165 this.OpenStatusOpMenuItem.Enabled = true;
12166 this.OpenFavotterOpMenuItem.Enabled = true;
12167 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
12171 this.RtOpMenuItem.Enabled = false; //公式RTは無効に
12172 this.RtUnOpMenuItem.Enabled = true;
12173 this.QtOpMenuItem.Enabled = true;
12174 this.FavoriteRetweetMenuItem.Enabled = false; //公式RTは無効に
12175 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12179 if (_curPost.IsProtect)
12181 this.RtOpMenuItem.Enabled = false;
12182 this.RtUnOpMenuItem.Enabled = false;
12183 this.QtOpMenuItem.Enabled = false;
12184 this.FavoriteRetweetMenuItem.Enabled = false;
12185 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12189 this.RtOpMenuItem.Enabled = true;
12190 this.RtUnOpMenuItem.Enabled = true;
12191 this.QtOpMenuItem.Enabled = true;
12192 this.FavoriteRetweetMenuItem.Enabled = true;
12193 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12198 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
12200 this.RefreshPrevOpMenuItem.Enabled = true;
12204 this.RefreshPrevOpMenuItem.Enabled = false;
12206 if (!this.ExistCurrentPost
12207 || _curPost.InReplyToStatusId == null)
12209 OpenRepSourceOpMenuItem.Enabled = false;
12213 OpenRepSourceOpMenuItem.Enabled = true;
12215 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12217 OpenRterHomeMenuItem.Enabled = false;
12221 OpenRterHomeMenuItem.Enabled = true;
12224 if (this.ExistCurrentPost)
12226 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
12230 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12232 ContextMenuTabProperty_Opening(sender, null);
12235 public Twitter TwitterInstance
12240 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12242 if (this._initialLayout)
12245 int splitterDistance;
12246 switch (this.WindowState)
12248 case FormWindowState.Normal:
12249 splitterDistance = this.SplitContainer3.SplitterDistance;
12251 case FormWindowState.Maximized:
12252 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
12253 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
12254 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
12255 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
12261 this._mySpDis3 = splitterDistance;
12262 this.ModifySettingLocal = true;
12265 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12267 if (_statuses.RemovedTab.Count == 0)
12269 UndoRemoveTabMenuItem.Enabled = false;
12273 UndoRemoveTabMenuItem.Enabled = true;
12275 if (ListTab.SelectedTab != null)
12277 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12278 PublicSearchQueryMenuItem.Enabled = true;
12280 PublicSearchQueryMenuItem.Enabled = false;
12284 PublicSearchQueryMenuItem.Enabled = false;
12286 if (!this.ExistCurrentPost)
12288 this.CopySTOTMenuItem.Enabled = false;
12289 this.CopyURLMenuItem.Enabled = false;
12290 this.CopyUserIdStripMenuItem.Enabled = false;
12294 this.CopySTOTMenuItem.Enabled = true;
12295 this.CopyURLMenuItem.Enabled = true;
12296 this.CopyUserIdStripMenuItem.Enabled = true;
12297 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12298 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12302 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12304 SetNotifyIconText();
12307 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12309 var id = _curPost?.ScreenName ?? "";
12311 await this.ShowUserStatus(id);
12314 private async Task doShowUserStatus(string id, bool ShowInputDialog)
12316 TwitterUser user = null;
12318 if (ShowInputDialog)
12320 using (var inputName = new InputTabName())
12322 inputName.FormTitle = "Show UserStatus";
12323 inputName.FormDescription = Properties.Resources.FRMessage1;
12324 inputName.TabName = id;
12326 if (inputName.ShowDialog(this) != DialogResult.OK)
12328 if (string.IsNullOrWhiteSpace(inputName.TabName))
12331 id = inputName.TabName.Trim();
12335 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
12337 var cancellationToken = dialog.EnableCancellation();
12341 var task = this.twitterApi.UsersShow(id);
12342 user = await dialog.WaitForAsync(this, task);
12344 catch (WebApiException ex)
12346 if (!cancellationToken.IsCancellationRequested)
12347 MessageBox.Show(ex.Message);
12351 if (cancellationToken.IsCancellationRequested)
12355 await this.doShowUserStatus(user);
12358 private async Task doShowUserStatus(TwitterUser user)
12360 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
12362 var showUserTask = userDialog.ShowUserAsync(user);
12363 userDialog.ShowDialog(this);
12366 this.BringToFront();
12368 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12369 await showUserTask;
12373 private Task ShowUserStatus(string id, bool ShowInputDialog)
12375 return this.doShowUserStatus(id, ShowInputDialog);
12378 private Task ShowUserStatus(string id)
12380 return this.doShowUserStatus(id, true);
12383 private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12385 if (NameLabel.Tag != null)
12387 string id = (string)NameLabel.Tag;
12388 if (id != tw.Username)
12390 await this.FollowCommand(id);
12395 private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12397 if (NameLabel.Tag != null)
12399 string id = (string)NameLabel.Tag;
12400 if (id != tw.Username)
12402 await this.RemoveCommand(id, false);
12407 private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12409 if (NameLabel.Tag != null)
12411 string id = (string)NameLabel.Tag;
12412 if (id != tw.Username)
12414 await this.ShowFriendship(id);
12419 private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12421 if (NameLabel.Tag != null)
12423 string id = (string)NameLabel.Tag;
12424 await this.ShowUserStatus(id, false);
12428 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12430 if (NameLabel.Tag != null)
12432 string id = (string)NameLabel.Tag;
12433 AddNewTabForUserTimeline(id);
12437 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12439 if (NameLabel.Tag != null)
12441 string id = (string)NameLabel.Tag;
12442 AddNewTabForSearch("@" + id);
12446 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
12448 if (_curPost != null)
12450 await this.ShowUserStatus(_curPost.ScreenName, false);
12454 private async void RtCountMenuItem_Click(object sender, EventArgs e)
12456 if (!this.ExistCurrentPost)
12459 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
12460 int retweetCount = 0;
12462 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
12464 var cancellationToken = dialog.EnableCancellation();
12468 var task = Task.Run(() => this.tw.GetStatus_Retweeted_Count(statusId));
12469 retweetCount = await dialog.WaitForAsync(this, task);
12471 catch (WebApiException ex)
12473 if (!cancellationToken.IsCancellationRequested)
12474 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + ex.Message);
12478 if (cancellationToken.IsCancellationRequested)
12482 MessageBox.Show(retweetCount + Properties.Resources.RtCountText1);
12485 private HookGlobalHotkey _hookGlobalHotkey;
12488 _hookGlobalHotkey = new HookGlobalHotkey(this);
12490 // この呼び出しは、Windows フォーム デザイナで必要です。
12491 InitializeComponent();
12493 // InitializeComponent() 呼び出しの後で初期化を追加します。
12495 if (!this.DesignMode)
12497 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12498 this.StatusText.Dock = DockStyle.Fill;
12501 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12502 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12503 this.gh.NotifyClicked += GrowlHelper_Callback;
12505 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12506 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12508 this.ImageSelector.Visible = false;
12509 this.ImageSelector.Enabled = false;
12510 this.ImageSelector.FilePickDialog = OpenFileDialog1;
12512 this.ReplaceAppName();
12513 this.InitializeShortcuts();
12516 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12518 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12521 this.Visible = false;
12523 else if (Form.ActiveForm == null)
12525 this.Visible = true;
12526 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12528 this.BringToFront();
12529 this.StatusText.Focus();
12533 private void UserPicture_MouseEnter(object sender, EventArgs e)
12535 this.UserPicture.Cursor = Cursors.Hand;
12538 private void UserPicture_MouseLeave(object sender, EventArgs e)
12540 this.UserPicture.Cursor = Cursors.Default;
12543 private async void UserPicture_DoubleClick(object sender, EventArgs e)
12545 if (NameLabel.Tag != null)
12547 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12551 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12553 this.MultiLineMenuItem.PerformClick();
12556 public PostClass CurPost
12558 get { return _curPost; }
12562 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12564 if (ImageSelector.Visible)
12565 ImageSelector.EndSelection();
12567 ImageSelector.BeginSelection();
12570 private void SelectMedia_DragEnter(DragEventArgs e)
12572 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12574 e.Effect = DragDropEffects.Copy;
12577 e.Effect = DragDropEffects.None;
12580 private void SelectMedia_DragDrop(DragEventArgs e)
12583 this.BringToFront();
12584 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12585 StatusText.Focus();
12588 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12590 TimelinePanel.Visible = false;
12591 TimelinePanel.Enabled = false;
12594 private void ImageSelector_EndSelecting(object sender, EventArgs e)
12596 TimelinePanel.Visible = true;
12597 TimelinePanel.Enabled = true;
12598 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12601 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12603 this.AllowDrop = false;
12606 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12608 this.AllowDrop = true;
12611 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12613 if (ImageSelector.Visible)
12615 ModifySettingCommon = true;
12616 SaveConfigsAll(true);
12618 if (ImageSelector.ServiceName.Equals("Twitter"))
12619 this.StatusText_TextChanged(null, null);
12623 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12625 this.StatusText_TextChanged(null, null);
12629 /// StatusTextでCtrl+Vが押下された時の処理
12631 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
12633 if (Clipboard.ContainsText())
12635 // clipboardにテキストがある場合は貼り付け処理
12636 this.StatusText.Paste(Clipboard.GetText());
12638 else if (Clipboard.ContainsImage())
12641 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
12642 Properties.Resources.PostPictureWarn4,
12643 MessageBoxButtons.OKCancel,
12644 MessageBoxIcon.Question,
12645 MessageBoxDefaultButton.Button2)
12646 == DialogResult.OK)
12648 // clipboardから画像を取得
12649 using (var image = Clipboard.GetImage())
12651 this.ImageSelector.BeginSelection(image);
12658 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12660 using (ListManage form = new ListManage(tw))
12662 form.ShowDialog(this);
12666 public bool ModifySettingCommon { get; set; }
12667 public bool ModifySettingLocal { get; set; }
12668 public bool ModifySettingAtId { get; set; }
12670 private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12672 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12673 if (sourceUri != null && e.Button == MouseButtons.Left)
12675 await this.OpenUriInBrowserAsync(sourceUri.AbsoluteUri);
12679 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12681 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12682 if (sourceUri != null)
12684 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri);
12688 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12690 SetStatusLabelUrl();
12693 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12695 if (this.ExistCurrentPost && !_curPost.IsDm)
12696 RtCountMenuItem.Enabled = true;
12698 RtCountMenuItem.Enabled = false;
12700 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12701 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12703 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12706 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12711 private void CopyUserId()
12713 if (_curPost == null) return;
12714 string clstr = _curPost.ScreenName;
12717 Clipboard.SetDataObject(clstr, false, 5, 100);
12719 catch (Exception ex)
12721 MessageBox.Show(ex.Message);
12725 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12727 if (this.ExistCurrentPost && !_curPost.IsDm)
12731 await this.OpenRelatedTab(this._curPost);
12733 catch (TabException ex)
12735 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12741 /// 指定されたツイートに対する関連発言タブを開きます
12743 /// <param name="statusId">表示するツイートのID</param>
12744 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12745 private async Task OpenRelatedTab(long statusId)
12747 var post = this._statuses[statusId];
12752 post = await Task.Run(() => this.tw.GetStatusApi(false, statusId));
12754 catch (WebApiException ex)
12756 this.StatusLabel.Text = ex.Message;
12761 await this.OpenRelatedTab(post);
12765 /// 指定されたツイートに対する関連発言タブを開きます
12767 /// <param name="post">表示する対象となるツイート</param>
12768 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12769 private async Task OpenRelatedTab(PostClass post)
12771 var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12774 if (tabRelated == null)
12776 tabName = this._statuses.MakeTabName("Related Tweets");
12778 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12779 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12781 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12782 tabRelated.UnreadManage = false;
12783 tabRelated.Notify = false;
12787 tabName = tabRelated.TabName;
12790 tabRelated.RelationTargetPost = post;
12791 this.ClearTab(tabName, false);
12793 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12795 var tabPage = this.ListTab.TabPages[i];
12796 if (tabName == tabPage.Text)
12798 this.ListTab.SelectedIndex = i;
12803 await this.GetRelatedTweetsAsync(tabRelated);
12806 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12808 StringBuilder buf = new StringBuilder();
12809 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12810 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12811 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12812 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12813 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12816 private void tw_UserIdChanged()
12818 this.ModifySettingCommon = true;
12821 #region "Userstream"
12822 private bool _isActiveUserstream = false;
12824 private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12828 if (InvokeRequired && !IsDisposed)
12830 Invoke((Action) (async () =>
12832 _statuses.RemovePostReserve(e.StatusId);
12833 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12835 this.PurgeListViewItemCache();
12836 ((DetailsListView)_curTab.Tag).Update();
12837 if (_curPost != null && _curPost.StatusId == e.StatusId)
12838 await this.DispSelectedPost(true);
12844 catch (ObjectDisposedException)
12848 catch (InvalidOperationException)
12854 private int userStreamsRefreshing = 0;
12856 private async void tw_NewPostFromStream(object sender, EventArgs e)
12858 if (this._cfgCommon.ReadOldPosts)
12860 _statuses.SetReadHomeTab(); //新着時未読クリア
12863 int rsltAddCount = _statuses.DistributePosts();
12865 this.UpdateTimelineSpeed(rsltAddCount);
12867 if (this._cfgCommon.UserstreamPeriod > 0) return;
12869 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
12870 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
12874 await this.InvokeAsync(() => this.RefreshTimeline())
12875 .ConfigureAwait(false);
12879 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
12884 private void tw_UserStreamStarted(object sender, EventArgs e)
12886 this._isActiveUserstream = true;
12889 if (InvokeRequired && !IsDisposed)
12891 Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12895 catch (ObjectDisposedException)
12899 catch (InvalidOperationException)
12904 MenuItemUserStream.Text = "&UserStream ▶";
12905 MenuItemUserStream.Enabled = true;
12906 StopToolStripMenuItem.Text = "&Stop";
12907 StopToolStripMenuItem.Enabled = true;
12909 StatusLabel.Text = "UserStream Started.";
12912 private void tw_UserStreamStopped(object sender, EventArgs e)
12914 this._isActiveUserstream = false;
12917 if (InvokeRequired && !IsDisposed)
12919 Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12923 catch (ObjectDisposedException)
12927 catch (InvalidOperationException)
12932 MenuItemUserStream.Text = "&UserStream ■";
12933 MenuItemUserStream.Enabled = true;
12934 StopToolStripMenuItem.Text = "&Start";
12935 StopToolStripMenuItem.Enabled = true;
12937 StatusLabel.Text = "UserStream Stopped.";
12940 private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12944 if (InvokeRequired && !IsDisposed)
12946 Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12950 catch (ObjectDisposedException)
12954 catch (InvalidOperationException)
12958 var ev = e.EventData;
12959 StatusLabel.Text = "Event: " + ev.Event;
12960 //if (ev.Event == "favorite")
12962 // NotifyFavorite(ev);
12965 if (ev.Event == "favorite" || ev.Event == "unfavorite")
12967 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12969 this.PurgeListViewItemCache();
12970 ((DetailsListView)_curTab.Tag).Update();
12972 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
12974 RemovePostFromFavTab(new long[] {ev.Id});
12979 private void NotifyEvent(Twitter.FormattedEvent ev)
12982 if (BalloonRequired(ev))
12984 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
12985 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
12986 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
12987 StringBuilder title = new StringBuilder();
12988 if (this._cfgCommon.DispUsername)
12990 title.Append(tw.Username);
12991 title.Append(" - ");
12997 title.Append(Application.ProductName);
12998 title.Append(" [");
12999 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
13000 title.Append("] by ");
13001 if (!string.IsNullOrEmpty(ev.Username))
13003 title.Append(ev.Username.ToString());
13007 //title.Append("");
13010 if (!string.IsNullOrEmpty(ev.Target))
13012 //NotifyIcon1.BalloonTipText = ev.Target;
13017 //NotifyIcon1.BalloonTipText = " ";
13020 //NotifyIcon1.ShowBalloonTip(500);
13021 if (this._cfgCommon.IsUseNotifyGrowl)
13023 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13024 ev.Id.ToString(), title.ToString(), text);
13028 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13029 NotifyIcon1.BalloonTipTitle = title.ToString();
13030 NotifyIcon1.BalloonTipText = text;
13031 NotifyIcon1.ShowBalloonTip(500);
13036 string snd = this._cfgCommon.EventSoundFile;
13037 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
13039 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13043 string dir = Application.StartupPath;
13044 if (Directory.Exists(Path.Combine(dir, "Sounds")))
13046 dir = Path.Combine(dir, "Sounds");
13048 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13060 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13062 MenuItemUserStream.Enabled = false;
13063 if (StopRefreshAllMenuItem.Checked)
13065 StopRefreshAllMenuItem.Checked = false;
13068 if (this._isActiveUserstream)
13070 tw.StopUserStream();
13074 tw.StartUserStream();
13078 private static string inputTrack = "";
13080 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13082 if (TrackToolStripMenuItem.Checked)
13084 using (InputTabName inputForm = new InputTabName())
13086 inputForm.TabName = inputTrack;
13087 inputForm.FormTitle = "Input track word";
13088 inputForm.FormDescription = "Track word";
13089 if (inputForm.ShowDialog() != DialogResult.OK)
13091 TrackToolStripMenuItem.Checked = false;
13094 inputTrack = inputForm.TabName.Trim();
13096 if (!inputTrack.Equals(tw.TrackWord))
13098 tw.TrackWord = inputTrack;
13099 this.ModifySettingCommon = true;
13100 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13101 tw.ReconnectUserStream();
13107 tw.ReconnectUserStream();
13109 this.ModifySettingCommon = true;
13112 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13114 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13115 this.ModifySettingCommon = true;
13116 tw.ReconnectUserStream();
13119 private void EventViewerMenuItem_Click(object sender, EventArgs e)
13121 if (evtDialog == null || evtDialog.IsDisposed)
13124 evtDialog = new EventViewerDialog();
13125 evtDialog.Owner = this;
13127 Point pos = evtDialog.Location;
13128 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13129 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13130 evtDialog.Location = pos;
13132 evtDialog.EventSource = tw.StoredEvent;
13133 if (!evtDialog.Visible)
13135 evtDialog.Show(this);
13139 evtDialog.Activate();
13141 this.TopMost = this._cfgCommon.AlwaysTop;
13145 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13147 MyCommon._endingFlag = true;
13151 Application.Restart();
13155 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13159 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13161 if (!string.IsNullOrEmpty(tw.Username))
13162 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13165 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13167 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
13170 private async Task doTranslation(string str)
13172 if (string.IsNullOrEmpty(str))
13175 var bing = new Bing();
13178 var translatedText = await bing.TranslateAsync(str,
13180 langTo: this._cfgCommon.TranslateLanguage);
13182 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
13184 catch (HttpRequestException e)
13186 this.StatusLabel.Text = "Err:" + e.Message;
13188 catch (OperationCanceledException)
13190 this.StatusLabel.Text = "Err:Timeout";
13194 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13196 if (!this.ExistCurrentPost)
13199 await this.doTranslation(this._curPost.TextFromApi);
13202 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13204 var text = this.PostBrowser.GetSelectedText();
13205 await this.doTranslation(text);
13208 private bool ExistCurrentPost
13212 if (_curPost == null) return false;
13213 if (_curPost.IsDeleted) return false;
13218 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13220 ShowUserTimeline();
13223 private string GetUserIdFromCurPostOrInput(string caption)
13225 var id = _curPost?.ScreenName ?? "";
13227 using (InputTabName inputName = new InputTabName())
13229 inputName.FormTitle = caption;
13230 inputName.FormDescription = Properties.Resources.FRMessage1;
13231 inputName.TabName = id;
13232 if (inputName.ShowDialog() == DialogResult.OK &&
13233 !string.IsNullOrEmpty(inputName.TabName.Trim()))
13235 id = inputName.TabName.Trim();
13245 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13247 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13248 if (!string.IsNullOrEmpty(id))
13250 AddNewTabForUserTimeline(id);
13254 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13256 string id = GetUserIdFromCurPostOrInput("Show Favstar");
13257 if (!string.IsNullOrEmpty(id))
13259 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13263 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13265 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13268 private void TimelineRefreshEnableChange(bool isEnable)
13272 tw.StartUserStream();
13276 tw.StopUserStream();
13278 TimerTimeline.Enabled = isEnable;
13281 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13283 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13286 private async Task OpenUserAppointUrl()
13288 if (this._cfgCommon.UserAppointUrl != null)
13290 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
13292 if (_curPost != null)
13294 string xUrl = this._cfgCommon.UserAppointUrl;
13295 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13297 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
13298 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
13300 await this.OpenUriInBrowserAsync(xUrl);
13305 await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
13310 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13312 await this.OpenUserAppointUrl();
13315 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13317 string selText = SourceLinkLabel.Text;
13320 Clipboard.SetDataObject(selText, false, 5, 100);
13322 catch (Exception ex)
13324 MessageBox.Show(ex.Message);
13328 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13330 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
13333 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
13335 catch (Exception ex)
13337 MessageBox.Show(ex.Message);
13341 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13343 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13345 SourceCopyMenuItem.Enabled = false;
13346 SourceUrlCopyMenuItem.Enabled = false;
13350 SourceCopyMenuItem.Enabled = true;
13351 SourceUrlCopyMenuItem.Enabled = true;
13355 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13357 if (Form.ActiveForm == null)
13359 this.BeginInvoke((Action) (() =>
13361 this.Visible = true;
13362 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13364 this.BringToFront();
13365 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13367 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13371 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13377 private void ReplaceAppName()
13379 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13380 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13383 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13385 this.SplitContainer3.Panel2Collapsed = false;
13388 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13390 await this.OpenThumbnailPicture(e.Thumbnail);
13393 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13395 await this.OpenUriInBrowserAsync(e.ImageUrl);
13398 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
13400 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
13402 await this.OpenUriInBrowserAsync(url);
13405 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13407 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
13410 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13412 if (e.KeyCode == Keys.Space)
13414 this.JumpUnreadMenuItem_Click(null, null);
13416 e.SuppressKeyPress = true;
13420 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13422 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13423 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13424 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13425 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13426 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13428 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13431 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13433 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13436 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13438 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13441 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13443 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13446 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13448 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13451 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13453 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13456 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13458 if (this._cfgCommon.IconSize == iconSize) return;
13460 var oldIconCol = _iconCol;
13462 this._cfgCommon.IconSize = iconSize;
13463 ApplyListViewIconSize(iconSize);
13465 if (_iconCol != oldIconCol)
13467 foreach (TabPage tp in ListTab.TabPages)
13469 ResetColumns((DetailsListView)tp.Tag);
13473 _curList?.Refresh();
13475 ModifySettingCommon = true;
13478 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13480 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13481 if (this._cfgCommon.SortOrderLock == state) return;
13483 this._cfgCommon.SortOrderLock = state;
13485 ModifySettingCommon = true;