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.Generic;
33 using System.ComponentModel;
34 using System.Diagnostics;
40 using System.Net.Http;
41 using System.Reflection;
43 using System.Text.RegularExpressions;
44 using System.Threading;
45 using System.Threading.Tasks;
46 using System.Windows.Forms;
48 using OpenTween.Connection;
49 using OpenTween.OpenTweenCustomControl;
50 using OpenTween.Thumbnail;
54 public partial class TweenMain : OTBaseForm
57 private Size _mySize; //画面サイズ
58 private Point _myLoc; //画面位置
59 private int _mySpDis; //区切り位置
60 private int _mySpDis2; //発言欄区切り位置
61 private int _mySpDis3; //プレビュー区切り位置
62 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
63 private bool _iconCol; //1列表示の時true(48サイズのとき)
66 private bool _initial; //true:起動時処理中
67 private bool _initialLayout = true;
68 private bool _ignoreConfigSave; //true:起動時処理中
69 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
70 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
71 private Point _tabMouseDownPoint;
72 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
73 private readonly object _syncObject = new object(); //ロック用
75 private const string detailHtmlFormatHeaderMono =
76 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
77 + "<style type=\"text/css\"><!-- "
78 + "body, p, pre {margin: 0;} "
79 + "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%);} "
80 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
81 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
82 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
83 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
85 + "</head><body><pre>";
86 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
87 private const string detailHtmlFormatHeaderColor =
88 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
89 + "<style type=\"text/css\"><!-- "
90 + "body, p, pre {margin: 0;} "
91 + "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%);} "
92 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
93 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
94 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
95 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
98 private const string detailHtmlFormatFooterColor = "</p></body></html>";
99 private string detailHtmlFormatHeader;
100 private string detailHtmlFormatFooter;
102 private bool _myStatusError = false;
103 private bool _myStatusOnline = false;
104 private bool soundfileListup = false;
105 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
108 //private SettingToConfig _cfg; //旧
109 private SettingLocal _cfgLocal;
110 private SettingCommon _cfgCommon;
111 private bool _modifySettingLocal = false;
112 private bool _modifySettingCommon = false;
113 private bool _modifySettingAtId = false;
116 private Twitter tw = new Twitter();
119 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
122 private SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
123 private OpenURL UrlDialog = new OpenURL();
124 public AtIdSupplement AtIdSupl; //@id補助
125 public AtIdSupplement HashSupl; //Hashtag補助
126 public HashtagManage HashMgr;
127 private EventViewerDialog evtDialog;
130 private Font _fntUnread; //未読用フォント
131 private Color _clUnread; //未読用文字色
132 private Font _fntReaded; //既読用フォント
133 private Color _clReaded; //既読用文字色
134 private Color _clFav; //Fav用文字色
135 private Color _clOWL; //片思い用文字色
136 private Color _clRetweet; //Retweet用文字色
137 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
138 private Font _fntDetail; //発言詳細部用フォント
139 private Color _clDetail; //発言詳細部用色
140 private Color _clDetailLink; //発言詳細部用リンク文字色
141 private Color _clDetailBackcolor; //発言詳細部用背景色
142 private Color _clSelf; //自分の発言用背景色
143 private Color _clAtSelf; //自分宛返信用背景色
144 private Color _clTarget; //選択発言者の他の発言用背景色
145 private Color _clAtTarget; //選択発言中の返信先用背景色
146 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
147 private Color _clAtTo; //選択発言の唯一@先
148 private Color _clListBackcolor; //リスト部通常発言背景色
149 private Color _clInputBackcolor; //入力欄背景色
150 private Color _clInputFont; //入力欄文字色
151 private Font _fntInputFont; //入力欄フォント
152 private ImageCache IconCache; //アイコン画像リスト
153 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
154 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
155 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
156 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
157 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
158 private Icon MainIcon; //Main.ico 画面左上のアイコン
159 private Icon ReplyIcon; //5g
160 private Icon ReplyIconBlink; //6g
162 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
164 private PostClass _anchorPost;
165 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
167 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
168 private int _hisIdx; //発言履歴カレントインデックス
170 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
171 private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
174 private List<DateTime> _postTimestamps = new List<DateTime>();
175 private List<DateTime> _favTimestamps = new List<DateTime>();
176 private Dictionary<DateTime, int> _tlTimestamps = new Dictionary<DateTime, int>();
177 private int _tlCount;
180 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
181 private SolidBrush _brsBackColorMine;
182 private SolidBrush _brsBackColorAt;
183 private SolidBrush _brsBackColorYou;
184 private SolidBrush _brsBackColorAtYou;
185 private SolidBrush _brsBackColorAtFromTarget;
186 private SolidBrush _brsBackColorAtTo;
187 private SolidBrush _brsBackColorNone;
188 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
189 private StringFormat sfTab = new StringFormat();
191 //////////////////////////////////////////////////////////////////////////////////////////////////////////
192 private TabInformations _statuses;
195 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
198 /// キャッシュクリアのために null が代入されることがあるため、
199 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
200 /// 一旦ローカル変数に代入してから参照すること。
202 private ListViewItemCache _listItemCache = null;
204 internal class ListViewItemCache
206 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
207 public ListView TargetList { get; set; }
209 /// <summary>キャッシュする範囲の開始インデックス</summary>
210 public int StartIndex { get; set; }
212 /// <summary>キャッシュする範囲の終了インデックス</summary>
213 public int EndIndex { get; set; }
215 /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
216 public ListViewItem[] ListItem { get; set; }
218 /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
219 public PostClass[] Post { get; set; }
221 /// <summary>キャッシュされたアイテムの件数</summary>
223 => this.EndIndex - this.StartIndex + 1;
225 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
226 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
227 public bool Contains(int index)
228 => index >= this.StartIndex && index <= this.EndIndex;
230 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
231 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
232 public bool IsSupersetOf(int rangeStart, int rangeEnd)
233 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
235 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
236 /// <returns>取得に成功すれば true、それ以外は false</returns>
237 public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
239 if (this.Contains(index))
241 item = this.ListItem[index - this.StartIndex];
242 post = this.Post[index - this.StartIndex];
254 private TabPage _curTab;
255 private int _curItemIndex;
256 private DetailsListView _curList;
257 private PostClass _curPost;
258 private bool _isColumnChanged = false;
260 private const int MAX_WORKER_THREADS = 20;
261 private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
262 private CancellationTokenSource workerCts = new CancellationTokenSource();
264 private int UnreadCounter = -1;
265 private int UnreadAtCounter = -1;
267 private string[] ColumnOrgText = new string[9];
268 private string[] ColumnText = new string[9];
270 private bool _DoFavRetweetFlags = false;
271 private bool osResumed = false;
273 //////////////////////////////////////////////////////////////////////////////////////////////////////////
274 private string _postBrowserStatusText = "";
276 private bool _colorize = false;
278 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
280 private ImageListViewItem displayItem;
282 private string recommendedStatusFooter;
285 private struct urlUndo
287 public string Before;
291 private List<urlUndo> urlUndoBuffer = null;
293 private struct ReplyChain
295 public long OriginalId;
296 public long InReplyToId;
297 public TabPage OriginalTab;
299 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
301 this.OriginalId = originalId;
302 this.InReplyToId = inReplyToId;
303 this.OriginalTab = originalTab;
307 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
308 private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
311 private enum SEARCHTYPE
318 private class PostingStatus
320 public string status = "";
321 public long? inReplyToId = null;
322 public string inReplyToName = null;
323 public string imageService = ""; //画像投稿サービス名
324 public IMediaItem[] mediaItems = null;
325 public PostingStatus()
328 public PostingStatus(string status, long? replyToId, string replyToName)
330 this.status = status;
331 this.inReplyToId = replyToId;
332 this.inReplyToName = replyToName;
336 private void TweenMain_Activated(object sender, EventArgs e)
338 //画面がアクティブになったら、発言欄の背景色戻す
339 if (StatusText.Focused)
341 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
345 private bool disposed = false;
348 /// 使用中のリソースをすべてクリーンアップします。
350 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
351 protected override void Dispose(bool disposing)
353 base.Dispose(disposing);
360 this.components?.Dispose();
363 SearchDialog.Dispose();
366 NIconAtRed?.Dispose();
367 NIconAtSmoke?.Dispose();
368 foreach (var iconRefresh in this.NIconRefresh)
370 iconRefresh?.Dispose();
374 ReplyIcon?.Dispose();
375 ReplyIconBlink?.Dispose();
376 _listViewImageList.Dispose();
377 _brsHighLight.Dispose();
378 _brsBackColorMine?.Dispose();
379 _brsBackColorAt?.Dispose();
380 _brsBackColorYou?.Dispose();
381 _brsBackColorAtYou?.Dispose();
382 _brsBackColorAtFromTarget?.Dispose();
383 _brsBackColorAtTo?.Dispose();
384 _brsBackColorNone?.Dispose();
385 _brsDeactiveSelection?.Dispose();
389 this.workerCts.Cancel();
391 if (IconCache != null)
393 this.IconCache.CancelAsync();
394 this.IconCache.Dispose();
397 this.thumbnailTokenSource?.Dispose();
400 this._hookGlobalHotkey.Dispose();
403 // 終了時にRemoveHandlerしておかないとメモリリークする
404 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
405 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
407 this.disposed = true;
410 private void LoadIcons()
412 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
413 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
416 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
419 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
422 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
425 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
427 // タスクトレイ: オフライン時アイコン
428 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
430 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
431 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
432 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
434 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
435 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
436 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
437 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
438 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
440 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
442 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
443 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
444 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
445 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
446 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
448 if (iconReply != null && iconReplyBlink != null)
450 this.ReplyIcon = iconReply;
451 this.ReplyIconBlink = iconReplyBlink;
455 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
456 this.ReplyIconBlink = this.NIconAt;
459 if (iconRefresh1 == null)
461 this.NIconRefresh = new[] {
462 Properties.Resources.Refresh, Properties.Resources.Refresh2,
463 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
466 else if (iconRefresh2 == null)
468 this.NIconRefresh = new[] { iconRefresh1 };
470 else if (iconRefresh3 == null)
472 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
474 else if (iconRefresh4 == null)
476 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
478 else // iconRefresh1 から iconRefresh4 まで全て揃っている
480 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
484 private Icon LoadIcon(string filePath)
486 if (!File.Exists(filePath))
491 return new Icon(filePath);
499 private void InitColumns(ListView list, bool startup)
501 this.InitColumnText();
503 ColumnHeader[] columns;
508 new ColumnHeader { Text = this.ColumnText[0], Width = 48 }, // アイコン
509 new ColumnHeader { Text = this.ColumnText[2], Width = 300 }, // 本文
514 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
516 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
517 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
518 columns[0].DisplayIndex = 0;
519 columns[1].DisplayIndex = 1;
524 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
526 columns[idx].Width = curListColumn.Width;
527 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
536 new ColumnHeader { Text = this.ColumnText[0], Width = 48 }, // アイコン
537 new ColumnHeader { Text = this.ColumnText[1], Width = 80 }, // ニックネーム
538 new ColumnHeader { Text = this.ColumnText[2], Width = 300 }, // 本文
539 new ColumnHeader { Text = this.ColumnText[3], Width = 50 }, // 日付
540 new ColumnHeader { Text = this.ColumnText[4], Width = 50 }, // ユーザID
541 new ColumnHeader { Text = this.ColumnText[5], Width = 16 }, // 未読
542 new ColumnHeader { Text = this.ColumnText[6], Width = 16 }, // マーク&プロテクト
543 new ColumnHeader { Text = this.ColumnText[7], Width = 50 }, // ソース
548 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
550 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
551 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
552 columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
553 columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
554 columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
555 columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
556 columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
557 columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
559 var displayIndex = new[] {
560 this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
561 this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
562 this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
563 this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
566 foreach (var i in Enumerable.Range(0, displayIndex.Length))
568 columns[i].DisplayIndex = displayIndex[i];
574 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
576 columns[idx].Width = curListColumn.Width;
577 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
583 list.Columns.AddRange(columns);
586 private void InitColumnText()
589 ColumnText[1] = Properties.Resources.AddNewTabText2;
590 ColumnText[2] = Properties.Resources.AddNewTabText3;
591 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
592 ColumnText[4] = Properties.Resources.AddNewTabText5;
595 ColumnText[7] = "Source";
597 ColumnOrgText[0] = "";
598 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
599 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
600 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
601 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
602 ColumnOrgText[5] = "";
603 ColumnOrgText[6] = "";
604 ColumnOrgText[7] = "Source";
607 switch (_statuses.SortMode)
609 case ComparerMode.Nickname: //ニックネーム
612 case ComparerMode.Data: //本文
615 case ComparerMode.Id: //時刻=発言Id
618 case ComparerMode.Name: //名前
621 case ComparerMode.Source: //Source
628 if (_statuses.SortOrder == SortOrder.Descending)
630 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
631 ColumnText[2] = ColumnOrgText[2] + "▾";
635 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
636 ColumnText[2] = ColumnOrgText[2] + "▴";
641 if (_statuses.SortOrder == SortOrder.Descending)
643 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
644 ColumnText[c] = ColumnOrgText[c] + "▾";
648 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
649 ColumnText[c] = ColumnOrgText[c] + "▴";
654 private void InitializeTraceFrag()
657 TraceOutToolStripMenuItem.Checked = true;
658 MyCommon.TraceFlag = true;
660 if (!MyCommon.FileVersion.EndsWith("0"))
662 TraceOutToolStripMenuItem.Checked = true;
663 MyCommon.TraceFlag = true;
667 private void TweenMain_Load(object sender, EventArgs e)
669 _ignoreConfigSave = true;
670 this.Visible = false;
672 if (MyApplication.StartupOptions.ContainsKey("d"))
673 MyCommon.TraceFlag = true;
675 InitializeTraceFrag();
677 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
679 new InternetSecurityManager(PostBrowser);
680 this.PostBrowser.AllowWebBrowserDrop = false; // COMException を回避するため、ActiveX の初期化が終わってから設定する
682 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
683 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
685 Regex.CacheSize = 100;
688 _statuses = TabInformations.GetInstance();
692 this.Icon = MainIcon; //メインフォーム(TweenMain)
693 NotifyIcon1.Icon = NIconAt; //タスクトレイ
694 TabImage.Images.Add(TabIcon); //タブ見出し
696 //<<<<<<<<<設定関連>>>>>>>>>
700 // 現在の DPI と設定保存時の DPI との比を取得する
701 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
704 var fontUIGlobal = this._cfgLocal.FontUIGlobal;
705 if (fontUIGlobal != null)
707 OTBaseForm.GlobalFont = fontUIGlobal;
708 this.Font = fontUIGlobal;
712 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
714 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
715 this._cfgCommon.TimelinePeriod = 15;
717 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
718 this._cfgCommon.ReplyPeriod = 15;
720 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
721 this._cfgCommon.DMPeriod = 15;
723 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
724 this._cfgCommon.PubSearchPeriod = 30;
726 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
727 this._cfgCommon.UserTimelinePeriod = 15;
729 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
730 this._cfgCommon.ListsPeriod = 15;
733 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
734 this._cfgCommon.CountApi = 60;
735 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
736 this._cfgCommon.CountApiReply = 40;
738 if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
739 this._cfgCommon.MoreCountApi = 200;
740 if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
741 this._cfgCommon.FirstCountApi = 100;
743 if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
744 this._cfgCommon.FavoritesCountApi = 40;
745 if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
746 this._cfgCommon.ListCountApi = 100;
747 if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
748 this._cfgCommon.SearchCountApi = 100;
749 if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
750 this._cfgCommon.UserTimelineCountApi = 20;
752 //廃止サービスが選択されていた場合ux.nuへ読み替え
753 if (this._cfgCommon.AutoShortUrlFirst < 0)
754 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
756 HttpTwitter.TwitterUrl = this._cfgCommon.TwitterUrl;
759 if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
760 tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
764 Networking.Initialize();
766 bool saveRequired = false;
767 bool firstRun = false;
769 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
770 if (string.IsNullOrEmpty(tw.Username))
775 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
776 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
777 string.IsNullOrEmpty(tw.Username))
779 Application.Exit(); //強制終了
785 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
786 Networking.SetWebProxy(this._cfgLocal.ProxyType,
787 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
788 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
789 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
791 HttpTwitter.TwitterUrl = this._cfgCommon.TwitterUrl;
792 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
793 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
794 tw.TrackWord = this._cfgCommon.TrackWord;
795 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
796 tw.AllAtReply = this._cfgCommon.AllAtReply;
797 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
798 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
799 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
800 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
802 // アクセストークンが有効であるか確認する
803 // ここが Twitter API への最初のアクセスになるようにすること
806 this.tw.VerifyCredentials();
808 catch (WebApiException ex)
810 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
811 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
815 //プロキシ設定等の通信まわりの初期化が済んでから処理する
816 ThumbnailGenerator.InitializeGenerator();
818 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
819 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
820 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
822 Thumbnail.Services.TonTwitterCom.InitializeOAuthToken = x =>
823 x.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
824 this.tw.AccessToken, this.tw.AccessTokenSecret, "", "");
827 ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
830 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
831 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
832 HashMgr = new HashtagManage(HashSupl,
833 _cfgCommon.HashTags.ToArray(),
834 _cfgCommon.HashSelected,
835 _cfgCommon.HashIsPermanent,
836 _cfgCommon.HashIsHead,
837 _cfgCommon.HashIsNotAddToAtReply);
838 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
841 this.IconCache = new ImageCache();
844 _fntUnread = this._cfgLocal.FontUnread;
845 _clUnread = this._cfgLocal.ColorUnread;
846 _fntReaded = this._cfgLocal.FontRead;
847 _clReaded = this._cfgLocal.ColorRead;
848 _clFav = this._cfgLocal.ColorFav;
849 _clOWL = this._cfgLocal.ColorOWL;
850 _clRetweet = this._cfgLocal.ColorRetweet;
851 _fntDetail = this._cfgLocal.FontDetail;
852 _clDetail = this._cfgLocal.ColorDetail;
853 _clDetailLink = this._cfgLocal.ColorDetailLink;
854 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
855 _clSelf = this._cfgLocal.ColorSelf;
856 _clAtSelf = this._cfgLocal.ColorAtSelf;
857 _clTarget = this._cfgLocal.ColorTarget;
858 _clAtTarget = this._cfgLocal.ColorAtTarget;
859 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
860 _clAtTo = this._cfgLocal.ColorAtTo;
861 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
862 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
863 _clInputFont = this._cfgLocal.ColorInputFont;
864 _fntInputFont = this._cfgLocal.FontInputFont;
866 _brsBackColorMine = new SolidBrush(_clSelf);
867 _brsBackColorAt = new SolidBrush(_clAtSelf);
868 _brsBackColorYou = new SolidBrush(_clTarget);
869 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
870 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
871 _brsBackColorAtTo = new SolidBrush(_clAtTo);
872 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
873 _brsBackColorNone = new SolidBrush(_clListBackcolor);
875 // StringFormatオブジェクトへの事前設定
876 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
877 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
878 //sf.FormatFlags = StringFormatFlags.LineLimit; //
879 sfTab.Alignment = StringAlignment.Center;
880 sfTab.LineAlignment = StringAlignment.Center;
882 InitDetailHtmlFormat();
884 //Regex statregex = new Regex("^0*");
885 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
887 _history.Add(new PostingStatus());
889 this.inReplyTo = null;
892 SearchDialog.Owner = this;
893 UrlDialog.Owner = this;
896 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
897 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
899 //新着取得時のリストスクロールをするか。trueならスクロールしない
900 ListLockMenuItem.Checked = _cfgCommon.ListLock;
901 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
903 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
904 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
906 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
907 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
910 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
911 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
912 _myLoc = _cfgLocal.FormLocation;
914 if (this.WindowState != FormWindowState.Minimized)
916 this.DesktopLocation = _cfgLocal.FormLocation;
917 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
918 bool outOfScreen = true;
919 if (Screen.AllScreens.Length == 1) //ハングするとの報告
921 foreach (Screen scr in Screen.AllScreens)
923 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
931 this.DesktopLocation = new Point(0, 0);
932 _myLoc = this.DesktopLocation;
936 this.TopMost = this._cfgCommon.AlwaysTop;
937 _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
938 _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
939 if (_cfgLocal.PreviewDistance == -1)
941 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
942 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
943 _cfgLocal.PreviewDistance = _mySpDis3;
947 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
949 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
950 //this.Tween_ClientSizeChanged(this, null);
951 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
952 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
954 StatusText.Font = _fntInputFont;
955 StatusText.ForeColor = _clInputFont;
957 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
958 this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
959 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
961 // NameLabel のフォントを OTBaseForm.GlobalFont に変更
962 this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
964 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
965 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
967 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
968 if (this._cfgCommon.UnreadManage == false)
970 ReadedStripMenuItem.Enabled = false;
971 UnreadStripMenuItem.Enabled = false;
976 DateTimeLabel.Text = "";
977 SourceLinkLabel.Text = "";
979 //リンク先URL表示部の初期化(画面左下)
980 StatusLabelUrl.Text = "";
982 StatusLabel.Text = "";
983 StatusLabel.AutoToolTip = false;
984 StatusLabel.ToolTipText = "";
986 lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
988 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
989 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
990 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
991 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
993 ////////////////////////////////////////////////////////////////////////////////
994 var sortOrder = (SortOrder)_cfgCommon.SortOrder;
995 var mode = ComparerMode.Id;
996 switch (_cfgCommon.SortColumn)
998 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1002 mode = ComparerMode.Id; //Idソートに読み替え
1005 mode = ComparerMode.Nickname;
1008 mode = ComparerMode.Data;
1011 mode = ComparerMode.Id;
1014 mode = ComparerMode.Name;
1017 mode = ComparerMode.Source;
1020 _statuses.SetSortMode(mode, sortOrder);
1021 ////////////////////////////////////////////////////////////////////////////////
1023 ApplyListViewIconSize(this._cfgCommon.IconSize);
1025 //<<<<<<<<タブ関連>>>>>>>
1029 //デフォルトタブの存在チェック、ない場合には追加
1030 if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1033 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1035 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1039 tab.TabType = MyCommon.TabUsageType.Home;
1042 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1045 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1047 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1051 tab.TabType = MyCommon.TabUsageType.Mentions;
1054 if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1057 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1059 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1063 tab.TabType = MyCommon.TabUsageType.DirectMessage;
1066 if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1069 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1071 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1075 tab.TabType = MyCommon.TabUsageType.Favorites;
1078 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mute) == null)
1081 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.MUTE, out tab))
1083 _statuses.AddTab(MyCommon.DEFAULTTAB.MUTE, MyCommon.TabUsageType.Mute, null);
1087 tab.TabType = MyCommon.TabUsageType.Mute;
1091 foreach (var tab in _statuses.Tabs.Values)
1094 if (tab.TabType == MyCommon.TabUsageType.Mute)
1097 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1099 tab.TabType = MyCommon.TabUsageType.UserDefined;
1101 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo))
1102 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1105 _curTab = ListTab.SelectedTab;
1107 _curList = (DetailsListView)_curTab.Tag;
1109 if (this._cfgCommon.TabIconDisp)
1111 ListTab.DrawMode = TabDrawMode.Normal;
1115 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1116 ListTab.DrawItem += ListTab_DrawItem;
1117 ListTab.ImageList = null;
1120 if (this._cfgCommon.HotkeyEnabled)
1123 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1124 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1125 modKey |= HookGlobalHotkey.ModKeys.Alt;
1126 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1127 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1128 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1129 modKey |= HookGlobalHotkey.ModKeys.Shift;
1130 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1131 modKey |= HookGlobalHotkey.ModKeys.Win;
1133 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1136 if (this._cfgCommon.IsUseNotifyGrowl)
1139 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1141 SetMainWindowTitle();
1142 SetNotifyIconText();
1144 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1146 this.Visible = true;
1150 TimerTimeline.AutoReset = true;
1151 TimerTimeline.SynchronizingObject = this;
1153 TimerTimeline.Interval = 1000;
1154 TimerTimeline.Enabled = true;
1156 TimerRefreshIcon.Interval = 200;
1157 TimerRefreshIcon.Enabled = true;
1159 _ignoreConfigSave = false;
1160 this.TweenMain_Resize(null, null);
1161 if (saveRequired) SaveConfigsAll(false);
1163 foreach (var ua in this._cfgCommon.UserAccounts)
1165 if (ua.UserId == 0 && ua.Username.ToLower() == tw.Username.ToLower())
1167 ua.UserId = tw.UserId;
1174 // 初回起動時だけ右下のメニューを目立たせる
1175 HashStripSplitButton.ShowDropDown();
1179 private void InitDetailHtmlFormat()
1181 if (this._cfgCommon.IsMonospace)
1183 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1184 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1188 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1189 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1192 detailHtmlFormatHeader = detailHtmlFormatHeader
1193 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1194 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1195 .Replace("%FONT_COLOR%", _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString())
1196 .Replace("%LINK_COLOR%", _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString())
1197 .Replace("%BG_COLOR%", _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString());
1200 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1205 txt = ListTab.TabPages[e.Index].Text;
1212 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1213 if (e.State == DrawItemState.Selected)
1215 e.DrawFocusRectangle();
1220 if (_statuses.Tabs[txt].UnreadCount > 0)
1223 fore = System.Drawing.SystemBrushes.ControlText;
1227 fore = System.Drawing.SystemBrushes.ControlText;
1229 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1232 private void LoadConfig()
1234 _cfgCommon = SettingCommon.Load();
1235 SettingCommon.Instance = this._cfgCommon;
1236 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1238 _cfgCommon.UserAccounts = new List<UserAccount>();
1239 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1241 UserAccount account = new UserAccount();
1242 account.Username = _cfgCommon.UserName;
1243 account.UserId = _cfgCommon.UserId;
1244 account.Token = _cfgCommon.Token;
1245 account.TokenSecret = _cfgCommon.TokenSecret;
1247 _cfgCommon.UserAccounts.Add(account);
1251 _cfgLocal = SettingLocal.Load();
1253 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1254 if (_cfgLocal.ScaleDimension.IsEmpty)
1255 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1257 List<TabClass> tabs = SettingTabs.Load().Tabs;
1258 foreach (TabClass tb in tabs)
1262 tb.FilterModified = false;
1263 _statuses.Tabs.Add(tb.TabName, tb);
1267 tb.TabName = _statuses.MakeTabName("MyTab");
1268 _statuses.Tabs.Add(tb.TabName, tb);
1271 if (_statuses.Tabs.Count == 0)
1273 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1274 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1275 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1276 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1280 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1282 if (!TimerTimeline.Enabled) return;
1286 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1288 private static int homeCounter = 0;
1289 private static int mentionCounter = 0;
1290 private static int dmCounter = 0;
1291 private static int pubSearchCounter = 0;
1292 private static int userTimelineCounter = 0;
1293 private static int listsCounter = 0;
1294 private static int usCounter = 0;
1295 private static int ResumeWait = 0;
1296 private static int refreshFollowers = 0;
1298 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1300 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1301 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1302 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1303 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1304 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1305 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1306 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1307 Interlocked.Increment(ref refreshFollowers);
1309 var refreshTasks = new List<Task>();
1312 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1314 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1315 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1316 refreshTasks.Add(this.GetHomeTimelineAsync());
1317 ResetTimers.Timeline = false;
1319 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1321 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1322 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1323 refreshTasks.Add(this.GetReplyAsync());
1324 ResetTimers.Reply = false;
1326 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1328 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1329 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1330 refreshTasks.Add(this.GetDirectMessagesAsync());
1331 ResetTimers.DirectMessage = false;
1333 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1335 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1336 if (!ResetTimers.PublicSearch)
1337 refreshTasks.Add(this.GetPublicSearchAllAsync());
1338 ResetTimers.PublicSearch = false;
1340 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1342 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1343 if (!ResetTimers.UserTimeline)
1344 refreshTasks.Add(this.GetUserTimelineAllAsync());
1345 ResetTimers.UserTimeline = false;
1347 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1349 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1350 if (!ResetTimers.Lists)
1351 refreshTasks.Add(this.GetListTimelineAllAsync());
1352 ResetTimers.Lists = false;
1354 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1356 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1357 if (this._isActiveUserstream)
1359 refreshTasks.Add(this.RefreshTasktrayIcon(true));
1360 this.RefreshTimeline();
1362 ResetTimers.UserStream = false;
1364 if (refreshFollowers > 6 * 3600)
1366 Interlocked.Exchange(ref refreshFollowers, 0);
1367 refreshTasks.AddRange(new[]
1369 this.doGetFollowersMenu(),
1370 this.RefreshNoRetweetIdsAsync(),
1371 this.RefreshTwitterConfigurationAsync(),
1376 Interlocked.Increment(ref ResumeWait);
1377 if (ResumeWait > 30)
1380 Interlocked.Exchange(ref ResumeWait, 0);
1381 refreshTasks.AddRange(new[]
1383 this.GetHomeTimelineAsync(),
1384 this.GetReplyAsync(),
1385 this.GetDirectMessagesAsync(),
1386 this.GetPublicSearchAllAsync(),
1387 this.GetUserTimelineAllAsync(),
1388 this.GetListTimelineAllAsync(),
1389 this.doGetFollowersMenu(),
1390 this.RefreshTwitterConfigurationAsync(),
1395 await Task.WhenAll(refreshTasks);
1398 private void RefreshTimeline()
1400 // 現在表示中のタブのスクロール位置を退避
1401 var curListScroll = this.SaveListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text]);
1403 // 各タブのリスト上の選択位置などを退避
1404 var listSelections = this.SaveListViewSelection();
1407 PostClass[] notifyPosts;
1410 bool newMentionOrDm;
1412 addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1414 if (MyCommon._endingFlag) return;
1419 foreach (TabPage tab in ListTab.TabPages)
1421 DetailsListView lst = (DetailsListView)tab.Tag;
1422 TabClass tabInfo = _statuses.Tabs[tab.Text];
1423 using (ControlTransaction.Update(lst))
1425 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1427 if (lst.Equals(_curList))
1429 this.PurgeListViewItemCache();
1433 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1441 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
1444 if (tabInfo.UnreadCount > 0)
1445 if (this._cfgCommon.TabIconDisp)
1446 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1448 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1452 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1457 this.RestoreListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text], curListScroll);
1460 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1462 SetMainWindowTitle();
1463 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
1465 HashSupl.AddRangeItem(tw.GetHashList());
1469 internal struct ListViewScroll
1471 public ScrollLockMode ScrollLockMode { get; set; }
1472 public long? TopItemStatusId { get; set; }
1475 internal enum ScrollLockMode
1477 /// <summary>固定しない</summary>
1480 /// <summary>最上部に固定する</summary>
1483 /// <summary>最下部に固定する</summary>
1486 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1491 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1493 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabClass tab)
1495 var listScroll = new ListViewScroll
1497 ScrollLockMode = this.GetScrollLockMode(listView),
1500 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1502 var topItem = listView.TopItem;
1503 if (topItem != null)
1504 listScroll.TopItemStatusId = tab.GetId(topItem.Index);
1510 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1512 if (this._statuses.SortMode == ComparerMode.Id)
1514 if (this._statuses.SortOrder == SortOrder.Ascending)
1517 if (this.ListLockMenuItem.Checked)
1518 return ScrollLockMode.None;
1520 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1523 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1524 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1525 return ScrollLockMode.FixedToBottom;
1527 return ScrollLockMode.None;
1532 if (this.ListLockMenuItem.Checked)
1533 return ScrollLockMode.FixedToItem;
1535 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1536 var topItem = listView.TopItem;
1537 if (topItem == null || topItem.Index == 0)
1538 return ScrollLockMode.FixedToTop;
1540 return ScrollLockMode.FixedToItem;
1545 return ScrollLockMode.FixedToItem;
1549 internal struct ListViewSelection
1551 public long[] SelectedStatusIds { get; set; }
1552 public long? SelectionMarkStatusId { get; set; }
1553 public long? FocusedStatusId { get; set; }
1557 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1559 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1561 var listsDict = new Dictionary<string, ListViewSelection>();
1563 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1565 var listView = (DetailsListView)tabPage.Tag;
1566 var tab = _statuses.Tabs[tabPage.Text];
1568 ListViewSelection listStatus;
1569 if (listView.VirtualListSize != 0)
1571 listStatus = new ListViewSelection
1573 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1574 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1575 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1580 listStatus = new ListViewSelection
1582 SelectedStatusIds = new long[0],
1583 SelectionMarkStatusId = null,
1584 FocusedStatusId = null,
1588 listsDict[tab.TabName] = listStatus;
1594 private long[] GetSelectedStatusIds(DetailsListView listView, TabClass tab)
1596 var selectedIndices = listView.SelectedIndices;
1597 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1598 return tab.GetId(selectedIndices);
1603 private long? GetFocusedStatusId(DetailsListView listView, TabClass tab)
1605 var focusedItem = listView.FocusedItem;
1607 return focusedItem != null ? tab.GetId(focusedItem.Index) : (long?)null;
1610 private long? GetSelectionMarkStatusId(DetailsListView listView, TabClass tab)
1612 var selectionMarkIndex = listView.SelectionMark;
1614 return selectionMarkIndex != -1 ? tab.GetId(selectionMarkIndex) : (long?)null;
1618 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1620 private void RestoreListViewScroll(DetailsListView listView, TabClass tab, ListViewScroll listScroll)
1622 if (listView.VirtualListSize == 0)
1625 switch (listScroll.ScrollLockMode)
1627 case ScrollLockMode.FixedToTop:
1628 listView.EnsureVisible(0);
1630 case ScrollLockMode.FixedToBottom:
1631 listView.EnsureVisible(listView.VirtualListSize - 1);
1633 case ScrollLockMode.FixedToItem:
1634 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1636 listView.TopItem = listView.Items[topIndex];
1638 case ScrollLockMode.None:
1645 /// <see cref="SaveListViewStatus"/> によって保存された選択状態を復元します
1647 private void RestoreListViewSelection(DetailsListView listView, TabClass tab, ListViewSelection listSelection)
1649 // status_id から ListView 上のインデックスに変換
1650 int[] selectedIndices = null;
1651 if (listSelection.SelectedStatusIds != null)
1652 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1654 var focusedIndex = -1;
1655 if (listSelection.FocusedStatusId != null)
1656 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1658 var selectionMarkIndex = -1;
1659 if (listSelection.SelectionMarkStatusId != null)
1660 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1662 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1665 private bool BalloonRequired()
1667 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1668 ev.Eventtype = MyCommon.EVENTTYPE.None;
1670 return BalloonRequired(ev);
1673 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1675 if (type == MyCommon.EVENTTYPE.None)
1678 if (!this._cfgCommon.EventNotifyEnabled)
1681 return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1684 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1689 return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1692 private bool BalloonRequired(Twitter.FormattedEvent ev)
1697 if (NativeMethods.IsScreenSaverRunning())
1701 if (!this.NewPostPopMenuItem.Checked)
1703 // 「新着通知が無効でもイベントを通知する」にも該当しない
1704 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1708 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1709 if (this._cfgCommon.LimitBalloon)
1711 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1715 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1718 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1720 if (this._cfgCommon.ReadOwnPost)
1722 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1727 if (BalloonRequired())
1729 if (notifyPosts != null && notifyPosts.Length > 0)
1731 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1732 if (this._cfgCommon.IsUseNotifyGrowl)
1734 StringBuilder sb = new StringBuilder();
1738 foreach (PostClass post in notifyPosts)
1740 if (!(notifyPosts.Length > 3))
1746 if (post.IsReply && !post.IsExcludeReply) reply = true;
1747 if (post.IsDm) dm = true;
1748 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1749 switch (this._cfgCommon.NameBalloon)
1751 case MyCommon.NameBalloonEnum.UserID:
1752 sb.Append(post.ScreenName).Append(" : ");
1754 case MyCommon.NameBalloonEnum.NickName:
1755 sb.Append(post.Nickname).Append(" : ");
1758 sb.Append(post.TextFromApi);
1759 if (notifyPosts.Length > 3)
1761 if (notifyPosts.Last() != post) continue;
1764 StringBuilder title = new StringBuilder();
1765 GrowlHelper.NotifyType nt;
1766 if (this._cfgCommon.DispUsername)
1768 title.Append(tw.Username);
1769 title.Append(" - ");
1777 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1778 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1779 title.Append(Application.ProductName);
1780 title.Append(" [DM] ");
1781 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1782 nt = GrowlHelper.NotifyType.DirectMessage;
1786 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1787 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1788 title.Append(Application.ProductName);
1789 title.Append(" [Reply!] ");
1790 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1791 nt = GrowlHelper.NotifyType.Reply;
1795 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1796 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1797 title.Append(Application.ProductName);
1799 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1800 nt = GrowlHelper.NotifyType.Notify;
1802 string bText = sb.ToString();
1803 if (string.IsNullOrEmpty(bText)) return;
1805 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1806 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1811 StringBuilder sb = new StringBuilder();
1814 foreach (PostClass post in notifyPosts)
1816 if (post.IsReply && !post.IsExcludeReply) reply = true;
1817 if (post.IsDm) dm = true;
1818 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1819 switch (this._cfgCommon.NameBalloon)
1821 case MyCommon.NameBalloonEnum.UserID:
1822 sb.Append(post.ScreenName).Append(" : ");
1824 case MyCommon.NameBalloonEnum.NickName:
1825 sb.Append(post.Nickname).Append(" : ");
1828 sb.Append(post.TextFromApi);
1831 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1832 StringBuilder title = new StringBuilder();
1834 if (this._cfgCommon.DispUsername)
1836 title.Append(tw.Username);
1837 title.Append(" - ");
1845 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1846 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1847 ntIcon = ToolTipIcon.Warning;
1848 title.Append(Application.ProductName);
1849 title.Append(" [DM] ");
1850 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1854 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1855 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1856 ntIcon = ToolTipIcon.Warning;
1857 title.Append(Application.ProductName);
1858 title.Append(" [Reply!] ");
1859 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1863 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1864 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1865 ntIcon = ToolTipIcon.Info;
1866 title.Append(Application.ProductName);
1868 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1870 string bText = sb.ToString();
1871 if (string.IsNullOrEmpty(bText)) return;
1872 //NotifyIcon1.BalloonTipText = sb.ToString();
1873 //NotifyIcon1.ShowBalloonTip(500);
1874 NotifyIcon1.BalloonTipTitle = title.ToString();
1875 NotifyIcon1.BalloonTipText = bText;
1876 NotifyIcon1.BalloonTipIcon = ntIcon;
1877 NotifyIcon1.ShowBalloonTip(500);
1883 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1887 string dir = Application.StartupPath;
1888 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1890 dir = Path.Combine(dir, "Sounds");
1892 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1902 //mentions新着時に画面ブリンク
1903 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1905 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1909 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1911 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1913 _curItemIndex = _curList.SelectedIndices[0];
1914 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1918 _curPost = GetCurTabPost(_curItemIndex);
1920 catch (ArgumentException)
1925 this.PushSelectPostChain();
1927 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1929 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1935 private void ChangeCacheStyleRead(bool Read, int Index)
1937 var tabInfo = _statuses.Tabs[_curTab.Text];
1938 //Read:true=既読 false=未読
1939 //未読管理していなかったら既読として扱う
1940 if (!tabInfo.UnreadManage ||
1941 !this._cfgCommon.UnreadManage) Read = true;
1943 var listCache = this._listItemCache;
1944 if (listCache == null)
1947 // キャッシュに含まれていないアイテムは対象外
1950 if (!listCache.TryGetValue(Index, out itm, out post))
1953 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1956 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1963 Item.SubItems[5].Text = "";
1968 Item.SubItems[5].Text = "★";
1974 else if (Post.RetweetedId != null)
1976 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1978 else if (Read || !this._cfgCommon.UseUnreadStyle)
1983 if (DList == null || Item.Index == -1)
1985 Item.ForeColor = cl;
1986 if (this._cfgCommon.UseUnreadStyle)
1992 if (this._cfgCommon.UseUnreadStyle)
1993 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1995 DList.ChangeItemForeColor(Item.Index, cl);
1996 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2000 private void ColorizeList()
2002 //Index:更新対象のListviewItem.Index。Colorを返す。
2003 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2006 _post = _anchorPost;
2010 if (_post == null) return;
2012 var listCache = this._listItemCache;
2013 if (listCache == null)
2016 var index = listCache.StartIndex;
2017 foreach (var cachedPost in listCache.Post)
2019 var backColor = this.JudgeColor(_post, cachedPost);
2020 this._curList.ChangeItemBackColor(index++, backColor);
2024 private void ColorizeList(ListViewItem Item, int Index)
2026 //Index:更新対象のListviewItem.Index。Colorを返す。
2027 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2030 _post = _anchorPost;
2034 PostClass tPost = GetCurTabPost(Index);
2036 if (_post == null) return;
2038 if (Item.Index == -1)
2039 Item.BackColor = JudgeColor(_post, tPost);
2041 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2044 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2047 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2050 else if (TargetPost.IsMe)
2053 else if (TargetPost.IsReply)
2056 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLower()))
2058 cl = _clAtFromTarget;
2059 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLower()))
2062 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2067 cl = _clListBackcolor;
2072 private async void PostButton_Click(object sender, EventArgs e)
2074 if (StatusText.Text.Trim().Length == 0)
2076 if (!ImageSelector.Enabled)
2078 await this.DoRefresh();
2083 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2085 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2087 MessageBoxButtons.YesNoCancel,
2088 MessageBoxIcon.Question);
2091 case DialogResult.Yes:
2092 StatusText.Text = "";
2093 await this.doReTweetOfficial(false);
2095 case DialogResult.Cancel:
2100 var inReplyToStatusId = this.inReplyTo?.Item1;
2101 var inReplyToScreenName = this.inReplyTo?.Item2;
2102 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2104 if (this._cfgCommon.Nicoms)
2106 StatusText.SelectionStart = StatusText.Text.Length;
2107 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2109 //if (SettingDialog.UrlConvertAuto)
2111 // StatusText.SelectionStart = StatusText.Text.Length;
2112 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2114 //else if (SettingDialog.Nicoms)
2116 // StatusText.SelectionStart = StatusText.Text.Length;
2117 // UrlConvert(UrlConverter.Nicoms);
2119 StatusText.SelectionStart = StatusText.Text.Length;
2120 CheckReplyTo(StatusText.Text);
2122 var statusText = this.FormatStatusText(this.StatusText.Text);
2124 if (this.GetRestStatusCount(statusText) < 0)
2126 // 文字数制限を超えているが強制的に投稿するか
2127 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2128 if (ret != DialogResult.OK)
2132 var status = new PostingStatus();
2133 status.status = statusText;
2135 status.inReplyToId = this.inReplyTo?.Item1;
2136 status.inReplyToName = this.inReplyTo?.Item2;
2137 if (ImageSelector.Visible)
2140 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2144 this.inReplyTo = null;
2145 StatusText.Text = "";
2146 _history.Add(new PostingStatus());
2147 _hisIdx = _history.Count - 1;
2148 if (!ToolStripFocusLockMenuItem.Checked)
2149 ((Control)ListTab.SelectedTab.Tag).Focus();
2150 urlUndoBuffer = null;
2151 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2154 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2156 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2157 await this.OpenUriInBrowserAsync(tmp);
2160 await this.PostMessageAsync(status);
2163 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2165 MyCommon._endingFlag = true;
2169 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2171 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2173 //_endingFlag=false:フォームの×ボタン
2175 this.Visible = false;
2179 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2180 _ignoreConfigSave = true;
2181 MyCommon._endingFlag = true;
2182 TimerTimeline.Enabled = false;
2183 TimerRefreshIcon.Enabled = false;
2187 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2189 this.Visible = true;
2190 if (this.WindowState == FormWindowState.Minimized)
2192 this.WindowState = FormWindowState.Normal;
2195 this.BringToFront();
2198 private static int errorCount = 0;
2200 private static bool CheckAccountValid()
2202 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2208 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2217 private Task GetHomeTimelineAsync()
2219 return this.GetHomeTimelineAsync(loadMore: false);
2222 private async Task GetHomeTimelineAsync(bool loadMore)
2224 await this.workerSemaphore.WaitAsync();
2228 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2230 await this.GetHomeTimelineAsyncInternal(progress, this.workerCts.Token, loadMore);
2232 catch (WebApiException ex)
2234 this._myStatusError = true;
2235 this.StatusLabel.Text = ex.Message;
2239 this.workerSemaphore.Release();
2243 private async Task GetHomeTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2245 if (ct.IsCancellationRequested)
2248 if (!CheckAccountValid())
2249 throw new WebApiException("Auth error. Check your account");
2252 if (!this._cfgCommon.UnreadManage)
2255 read = this._initial && this._cfgCommon.Read;
2257 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5, loadMore ? -1 : 1));
2259 await Task.Run(() =>
2261 this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Timeline, loadMore, this._initial);
2264 if (this._cfgCommon.ReadOldPosts)
2265 this._statuses.SetReadHomeTab();
2267 var addCount = this._statuses.DistributePosts();
2271 lock (this._syncObject)
2273 var tm = DateTime.Now;
2274 if (this._tlTimestamps.ContainsKey(tm))
2275 this._tlTimestamps[tm] += addCount;
2277 this._tlTimestamps[tm] = addCount;
2279 var removeKeys = new List<DateTime>();
2280 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2283 foreach (var pair in this._tlTimestamps)
2285 if (pair.Key < oneHour)
2286 removeKeys.Add(pair.Key);
2288 this._tlCount += pair.Value;
2291 foreach (var key in removeKeys)
2292 this._tlTimestamps.Remove(key);
2297 if (ct.IsCancellationRequested)
2300 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1);
2302 this.RefreshTimeline();
2305 private Task GetReplyAsync()
2307 return this.GetReplyAsync(loadMore: false);
2310 private async Task GetReplyAsync(bool loadMore)
2312 await this.workerSemaphore.WaitAsync();
2316 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2318 await this.GetReplyAsyncInternal(progress, this.workerCts.Token, loadMore);
2320 catch (WebApiException ex)
2322 this._myStatusError = true;
2323 this.StatusLabel.Text = ex.Message;
2327 this.workerSemaphore.Release();
2331 private async Task GetReplyAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2333 if (ct.IsCancellationRequested)
2336 if (!CheckAccountValid())
2337 throw new WebApiException("Auth error. Check your account");
2340 if (!this._cfgCommon.UnreadManage)
2343 read = this._initial && this._cfgCommon.Read;
2345 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4, loadMore ? -1 : 1));
2347 await Task.Run(() =>
2349 this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Reply, loadMore, this._initial);
2351 this._statuses.DistributePosts();
2354 if (ct.IsCancellationRequested)
2357 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9);
2359 this.RefreshTimeline();
2362 private Task GetDirectMessagesAsync()
2364 return this.GetDirectMessagesAsync(loadMore: false);
2367 private async Task GetDirectMessagesAsync(bool loadMore)
2369 await this.workerSemaphore.WaitAsync();
2373 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2375 await this.GetDirectMessagesAsyncInternal(progress, this.workerCts.Token, loadMore);
2377 catch (WebApiException ex)
2379 this._myStatusError = true;
2380 this.StatusLabel.Text = ex.Message;
2384 this.workerSemaphore.Release();
2388 private async Task GetDirectMessagesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2390 if (ct.IsCancellationRequested)
2393 if (!CheckAccountValid())
2394 throw new WebApiException("Auth error. Check your account");
2397 if (!this._cfgCommon.UnreadManage)
2400 read = this._initial && this._cfgCommon.Read;
2402 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8, loadMore ? -1 : 1));
2404 await Task.Run(() =>
2406 this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, loadMore);
2407 this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, loadMore);
2409 this._statuses.DistributePosts();
2412 if (ct.IsCancellationRequested)
2415 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11);
2417 this.RefreshTimeline();
2420 private Task GetFavoritesAsync()
2422 return this.GetFavoritesAsync(loadMore: false);
2425 private async Task GetFavoritesAsync(bool loadMore)
2427 await this.workerSemaphore.WaitAsync();
2431 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2433 await this.GetFavoritesAsyncInternal(progress, this.workerCts.Token, loadMore);
2435 catch (WebApiException ex)
2437 this._myStatusError = true;
2438 this.StatusLabel.Text = ex.Message;
2442 this.workerSemaphore.Release();
2446 private async Task GetFavoritesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2448 if (ct.IsCancellationRequested)
2451 if (!CheckAccountValid())
2452 throw new WebApiException("Auth error. Check your account");
2455 if (!this._cfgCommon.UnreadManage)
2458 read = this._initial && this._cfgCommon.Read;
2460 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19);
2462 await Task.Run(() =>
2464 this.tw.GetFavoritesApi(read, loadMore);
2466 this._statuses.DistributePosts();
2469 if (ct.IsCancellationRequested)
2472 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20);
2474 this.RefreshTimeline();
2477 private Task GetPublicSearchAllAsync()
2479 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch);
2481 return this.GetPublicSearchAsync(tabs, loadMore: false);
2484 private Task GetPublicSearchAsync(TabClass tab)
2486 return this.GetPublicSearchAsync(tab, loadMore: false);
2489 private Task GetPublicSearchAsync(TabClass tab, bool loadMore)
2491 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2494 private async Task GetPublicSearchAsync(IEnumerable<TabClass> tabs, bool loadMore)
2496 await this.workerSemaphore.WaitAsync();
2500 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2502 await this.GetPublicSearchAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2504 catch (WebApiException ex)
2506 this._myStatusError = true;
2507 this.StatusLabel.Text = ex.Message;
2511 this.workerSemaphore.Release();
2515 private async Task GetPublicSearchAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2517 if (ct.IsCancellationRequested)
2520 if (!CheckAccountValid())
2521 throw new WebApiException("Auth error. Check your account");
2524 if (!this._cfgCommon.UnreadManage)
2527 read = this._initial && this._cfgCommon.Read;
2529 p.Report("Search refreshing...");
2531 await Task.Run(() =>
2533 WebApiException lastException = null;
2535 foreach (var tab in tabs)
2539 if (string.IsNullOrEmpty(tab.SearchWords))
2542 this.tw.GetSearch(read, tab, false);
2545 this.tw.GetSearch(read, tab, true);
2547 catch (WebApiException ex)
2553 this._statuses.DistributePosts();
2555 if (lastException != null)
2556 throw new WebApiException(lastException.Message, lastException);
2559 if (ct.IsCancellationRequested)
2562 p.Report("Search refreshed");
2564 this.RefreshTimeline();
2567 private Task GetUserTimelineAllAsync()
2569 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline);
2571 return this.GetUserTimelineAsync(tabs, loadMore: false);
2574 private Task GetUserTimelineAsync(TabClass tab)
2576 return this.GetUserTimelineAsync(tab, loadMore: false);
2579 private Task GetUserTimelineAsync(TabClass tab, bool loadMore)
2581 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2584 private async Task GetUserTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2586 await this.workerSemaphore.WaitAsync();
2590 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2592 await this.GetUserTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2594 catch (WebApiException ex)
2596 this._myStatusError = true;
2597 this.StatusLabel.Text = ex.Message;
2601 this.workerSemaphore.Release();
2605 private async Task GetUserTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2607 if (ct.IsCancellationRequested)
2610 if (!CheckAccountValid())
2611 throw new WebApiException("Auth error. Check your account");
2614 if (!this._cfgCommon.UnreadManage)
2617 read = this._initial && this._cfgCommon.Read;
2619 p.Report("UserTimeline refreshing...");
2621 await Task.Run(() =>
2623 WebApiException lastException = null;
2625 foreach (var tab in tabs)
2629 if (string.IsNullOrEmpty(tab.User))
2632 this.tw.GetUserTimelineApi(read, tab.User, tab, loadMore);
2634 catch (WebApiException ex)
2640 this._statuses.DistributePosts();
2642 if (lastException != null)
2643 throw new WebApiException(lastException.Message, lastException);
2646 if (ct.IsCancellationRequested)
2649 p.Report("UserTimeline refreshed");
2651 this.RefreshTimeline();
2654 private Task GetListTimelineAllAsync()
2656 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.Lists);
2658 return this.GetListTimelineAsync(tabs, loadMore: false);
2661 private Task GetListTimelineAsync(TabClass tab)
2663 return this.GetListTimelineAsync(tab, loadMore: false);
2666 private Task GetListTimelineAsync(TabClass tab, bool loadMore)
2668 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2671 private async Task GetListTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2673 await this.workerSemaphore.WaitAsync();
2677 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2679 await this.GetListTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2681 catch (WebApiException ex)
2683 this._myStatusError = true;
2684 this.StatusLabel.Text = ex.Message;
2688 this.workerSemaphore.Release();
2692 private async Task GetListTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2694 if (ct.IsCancellationRequested)
2697 if (!CheckAccountValid())
2698 throw new WebApiException("Auth error. Check your account");
2701 if (!this._cfgCommon.UnreadManage)
2704 read = this._initial && this._cfgCommon.Read;
2706 p.Report("List refreshing...");
2708 await Task.Run(() =>
2710 WebApiException lastException = null;
2712 foreach (var tab in tabs)
2716 if (tab.ListInfo == null || tab.ListInfo.Id == 0)
2719 this.tw.GetListStatus(read, tab, loadMore, this._initial);
2721 catch (WebApiException ex)
2727 this._statuses.DistributePosts();
2729 if (lastException != null)
2730 throw new WebApiException(lastException.Message, lastException);
2733 if (ct.IsCancellationRequested)
2736 p.Report("List refreshed");
2738 this.RefreshTimeline();
2741 private async Task GetRelatedTweetsAsync(TabClass tab)
2743 await this.workerSemaphore.WaitAsync();
2747 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2749 await this.GetRelatedTweetsAsyncInternal(progress, this.workerCts.Token, tab);
2751 catch (WebApiException ex)
2753 this._myStatusError = true;
2754 this.StatusLabel.Text = ex.Message;
2758 this.workerSemaphore.Release();
2762 private async Task GetRelatedTweetsAsyncInternal(IProgress<string> p, CancellationToken ct, TabClass tab)
2764 if (ct.IsCancellationRequested)
2767 if (!CheckAccountValid())
2768 throw new WebApiException("Auth error. Check your account");
2771 if (!this._cfgCommon.UnreadManage)
2774 read = this._initial && this._cfgCommon.Read;
2776 p.Report("Related refreshing...");
2778 await Task.Run(() =>
2780 this.tw.GetRelatedResult(read, tab);
2782 this._statuses.DistributePosts();
2785 if (ct.IsCancellationRequested)
2788 p.Report("Related refreshed");
2790 this.RefreshTimeline();
2792 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
2793 .FirstOrDefault(x => x.Text == tab.TabName);
2795 if (tabPage != null)
2797 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
2799 var listView = (DetailsListView)tabPage.Tag;
2800 var index = tab.IndexOf(tab.RelationTargetPost.RetweetedId ?? tab.RelationTargetPost.StatusId);
2802 if (index != -1 && index < listView.Items.Count)
2804 listView.SelectedIndices.Add(index);
2805 listView.Items[index].Focused = true;
2810 private async Task FavAddAsync(IReadOnlyList<long> statusIds, TabClass tab)
2812 await this.workerSemaphore.WaitAsync();
2816 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2818 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2820 catch (WebApiException ex)
2822 this._myStatusError = true;
2823 this.StatusLabel.Text = ex.Message;
2827 this.workerSemaphore.Release();
2831 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2833 if (ct.IsCancellationRequested)
2836 if (!CheckAccountValid())
2837 throw new WebApiException("Auth error. Check your account");
2839 var successIds = new List<long>();
2841 await Task.Run(() =>
2845 var failedCount = 0;
2847 foreach (var statusId in statusIds)
2851 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, allCount, statusIds.Count, failedCount));
2853 var post = tab.Posts[statusId];
2860 this.tw.PostFavAdd(post.RetweetedId ?? post.StatusId);
2862 catch (WebApiException)
2868 successIds.Add(statusId);
2869 post.IsFav = true; // リスト再描画必要
2871 this._favTimestamps.Add(DateTime.Now);
2874 if (this._statuses.ContainsKey(statusId))
2876 var postTl = this._statuses[statusId];
2877 postTl.IsFav = true;
2879 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2880 favTab.AddPostImmediately(statusId, postTl.IsRead);
2883 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2884 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2886 if (tb.Contains(statusId))
2887 tb.Posts[statusId].IsFav = true;
2892 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2893 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2895 if (this._favTimestamps[i] < oneHour)
2896 this._favTimestamps.RemoveAt(i);
2899 this._statuses.DistributePosts();
2902 if (ct.IsCancellationRequested)
2905 this.RefreshTimeline();
2907 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2909 using (ControlTransaction.Update(this._curList))
2911 foreach (var statusId in successIds)
2913 var idx = tab.IndexOf(statusId);
2917 var post = tab.Posts[statusId];
2918 this.ChangeCacheStyleRead(post.IsRead, idx);
2922 if (successIds.Contains(this._curPost.StatusId))
2923 await this.DispSelectedPost(true); // 選択アイテム再表示
2927 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabClass tab)
2929 await this.workerSemaphore.WaitAsync();
2933 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2935 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2937 catch (WebApiException ex)
2939 this._myStatusError = true;
2940 this.StatusLabel.Text = ex.Message;
2944 this.workerSemaphore.Release();
2948 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2950 if (ct.IsCancellationRequested)
2953 if (!CheckAccountValid())
2954 throw new WebApiException("Auth error. Check your account");
2956 var successIds = new List<long>();
2958 await Task.Run(() =>
2962 var failedCount = 0;
2963 foreach (var statusId in statusIds)
2967 var post = tab.Posts[statusId];
2969 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2976 this.tw.PostFavRemove(post.RetweetedId ?? post.StatusId);
2978 catch (WebApiException)
2984 successIds.Add(statusId);
2985 post.IsFav = false; // リスト再描画必要
2987 if (this._statuses.ContainsKey(statusId))
2989 this._statuses[statusId].IsFav = false;
2992 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2993 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2995 if (tb.Contains(statusId))
2996 tb.Posts[statusId].IsFav = false;
3001 if (ct.IsCancellationRequested)
3004 this.RemovePostFromFavTab(successIds.ToArray());
3006 this.RefreshTimeline();
3008 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
3010 if (tab.TabType == MyCommon.TabUsageType.Favorites)
3016 using (ControlTransaction.Update(this._curList))
3018 foreach (var statusId in successIds)
3020 var idx = tab.IndexOf(statusId);
3024 var post = tab.Posts[statusId];
3025 this.ChangeCacheStyleRead(post.IsRead, idx);
3029 if (successIds.Contains(this._curPost.StatusId))
3030 await this.DispSelectedPost(true); // 選択アイテム再表示
3035 private async Task PostMessageAsync(PostingStatus status)
3037 await this.workerSemaphore.WaitAsync();
3041 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3043 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
3045 catch (WebApiException ex)
3047 this._myStatusError = true;
3048 this.StatusLabel.Text = ex.Message;
3052 this.workerSemaphore.Release();
3056 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
3058 if (ct.IsCancellationRequested)
3061 if (!CheckAccountValid())
3062 throw new WebApiException("Auth error. Check your account");
3064 p.Report("Posting...");
3070 await Task.Run(async () =>
3072 if (status.mediaItems == null || status.mediaItems.Length == 0)
3074 this.tw.PostStatus(status.status, status.inReplyToId);
3078 var service = ImageSelector.GetService(status.imageService);
3079 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
3080 .ConfigureAwait(false);
3084 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3086 catch (WebApiException ex)
3088 // 処理は中断せずエラーの表示のみ行う
3089 errMsg = ex.Message;
3091 this._myStatusError = true;
3095 // 使い終わった MediaItem は破棄する
3096 if (status.mediaItems != null)
3098 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
3100 disposableItem.Dispose();
3105 if (ct.IsCancellationRequested)
3108 if (!string.IsNullOrEmpty(errMsg) &&
3109 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
3110 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
3112 var ret = MessageBox.Show(
3114 "{0} ---> [ " + errMsg + " ]" + Environment.NewLine +
3115 "\"" + status.status + "\"" + Environment.NewLine +
3117 Properties.Resources.StatusUpdateFailed1,
3118 Properties.Resources.StatusUpdateFailed2),
3119 "Failed to update status",
3120 MessageBoxButtons.RetryCancel,
3121 MessageBoxIcon.Question);
3123 if (ret == DialogResult.Retry)
3125 await this.PostMessageAsync(status);
3129 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3130 if (this.ToolStripFocusLockMenuItem.Checked)
3131 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
3136 this._postTimestamps.Add(DateTime.Now);
3138 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3139 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3141 if (this._postTimestamps[i] < oneHour)
3142 this._postTimestamps.RemoveAt(i);
3145 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
3147 this.HashMgr.ClearHashtag();
3148 this.HashStripSplitButton.Text = "#[-]";
3149 this.HashToggleMenuItem.Checked = false;
3150 this.HashToggleToolStripMenuItem.Checked = false;
3153 this.SetMainWindowTitle();
3155 if (this._cfgCommon.PostAndGet)
3157 if (this._isActiveUserstream)
3158 this.RefreshTimeline();
3160 await this.GetHomeTimelineAsync();
3164 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
3166 await this.workerSemaphore.WaitAsync();
3170 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3172 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
3174 catch (WebApiException ex)
3176 this._myStatusError = true;
3177 this.StatusLabel.Text = ex.Message;
3181 this.workerSemaphore.Release();
3185 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
3187 if (ct.IsCancellationRequested)
3190 if (!CheckAccountValid())
3191 throw new WebApiException("Auth error. Check your account");
3194 if (!this._cfgCommon.UnreadManage)
3197 read = this._initial && this._cfgCommon.Read;
3199 p.Report("Posting...");
3201 await Task.Run(() =>
3203 foreach (var statusId in statusIds)
3205 this.tw.PostRetweet(statusId, read);
3209 if (ct.IsCancellationRequested)
3212 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3214 this._postTimestamps.Add(DateTime.Now);
3216 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3217 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3219 if (this._postTimestamps[i] < oneHour)
3220 this._postTimestamps.RemoveAt(i);
3223 if (this._cfgCommon.PostAndGet && !this._isActiveUserstream)
3224 await this.GetHomeTimelineAsync();
3227 private async Task RefreshFollowerIdsAsync()
3229 await this.workerSemaphore.WaitAsync();
3232 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
3234 await Task.Run(() => tw.RefreshFollowerIds());
3236 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
3238 this.RefreshTimeline();
3239 this.PurgeListViewItemCache();
3240 this._curList?.Refresh();
3242 catch (WebApiException ex)
3244 this.StatusLabel.Text = ex.Message;
3248 this.workerSemaphore.Release();
3252 private async Task RefreshNoRetweetIdsAsync()
3254 await this.workerSemaphore.WaitAsync();
3257 await Task.Run(() => tw.RefreshNoRetweetIds());
3259 this.StatusLabel.Text = "NoRetweetIds refreshed";
3261 catch (WebApiException ex)
3263 this.StatusLabel.Text = ex.Message;
3267 this.workerSemaphore.Release();
3271 private async Task RefreshBlockIdsAsync()
3273 await this.workerSemaphore.WaitAsync();
3276 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
3278 await Task.Run(() => tw.RefreshBlockIds());
3280 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
3282 catch (WebApiException ex)
3284 this.StatusLabel.Text = ex.Message;
3288 this.workerSemaphore.Release();
3292 private async Task RefreshTwitterConfigurationAsync()
3294 await this.workerSemaphore.WaitAsync();
3297 await Task.Run(() => tw.RefreshConfiguration());
3299 if (this.tw.Configuration.PhotoSizeLimit != 0)
3301 foreach (var service in this.ImageSelector.GetServices())
3303 service.UpdateTwitterConfiguration(this.tw.Configuration);
3307 this.PurgeListViewItemCache();
3309 this._curList?.Refresh();
3311 catch (WebApiException ex)
3313 this.StatusLabel.Text = ex.Message;
3317 this.workerSemaphore.Release();
3321 private async Task RefreshMuteUserIdsAsync()
3323 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3327 await tw.RefreshMuteUserIdsAsync();
3329 catch (WebApiException ex)
3331 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3335 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3338 private void RemovePostFromFavTab(Int64[] ids)
3340 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
3341 string favTabName = favTab.TabName;
3343 if (_curTab.Text.Equals(favTabName))
3345 fidx = _curList.FocusedItem?.Index ?? _curList.TopItem?.Index ?? 0;
3348 foreach (long i in ids)
3352 _statuses.RemoveFavPost(i);
3359 if (_curTab != null && _curTab.Text.Equals(favTabName))
3361 this.PurgeListViewItemCache();
3363 //_curItemIndex = -1;
3365 foreach (TabPage tp in ListTab.TabPages)
3367 if (tp.Text == favTabName)
3369 ((DetailsListView)tp.Tag).VirtualListSize = favTab.AllCount;
3373 if (_curTab.Text.Equals(favTabName))
3377 _curList.SelectedIndices.Clear();
3379 while (_curList.SelectedIndices.Count > 0);
3381 if (favTab.AllCount > 0)
3383 if (favTab.AllCount - 1 > fidx && fidx > -1)
3385 _curList.SelectedIndices.Add(fidx);
3389 _curList.SelectedIndices.Add(favTab.AllCount - 1);
3391 if (_curList.SelectedIndices.Count > 0)
3393 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3394 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3400 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3402 if (e.Button == MouseButtons.Left)
3404 this.Visible = true;
3405 if (this.WindowState == FormWindowState.Minimized)
3407 this.WindowState = _formWindowState;
3410 this.BringToFront();
3414 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3416 switch (this._cfgCommon.ListDoubleClickAction)
3419 MakeReplyOrDirectStatus();
3422 await this.FavoriteChange(true);
3425 if (_curPost != null)
3426 await this.ShowUserStatus(_curPost.ScreenName, false);
3432 ShowRelatedStatusesMenuItem_Click(null, null);
3435 MoveToHomeToolStripMenuItem_Click(null, null);
3438 StatusOpenMenuItem_Click(null, null);
3446 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3448 await this.FavoriteChange(true);
3451 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3453 await this.FavoriteChange(false);
3457 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3459 await this.FavoritesRetweetOfficial();
3462 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3464 await this.FavoritesRetweetUnofficial();
3467 private async Task FavoriteChange(bool FavAdd , bool multiFavoriteChangeDialogEnable = true)
3470 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3473 //trueでFavAdd,falseでFavRemove
3474 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3475 || !this.ExistCurrentPost) return;
3477 // 誤ふぁぼ・故意によるふぁぼ爆対策 (変更しないこと)
3478 // https://support.twitter.com/articles/76915#favoriting
3479 const int MultiSelectFavLimit = 1;
3482 if (_curList.SelectedIndices.Count > MultiSelectFavLimit && FavAdd)
3484 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, MultiSelectFavLimit));
3485 _DoFavRetweetFlags = false;
3488 else if (multiFavoriteChangeDialogEnable && _curList.SelectedIndices.Count > 1)
3492 string QuestionText = Properties.Resources.FavAddToolStripMenuItem_ClickText1;
3493 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText3;
3494 if (MessageBox.Show(QuestionText, Properties.Resources.FavAddToolStripMenuItem_ClickText2,
3495 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3497 _DoFavRetweetFlags = false;
3503 if (MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1, Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3504 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3511 var statusIds = new List<long>();
3512 foreach (int idx in _curList.SelectedIndices)
3514 PostClass post = GetCurTabPost(idx);
3518 statusIds.Add(post.StatusId);
3523 statusIds.Add(post.StatusId);
3526 if (statusIds.Count == 0)
3529 StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3531 StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3537 await this.FavAddAsync(statusIds, tab);
3539 await this.FavRemoveAsync(statusIds, tab);
3542 private PostClass GetCurTabPost(int Index)
3544 var listCache = this._listItemCache;
3545 if (listCache != null)
3549 if (listCache.TryGetValue(Index, out item, out post))
3553 return _statuses.Tabs[_curTab.Text][Index];
3556 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3558 if (_curList.SelectedIndices.Count > 0)
3559 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3560 else if (_curList.SelectedIndices.Count == 0)
3561 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3564 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3566 if (_curList.SelectedIndices.Count > 0)
3567 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3570 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3572 if ((!_initialLayout) && this.Visible)
3574 if (this.WindowState == FormWindowState.Normal)
3576 _mySize = this.ClientSize;
3577 _mySpDis = this.SplitContainer1.SplitterDistance;
3578 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3579 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3580 _modifySettingLocal = true;
3585 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3587 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3588 if (comparerMode == null)
3591 this.SetSortColumn(comparerMode.Value);
3595 /// 列インデックスからソートを行う ComparerMode を求める
3597 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3598 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3599 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3602 return ComparerMode.Id;
3604 switch (columnIndex)
3607 return ComparerMode.Nickname;
3609 return ComparerMode.Data;
3611 return ComparerMode.Id;
3613 return ComparerMode.Name;
3615 return ComparerMode.Source;
3617 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3623 /// 発言一覧の指定した位置の列でソートする
3625 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3626 private void SetSortColumnByDisplayIndex(int columnIndex)
3628 // 表示上の列の位置から ColumnHeader を求める
3629 var col = this._curList.Columns.Cast<ColumnHeader>()
3630 .Where(x => x.DisplayIndex == columnIndex)
3636 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3637 if (comparerMode == null)
3640 this.SetSortColumn(comparerMode.Value);
3644 /// 発言一覧の最後列の項目でソートする
3646 private void SetSortLastColumn()
3648 // 表示上の最後列にある ColumnHeader を求める
3649 var col = this._curList.Columns.Cast<ColumnHeader>()
3650 .OrderByDescending(x => x.DisplayIndex)
3653 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3654 if (comparerMode == null)
3657 this.SetSortColumn(comparerMode.Value);
3661 /// 発言一覧を指定された ComparerMode に基づいてソートする
3663 private void SetSortColumn(ComparerMode sortColumn)
3665 if (this._cfgCommon.SortOrderLock)
3668 this._statuses.ToggleSortOrder(sortColumn);
3669 this.InitColumnText();
3671 var list = this._curList;
3674 list.Columns[0].Text = this.ColumnText[0];
3675 list.Columns[1].Text = this.ColumnText[2];
3679 for (var i = 0; i <= 7; i++)
3681 list.Columns[i].Text = this.ColumnText[i];
3685 this.PurgeListViewItemCache();
3687 var tab = this._statuses.Tabs[this._curTab.Text];
3688 if (tab.AllCount > 0 && this._curPost != null)
3690 var idx = tab.IndexOf(this._curPost.StatusId);
3693 this.SelectListItem(list, idx);
3694 list.EnsureVisible(idx);
3699 this._modifySettingCommon = true;
3702 private void TweenMain_LocationChanged(object sender, EventArgs e)
3704 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3706 _myLoc = this.DesktopLocation;
3707 _modifySettingLocal = true;
3711 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3713 if (ListTab.SelectedTab == null) return;
3714 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3715 if (!this.ExistCurrentPost)
3717 ReplyStripMenuItem.Enabled = false;
3718 ReplyAllStripMenuItem.Enabled = false;
3719 DMStripMenuItem.Enabled = false;
3720 ShowProfileMenuItem.Enabled = false;
3721 ShowUserTimelineContextMenuItem.Enabled = false;
3722 ListManageUserContextToolStripMenuItem2.Enabled = false;
3723 MoveToFavToolStripMenuItem.Enabled = false;
3724 TabMenuItem.Enabled = false;
3725 IDRuleMenuItem.Enabled = false;
3726 SourceRuleMenuItem.Enabled = false;
3727 ReadedStripMenuItem.Enabled = false;
3728 UnreadStripMenuItem.Enabled = false;
3732 ShowProfileMenuItem.Enabled = true;
3733 ListManageUserContextToolStripMenuItem2.Enabled = true;
3734 ReplyStripMenuItem.Enabled = true;
3735 ReplyAllStripMenuItem.Enabled = true;
3736 DMStripMenuItem.Enabled = true;
3737 ShowUserTimelineContextMenuItem.Enabled = true;
3738 MoveToFavToolStripMenuItem.Enabled = true;
3739 TabMenuItem.Enabled = true;
3740 IDRuleMenuItem.Enabled = true;
3741 SourceRuleMenuItem.Enabled = true;
3742 ReadedStripMenuItem.Enabled = true;
3743 UnreadStripMenuItem.Enabled = true;
3745 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3747 FavAddToolStripMenuItem.Enabled = false;
3748 FavRemoveToolStripMenuItem.Enabled = false;
3749 StatusOpenMenuItem.Enabled = false;
3750 FavorareMenuItem.Enabled = false;
3751 ShowRelatedStatusesMenuItem.Enabled = false;
3753 ReTweetStripMenuItem.Enabled = false;
3754 ReTweetUnofficialStripMenuItem.Enabled = false;
3755 QuoteStripMenuItem.Enabled = false;
3756 FavoriteRetweetContextMenu.Enabled = false;
3757 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3761 FavAddToolStripMenuItem.Enabled = true;
3762 FavRemoveToolStripMenuItem.Enabled = true;
3763 StatusOpenMenuItem.Enabled = true;
3764 FavorareMenuItem.Enabled = true;
3765 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3769 ReTweetStripMenuItem.Enabled = false; //公式RTは無効に
3770 ReTweetUnofficialStripMenuItem.Enabled = true;
3771 QuoteStripMenuItem.Enabled = true;
3772 FavoriteRetweetContextMenu.Enabled = false; //公式RTは無効に
3773 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3777 if (_curPost.IsProtect)
3779 ReTweetStripMenuItem.Enabled = false;
3780 ReTweetUnofficialStripMenuItem.Enabled = false;
3781 QuoteStripMenuItem.Enabled = false;
3782 FavoriteRetweetContextMenu.Enabled = false;
3783 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3787 ReTweetStripMenuItem.Enabled = true;
3788 ReTweetUnofficialStripMenuItem.Enabled = true;
3789 QuoteStripMenuItem.Enabled = true;
3790 FavoriteRetweetContextMenu.Enabled = true;
3791 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3795 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3797 // RefreshMoreStripMenuItem.Enabled = true;
3801 // RefreshMoreStripMenuItem.Enabled = false;
3803 if (!this.ExistCurrentPost
3804 || _curPost.InReplyToStatusId == null)
3806 RepliedStatusOpenMenuItem.Enabled = false;
3810 RepliedStatusOpenMenuItem.Enabled = true;
3812 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3814 MoveToRTHomeMenuItem.Enabled = false;
3818 MoveToRTHomeMenuItem.Enabled = true;
3821 if (this.ExistCurrentPost)
3823 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3824 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3825 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3827 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3831 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3833 MakeReplyOrDirectStatus(false, true);
3836 private void DMStripMenuItem_Click(object sender, EventArgs e)
3838 MakeReplyOrDirectStatus(false, false);
3841 private void doStatusDelete()
3843 if (this._curTab == null || this._curList == null)
3846 if (this._curList.SelectedIndices.Count == 0)
3849 var posts = this._curList.SelectedIndices.Cast<int>()
3850 .Select(x => this.GetCurTabPost(x))
3853 // 選択されたツイートの中に削除可能なものが一つでもあるか
3854 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3857 var ret = MessageBox.Show(this,
3858 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3859 Properties.Resources.DeleteStripMenuItem_ClickText2,
3860 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3862 if (ret != DialogResult.OK)
3865 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3867 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3869 Exception lastException = null;
3870 foreach (var post in posts)
3872 if (!post.CanDeleteBy(this.tw.UserId))
3879 this.tw.RemoveDirectMessage(post.StatusId, post);
3883 if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3884 // 他人に RT された自分のツイート
3885 this.tw.RemoveStatus(post.RetweetedId.Value);
3887 // 自分のツイート or 自分が RT したツイート
3888 this.tw.RemoveStatus(post.StatusId);
3891 catch (WebApiException ex)
3897 this._statuses.RemovePost(post.StatusId);
3900 if (lastException == null)
3901 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3903 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3905 this.PurgeListViewItemCache();
3906 this._curPost = null;
3907 this._curItemIndex = -1;
3909 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3911 var listView = (DetailsListView)tabPage.Tag;
3912 var tab = this._statuses.Tabs[tabPage.Text];
3914 using (ControlTransaction.Update(listView))
3916 listView.VirtualListSize = tab.AllCount;
3918 if (tabPage == this._curTab)
3920 listView.SelectedIndices.Clear();
3922 if (tab.AllCount != 0)
3925 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3926 selectedIndex = focusedIndex;
3928 selectedIndex = tab.AllCount - 1;
3930 listView.SelectedIndices.Add(selectedIndex);
3931 listView.EnsureVisible(selectedIndex);
3932 listView.FocusedItem = listView.Items[selectedIndex];
3937 if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3939 if (tabPage.ImageIndex == 0)
3940 tabPage.ImageIndex = -1; // タブアイコン
3944 if (!this._cfgCommon.TabIconDisp)
3945 this.ListTab.Refresh();
3949 private void DeleteStripMenuItem_Click(object sender, EventArgs e)
3954 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3956 using (ControlTransaction.Update(this._curList))
3958 foreach (int idx in _curList.SelectedIndices)
3960 var post = this._statuses.Tabs[this._curTab.Text][idx];
3961 this._statuses.SetReadAllTab(post.StatusId, read: true);
3962 ChangeCacheStyleRead(true, idx);
3966 foreach (TabPage tb in ListTab.TabPages)
3968 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3970 if (this._cfgCommon.TabIconDisp)
3972 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3976 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3979 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3981 using (ControlTransaction.Update(this._curList))
3983 foreach (int idx in _curList.SelectedIndices)
3985 var post = this._statuses.Tabs[this._curTab.Text][idx];
3986 this._statuses.SetReadAllTab(post.StatusId, read: false);
3987 ChangeCacheStyleRead(false, idx);
3991 foreach (TabPage tb in ListTab.TabPages)
3993 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3995 if (this._cfgCommon.TabIconDisp)
3997 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
4001 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
4004 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
4006 await this.DoRefresh();
4009 private async Task DoRefresh()
4011 if (_curTab != null)
4014 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4017 switch (_statuses.Tabs[_curTab.Text].TabType)
4019 case MyCommon.TabUsageType.Mentions:
4020 await this.GetReplyAsync();
4022 case MyCommon.TabUsageType.DirectMessage:
4023 await this.GetDirectMessagesAsync();
4025 case MyCommon.TabUsageType.Favorites:
4026 await this.GetFavoritesAsync();
4028 //case MyCommon.TabUsageType.Profile:
4030 case MyCommon.TabUsageType.PublicSearch:
4032 if (string.IsNullOrEmpty(tab.SearchWords)) return;
4033 await this.GetPublicSearchAsync(tab);
4035 case MyCommon.TabUsageType.UserTimeline:
4036 await this.GetUserTimelineAsync(tab);
4038 case MyCommon.TabUsageType.Lists:
4040 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4041 await this.GetListTimelineAsync(tab);
4044 await this.GetHomeTimelineAsync();
4050 await this.GetHomeTimelineAsync();
4054 private async Task DoRefreshMore()
4057 if (_curTab != null)
4060 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4063 switch (_statuses.Tabs[_curTab.Text].TabType)
4065 case MyCommon.TabUsageType.Mentions:
4066 await this.GetReplyAsync(loadMore: true);
4068 case MyCommon.TabUsageType.DirectMessage:
4069 await this.GetDirectMessagesAsync(loadMore: true);
4071 case MyCommon.TabUsageType.Favorites:
4072 await this.GetFavoritesAsync(loadMore: true);
4074 case MyCommon.TabUsageType.Profile:
4077 case MyCommon.TabUsageType.PublicSearch:
4079 if (string.IsNullOrEmpty(tab.SearchWords)) return;
4080 await this.GetPublicSearchAsync(tab, loadMore: true);
4082 case MyCommon.TabUsageType.UserTimeline:
4083 await this.GetUserTimelineAsync(tab, loadMore: true);
4085 case MyCommon.TabUsageType.Lists:
4087 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4088 await this.GetListTimelineAsync(tab, loadMore: true);
4091 await this.GetHomeTimelineAsync(loadMore: true);
4097 await this.GetHomeTimelineAsync(loadMore: true);
4101 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
4103 DialogResult result = DialogResult.Abort;
4105 using (var settingDialog = new AppendSettingDialog())
4107 settingDialog.Icon = this.MainIcon;
4108 settingDialog.Owner = this;
4109 settingDialog.ShowInTaskbar = showTaskbarIcon;
4110 settingDialog.IntervalChanged += this.TimerInterval_Changed;
4112 settingDialog.tw = this.tw;
4113 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
4117 result = settingDialog.ShowDialog(this);
4121 return DialogResult.Abort;
4124 if (result == DialogResult.OK)
4128 settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
4136 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
4139 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
4141 var oldIconSz = this._cfgCommon.IconSize;
4143 if (ShowSettingDialog() == DialogResult.OK)
4147 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
4148 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
4149 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
4150 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
4151 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
4152 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
4154 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
4155 Networking.SetWebProxy(this._cfgLocal.ProxyType,
4156 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
4157 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
4158 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
4160 ImageSelector.Reset(tw, this.tw.Configuration);
4164 if (this._cfgCommon.TabIconDisp)
4166 ListTab.DrawItem -= ListTab_DrawItem;
4167 ListTab.DrawMode = TabDrawMode.Normal;
4168 ListTab.ImageList = this.TabImage;
4172 ListTab.DrawItem -= ListTab_DrawItem;
4173 ListTab.DrawItem += ListTab_DrawItem;
4174 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
4175 ListTab.ImageList = null;
4178 catch (Exception ex)
4180 ex.Data["Instance"] = "ListTab(TabIconDisp)";
4181 ex.Data["IsTerminatePermission"] = false;
4187 if (!this._cfgCommon.UnreadManage)
4189 ReadedStripMenuItem.Enabled = false;
4190 UnreadStripMenuItem.Enabled = false;
4191 if (this._cfgCommon.TabIconDisp)
4193 foreach (TabPage myTab in ListTab.TabPages)
4195 myTab.ImageIndex = -1;
4201 ReadedStripMenuItem.Enabled = true;
4202 UnreadStripMenuItem.Enabled = true;
4205 catch (Exception ex)
4207 ex.Data["Instance"] = "ListTab(UnreadManage)";
4208 ex.Data["IsTerminatePermission"] = false;
4215 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
4217 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
4218 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
4219 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
4221 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
4222 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
4223 _fntUnread = this._cfgLocal.FontUnread;
4224 _clUnread = this._cfgLocal.ColorUnread;
4225 _fntReaded = this._cfgLocal.FontRead;
4226 _clReaded = this._cfgLocal.ColorRead;
4227 _clFav = this._cfgLocal.ColorFav;
4228 _clOWL = this._cfgLocal.ColorOWL;
4229 _clRetweet = this._cfgLocal.ColorRetweet;
4230 _fntDetail = this._cfgLocal.FontDetail;
4231 _clDetail = this._cfgLocal.ColorDetail;
4232 _clDetailLink = this._cfgLocal.ColorDetailLink;
4233 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
4234 _clSelf = this._cfgLocal.ColorSelf;
4235 _clAtSelf = this._cfgLocal.ColorAtSelf;
4236 _clTarget = this._cfgLocal.ColorTarget;
4237 _clAtTarget = this._cfgLocal.ColorAtTarget;
4238 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
4239 _clAtTo = this._cfgLocal.ColorAtTo;
4240 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
4241 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
4242 _clInputFont = this._cfgLocal.ColorInputFont;
4243 _fntInputFont = this._cfgLocal.FontInputFont;
4244 _brsBackColorMine.Dispose();
4245 _brsBackColorAt.Dispose();
4246 _brsBackColorYou.Dispose();
4247 _brsBackColorAtYou.Dispose();
4248 _brsBackColorAtFromTarget.Dispose();
4249 _brsBackColorAtTo.Dispose();
4250 _brsBackColorNone.Dispose();
4251 _brsBackColorMine = new SolidBrush(_clSelf);
4252 _brsBackColorAt = new SolidBrush(_clAtSelf);
4253 _brsBackColorYou = new SolidBrush(_clTarget);
4254 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4255 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4256 _brsBackColorAtTo = new SolidBrush(_clAtTo);
4257 _brsBackColorNone = new SolidBrush(_clListBackcolor);
4261 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4262 StatusText.Font = _fntInputFont;
4263 StatusText.ForeColor = _clInputFont;
4265 catch (Exception ex)
4267 MessageBox.Show(ex.Message);
4272 InitDetailHtmlFormat();
4274 catch (Exception ex)
4276 ex.Data["Instance"] = "Font";
4277 ex.Data["IsTerminatePermission"] = false;
4283 foreach (TabPage tb in ListTab.TabPages)
4285 if (this._cfgCommon.TabIconDisp)
4287 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4294 catch (Exception ex)
4296 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4297 ex.Data["IsTerminatePermission"] = false;
4303 var oldIconCol = _iconCol;
4305 if (this._cfgCommon.IconSize != oldIconSz)
4306 ApplyListViewIconSize(this._cfgCommon.IconSize);
4308 foreach (TabPage tp in ListTab.TabPages)
4310 DetailsListView lst = (DetailsListView)tp.Tag;
4312 using (ControlTransaction.Update(lst))
4314 lst.GridLines = this._cfgCommon.ShowGrid;
4315 lst.Font = _fntReaded;
4316 lst.BackColor = _clListBackcolor;
4318 if (_iconCol != oldIconCol)
4323 catch (Exception ex)
4325 ex.Data["Instance"] = "ListView(IconSize)";
4326 ex.Data["IsTerminatePermission"] = false;
4330 SetMainWindowTitle();
4331 SetNotifyIconText();
4333 this.PurgeListViewItemCache();
4334 _curList?.Refresh();
4337 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4338 if (this._cfgCommon.HotkeyEnabled)
4340 ///グローバルホットキーの登録。設定で変更可能にするかも
4341 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4342 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4343 modKey |= HookGlobalHotkey.ModKeys.Alt;
4344 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4345 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4346 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4347 modKey |= HookGlobalHotkey.ModKeys.Shift;
4348 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4349 modKey |= HookGlobalHotkey.ModKeys.Win;
4351 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4354 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4357 StatusText_TextChanged(null, null);
4366 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
4367 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
4370 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4372 this.TopMost = this._cfgCommon.AlwaysTop;
4373 SaveConfigsAll(false);
4375 if (tw.Username != oldUser.Username)
4376 await this.doGetFollowersMenu();
4382 private void SetTabAlignment()
4384 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4385 if (ListTab.Alignment == newAlignment) return;
4387 // 各タブのリスト上の選択位置などを退避
4388 var listSelections = this.SaveListViewSelection();
4390 ListTab.Alignment = newAlignment;
4392 foreach (TabPage tab in ListTab.TabPages)
4394 DetailsListView lst = (DetailsListView)tab.Tag;
4395 TabClass tabInfo = _statuses.Tabs[tab.Text];
4396 using (ControlTransaction.Update(lst))
4399 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4404 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4410 case MyCommon.IconSizes.IconNone:
4413 case MyCommon.IconSizes.Icon16:
4416 case MyCommon.IconSizes.Icon24:
4419 case MyCommon.IconSizes.Icon48:
4422 case MyCommon.IconSizes.Icon48_2:
4430 // ディスプレイの DPI 設定を考慮したサイズを設定する
4431 _listViewImageList.ImageSize = new Size(
4433 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4437 _listViewImageList.ImageSize = new Size(1, 1);
4441 private void ResetColumns(DetailsListView list)
4443 using (ControlTransaction.Update(list))
4444 using (ControlTransaction.Layout(list, false))
4447 list.ColumnClick -= MyList_ColumnClick;
4448 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4449 list.ColumnReordered -= MyList_ColumnReordered;
4450 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4452 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4453 list.Columns.Clear();
4454 cols.ForEach(col => col.Dispose());
4457 InitColumns(list, true);
4459 list.ColumnClick += MyList_ColumnClick;
4460 list.DrawColumnHeader += MyList_DrawColumnHeader;
4461 list.ColumnReordered += MyList_ColumnReordered;
4462 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4466 private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4468 if (e.Url.AbsoluteUri != "about:blank")
4470 await this.DispSelectedPost();
4471 await this.OpenUriInBrowserAsync(e.Url.OriginalString);
4475 private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4477 if (e.Url.Scheme == "data")
4479 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4481 else if (e.Url.AbsoluteUri != "about:blank")
4484 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
4485 await this.OpenUriAsync( e.Url, MyCommon.IsKeyDown( Keys.Control ) );
4489 public void AddNewTabForSearch(string searchWord)
4491 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4492 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4494 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4496 foreach (TabPage tp in ListTab.TabPages)
4498 if (tb.TabName == tp.Text)
4500 ListTab.SelectedTab = tp;
4507 string tabName = searchWord;
4508 for (int i = 0; i <= 100; i++)
4510 if (_statuses.ContainsTab(tabName))
4516 _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4517 AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4519 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4521 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4522 cmb.Items.Add(searchWord);
4523 cmb.Text = searchWord;
4526 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4529 private void ShowUserTimeline()
4531 if (!this.ExistCurrentPost) return;
4532 AddNewTabForUserTimeline(_curPost.ScreenName);
4535 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4537 if (e.KeyCode == Keys.Escape)
4539 TabPage relTp = ListTab.SelectedTab;
4540 RemoveSpecifiedTab(relTp.Text, false);
4542 e.SuppressKeyPress = true;
4546 public void AddNewTabForUserTimeline(string user)
4548 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4549 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4551 if (tb.User == user)
4553 foreach (TabPage tp in ListTab.TabPages)
4555 if (tb.TabName == tp.Text)
4557 ListTab.SelectedTab = tp;
4564 string tabName = "user:" + user;
4565 while (_statuses.ContainsTab(tabName))
4570 _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4571 var tab = this._statuses.Tabs[tabName];
4573 AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4575 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4578 this.GetUserTimelineAsync(tab);
4581 public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4584 foreach (TabPage tb in ListTab.TabPages)
4586 if (tb.Text == tabName) return false;
4590 if (tabName == Properties.Resources.AddNewTabText1) return false;
4595 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4596 tabType == MyCommon.TabUsageType.Favorites ||
4597 tabType == MyCommon.TabUsageType.Home ||
4598 tabType == MyCommon.TabUsageType.Mentions ||
4599 tabType == MyCommon.TabUsageType.Related)
4601 if (_statuses.GetTabByType(tabType) != null) return false;
4605 var _tabPage = new TabPage();
4606 var _listCustom = new DetailsListView();
4608 int cnt = ListTab.TabPages.Count;
4610 ///ToDo:Create and set controls follow tabtypes
4612 using (ControlTransaction.Update(_listCustom))
4613 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4614 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4615 using (ControlTransaction.Layout(this.SplitContainer1, false))
4616 using (ControlTransaction.Layout(this.ListTab, false))
4617 using (ControlTransaction.Layout(this))
4618 using (ControlTransaction.Layout(_tabPage, false))
4620 _tabPage.Controls.Add(_listCustom);
4623 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4625 var label = new Label();
4626 label.Dock = DockStyle.Top;
4627 label.Name = "labelUser";
4628 if (tabType == MyCommon.TabUsageType.Lists)
4630 label.Text = listInfo.ToString();
4634 label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4636 label.TextAlign = ContentAlignment.MiddleLeft;
4637 using (ComboBox tmpComboBox = new ComboBox())
4639 label.Height = tmpComboBox.Height;
4641 _tabPage.Controls.Add(label);
4644 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4646 var pnl = new Panel();
4648 var lbl = new Label();
4649 var cmb = new ComboBox();
4650 var btn = new Button();
4651 var cmbLang = new ComboBox();
4653 using (ControlTransaction.Layout(pnl, false))
4655 pnl.Controls.Add(cmb);
4656 pnl.Controls.Add(cmbLang);
4657 pnl.Controls.Add(btn);
4658 pnl.Controls.Add(lbl);
4659 pnl.Name = "panelSearch";
4660 pnl.Dock = DockStyle.Top;
4661 pnl.Height = cmb.Height;
4662 pnl.Enter += SearchControls_Enter;
4663 pnl.Leave += SearchControls_Leave;
4666 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4667 cmb.Dock = DockStyle.Fill;
4668 cmb.Name = "comboSearch";
4669 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4670 cmb.ImeMode = ImeMode.NoControl;
4671 cmb.TabStop = false;
4672 cmb.AutoCompleteMode = AutoCompleteMode.None;
4673 cmb.KeyDown += SearchComboBox_KeyDown;
4676 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4677 cmbLang.Dock = DockStyle.Right;
4679 cmbLang.Name = "comboLang";
4680 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4681 cmbLang.TabStop = false;
4682 cmbLang.Items.Add("");
4683 cmbLang.Items.Add("ja");
4684 cmbLang.Items.Add("en");
4685 cmbLang.Items.Add("ar");
4686 cmbLang.Items.Add("da");
4687 cmbLang.Items.Add("nl");
4688 cmbLang.Items.Add("fa");
4689 cmbLang.Items.Add("fi");
4690 cmbLang.Items.Add("fr");
4691 cmbLang.Items.Add("de");
4692 cmbLang.Items.Add("hu");
4693 cmbLang.Items.Add("is");
4694 cmbLang.Items.Add("it");
4695 cmbLang.Items.Add("no");
4696 cmbLang.Items.Add("pl");
4697 cmbLang.Items.Add("pt");
4698 cmbLang.Items.Add("ru");
4699 cmbLang.Items.Add("es");
4700 cmbLang.Items.Add("sv");
4701 cmbLang.Items.Add("th");
4703 lbl.Text = "Search(C-S-f)";
4704 lbl.Name = "label1";
4705 lbl.Dock = DockStyle.Left;
4707 lbl.Height = cmb.Height;
4708 lbl.TextAlign = ContentAlignment.MiddleLeft;
4710 btn.Text = "Search";
4711 btn.Name = "buttonSearch";
4712 btn.UseVisualStyleBackColor = true;
4713 btn.Dock = DockStyle.Right;
4714 btn.TabStop = false;
4715 btn.Click += SearchButton_Click;
4718 if (_statuses.Tabs.TryGetValue(tabName, out tab))
4720 if (!string.IsNullOrEmpty(tab.SearchWords))
4722 cmb.Items.Add(tab.SearchWords);
4723 cmb.Text = tab.SearchWords;
4726 cmbLang.Text = tab.SearchLang;
4729 _tabPage.Controls.Add(pnl);
4733 _tabPage.Tag = _listCustom;
4734 this.ListTab.Controls.Add(_tabPage);
4736 _tabPage.Location = new Point(4, 4);
4737 _tabPage.Name = "CTab" + cnt.ToString();
4738 _tabPage.Size = new Size(380, 260);
4739 _tabPage.TabIndex = 2 + cnt;
4740 _tabPage.Text = tabName;
4741 _tabPage.UseVisualStyleBackColor = true;
4742 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4744 _listCustom.AllowColumnReorder = true;
4745 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4746 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4747 _listCustom.Dock = DockStyle.Fill;
4748 _listCustom.FullRowSelect = true;
4749 _listCustom.HideSelection = false;
4750 _listCustom.Location = new Point(0, 0);
4751 _listCustom.Margin = new Padding(0);
4752 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4753 _listCustom.ShowItemToolTips = true;
4754 _listCustom.Size = new Size(380, 260);
4755 _listCustom.UseCompatibleStateImageBehavior = false;
4756 _listCustom.View = View.Details;
4757 _listCustom.OwnerDraw = true;
4758 _listCustom.VirtualMode = true;
4759 _listCustom.Font = _fntReaded;
4760 _listCustom.BackColor = _clListBackcolor;
4762 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4763 _listCustom.AllowDrop = true;
4765 _listCustom.SmallImageList = _listViewImageList;
4767 InitColumns(_listCustom, startup);
4769 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4770 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4771 _listCustom.ColumnClick += MyList_ColumnClick;
4772 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4773 _listCustom.DragDrop += TweenMain_DragDrop;
4774 _listCustom.DragEnter += TweenMain_DragEnter;
4775 _listCustom.DragOver += TweenMain_DragOver;
4776 _listCustom.DrawItem += MyList_DrawItem;
4777 _listCustom.MouseClick += MyList_MouseClick;
4778 _listCustom.ColumnReordered += MyList_ColumnReordered;
4779 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4780 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4781 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4782 _listCustom.DrawSubItem += MyList_DrawSubItem;
4783 _listCustom.HScrolled += MyList_HScrolled;
4789 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4791 var tabInfo = _statuses.GetTabByName(TabName);
4792 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4796 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4797 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4798 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4804 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4805 if (_tabPage == null) return false;
4807 SetListProperty(); //他のタブに列幅等を反映
4810 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4811 _tabPage.Tag = null;
4813 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4814 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4815 using (ControlTransaction.Layout(this.SplitContainer1, false))
4816 using (ControlTransaction.Layout(this.ListTab, false))
4817 using (ControlTransaction.Layout(this))
4818 using (ControlTransaction.Layout(_tabPage, false))
4820 if (this.ListTab.SelectedTab == _tabPage)
4822 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4823 this._beforeSelectedTab = null;
4825 this.ListTab.Controls.Remove(_tabPage);
4828 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4830 using (Control label = _tabPage.Controls["labelUser"])
4832 _tabPage.Controls.Remove(label);
4835 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4837 using (Control pnl = _tabPage.Controls["panelSearch"])
4839 pnl.Enter -= SearchControls_Enter;
4840 pnl.Leave -= SearchControls_Leave;
4841 _tabPage.Controls.Remove(pnl);
4843 foreach (Control ctrl in pnl.Controls)
4845 if (ctrl.Name == "buttonSearch")
4847 ctrl.Click -= SearchButton_Click;
4849 else if (ctrl.Name == "comboSearch")
4851 ctrl.KeyDown -= SearchComboBox_KeyDown;
4853 pnl.Controls.Remove(ctrl);
4859 _tabPage.Controls.Remove(_listCustom);
4861 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4862 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4863 _listCustom.ColumnClick -= MyList_ColumnClick;
4864 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4865 _listCustom.DragDrop -= TweenMain_DragDrop;
4866 _listCustom.DragEnter -= TweenMain_DragEnter;
4867 _listCustom.DragOver -= TweenMain_DragOver;
4868 _listCustom.DrawItem -= MyList_DrawItem;
4869 _listCustom.MouseClick -= MyList_MouseClick;
4870 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4871 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4872 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4873 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4874 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4875 _listCustom.HScrolled -= MyList_HScrolled;
4877 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4878 _listCustom.Columns.Clear();
4879 cols.ForEach(col => col.Dispose());
4882 _listCustom.ContextMenuStrip = null;
4883 _listCustom.ColumnHeaderContextMenuStrip = null;
4884 _listCustom.Font = null;
4886 _listCustom.SmallImageList = null;
4887 _listCustom.ListViewItemSorter = null;
4890 if (_curTab.Equals(_tabPage))
4897 this.PurgeListViewItemCache();
4901 _listCustom.Dispose();
4902 _statuses.RemoveTab(TabName);
4904 foreach (TabPage tp in ListTab.TabPages)
4906 DetailsListView lst = (DetailsListView)tp.Tag;
4907 var count = _statuses.Tabs[tp.Text].AllCount;
4908 if (lst.VirtualListSize != count)
4910 lst.VirtualListSize = count;
4917 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4919 this.PurgeListViewItemCache();
4920 _beforeSelectedTab = e.TabPage;
4923 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4927 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4930 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4931 if (!dragEnableRectangle.Contains(e.Location))
4933 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4934 tn = ListTab.SelectedTab.Text;
4937 if (string.IsNullOrEmpty(tn)) return;
4939 foreach (TabPage tb in ListTab.TabPages)
4943 ListTab.DoDragDrop(tb, DragDropEffects.All);
4953 Point cpos = new Point(e.X, e.Y);
4954 for (int i = 0; i < ListTab.TabPages.Count; i++)
4956 Rectangle rect = ListTab.GetTabRect(i);
4957 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4958 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4960 _rclickTabName = ListTab.TabPages[i].Text;
4966 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4968 //_curList.Refresh();
4969 SetMainWindowTitle();
4970 SetStatusLabelUrl();
4971 SetApiStatusLabel();
4972 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4973 TabMenuControl(ListTab.SelectedTab.Text);
4974 this.PushSelectPostChain();
4975 await DispSelectedPost();
4978 private void SetListProperty()
4980 //削除などで見つからない場合は処理せず
4981 if (_curList == null) return;
4982 if (!_isColumnChanged) return;
4984 int[] dispOrder = new int[_curList.Columns.Count];
4985 for (int i = 0; i < _curList.Columns.Count; i++)
4987 for (int j = 0; j < _curList.Columns.Count; j++)
4989 if (_curList.Columns[j].DisplayIndex == i)
4998 foreach (TabPage tb in ListTab.TabPages)
5000 if (!tb.Equals(_curTab))
5002 if (tb.Tag != null && tb.Controls.Count > 0)
5004 DetailsListView lst = (DetailsListView)tb.Tag;
5005 for (int i = 0; i < lst.Columns.Count; i++)
5007 lst.Columns[dispOrder[i]].DisplayIndex = i;
5008 lst.Columns[i].Width = _curList.Columns[i].Width;
5014 _isColumnChanged = false;
5017 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
5021 if (PostBrowser.StatusText.StartsWith("http") || PostBrowser.StatusText.StartsWith("ftp")
5022 || PostBrowser.StatusText.StartsWith("data"))
5024 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
5026 if (string.IsNullOrEmpty(PostBrowser.StatusText))
5028 SetStatusLabelUrl();
5036 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
5038 if (e.KeyChar == '@')
5040 if (!this._cfgCommon.UseAtIdSupplement) return;
5042 int cnt = AtIdSupl.ItemCount;
5043 ShowSuplDialog(StatusText, AtIdSupl);
5044 if (cnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
5047 else if (e.KeyChar == '#')
5049 if (!this._cfgCommon.UseHashSupplement) return;
5050 ShowSuplDialog(StatusText, HashSupl);
5055 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
5057 ShowSuplDialog(owner, dialog, 0, "");
5060 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
5062 ShowSuplDialog(owner, dialog, offset, "");
5065 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
5067 dialog.StartsWith = startswith;
5074 dialog.ShowDialog();
5076 this.TopMost = this._cfgCommon.AlwaysTop;
5077 int selStart = owner.SelectionStart;
5080 if (dialog.DialogResult == DialogResult.OK)
5082 if (!string.IsNullOrEmpty(dialog.inputText))
5086 fHalf = owner.Text.Substring(0, selStart - offset);
5088 if (selStart < owner.Text.Length)
5090 eHalf = owner.Text.Substring(selStart);
5092 owner.Text = fHalf + dialog.inputText + eHalf;
5093 owner.SelectionStart = selStart + dialog.inputText.Length;
5100 fHalf = owner.Text.Substring(0, selStart);
5102 if (selStart < owner.Text.Length)
5104 eHalf = owner.Text.Substring(selStart);
5106 owner.Text = fHalf + eHalf;
5109 owner.SelectionStart = selStart;
5115 private void StatusText_KeyUp(object sender, KeyEventArgs e)
5118 if (!e.Alt && !e.Control && !e.Shift)
5120 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
5122 bool isSpace = false;
5123 foreach (char c in StatusText.Text.ToCharArray())
5125 if (c == ' ' || c == ' ')
5138 StatusText.Text = "";
5139 JumpUnreadMenuItem_Click(null, null);
5143 this.StatusText_TextChanged(null, null);
5146 private void StatusText_TextChanged(object sender, EventArgs e)
5149 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
5150 lblLen.Text = pLen.ToString();
5153 StatusText.ForeColor = Color.Red;
5157 StatusText.ForeColor = _clInputFont;
5159 if (string.IsNullOrEmpty(StatusText.Text))
5161 this.inReplyTo = null;
5166 /// ツイート投稿前のフッター付与などの前処理を行います
5168 private string FormatStatusText(string statusText)
5170 statusText = statusText.Replace("\r\n", "\n");
5172 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
5175 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
5178 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
5180 // 文中の全角スペースを半角スペース1個にする
5181 statusText = statusText.Replace(" ", " ");
5184 // DM の場合はこれ以降の処理を行わない
5185 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
5189 if (this._cfgCommon.PostShiftEnter)
5191 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5195 if (this.StatusText.Multiline)
5196 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5198 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
5201 if (statusText.Contains("RT @"))
5202 disableFooter = true;
5207 var hashtag = this.HashMgr.UseHash;
5208 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
5211 header = HashMgr.UseHash + " ";
5213 footer = " " + HashMgr.UseHash;
5218 if (this._cfgLocal.UseRecommendStatus)
5221 footer += this.recommendedStatusFooter;
5223 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
5225 // テキストボックスに入力されている文字列を使用する
5226 footer += " " + this._cfgLocal.StatusText.Trim();
5230 statusText = header + statusText + footer;
5232 if (this.ToolStripMenuItemApiCommandEvasion.Checked)
5235 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
5236 && !statusText.EndsWith(" .", StringComparison.Ordinal))
5244 /// 投稿欄に表示する入力可能な文字数を計算します
5246 private int GetRestStatusCount(string statusText)
5249 var remainCount = this.tw.GetTextLengthRemain(statusText);
5251 if (this.ImageSelector.Visible && !string.IsNullOrEmpty(this.ImageSelector.ServiceName))
5253 remainCount -= this.tw.Configuration.CharactersReservedPerMedia;
5259 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5261 if (sender != this._curList)
5264 var listCache = this._listItemCache;
5265 if (listCache != null && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
5267 // If the newly requested cache is a subset of the old cache,
5268 // no need to rebuild everything, so do nothing.
5272 // Now we need to rebuild the cache.
5273 this.CreateCache(e.StartIndex, e.EndIndex);
5276 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5278 var listCache = this._listItemCache;
5279 if (listCache != null && listCache.TargetList == sender)
5282 PostClass cacheItemPost;
5283 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
5290 // A cache miss, so create a new ListViewItem and pass it back.
5291 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5294 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
5298 // 不正な要求に対する間に合わせの応答
5299 string[] sitem = {"", "", "", "", "", "", "", ""};
5300 e.Item = new ImageListViewItem(sitem);
5304 private void CreateCache(int startIndex, int endIndex)
5306 var tabInfo = this._statuses.Tabs[this._curTab.Text];
5308 // キャッシュ要求(要求範囲±30を作成)
5309 startIndex = Math.Max(startIndex - 30, 0);
5310 endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
5312 var cacheLength = endIndex - startIndex + 1;
5314 var posts = tabInfo[startIndex, endIndex]; //配列で取得
5315 var listItems = Enumerable.Range(0, cacheLength)
5316 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
5319 var listCache = new ListViewItemCache
5321 TargetList = this._curList,
5322 StartIndex = startIndex,
5323 EndIndex = endIndex,
5325 ListItem = listItems,
5328 Interlocked.Exchange(ref this._listItemCache, listCache);
5332 /// DetailsListView のための ListViewItem のキャッシュを消去する
5334 private void PurgeListViewItemCache()
5336 Interlocked.Exchange(ref this._listItemCache, null);
5339 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5341 StringBuilder mk = new StringBuilder();
5342 //if (Post.IsDeleted) mk.Append("×");
5343 //if (Post.IsMark) mk.Append("♪");
5344 //if (Post.IsProtect) mk.Append("Ю");
5345 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5346 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5347 ImageListViewItem itm;
5348 if (Post.RetweetedId == null)
5350 string[] sitem= {"",
5352 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5353 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5358 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5362 string[] sitem = {"",
5364 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5365 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5366 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5370 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5372 itm.StateIndex = Post.StateIndex;
5374 bool read = Post.IsRead;
5375 //未読管理していなかったら既読として扱う
5376 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5377 ChangeItemStyleRead(read, itm, Post, null);
5378 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5383 /// 全てのタブの振り分けルールを反映し直します
5385 private void ApplyPostFilters()
5387 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5389 this.PurgeListViewItemCache();
5390 this._curPost = null;
5391 this._curItemIndex = -1;
5392 this._statuses.FilterAll();
5394 foreach (TabPage tabPage in this.ListTab.TabPages)
5396 var tab = this._statuses.Tabs[tabPage.Text];
5398 var listview = (DetailsListView)tabPage.Tag;
5399 using (ControlTransaction.Update(listview))
5401 listview.VirtualListSize = tab.AllCount;
5404 if (this._cfgCommon.TabIconDisp)
5406 if (tab.UnreadCount > 0)
5407 tabPage.ImageIndex = 0;
5409 tabPage.ImageIndex = -1;
5413 if (!this._cfgCommon.TabIconDisp)
5414 this.ListTab.Refresh();
5416 SetMainWindowTitle();
5417 SetStatusLabelUrl();
5421 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5423 e.DrawDefault = true;
5426 private void MyList_HScrolled(object sender, EventArgs e)
5428 DetailsListView listView = (DetailsListView)sender;
5432 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5434 if (e.State == 0) return;
5435 e.DrawDefault = false;
5437 SolidBrush brs2 = null;
5438 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5440 if (e.Item.BackColor == _clSelf)
5441 brs2 = _brsBackColorMine;
5442 else if (e.Item.BackColor == _clAtSelf)
5443 brs2 = _brsBackColorAt;
5444 else if (e.Item.BackColor == _clTarget)
5445 brs2 = _brsBackColorYou;
5446 else if (e.Item.BackColor == _clAtTarget)
5447 brs2 = _brsBackColorAtYou;
5448 else if (e.Item.BackColor == _clAtFromTarget)
5449 brs2 = _brsBackColorAtFromTarget;
5450 else if (e.Item.BackColor == _clAtTo)
5451 brs2 = _brsBackColorAtTo;
5453 brs2 = _brsBackColorNone;
5458 if (((Control)sender).Focused)
5459 brs2 = _brsHighLight;
5461 brs2 = _brsDeactiveSelection;
5463 e.Graphics.FillRectangle(brs2, e.Bounds);
5464 e.DrawFocusRectangle();
5465 this.DrawListViewItemIcon(e);
5468 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5470 if (e.ItemState == 0) return;
5472 if (e.ColumnIndex > 0)
5475 RectangleF rct = e.Bounds;
5476 rct.Width = e.Header.Width;
5477 int fontHeight = e.Item.Font.Height;
5480 rct.Y += fontHeight;
5481 rct.Height -= fontHeight;
5485 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5487 //if (heightDiff > fontHeight * 0.7)
5489 // rct.Height += fontHeight;
5490 // drawLineCount += 1;
5493 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5494 if (!_iconCol && drawLineCount <= 1)
5496 //rct.Inflate(0, heightDiff / -2);
5497 //rct.Height += fontHeight / 2;
5499 else if (heightDiff < fontHeight * 0.7)
5501 //最終行が70%以上欠けていたら、最終行は表示しない
5502 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5503 rct.Height = (fontHeight * drawLineCount) - 1;
5510 //if (!_iconCol && drawLineCount > 1)
5512 // rct.Y += fontHeight * 0.2;
5513 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5518 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5519 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5524 Rectangle rctB = e.Bounds;
5525 rctB.Width = e.Header.Width;
5526 rctB.Height = fontHeight;
5528 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5530 TextRenderer.DrawText(e.Graphics,
5531 e.Item.SubItems[2].Text,
5533 Rectangle.Round(rct),
5535 TextFormatFlags.WordBreak |
5536 TextFormatFlags.EndEllipsis |
5537 TextFormatFlags.GlyphOverhangPadding |
5538 TextFormatFlags.NoPrefix);
5539 TextRenderer.DrawText(e.Graphics,
5540 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 + "]",
5544 TextFormatFlags.SingleLine |
5545 TextFormatFlags.EndEllipsis |
5546 TextFormatFlags.GlyphOverhangPadding |
5547 TextFormatFlags.NoPrefix);
5550 else if (drawLineCount == 1)
5552 TextRenderer.DrawText(e.Graphics,
5555 Rectangle.Round(rct),
5557 TextFormatFlags.SingleLine |
5558 TextFormatFlags.EndEllipsis |
5559 TextFormatFlags.GlyphOverhangPadding |
5560 TextFormatFlags.NoPrefix |
5561 TextFormatFlags.VerticalCenter);
5565 TextRenderer.DrawText(e.Graphics,
5568 Rectangle.Round(rct),
5570 TextFormatFlags.WordBreak |
5571 TextFormatFlags.EndEllipsis |
5572 TextFormatFlags.GlyphOverhangPadding |
5573 TextFormatFlags.NoPrefix);
5575 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5580 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5582 if (_iconSz == 0) return;
5584 ImageListViewItem item = (ImageListViewItem)e.Item;
5586 //e.Bounds.Leftが常に0を指すから自前で計算
5587 Rectangle itemRect = item.Bounds;
5588 var col0 = e.Item.ListView.Columns[0];
5589 itemRect.Width = col0.Width;
5591 if (col0.DisplayIndex > 0)
5593 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5595 if (clm.DisplayIndex < col0.DisplayIndex)
5596 itemRect.X += clm.Width;
5600 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5601 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5602 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5605 var img = item.Image;
5608 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5609 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5611 if (iconRect.Width > 0)
5613 e.Graphics.FillRectangle(Brushes.White, iconRect);
5614 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5617 e.Graphics.DrawImage(img.Image, iconRect);
5619 catch (ArgumentException)
5621 item.RefreshImageAsync();
5627 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5628 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5630 item.GetImageAsync();
5633 if (item.StateIndex > -1)
5635 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5636 if (stateRect.Width > 0)
5638 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5639 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5640 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5645 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5647 base.ScaleControl(factor, specified);
5649 ScaleChildControl(this.TabImage, factor);
5651 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5652 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5654 foreach (var listview in listviews)
5656 ScaleChildControl(listview, factor);
5660 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5662 // ImageListViewItem item = (ImageListViewItem)e.Item;
5663 // if (item.StateImageIndex > -1)
5665 // ////e.Bounds.Leftが常に0を指すから自前で計算
5666 // //Rectangle itemRect = item.Bounds;
5667 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5669 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5671 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5673 // // itemRect.X += clm.Width;
5677 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5678 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5680 // if (rct.Width > 0)
5682 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5683 // //e.Graphics.FillRectangle(Brushes.White, rct);
5684 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5685 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5690 private void DoTabSearch(string _word,
5700 if (_curList.VirtualListSize == 0)
5702 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5705 if (_curList.SelectedIndices.Count > 0)
5707 cidx = _curList.SelectedIndices[0];
5709 toIdx = _curList.VirtualListSize;
5713 case SEARCHTYPE.DialogSearch: //ダイアログからの検索
5714 if (_curList.SelectedIndices.Count > 0)
5715 cidx = _curList.SelectedIndices[0];
5719 case SEARCHTYPE.NextSearch: //次を検索
5720 if (_curList.SelectedIndices.Count > 0)
5722 cidx = _curList.SelectedIndices[0] + 1;
5723 if (cidx > toIdx) cidx = toIdx;
5730 case SEARCHTYPE.PrevSearch: //前を検索
5731 if (_curList.SelectedIndices.Count > 0)
5733 cidx = _curList.SelectedIndices[0] - 1;
5734 if (cidx < 0) cidx = 0;
5745 RegexOptions regOpt = RegexOptions.None;
5746 StringComparison fndOpt = StringComparison.Ordinal;
5749 regOpt = RegexOptions.IgnoreCase;
5750 fndOpt = StringComparison.OrdinalIgnoreCase;
5761 _search = new Regex(_word, regOpt);
5762 for (int idx = cidx; idx != toIdx; idx += stp)
5767 post = _statuses.Tabs[_curTab.Text][idx];
5773 if (_search.IsMatch(post.Nickname)
5774 || _search.IsMatch(post.TextFromApi)
5775 || _search.IsMatch(post.ScreenName))
5777 SelectListItem(_curList, idx);
5778 _curList.EnsureVisible(idx);
5783 catch (ArgumentException)
5785 MessageBox.Show(Properties.Resources.DoTabSearchText1, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
5792 for (int idx = cidx; idx != toIdx; idx += stp)
5797 post = _statuses.Tabs[_curTab.Text][idx];
5803 if (post.Nickname.IndexOf(_word, fndOpt) > -1
5804 || post.TextFromApi.IndexOf(_word, fndOpt) > -1
5805 || post.ScreenName.IndexOf(_word, fndOpt) > -1)
5807 SelectListItem(_curList, idx);
5808 _curList.EnsureVisible(idx);
5818 case SEARCHTYPE.DialogSearch:
5819 case SEARCHTYPE.NextSearch:
5823 case SEARCHTYPE.PrevSearch:
5825 cidx = _curList.VirtualListSize - 1;
5832 catch (ArgumentOutOfRangeException)
5835 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5838 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5841 this.ShowSearchDialog();
5844 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5846 var previousSearch = this.SearchDialog.ResultOptions;
5847 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5849 this.SearchDialog.Reset();
5850 this.ShowSearchDialog();
5856 previousSearch.Query,
5857 previousSearch.CaseSensitive,
5858 previousSearch.UseRegex,
5859 SEARCHTYPE.NextSearch);
5862 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5864 var previousSearch = this.SearchDialog.ResultOptions;
5865 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5867 this.SearchDialog.Reset();
5868 this.ShowSearchDialog();
5874 previousSearch.Query,
5875 previousSearch.CaseSensitive,
5876 previousSearch.UseRegex,
5877 SEARCHTYPE.PrevSearch);
5881 /// 検索ダイアログを表示し、検索を実行します
5883 private void ShowSearchDialog()
5885 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5887 this.TopMost = this._cfgCommon.AlwaysTop;
5890 this.TopMost = this._cfgCommon.AlwaysTop;
5892 var searchOptions = this.SearchDialog.ResultOptions;
5893 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5895 if (searchOptions.NewTab)
5897 var tabName = Properties.Resources.SearchResults_TabName;
5901 tabName = this._statuses.MakeTabName(tabName);
5903 catch (TabException ex)
5905 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5908 this.AddNewTab(tabName, false, MyCommon.TabUsageType.SearchResults);
5909 this._statuses.AddTab(tabName, MyCommon.TabUsageType.SearchResults, null);
5911 var filter = new PostFilterRule
5913 FilterBody = new[] { searchOptions.Query },
5914 UseRegex = searchOptions.UseRegex,
5915 CaseSensitive = searchOptions.CaseSensitive,
5918 var targetTab = this._statuses.Tabs[this._curTab.Text];
5919 var posts = targetTab.Posts.Values
5920 .Where(x => filter.ExecFilter(x) == MyCommon.HITRESULT.CopyAndMark)
5921 .Where(x => targetTab.Contains(x.StatusId));
5923 var resultTab = this._statuses.Tabs[tabName];
5924 foreach (var post in posts)
5926 resultTab.AddPostToInnerStorage(post);
5929 this._statuses.DistributePosts();
5930 this.RefreshTimeline();
5932 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5933 .First(x => x.Text == tabName);
5935 this.ListTab.SelectedTab = tabPage;
5940 searchOptions.Query,
5941 searchOptions.CaseSensitive,
5942 searchOptions.UseRegex,
5943 SEARCHTYPE.DialogSearch);
5946 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5948 this.AddNewTabForSearch(searchOptions.Query);
5952 private void AboutMenuItem_Click(object sender, EventArgs e)
5954 using (TweenAboutBox about = new TweenAboutBox())
5956 about.ShowDialog(this);
5958 this.TopMost = this._cfgCommon.AlwaysTop;
5961 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5963 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5965 DetailsListView lst = null;
5967 if (ImageSelector.Enabled)
5971 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5974 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5977 ListTab.SelectedIndex = i;
5978 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5979 //_curTab = ListTab.TabPages[i];
5984 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5985 if (idx == -1 && bgnIdx > 0)
5987 for (int i = 0; i < bgnIdx; i++)
5989 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5992 ListTab.SelectedIndex = i;
5993 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5994 //_curTab = ListTab.TabPages[i];
6000 //全部調べたが未読見つからず→先頭タブの最新発言へ
6003 ListTab.SelectedIndex = 0;
6004 lst = (DetailsListView)ListTab.TabPages[0].Tag;
6005 //_curTab = ListTab.TabPages[0];
6006 if (_statuses.SortOrder == SortOrder.Ascending)
6007 idx = lst.VirtualListSize - 1;
6012 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
6014 SelectListItem(lst, idx);
6015 if (_statuses.SortMode == ComparerMode.Id)
6017 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
6018 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
6024 lst.EnsureVisible(idx);
6029 lst.EnsureVisible(idx);
6035 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
6037 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
6039 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6040 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
6044 private async void FavorareMenuItem_Click(object sender, EventArgs e)
6046 if (_curList.SelectedIndices.Count > 0)
6048 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6049 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
6053 private async void VerUpMenuItem_Click(object sender, EventArgs e)
6055 await this.CheckNewVersion(false);
6058 private void RunTweenUp()
6060 ProcessStartInfo pinfo = new ProcessStartInfo();
6061 pinfo.UseShellExecute = true;
6062 pinfo.WorkingDirectory = MyCommon.settingPath;
6063 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
6064 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
6067 Process.Start(pinfo);
6071 MessageBox.Show("Failed to execute TweenUp3.exe.");
6075 public class VersionInfo
6077 public Version Version { get; set; }
6078 public Uri DownloadUri { get; set; }
6079 public string ReleaseNote { get; set; }
6083 /// OpenTween の最新バージョンの情報を取得します
6085 public async Task<VersionInfo> GetVersionInfoAsync()
6087 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
6088 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
6090 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
6091 .ConfigureAwait(false);
6093 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
6094 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
6096 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
6097 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
6099 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
6101 return new VersionInfo
6103 Version = Version.Parse(msgHeader[0]),
6104 DownloadUri = new Uri(msgHeader[1]),
6105 ReleaseNote = msgBody,
6109 private async Task CheckNewVersion(bool startup = false)
6111 if (ApplicationSettings.VersionInfoUrl == null)
6112 return; // 更新チェック無効化
6116 var versionInfo = await this.GetVersionInfoAsync();
6118 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
6123 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
6124 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
6125 msgtext = MyCommon.ReplaceAppName(msgtext);
6127 MessageBox.Show(msgtext,
6128 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6129 MessageBoxButtons.OK, MessageBoxIcon.Information);
6134 using (var dialog = new UpdateDialog())
6136 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
6137 MyCommon.GetReadableVersion(versionInfo.Version));
6138 dialog.DetailsText = versionInfo.ReleaseNote;
6140 if (dialog.ShowDialog(this) == DialogResult.Yes)
6142 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
6148 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
6151 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
6152 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6153 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
6158 private async Task Colorize()
6161 await this.DispSelectedPost();
6162 //件数関連の場合、タイトル即時書き換え
6163 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
6164 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6165 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6166 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6168 SetMainWindowTitle();
6170 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6171 foreach (TabPage tb in ListTab.TabPages)
6173 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6175 if (this._cfgCommon.TabIconDisp)
6177 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6181 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
6184 public string createDetailHtml(string orgdata)
6186 if (this._cfgLocal.UseTwemoji)
6187 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
6189 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6192 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6194 if (sender.Equals(displayItem))
6196 this.ClearUserPicture();
6198 var img = displayItem.Image;
6202 img = await img.CloneAsync();
6204 UserPicture.Image = img;
6208 UserPicture.ShowErrorImage();
6213 private Task DispSelectedPost()
6215 return this.DispSelectedPost(false);
6218 private PostClass displayPost = new PostClass();
6221 /// サムネイル表示に使用する CancellationToken の生成元
6223 private CancellationTokenSource thumbnailTokenSource = null;
6225 private async Task DispSelectedPost(bool forceupdate)
6227 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6230 var oldDisplayPost = this.displayPost;
6231 this.displayPost = this._curPost;
6233 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6236 if (displayItem != null)
6238 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6241 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6242 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6244 using (ControlTransaction.Update(this.TableLayoutPanel1))
6246 SourceLinkLabel.Text = this._curPost.Source;
6247 SourceLinkLabel.Tag = this._curPost.SourceUri;
6248 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6254 nameText = "DM FROM <- ";
6256 nameText = "DM TO -> ";
6262 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6263 if (_curPost.RetweetedId != null)
6264 nameText += " (RT:" + _curPost.RetweetedBy + ")";
6266 NameLabel.Text = nameText;
6267 NameLabel.Tag = _curPost.ScreenName;
6269 var nameForeColor = SystemColors.ControlText;
6270 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6271 nameForeColor = this._clOWL;
6272 if (_curPost.RetweetedId != null)
6273 nameForeColor = this._clRetweet;
6275 nameForeColor = this._clFav;
6276 NameLabel.ForeColor = nameForeColor;
6278 this.ClearUserPicture();
6280 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6282 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6285 UserPicture.Image = image?.Clone();
6289 UserPicture.ShowErrorImage();
6293 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6296 if (DumpPostClassToolStripMenuItem.Checked)
6298 StringBuilder sb = new StringBuilder(512);
6300 sb.Append("-----Start PostClass Dump<br>");
6301 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
6302 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6303 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
6304 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
6305 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
6306 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
6307 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
6308 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
6309 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
6310 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
6311 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
6312 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
6313 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
6314 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
6315 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
6317 foreach (string nm in _curPost.ReplyToList)
6319 sb.AppendFormat("ReplyToList : {0}<br>", nm);
6322 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
6323 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
6324 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
6325 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
6326 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
6327 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
6328 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
6329 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
6330 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
6331 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
6333 sb.AppendFormat("Media.Count : {0}<br>", _curPost.Media.Count);
6334 if (_curPost.Media.Count > 0)
6336 for (int i = 0; i < _curPost.Media.Count; i++)
6338 var info = _curPost.Media[i];
6339 sb.AppendFormat("Media[{0}].Url : {1}<br>", i, info.Url);
6340 sb.AppendFormat("Media[{0}].VideoUrl : {1}<br>", i, info.VideoUrl ?? "---");
6343 sb.Append("-----End PostClass Dump<br>");
6345 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6349 var loadTasks = new List<Task>();
6351 // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6352 // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6353 if (_curPost.StatusId != oldDisplayPost.StatusId)
6355 using (ControlTransaction.Update(this.PostBrowser))
6357 this.PostBrowser.DocumentText =
6358 this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6360 this.PostBrowser.Document.Window.ScrollTo(0, 0);
6363 this.SplitContainer3.Panel2Collapsed = true;
6365 if (this._cfgCommon.PreviewEnable)
6367 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
6368 oldTokenSource?.Cancel();
6370 var token = this.thumbnailTokenSource.Token;
6371 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
6374 loadTasks.Add(this.AppendQuoteTweetAsync(this._curPost));
6379 await Task.WhenAll(loadTasks);
6381 catch (OperationCanceledException) { }
6385 /// 発言詳細欄のツイートURLを展開する
6387 private async Task AppendQuoteTweetAsync(PostClass post)
6389 var statusIds = post.QuoteStatusIds;
6390 if (statusIds.Length == 0)
6394 var loadingQuoteHtml = statusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText));
6395 var body = post.Text + string.Concat(loadingQuoteHtml);
6397 using (ControlTransaction.Update(this.PostBrowser))
6398 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6401 var quoteHtmls = await Task.WhenAll(statusIds.Select(x => this.CreateQuoteTweetHtml(x)));
6403 // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
6404 if (this._curPost != post || this._curPost.IsDeleted)
6407 body = post.Text + string.Concat(quoteHtmls);
6409 using (ControlTransaction.Update(this.PostBrowser))
6410 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6413 private async Task<string> CreateQuoteTweetHtml(long statusId)
6415 PostClass post = this._statuses[statusId];
6420 post = await Task.Run(() => this.tw.GetStatusApi(false, statusId))
6421 .ConfigureAwait(false);
6423 catch (WebApiException ex)
6425 return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode(ex.Message));
6429 if (!this._statuses.AddQuoteTweet(post))
6430 return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.");
6433 return FormatQuoteTweetHtml(post);
6436 internal static string FormatQuoteTweetHtml(PostClass post)
6438 var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
6439 " — " + WebUtility.HtmlEncode(post.Nickname) +
6440 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
6441 WebUtility.HtmlEncode(post.CreatedAt.ToString());
6443 return FormatQuoteTweetHtml(post.StatusId, innerHtml);
6446 internal static string FormatQuoteTweetHtml(long statusId, string innerHtml)
6448 return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
6449 "<blockquote class=\"quote-tweet\">" + innerHtml + "</blockquote>" +
6454 /// 指定されたHTMLからリンクを除去します
6456 internal static string StripLinkTagHtml(string html)
6458 // a 要素はネストされていない前提の正規表現パターン
6459 return Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1");
6462 private async void MatomeMenuItem_Click(object sender, EventArgs e)
6464 await this.OpenApplicationWebsite();
6467 private async Task OpenApplicationWebsite()
6469 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
6472 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6474 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
6477 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
6479 if (ListTab.SelectedTab != null)
6481 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6483 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6484 if (pnl.Controls["comboSearch"].Focused ||
6485 pnl.Controls["comboLang"].Focused ||
6486 pnl.Controls["buttonSearch"].Focused) return;
6489 if (e.Control || e.Shift || e.Alt)
6490 this._anchorFlag = false;
6493 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
6496 e.SuppressKeyPress = true;
6499 if (asyncTask != null)
6504 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
6506 private void InitializeShortcuts()
6508 this.shortcutCommands = new[]
6510 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6511 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
6512 .FocusedOn(FocusedControl.ListTab)
6513 .Do(() => SendKeys.Send("{DOWN}")),
6515 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
6516 .FocusedOn(FocusedControl.ListTab)
6517 .Do(() => SendKeys.Send("{UP}")),
6519 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
6520 .FocusedOn(FocusedControl.ListTab)
6521 .Do(() => SendKeys.Send("{PGDN}")),
6523 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
6524 .FocusedOn(FocusedControl.ListTab)
6525 .Do(() => SendKeys.Send("{PGUP}")),
6527 ShortcutCommand.Create(Keys.F1)
6528 .Do(() => this.OpenApplicationWebsite()),
6530 ShortcutCommand.Create(Keys.F3)
6531 .Do(() => this.MenuItemSearchNext_Click(null, null)),
6533 ShortcutCommand.Create(Keys.F5)
6534 .Do(() => this.DoRefresh()),
6536 ShortcutCommand.Create(Keys.F6)
6537 .Do(() => this.GetReplyAsync()),
6539 ShortcutCommand.Create(Keys.F7)
6540 .Do(() => this.GetDirectMessagesAsync()),
6542 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
6543 .NotFocusedOn(FocusedControl.StatusText)
6544 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
6546 ShortcutCommand.Create(Keys.G)
6547 .NotFocusedOn(FocusedControl.StatusText)
6548 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
6550 ShortcutCommand.Create(Keys.Right, Keys.N)
6551 .FocusedOn(FocusedControl.ListTab)
6552 .Do(() => this.GoRelPost(forward: true)),
6554 ShortcutCommand.Create(Keys.Left, Keys.P)
6555 .FocusedOn(FocusedControl.ListTab)
6556 .Do(() => this.GoRelPost(forward: false)),
6558 ShortcutCommand.Create(Keys.OemPeriod)
6559 .FocusedOn(FocusedControl.ListTab)
6560 .Do(() => this.GoAnchor()),
6562 ShortcutCommand.Create(Keys.I)
6563 .FocusedOn(FocusedControl.ListTab)
6564 .OnlyWhen(() => this.StatusText.Enabled)
6565 .Do(() => this.StatusText.Focus()),
6567 ShortcutCommand.Create(Keys.Enter)
6568 .FocusedOn(FocusedControl.ListTab)
6569 .Do(() => this.MakeReplyOrDirectStatus()),
6571 ShortcutCommand.Create(Keys.R)
6572 .FocusedOn(FocusedControl.ListTab)
6573 .Do(() => this.DoRefresh()),
6575 ShortcutCommand.Create(Keys.L)
6576 .FocusedOn(FocusedControl.ListTab)
6577 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
6579 ShortcutCommand.Create(Keys.H)
6580 .FocusedOn(FocusedControl.ListTab)
6581 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6583 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6584 .FocusedOn(FocusedControl.ListTab)
6585 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6587 ShortcutCommand.Create(Keys.S)
6588 .FocusedOn(FocusedControl.ListTab)
6589 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6591 ShortcutCommand.Create(Keys.A)
6592 .FocusedOn(FocusedControl.ListTab)
6593 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6595 // ] in_reply_to参照元へ戻る
6596 ShortcutCommand.Create(Keys.Oem4)
6597 .FocusedOn(FocusedControl.ListTab)
6598 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6600 // [ in_reply_toへジャンプ
6601 ShortcutCommand.Create(Keys.Oem6)
6602 .FocusedOn(FocusedControl.ListTab)
6603 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6605 ShortcutCommand.Create(Keys.Escape)
6606 .FocusedOn(FocusedControl.ListTab)
6608 this._anchorFlag = false;
6609 if (ListTab.SelectedTab != null)
6611 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6612 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6614 var relTp = ListTab.SelectedTab;
6615 RemoveSpecifiedTab(relTp.Text, false);
6621 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
6622 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
6623 .FocusedOn(FocusedControl.ListTab)
6624 .Do(() => this._anchorFlag = false, preventDefault: false),
6626 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6627 ShortcutCommand.Create(Keys.Up, Keys.Down)
6628 .FocusedOn(FocusedControl.PostBrowser)
6631 ShortcutCommand.Create(Keys.Control | Keys.R)
6632 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6634 ShortcutCommand.Create(Keys.Control | Keys.D)
6635 .Do(() => this.doStatusDelete()),
6637 ShortcutCommand.Create(Keys.Control | Keys.M)
6638 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6640 ShortcutCommand.Create(Keys.Control | Keys.S)
6641 .Do(() => this.FavoriteChange(FavAdd: true)),
6643 ShortcutCommand.Create(Keys.Control | Keys.I)
6644 .Do(() => this.doRepliedStatusOpen()),
6646 ShortcutCommand.Create(Keys.Control | Keys.Q)
6647 .Do(() => this.doQuoteOfficial()),
6649 ShortcutCommand.Create(Keys.Control | Keys.B)
6650 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6652 ShortcutCommand.Create(Keys.Control | Keys.T)
6653 .Do(() => this.HashManageMenuItem_Click(null, null)),
6655 ShortcutCommand.Create(Keys.Control | Keys.L)
6656 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6658 ShortcutCommand.Create(Keys.Control | Keys.Y)
6659 .NotFocusedOn(FocusedControl.PostBrowser)
6660 .Do(() => this.MultiLineMenuItem_Click(null, null)),
6662 ShortcutCommand.Create(Keys.Control | Keys.F)
6663 .Do(() => this.MenuItemSubSearch_Click(null, null)),
6665 ShortcutCommand.Create(Keys.Control | Keys.U)
6666 .Do(() => this.ShowUserTimeline()),
6668 ShortcutCommand.Create(Keys.Control | Keys.H)
6669 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6671 ShortcutCommand.Create(Keys.Control | Keys.G)
6672 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6674 ShortcutCommand.Create(Keys.Control | Keys.O)
6675 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6677 ShortcutCommand.Create(Keys.Control | Keys.E)
6678 .Do(() => this.OpenURLMenuItem_Click(null, null)),
6680 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6681 .FocusedOn(FocusedControl.ListTab)
6682 .Do(() => this._colorize = true, preventDefault: false),
6684 ShortcutCommand.Create(Keys.Control | Keys.N)
6685 .FocusedOn(FocusedControl.ListTab)
6686 .Do(() => this.GoNextTab(forward: true)),
6688 ShortcutCommand.Create(Keys.Control | Keys.P)
6689 .FocusedOn(FocusedControl.ListTab)
6690 .Do(() => this.GoNextTab(forward: false)),
6692 ShortcutCommand.Create(Keys.Control | Keys.C)
6693 .FocusedOn(FocusedControl.ListTab)
6694 .Do(() => this.CopyStot()),
6696 ShortcutCommand.Create(Keys.Control | Keys.C)
6697 .FocusedOn(FocusedControl.ListTab)
6698 .Do(() => this.CopyStot()),
6700 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6701 ShortcutCommand.Create(Keys.Control | Keys.D1)
6702 .FocusedOn(FocusedControl.ListTab)
6703 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6704 .Do(() => this.ListTab.SelectedIndex = 0),
6706 ShortcutCommand.Create(Keys.Control | Keys.D2)
6707 .FocusedOn(FocusedControl.ListTab)
6708 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6709 .Do(() => this.ListTab.SelectedIndex = 1),
6711 ShortcutCommand.Create(Keys.Control | Keys.D3)
6712 .FocusedOn(FocusedControl.ListTab)
6713 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6714 .Do(() => this.ListTab.SelectedIndex = 2),
6716 ShortcutCommand.Create(Keys.Control | Keys.D4)
6717 .FocusedOn(FocusedControl.ListTab)
6718 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6719 .Do(() => this.ListTab.SelectedIndex = 3),
6721 ShortcutCommand.Create(Keys.Control | Keys.D5)
6722 .FocusedOn(FocusedControl.ListTab)
6723 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6724 .Do(() => this.ListTab.SelectedIndex = 4),
6726 ShortcutCommand.Create(Keys.Control | Keys.D6)
6727 .FocusedOn(FocusedControl.ListTab)
6728 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6729 .Do(() => this.ListTab.SelectedIndex = 5),
6731 ShortcutCommand.Create(Keys.Control | Keys.D7)
6732 .FocusedOn(FocusedControl.ListTab)
6733 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6734 .Do(() => this.ListTab.SelectedIndex = 6),
6736 ShortcutCommand.Create(Keys.Control | Keys.D8)
6737 .FocusedOn(FocusedControl.ListTab)
6738 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6739 .Do(() => this.ListTab.SelectedIndex = 7),
6741 ShortcutCommand.Create(Keys.Control | Keys.D9)
6742 .FocusedOn(FocusedControl.ListTab)
6743 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6745 ShortcutCommand.Create(Keys.Control | Keys.A)
6746 .FocusedOn(FocusedControl.StatusText)
6747 .Do(() => this.StatusText.SelectAll()),
6749 ShortcutCommand.Create(Keys.Control | Keys.V)
6750 .FocusedOn(FocusedControl.StatusText)
6751 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6753 ShortcutCommand.Create(Keys.Control | Keys.Up)
6754 .FocusedOn(FocusedControl.StatusText)
6756 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6758 var inReplyToStatusId = this.inReplyTo?.Item1;
6759 var inReplyToScreenName = this.inReplyTo?.Item2;
6760 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6763 if (_hisIdx < 0) _hisIdx = 0;
6765 var historyItem = this._history[this._hisIdx];
6766 StatusText.Text = historyItem.status;
6767 StatusText.SelectionStart = StatusText.Text.Length;
6768 if (historyItem.inReplyToId != null)
6769 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6771 this.inReplyTo = null;
6774 ShortcutCommand.Create(Keys.Control | Keys.Down)
6775 .FocusedOn(FocusedControl.StatusText)
6777 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6779 var inReplyToStatusId = this.inReplyTo?.Item1;
6780 var inReplyToScreenName = this.inReplyTo?.Item2;
6781 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6784 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6786 var historyItem = this._history[this._hisIdx];
6787 StatusText.Text = historyItem.status;
6788 StatusText.SelectionStart = StatusText.Text.Length;
6789 if (historyItem.inReplyToId != null)
6790 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6792 this.inReplyTo = null;
6795 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6796 .FocusedOn(FocusedControl.StatusText)
6798 if (ListTab.SelectedIndex == 0)
6800 ListTab.SelectedIndex = ListTab.TabCount - 1;
6804 ListTab.SelectedIndex -= 1;
6809 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6810 .FocusedOn(FocusedControl.StatusText)
6812 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6814 ListTab.SelectedIndex = 0;
6818 ListTab.SelectedIndex += 1;
6823 ShortcutCommand.Create(Keys.Control | Keys.Y)
6824 .FocusedOn(FocusedControl.PostBrowser)
6826 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6827 MultiLineMenuItem_Click(null, null);
6830 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6831 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6833 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6834 .Do(() => this.DoRefreshMore()),
6836 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6837 .Do(() => this.GetReplyAsync(loadMore: true)),
6839 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6840 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6842 ShortcutCommand.Create(Keys.Shift | Keys.R)
6843 .NotFocusedOn(FocusedControl.StatusText)
6844 .Do(() => this.DoRefreshMore()),
6846 ShortcutCommand.Create(Keys.Shift | Keys.H)
6847 .FocusedOn(FocusedControl.ListTab)
6848 .Do(() => this.GoTopEnd(GoTop: true)),
6850 ShortcutCommand.Create(Keys.Shift | Keys.L)
6851 .FocusedOn(FocusedControl.ListTab)
6852 .Do(() => this.GoTopEnd(GoTop: false)),
6854 ShortcutCommand.Create(Keys.Shift | Keys.M)
6855 .FocusedOn(FocusedControl.ListTab)
6856 .Do(() => this.GoMiddle()),
6858 ShortcutCommand.Create(Keys.Shift | Keys.G)
6859 .FocusedOn(FocusedControl.ListTab)
6860 .Do(() => this.GoLast()),
6862 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6863 .FocusedOn(FocusedControl.ListTab)
6864 .Do(() => this.MoveMiddle()),
6866 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6867 .FocusedOn(FocusedControl.ListTab)
6868 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6870 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6871 .FocusedOn(FocusedControl.ListTab)
6872 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6874 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6875 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6876 .FocusedOn(FocusedControl.ListTab)
6877 .Do(() => this.GoFav(forward: true)),
6879 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6880 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6881 .FocusedOn(FocusedControl.ListTab)
6882 .Do(() => this.GoFav(forward: false)),
6884 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6885 .FocusedOn(FocusedControl.ListTab)
6886 .Do(() => this.GoBackSelectPostChain()),
6888 ShortcutCommand.Create(Keys.Alt | Keys.R)
6889 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6891 ShortcutCommand.Create(Keys.Alt | Keys.P)
6892 .OnlyWhen(() => this._curPost != null)
6893 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6895 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6896 .Do(() => this.ScrollDownPostBrowser(forward: false)),
6898 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6899 .Do(() => this.ScrollDownPostBrowser(forward: true)),
6901 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6902 .Do(() => this.PageDownPostBrowser(forward: false)),
6904 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6905 .Do(() => this.PageDownPostBrowser(forward: true)),
6907 // 別タブの同じ書き込みへ(ALT+←/→)
6908 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6909 .FocusedOn(FocusedControl.ListTab)
6910 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6912 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6913 .FocusedOn(FocusedControl.ListTab)
6914 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6916 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6917 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6919 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C)
6920 .Do(() => this.CopyIdUri()),
6922 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6923 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6924 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6925 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6927 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6928 .Do(() => this.FavoriteChange(FavAdd: false)),
6930 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6931 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6933 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6934 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6936 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6937 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6939 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6940 .Do(() => this.doMoveToRTHome()),
6942 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6943 .Do(() => this.FavorareMenuItem_Click(null, null)),
6945 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6946 .FocusedOn(FocusedControl.StatusText)
6948 if (_curList != null && _curList.VirtualListSize != 0 &&
6949 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6951 var idx = _curList.SelectedIndices[0] - 1;
6952 SelectListItem(_curList, idx);
6953 _curList.EnsureVisible(idx);
6957 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6958 .FocusedOn(FocusedControl.StatusText)
6960 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6961 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6963 var idx = _curList.SelectedIndices[0] + 1;
6964 SelectListItem(_curList, idx);
6965 _curList.EnsureVisible(idx);
6969 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6970 .FocusedOn(FocusedControl.StatusText)
6972 if (StatusText.SelectionStart > 0)
6974 int endidx = StatusText.SelectionStart - 1;
6975 string startstr = "";
6976 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6978 char c = StatusText.Text[i];
6979 if (Char.IsLetterOrDigit(c) || c == '_')
6985 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6986 int cnt = AtIdSupl.ItemCount;
6987 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6988 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
6992 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6993 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
7003 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
7004 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
7005 .FocusedOn(FocusedControl.ListTab)
7006 .Do(() => this.SetSortColumnByDisplayIndex(0)),
7008 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
7009 .FocusedOn(FocusedControl.ListTab)
7010 .Do(() => this.SetSortColumnByDisplayIndex(1)),
7012 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
7013 .FocusedOn(FocusedControl.ListTab)
7014 .Do(() => this.SetSortColumnByDisplayIndex(2)),
7016 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
7017 .FocusedOn(FocusedControl.ListTab)
7018 .Do(() => this.SetSortColumnByDisplayIndex(3)),
7020 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
7021 .FocusedOn(FocusedControl.ListTab)
7022 .Do(() => this.SetSortColumnByDisplayIndex(4)),
7024 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
7025 .FocusedOn(FocusedControl.ListTab)
7026 .Do(() => this.SetSortColumnByDisplayIndex(5)),
7028 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
7029 .FocusedOn(FocusedControl.ListTab)
7030 .Do(() => this.SetSortColumnByDisplayIndex(6)),
7032 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
7033 .FocusedOn(FocusedControl.ListTab)
7034 .Do(() => this.SetSortColumnByDisplayIndex(7)),
7036 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
7037 .FocusedOn(FocusedControl.ListTab)
7038 .Do(() => this.SetSortLastColumn()),
7040 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
7041 .Do(() => this.FavoritesRetweetOfficial()),
7043 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
7044 .Do(() => this.FavoritesRetweetUnofficial()),
7046 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
7047 .Do(() => this.OpenUserAppointUrl()),
7049 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7050 .FocusedOn(FocusedControl.PostBrowser)
7051 .Do(() => this.doReTweetUnofficial()),
7053 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C)
7054 .FocusedOn(FocusedControl.PostBrowser)
7055 .Do(() => this.CopyUserId()),
7057 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
7058 .OnlyWhen(() => this.ExistCurrentPost)
7059 .Do(() => this.doTranslation(_curPost.TextFromApi)),
7061 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7062 .Do(() => this.doReTweetUnofficial()),
7064 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C)
7065 .Do(() => this.CopyUserId()),
7067 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
7068 .Do(() => this.tweetThumbnail1.ScrollUp()),
7070 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
7071 .Do(() => this.tweetThumbnail1.ScrollDown()),
7073 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
7074 .FocusedOn(FocusedControl.ListTab)
7075 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
7076 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
7080 private bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
7082 // Task を返す非同期処理があれば asyncTask に代入する
7085 // ShortcutCommand に対応しているコマンドはここで処理される
7086 foreach (var command in this.shortcutCommands)
7088 if (command.IsMatch(keyData, focusedOn))
7090 asyncTask = command.RunCommand();
7091 return command.PreventDefault;
7098 private void ScrollDownPostBrowser(bool forward)
7100 var doc = PostBrowser.Document;
7101 if (doc == null) return;
7103 var tags = doc.GetElementsByTagName("html");
7107 tags[0].ScrollTop += this._fntDetail.Height;
7109 tags[0].ScrollTop -= this._fntDetail.Height;
7113 private void PageDownPostBrowser(bool forward)
7115 var doc = PostBrowser.Document;
7116 if (doc == null) return;
7118 var tags = doc.GetElementsByTagName("html");
7122 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7124 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7128 private void GoNextTab(bool forward)
7130 int idx = ListTab.SelectedIndex;
7134 if (idx > ListTab.TabPages.Count - 1) idx = 0;
7139 if (idx < 0) idx = ListTab.TabPages.Count - 1;
7141 ListTab.SelectedIndex = idx;
7144 private void CopyStot()
7147 StringBuilder sb = new StringBuilder();
7148 bool IsProtected = false;
7150 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7151 foreach (int idx in _curList.SelectedIndices)
7153 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7159 if (post.IsDeleted) continue;
7162 if (post.RetweetedId != null)
7163 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7165 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7169 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7174 MessageBox.Show(Properties.Resources.CopyStotText1);
7178 clstr = sb.ToString();
7181 Clipboard.SetDataObject(clstr, false, 5, 100);
7183 catch (Exception ex)
7185 MessageBox.Show(ex.Message);
7190 private void CopyIdUri()
7193 StringBuilder sb = new StringBuilder();
7194 if (this._curTab == null) return;
7195 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7196 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7197 foreach (int idx in _curList.SelectedIndices)
7199 var post = _statuses.Tabs[_curTab.Text][idx];
7200 sb.Append(MyCommon.GetStatusUrl(post));
7201 sb.Append(Environment.NewLine);
7205 clstr = sb.ToString();
7208 Clipboard.SetDataObject(clstr, false, 5, 100);
7210 catch (Exception ex)
7212 MessageBox.Show(ex.Message);
7217 private void GoFav(bool forward)
7219 if (_curList.VirtualListSize == 0) return;
7226 if (_curList.SelectedIndices.Count == 0)
7232 fIdx = _curList.SelectedIndices[0] + 1;
7233 if (fIdx > _curList.VirtualListSize - 1) return;
7235 toIdx = _curList.VirtualListSize;
7240 if (_curList.SelectedIndices.Count == 0)
7242 fIdx = _curList.VirtualListSize - 1;
7246 fIdx = _curList.SelectedIndices[0] - 1;
7247 if (fIdx < 0) return;
7253 for (int idx = fIdx; idx != toIdx; idx += stp)
7255 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
7257 SelectListItem(_curList, idx);
7258 _curList.EnsureVisible(idx);
7264 private void GoSamePostToAnotherTab(bool left)
7266 if (_curList.VirtualListSize == 0) return;
7272 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7273 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7275 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7280 if (ListTab.SelectedIndex == 0)
7286 fIdx = ListTab.SelectedIndex - 1;
7294 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7300 fIdx = ListTab.SelectedIndex + 1;
7302 toIdx = ListTab.TabCount;
7307 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7309 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7310 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7312 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
7314 ListTab.SelectedIndex = tabidx;
7315 SelectListItem(_curList, idx);
7316 _curList.EnsureVisible(idx);
7325 private void GoPost(bool forward)
7327 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7334 fIdx = _curList.SelectedIndices[0] + 1;
7335 if (fIdx > _curList.VirtualListSize - 1) return;
7336 toIdx = _curList.VirtualListSize;
7341 fIdx = _curList.SelectedIndices[0] - 1;
7342 if (fIdx < 0) return;
7348 if (_curPost.RetweetedId == null)
7350 name = _curPost.ScreenName;
7354 name = _curPost.RetweetedBy;
7356 for (int idx = fIdx; idx != toIdx; idx += stp)
7358 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
7360 if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
7362 SelectListItem(_curList, idx);
7363 _curList.EnsureVisible(idx);
7369 if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
7371 SelectListItem(_curList, idx);
7372 _curList.EnsureVisible(idx);
7379 private void GoRelPost(bool forward)
7381 if (_curList.SelectedIndices.Count == 0) return;
7388 fIdx = _curList.SelectedIndices[0] + 1;
7389 if (fIdx > _curList.VirtualListSize - 1) return;
7390 toIdx = _curList.VirtualListSize;
7395 fIdx = _curList.SelectedIndices[0] - 1;
7396 if (fIdx < 0) return;
7403 if (_curPost == null) return;
7404 _anchorPost = _curPost;
7409 if (_anchorPost == null) return;
7412 for (int idx = fIdx; idx != toIdx; idx += stp)
7414 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7415 if (post.ScreenName == _anchorPost.ScreenName ||
7416 post.RetweetedBy == _anchorPost.ScreenName ||
7417 post.ScreenName == _anchorPost.RetweetedBy ||
7418 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7419 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLower()) ||
7420 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLower()) ||
7421 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLower()) ||
7422 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLower()))
7424 SelectListItem(_curList, idx);
7425 _curList.EnsureVisible(idx);
7431 private void GoAnchor()
7433 if (_anchorPost == null) return;
7434 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7435 if (idx == -1) return;
7437 SelectListItem(_curList, idx);
7438 _curList.EnsureVisible(idx);
7441 private void GoTopEnd(bool GoTop)
7443 if (_curList.VirtualListSize == 0)
7451 _item = _curList.GetItemAt(0, 25);
7459 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7461 idx = _curList.VirtualListSize - 1;
7465 SelectListItem(_curList, idx);
7468 private void GoMiddle()
7470 if (_curList.VirtualListSize == 0)
7478 _item = _curList.GetItemAt(0, 0);
7488 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7491 idx2 = _curList.VirtualListSize - 1;
7497 idx3 = (idx1 + idx2) / 2;
7499 SelectListItem(_curList, idx3);
7502 private void GoLast()
7504 if (_curList.VirtualListSize == 0) return;
7506 if (_statuses.SortOrder == SortOrder.Ascending)
7508 SelectListItem(_curList, _curList.VirtualListSize - 1);
7509 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7513 SelectListItem(_curList, 0);
7514 _curList.EnsureVisible(0);
7518 private void MoveTop()
7520 if (_curList.SelectedIndices.Count == 0) return;
7521 int idx = _curList.SelectedIndices[0];
7522 if (_statuses.SortOrder == SortOrder.Ascending)
7524 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7528 _curList.EnsureVisible(0);
7530 _curList.EnsureVisible(idx);
7533 private async Task GoInReplyToPostTree()
7535 if (_curPost == null) return;
7537 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7539 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7543 var post = tw.GetStatusApi(false, _curPost.StatusId);
7545 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7546 _curPost.InReplyToUser = post.InReplyToUser;
7547 _curPost.IsReply = post.IsReply;
7548 this.PurgeListViewItemCache();
7549 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7551 catch (WebApiException ex)
7553 this.StatusLabel.Text = ex.Message;
7557 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7559 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7561 replyChains = new Stack<ReplyChain>();
7563 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7566 string inReplyToTabName;
7567 long inReplyToId = _curPost.InReplyToStatusId.Value;
7568 string inReplyToUser = _curPost.InReplyToUser;
7569 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7571 var inReplyToPosts = from tab in _statuses.Tabs.Values
7572 orderby tab != curTabClass
7573 from post in tab.Posts.Values
7574 where post.StatusId == inReplyToId
7575 let index = tab.IndexOf(post.StatusId)
7577 select new {Tab = tab, Index = index};
7579 var inReplyPost = inReplyToPosts.FirstOrDefault();
7580 if (inReplyPost == null)
7584 await Task.Run(() =>
7586 var post = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value);
7589 _statuses.AddPost(post);
7590 _statuses.DistributePosts();
7593 catch (WebApiException ex)
7595 this.StatusLabel.Text = ex.Message;
7596 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7600 this.RefreshTimeline();
7602 inReplyPost = inReplyToPosts.FirstOrDefault();
7603 if (inReplyPost == null)
7605 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7609 inReplyToTabName = inReplyPost.Tab.TabName;
7610 inReplyToIndex = inReplyPost.Index;
7612 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7613 DetailsListView listView = (DetailsListView)tabPage.Tag;
7615 if (_curTab != tabPage)
7617 this.ListTab.SelectTab(tabPage);
7620 this.SelectListItem(listView, inReplyToIndex);
7621 listView.EnsureVisible(inReplyToIndex);
7624 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7626 if (_curPost == null) return;
7628 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7629 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7633 if (_curPost.InReplyToStatusId != null)
7635 var posts = from t in _statuses.Tabs
7636 from p in t.Value.Posts
7637 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7638 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7640 orderby isForward ? indexOf : indexOf * -1
7641 orderby t.Value != curTabClass
7642 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7645 var postList = posts.ToList();
7646 for (int i = postList.Count - 1; i >= 0; i--)
7649 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7651 postList.RemoveAt(index);
7654 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7655 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7656 if (post == null) post = postList.First();
7657 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7658 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7659 SelectListItem(listView, post.Index);
7660 listView.EnsureVisible(post.Index);
7662 catch (InvalidOperationException)
7670 if (replyChains == null || replyChains.Count < 1)
7672 var posts = from t in _statuses.Tabs
7673 from p in t.Value.Posts
7674 where p.Value.InReplyToStatusId == _curPost.StatusId
7675 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7678 orderby t.Value != curTabClass
7679 select new {Tab = t.Value, Index = indexOf};
7682 var post = posts.First();
7683 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7684 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7685 SelectListItem(listView, post.Index);
7686 listView.EnsureVisible(post.Index);
7688 catch (InvalidOperationException)
7695 ReplyChain chainHead = replyChains.Pop();
7696 if (chainHead.InReplyToId == _curPost.StatusId)
7698 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7707 ListTab.SelectTab(chainHead.OriginalTab);
7713 SelectListItem(_curList, idx);
7714 _curList.EnsureVisible(idx);
7720 this.GoBackInReplyToPostTree(parallel);
7726 private void GoBackSelectPostChain()
7728 if (this.selectPostChains.Count > 1)
7737 this.selectPostChains.Pop();
7738 var tabPostPair = this.selectPostChains.Peek();
7740 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7742 if (tabPostPair.Item2 != null)
7744 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7745 if (idx == -1) continue; //該当ポストが存在しないので無視
7748 tp = tabPostPair.Item1;
7750 this.selectPostChains.Pop();
7752 catch (InvalidOperationException)
7758 while (this.selectPostChains.Count > 1);
7763 //履歴が残り1つであればクリアしておく
7764 if (this.selectPostChains.Count == 1)
7765 this.selectPostChains.Clear();
7769 DetailsListView lst = (DetailsListView)tp.Tag;
7770 this.ListTab.SelectedTab = tp;
7773 SelectListItem(lst, idx);
7774 lst.EnsureVisible(idx);
7780 private void PushSelectPostChain()
7782 int count = this.selectPostChains.Count;
7785 var p = this.selectPostChains.Peek();
7786 if (p.Item1 == this._curTab)
7788 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7789 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7792 if (count >= 2500) TrimPostChain();
7793 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7796 private void TrimPostChain()
7798 if (this.selectPostChains.Count <= 2000) return;
7799 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7800 for (int i = 0; i < 2000; i++)
7802 p.Push(this.selectPostChains.Pop());
7804 this.selectPostChains.Clear();
7805 for (int i = 0; i < 2000; i++)
7807 this.selectPostChains.Push(p.Pop());
7811 private bool GoStatus(long statusId)
7813 if (statusId == 0) return false;
7814 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7816 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7818 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7819 ListTab.SelectedIndex = tabidx;
7820 SelectListItem(_curList, idx);
7821 _curList.EnsureVisible(idx);
7828 private bool GoDirectMessage(long statusId)
7830 if (statusId == 0) return false;
7831 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7833 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7835 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7836 ListTab.SelectedIndex = tabidx;
7837 SelectListItem(_curList, idx);
7838 _curList.EnsureVisible(idx);
7845 private void MyList_MouseClick(object sender, MouseEventArgs e)
7847 _anchorFlag = false;
7850 private void StatusText_Enter(object sender, EventArgs e)
7852 // フォーカスの戻り先を StatusText に設定
7853 this.Tag = StatusText;
7854 StatusText.BackColor = _clInputBackcolor;
7857 public Color InputBackColor
7859 get { return _clInputBackcolor; }
7860 set { _clInputBackcolor = value; }
7863 private void StatusText_Leave(object sender, EventArgs e)
7865 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7866 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7867 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7870 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7873 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7876 e.SuppressKeyPress = true;
7879 this.StatusText_TextChanged(null, null);
7881 if (asyncTask != null)
7885 private void SaveConfigsAll(bool ifModified)
7889 SaveConfigsCommon();
7896 if (_modifySettingCommon) SaveConfigsCommon();
7897 if (_modifySettingLocal) SaveConfigsLocal();
7898 if (_modifySettingAtId) SaveConfigsAtId();
7902 private void SaveConfigsAtId()
7904 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7906 _modifySettingAtId = false;
7907 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7911 private void SaveConfigsCommon()
7913 if (_ignoreConfigSave) return;
7915 _modifySettingCommon = false;
7918 _cfgCommon.UserName = tw.Username;
7919 _cfgCommon.UserId = tw.UserId;
7920 _cfgCommon.Password = tw.Password;
7921 _cfgCommon.Token = tw.AccessToken;
7922 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7924 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7925 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7927 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7930 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7931 switch (_statuses.SortMode)
7933 case ComparerMode.Nickname: //ニックネーム
7934 _cfgCommon.SortColumn = 1;
7936 case ComparerMode.Data: //本文
7937 _cfgCommon.SortColumn = 2;
7939 case ComparerMode.Id: //時刻=発言Id
7940 _cfgCommon.SortColumn = 3;
7942 case ComparerMode.Name: //名前
7943 _cfgCommon.SortColumn = 4;
7945 case ComparerMode.Source: //Source
7946 _cfgCommon.SortColumn = 7;
7950 _cfgCommon.HashTags = HashMgr.HashHistories;
7951 if (HashMgr.IsPermanent)
7953 _cfgCommon.HashSelected = HashMgr.UseHash;
7957 _cfgCommon.HashSelected = "";
7959 _cfgCommon.HashIsHead = HashMgr.IsHead;
7960 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7961 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7962 if (ToolStripFocusLockMenuItem != null &&
7963 ToolStripFocusLockMenuItem.IsDisposed == false)
7965 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7967 _cfgCommon.TrackWord = tw.TrackWord;
7968 _cfgCommon.AllAtReply = tw.AllAtReply;
7969 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7970 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7976 private void SaveConfigsLocal()
7978 if (_ignoreConfigSave) return;
7981 _modifySettingLocal = false;
7982 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7983 _cfgLocal.FormSize = _mySize;
7984 _cfgLocal.FormLocation = _myLoc;
7985 _cfgLocal.SplitterDistance = _mySpDis;
7986 _cfgLocal.PreviewDistance = _mySpDis3;
7987 _cfgLocal.StatusMultiline = StatusText.Multiline;
7988 _cfgLocal.StatusTextHeight = _mySpDis2;
7990 _cfgLocal.FontUnread = _fntUnread;
7991 _cfgLocal.ColorUnread = _clUnread;
7992 _cfgLocal.FontRead = _fntReaded;
7993 _cfgLocal.ColorRead = _clReaded;
7994 _cfgLocal.FontDetail = _fntDetail;
7995 _cfgLocal.ColorDetail = _clDetail;
7996 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7997 _cfgLocal.ColorDetailLink = _clDetailLink;
7998 _cfgLocal.ColorFav = _clFav;
7999 _cfgLocal.ColorOWL = _clOWL;
8000 _cfgLocal.ColorRetweet = _clRetweet;
8001 _cfgLocal.ColorSelf = _clSelf;
8002 _cfgLocal.ColorAtSelf = _clAtSelf;
8003 _cfgLocal.ColorTarget = _clTarget;
8004 _cfgLocal.ColorAtTarget = _clAtTarget;
8005 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
8006 _cfgLocal.ColorAtTo = _clAtTo;
8007 _cfgLocal.ColorListBackcolor = _clListBackcolor;
8008 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
8009 _cfgLocal.ColorInputFont = _clInputFont;
8010 _cfgLocal.FontInputFont = _fntInputFont;
8012 if (_ignoreConfigSave) return;
8017 private void SaveConfigsTabs()
8019 SettingTabs tabSetting = new SettingTabs();
8020 for (int i = 0; i < ListTab.TabPages.Count; i++)
8022 var tab = _statuses.Tabs[ListTab.TabPages[i].Text];
8023 if (tab.TabType != MyCommon.TabUsageType.Related && tab.TabType != MyCommon.TabUsageType.SearchResults)
8024 tabSetting.Tabs.Add(tab);
8026 tabSetting.Tabs.Add(this._statuses.GetTabByType(MyCommon.TabUsageType.Mute));
8030 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
8033 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
8034 if (ret != DialogResult.OK)
8037 var match = Twitter.StatusUrlRegex.Match(inputText);
8040 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
8041 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8047 var statusId = long.Parse(match.Groups["StatusId"].Value);
8048 await this.OpenRelatedTab(statusId);
8050 catch (TabException ex)
8052 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8056 private void SaveLogMenuItem_Click(object sender, EventArgs e)
8058 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8059 Properties.Resources.SaveLogMenuItem_ClickText2,
8060 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8061 if (rslt == DialogResult.Cancel) return;
8063 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8064 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8065 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8066 SaveFileDialog1.FilterIndex = 0;
8067 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8068 SaveFileDialog1.RestoreDirectory = true;
8070 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8072 if (!SaveFileDialog1.ValidateNames) return;
8073 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8075 if (rslt == DialogResult.Yes)
8078 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8080 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8081 string protect = "";
8082 if (post.IsProtect) protect = "Protect";
8083 sw.WriteLine(post.Nickname + "\t" +
8084 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8085 post.CreatedAt.ToString() + "\t" +
8086 post.ScreenName + "\t" +
8087 post.StatusId.ToString() + "\t" +
8088 post.ImageUrl + "\t" +
8089 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8095 foreach (int idx in _curList.SelectedIndices)
8097 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8098 string protect = "";
8099 if (post.IsProtect) protect = "Protect";
8100 sw.WriteLine(post.Nickname + "\t" +
8101 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8102 post.CreatedAt.ToString() + "\t" +
8103 post.ScreenName + "\t" +
8104 post.StatusId.ToString() + "\t" +
8105 post.ImageUrl + "\t" +
8106 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8112 this.TopMost = this._cfgCommon.AlwaysTop;
8115 private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8118 bool KeyRes = CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out asyncTask);
8121 e.IsInputKey = true;
8125 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
8127 var shortcut = (Shortcut)e.KeyData;
8130 case Shortcut.CtrlA:
8131 case Shortcut.CtrlC:
8132 case Shortcut.CtrlIns:
8136 // その他のショートカットキーは無効にする
8137 e.IsInputKey = true;
8143 if (asyncTask != null)
8146 public bool TabRename(ref string tabName)
8149 string newTabText = null;
8150 using (InputTabName inputName = new InputTabName())
8152 inputName.TabName = tabName;
8153 inputName.ShowDialog();
8154 if (inputName.DialogResult == DialogResult.Cancel) return false;
8155 newTabText = inputName.TabName;
8157 this.TopMost = this._cfgCommon.AlwaysTop;
8158 if (!string.IsNullOrEmpty(newTabText))
8161 for (int i = 0; i < ListTab.TabCount; i++)
8163 if (ListTab.TabPages[i].Text == newTabText)
8165 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8166 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8171 for (int i = 0; i < ListTab.TabCount; i++)
8173 if (ListTab.TabPages[i].Text == tabName)
8175 ListTab.TabPages[i].Text = newTabText;
8179 _statuses.RenameTab(tabName, newTabText);
8181 SaveConfigsCommon();
8183 _rclickTabName = newTabText;
8184 tabName = newTabText;
8193 private void ListTab_MouseClick(object sender, MouseEventArgs e)
8195 if (e.Button == MouseButtons.Middle)
8197 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8199 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8201 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8202 this.SaveConfigsTabs();
8209 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8211 string tn = ListTab.SelectedTab.Text;
8215 private void ListTab_MouseDown(object sender, MouseEventArgs e)
8217 if (this._cfgCommon.TabMouseLock) return;
8218 Point cpos = new Point(e.X, e.Y);
8219 if (e.Button == MouseButtons.Left)
8221 for (int i = 0; i < ListTab.TabPages.Count; i++)
8223 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8226 _tabMouseDownPoint = e.Location;
8237 private void ListTab_DragEnter(object sender, DragEventArgs e)
8239 if (e.Data.GetDataPresent(typeof(TabPage)))
8240 e.Effect = DragDropEffects.Move;
8242 e.Effect = DragDropEffects.None;
8245 private void ListTab_DragDrop(object sender, DragEventArgs e)
8247 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8252 Point cpos = new Point(e.X, e.Y);
8253 Point spos = ListTab.PointToClient(cpos);
8255 for (i = 0; i < ListTab.TabPages.Count; i++)
8257 Rectangle rect = ListTab.GetTabRect(i);
8258 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8259 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8261 tn = ListTab.TabPages[i].Text;
8262 if (spos.X <= (rect.Left + rect.Right) / 2)
8271 //タブのないところにドロップ->最後尾へ移動
8272 if (string.IsNullOrEmpty(tn))
8274 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8276 i = ListTab.TabPages.Count - 1;
8279 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8280 if (tp.Text == tn) return;
8282 ReOrderTab(tp.Text, tn, bef);
8285 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8287 var baseIndex = this.GetTabPageIndex(baseTabText);
8288 if (baseIndex == -1)
8291 var targetIndex = this.GetTabPageIndex(targetTabText);
8292 if (targetIndex == -1)
8295 using (ControlTransaction.Layout(this.ListTab))
8297 var mTp = this.ListTab.TabPages[targetIndex];
8298 this.ListTab.TabPages.Remove(mTp);
8300 if (targetIndex < baseIndex)
8303 if (isBeforeBaseTab)
8304 ListTab.TabPages.Insert(baseIndex, mTp);
8306 ListTab.TabPages.Insert(baseIndex + 1, mTp);
8312 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8314 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8315 //isReply:true=@,false=DM
8316 if (!StatusText.Enabled) return;
8317 if (_curList == null) return;
8318 if (_curTab == null) return;
8319 if (!this.ExistCurrentPost) return;
8321 // 複数あてリプライはReplyではなく通常ポスト
8322 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8323 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8324 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8326 if (_curList.SelectedIndices.Count > 0)
8329 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8332 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8335 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8336 StatusText.SelectionStart = StatusText.Text.Length;
8338 this.inReplyTo = null;
8341 if (string.IsNullOrEmpty(StatusText.Text))
8345 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8346 StatusText.Text = "@" + _curPost.ScreenName + " ";
8348 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8349 var inReplyToScreenName = this._curPost.ScreenName;
8350 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8358 //1件選んでEnter or DoubleClick
8359 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8361 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
8364 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8365 var inReplyToScreenName = this._curPost.ScreenName;
8366 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8370 if (!StatusText.Text.StartsWith("@"))
8373 if (StatusText.Text.StartsWith(". "))
8376 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8377 this.inReplyTo = null;
8382 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8383 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8384 var inReplyToScreenName = this._curPost.ScreenName;
8385 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8392 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8393 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8394 this.inReplyTo = null;
8399 //1件選んでCtrl-Rの場合(返信先操作せず)
8400 int sidx = StatusText.SelectionStart;
8401 string id = "@" + _curPost.ScreenName + " ";
8404 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8409 StatusText.Text = StatusText.Text.Insert(sidx, id);
8411 //if (StatusText.Text.StartsWith("@"))
8414 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8415 // sidx += 5 + _curPost.ScreenName.Length;
8420 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8421 // sidx += 3 + _curPost.ScreenName.Length;
8423 StatusText.SelectionStart = sidx;
8426 //_reply_to_name = null;
8434 if (!isAuto && !isReply) return;
8436 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8440 //Enter or DoubleClick
8442 string sTxt = StatusText.Text;
8443 if (!sTxt.StartsWith(". "))
8446 this.inReplyTo = null;
8448 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8450 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8451 if (!sTxt.Contains("@" + post.ScreenName + " "))
8453 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8454 //sTxt = "@" + post.ScreenName + " " + sTxt;
8457 StatusText.Text = sTxt;
8462 if (_curList.SelectedIndices.Count > 1)
8467 int sidx = StatusText.SelectionStart;
8468 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8470 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8471 if (!ids.Contains("@" + post.ScreenName + " ") &&
8472 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8474 ids += "@" + post.ScreenName + " ";
8478 foreach (string nm in post.ReplyToList)
8480 if (!ids.Contains("@" + nm + " ") &&
8481 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8483 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8485 ids += "@" + m.Result("${id}") + " ";
8487 ids += "@" + nm + " ";
8492 if (ids.Length == 0) return;
8493 if (!StatusText.Text.StartsWith(". "))
8495 StatusText.Text = ". " + StatusText.Text;
8497 this.inReplyTo = null;
8501 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8506 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8508 //if (StatusText.Text.StartsWith("@"))
8510 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8511 // sidx += 2 + ids.Length;
8515 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8516 // sidx += 1 + ids.Length;
8518 StatusText.SelectionStart = sidx;
8524 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8527 int sidx = StatusText.SelectionStart;
8528 PostClass post = _curPost;
8529 if (!ids.Contains("@" + post.ScreenName + " ") &&
8530 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8532 ids += "@" + post.ScreenName + " ";
8534 foreach (string nm in post.ReplyToList)
8536 if (!ids.Contains("@" + nm + " ") &&
8537 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8539 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8541 ids += "@" + m.Result("${id}") + " ";
8543 ids += "@" + nm + " ";
8546 if (!string.IsNullOrEmpty(post.RetweetedBy))
8548 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8549 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8551 ids += "@" + post.RetweetedBy + " ";
8554 if (ids.Length == 0) return;
8555 if (string.IsNullOrEmpty(StatusText.Text))
8558 StatusText.Text = ids;
8559 StatusText.SelectionStart = ids.Length;
8562 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8563 var inReplyToScreenName = this._curPost.ScreenName;
8564 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8570 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8575 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8577 StatusText.SelectionStart = sidx;
8583 StatusText.SelectionStart = StatusText.Text.Length;
8588 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8593 private static int iconCnt = 0;
8594 private static int blinkCnt = 0;
8595 private static bool blink = false;
8596 private static bool idle = false;
8598 private async Task RefreshTasktrayIcon(bool forceRefresh)
8601 await this.Colorize();
8603 if (!TimerRefreshIcon.Enabled) return;
8604 //Static usCheckCnt As int = 0
8606 //Static iconDlListTopItem As ListViewItem = null
8608 if (forceRefresh) idle = false;
8610 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8611 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8613 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8615 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8621 //if (usCheckCnt > 300) //1min
8624 // if (!this.IsReceivedUserStream)
8626 // TraceOut("ReconnectUserStream");
8627 // tw.ReconnectUserStream();
8631 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8633 if (iconCnt >= this.NIconRefresh.Length)
8641 SaveConfigsAll(true);
8646 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8648 _myStatusError = false;
8652 TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8653 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8655 if (blinkCnt > 0) return;
8657 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8659 NotifyIcon1.Icon = ReplyIcon;
8663 NotifyIcon1.Icon = ReplyIconBlink;
8671 //優先度:エラー→オフライン→アイドル
8675 NotifyIcon1.Icon = NIconAtRed;
8678 if (_myStatusOnline)
8680 NotifyIcon1.Icon = NIconAt;
8684 NotifyIcon1.Icon = NIconAtSmoke;
8688 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8691 await this.RefreshTasktrayIcon(false);
8694 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8696 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8697 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8699 if (ListTab != null && ListTab.SelectedTab != null)
8700 _rclickTabName = ListTab.SelectedTab.Text;
8705 if (_statuses == null) return;
8706 if (_statuses.Tabs == null) return;
8708 TabClass tb = _statuses.Tabs[_rclickTabName];
8709 if (tb == null) return;
8711 NotifyDispMenuItem.Checked = tb.Notify;
8712 this.NotifyTbMenuItem.Checked = tb.Notify;
8714 soundfileListup = true;
8715 SoundFileComboBox.Items.Clear();
8716 this.SoundFileTbComboBox.Items.Clear();
8717 SoundFileComboBox.Items.Add("");
8718 this.SoundFileTbComboBox.Items.Add("");
8719 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8720 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8722 oDir = oDir.GetDirectories("Sounds")[0];
8724 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8726 SoundFileComboBox.Items.Add(oFile.Name);
8727 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8729 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8730 if (idx == -1) idx = 0;
8731 SoundFileComboBox.SelectedIndex = idx;
8732 this.SoundFileTbComboBox.SelectedIndex = idx;
8733 soundfileListup = false;
8734 UreadManageMenuItem.Checked = tb.UnreadManage;
8735 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8737 TabMenuControl(_rclickTabName);
8740 private void TabMenuControl(string tabName)
8742 var tabInfo = _statuses.GetTabByName(tabName);
8744 this.FilterEditMenuItem.Enabled = true;
8745 this.EditRuleTbMenuItem.Enabled = true;
8747 if (tabInfo.IsDefaultTabType)
8749 this.ProtectTabMenuItem.Enabled = false;
8750 this.ProtectTbMenuItem.Enabled = false;
8754 this.ProtectTabMenuItem.Enabled = true;
8755 this.ProtectTbMenuItem.Enabled = true;
8758 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8760 this.ProtectTabMenuItem.Checked = true;
8761 this.ProtectTbMenuItem.Checked = true;
8762 this.DeleteTabMenuItem.Enabled = false;
8763 this.DeleteTbMenuItem.Enabled = false;
8767 this.ProtectTabMenuItem.Checked = false;
8768 this.ProtectTbMenuItem.Checked = false;
8769 this.DeleteTabMenuItem.Enabled = true;
8770 this.DeleteTbMenuItem.Enabled = true;
8774 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8776 var checkState = ((ToolStripMenuItem)sender).Checked;
8779 this.ProtectTbMenuItem.Checked = checkState;
8780 this.ProtectTabMenuItem.Checked = checkState;
8783 this.DeleteTabMenuItem.Enabled = !checkState;
8784 this.DeleteTbMenuItem.Enabled = !checkState;
8786 if (string.IsNullOrEmpty(_rclickTabName)) return;
8787 _statuses.Tabs[_rclickTabName].Protected = checkState;
8792 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8794 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8795 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8797 if (string.IsNullOrEmpty(_rclickTabName)) return;
8798 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8803 public void ChangeTabUnreadManage(string tabName, bool isManage)
8805 var idx = this.GetTabPageIndex(tabName);
8809 _statuses.Tabs[tabName].UnreadManage = isManage;
8810 if (this._cfgCommon.TabIconDisp)
8812 if (_statuses.Tabs[tabName].UnreadCount > 0)
8813 ListTab.TabPages[idx].ImageIndex = 0;
8815 ListTab.TabPages[idx].ImageIndex = -1;
8818 if (_curTab.Text == tabName)
8820 this.PurgeListViewItemCache();
8824 SetMainWindowTitle();
8825 SetStatusLabelUrl();
8826 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8829 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8831 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8832 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8834 if (string.IsNullOrEmpty(_rclickTabName)) return;
8836 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8841 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8843 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8845 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8850 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8852 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8854 RemoveSpecifiedTab(_rclickTabName, true);
8858 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8860 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8862 using (var fltDialog = new FilterDialog())
8864 fltDialog.Owner = this;
8865 fltDialog.SetCurrent(_rclickTabName);
8866 fltDialog.ShowDialog(this);
8868 this.TopMost = this._cfgCommon.AlwaysTop;
8870 this.ApplyPostFilters();
8874 private void AddTabMenuItem_Click(object sender, EventArgs e)
8876 string tabName = null;
8877 MyCommon.TabUsageType tabUsage;
8878 using (InputTabName inputName = new InputTabName())
8880 inputName.TabName = _statuses.MakeTabName("MyTab");
8881 inputName.IsShowUsage = true;
8882 inputName.ShowDialog();
8883 if (inputName.DialogResult == DialogResult.Cancel) return;
8884 tabName = inputName.TabName;
8885 tabUsage = inputName.Usage;
8887 this.TopMost = this._cfgCommon.AlwaysTop;
8888 if (!string.IsNullOrEmpty(tabName))
8891 ListElement list = null;
8892 if (tabUsage == MyCommon.TabUsageType.Lists)
8894 using (ListAvailable listAvail = new ListAvailable())
8896 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8897 if (listAvail.SelectedList == null) return;
8898 list = listAvail.SelectedList;
8901 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8903 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8904 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8910 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8912 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8913 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8915 if (tabUsage == MyCommon.TabUsageType.Lists)
8917 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8918 var tab = this._statuses.Tabs[this._curTab.Text];
8919 this.GetListTimelineAsync(tab);
8925 private void TabMenuItem_Click(object sender, EventArgs e)
8927 using (var fltDialog = new FilterDialog())
8929 fltDialog.Owner = this;
8932 foreach (int idx in _curList.SelectedIndices)
8936 if (!SelectTab(out tabName)) return;
8938 fltDialog.SetCurrent(tabName);
8939 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8941 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8945 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8947 fltDialog.ShowDialog(this);
8948 this.TopMost = this._cfgCommon.AlwaysTop;
8952 this.ApplyPostFilters();
8954 if (this.ListTab.SelectedTab != null &&
8955 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8957 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8961 protected override bool ProcessDialogKey(Keys keyData)
8963 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8964 if ((keyData & Keys.KeyCode) == Keys.Enter)
8966 if (StatusText.Focused)
8968 bool _NewLine = false;
8971 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8973 if (StatusText.Multiline)
8975 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8977 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8981 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8985 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8987 if (StatusText.Multiline)
8989 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8991 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8995 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
9001 if (StatusText.Multiline)
9003 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
9005 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
9006 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
9010 if (((keyData & Keys.Shift) == Keys.Shift) ||
9011 (((keyData & Keys.Control) != Keys.Control) &&
9012 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
9018 int pos1 = StatusText.SelectionStart;
9019 if (StatusText.SelectionLength > 0)
9021 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
9023 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
9024 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
9029 PostButton_Click(null, null);
9033 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
9034 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
9035 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
9037 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
9042 return base.ProcessDialogKey(keyData);
9045 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9047 MakeReplyOrDirectStatus(false, true, true);
9050 private void IDRuleMenuItem_Click(object sender, EventArgs e)
9055 if (_curList.SelectedIndices.Count == 0) return;
9058 if (!SelectTab(out tabName)) return;
9060 var tab = this._statuses.Tabs[tabName];
9064 if (tab.TabType != MyCommon.TabUsageType.Mute)
9066 this.MoveOrCopy(out mv, out mk);
9070 // ミュートタブでは常に MoveMatches を true にする
9075 List<string> ids = new List<string>();
9076 foreach (int idx in _curList.SelectedIndices)
9078 PostClass post = _statuses.Tabs[_curTab.Text][idx];
9079 if (!ids.Contains(post.ScreenName))
9081 PostFilterRule fc = new PostFilterRule();
9082 ids.Add(post.ScreenName);
9083 if (post.RetweetedId == null)
9085 fc.FilterName = post.ScreenName;
9089 fc.FilterName = post.RetweetedBy;
9091 fc.UseNameField = true;
9092 fc.MoveMatches = mv;
9093 fc.MarkMatches = mk;
9094 fc.UseRegex = false;
9095 fc.FilterByUrl = false;
9101 List<string> atids = new List<string>();
9102 foreach (string id in ids)
9104 atids.Add("@" + id);
9106 int cnt = AtIdSupl.ItemCount;
9107 AtIdSupl.AddRangeItem(atids.ToArray());
9108 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
9111 this.ApplyPostFilters();
9115 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
9117 if (this._curList.SelectedIndices.Count == 0)
9120 // タブ選択ダイアログを表示(or追加)
9122 if (!this.SelectTab(out tabName))
9125 var currentTab = this._statuses.Tabs[this._curTab.Text];
9126 var filterTab = this._statuses.Tabs[tabName];
9130 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
9132 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
9133 this.MoveOrCopy(out mv, out mk);
9137 // ミュートタブでは常に MoveMatches を true にする
9142 // 振り分けルールに追加するSource
9143 var sources = new HashSet<string>();
9145 foreach (var idx in this._curList.SelectedIndices.Cast<int>())
9147 var post = currentTab[idx];
9148 var filterSource = post.Source;
9150 if (sources.Add(filterSource))
9152 var filter = new PostFilterRule
9154 FilterSource = filterSource,
9158 FilterByUrl = false,
9160 filterTab.AddFilter(filter);
9164 this.ApplyPostFilters();
9165 this.SaveConfigsTabs();
9168 private bool SelectTab(out string tabName)
9175 using (var dialog = new TabsDialog(_statuses))
9177 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9179 var selectedTab = dialog.SelectedTab;
9180 tabName = selectedTab == null ? null : selectedTab.TabName;
9183 ListTab.SelectedTab.Focus();
9185 if (tabName == null)
9187 using (InputTabName inputName = new InputTabName())
9189 inputName.TabName = _statuses.MakeTabName("MyTab");
9190 inputName.ShowDialog();
9191 if (inputName.DialogResult == DialogResult.Cancel) return false;
9192 tabName = inputName.TabName;
9194 this.TopMost = this._cfgCommon.AlwaysTop;
9195 if (!string.IsNullOrEmpty(tabName))
9197 if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9199 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9200 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9218 private void MoveOrCopy(out bool move, out bool mark)
9222 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9223 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9231 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9232 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9242 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9247 private void CopyURLMenuItem_Click(object sender, EventArgs e)
9252 private void SelectAllMenuItem_Click(object sender, EventArgs e)
9254 if (StatusText.Focused)
9257 StatusText.SelectAll();
9261 // ListView上でのCtrl+A
9262 NativeMethods.SelectAllItems(this._curList);
9266 private void MoveMiddle()
9272 if (_curList.SelectedIndices.Count == 0) return;
9274 int idx = _curList.SelectedIndices[0];
9276 _item = _curList.GetItemAt(0, 25);
9282 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9284 idx2 = _curList.VirtualListSize - 1;
9288 idx -= Math.Abs(idx1 - idx2) / 2;
9289 if (idx < 0) idx = 0;
9291 _curList.EnsureVisible(_curList.VirtualListSize - 1);
9292 _curList.EnsureVisible(idx);
9295 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
9297 var linkElements = this.PostBrowser.Document.Links.Cast<HtmlElement>()
9298 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
9301 if (linkElements.Length > 0)
9303 UrlDialog.ClearUrl();
9305 string openUrlStr = "";
9307 if (linkElements.Length == 1)
9309 // ツイートに含まれる URL が 1 つのみの場合
9310 // => OpenURL ダイアログを表示せずにリンクを開く
9315 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
9317 catch (ArgumentException)
9326 if (string.IsNullOrEmpty(urlStr)) return;
9327 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9329 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
9330 await this.OpenUriAsync(new Uri(openUrlStr));
9334 // ツイートに含まれる URL が複数ある場合
9335 // => OpenURL を表示しユーザーが選択したリンクを開く
9337 foreach (var linkElm in linkElements)
9340 string linkText = "";
9344 urlStr = linkElm.GetAttribute("title");
9345 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9346 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9347 linkText = linkElm.InnerText;
9349 catch (ArgumentException)
9358 if (string.IsNullOrEmpty(urlStr)) continue;
9359 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9363 if (UrlDialog.ShowDialog() == DialogResult.OK)
9365 openUrlStr = UrlDialog.SelectedUrl;
9367 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
9368 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
9375 this.TopMost = this._cfgCommon.AlwaysTop;
9380 private void ClearTabMenuItem_Click(object sender, EventArgs e)
9382 if (string.IsNullOrEmpty(_rclickTabName)) return;
9383 ClearTab(_rclickTabName, true);
9386 private void ClearTab(string tabName, bool showWarning)
9390 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9391 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9397 _statuses.ClearTabIds(tabName);
9398 if (ListTab.SelectedTab.Text == tabName)
9401 _anchorFlag = false;
9402 this.PurgeListViewItemCache();
9406 foreach (TabPage tb in ListTab.TabPages)
9408 if (tb.Text == tabName)
9411 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9415 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9417 SetMainWindowTitle();
9418 SetStatusLabelUrl();
9421 private static long followers = 0;
9423 private void SetMainWindowTitle()
9426 StringBuilder ttl = new StringBuilder(256);
9429 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9430 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9431 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9432 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9434 foreach (var tab in _statuses.Tabs.Values)
9436 ur += tab.UnreadCount;
9441 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9442 ttl.Append(Application.ProductName);
9444 switch (this._cfgCommon.DispLatestPost)
9446 case MyCommon.DispTitleEnum.Ver:
9447 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9449 case MyCommon.DispTitleEnum.Post:
9450 if (_history != null && _history.Count > 1)
9451 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9453 case MyCommon.DispTitleEnum.UnreadRepCount:
9454 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9456 case MyCommon.DispTitleEnum.UnreadAllCount:
9457 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9459 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9460 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9462 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9463 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9465 case MyCommon.DispTitleEnum.OwnStatus:
9466 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9467 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9473 this.Text = ttl.ToString();
9475 catch (AccessViolationException)
9477 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9481 private string GetStatusLabelText()
9484 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9485 if (_statuses == null) return "";
9486 TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9487 TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9488 if (tbRep == null || tbDm == null) return "";
9489 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9494 StringBuilder slbl = new StringBuilder(256);
9497 foreach (var tab in _statuses.Tabs.Values)
9499 ur += tab.UnreadCount;
9501 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9503 tur = tab.UnreadCount;
9514 UnreadAtCounter = urat;
9516 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9517 if (this._cfgCommon.TimelinePeriod == 0)
9519 slbl.Append(Properties.Resources.SetStatusLabelText2);
9523 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9525 return slbl.ToString();
9528 private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9532 if (this.InvokeRequired && !this.IsDisposed)
9534 this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9538 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9539 SetApiStatusLabel(endpointName);
9542 catch (ObjectDisposedException)
9546 catch (InvalidOperationException)
9552 private void SetApiStatusLabel(string endpointName = null)
9554 if (_curTab == null)
9556 this.toolStripApiGauge.ApiEndpoint = null;
9560 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9562 if (endpointName == null)
9567 case MyCommon.TabUsageType.Home:
9568 case MyCommon.TabUsageType.UserDefined:
9569 endpointName = "/statuses/home_timeline";
9572 case MyCommon.TabUsageType.Mentions:
9573 endpointName = "/statuses/mentions_timeline";
9576 case MyCommon.TabUsageType.Favorites:
9577 endpointName = "/favorites/list";
9580 case MyCommon.TabUsageType.DirectMessage:
9581 endpointName = "/direct_messages";
9584 case MyCommon.TabUsageType.UserTimeline:
9585 endpointName = "/statuses/user_timeline";
9588 case MyCommon.TabUsageType.Lists:
9589 endpointName = "/lists/statuses";
9592 case MyCommon.TabUsageType.PublicSearch:
9593 endpointName = "/search/tweets";
9596 case MyCommon.TabUsageType.Related:
9597 endpointName = "/statuses/show/:id";
9604 this.toolStripApiGauge.ApiEndpoint = endpointName;
9608 // 表示中のタブに関連する endpoint であれば更新
9611 switch (endpointName)
9613 case "/statuses/home_timeline":
9614 update = tabType == MyCommon.TabUsageType.Home ||
9615 tabType == MyCommon.TabUsageType.UserDefined;
9618 case "/statuses/mentions_timeline":
9619 update = tabType == MyCommon.TabUsageType.Mentions;
9622 case "/favorites/list":
9623 update = tabType == MyCommon.TabUsageType.Favorites;
9626 case "/direct_messages:":
9627 update = tabType == MyCommon.TabUsageType.DirectMessage;
9630 case "/statuses/user_timeline":
9631 update = tabType == MyCommon.TabUsageType.UserTimeline;
9634 case "/lists/statuses":
9635 update = tabType == MyCommon.TabUsageType.Lists;
9638 case "/search/tweets":
9639 update = tabType == MyCommon.TabUsageType.PublicSearch;
9642 case "/statuses/show/:id":
9643 update = tabType == MyCommon.TabUsageType.Related;
9652 this.toolStripApiGauge.ApiEndpoint = endpointName;
9658 private void SetStatusLabelUrl()
9660 StatusLabelUrl.Text = GetStatusLabelText();
9663 public void SetStatusLabel(string text)
9665 StatusLabel.Text = text;
9668 private static StringBuilder ur = new StringBuilder(64);
9670 private void SetNotifyIconText()
9672 // タスクトレイアイコンのツールチップテキスト書き換え
9674 ur.Remove(0, ur.Length);
9675 if (this._cfgCommon.DispUsername)
9677 ur.Append(tw.Username);
9680 ur.Append(Application.ProductName);
9682 ur.Append("(Debug Build)");
9684 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9687 ur.Append(UnreadCounter);
9689 ur.Append(UnreadAtCounter);
9692 NotifyIcon1.Text = ur.ToString();
9695 internal void CheckReplyTo(string StatusText)
9699 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9701 foreach (Match hm in m)
9703 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9705 hstr += "#" + hm.Result("$3") + " ";
9706 HashSupl.AddItem("#" + hm.Result("$3"));
9709 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9711 hstr += HashMgr.UseHash;
9713 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9715 // 本当にリプライ先指定すべきかどうかの判定
9716 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9718 if (this._cfgCommon.UseAtIdSupplement)
9720 int bCnt = AtIdSupl.ItemCount;
9721 foreach (Match mid in m)
9723 AtIdSupl.AddItem(mid.Result("${id}"));
9725 if (bCnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
9728 // リプライ先ステータスIDの指定がない場合は指定しない
9729 if (this.inReplyTo == null)
9733 // 次の条件を満たす場合に in_reply_to_status_id 指定
9734 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9735 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9736 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9740 var inReplyToScreenName = this.inReplyTo.Item2;
9741 if (StatusText.StartsWith("@"))
9743 if (StatusText.StartsWith("@" + inReplyToScreenName)) return;
9747 foreach (Match mid in m)
9749 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9754 this.inReplyTo = null;
9757 private void TweenMain_Resize(object sender, EventArgs e)
9759 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9761 this.Visible = false;
9763 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9765 // 現在の DPI と設定保存時の DPI との比を取得する
9766 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9768 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9769 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9770 this.DesktopLocation = _cfgLocal.FormLocation;
9771 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9774 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9775 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9776 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9778 this.SplitContainer1.SplitterDistance = splitterDistance;
9782 StatusText.Multiline = _cfgLocal.StatusMultiline;
9783 if (StatusText.Multiline)
9785 var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9786 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9787 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9789 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9791 StatusText.Height = statusTextHeight;
9795 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9797 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9801 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9802 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9804 this.SplitContainer3.SplitterDistance = previewDistance;
9807 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9808 this.SplitContainer3.Panel2Collapsed = true;
9810 _initialLayout = false;
9812 if (this.WindowState != FormWindowState.Minimized)
9814 _formWindowState = this.WindowState;
9818 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9820 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9821 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9822 if (PlaySoundMenuItem.Checked)
9824 this._cfgCommon.PlaySound = true;
9828 this._cfgCommon.PlaySound = false;
9830 _modifySettingCommon = true;
9833 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9835 if (this._initialLayout)
9838 int splitterDistance;
9839 switch (this.WindowState)
9841 case FormWindowState.Normal:
9842 splitterDistance = this.SplitContainer1.SplitterDistance;
9844 case FormWindowState.Maximized:
9845 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9846 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9847 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9848 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9854 this._mySpDis = splitterDistance;
9855 this._modifySettingLocal = true;
9858 private async Task doRepliedStatusOpen()
9860 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9862 if (MyCommon.IsKeyDown(Keys.Shift))
9864 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9867 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9869 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9870 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9874 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9876 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9877 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9878 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9881 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9886 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9888 await this.doRepliedStatusOpen();
9892 /// UserPicture.Image に設定されている画像を破棄します。
9894 private void ClearUserPicture()
9896 if (this.UserPicture.Image != null)
9898 var oldImage = this.UserPicture.Image;
9899 this.UserPicture.Image = null;
9904 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9906 //発言詳細のアイコン右クリック時のメニュー制御
9907 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9909 string name = _curPost.ImageUrl;
9910 if (name != null && name.Length > 0)
9912 int idx = name.LastIndexOf('/');
9915 name = Path.GetFileName(name.Substring(idx));
9916 if (name.Contains("_normal.") || name.EndsWith("_normal"))
9918 name = name.Replace("_normal", "");
9919 this.IconNameToolStripMenuItem.Text = name;
9920 this.IconNameToolStripMenuItem.Enabled = true;
9924 this.IconNameToolStripMenuItem.Enabled = false;
9925 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9930 this.IconNameToolStripMenuItem.Enabled = false;
9931 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9934 this.ReloadIconToolStripMenuItem.Enabled = true;
9936 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9938 this.SaveIconPictureToolStripMenuItem.Enabled = true;
9942 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9947 this.IconNameToolStripMenuItem.Enabled = false;
9948 this.ReloadIconToolStripMenuItem.Enabled = false;
9949 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9950 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9955 this.IconNameToolStripMenuItem.Enabled = false;
9956 this.ReloadIconToolStripMenuItem.Enabled = false;
9957 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9958 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9960 if (NameLabel.Tag != null)
9962 string id = (string)NameLabel.Tag;
9963 if (id == tw.Username)
9965 FollowToolStripMenuItem.Enabled = false;
9966 UnFollowToolStripMenuItem.Enabled = false;
9967 ShowFriendShipToolStripMenuItem.Enabled = false;
9968 ShowUserStatusToolStripMenuItem.Enabled = true;
9969 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9970 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9971 ListManageUserContextToolStripMenuItem3.Enabled = true;
9975 FollowToolStripMenuItem.Enabled = true;
9976 UnFollowToolStripMenuItem.Enabled = true;
9977 ShowFriendShipToolStripMenuItem.Enabled = true;
9978 ShowUserStatusToolStripMenuItem.Enabled = true;
9979 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9980 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9981 ListManageUserContextToolStripMenuItem3.Enabled = true;
9986 FollowToolStripMenuItem.Enabled = false;
9987 UnFollowToolStripMenuItem.Enabled = false;
9988 ShowFriendShipToolStripMenuItem.Enabled = false;
9989 ShowUserStatusToolStripMenuItem.Enabled = false;
9990 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9991 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9992 ListManageUserContextToolStripMenuItem3.Enabled = false;
9996 private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9998 if (_curPost == null) return;
9999 string name = _curPost.ImageUrl;
10000 await this.OpenUriInBrowserAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
10003 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
10005 if (this._curPost == null) return;
10007 await this.UserPicture.SetImageFromTask(async () =>
10009 var imageUrl = this._curPost.ImageUrl;
10011 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
10012 .ConfigureAwait(false);
10014 return await image.CloneAsync()
10015 .ConfigureAwait(false);
10019 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10021 if (_curPost == null) return;
10022 string name = _curPost.ImageUrl;
10023 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
10025 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
10027 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10033 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10035 if (_curPost == null) return;
10036 string name = _curPost.ImageUrl;
10038 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
10040 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10044 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
10046 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
10048 using (Graphics g = Graphics.FromImage(bmp2))
10050 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
10051 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
10053 bmp2.Save(this.SaveFileDialog1.FileName);
10059 //処理中にキャッシュアウトする可能性あり
10064 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
10066 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
10067 if (multiline != this.StatusText.Multiline)
10069 this.StatusText.Multiline = multiline;
10070 MultiLineMenuItem.Checked = multiline;
10071 _modifySettingLocal = true;
10075 private void StatusText_MultilineChanged(object sender, EventArgs e)
10077 if (this.StatusText.Multiline)
10078 this.StatusText.ScrollBars = ScrollBars.Vertical;
10080 this.StatusText.ScrollBars = ScrollBars.None;
10082 _modifySettingLocal = true;
10085 private void MultiLineMenuItem_Click(object sender, EventArgs e)
10088 StatusText.Multiline = MultiLineMenuItem.Checked;
10089 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
10090 if (MultiLineMenuItem.Checked)
10092 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
10093 SplitContainer2.SplitterDistance = 0;
10095 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
10099 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
10101 _modifySettingLocal = true;
10104 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
10106 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
10107 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
10109 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
10110 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
10111 //Appendix A. Collected ABNF for URI
10112 //http://www.ietf.org/rfc/rfc3986.txt
10114 string result = "";
10116 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
10118 if (StatusText.SelectionLength > 0)
10120 string tmp = StatusText.SelectedText;
10121 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
10122 if (tmp.StartsWith("http"))
10124 // 文字列が選択されている場合はその文字列について処理
10126 //nico.ms使用、nicovideoにマッチしたら変換
10127 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10129 result = nicoms.Shorten(tmp);
10131 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10133 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10136 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10137 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10138 result = resultUri.AbsoluteUri;
10140 catch (WebApiException e)
10142 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10145 catch (UriFormatException e)
10147 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10156 if (!string.IsNullOrEmpty(result))
10158 urlUndo undotmp = new urlUndo();
10160 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
10161 StatusText.SelectedText = result;
10164 undotmp.Before = tmp;
10165 undotmp.After = result;
10167 if (urlUndoBuffer == null)
10169 urlUndoBuffer = new List<urlUndo>();
10170 UrlUndoToolStripMenuItem.Enabled = true;
10173 urlUndoBuffer.Add(undotmp);
10179 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
10180 @"(?<url>(?<protocol>https?://)" +
10181 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
10182 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
10183 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
10184 // 正規表現にマッチしたURL文字列をtinyurl化
10185 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
10187 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
10188 string tmp = mt.Result("${url}");
10189 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
10190 urlUndo undotmp = new urlUndo();
10193 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10195 //nico.ms使用、nicovideoにマッチしたら変換
10196 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10198 result = nicoms.Shorten(tmp);
10200 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10202 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10205 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10206 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10207 result = resultUri.AbsoluteUri;
10209 catch (HttpRequestException e)
10211 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
10212 // のように長いので「:」が含まれていればそれ以降のみを抽出する
10213 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
10215 this.StatusLabel.Text = Converter_Type + ":" + message;
10218 catch (WebApiException e)
10220 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10223 catch (UriFormatException e)
10225 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10234 if (!string.IsNullOrEmpty(result))
10236 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10237 StatusText.SelectedText = result;
10239 undotmp.Before = mt.Result("${url}");
10240 undotmp.After = result;
10242 if (urlUndoBuffer == null)
10244 urlUndoBuffer = new List<urlUndo>();
10245 UrlUndoToolStripMenuItem.Enabled = true;
10248 urlUndoBuffer.Add(undotmp);
10256 private void doUrlUndo()
10258 if (urlUndoBuffer != null)
10260 string tmp = StatusText.Text;
10261 foreach (urlUndo data in urlUndoBuffer)
10263 tmp = tmp.Replace(data.After, data.Before);
10265 StatusText.Text = tmp;
10266 urlUndoBuffer = null;
10267 UrlUndoToolStripMenuItem.Enabled = false;
10268 StatusText.SelectionStart = 0;
10269 StatusText.SelectionLength = 0;
10273 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10275 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10278 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10280 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10283 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10285 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10288 private async void UxnuMenuItem_Click(object sender, EventArgs e)
10290 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10293 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10295 if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
10297 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
10298 Random rnd = new Random();
10299 // 前回使用した短縮URLサービス以外を選択する
10302 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10304 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10305 await UrlConvertAsync(svc);
10309 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10314 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10316 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10317 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10318 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10319 _modifySettingCommon = true;
10322 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10324 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10325 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10326 _cfgCommon.ListLock = ListLockMenuItem.Checked;
10327 _modifySettingCommon = true;
10330 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10332 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10333 MenuStrip1.Tag = new Object();
10334 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10337 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10339 if (this.Tag != null) // 設定された戻り先へ遷移
10341 if (this.Tag == this.ListTab.SelectedTab)
10342 ((Control)this.ListTab.SelectedTab.Tag).Select();
10344 ((Control)this.Tag).Select();
10346 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10348 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10350 this.Tag = ListTab.SelectedTab.Tag;
10351 ((Control)this.Tag).Select();
10354 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10355 MenuStrip1.Tag = null;
10358 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10360 DetailsListView lst = (DetailsListView)sender;
10361 if (_cfgLocal == null) return;
10365 _cfgLocal.Width1 = lst.Columns[0].Width;
10366 _cfgLocal.Width3 = lst.Columns[1].Width;
10370 int[] darr = new int[lst.Columns.Count];
10371 for (int i = 0; i < lst.Columns.Count; i++)
10373 darr[lst.Columns[i].DisplayIndex] = i;
10375 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10377 for (int i = 0; i < lst.Columns.Count; i++)
10382 _cfgLocal.DisplayIndex1 = i;
10385 _cfgLocal.DisplayIndex2 = i;
10388 _cfgLocal.DisplayIndex3 = i;
10391 _cfgLocal.DisplayIndex4 = i;
10394 _cfgLocal.DisplayIndex5 = i;
10397 _cfgLocal.DisplayIndex6 = i;
10400 _cfgLocal.DisplayIndex7 = i;
10403 _cfgLocal.DisplayIndex8 = i;
10407 _cfgLocal.Width1 = lst.Columns[0].Width;
10408 _cfgLocal.Width2 = lst.Columns[1].Width;
10409 _cfgLocal.Width3 = lst.Columns[2].Width;
10410 _cfgLocal.Width4 = lst.Columns[3].Width;
10411 _cfgLocal.Width5 = lst.Columns[4].Width;
10412 _cfgLocal.Width6 = lst.Columns[5].Width;
10413 _cfgLocal.Width7 = lst.Columns[6].Width;
10414 _cfgLocal.Width8 = lst.Columns[7].Width;
10416 _modifySettingLocal = true;
10417 _isColumnChanged = true;
10420 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10422 DetailsListView lst = (DetailsListView)sender;
10423 if (_cfgLocal == null) return;
10426 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10428 _cfgLocal.Width1 = lst.Columns[0].Width;
10429 _modifySettingLocal = true;
10430 _isColumnChanged = true;
10432 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10434 _cfgLocal.Width3 = lst.Columns[1].Width;
10435 _modifySettingLocal = true;
10436 _isColumnChanged = true;
10441 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10443 _cfgLocal.Width1 = lst.Columns[0].Width;
10444 _modifySettingLocal = true;
10445 _isColumnChanged = true;
10447 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10449 _cfgLocal.Width2 = lst.Columns[1].Width;
10450 _modifySettingLocal = true;
10451 _isColumnChanged = true;
10453 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10455 _cfgLocal.Width3 = lst.Columns[2].Width;
10456 _modifySettingLocal = true;
10457 _isColumnChanged = true;
10459 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10461 _cfgLocal.Width4 = lst.Columns[3].Width;
10462 _modifySettingLocal = true;
10463 _isColumnChanged = true;
10465 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10467 _cfgLocal.Width5 = lst.Columns[4].Width;
10468 _modifySettingLocal = true;
10469 _isColumnChanged = true;
10471 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10473 _cfgLocal.Width6 = lst.Columns[5].Width;
10474 _modifySettingLocal = true;
10475 _isColumnChanged = true;
10477 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10479 _cfgLocal.Width7 = lst.Columns[6].Width;
10480 _modifySettingLocal = true;
10481 _isColumnChanged = true;
10483 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10485 _cfgLocal.Width8 = lst.Columns[7].Width;
10486 _modifySettingLocal = true;
10487 _isColumnChanged = true;
10490 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10493 // SaveConfigsLocal();
10497 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10500 string _selText = this.PostBrowser.GetSelectedText();
10503 Clipboard.SetDataObject(_selText, false, 5, 100);
10505 catch (Exception ex)
10507 MessageBox.Show(ex.Message);
10511 private async Task doSearchToolStrip(string url)
10513 //発言詳細で「選択文字列で検索」(選択文字列取得)
10514 string _selText = this.PostBrowser.GetSelectedText();
10516 if (_selText != null)
10518 if (url == Properties.Resources.SearchItem4Url)
10521 AddNewTabForSearch(_selText);
10525 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10526 await this.OpenUriInBrowserAsync(tmp);
10530 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10533 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10536 private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10538 await this.doSearchToolStrip(Properties.Resources.SearchItem1Url);
10541 private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10543 await this.doSearchToolStrip(Properties.Resources.SearchItem2Url);
10546 private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10548 await this.doSearchToolStrip(Properties.Resources.SearchItem4Url);
10551 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10555 foreach (var link in this.PostBrowser.Document.Links.Cast<HtmlElement>())
10557 if (link.GetAttribute("href") == this._postBrowserStatusText)
10559 Clipboard.SetDataObject(link.GetAttribute("title"), false, 5, 100);
10564 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10566 catch (Exception ex)
10568 MessageBox.Show(ex.Message);
10572 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10574 // URLコピーの項目の表示/非表示
10575 if (PostBrowser.StatusText.StartsWith("http"))
10577 this._postBrowserStatusText = PostBrowser.StatusText;
10578 string name = GetUserId();
10579 UrlCopyContextMenuItem.Enabled = true;
10582 FollowContextMenuItem.Enabled = true;
10583 RemoveContextMenuItem.Enabled = true;
10584 FriendshipContextMenuItem.Enabled = true;
10585 ShowUserStatusContextMenuItem.Enabled = true;
10586 SearchPostsDetailToolStripMenuItem.Enabled = true;
10587 IdFilterAddMenuItem.Enabled = true;
10588 ListManageUserContextToolStripMenuItem.Enabled = true;
10589 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10593 FollowContextMenuItem.Enabled = false;
10594 RemoveContextMenuItem.Enabled = false;
10595 FriendshipContextMenuItem.Enabled = false;
10596 ShowUserStatusContextMenuItem.Enabled = false;
10597 SearchPostsDetailToolStripMenuItem.Enabled = false;
10598 IdFilterAddMenuItem.Enabled = false;
10599 ListManageUserContextToolStripMenuItem.Enabled = false;
10600 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10603 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10604 UseHashtagMenuItem.Enabled = true;
10606 UseHashtagMenuItem.Enabled = false;
10610 this._postBrowserStatusText = "";
10611 UrlCopyContextMenuItem.Enabled = false;
10612 FollowContextMenuItem.Enabled = false;
10613 RemoveContextMenuItem.Enabled = false;
10614 FriendshipContextMenuItem.Enabled = false;
10615 ShowUserStatusContextMenuItem.Enabled = false;
10616 SearchPostsDetailToolStripMenuItem.Enabled = false;
10617 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10618 UseHashtagMenuItem.Enabled = false;
10619 IdFilterAddMenuItem.Enabled = false;
10620 ListManageUserContextToolStripMenuItem.Enabled = false;
10622 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10623 string _selText = this.PostBrowser.GetSelectedText();
10624 if (_selText == null)
10626 SelectionSearchContextMenuItem.Enabled = false;
10627 SelectionCopyContextMenuItem.Enabled = false;
10628 SelectionTranslationToolStripMenuItem.Enabled = false;
10632 SelectionSearchContextMenuItem.Enabled = true;
10633 SelectionCopyContextMenuItem.Enabled = true;
10634 SelectionTranslationToolStripMenuItem.Enabled = true;
10636 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10637 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10638 bool fAllFlag = false;
10639 foreach (Match mu in ma)
10641 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
10647 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10649 if (_curPost == null)
10650 TranslationToolStripMenuItem.Enabled = false;
10652 TranslationToolStripMenuItem.Enabled = true;
10657 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10659 //発言詳細の選択文字列で現在のタブを検索
10660 string _selText = this.PostBrowser.GetSelectedText();
10662 if (_selText != null)
10664 var searchOptions = new SearchWordDialog.SearchOptions(
10665 SearchWordDialog.SearchType.Timeline,
10668 caseSensitive: false,
10671 this.SearchDialog.ResultOptions = searchOptions;
10674 searchOptions.Query,
10675 searchOptions.CaseSensitive,
10676 searchOptions.UseRegex,
10677 SEARCHTYPE.NextSearch);
10681 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10683 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10684 _modifySettingLocal = true;
10687 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10689 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10691 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10693 SelectMedia_DragDrop(e);
10696 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10698 var url = GetUrlFromDataObject(e.Data);
10701 if (url.Item2 == null)
10702 appendText = url.Item1;
10704 appendText = url.Item2 + " " + url.Item1;
10706 if (this.StatusText.TextLength == 0)
10707 this.StatusText.Text = appendText;
10709 this.StatusText.Text += " " + appendText;
10711 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10713 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10715 this.StatusText.Text += text;
10717 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10719 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10720 if (data != null) StatusText.Text += data;
10725 /// IDataObject から URL とタイトルの対を取得します
10728 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10730 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10731 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10732 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10734 if (data.GetDataPresent("text/x-moz-url"))
10736 // Firefox, Google Chrome で利用可能
10737 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10739 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10741 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10742 if (lines.Length < 2)
10743 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
10745 return new Tuple<string, string>(lines[0], lines[1]);
10748 else if (data.GetDataPresent("IESiteModeToUrl"))
10750 // Internet Exproler 用
10751 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10753 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10755 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10756 if (lines.Length < 2)
10757 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
10759 return new Tuple<string, string>(lines[0], lines[1]);
10762 else if (data.GetDataPresent("UniformResourceLocatorW"))
10766 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10768 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10769 return new Tuple<string, string>(url, null);
10773 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10776 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10778 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10780 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10782 SelectMedia_DragEnter(e);
10786 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10788 e.Effect = DragDropEffects.Copy;
10791 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10793 e.Effect = DragDropEffects.Copy;
10796 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10798 e.Effect = DragDropEffects.Copy;
10802 e.Effect = DragDropEffects.None;
10805 private void TweenMain_DragOver(object sender, DragEventArgs e)
10809 public bool IsNetworkAvailable()
10812 nw = MyCommon.IsNetworkAvailable();
10813 _myStatusOnline = nw;
10817 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
10819 var uriStr = uri.AbsoluteUri;
10821 // OpenTween 内部で使用する URL
10822 if (uri.Authority == "opentween")
10824 await this.OpenInternalUriAsync(uri);
10828 // ハッシュタグを含む Twitter 検索
10829 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
10831 // ハッシュタグの場合は、タブで開く
10832 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
10833 var pos = unescapedQuery.IndexOf('#');
10834 if (pos == -1) return;
10836 var hash = unescapedQuery.Substring(pos);
10837 this.HashSupl.AddItem(hash);
10838 this.HashMgr.AddHashToHistory(hash.Trim(), false);
10839 this.AddNewTabForSearch(hash);
10844 // フラグが立っている場合は設定と逆の動作をする
10845 if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
10846 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
10848 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
10849 if (userUriMatch.Success)
10851 var screenName = userUriMatch.Groups["ScreenName"].Value;
10852 if (this.IsTwitterId(screenName))
10854 this.AddNewTabForUserTimeline(screenName);
10860 // どのパターンにも該当しないURL
10861 await this.OpenUriInBrowserAsync(uriStr);
10865 /// OpenTween 内部の機能を呼び出すための URL を開きます
10867 private async Task OpenInternalUriAsync(Uri uri)
10869 // ツイートを開く (//opentween/status/:status_id)
10870 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
10873 var statusId = long.Parse(match.Groups[1].Value);
10874 await this.OpenRelatedTab(statusId);
10879 public Task OpenUriInBrowserAsync(string UriString)
10881 return Task.Run(() =>
10883 string myPath = UriString;
10887 var configBrowserPath = this._cfgLocal.BrowserPath;
10888 if (!string.IsNullOrEmpty(configBrowserPath))
10890 if (configBrowserPath.StartsWith("\"") && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2) > -1)
10892 int sep = configBrowserPath.IndexOf("\"", 2);
10893 string browserPath = configBrowserPath.Substring(1, sep - 1);
10895 if (sep < configBrowserPath.Length - 1)
10897 arg = configBrowserPath.Substring(sep + 1);
10899 myPath = arg + " " + myPath;
10900 System.Diagnostics.Process.Start(browserPath, myPath);
10904 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10909 System.Diagnostics.Process.Start(myPath);
10914 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10919 private void ListTabSelect(TabPage _tab)
10923 this.PurgeListViewItemCache();
10926 _curList = (DetailsListView)_tab.Tag;
10927 if (_curList.SelectedIndices.Count > 0)
10929 _curItemIndex = _curList.SelectedIndices[0];
10930 _curPost = GetCurTabPost(_curItemIndex);
10934 _curItemIndex = -1;
10938 _anchorPost = null;
10939 _anchorFlag = false;
10943 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10947 for (int i = 0; i < _curList.Columns.Count; i++)
10949 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10954 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10956 ListTabSelect(e.TabPage);
10959 private void SelectListItem(DetailsListView LView, int Index)
10962 Rectangle bnd = new Rectangle();
10964 var item = LView.FocusedItem;
10973 LView.SelectedIndices.Clear();
10975 while (LView.SelectedIndices.Count > 0);
10976 item = LView.Items[Index];
10977 item.Selected = true;
10978 item.Focused = true;
10980 if (flg) LView.Invalidate(bnd);
10983 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
10986 Rectangle bnd = new Rectangle();
10988 var item = LView.FocusedItem;
10999 LView.SelectedIndices.Clear();
11001 while (LView.SelectedIndices.Count > 0);
11002 LView.SelectItems(Index);
11004 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
11006 LView.SelectionMark = selectionMarkIndex;
11008 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
11010 LView.Items[focusedIndex].Focused = true;
11012 else if (Index != null && Index.Length != 0)
11014 LView.Items[Index.Last()].Focused = true;
11017 if (flg) LView.Invalidate(bnd);
11020 private void StartUserStream()
11022 tw.NewPostFromStream += tw_NewPostFromStream;
11023 tw.UserStreamStarted += tw_UserStreamStarted;
11024 tw.UserStreamStopped += tw_UserStreamStopped;
11025 tw.PostDeleted += tw_PostDeleted;
11026 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
11028 MenuItemUserStream.Text = "&UserStream ■";
11029 MenuItemUserStream.Enabled = true;
11030 StopToolStripMenuItem.Text = "&Start";
11031 StopToolStripMenuItem.Enabled = true;
11032 if (this._cfgCommon.UserstreamStartup) tw.StartUserStream();
11035 private async void TweenMain_Shown(object sender, EventArgs e)
11039 using (ControlTransaction.Update(this.PostBrowser))
11041 PostBrowser.Url = new Uri("about:blank");
11042 PostBrowser.DocumentText = ""; //発言詳細部初期化
11049 NotifyIcon1.Visible = true;
11051 if (this.IsNetworkAvailable())
11055 var loadTasks = new List<Task>
11057 this.RefreshMuteUserIdsAsync(),
11058 this.RefreshBlockIdsAsync(),
11059 this.RefreshNoRetweetIdsAsync(),
11060 this.RefreshTwitterConfigurationAsync(),
11061 this.GetHomeTimelineAsync(),
11062 this.GetReplyAsync(),
11063 this.GetDirectMessagesAsync(),
11064 this.GetPublicSearchAllAsync(),
11065 this.GetUserTimelineAllAsync(),
11066 this.GetListTimelineAllAsync(),
11069 if (this._cfgCommon.StartupFollowers)
11070 loadTasks.Add(this.RefreshFollowerIdsAsync());
11072 if (this._cfgCommon.GetFav)
11073 loadTasks.Add(this.GetFavoritesAsync());
11075 var allTasks = Task.WhenAll(loadTasks);
11080 var timeout = Task.Delay(5000);
11081 if (await Task.WhenAny(allTasks, timeout) != timeout)
11085 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
11087 if (MyCommon._endingFlag)
11091 if (MyCommon._endingFlag) return;
11093 if (ApplicationSettings.VersionInfoUrl != null)
11095 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
11096 if (this._cfgCommon.StartupVersion)
11097 await this.CheckNewVersion(true);
11101 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
11102 this.VerUpMenuItem.Enabled = false;
11103 this.VerUpMenuItem.Available = false;
11104 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
11107 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
11108 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
11110 MessageBox.Show(Properties.Resources.ReAuthorizeText);
11111 SettingStripMenuItem_Click(null, null);
11115 var reloadTasks = new List<Task>();
11117 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
11118 reloadTasks.Add(this.RefreshFollowerIdsAsync());
11120 if (!tw.GetNoRetweetSuccess)
11121 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
11123 if (this.tw.Configuration.PhotoSizeLimit == 0)
11124 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
11126 await Task.WhenAll(reloadTasks);
11131 TimerTimeline.Enabled = true;
11134 private async Task doGetFollowersMenu()
11136 await this.RefreshFollowerIdsAsync();
11137 await this.DispSelectedPost(true);
11140 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
11142 await this.doGetFollowersMenu();
11145 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
11147 doReTweetUnofficial();
11150 private async Task doReTweetOfficial(bool isConfirm)
11153 if (this.ExistCurrentPost)
11155 if (_curPost.IsProtect)
11157 MessageBox.Show("Protected.");
11158 _DoFavRetweetFlags = false;
11161 if (_curList.SelectedIndices.Count > 15)
11163 MessageBox.Show(Properties.Resources.RetweetLimitText);
11164 _DoFavRetweetFlags = false;
11167 else if (_curList.SelectedIndices.Count > 1)
11169 string QuestionText = Properties.Resources.RetweetQuestion2;
11170 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
11171 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
11173 case DialogResult.Cancel:
11174 case DialogResult.No:
11175 _DoFavRetweetFlags = false;
11181 if (_curPost.IsDm || _curPost.IsMe)
11183 _DoFavRetweetFlags = false;
11186 if (!this._cfgCommon.RetweetNoConfirm)
11188 string Questiontext = Properties.Resources.RetweetQuestion1;
11189 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11190 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11192 _DoFavRetweetFlags = false;
11198 var statusIds = new List<long>();
11199 foreach (int idx in _curList.SelectedIndices)
11201 PostClass post = GetCurTabPost(idx);
11202 if (!post.IsMe && !post.IsProtect && !post.IsDm)
11203 statusIds.Add(post.StatusId);
11206 await this.RetweetAsync(statusIds);
11210 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
11212 await this.doReTweetOfficial(true);
11215 private async Task FavoritesRetweetOfficial()
11217 if (!this.ExistCurrentPost) return;
11218 _DoFavRetweetFlags = true;
11219 var retweetTask = this.doReTweetOfficial(true);
11220 if (_DoFavRetweetFlags)
11222 _DoFavRetweetFlags = false;
11223 var favoriteTask = this.FavoriteChange(true, false);
11225 await Task.WhenAll(retweetTask, favoriteTask);
11233 private async Task FavoritesRetweetUnofficial()
11235 if (this.ExistCurrentPost && !_curPost.IsDm)
11237 _DoFavRetweetFlags = true;
11238 var favoriteTask = this.FavoriteChange(true);
11239 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11241 _DoFavRetweetFlags = false;
11242 doReTweetUnofficial();
11245 await favoriteTask;
11250 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11252 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11253 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11254 /// <returns>復元されたツイート本文</returns>
11255 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11257 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11260 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11262 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11264 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11268 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11270 statusHtml = statusHtml.Replace("<br>", " ");
11272 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11273 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
11274 statusHtml = statusHtml.Replace(" ", " ");
11276 return WebUtility.HtmlDecode(statusHtml);
11279 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11281 if (_curPost != null)
11282 await this.DispSelectedPost(true);
11285 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11287 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11288 DebugModeToolStripMenuItem.Visible = true;
11290 DebugModeToolStripMenuItem.Visible = false;
11293 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11295 this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11298 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11300 ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
11303 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11305 if (TraceOutToolStripMenuItem.Checked)
11306 MyCommon.TraceFlag = true;
11308 MyCommon.TraceFlag = false;
11311 private void TweenMain_Deactivate(object sender, EventArgs e)
11313 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11314 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11317 private void TabRenameMenuItem_Click(object sender, EventArgs e)
11319 if (string.IsNullOrEmpty(_rclickTabName)) return;
11320 TabRename(ref _rclickTabName);
11323 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11325 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11328 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11330 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11333 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11335 TwitterApiStatus apiStatus;
11337 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
11339 var cancellationToken = dialog.EnableCancellation();
11343 var task = Task.Run(() => this.tw.GetInfoApi());
11344 apiStatus = await dialog.WaitForAsync(this, task);
11346 catch (WebApiException)
11351 if (cancellationToken.IsCancellationRequested)
11354 if (apiStatus == null)
11356 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11361 using (var apiDlg = new ApiInfoDialog())
11363 apiDlg.ShowDialog(this);
11367 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
11369 var id = _curPost?.ScreenName ?? "";
11371 await this.FollowCommand(id);
11374 private async Task FollowCommand(string id)
11376 using (var inputName = new InputTabName())
11378 inputName.FormTitle = "Follow";
11379 inputName.FormDescription = Properties.Resources.FRMessage1;
11380 inputName.TabName = id;
11382 if (inputName.ShowDialog(this) != DialogResult.OK)
11384 if (string.IsNullOrWhiteSpace(inputName.TabName))
11387 id = inputName.TabName.Trim();
11390 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
11394 var task = Task.Run(() => this.tw.PostFollowCommand(id));
11395 await dialog.WaitForAsync(this, task);
11397 catch (WebApiException ex)
11399 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11404 MessageBox.Show(Properties.Resources.FRMessage3);
11407 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11409 var id = _curPost?.ScreenName ?? "";
11411 await this.RemoveCommand(id, false);
11414 private async Task RemoveCommand(string id, bool skipInput)
11418 using (var inputName = new InputTabName())
11420 inputName.FormTitle = "Unfollow";
11421 inputName.FormDescription = Properties.Resources.FRMessage1;
11422 inputName.TabName = id;
11424 if (inputName.ShowDialog(this) != DialogResult.OK)
11426 if (string.IsNullOrWhiteSpace(inputName.TabName))
11429 id = inputName.TabName.Trim();
11433 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
11437 var task = Task.Run(() => this.tw.PostRemoveCommand(id));
11438 await dialog.WaitForAsync(this, task);
11440 catch (WebApiException ex)
11442 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11447 MessageBox.Show(Properties.Resources.FRMessage3);
11450 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
11452 var id = _curPost?.ScreenName ?? "";
11454 await this.ShowFriendship(id);
11457 private async Task ShowFriendship(string id)
11459 using (var inputName = new InputTabName())
11461 inputName.FormTitle = "Show Friendships";
11462 inputName.FormDescription = Properties.Resources.FRMessage1;
11463 inputName.TabName = id;
11465 if (inputName.ShowDialog(this) != DialogResult.OK)
11467 if (string.IsNullOrWhiteSpace(inputName.TabName))
11470 id = inputName.TabName.Trim();
11473 bool isFollowing, isFollowed;
11475 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11477 var cancellationToken = dialog.EnableCancellation();
11481 var task = Task.Run(() => this.tw.GetFriendshipInfo(id));
11482 var friendship = await dialog.WaitForAsync(this, task);
11484 isFollowing = friendship.Relationship.Source.Following;
11485 isFollowed = friendship.Relationship.Source.FollowedBy;
11487 catch (WebApiException ex)
11489 if (!cancellationToken.IsCancellationRequested)
11490 MessageBox.Show(ex.Message);
11494 if (cancellationToken.IsCancellationRequested)
11498 string result = "";
11501 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11505 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11509 result += Properties.Resources.GetFriendshipInfo3;
11513 result += Properties.Resources.GetFriendshipInfo4;
11515 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11516 MessageBox.Show(result);
11519 private async Task ShowFriendship(string[] ids)
11521 foreach (string id in ids)
11523 bool isFollowing, isFollowed;
11525 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11527 var cancellationToken = dialog.EnableCancellation();
11531 var task = Task.Run(() => this.tw.GetFriendshipInfo(id));
11532 var friendship = await dialog.WaitForAsync(this, task);
11534 isFollowing = friendship.Relationship.Source.Following;
11535 isFollowed = friendship.Relationship.Source.FollowedBy;
11537 catch (WebApiException ex)
11539 if (!cancellationToken.IsCancellationRequested)
11540 MessageBox.Show(ex.Message);
11544 if (cancellationToken.IsCancellationRequested)
11548 string result = "";
11554 ff += Properties.Resources.GetFriendshipInfo1;
11558 ff += Properties.Resources.GetFriendshipInfo2;
11561 ff += System.Environment.NewLine + " ";
11564 ff += Properties.Resources.GetFriendshipInfo3;
11568 ff += Properties.Resources.GetFriendshipInfo4;
11570 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11573 if (MessageBox.Show(
11574 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11575 MessageBoxButtons.YesNo,
11576 MessageBoxIcon.Question,
11577 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11579 await this.RemoveCommand(id, true);
11584 MessageBox.Show(result);
11589 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
11591 await this.doShowUserStatus(tw.Username, false);
11592 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11594 // doShowUserStatus(tw.Username, false);
11598 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11603 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11604 // URLから切り出した文字列を渡す
11606 public bool IsTwitterId(string name)
11608 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11609 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11611 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLower());
11614 private string GetUserId()
11616 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11617 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11618 return m.Result("${ScreenName}");
11623 private async void FollowContextMenuItem_Click(object sender, EventArgs e)
11625 string name = GetUserId();
11627 await this.FollowCommand(name);
11630 private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
11632 string name = GetUserId();
11634 await this.RemoveCommand(name, false);
11637 private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11639 string name = GetUserId();
11641 await this.ShowFriendship(name);
11644 private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11646 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11647 List<string> ids = new List<string>();
11648 foreach (Match mu in ma)
11650 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11652 ids.Add(mu.Result("${ScreenName}"));
11656 await this.ShowFriendship(ids.ToArray());
11659 private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11661 string name = GetUserId();
11663 await this.ShowUserStatus(name);
11666 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11668 string name = GetUserId();
11669 if (name != null) AddNewTabForUserTimeline(name);
11672 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11674 string name = GetUserId();
11675 if (name != null) AddNewTabForSearch("@" + name);
11678 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11680 _modifySettingCommon = true;
11683 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11685 _modifySettingCommon = true;
11688 private void doQuoteOfficial()
11690 if (this.ExistCurrentPost)
11692 if (_curPost.IsDm ||
11693 !StatusText.Enabled) return;
11695 if (_curPost.IsProtect)
11697 MessageBox.Show("Protected.");
11701 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
11703 this.inReplyTo = null;
11705 StatusText.SelectionStart = 0;
11706 StatusText.Focus();
11710 private void doReTweetUnofficial()
11713 if (this.ExistCurrentPost)
11715 if (_curPost.IsDm || !StatusText.Enabled)
11718 if (_curPost.IsProtect)
11720 MessageBox.Show("Protected.");
11723 string rtdata = _curPost.Text;
11724 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11726 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
11728 // 投稿時に in_reply_to_status_id を付加する
11729 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11730 var inReplyToScreenName = this._curPost.ScreenName;
11731 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
11733 StatusText.SelectionStart = 0;
11734 StatusText.Focus();
11738 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11743 private void SearchButton_Click(object sender, EventArgs e)
11746 Control pnl = ((Control)sender).Parent;
11747 if (pnl == null) return;
11748 string tbName = pnl.Parent.Text;
11749 TabClass tb = _statuses.Tabs[tbName];
11750 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11751 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11752 cmb.Text = cmb.Text.Trim();
11753 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11754 bool Quote = false;
11755 StringBuilder buf = new StringBuilder();
11756 char[] c = cmb.Text.ToCharArray();
11757 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11759 if (cnt > cmb.Text.Length - 4)
11761 buf.Append(cmb.Text.Substring(cnt));
11770 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11772 buf.Append(" OR ");
11777 buf.Append(c[cnt]);
11779 cmb.Text = buf.ToString();
11781 var listView = (DetailsListView)pnl.Parent.Tag;
11783 tb.SearchWords = cmb.Text;
11784 tb.SearchLang = cmbLang.Text;
11785 if (string.IsNullOrEmpty(cmb.Text))
11791 if (tb.IsSearchQueryChanged)
11793 int idx = cmb.Items.IndexOf(tb.SearchWords);
11794 if (idx > -1) cmb.Items.RemoveAt(idx);
11795 cmb.Items.Insert(0, tb.SearchWords);
11796 cmb.Text = tb.SearchWords;
11798 this.PurgeListViewItemCache();
11799 listView.VirtualListSize = 0;
11800 _statuses.ClearTabIds(tbName);
11801 SaveConfigsTabs(); //検索条件の保存
11804 this.GetPublicSearchAsync(tb);
11808 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11811 await this.DoRefreshMore();
11815 /// 指定されたタブのListTabにおける位置を返します
11818 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
11820 public int GetTabPageIndex(string tabName)
11823 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
11825 if (tabPage.Text == tabName)
11834 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11836 if (_statuses.RemovedTab.Count == 0)
11838 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11843 DetailsListView listView = null;
11845 TabClass tb = _statuses.RemovedTab.Pop();
11846 if (tb.TabType == MyCommon.TabUsageType.Related)
11848 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11849 if (relatedTab != null)
11851 // 関連発言なら既存のタブを置き換える
11852 tb.TabName = relatedTab.TabName;
11853 this.ClearTab(tb.TabName, false);
11854 _statuses.Tabs[tb.TabName] = tb;
11856 for (int i = 0; i < ListTab.TabPages.Count; i++)
11858 var tabPage = ListTab.TabPages[i];
11859 if (tb.TabName == tabPage.Text)
11861 listView = (DetailsListView)tabPage.Tag;
11862 ListTab.SelectedIndex = i;
11869 const string TabName = "Related Tweets";
11870 string renamed = TabName;
11871 for (int i = 2; i <= 100; i++)
11873 if (!_statuses.ContainsTab(renamed)) break;
11874 renamed = TabName + i.ToString();
11876 tb.TabName = renamed;
11877 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11878 _statuses.Tabs.Add(renamed, tb); // 後に
11880 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11881 listView = (DetailsListView)tabPage.Tag;
11882 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11887 string renamed = tb.TabName;
11888 for (int i = 1; i < int.MaxValue; i++)
11890 if (!_statuses.ContainsTab(renamed)) break;
11891 renamed = tb.TabName + "(" + i.ToString() + ")";
11893 tb.TabName = renamed;
11894 _statuses.Tabs.Add(renamed, tb); // 先に
11895 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11897 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11898 listView = (DetailsListView)tabPage.Tag;
11899 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11903 if (listView != null)
11905 using (ControlTransaction.Update(listView))
11907 listView.VirtualListSize = tb.AllCount;
11913 private async Task doMoveToRTHome()
11915 if (_curList.SelectedIndices.Count > 0)
11917 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11918 if (post.RetweetedId != null)
11920 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11925 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11927 await this.doMoveToRTHome();
11930 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11932 string name = GetUserId();
11938 if (_curList.SelectedIndices.Count == 0) return;
11941 if (!SelectTab(out tabName)) return;
11943 var tab = this._statuses.Tabs[tabName];
11947 if (tab.TabType != MyCommon.TabUsageType.Mute)
11949 this.MoveOrCopy(out mv, out mk);
11953 // ミュートタブでは常に MoveMatches を true にする
11958 PostFilterRule fc = new PostFilterRule();
11959 fc.FilterName = name;
11960 fc.UseNameField = true;
11961 fc.MoveMatches = mv;
11962 fc.MarkMatches = mk;
11963 fc.UseRegex = false;
11964 fc.FilterByUrl = false;
11967 this.ApplyPostFilters();
11972 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11976 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11978 if (menuItem.Owner == this.ContextMenuPostBrowser)
11980 user = GetUserId();
11981 if (user == null) return;
11983 else if (this._curPost != null)
11985 user = this._curPost.ScreenName;
11992 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11996 this.tw.GetListsApi();
11998 catch (WebApiException ex)
12000 MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
12005 using (MyLists listSelectForm = new MyLists(user, this.tw))
12007 listSelectForm.ShowDialog(this);
12011 private void SearchControls_Enter(object sender, EventArgs e)
12013 Control pnl = (Control)sender;
12014 foreach (Control ctl in pnl.Controls)
12016 ctl.TabStop = true;
12020 private void SearchControls_Leave(object sender, EventArgs e)
12022 Control pnl = (Control)sender;
12023 foreach (Control ctl in pnl.Controls)
12025 ctl.TabStop = false;
12029 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
12031 if (ListTab.SelectedTab != null)
12033 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
12034 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
12038 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
12040 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
12043 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
12044 HashStripSplitButton.Text = HashMgr.UseHash;
12045 HashToggleMenuItem.Checked = true;
12046 HashToggleToolStripMenuItem.Checked = true;
12048 _modifySettingCommon = true;
12052 private void StatusLabel_DoubleClick(object sender, EventArgs e)
12054 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
12057 private void HashManageMenuItem_Click(object sender, EventArgs e)
12059 DialogResult rslt = DialogResult.Cancel;
12062 rslt = HashMgr.ShowDialog();
12068 this.TopMost = this._cfgCommon.AlwaysTop;
12069 if (rslt == DialogResult.Cancel) return;
12070 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12072 HashStripSplitButton.Text = HashMgr.UseHash;
12073 HashToggleMenuItem.Checked = true;
12074 HashToggleToolStripMenuItem.Checked = true;
12078 HashStripSplitButton.Text = "#[-]";
12079 HashToggleMenuItem.Checked = false;
12080 HashToggleToolStripMenuItem.Checked = false;
12082 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
12084 // int sidx = StatusText.SelectionStart;
12085 // string hash = HashMgr.UseHash + " ";
12088 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
12089 // hash = " " + hash;
12091 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
12092 // sidx += hash.Length;
12093 // StatusText.SelectionStart = sidx;
12094 // StatusText.Focus();
12096 _modifySettingCommon = true;
12097 this.StatusText_TextChanged(null, null);
12100 private void HashToggleMenuItem_Click(object sender, EventArgs e)
12102 HashMgr.ToggleHash();
12103 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12105 HashStripSplitButton.Text = HashMgr.UseHash;
12106 HashToggleMenuItem.Checked = true;
12107 HashToggleToolStripMenuItem.Checked = true;
12111 HashStripSplitButton.Text = "#[-]";
12112 HashToggleMenuItem.Checked = false;
12113 HashToggleToolStripMenuItem.Checked = false;
12115 _modifySettingCommon = true;
12116 this.StatusText_TextChanged(null, null);
12119 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
12121 HashToggleMenuItem_Click(null, null);
12124 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
12126 if (ListTab.SelectedTab == null) return;
12127 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
12128 if (!this.ExistCurrentPost)
12130 this.ReplyOpMenuItem.Enabled = false;
12131 this.ReplyAllOpMenuItem.Enabled = false;
12132 this.DmOpMenuItem.Enabled = false;
12133 this.ShowProfMenuItem.Enabled = false;
12134 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
12135 this.ListManageMenuItem.Enabled = false;
12136 this.OpenFavOpMenuItem.Enabled = false;
12137 this.CreateTabRuleOpMenuItem.Enabled = false;
12138 this.CreateIdRuleOpMenuItem.Enabled = false;
12139 this.CreateSourceRuleOpMenuItem.Enabled = false;
12140 this.ReadOpMenuItem.Enabled = false;
12141 this.UnreadOpMenuItem.Enabled = false;
12145 this.ReplyOpMenuItem.Enabled = true;
12146 this.ReplyAllOpMenuItem.Enabled = true;
12147 this.DmOpMenuItem.Enabled = true;
12148 this.ShowProfMenuItem.Enabled = true;
12149 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
12150 this.ListManageMenuItem.Enabled = true;
12151 this.OpenFavOpMenuItem.Enabled = true;
12152 this.CreateTabRuleOpMenuItem.Enabled = true;
12153 this.CreateIdRuleOpMenuItem.Enabled = true;
12154 this.CreateSourceRuleOpMenuItem.Enabled = true;
12155 this.ReadOpMenuItem.Enabled = true;
12156 this.UnreadOpMenuItem.Enabled = true;
12159 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
12161 this.FavOpMenuItem.Enabled = false;
12162 this.UnFavOpMenuItem.Enabled = false;
12163 this.OpenStatusOpMenuItem.Enabled = false;
12164 this.OpenFavotterOpMenuItem.Enabled = false;
12165 this.ShowRelatedStatusesMenuItem2.Enabled = false;
12166 this.RtOpMenuItem.Enabled = false;
12167 this.RtUnOpMenuItem.Enabled = false;
12168 this.QtOpMenuItem.Enabled = false;
12169 this.FavoriteRetweetMenuItem.Enabled = false;
12170 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12174 this.FavOpMenuItem.Enabled = true;
12175 this.UnFavOpMenuItem.Enabled = true;
12176 this.OpenStatusOpMenuItem.Enabled = true;
12177 this.OpenFavotterOpMenuItem.Enabled = true;
12178 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
12182 this.RtOpMenuItem.Enabled = false; //公式RTは無効に
12183 this.RtUnOpMenuItem.Enabled = true;
12184 this.QtOpMenuItem.Enabled = true;
12185 this.FavoriteRetweetMenuItem.Enabled = false; //公式RTは無効に
12186 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12190 if (_curPost.IsProtect)
12192 this.RtOpMenuItem.Enabled = false;
12193 this.RtUnOpMenuItem.Enabled = false;
12194 this.QtOpMenuItem.Enabled = false;
12195 this.FavoriteRetweetMenuItem.Enabled = false;
12196 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12200 this.RtOpMenuItem.Enabled = true;
12201 this.RtUnOpMenuItem.Enabled = true;
12202 this.QtOpMenuItem.Enabled = true;
12203 this.FavoriteRetweetMenuItem.Enabled = true;
12204 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12209 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
12211 this.RefreshPrevOpMenuItem.Enabled = true;
12215 this.RefreshPrevOpMenuItem.Enabled = false;
12217 if (!this.ExistCurrentPost
12218 || _curPost.InReplyToStatusId == null)
12220 OpenRepSourceOpMenuItem.Enabled = false;
12224 OpenRepSourceOpMenuItem.Enabled = true;
12226 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12228 OpenRterHomeMenuItem.Enabled = false;
12232 OpenRterHomeMenuItem.Enabled = true;
12235 if (this.ExistCurrentPost)
12237 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
12241 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12243 ContextMenuTabProperty_Opening(sender, null);
12246 public Twitter TwitterInstance
12251 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12253 if (this._initialLayout)
12256 int splitterDistance;
12257 switch (this.WindowState)
12259 case FormWindowState.Normal:
12260 splitterDistance = this.SplitContainer3.SplitterDistance;
12262 case FormWindowState.Maximized:
12263 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
12264 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
12265 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
12266 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
12272 this._mySpDis3 = splitterDistance;
12273 this._modifySettingLocal = true;
12276 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12278 if (_statuses.RemovedTab.Count == 0)
12280 UndoRemoveTabMenuItem.Enabled = false;
12284 UndoRemoveTabMenuItem.Enabled = true;
12286 if (ListTab.SelectedTab != null)
12288 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12289 PublicSearchQueryMenuItem.Enabled = true;
12291 PublicSearchQueryMenuItem.Enabled = false;
12295 PublicSearchQueryMenuItem.Enabled = false;
12297 if (!this.ExistCurrentPost)
12299 this.CopySTOTMenuItem.Enabled = false;
12300 this.CopyURLMenuItem.Enabled = false;
12301 this.CopyUserIdStripMenuItem.Enabled = false;
12305 this.CopySTOTMenuItem.Enabled = true;
12306 this.CopyURLMenuItem.Enabled = true;
12307 this.CopyUserIdStripMenuItem.Enabled = true;
12308 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12309 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12313 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12315 SetNotifyIconText();
12318 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12320 var id = _curPost?.ScreenName ?? "";
12322 await this.ShowUserStatus(id);
12325 private async Task doShowUserStatus(string id, bool ShowInputDialog)
12327 TwitterUser user = null;
12329 if (ShowInputDialog)
12331 using (var inputName = new InputTabName())
12333 inputName.FormTitle = "Show UserStatus";
12334 inputName.FormDescription = Properties.Resources.FRMessage1;
12335 inputName.TabName = id;
12337 if (inputName.ShowDialog(this) != DialogResult.OK)
12339 if (string.IsNullOrWhiteSpace(inputName.TabName))
12342 id = inputName.TabName.Trim();
12346 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
12348 var cancellationToken = dialog.EnableCancellation();
12352 var task = Task.Run(() => this.tw.GetUserInfo(id));
12353 user = await dialog.WaitForAsync(this, task);
12355 catch (WebApiException ex)
12357 if (!cancellationToken.IsCancellationRequested)
12358 MessageBox.Show(ex.Message);
12362 if (cancellationToken.IsCancellationRequested)
12366 await this.doShowUserStatus(user);
12369 private async Task doShowUserStatus(TwitterUser user)
12371 using (var userDialog = new UserInfoDialog(this, this.tw))
12373 var showUserTask = userDialog.ShowUserAsync(user);
12374 userDialog.ShowDialog(this);
12377 this.BringToFront();
12379 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12380 await showUserTask;
12384 private Task ShowUserStatus(string id, bool ShowInputDialog)
12386 return this.doShowUserStatus(id, ShowInputDialog);
12389 private Task ShowUserStatus(string id)
12391 return this.doShowUserStatus(id, true);
12394 private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12396 if (NameLabel.Tag != null)
12398 string id = (string)NameLabel.Tag;
12399 if (id != tw.Username)
12401 await this.FollowCommand(id);
12406 private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12408 if (NameLabel.Tag != null)
12410 string id = (string)NameLabel.Tag;
12411 if (id != tw.Username)
12413 await this.RemoveCommand(id, false);
12418 private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12420 if (NameLabel.Tag != null)
12422 string id = (string)NameLabel.Tag;
12423 if (id != tw.Username)
12425 await this.ShowFriendship(id);
12430 private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12432 if (NameLabel.Tag != null)
12434 string id = (string)NameLabel.Tag;
12435 await this.ShowUserStatus(id, false);
12439 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12441 if (NameLabel.Tag != null)
12443 string id = (string)NameLabel.Tag;
12444 AddNewTabForUserTimeline(id);
12448 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12450 if (NameLabel.Tag != null)
12452 string id = (string)NameLabel.Tag;
12453 AddNewTabForSearch("@" + id);
12457 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
12459 if (_curPost != null)
12461 await this.ShowUserStatus(_curPost.ScreenName, false);
12465 private async void RtCountMenuItem_Click(object sender, EventArgs e)
12467 if (!this.ExistCurrentPost)
12470 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
12471 int retweetCount = 0;
12473 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
12475 var cancellationToken = dialog.EnableCancellation();
12479 var task = Task.Run(() => this.tw.GetStatus_Retweeted_Count(statusId));
12480 retweetCount = await dialog.WaitForAsync(this, task);
12482 catch (WebApiException ex)
12484 if (!cancellationToken.IsCancellationRequested)
12485 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + ex.Message);
12489 if (cancellationToken.IsCancellationRequested)
12493 MessageBox.Show(retweetCount + Properties.Resources.RtCountText1);
12496 private HookGlobalHotkey _hookGlobalHotkey;
12499 _hookGlobalHotkey = new HookGlobalHotkey(this);
12501 // この呼び出しは、Windows フォーム デザイナで必要です。
12502 InitializeComponent();
12504 // InitializeComponent() 呼び出しの後で初期化を追加します。
12506 if (!this.DesignMode)
12508 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12509 this.StatusText.Dock = DockStyle.Fill;
12512 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12513 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12514 this.gh.NotifyClicked += GrowlHelper_Callback;
12516 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12517 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12519 this.ImageSelector.Visible = false;
12520 this.ImageSelector.Enabled = false;
12521 this.ImageSelector.FilePickDialog = OpenFileDialog1;
12523 this.ReplaceAppName();
12524 this.InitializeShortcuts();
12527 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12529 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12532 this.Visible = false;
12534 else if (Form.ActiveForm == null)
12536 this.Visible = true;
12537 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12539 this.BringToFront();
12540 this.StatusText.Focus();
12544 private void UserPicture_MouseEnter(object sender, EventArgs e)
12546 this.UserPicture.Cursor = Cursors.Hand;
12549 private void UserPicture_MouseLeave(object sender, EventArgs e)
12551 this.UserPicture.Cursor = Cursors.Default;
12554 private async void UserPicture_DoubleClick(object sender, EventArgs e)
12556 if (NameLabel.Tag != null)
12558 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12562 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12564 this.MultiLineMenuItem.PerformClick();
12567 public PostClass CurPost
12569 get { return _curPost; }
12573 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12575 if (ImageSelector.Visible)
12576 ImageSelector.EndSelection();
12578 ImageSelector.BeginSelection();
12581 private void SelectMedia_DragEnter(DragEventArgs e)
12583 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12585 e.Effect = DragDropEffects.Copy;
12588 e.Effect = DragDropEffects.None;
12591 private void SelectMedia_DragDrop(DragEventArgs e)
12594 this.BringToFront();
12595 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12596 StatusText.Focus();
12599 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12601 TimelinePanel.Visible = false;
12602 TimelinePanel.Enabled = false;
12605 private void ImageSelector_EndSelecting(object sender, EventArgs e)
12607 TimelinePanel.Visible = true;
12608 TimelinePanel.Enabled = true;
12609 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12612 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12614 this.AllowDrop = false;
12617 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12619 this.AllowDrop = true;
12622 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12624 if (ImageSelector.Visible)
12626 _modifySettingCommon = true;
12627 SaveConfigsAll(true);
12629 if (ImageSelector.ServiceName.Equals("Twitter"))
12630 this.StatusText_TextChanged(null, null);
12634 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12636 this.StatusText_TextChanged(null, null);
12640 /// StatusTextでCtrl+Vが押下された時の処理
12642 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
12644 if (Clipboard.ContainsText())
12646 // clipboardにテキストがある場合は貼り付け処理
12647 this.StatusText.Paste(Clipboard.GetText());
12649 else if (Clipboard.ContainsImage())
12652 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
12653 Properties.Resources.PostPictureWarn4,
12654 MessageBoxButtons.OKCancel,
12655 MessageBoxIcon.Question,
12656 MessageBoxDefaultButton.Button2)
12657 == DialogResult.OK)
12659 // clipboardから画像を取得
12660 using (var image = Clipboard.GetImage())
12662 this.ImageSelector.BeginSelection(image);
12669 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12671 using (ListManage form = new ListManage(tw))
12673 form.ShowDialog(this);
12677 public bool ModifySettingCommon
12679 set { _modifySettingCommon = value; }
12682 public bool ModifySettingLocal
12684 set { _modifySettingLocal = value; }
12687 public bool ModifySettingAtId
12689 set { _modifySettingAtId = value; }
12692 private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12694 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12695 if (sourceUri != null && e.Button == MouseButtons.Left)
12697 await this.OpenUriInBrowserAsync(sourceUri.AbsoluteUri);
12701 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12703 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12704 if (sourceUri != null)
12706 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri);
12710 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12712 SetStatusLabelUrl();
12715 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12717 if (this.ExistCurrentPost && !_curPost.IsDm)
12718 RtCountMenuItem.Enabled = true;
12720 RtCountMenuItem.Enabled = false;
12722 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12723 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12725 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12728 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12733 private void CopyUserId()
12735 if (_curPost == null) return;
12736 string clstr = _curPost.ScreenName;
12739 Clipboard.SetDataObject(clstr, false, 5, 100);
12741 catch (Exception ex)
12743 MessageBox.Show(ex.Message);
12747 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12749 if (this.ExistCurrentPost && !_curPost.IsDm)
12753 await this.OpenRelatedTab(this._curPost);
12755 catch (TabException ex)
12757 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12763 /// 指定されたツイートに対する関連発言タブを開きます
12765 /// <param name="statusId">表示するツイートのID</param>
12766 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12767 private async Task OpenRelatedTab(long statusId)
12769 var post = this._statuses[statusId];
12774 post = await Task.Run(() => this.tw.GetStatusApi(false, statusId));
12776 catch (WebApiException ex)
12778 this.StatusLabel.Text = ex.Message;
12783 await this.OpenRelatedTab(post);
12787 /// 指定されたツイートに対する関連発言タブを開きます
12789 /// <param name="post">表示する対象となるツイート</param>
12790 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12791 private async Task OpenRelatedTab(PostClass post)
12793 var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12796 if (tabRelated == null)
12798 tabName = this._statuses.MakeTabName("Related Tweets");
12800 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12801 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12803 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12804 tabRelated.UnreadManage = false;
12805 tabRelated.Notify = false;
12809 tabName = tabRelated.TabName;
12812 tabRelated.RelationTargetPost = post;
12813 this.ClearTab(tabName, false);
12815 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12817 var tabPage = this.ListTab.TabPages[i];
12818 if (tabName == tabPage.Text)
12820 this.ListTab.SelectedIndex = i;
12825 await this.GetRelatedTweetsAsync(tabRelated);
12828 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12830 StringBuilder buf = new StringBuilder();
12831 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12832 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12833 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12834 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12835 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12838 private void tw_UserIdChanged()
12840 this._modifySettingCommon = true;
12843 #region "Userstream"
12844 private bool _isActiveUserstream = false;
12846 private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12850 if (InvokeRequired && !IsDisposed)
12852 Invoke((Action) (async () =>
12854 _statuses.RemovePostReserve(e.StatusId);
12855 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12857 this.PurgeListViewItemCache();
12858 ((DetailsListView)_curTab.Tag).Update();
12859 if (_curPost != null && _curPost.StatusId == e.StatusId)
12860 await this.DispSelectedPost(true);
12866 catch (ObjectDisposedException)
12870 catch (InvalidOperationException)
12876 private void tw_NewPostFromStream(object sender, EventArgs e)
12878 if (this._cfgCommon.ReadOldPosts)
12880 _statuses.SetReadHomeTab(); //新着時未読クリア
12883 int rsltAddCount = _statuses.DistributePosts();
12886 DateTime tm = DateTime.Now;
12887 if (_tlTimestamps.ContainsKey(tm))
12889 _tlTimestamps[tm] += rsltAddCount;
12893 _tlTimestamps.Add(tm, rsltAddCount);
12895 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
12896 List<DateTime> keys = new List<DateTime>();
12898 foreach (DateTime key in _tlTimestamps.Keys)
12900 if (key.CompareTo(oneHour) < 0)
12903 _tlCount += _tlTimestamps[key];
12905 foreach (DateTime key in keys)
12907 _tlTimestamps.Remove(key);
12911 //Static DateTime before = Now;
12912 //if (before.Subtract(Now).Seconds > -5) return;
12916 if (this._cfgCommon.UserstreamPeriod > 0) return;
12920 if (InvokeRequired && !IsDisposed)
12922 Invoke((Action)(async () =>
12924 await this.RefreshTasktrayIcon(true);
12925 this.RefreshTimeline();
12930 catch (ObjectDisposedException)
12934 catch (InvalidOperationException)
12940 private void tw_UserStreamStarted(object sender, EventArgs e)
12942 this._isActiveUserstream = true;
12945 if (InvokeRequired && !IsDisposed)
12947 Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12951 catch (ObjectDisposedException)
12955 catch (InvalidOperationException)
12960 MenuItemUserStream.Text = "&UserStream ▶";
12961 MenuItemUserStream.Enabled = true;
12962 StopToolStripMenuItem.Text = "&Stop";
12963 StopToolStripMenuItem.Enabled = true;
12965 StatusLabel.Text = "UserStream Started.";
12968 private void tw_UserStreamStopped(object sender, EventArgs e)
12970 this._isActiveUserstream = false;
12973 if (InvokeRequired && !IsDisposed)
12975 Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12979 catch (ObjectDisposedException)
12983 catch (InvalidOperationException)
12988 MenuItemUserStream.Text = "&UserStream ■";
12989 MenuItemUserStream.Enabled = true;
12990 StopToolStripMenuItem.Text = "&Start";
12991 StopToolStripMenuItem.Enabled = true;
12993 StatusLabel.Text = "UserStream Stopped.";
12996 private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
13000 if (InvokeRequired && !IsDisposed)
13002 Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
13006 catch (ObjectDisposedException)
13010 catch (InvalidOperationException)
13014 var ev = e.EventData;
13015 StatusLabel.Text = "Event: " + ev.Event;
13016 //if (ev.Event == "favorite")
13018 // NotifyFavorite(ev);
13021 if (ev.Event == "favorite" || ev.Event == "unfavorite")
13023 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
13025 this.PurgeListViewItemCache();
13026 ((DetailsListView)_curTab.Tag).Update();
13028 if (ev.Event == "unfavorite" && ev.Username.ToLower().Equals(tw.Username.ToLower()))
13030 RemovePostFromFavTab(new long[] {ev.Id});
13035 private void NotifyEvent(Twitter.FormattedEvent ev)
13038 if (BalloonRequired(ev))
13040 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13041 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
13042 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
13043 StringBuilder title = new StringBuilder();
13044 if (this._cfgCommon.DispUsername)
13046 title.Append(tw.Username);
13047 title.Append(" - ");
13053 title.Append(Application.ProductName);
13054 title.Append(" [");
13055 title.Append(ev.Event.ToUpper());
13056 title.Append("] by ");
13057 if (!string.IsNullOrEmpty(ev.Username))
13059 title.Append(ev.Username.ToString());
13063 //title.Append("");
13066 if (!string.IsNullOrEmpty(ev.Target))
13068 //NotifyIcon1.BalloonTipText = ev.Target;
13073 //NotifyIcon1.BalloonTipText = " ";
13076 //NotifyIcon1.ShowBalloonTip(500);
13077 if (this._cfgCommon.IsUseNotifyGrowl)
13079 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13080 ev.Id.ToString(), title.ToString(), text);
13084 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13085 NotifyIcon1.BalloonTipTitle = title.ToString();
13086 NotifyIcon1.BalloonTipText = text;
13087 NotifyIcon1.ShowBalloonTip(500);
13092 string snd = this._cfgCommon.EventSoundFile;
13093 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
13095 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13099 string dir = Application.StartupPath;
13100 if (Directory.Exists(Path.Combine(dir, "Sounds")))
13102 dir = Path.Combine(dir, "Sounds");
13104 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13116 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13118 MenuItemUserStream.Enabled = false;
13119 if (StopRefreshAllMenuItem.Checked)
13121 StopRefreshAllMenuItem.Checked = false;
13124 if (this._isActiveUserstream)
13126 tw.StopUserStream();
13130 tw.StartUserStream();
13134 private static string inputTrack = "";
13136 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13138 if (TrackToolStripMenuItem.Checked)
13140 using (InputTabName inputForm = new InputTabName())
13142 inputForm.TabName = inputTrack;
13143 inputForm.FormTitle = "Input track word";
13144 inputForm.FormDescription = "Track word";
13145 if (inputForm.ShowDialog() != DialogResult.OK)
13147 TrackToolStripMenuItem.Checked = false;
13150 inputTrack = inputForm.TabName.Trim();
13152 if (!inputTrack.Equals(tw.TrackWord))
13154 tw.TrackWord = inputTrack;
13155 this._modifySettingCommon = true;
13156 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13157 tw.ReconnectUserStream();
13163 tw.ReconnectUserStream();
13165 this._modifySettingCommon = true;
13168 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13170 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13171 this._modifySettingCommon = true;
13172 tw.ReconnectUserStream();
13175 private void EventViewerMenuItem_Click(object sender, EventArgs e)
13177 if (evtDialog == null || evtDialog.IsDisposed)
13180 evtDialog = new EventViewerDialog();
13181 evtDialog.Owner = this;
13183 Point pos = evtDialog.Location;
13184 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13185 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13186 evtDialog.Location = pos;
13188 evtDialog.EventSource = tw.StoredEvent;
13189 if (!evtDialog.Visible)
13191 evtDialog.Show(this);
13195 evtDialog.Activate();
13197 this.TopMost = this._cfgCommon.AlwaysTop;
13201 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13203 MyCommon._endingFlag = true;
13207 Application.Restart();
13211 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13215 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13217 if (!string.IsNullOrEmpty(tw.Username))
13218 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13221 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13223 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
13226 private async Task doTranslation(string str)
13228 if (string.IsNullOrEmpty(str))
13231 var bing = new Bing();
13234 var translatedText = await bing.TranslateAsync(str,
13236 langTo: this._cfgCommon.TranslateLanguage);
13238 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
13240 catch (HttpRequestException e)
13242 this.StatusLabel.Text = "Err:" + e.Message;
13246 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13248 if (!this.ExistCurrentPost)
13251 await this.doTranslation(this._curPost.TextFromApi);
13254 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13256 var text = this.PostBrowser.GetSelectedText();
13257 await this.doTranslation(text);
13260 private bool ExistCurrentPost
13264 if (_curPost == null) return false;
13265 if (_curPost.IsDeleted) return false;
13270 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13272 ShowUserTimeline();
13275 private string GetUserIdFromCurPostOrInput(string caption)
13277 var id = _curPost?.ScreenName ?? "";
13279 using (InputTabName inputName = new InputTabName())
13281 inputName.FormTitle = caption;
13282 inputName.FormDescription = Properties.Resources.FRMessage1;
13283 inputName.TabName = id;
13284 if (inputName.ShowDialog() == DialogResult.OK &&
13285 !string.IsNullOrEmpty(inputName.TabName.Trim()))
13287 id = inputName.TabName.Trim();
13297 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13299 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13300 if (!string.IsNullOrEmpty(id))
13302 AddNewTabForUserTimeline(id);
13306 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13308 string id = GetUserIdFromCurPostOrInput("Show Favstar");
13309 if (!string.IsNullOrEmpty(id))
13311 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13315 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13317 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13320 private void TimelineRefreshEnableChange(bool isEnable)
13324 tw.StartUserStream();
13328 tw.StopUserStream();
13330 TimerTimeline.Enabled = isEnable;
13333 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13335 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13338 private async Task OpenUserAppointUrl()
13340 if (this._cfgCommon.UserAppointUrl != null)
13342 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
13344 if (_curPost != null)
13346 string xUrl = this._cfgCommon.UserAppointUrl;
13347 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13349 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
13350 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
13352 await this.OpenUriInBrowserAsync(xUrl);
13357 await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
13362 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13364 await this.OpenUserAppointUrl();
13367 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13369 string selText = SourceLinkLabel.Text;
13372 Clipboard.SetDataObject(selText, false, 5, 100);
13374 catch (Exception ex)
13376 MessageBox.Show(ex.Message);
13380 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13382 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
13385 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
13387 catch (Exception ex)
13389 MessageBox.Show(ex.Message);
13393 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13395 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13397 SourceCopyMenuItem.Enabled = false;
13398 SourceUrlCopyMenuItem.Enabled = false;
13402 SourceCopyMenuItem.Enabled = true;
13403 SourceUrlCopyMenuItem.Enabled = true;
13407 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13409 if (Form.ActiveForm == null)
13411 this.BeginInvoke((Action) (() =>
13413 this.Visible = true;
13414 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13416 this.BringToFront();
13417 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13419 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13423 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13429 private void ReplaceAppName()
13431 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13432 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13435 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13437 this.SplitContainer3.Panel2Collapsed = false;
13440 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13442 await this.OpenThumbnailPicture(e.Thumbnail);
13445 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13447 await this.OpenUriInBrowserAsync(e.ImageUrl);
13450 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
13452 var url = thumbnail.FullSizeImageUrl ?? thumbnail.ImageUrl;
13454 await this.OpenUriInBrowserAsync(url);
13457 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13459 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
13462 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13464 if (e.KeyCode == Keys.Space)
13466 this.JumpUnreadMenuItem_Click(null, null);
13468 e.SuppressKeyPress = true;
13472 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13474 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13475 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13476 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13477 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13478 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13480 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13483 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13485 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13488 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13490 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13493 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13495 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13498 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13500 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13503 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13505 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13508 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13510 if (this._cfgCommon.IconSize == iconSize) return;
13512 var oldIconCol = _iconCol;
13514 this._cfgCommon.IconSize = iconSize;
13515 ApplyListViewIconSize(iconSize);
13517 if (_iconCol != oldIconCol)
13519 foreach (TabPage tp in ListTab.TabPages)
13521 ResetColumns((DetailsListView)tp.Tag);
13525 _curList?.Refresh();
13527 _modifySettingCommon = true;
13530 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13532 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13533 if (this._cfgCommon.SortOrderLock == state) return;
13535 this._cfgCommon.SortOrderLock = state;
13537 _modifySettingCommon = true;