1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
28 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
29 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
32 using System.Collections.Concurrent;
33 using System.Collections.Generic;
34 using System.ComponentModel;
35 using System.Diagnostics;
41 using System.Net.Http;
42 using System.Reflection;
44 using System.Text.RegularExpressions;
45 using System.Threading;
46 using System.Threading.Tasks;
47 using System.Windows.Forms;
49 using OpenTween.Connection;
50 using OpenTween.OpenTweenCustomControl;
51 using OpenTween.Thumbnail;
55 public partial class TweenMain : OTBaseForm
58 private Size _mySize; //画面サイズ
59 private Point _myLoc; //画面位置
60 private int _mySpDis; //区切り位置
61 private int _mySpDis2; //発言欄区切り位置
62 private int _mySpDis3; //プレビュー区切り位置
63 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
64 private bool _iconCol; //1列表示の時true(48サイズのとき)
67 private bool _initial; //true:起動時処理中
68 private bool _initialLayout = true;
69 private bool _ignoreConfigSave; //true:起動時処理中
70 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
71 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
72 private Point _tabMouseDownPoint;
73 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
74 private readonly object _syncObject = new object(); //ロック用
76 private const string detailHtmlFormatHeaderMono =
77 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
78 + "<style type=\"text/css\"><!-- "
79 + "body, p, pre {margin: 0;} "
80 + "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%);} "
81 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
82 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
83 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
84 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
86 + "</head><body><pre>";
87 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
88 private const string detailHtmlFormatHeaderColor =
89 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
90 + "<style type=\"text/css\"><!-- "
91 + "body, p, pre {margin: 0;} "
92 + "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%);} "
93 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
94 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
95 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
96 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
99 private const string detailHtmlFormatFooterColor = "</p></body></html>";
100 private string detailHtmlFormatHeader;
101 private string detailHtmlFormatFooter;
103 private bool _myStatusError = false;
104 private bool _myStatusOnline = false;
105 private bool soundfileListup = false;
106 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
109 //private SettingToConfig _cfg; //旧
110 private SettingLocal _cfgLocal;
111 private SettingCommon _cfgCommon;
114 private Twitter tw = new Twitter();
117 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
120 private SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
121 private OpenURL UrlDialog = new OpenURL();
122 public AtIdSupplement AtIdSupl; //@id補助
123 public AtIdSupplement HashSupl; //Hashtag補助
124 public HashtagManage HashMgr;
125 private EventViewerDialog evtDialog;
128 private Font _fntUnread; //未読用フォント
129 private Color _clUnread; //未読用文字色
130 private Font _fntReaded; //既読用フォント
131 private Color _clReaded; //既読用文字色
132 private Color _clFav; //Fav用文字色
133 private Color _clOWL; //片思い用文字色
134 private Color _clRetweet; //Retweet用文字色
135 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
136 private Font _fntDetail; //発言詳細部用フォント
137 private Color _clDetail; //発言詳細部用色
138 private Color _clDetailLink; //発言詳細部用リンク文字色
139 private Color _clDetailBackcolor; //発言詳細部用背景色
140 private Color _clSelf; //自分の発言用背景色
141 private Color _clAtSelf; //自分宛返信用背景色
142 private Color _clTarget; //選択発言者の他の発言用背景色
143 private Color _clAtTarget; //選択発言中の返信先用背景色
144 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
145 private Color _clAtTo; //選択発言の唯一@先
146 private Color _clListBackcolor; //リスト部通常発言背景色
147 private Color _clInputBackcolor; //入力欄背景色
148 private Color _clInputFont; //入力欄文字色
149 private Font _fntInputFont; //入力欄フォント
150 private ImageCache IconCache; //アイコン画像リスト
151 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
152 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
153 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
154 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
155 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
156 private Icon MainIcon; //Main.ico 画面左上のアイコン
157 private Icon ReplyIcon; //5g
158 private Icon ReplyIconBlink; //6g
160 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
162 private PostClass _anchorPost;
163 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
165 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
166 private int _hisIdx; //発言履歴カレントインデックス
168 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
169 private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
172 private List<DateTime> _postTimestamps = new List<DateTime>();
173 private List<DateTime> _favTimestamps = new List<DateTime>();
174 private ConcurrentDictionary<DateTime, int> _tlTimestamps = new ConcurrentDictionary<DateTime, int>();
175 private int _tlCount;
178 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
179 private SolidBrush _brsBackColorMine;
180 private SolidBrush _brsBackColorAt;
181 private SolidBrush _brsBackColorYou;
182 private SolidBrush _brsBackColorAtYou;
183 private SolidBrush _brsBackColorAtFromTarget;
184 private SolidBrush _brsBackColorAtTo;
185 private SolidBrush _brsBackColorNone;
186 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
187 private StringFormat sfTab = new StringFormat();
189 //////////////////////////////////////////////////////////////////////////////////////////////////////////
190 private TabInformations _statuses;
193 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
196 /// キャッシュクリアのために null が代入されることがあるため、
197 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
198 /// 一旦ローカル変数に代入してから参照すること。
200 private ListViewItemCache _listItemCache = null;
202 internal class ListViewItemCache
204 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
205 public ListView TargetList { get; set; }
207 /// <summary>キャッシュする範囲の開始インデックス</summary>
208 public int StartIndex { get; set; }
210 /// <summary>キャッシュする範囲の終了インデックス</summary>
211 public int EndIndex { get; set; }
213 /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
214 public ListViewItem[] ListItem { get; set; }
216 /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
217 public PostClass[] Post { get; set; }
219 /// <summary>キャッシュされたアイテムの件数</summary>
221 => this.EndIndex - this.StartIndex + 1;
223 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
224 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
225 public bool Contains(int index)
226 => index >= this.StartIndex && index <= this.EndIndex;
228 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
229 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
230 public bool IsSupersetOf(int rangeStart, int rangeEnd)
231 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
233 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
234 /// <returns>取得に成功すれば true、それ以外は false</returns>
235 public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
237 if (this.Contains(index))
239 item = this.ListItem[index - this.StartIndex];
240 post = this.Post[index - this.StartIndex];
252 private TabPage _curTab;
253 private int _curItemIndex;
254 private DetailsListView _curList;
255 private PostClass _curPost;
256 private bool _isColumnChanged = false;
258 private const int MAX_WORKER_THREADS = 20;
259 private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
260 private CancellationTokenSource workerCts = new CancellationTokenSource();
262 private int UnreadCounter = -1;
263 private int UnreadAtCounter = -1;
265 private string[] ColumnOrgText = new string[9];
266 private string[] ColumnText = new string[9];
268 private bool _DoFavRetweetFlags = false;
269 private bool osResumed = false;
271 //////////////////////////////////////////////////////////////////////////////////////////////////////////
272 private string _postBrowserStatusText = "";
274 private bool _colorize = false;
276 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
278 private ImageListViewItem displayItem;
280 private string recommendedStatusFooter;
283 private struct urlUndo
285 public string Before;
289 private List<urlUndo> urlUndoBuffer = null;
291 private struct ReplyChain
293 public long OriginalId;
294 public long InReplyToId;
295 public TabPage OriginalTab;
297 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
299 this.OriginalId = originalId;
300 this.InReplyToId = inReplyToId;
301 this.OriginalTab = originalTab;
305 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
306 private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
309 private enum SEARCHTYPE
316 private class PostingStatus
318 public string status = "";
319 public long? inReplyToId = null;
320 public string inReplyToName = null;
321 public string imageService = ""; //画像投稿サービス名
322 public IMediaItem[] mediaItems = null;
323 public PostingStatus()
326 public PostingStatus(string status, long? replyToId, string replyToName)
328 this.status = status;
329 this.inReplyToId = replyToId;
330 this.inReplyToName = replyToName;
334 private void TweenMain_Activated(object sender, EventArgs e)
336 //画面がアクティブになったら、発言欄の背景色戻す
337 if (StatusText.Focused)
339 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
343 private bool disposed = false;
346 /// 使用中のリソースをすべてクリーンアップします。
348 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
349 protected override void Dispose(bool disposing)
351 base.Dispose(disposing);
358 this.components?.Dispose();
361 SearchDialog.Dispose();
364 NIconAtRed?.Dispose();
365 NIconAtSmoke?.Dispose();
366 foreach (var iconRefresh in this.NIconRefresh)
368 iconRefresh?.Dispose();
372 ReplyIcon?.Dispose();
373 ReplyIconBlink?.Dispose();
374 _listViewImageList.Dispose();
375 _brsHighLight.Dispose();
376 _brsBackColorMine?.Dispose();
377 _brsBackColorAt?.Dispose();
378 _brsBackColorYou?.Dispose();
379 _brsBackColorAtYou?.Dispose();
380 _brsBackColorAtFromTarget?.Dispose();
381 _brsBackColorAtTo?.Dispose();
382 _brsBackColorNone?.Dispose();
383 _brsDeactiveSelection?.Dispose();
387 this.workerCts.Cancel();
389 if (IconCache != null)
391 this.IconCache.CancelAsync();
392 this.IconCache.Dispose();
395 this.thumbnailTokenSource?.Dispose();
398 this._hookGlobalHotkey.Dispose();
401 // 終了時にRemoveHandlerしておかないとメモリリークする
402 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
403 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
405 this.disposed = true;
408 private void LoadIcons()
410 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
411 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
414 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
417 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
420 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
423 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
425 // タスクトレイ: オフライン時アイコン
426 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
428 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
429 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
430 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
432 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
433 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
434 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
435 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
436 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
438 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
440 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
441 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
442 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
443 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
444 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
446 if (iconReply != null && iconReplyBlink != null)
448 this.ReplyIcon = iconReply;
449 this.ReplyIconBlink = iconReplyBlink;
453 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
454 this.ReplyIconBlink = this.NIconAt;
457 if (iconRefresh1 == null)
459 this.NIconRefresh = new[] {
460 Properties.Resources.Refresh, Properties.Resources.Refresh2,
461 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
464 else if (iconRefresh2 == null)
466 this.NIconRefresh = new[] { iconRefresh1 };
468 else if (iconRefresh3 == null)
470 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
472 else if (iconRefresh4 == null)
474 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
476 else // iconRefresh1 から iconRefresh4 まで全て揃っている
478 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
482 private Icon LoadIcon(string filePath)
484 if (!File.Exists(filePath))
489 return new Icon(filePath);
497 private void InitColumns(ListView list, bool startup)
499 this.InitColumnText();
501 ColumnHeader[] columns;
506 new ColumnHeader { Text = this.ColumnText[0], Width = 48 }, // アイコン
507 new ColumnHeader { Text = this.ColumnText[2], Width = 300 }, // 本文
512 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
514 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
515 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
516 columns[0].DisplayIndex = 0;
517 columns[1].DisplayIndex = 1;
522 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
524 columns[idx].Width = curListColumn.Width;
525 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
534 new ColumnHeader { Text = this.ColumnText[0], Width = 48 }, // アイコン
535 new ColumnHeader { Text = this.ColumnText[1], Width = 80 }, // ニックネーム
536 new ColumnHeader { Text = this.ColumnText[2], Width = 300 }, // 本文
537 new ColumnHeader { Text = this.ColumnText[3], Width = 50 }, // 日付
538 new ColumnHeader { Text = this.ColumnText[4], Width = 50 }, // ユーザID
539 new ColumnHeader { Text = this.ColumnText[5], Width = 16 }, // 未読
540 new ColumnHeader { Text = this.ColumnText[6], Width = 16 }, // マーク&プロテクト
541 new ColumnHeader { Text = this.ColumnText[7], Width = 50 }, // ソース
546 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
548 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
549 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
550 columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
551 columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
552 columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
553 columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
554 columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
555 columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
557 var displayIndex = new[] {
558 this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
559 this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
560 this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
561 this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
564 foreach (var i in Enumerable.Range(0, displayIndex.Length))
566 columns[i].DisplayIndex = displayIndex[i];
572 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
574 columns[idx].Width = curListColumn.Width;
575 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
581 list.Columns.AddRange(columns);
584 private void InitColumnText()
587 ColumnText[1] = Properties.Resources.AddNewTabText2;
588 ColumnText[2] = Properties.Resources.AddNewTabText3;
589 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
590 ColumnText[4] = Properties.Resources.AddNewTabText5;
593 ColumnText[7] = "Source";
595 ColumnOrgText[0] = "";
596 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
597 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
598 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
599 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
600 ColumnOrgText[5] = "";
601 ColumnOrgText[6] = "";
602 ColumnOrgText[7] = "Source";
605 switch (_statuses.SortMode)
607 case ComparerMode.Nickname: //ニックネーム
610 case ComparerMode.Data: //本文
613 case ComparerMode.Id: //時刻=発言Id
616 case ComparerMode.Name: //名前
619 case ComparerMode.Source: //Source
626 if (_statuses.SortOrder == SortOrder.Descending)
628 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
629 ColumnText[2] = ColumnOrgText[2] + "▾";
633 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
634 ColumnText[2] = ColumnOrgText[2] + "▴";
639 if (_statuses.SortOrder == SortOrder.Descending)
641 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
642 ColumnText[c] = ColumnOrgText[c] + "▾";
646 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
647 ColumnText[c] = ColumnOrgText[c] + "▴";
652 private void InitializeTraceFrag()
655 TraceOutToolStripMenuItem.Checked = true;
656 MyCommon.TraceFlag = true;
658 if (!MyCommon.FileVersion.EndsWith("0"))
660 TraceOutToolStripMenuItem.Checked = true;
661 MyCommon.TraceFlag = true;
665 private void TweenMain_Load(object sender, EventArgs e)
667 _ignoreConfigSave = true;
668 this.Visible = false;
670 if (MyApplication.StartupOptions.ContainsKey("d"))
671 MyCommon.TraceFlag = true;
673 InitializeTraceFrag();
675 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
677 new InternetSecurityManager(PostBrowser);
678 this.PostBrowser.AllowWebBrowserDrop = false; // COMException を回避するため、ActiveX の初期化が終わってから設定する
680 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
681 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
683 Regex.CacheSize = 100;
686 _statuses = TabInformations.GetInstance();
690 this.Icon = MainIcon; //メインフォーム(TweenMain)
691 NotifyIcon1.Icon = NIconAt; //タスクトレイ
692 TabImage.Images.Add(TabIcon); //タブ見出し
694 //<<<<<<<<<設定関連>>>>>>>>>
698 // 現在の DPI と設定保存時の DPI との比を取得する
699 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
702 var fontUIGlobal = this._cfgLocal.FontUIGlobal;
703 if (fontUIGlobal != null)
705 OTBaseForm.GlobalFont = fontUIGlobal;
706 this.Font = fontUIGlobal;
710 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
712 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
713 this._cfgCommon.TimelinePeriod = 15;
715 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
716 this._cfgCommon.ReplyPeriod = 15;
718 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
719 this._cfgCommon.DMPeriod = 15;
721 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
722 this._cfgCommon.PubSearchPeriod = 30;
724 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
725 this._cfgCommon.UserTimelinePeriod = 15;
727 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
728 this._cfgCommon.ListsPeriod = 15;
731 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
732 this._cfgCommon.CountApi = 60;
733 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
734 this._cfgCommon.CountApiReply = 40;
736 if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
737 this._cfgCommon.MoreCountApi = 200;
738 if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
739 this._cfgCommon.FirstCountApi = 100;
741 if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
742 this._cfgCommon.FavoritesCountApi = 40;
743 if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
744 this._cfgCommon.ListCountApi = 100;
745 if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
746 this._cfgCommon.SearchCountApi = 100;
747 if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
748 this._cfgCommon.UserTimelineCountApi = 20;
750 //廃止サービスが選択されていた場合ux.nuへ読み替え
751 if (this._cfgCommon.AutoShortUrlFirst < 0)
752 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
754 HttpTwitter.TwitterUrl = this._cfgCommon.TwitterUrl;
757 if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
758 tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
762 Networking.Initialize();
764 bool saveRequired = false;
765 bool firstRun = false;
767 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
768 if (string.IsNullOrEmpty(tw.Username))
773 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
774 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
775 string.IsNullOrEmpty(tw.Username))
777 Application.Exit(); //強制終了
783 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
784 Networking.SetWebProxy(this._cfgLocal.ProxyType,
785 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
786 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
787 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
789 HttpTwitter.TwitterUrl = this._cfgCommon.TwitterUrl;
790 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
791 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
792 tw.TrackWord = this._cfgCommon.TrackWord;
793 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
794 tw.AllAtReply = this._cfgCommon.AllAtReply;
795 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
796 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
797 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
798 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
800 // アクセストークンが有効であるか確認する
801 // ここが Twitter API への最初のアクセスになるようにすること
804 this.tw.VerifyCredentials();
806 catch (WebApiException ex)
808 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
809 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
813 //プロキシ設定等の通信まわりの初期化が済んでから処理する
814 ThumbnailGenerator.InitializeGenerator();
816 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
817 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
818 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
820 Thumbnail.Services.TonTwitterCom.InitializeOAuthToken = x =>
821 x.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
822 this.tw.AccessToken, this.tw.AccessTokenSecret, "", "");
825 ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
828 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
829 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
830 HashMgr = new HashtagManage(HashSupl,
831 _cfgCommon.HashTags.ToArray(),
832 _cfgCommon.HashSelected,
833 _cfgCommon.HashIsPermanent,
834 _cfgCommon.HashIsHead,
835 _cfgCommon.HashIsNotAddToAtReply);
836 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
839 this.IconCache = new ImageCache();
842 _fntUnread = this._cfgLocal.FontUnread;
843 _clUnread = this._cfgLocal.ColorUnread;
844 _fntReaded = this._cfgLocal.FontRead;
845 _clReaded = this._cfgLocal.ColorRead;
846 _clFav = this._cfgLocal.ColorFav;
847 _clOWL = this._cfgLocal.ColorOWL;
848 _clRetweet = this._cfgLocal.ColorRetweet;
849 _fntDetail = this._cfgLocal.FontDetail;
850 _clDetail = this._cfgLocal.ColorDetail;
851 _clDetailLink = this._cfgLocal.ColorDetailLink;
852 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
853 _clSelf = this._cfgLocal.ColorSelf;
854 _clAtSelf = this._cfgLocal.ColorAtSelf;
855 _clTarget = this._cfgLocal.ColorTarget;
856 _clAtTarget = this._cfgLocal.ColorAtTarget;
857 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
858 _clAtTo = this._cfgLocal.ColorAtTo;
859 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
860 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
861 _clInputFont = this._cfgLocal.ColorInputFont;
862 _fntInputFont = this._cfgLocal.FontInputFont;
864 _brsBackColorMine = new SolidBrush(_clSelf);
865 _brsBackColorAt = new SolidBrush(_clAtSelf);
866 _brsBackColorYou = new SolidBrush(_clTarget);
867 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
868 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
869 _brsBackColorAtTo = new SolidBrush(_clAtTo);
870 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
871 _brsBackColorNone = new SolidBrush(_clListBackcolor);
873 // StringFormatオブジェクトへの事前設定
874 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
875 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
876 //sf.FormatFlags = StringFormatFlags.LineLimit; //
877 sfTab.Alignment = StringAlignment.Center;
878 sfTab.LineAlignment = StringAlignment.Center;
880 InitDetailHtmlFormat();
882 //Regex statregex = new Regex("^0*");
883 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
885 _history.Add(new PostingStatus());
887 this.inReplyTo = null;
890 SearchDialog.Owner = this;
891 UrlDialog.Owner = this;
894 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
895 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
897 //新着取得時のリストスクロールをするか。trueならスクロールしない
898 ListLockMenuItem.Checked = _cfgCommon.ListLock;
899 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
901 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
902 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
904 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
905 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
908 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
909 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
910 _myLoc = _cfgLocal.FormLocation;
912 if (this.WindowState != FormWindowState.Minimized)
914 this.DesktopLocation = _cfgLocal.FormLocation;
915 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
916 bool outOfScreen = true;
917 if (Screen.AllScreens.Length == 1) //ハングするとの報告
919 foreach (Screen scr in Screen.AllScreens)
921 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
929 this.DesktopLocation = new Point(0, 0);
930 _myLoc = this.DesktopLocation;
934 this.TopMost = this._cfgCommon.AlwaysTop;
935 _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
936 _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
937 if (_cfgLocal.PreviewDistance == -1)
939 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
940 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
941 _cfgLocal.PreviewDistance = _mySpDis3;
945 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
947 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
948 //this.Tween_ClientSizeChanged(this, null);
949 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
950 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
952 StatusText.Font = _fntInputFont;
953 StatusText.ForeColor = _clInputFont;
955 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
956 this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
957 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
959 // NameLabel のフォントを OTBaseForm.GlobalFont に変更
960 this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
962 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
963 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
965 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
966 if (this._cfgCommon.UnreadManage == false)
968 ReadedStripMenuItem.Enabled = false;
969 UnreadStripMenuItem.Enabled = false;
974 DateTimeLabel.Text = "";
975 SourceLinkLabel.Text = "";
977 //リンク先URL表示部の初期化(画面左下)
978 StatusLabelUrl.Text = "";
980 StatusLabel.Text = "";
981 StatusLabel.AutoToolTip = false;
982 StatusLabel.ToolTipText = "";
984 lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
986 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
987 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
988 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
989 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
991 ////////////////////////////////////////////////////////////////////////////////
992 var sortOrder = (SortOrder)_cfgCommon.SortOrder;
993 var mode = ComparerMode.Id;
994 switch (_cfgCommon.SortColumn)
996 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1000 mode = ComparerMode.Id; //Idソートに読み替え
1003 mode = ComparerMode.Nickname;
1006 mode = ComparerMode.Data;
1009 mode = ComparerMode.Id;
1012 mode = ComparerMode.Name;
1015 mode = ComparerMode.Source;
1018 _statuses.SetSortMode(mode, sortOrder);
1019 ////////////////////////////////////////////////////////////////////////////////
1021 ApplyListViewIconSize(this._cfgCommon.IconSize);
1023 //<<<<<<<<タブ関連>>>>>>>
1027 //デフォルトタブの存在チェック、ない場合には追加
1028 if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1031 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1033 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1037 tab.TabType = MyCommon.TabUsageType.Home;
1040 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1043 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1045 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1049 tab.TabType = MyCommon.TabUsageType.Mentions;
1052 if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1055 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1057 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1061 tab.TabType = MyCommon.TabUsageType.DirectMessage;
1064 if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1067 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1069 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1073 tab.TabType = MyCommon.TabUsageType.Favorites;
1076 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mute) == null)
1079 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.MUTE, out tab))
1081 _statuses.AddTab(MyCommon.DEFAULTTAB.MUTE, MyCommon.TabUsageType.Mute, null);
1085 tab.TabType = MyCommon.TabUsageType.Mute;
1089 foreach (var tab in _statuses.Tabs.Values)
1092 if (tab.TabType == MyCommon.TabUsageType.Mute)
1095 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1097 tab.TabType = MyCommon.TabUsageType.UserDefined;
1099 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo))
1100 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1103 _curTab = ListTab.SelectedTab;
1105 _curList = (DetailsListView)_curTab.Tag;
1107 if (this._cfgCommon.TabIconDisp)
1109 ListTab.DrawMode = TabDrawMode.Normal;
1113 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1114 ListTab.DrawItem += ListTab_DrawItem;
1115 ListTab.ImageList = null;
1118 if (this._cfgCommon.HotkeyEnabled)
1121 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1122 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1123 modKey |= HookGlobalHotkey.ModKeys.Alt;
1124 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1125 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1126 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1127 modKey |= HookGlobalHotkey.ModKeys.Shift;
1128 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1129 modKey |= HookGlobalHotkey.ModKeys.Win;
1131 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1134 if (this._cfgCommon.IsUseNotifyGrowl)
1137 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1139 SetMainWindowTitle();
1140 SetNotifyIconText();
1142 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1144 this.Visible = true;
1148 TimerTimeline.AutoReset = true;
1149 TimerTimeline.SynchronizingObject = this;
1151 TimerTimeline.Interval = 1000;
1152 TimerTimeline.Enabled = true;
1154 TimerRefreshIcon.Interval = 200;
1155 TimerRefreshIcon.Enabled = true;
1157 _ignoreConfigSave = false;
1158 this.TweenMain_Resize(null, null);
1159 if (saveRequired) SaveConfigsAll(false);
1161 foreach (var ua in this._cfgCommon.UserAccounts)
1163 if (ua.UserId == 0 && ua.Username.ToLower() == tw.Username.ToLower())
1165 ua.UserId = tw.UserId;
1172 // 初回起動時だけ右下のメニューを目立たせる
1173 HashStripSplitButton.ShowDropDown();
1177 private void InitDetailHtmlFormat()
1179 if (this._cfgCommon.IsMonospace)
1181 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1182 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1186 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1187 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1190 detailHtmlFormatHeader = detailHtmlFormatHeader
1191 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1192 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1193 .Replace("%FONT_COLOR%", _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString())
1194 .Replace("%LINK_COLOR%", _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString())
1195 .Replace("%BG_COLOR%", _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString());
1198 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1203 txt = ListTab.TabPages[e.Index].Text;
1210 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1211 if (e.State == DrawItemState.Selected)
1213 e.DrawFocusRectangle();
1218 if (_statuses.Tabs[txt].UnreadCount > 0)
1221 fore = System.Drawing.SystemBrushes.ControlText;
1225 fore = System.Drawing.SystemBrushes.ControlText;
1227 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1230 private void LoadConfig()
1232 _cfgCommon = SettingCommon.Load();
1233 SettingCommon.Instance = this._cfgCommon;
1234 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1236 _cfgCommon.UserAccounts = new List<UserAccount>();
1237 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1239 UserAccount account = new UserAccount();
1240 account.Username = _cfgCommon.UserName;
1241 account.UserId = _cfgCommon.UserId;
1242 account.Token = _cfgCommon.Token;
1243 account.TokenSecret = _cfgCommon.TokenSecret;
1245 _cfgCommon.UserAccounts.Add(account);
1249 _cfgLocal = SettingLocal.Load();
1251 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1252 if (_cfgLocal.ScaleDimension.IsEmpty)
1253 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1255 List<TabClass> tabs = SettingTabs.Load().Tabs;
1256 foreach (TabClass tb in tabs)
1260 tb.FilterModified = false;
1261 _statuses.Tabs.Add(tb.TabName, tb);
1265 tb.TabName = _statuses.MakeTabName("MyTab");
1266 _statuses.Tabs.Add(tb.TabName, tb);
1269 if (_statuses.Tabs.Count == 0)
1271 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1272 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1273 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1274 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1278 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1280 if (!TimerTimeline.Enabled) return;
1284 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1286 private static int homeCounter = 0;
1287 private static int mentionCounter = 0;
1288 private static int dmCounter = 0;
1289 private static int pubSearchCounter = 0;
1290 private static int userTimelineCounter = 0;
1291 private static int listsCounter = 0;
1292 private static int usCounter = 0;
1293 private static int ResumeWait = 0;
1294 private static int refreshFollowers = 0;
1296 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1298 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1299 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1300 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1301 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1302 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1303 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1304 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1305 Interlocked.Increment(ref refreshFollowers);
1307 var refreshTasks = new List<Task>();
1310 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1312 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1313 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1314 refreshTasks.Add(this.GetHomeTimelineAsync());
1315 ResetTimers.Timeline = false;
1317 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1319 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1320 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1321 refreshTasks.Add(this.GetReplyAsync());
1322 ResetTimers.Reply = false;
1324 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1326 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1327 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1328 refreshTasks.Add(this.GetDirectMessagesAsync());
1329 ResetTimers.DirectMessage = false;
1331 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1333 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1334 if (!ResetTimers.PublicSearch)
1335 refreshTasks.Add(this.GetPublicSearchAllAsync());
1336 ResetTimers.PublicSearch = false;
1338 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1340 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1341 if (!ResetTimers.UserTimeline)
1342 refreshTasks.Add(this.GetUserTimelineAllAsync());
1343 ResetTimers.UserTimeline = false;
1345 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1347 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1348 if (!ResetTimers.Lists)
1349 refreshTasks.Add(this.GetListTimelineAllAsync());
1350 ResetTimers.Lists = false;
1352 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1354 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1355 if (this._isActiveUserstream)
1356 this.RefreshTimeline();
1357 ResetTimers.UserStream = false;
1359 if (refreshFollowers > 6 * 3600)
1361 Interlocked.Exchange(ref refreshFollowers, 0);
1362 refreshTasks.AddRange(new[]
1364 this.doGetFollowersMenu(),
1365 this.RefreshNoRetweetIdsAsync(),
1366 this.RefreshTwitterConfigurationAsync(),
1371 Interlocked.Increment(ref ResumeWait);
1372 if (ResumeWait > 30)
1375 Interlocked.Exchange(ref ResumeWait, 0);
1376 refreshTasks.AddRange(new[]
1378 this.GetHomeTimelineAsync(),
1379 this.GetReplyAsync(),
1380 this.GetDirectMessagesAsync(),
1381 this.GetPublicSearchAllAsync(),
1382 this.GetUserTimelineAllAsync(),
1383 this.GetListTimelineAllAsync(),
1384 this.doGetFollowersMenu(),
1385 this.RefreshTwitterConfigurationAsync(),
1390 await Task.WhenAll(refreshTasks);
1393 private void RefreshTimeline()
1395 // 現在表示中のタブのスクロール位置を退避
1396 var curListScroll = this.SaveListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text]);
1398 // 各タブのリスト上の選択位置などを退避
1399 var listSelections = this.SaveListViewSelection();
1402 PostClass[] notifyPosts;
1405 bool newMentionOrDm;
1407 addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1409 if (MyCommon._endingFlag) return;
1414 foreach (TabPage tab in ListTab.TabPages)
1416 DetailsListView lst = (DetailsListView)tab.Tag;
1417 TabClass tabInfo = _statuses.Tabs[tab.Text];
1418 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1420 using (ControlTransaction.Update(lst))
1422 if (lst.Equals(_curList))
1424 this.PurgeListViewItemCache();
1428 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1436 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
1439 if (tabInfo.UnreadCount > 0)
1440 if (this._cfgCommon.TabIconDisp)
1441 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1443 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1447 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1452 this.RestoreListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text], curListScroll);
1455 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1457 SetMainWindowTitle();
1458 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
1460 HashSupl.AddRangeItem(tw.GetHashList());
1464 internal struct ListViewScroll
1466 public ScrollLockMode ScrollLockMode { get; set; }
1467 public long? TopItemStatusId { get; set; }
1470 internal enum ScrollLockMode
1472 /// <summary>固定しない</summary>
1475 /// <summary>最上部に固定する</summary>
1478 /// <summary>最下部に固定する</summary>
1481 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1486 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1488 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabClass tab)
1490 var listScroll = new ListViewScroll
1492 ScrollLockMode = this.GetScrollLockMode(listView),
1495 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1497 var topItem = listView.TopItem;
1498 if (topItem != null)
1499 listScroll.TopItemStatusId = tab.GetId(topItem.Index);
1505 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1507 if (this._statuses.SortMode == ComparerMode.Id)
1509 if (this._statuses.SortOrder == SortOrder.Ascending)
1512 if (this.ListLockMenuItem.Checked)
1513 return ScrollLockMode.None;
1515 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1518 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1519 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1520 return ScrollLockMode.FixedToBottom;
1522 return ScrollLockMode.None;
1527 if (this.ListLockMenuItem.Checked)
1528 return ScrollLockMode.FixedToItem;
1530 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1531 var topItem = listView.TopItem;
1532 if (topItem == null || topItem.Index == 0)
1533 return ScrollLockMode.FixedToTop;
1535 return ScrollLockMode.FixedToItem;
1540 return ScrollLockMode.FixedToItem;
1544 internal struct ListViewSelection
1546 public long[] SelectedStatusIds { get; set; }
1547 public long? SelectionMarkStatusId { get; set; }
1548 public long? FocusedStatusId { get; set; }
1552 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1554 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1556 var listsDict = new Dictionary<string, ListViewSelection>();
1558 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1560 var listView = (DetailsListView)tabPage.Tag;
1561 var tab = _statuses.Tabs[tabPage.Text];
1563 ListViewSelection listStatus;
1564 if (listView.VirtualListSize != 0)
1566 listStatus = new ListViewSelection
1568 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1569 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1570 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1575 listStatus = new ListViewSelection
1577 SelectedStatusIds = new long[0],
1578 SelectionMarkStatusId = null,
1579 FocusedStatusId = null,
1583 listsDict[tab.TabName] = listStatus;
1589 private long[] GetSelectedStatusIds(DetailsListView listView, TabClass tab)
1591 var selectedIndices = listView.SelectedIndices;
1592 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1593 return tab.GetId(selectedIndices);
1598 private long? GetFocusedStatusId(DetailsListView listView, TabClass tab)
1600 var focusedItem = listView.FocusedItem;
1602 return focusedItem != null ? tab.GetId(focusedItem.Index) : (long?)null;
1605 private long? GetSelectionMarkStatusId(DetailsListView listView, TabClass tab)
1607 var selectionMarkIndex = listView.SelectionMark;
1609 return selectionMarkIndex != -1 ? tab.GetId(selectionMarkIndex) : (long?)null;
1613 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1615 private void RestoreListViewScroll(DetailsListView listView, TabClass tab, ListViewScroll listScroll)
1617 if (listView.VirtualListSize == 0)
1620 switch (listScroll.ScrollLockMode)
1622 case ScrollLockMode.FixedToTop:
1623 listView.EnsureVisible(0);
1625 case ScrollLockMode.FixedToBottom:
1626 listView.EnsureVisible(listView.VirtualListSize - 1);
1628 case ScrollLockMode.FixedToItem:
1629 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1631 listView.TopItem = listView.Items[topIndex];
1633 case ScrollLockMode.None:
1640 /// <see cref="SaveListViewStatus"/> によって保存された選択状態を復元します
1642 private void RestoreListViewSelection(DetailsListView listView, TabClass tab, ListViewSelection listSelection)
1644 // status_id から ListView 上のインデックスに変換
1645 int[] selectedIndices = null;
1646 if (listSelection.SelectedStatusIds != null)
1647 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1649 var focusedIndex = -1;
1650 if (listSelection.FocusedStatusId != null)
1651 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1653 var selectionMarkIndex = -1;
1654 if (listSelection.SelectionMarkStatusId != null)
1655 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1657 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1660 private bool BalloonRequired()
1662 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1663 ev.Eventtype = MyCommon.EVENTTYPE.None;
1665 return BalloonRequired(ev);
1668 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1670 if (type == MyCommon.EVENTTYPE.None)
1673 if (!this._cfgCommon.EventNotifyEnabled)
1676 return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1679 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1684 return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1687 private bool BalloonRequired(Twitter.FormattedEvent ev)
1692 if (NativeMethods.IsScreenSaverRunning())
1696 if (!this.NewPostPopMenuItem.Checked)
1698 // 「新着通知が無効でもイベントを通知する」にも該当しない
1699 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1703 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1704 if (this._cfgCommon.LimitBalloon)
1706 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1710 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1713 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1715 if (this._cfgCommon.ReadOwnPost)
1717 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1722 if (BalloonRequired())
1724 if (notifyPosts != null && notifyPosts.Length > 0)
1726 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1727 if (this._cfgCommon.IsUseNotifyGrowl)
1729 StringBuilder sb = new StringBuilder();
1733 foreach (PostClass post in notifyPosts)
1735 if (!(notifyPosts.Length > 3))
1741 if (post.IsReply && !post.IsExcludeReply) reply = true;
1742 if (post.IsDm) dm = true;
1743 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1744 switch (this._cfgCommon.NameBalloon)
1746 case MyCommon.NameBalloonEnum.UserID:
1747 sb.Append(post.ScreenName).Append(" : ");
1749 case MyCommon.NameBalloonEnum.NickName:
1750 sb.Append(post.Nickname).Append(" : ");
1753 sb.Append(post.TextFromApi);
1754 if (notifyPosts.Length > 3)
1756 if (notifyPosts.Last() != post) continue;
1759 StringBuilder title = new StringBuilder();
1760 GrowlHelper.NotifyType nt;
1761 if (this._cfgCommon.DispUsername)
1763 title.Append(tw.Username);
1764 title.Append(" - ");
1772 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1773 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1774 title.Append(Application.ProductName);
1775 title.Append(" [DM] ");
1776 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1777 nt = GrowlHelper.NotifyType.DirectMessage;
1781 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1782 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1783 title.Append(Application.ProductName);
1784 title.Append(" [Reply!] ");
1785 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1786 nt = GrowlHelper.NotifyType.Reply;
1790 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1791 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1792 title.Append(Application.ProductName);
1794 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1795 nt = GrowlHelper.NotifyType.Notify;
1797 string bText = sb.ToString();
1798 if (string.IsNullOrEmpty(bText)) return;
1800 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1801 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1806 StringBuilder sb = new StringBuilder();
1809 foreach (PostClass post in notifyPosts)
1811 if (post.IsReply && !post.IsExcludeReply) reply = true;
1812 if (post.IsDm) dm = true;
1813 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1814 switch (this._cfgCommon.NameBalloon)
1816 case MyCommon.NameBalloonEnum.UserID:
1817 sb.Append(post.ScreenName).Append(" : ");
1819 case MyCommon.NameBalloonEnum.NickName:
1820 sb.Append(post.Nickname).Append(" : ");
1823 sb.Append(post.TextFromApi);
1826 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1827 StringBuilder title = new StringBuilder();
1829 if (this._cfgCommon.DispUsername)
1831 title.Append(tw.Username);
1832 title.Append(" - ");
1840 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1841 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1842 ntIcon = ToolTipIcon.Warning;
1843 title.Append(Application.ProductName);
1844 title.Append(" [DM] ");
1845 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1849 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1850 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1851 ntIcon = ToolTipIcon.Warning;
1852 title.Append(Application.ProductName);
1853 title.Append(" [Reply!] ");
1854 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1858 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1859 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1860 ntIcon = ToolTipIcon.Info;
1861 title.Append(Application.ProductName);
1863 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1865 string bText = sb.ToString();
1866 if (string.IsNullOrEmpty(bText)) return;
1867 //NotifyIcon1.BalloonTipText = sb.ToString();
1868 //NotifyIcon1.ShowBalloonTip(500);
1869 NotifyIcon1.BalloonTipTitle = title.ToString();
1870 NotifyIcon1.BalloonTipText = bText;
1871 NotifyIcon1.BalloonTipIcon = ntIcon;
1872 NotifyIcon1.ShowBalloonTip(500);
1878 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1882 string dir = Application.StartupPath;
1883 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1885 dir = Path.Combine(dir, "Sounds");
1887 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1897 //mentions新着時に画面ブリンク
1898 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1900 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1904 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1906 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1908 _curItemIndex = _curList.SelectedIndices[0];
1909 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1911 PostClass selectedPost;
1914 selectedPost = GetCurTabPost(_curItemIndex);
1916 catch (ArgumentException)
1921 if (selectedPost.StatusId == this._curPost?.StatusId)
1924 this._curPost = selectedPost;
1926 this.PushSelectPostChain();
1928 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1930 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1936 private void ChangeCacheStyleRead(bool Read, int Index)
1938 var tabInfo = _statuses.Tabs[_curTab.Text];
1939 //Read:true=既読 false=未読
1940 //未読管理していなかったら既読として扱う
1941 if (!tabInfo.UnreadManage ||
1942 !this._cfgCommon.UnreadManage) Read = true;
1944 var listCache = this._listItemCache;
1945 if (listCache == null)
1948 // キャッシュに含まれていないアイテムは対象外
1951 if (!listCache.TryGetValue(Index, out itm, out post))
1954 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1957 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1964 Item.SubItems[5].Text = "";
1969 Item.SubItems[5].Text = "★";
1975 else if (Post.RetweetedId != null)
1977 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1979 else if (Read || !this._cfgCommon.UseUnreadStyle)
1984 if (DList == null || Item.Index == -1)
1986 Item.ForeColor = cl;
1987 if (this._cfgCommon.UseUnreadStyle)
1993 if (this._cfgCommon.UseUnreadStyle)
1994 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1996 DList.ChangeItemForeColor(Item.Index, cl);
1997 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2001 private void ColorizeList()
2003 //Index:更新対象のListviewItem.Index。Colorを返す。
2004 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2007 _post = _anchorPost;
2011 if (_post == null) return;
2013 var listCache = this._listItemCache;
2014 if (listCache == null)
2017 var index = listCache.StartIndex;
2018 foreach (var cachedPost in listCache.Post)
2020 var backColor = this.JudgeColor(_post, cachedPost);
2021 this._curList.ChangeItemBackColor(index++, backColor);
2025 private void ColorizeList(ListViewItem Item, int Index)
2027 //Index:更新対象のListviewItem.Index。Colorを返す。
2028 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2031 _post = _anchorPost;
2035 PostClass tPost = GetCurTabPost(Index);
2037 if (_post == null) return;
2039 if (Item.Index == -1)
2040 Item.BackColor = JudgeColor(_post, tPost);
2042 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2045 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2048 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2051 else if (TargetPost.IsMe)
2054 else if (TargetPost.IsReply)
2057 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLower()))
2059 cl = _clAtFromTarget;
2060 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLower()))
2063 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2068 cl = _clListBackcolor;
2073 private async void PostButton_Click(object sender, EventArgs e)
2075 if (StatusText.Text.Trim().Length == 0)
2077 if (!ImageSelector.Enabled)
2079 await this.DoRefresh();
2084 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2086 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2088 MessageBoxButtons.YesNoCancel,
2089 MessageBoxIcon.Question);
2092 case DialogResult.Yes:
2093 StatusText.Text = "";
2094 await this.doReTweetOfficial(false);
2096 case DialogResult.Cancel:
2101 var inReplyToStatusId = this.inReplyTo?.Item1;
2102 var inReplyToScreenName = this.inReplyTo?.Item2;
2103 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2105 if (this._cfgCommon.Nicoms)
2107 StatusText.SelectionStart = StatusText.Text.Length;
2108 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2110 //if (SettingDialog.UrlConvertAuto)
2112 // StatusText.SelectionStart = StatusText.Text.Length;
2113 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2115 //else if (SettingDialog.Nicoms)
2117 // StatusText.SelectionStart = StatusText.Text.Length;
2118 // UrlConvert(UrlConverter.Nicoms);
2120 StatusText.SelectionStart = StatusText.Text.Length;
2121 CheckReplyTo(StatusText.Text);
2123 var statusText = this.FormatStatusText(this.StatusText.Text);
2125 if (this.GetRestStatusCount(statusText) < 0)
2127 // 文字数制限を超えているが強制的に投稿するか
2128 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2129 if (ret != DialogResult.OK)
2133 var status = new PostingStatus();
2134 status.status = statusText;
2136 status.inReplyToId = this.inReplyTo?.Item1;
2137 status.inReplyToName = this.inReplyTo?.Item2;
2138 if (ImageSelector.Visible)
2141 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2145 this.inReplyTo = null;
2146 StatusText.Text = "";
2147 _history.Add(new PostingStatus());
2148 _hisIdx = _history.Count - 1;
2149 if (!ToolStripFocusLockMenuItem.Checked)
2150 ((Control)ListTab.SelectedTab.Tag).Focus();
2151 urlUndoBuffer = null;
2152 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2155 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2157 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2158 await this.OpenUriInBrowserAsync(tmp);
2161 await this.PostMessageAsync(status);
2164 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2166 MyCommon._endingFlag = true;
2170 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2172 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2174 //_endingFlag=false:フォームの×ボタン
2176 this.Visible = false;
2180 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2181 _ignoreConfigSave = true;
2182 MyCommon._endingFlag = true;
2183 TimerTimeline.Enabled = false;
2184 TimerRefreshIcon.Enabled = false;
2188 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2190 this.Visible = true;
2191 if (this.WindowState == FormWindowState.Minimized)
2193 this.WindowState = FormWindowState.Normal;
2196 this.BringToFront();
2199 private static int errorCount = 0;
2201 private static bool CheckAccountValid()
2203 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2209 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2218 private Task GetHomeTimelineAsync()
2220 return this.GetHomeTimelineAsync(loadMore: false);
2223 private async Task GetHomeTimelineAsync(bool loadMore)
2225 await this.workerSemaphore.WaitAsync();
2229 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2231 await this.GetHomeTimelineAsyncInternal(progress, this.workerCts.Token, loadMore);
2233 catch (WebApiException ex)
2235 this._myStatusError = true;
2236 this.StatusLabel.Text = ex.Message;
2240 this.workerSemaphore.Release();
2244 private async Task GetHomeTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2246 if (ct.IsCancellationRequested)
2249 if (!CheckAccountValid())
2250 throw new WebApiException("Auth error. Check your account");
2253 if (!this._cfgCommon.UnreadManage)
2256 read = this._initial && this._cfgCommon.Read;
2258 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5, loadMore ? -1 : 1));
2260 await Task.Run(() =>
2262 this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Timeline, loadMore, this._initial);
2265 if (this._cfgCommon.ReadOldPosts)
2266 this._statuses.SetReadHomeTab();
2268 var addCount = this._statuses.DistributePosts();
2271 this.UpdateTimelineSpeed(addCount);
2274 if (ct.IsCancellationRequested)
2277 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1);
2279 this.RefreshTimeline();
2283 /// タイムラインに追加された発言件数を反映し、タイムラインの流速を更新します
2285 /// <param name="addCount">直前にタイムラインに追加した発言件数</param>
2286 private void UpdateTimelineSpeed(int addCount)
2288 var now = DateTime.Now;
2289 this._tlTimestamps.AddOrUpdate(now, addCount, (k, v) => v + addCount);
2291 var removeKeys = new List<DateTime>();
2292 var oneHour = TimeSpan.FromHours(1);
2294 foreach (var pair in this._tlTimestamps)
2296 if (now - pair.Key > oneHour)
2297 removeKeys.Add(pair.Key);
2299 tlCount += pair.Value;
2301 Interlocked.Exchange(ref this._tlCount, tlCount);
2304 foreach (var key in removeKeys)
2305 this._tlTimestamps.TryRemove(key, out _);
2308 private Task GetReplyAsync()
2310 return this.GetReplyAsync(loadMore: false);
2313 private async Task GetReplyAsync(bool loadMore)
2315 await this.workerSemaphore.WaitAsync();
2319 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2321 await this.GetReplyAsyncInternal(progress, this.workerCts.Token, loadMore);
2323 catch (WebApiException ex)
2325 this._myStatusError = true;
2326 this.StatusLabel.Text = ex.Message;
2330 this.workerSemaphore.Release();
2334 private async Task GetReplyAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2336 if (ct.IsCancellationRequested)
2339 if (!CheckAccountValid())
2340 throw new WebApiException("Auth error. Check your account");
2343 if (!this._cfgCommon.UnreadManage)
2346 read = this._initial && this._cfgCommon.Read;
2348 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4, loadMore ? -1 : 1));
2350 await Task.Run(() =>
2352 this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Reply, loadMore, this._initial);
2354 this._statuses.DistributePosts();
2357 if (ct.IsCancellationRequested)
2360 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9);
2362 this.RefreshTimeline();
2365 private Task GetDirectMessagesAsync()
2367 return this.GetDirectMessagesAsync(loadMore: false);
2370 private async Task GetDirectMessagesAsync(bool loadMore)
2372 await this.workerSemaphore.WaitAsync();
2376 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2378 await this.GetDirectMessagesAsyncInternal(progress, this.workerCts.Token, loadMore);
2380 catch (WebApiException ex)
2382 this._myStatusError = true;
2383 this.StatusLabel.Text = ex.Message;
2387 this.workerSemaphore.Release();
2391 private async Task GetDirectMessagesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2393 if (ct.IsCancellationRequested)
2396 if (!CheckAccountValid())
2397 throw new WebApiException("Auth error. Check your account");
2400 if (!this._cfgCommon.UnreadManage)
2403 read = this._initial && this._cfgCommon.Read;
2405 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8, loadMore ? -1 : 1));
2407 await Task.Run(() =>
2409 this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, loadMore);
2410 this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, loadMore);
2412 this._statuses.DistributePosts();
2415 if (ct.IsCancellationRequested)
2418 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11);
2420 this.RefreshTimeline();
2423 private Task GetFavoritesAsync()
2425 return this.GetFavoritesAsync(loadMore: false);
2428 private async Task GetFavoritesAsync(bool loadMore)
2430 await this.workerSemaphore.WaitAsync();
2434 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2436 await this.GetFavoritesAsyncInternal(progress, this.workerCts.Token, loadMore);
2438 catch (WebApiException ex)
2440 this._myStatusError = true;
2441 this.StatusLabel.Text = ex.Message;
2445 this.workerSemaphore.Release();
2449 private async Task GetFavoritesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2451 if (ct.IsCancellationRequested)
2454 if (!CheckAccountValid())
2455 throw new WebApiException("Auth error. Check your account");
2458 if (!this._cfgCommon.UnreadManage)
2461 read = this._initial && this._cfgCommon.Read;
2463 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19);
2465 await Task.Run(() =>
2467 this.tw.GetFavoritesApi(read, loadMore);
2469 this._statuses.DistributePosts();
2472 if (ct.IsCancellationRequested)
2475 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20);
2477 this.RefreshTimeline();
2480 private Task GetPublicSearchAllAsync()
2482 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch);
2484 return this.GetPublicSearchAsync(tabs, loadMore: false);
2487 private Task GetPublicSearchAsync(TabClass tab)
2489 return this.GetPublicSearchAsync(tab, loadMore: false);
2492 private Task GetPublicSearchAsync(TabClass tab, bool loadMore)
2494 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2497 private async Task GetPublicSearchAsync(IEnumerable<TabClass> tabs, bool loadMore)
2499 await this.workerSemaphore.WaitAsync();
2503 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2505 await this.GetPublicSearchAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2507 catch (WebApiException ex)
2509 this._myStatusError = true;
2510 this.StatusLabel.Text = ex.Message;
2514 this.workerSemaphore.Release();
2518 private async Task GetPublicSearchAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2520 if (ct.IsCancellationRequested)
2523 if (!CheckAccountValid())
2524 throw new WebApiException("Auth error. Check your account");
2527 if (!this._cfgCommon.UnreadManage)
2530 read = this._initial && this._cfgCommon.Read;
2532 p.Report("Search refreshing...");
2534 await Task.Run(() =>
2536 WebApiException lastException = null;
2538 foreach (var tab in tabs)
2542 if (string.IsNullOrEmpty(tab.SearchWords))
2545 this.tw.GetSearch(read, tab, false);
2548 this.tw.GetSearch(read, tab, true);
2550 catch (WebApiException ex)
2556 this._statuses.DistributePosts();
2558 if (lastException != null)
2559 throw new WebApiException(lastException.Message, lastException);
2562 if (ct.IsCancellationRequested)
2565 p.Report("Search refreshed");
2567 this.RefreshTimeline();
2570 private Task GetUserTimelineAllAsync()
2572 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline);
2574 return this.GetUserTimelineAsync(tabs, loadMore: false);
2577 private Task GetUserTimelineAsync(TabClass tab)
2579 return this.GetUserTimelineAsync(tab, loadMore: false);
2582 private Task GetUserTimelineAsync(TabClass tab, bool loadMore)
2584 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2587 private async Task GetUserTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2589 await this.workerSemaphore.WaitAsync();
2593 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2595 await this.GetUserTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2597 catch (WebApiException ex)
2599 this._myStatusError = true;
2600 this.StatusLabel.Text = ex.Message;
2604 this.workerSemaphore.Release();
2608 private async Task GetUserTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2610 if (ct.IsCancellationRequested)
2613 if (!CheckAccountValid())
2614 throw new WebApiException("Auth error. Check your account");
2617 if (!this._cfgCommon.UnreadManage)
2620 read = this._initial && this._cfgCommon.Read;
2622 p.Report("UserTimeline refreshing...");
2624 await Task.Run(() =>
2626 WebApiException lastException = null;
2628 foreach (var tab in tabs)
2632 if (string.IsNullOrEmpty(tab.User))
2635 this.tw.GetUserTimelineApi(read, tab.User, tab, loadMore);
2637 catch (WebApiException ex)
2643 this._statuses.DistributePosts();
2645 if (lastException != null)
2646 throw new WebApiException(lastException.Message, lastException);
2649 if (ct.IsCancellationRequested)
2652 p.Report("UserTimeline refreshed");
2654 this.RefreshTimeline();
2657 private Task GetListTimelineAllAsync()
2659 var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.Lists);
2661 return this.GetListTimelineAsync(tabs, loadMore: false);
2664 private Task GetListTimelineAsync(TabClass tab)
2666 return this.GetListTimelineAsync(tab, loadMore: false);
2669 private Task GetListTimelineAsync(TabClass tab, bool loadMore)
2671 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2674 private async Task GetListTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2676 await this.workerSemaphore.WaitAsync();
2680 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2682 await this.GetListTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2684 catch (WebApiException ex)
2686 this._myStatusError = true;
2687 this.StatusLabel.Text = ex.Message;
2691 this.workerSemaphore.Release();
2695 private async Task GetListTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2697 if (ct.IsCancellationRequested)
2700 if (!CheckAccountValid())
2701 throw new WebApiException("Auth error. Check your account");
2704 if (!this._cfgCommon.UnreadManage)
2707 read = this._initial && this._cfgCommon.Read;
2709 p.Report("List refreshing...");
2711 await Task.Run(() =>
2713 WebApiException lastException = null;
2715 foreach (var tab in tabs)
2719 if (tab.ListInfo == null || tab.ListInfo.Id == 0)
2722 this.tw.GetListStatus(read, tab, loadMore, this._initial);
2724 catch (WebApiException ex)
2730 this._statuses.DistributePosts();
2732 if (lastException != null)
2733 throw new WebApiException(lastException.Message, lastException);
2736 if (ct.IsCancellationRequested)
2739 p.Report("List refreshed");
2741 this.RefreshTimeline();
2744 private async Task GetRelatedTweetsAsync(TabClass tab)
2746 await this.workerSemaphore.WaitAsync();
2750 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2752 await this.GetRelatedTweetsAsyncInternal(progress, this.workerCts.Token, tab);
2754 catch (WebApiException ex)
2756 this._myStatusError = true;
2757 this.StatusLabel.Text = ex.Message;
2761 this.workerSemaphore.Release();
2765 private async Task GetRelatedTweetsAsyncInternal(IProgress<string> p, CancellationToken ct, TabClass tab)
2767 if (ct.IsCancellationRequested)
2770 if (!CheckAccountValid())
2771 throw new WebApiException("Auth error. Check your account");
2774 if (!this._cfgCommon.UnreadManage)
2777 read = this._initial && this._cfgCommon.Read;
2779 p.Report("Related refreshing...");
2781 await Task.Run(() =>
2783 this.tw.GetRelatedResult(read, tab);
2785 this._statuses.DistributePosts();
2788 if (ct.IsCancellationRequested)
2791 p.Report("Related refreshed");
2793 this.RefreshTimeline();
2795 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
2796 .FirstOrDefault(x => x.Text == tab.TabName);
2798 if (tabPage != null)
2800 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
2802 var listView = (DetailsListView)tabPage.Tag;
2803 var index = tab.IndexOf(tab.RelationTargetPost.RetweetedId ?? tab.RelationTargetPost.StatusId);
2805 if (index != -1 && index < listView.Items.Count)
2807 listView.SelectedIndices.Add(index);
2808 listView.Items[index].Focused = true;
2813 private async Task FavAddAsync(IReadOnlyList<long> statusIds, TabClass tab)
2815 await this.workerSemaphore.WaitAsync();
2819 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2821 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2823 catch (WebApiException ex)
2825 this._myStatusError = true;
2826 this.StatusLabel.Text = ex.Message;
2830 this.workerSemaphore.Release();
2834 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2836 if (ct.IsCancellationRequested)
2839 if (!CheckAccountValid())
2840 throw new WebApiException("Auth error. Check your account");
2842 var successIds = new List<long>();
2844 await Task.Run(() =>
2848 var failedCount = 0;
2850 foreach (var statusId in statusIds)
2854 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, allCount, statusIds.Count, failedCount));
2856 var post = tab.Posts[statusId];
2863 this.tw.PostFavAdd(post.RetweetedId ?? post.StatusId);
2865 catch (WebApiException)
2871 successIds.Add(statusId);
2872 post.IsFav = true; // リスト再描画必要
2874 this._favTimestamps.Add(DateTime.Now);
2877 if (this._statuses.ContainsKey(statusId))
2879 var postTl = this._statuses[statusId];
2880 postTl.IsFav = true;
2882 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2883 favTab.AddPostImmediately(statusId, postTl.IsRead);
2886 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2887 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2889 if (tb.Contains(statusId))
2890 tb.Posts[statusId].IsFav = true;
2895 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2896 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2898 if (this._favTimestamps[i] < oneHour)
2899 this._favTimestamps.RemoveAt(i);
2902 this._statuses.DistributePosts();
2905 if (ct.IsCancellationRequested)
2908 this.RefreshTimeline();
2910 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2912 using (ControlTransaction.Update(this._curList))
2914 foreach (var statusId in successIds)
2916 var idx = tab.IndexOf(statusId);
2920 var post = tab.Posts[statusId];
2921 this.ChangeCacheStyleRead(post.IsRead, idx);
2925 if (successIds.Contains(this._curPost.StatusId))
2926 await this.DispSelectedPost(true); // 選択アイテム再表示
2930 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabClass tab)
2932 await this.workerSemaphore.WaitAsync();
2936 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2938 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2940 catch (WebApiException ex)
2942 this._myStatusError = true;
2943 this.StatusLabel.Text = ex.Message;
2947 this.workerSemaphore.Release();
2951 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2953 if (ct.IsCancellationRequested)
2956 if (!CheckAccountValid())
2957 throw new WebApiException("Auth error. Check your account");
2959 var successIds = new List<long>();
2961 await Task.Run(() =>
2965 var failedCount = 0;
2966 foreach (var statusId in statusIds)
2970 var post = tab.Posts[statusId];
2972 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2979 this.tw.PostFavRemove(post.RetweetedId ?? post.StatusId);
2981 catch (WebApiException)
2987 successIds.Add(statusId);
2988 post.IsFav = false; // リスト再描画必要
2990 if (this._statuses.ContainsKey(statusId))
2992 this._statuses[statusId].IsFav = false;
2995 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2996 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2998 if (tb.Contains(statusId))
2999 tb.Posts[statusId].IsFav = false;
3004 if (ct.IsCancellationRequested)
3007 this.RemovePostFromFavTab(successIds.ToArray());
3009 this.RefreshTimeline();
3011 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
3013 if (tab.TabType == MyCommon.TabUsageType.Favorites)
3019 using (ControlTransaction.Update(this._curList))
3021 foreach (var statusId in successIds)
3023 var idx = tab.IndexOf(statusId);
3027 var post = tab.Posts[statusId];
3028 this.ChangeCacheStyleRead(post.IsRead, idx);
3032 if (successIds.Contains(this._curPost.StatusId))
3033 await this.DispSelectedPost(true); // 選択アイテム再表示
3038 private async Task PostMessageAsync(PostingStatus status)
3040 await this.workerSemaphore.WaitAsync();
3044 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3046 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
3048 catch (WebApiException ex)
3050 this._myStatusError = true;
3051 this.StatusLabel.Text = ex.Message;
3055 this.workerSemaphore.Release();
3059 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
3061 if (ct.IsCancellationRequested)
3064 if (!CheckAccountValid())
3065 throw new WebApiException("Auth error. Check your account");
3067 p.Report("Posting...");
3073 await Task.Run(async () =>
3075 if (status.mediaItems == null || status.mediaItems.Length == 0)
3077 this.tw.PostStatus(status.status, status.inReplyToId);
3081 var service = ImageSelector.GetService(status.imageService);
3082 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
3083 .ConfigureAwait(false);
3087 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3089 catch (WebApiException ex)
3091 // 処理は中断せずエラーの表示のみ行う
3092 errMsg = ex.Message;
3094 this._myStatusError = true;
3098 // 使い終わった MediaItem は破棄する
3099 if (status.mediaItems != null)
3101 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
3103 disposableItem.Dispose();
3108 if (ct.IsCancellationRequested)
3111 if (!string.IsNullOrEmpty(errMsg) &&
3112 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
3113 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
3115 var ret = MessageBox.Show(
3117 "{0} ---> [ " + errMsg + " ]" + Environment.NewLine +
3118 "\"" + status.status + "\"" + Environment.NewLine +
3120 Properties.Resources.StatusUpdateFailed1,
3121 Properties.Resources.StatusUpdateFailed2),
3122 "Failed to update status",
3123 MessageBoxButtons.RetryCancel,
3124 MessageBoxIcon.Question);
3126 if (ret == DialogResult.Retry)
3128 await this.PostMessageAsync(status);
3132 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3133 if (this.ToolStripFocusLockMenuItem.Checked)
3134 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
3139 this._postTimestamps.Add(DateTime.Now);
3141 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3142 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3144 if (this._postTimestamps[i] < oneHour)
3145 this._postTimestamps.RemoveAt(i);
3148 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
3150 this.HashMgr.ClearHashtag();
3151 this.HashStripSplitButton.Text = "#[-]";
3152 this.HashToggleMenuItem.Checked = false;
3153 this.HashToggleToolStripMenuItem.Checked = false;
3156 this.SetMainWindowTitle();
3158 if (this._cfgCommon.PostAndGet)
3160 if (this._isActiveUserstream)
3161 this.RefreshTimeline();
3163 await this.GetHomeTimelineAsync();
3167 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
3169 await this.workerSemaphore.WaitAsync();
3173 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3175 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
3177 catch (WebApiException ex)
3179 this._myStatusError = true;
3180 this.StatusLabel.Text = ex.Message;
3184 this.workerSemaphore.Release();
3188 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
3190 if (ct.IsCancellationRequested)
3193 if (!CheckAccountValid())
3194 throw new WebApiException("Auth error. Check your account");
3197 if (!this._cfgCommon.UnreadManage)
3200 read = this._initial && this._cfgCommon.Read;
3202 p.Report("Posting...");
3204 await Task.Run(() =>
3206 foreach (var statusId in statusIds)
3208 this.tw.PostRetweet(statusId, read);
3212 if (ct.IsCancellationRequested)
3215 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3217 this._postTimestamps.Add(DateTime.Now);
3219 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3220 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3222 if (this._postTimestamps[i] < oneHour)
3223 this._postTimestamps.RemoveAt(i);
3226 if (this._cfgCommon.PostAndGet && !this._isActiveUserstream)
3227 await this.GetHomeTimelineAsync();
3230 private async Task RefreshFollowerIdsAsync()
3232 await this.workerSemaphore.WaitAsync();
3235 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
3237 await Task.Run(() => tw.RefreshFollowerIds());
3239 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
3241 this.RefreshTimeline();
3242 this.PurgeListViewItemCache();
3243 this._curList?.Refresh();
3245 catch (WebApiException ex)
3247 this.StatusLabel.Text = ex.Message;
3251 this.workerSemaphore.Release();
3255 private async Task RefreshNoRetweetIdsAsync()
3257 await this.workerSemaphore.WaitAsync();
3260 await Task.Run(() => tw.RefreshNoRetweetIds());
3262 this.StatusLabel.Text = "NoRetweetIds refreshed";
3264 catch (WebApiException ex)
3266 this.StatusLabel.Text = ex.Message;
3270 this.workerSemaphore.Release();
3274 private async Task RefreshBlockIdsAsync()
3276 await this.workerSemaphore.WaitAsync();
3279 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
3281 await Task.Run(() => tw.RefreshBlockIds());
3283 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
3285 catch (WebApiException ex)
3287 this.StatusLabel.Text = ex.Message;
3291 this.workerSemaphore.Release();
3295 private async Task RefreshTwitterConfigurationAsync()
3297 await this.workerSemaphore.WaitAsync();
3300 await Task.Run(() => tw.RefreshConfiguration());
3302 if (this.tw.Configuration.PhotoSizeLimit != 0)
3304 foreach (var service in this.ImageSelector.GetServices())
3306 service.UpdateTwitterConfiguration(this.tw.Configuration);
3310 this.PurgeListViewItemCache();
3312 this._curList?.Refresh();
3314 catch (WebApiException ex)
3316 this.StatusLabel.Text = ex.Message;
3320 this.workerSemaphore.Release();
3324 private async Task RefreshMuteUserIdsAsync()
3326 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3330 await tw.RefreshMuteUserIdsAsync();
3332 catch (WebApiException ex)
3334 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3338 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3341 private void RemovePostFromFavTab(Int64[] ids)
3343 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
3344 string favTabName = favTab.TabName;
3346 if (_curTab.Text.Equals(favTabName))
3348 fidx = _curList.FocusedItem?.Index ?? _curList.TopItem?.Index ?? 0;
3351 foreach (long i in ids)
3355 _statuses.RemoveFavPost(i);
3362 if (_curTab != null && _curTab.Text.Equals(favTabName))
3364 this.PurgeListViewItemCache();
3366 //_curItemIndex = -1;
3368 foreach (TabPage tp in ListTab.TabPages)
3370 if (tp.Text == favTabName)
3372 ((DetailsListView)tp.Tag).VirtualListSize = favTab.AllCount;
3376 if (_curTab.Text.Equals(favTabName))
3380 _curList.SelectedIndices.Clear();
3382 while (_curList.SelectedIndices.Count > 0);
3384 if (favTab.AllCount > 0)
3386 if (favTab.AllCount - 1 > fidx && fidx > -1)
3388 _curList.SelectedIndices.Add(fidx);
3392 _curList.SelectedIndices.Add(favTab.AllCount - 1);
3394 if (_curList.SelectedIndices.Count > 0)
3396 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3397 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3403 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3405 if (e.Button == MouseButtons.Left)
3407 this.Visible = true;
3408 if (this.WindowState == FormWindowState.Minimized)
3410 this.WindowState = _formWindowState;
3413 this.BringToFront();
3417 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3419 switch (this._cfgCommon.ListDoubleClickAction)
3422 MakeReplyOrDirectStatus();
3425 await this.FavoriteChange(true);
3428 if (_curPost != null)
3429 await this.ShowUserStatus(_curPost.ScreenName, false);
3435 ShowRelatedStatusesMenuItem_Click(null, null);
3438 MoveToHomeToolStripMenuItem_Click(null, null);
3441 StatusOpenMenuItem_Click(null, null);
3449 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3451 await this.FavoriteChange(true);
3454 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3456 await this.FavoriteChange(false);
3460 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3462 await this.FavoritesRetweetOfficial();
3465 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3467 await this.FavoritesRetweetUnofficial();
3470 private async Task FavoriteChange(bool FavAdd , bool multiFavoriteChangeDialogEnable = true)
3473 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3476 //trueでFavAdd,falseでFavRemove
3477 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3478 || !this.ExistCurrentPost) return;
3480 // 誤ふぁぼ・故意によるふぁぼ爆対策 (変更しないこと)
3481 // https://support.twitter.com/articles/76915#favoriting
3482 const int MultiSelectFavLimit = 1;
3485 if (_curList.SelectedIndices.Count > MultiSelectFavLimit && FavAdd)
3487 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, MultiSelectFavLimit));
3488 _DoFavRetweetFlags = false;
3491 else if (multiFavoriteChangeDialogEnable && _curList.SelectedIndices.Count > 1)
3495 string QuestionText = Properties.Resources.FavAddToolStripMenuItem_ClickText1;
3496 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText3;
3497 if (MessageBox.Show(QuestionText, Properties.Resources.FavAddToolStripMenuItem_ClickText2,
3498 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3500 _DoFavRetweetFlags = false;
3506 if (MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1, Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3507 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3514 var statusIds = new List<long>();
3515 foreach (int idx in _curList.SelectedIndices)
3517 PostClass post = GetCurTabPost(idx);
3521 statusIds.Add(post.StatusId);
3526 statusIds.Add(post.StatusId);
3529 if (statusIds.Count == 0)
3532 StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3534 StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3540 await this.FavAddAsync(statusIds, tab);
3542 await this.FavRemoveAsync(statusIds, tab);
3545 private PostClass GetCurTabPost(int Index)
3547 var listCache = this._listItemCache;
3548 if (listCache != null)
3552 if (listCache.TryGetValue(Index, out item, out post))
3556 return _statuses.Tabs[_curTab.Text][Index];
3559 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3561 if (_curList.SelectedIndices.Count > 0)
3562 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3563 else if (_curList.SelectedIndices.Count == 0)
3564 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3567 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3569 if (_curList.SelectedIndices.Count > 0)
3570 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3573 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3575 if ((!_initialLayout) && this.Visible)
3577 if (this.WindowState == FormWindowState.Normal)
3579 _mySize = this.ClientSize;
3580 _mySpDis = this.SplitContainer1.SplitterDistance;
3581 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3582 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3583 ModifySettingLocal = true;
3588 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3590 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3591 if (comparerMode == null)
3594 this.SetSortColumn(comparerMode.Value);
3598 /// 列インデックスからソートを行う ComparerMode を求める
3600 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3601 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3602 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3605 return ComparerMode.Id;
3607 switch (columnIndex)
3610 return ComparerMode.Nickname;
3612 return ComparerMode.Data;
3614 return ComparerMode.Id;
3616 return ComparerMode.Name;
3618 return ComparerMode.Source;
3620 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3626 /// 発言一覧の指定した位置の列でソートする
3628 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3629 private void SetSortColumnByDisplayIndex(int columnIndex)
3631 // 表示上の列の位置から ColumnHeader を求める
3632 var col = this._curList.Columns.Cast<ColumnHeader>()
3633 .Where(x => x.DisplayIndex == columnIndex)
3639 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3640 if (comparerMode == null)
3643 this.SetSortColumn(comparerMode.Value);
3647 /// 発言一覧の最後列の項目でソートする
3649 private void SetSortLastColumn()
3651 // 表示上の最後列にある ColumnHeader を求める
3652 var col = this._curList.Columns.Cast<ColumnHeader>()
3653 .OrderByDescending(x => x.DisplayIndex)
3656 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3657 if (comparerMode == null)
3660 this.SetSortColumn(comparerMode.Value);
3664 /// 発言一覧を指定された ComparerMode に基づいてソートする
3666 private void SetSortColumn(ComparerMode sortColumn)
3668 if (this._cfgCommon.SortOrderLock)
3671 this._statuses.ToggleSortOrder(sortColumn);
3672 this.InitColumnText();
3674 var list = this._curList;
3677 list.Columns[0].Text = this.ColumnText[0];
3678 list.Columns[1].Text = this.ColumnText[2];
3682 for (var i = 0; i <= 7; i++)
3684 list.Columns[i].Text = this.ColumnText[i];
3688 this.PurgeListViewItemCache();
3690 var tab = this._statuses.Tabs[this._curTab.Text];
3691 if (tab.AllCount > 0 && this._curPost != null)
3693 var idx = tab.IndexOf(this._curPost.StatusId);
3696 this.SelectListItem(list, idx);
3697 list.EnsureVisible(idx);
3702 this.ModifySettingCommon = true;
3705 private void TweenMain_LocationChanged(object sender, EventArgs e)
3707 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3709 _myLoc = this.DesktopLocation;
3710 ModifySettingLocal = true;
3714 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3716 if (ListTab.SelectedTab == null) return;
3717 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3718 if (!this.ExistCurrentPost)
3720 ReplyStripMenuItem.Enabled = false;
3721 ReplyAllStripMenuItem.Enabled = false;
3722 DMStripMenuItem.Enabled = false;
3723 ShowProfileMenuItem.Enabled = false;
3724 ShowUserTimelineContextMenuItem.Enabled = false;
3725 ListManageUserContextToolStripMenuItem2.Enabled = false;
3726 MoveToFavToolStripMenuItem.Enabled = false;
3727 TabMenuItem.Enabled = false;
3728 IDRuleMenuItem.Enabled = false;
3729 SourceRuleMenuItem.Enabled = false;
3730 ReadedStripMenuItem.Enabled = false;
3731 UnreadStripMenuItem.Enabled = false;
3735 ShowProfileMenuItem.Enabled = true;
3736 ListManageUserContextToolStripMenuItem2.Enabled = true;
3737 ReplyStripMenuItem.Enabled = true;
3738 ReplyAllStripMenuItem.Enabled = true;
3739 DMStripMenuItem.Enabled = true;
3740 ShowUserTimelineContextMenuItem.Enabled = true;
3741 MoveToFavToolStripMenuItem.Enabled = true;
3742 TabMenuItem.Enabled = true;
3743 IDRuleMenuItem.Enabled = true;
3744 SourceRuleMenuItem.Enabled = true;
3745 ReadedStripMenuItem.Enabled = true;
3746 UnreadStripMenuItem.Enabled = true;
3748 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3750 FavAddToolStripMenuItem.Enabled = false;
3751 FavRemoveToolStripMenuItem.Enabled = false;
3752 StatusOpenMenuItem.Enabled = false;
3753 FavorareMenuItem.Enabled = false;
3754 ShowRelatedStatusesMenuItem.Enabled = false;
3756 ReTweetStripMenuItem.Enabled = false;
3757 ReTweetUnofficialStripMenuItem.Enabled = false;
3758 QuoteStripMenuItem.Enabled = false;
3759 FavoriteRetweetContextMenu.Enabled = false;
3760 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3764 FavAddToolStripMenuItem.Enabled = true;
3765 FavRemoveToolStripMenuItem.Enabled = true;
3766 StatusOpenMenuItem.Enabled = true;
3767 FavorareMenuItem.Enabled = true;
3768 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3772 ReTweetStripMenuItem.Enabled = false; //公式RTは無効に
3773 ReTweetUnofficialStripMenuItem.Enabled = true;
3774 QuoteStripMenuItem.Enabled = true;
3775 FavoriteRetweetContextMenu.Enabled = false; //公式RTは無効に
3776 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3780 if (_curPost.IsProtect)
3782 ReTweetStripMenuItem.Enabled = false;
3783 ReTweetUnofficialStripMenuItem.Enabled = false;
3784 QuoteStripMenuItem.Enabled = false;
3785 FavoriteRetweetContextMenu.Enabled = false;
3786 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3790 ReTweetStripMenuItem.Enabled = true;
3791 ReTweetUnofficialStripMenuItem.Enabled = true;
3792 QuoteStripMenuItem.Enabled = true;
3793 FavoriteRetweetContextMenu.Enabled = true;
3794 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3798 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3800 // RefreshMoreStripMenuItem.Enabled = true;
3804 // RefreshMoreStripMenuItem.Enabled = false;
3806 if (!this.ExistCurrentPost
3807 || _curPost.InReplyToStatusId == null)
3809 RepliedStatusOpenMenuItem.Enabled = false;
3813 RepliedStatusOpenMenuItem.Enabled = true;
3815 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3817 MoveToRTHomeMenuItem.Enabled = false;
3821 MoveToRTHomeMenuItem.Enabled = true;
3824 if (this.ExistCurrentPost)
3826 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3827 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3828 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3830 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3834 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3836 MakeReplyOrDirectStatus(false, true);
3839 private void DMStripMenuItem_Click(object sender, EventArgs e)
3841 MakeReplyOrDirectStatus(false, false);
3844 private void doStatusDelete()
3846 if (this._curTab == null || this._curList == null)
3849 if (this._curList.SelectedIndices.Count == 0)
3852 var posts = this._curList.SelectedIndices.Cast<int>()
3853 .Select(x => this.GetCurTabPost(x))
3856 // 選択されたツイートの中に削除可能なものが一つでもあるか
3857 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3860 var ret = MessageBox.Show(this,
3861 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3862 Properties.Resources.DeleteStripMenuItem_ClickText2,
3863 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3865 if (ret != DialogResult.OK)
3868 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3870 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3872 Exception lastException = null;
3873 foreach (var post in posts)
3875 if (!post.CanDeleteBy(this.tw.UserId))
3882 this.tw.RemoveDirectMessage(post.StatusId, post);
3886 if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3887 // 他人に RT された自分のツイート
3888 this.tw.RemoveStatus(post.RetweetedId.Value);
3890 // 自分のツイート or 自分が RT したツイート
3891 this.tw.RemoveStatus(post.StatusId);
3894 catch (WebApiException ex)
3900 this._statuses.RemovePost(post.StatusId);
3903 if (lastException == null)
3904 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3906 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3908 this.PurgeListViewItemCache();
3909 this._curPost = null;
3910 this._curItemIndex = -1;
3912 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3914 var listView = (DetailsListView)tabPage.Tag;
3915 var tab = this._statuses.Tabs[tabPage.Text];
3917 using (ControlTransaction.Update(listView))
3919 listView.VirtualListSize = tab.AllCount;
3921 if (tabPage == this._curTab)
3923 listView.SelectedIndices.Clear();
3925 if (tab.AllCount != 0)
3928 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3929 selectedIndex = focusedIndex;
3931 selectedIndex = tab.AllCount - 1;
3933 listView.SelectedIndices.Add(selectedIndex);
3934 listView.EnsureVisible(selectedIndex);
3935 listView.FocusedItem = listView.Items[selectedIndex];
3940 if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3942 if (tabPage.ImageIndex == 0)
3943 tabPage.ImageIndex = -1; // タブアイコン
3947 if (!this._cfgCommon.TabIconDisp)
3948 this.ListTab.Refresh();
3952 private void DeleteStripMenuItem_Click(object sender, EventArgs e)
3957 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3959 using (ControlTransaction.Update(this._curList))
3961 foreach (int idx in _curList.SelectedIndices)
3963 var post = this._statuses.Tabs[this._curTab.Text][idx];
3964 this._statuses.SetReadAllTab(post.StatusId, read: true);
3965 ChangeCacheStyleRead(true, idx);
3969 foreach (TabPage tb in ListTab.TabPages)
3971 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3973 if (this._cfgCommon.TabIconDisp)
3975 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3979 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3982 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3984 using (ControlTransaction.Update(this._curList))
3986 foreach (int idx in _curList.SelectedIndices)
3988 var post = this._statuses.Tabs[this._curTab.Text][idx];
3989 this._statuses.SetReadAllTab(post.StatusId, read: false);
3990 ChangeCacheStyleRead(false, idx);
3994 foreach (TabPage tb in ListTab.TabPages)
3996 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3998 if (this._cfgCommon.TabIconDisp)
4000 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
4004 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
4007 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
4009 await this.DoRefresh();
4012 private async Task DoRefresh()
4014 if (_curTab != null)
4017 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4020 switch (_statuses.Tabs[_curTab.Text].TabType)
4022 case MyCommon.TabUsageType.Mentions:
4023 await this.GetReplyAsync();
4025 case MyCommon.TabUsageType.DirectMessage:
4026 await this.GetDirectMessagesAsync();
4028 case MyCommon.TabUsageType.Favorites:
4029 await this.GetFavoritesAsync();
4031 //case MyCommon.TabUsageType.Profile:
4033 case MyCommon.TabUsageType.PublicSearch:
4035 if (string.IsNullOrEmpty(tab.SearchWords)) return;
4036 await this.GetPublicSearchAsync(tab);
4038 case MyCommon.TabUsageType.UserTimeline:
4039 await this.GetUserTimelineAsync(tab);
4041 case MyCommon.TabUsageType.Lists:
4043 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4044 await this.GetListTimelineAsync(tab);
4047 await this.GetHomeTimelineAsync();
4053 await this.GetHomeTimelineAsync();
4057 private async Task DoRefreshMore()
4060 if (_curTab != null)
4063 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4066 switch (_statuses.Tabs[_curTab.Text].TabType)
4068 case MyCommon.TabUsageType.Mentions:
4069 await this.GetReplyAsync(loadMore: true);
4071 case MyCommon.TabUsageType.DirectMessage:
4072 await this.GetDirectMessagesAsync(loadMore: true);
4074 case MyCommon.TabUsageType.Favorites:
4075 await this.GetFavoritesAsync(loadMore: true);
4077 case MyCommon.TabUsageType.Profile:
4080 case MyCommon.TabUsageType.PublicSearch:
4082 if (string.IsNullOrEmpty(tab.SearchWords)) return;
4083 await this.GetPublicSearchAsync(tab, loadMore: true);
4085 case MyCommon.TabUsageType.UserTimeline:
4086 await this.GetUserTimelineAsync(tab, loadMore: true);
4088 case MyCommon.TabUsageType.Lists:
4090 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4091 await this.GetListTimelineAsync(tab, loadMore: true);
4094 await this.GetHomeTimelineAsync(loadMore: true);
4100 await this.GetHomeTimelineAsync(loadMore: true);
4104 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
4106 DialogResult result = DialogResult.Abort;
4108 using (var settingDialog = new AppendSettingDialog())
4110 settingDialog.Icon = this.MainIcon;
4111 settingDialog.Owner = this;
4112 settingDialog.ShowInTaskbar = showTaskbarIcon;
4113 settingDialog.IntervalChanged += this.TimerInterval_Changed;
4115 settingDialog.tw = this.tw;
4116 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
4120 result = settingDialog.ShowDialog(this);
4124 return DialogResult.Abort;
4127 if (result == DialogResult.OK)
4131 settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
4139 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
4142 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
4144 var oldIconSz = this._cfgCommon.IconSize;
4146 if (ShowSettingDialog() == DialogResult.OK)
4150 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
4151 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
4152 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
4153 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
4154 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
4155 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
4157 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
4158 Networking.SetWebProxy(this._cfgLocal.ProxyType,
4159 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
4160 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
4161 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
4163 ImageSelector.Reset(tw, this.tw.Configuration);
4167 if (this._cfgCommon.TabIconDisp)
4169 ListTab.DrawItem -= ListTab_DrawItem;
4170 ListTab.DrawMode = TabDrawMode.Normal;
4171 ListTab.ImageList = this.TabImage;
4175 ListTab.DrawItem -= ListTab_DrawItem;
4176 ListTab.DrawItem += ListTab_DrawItem;
4177 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
4178 ListTab.ImageList = null;
4181 catch (Exception ex)
4183 ex.Data["Instance"] = "ListTab(TabIconDisp)";
4184 ex.Data["IsTerminatePermission"] = false;
4190 if (!this._cfgCommon.UnreadManage)
4192 ReadedStripMenuItem.Enabled = false;
4193 UnreadStripMenuItem.Enabled = false;
4194 if (this._cfgCommon.TabIconDisp)
4196 foreach (TabPage myTab in ListTab.TabPages)
4198 myTab.ImageIndex = -1;
4204 ReadedStripMenuItem.Enabled = true;
4205 UnreadStripMenuItem.Enabled = true;
4208 catch (Exception ex)
4210 ex.Data["Instance"] = "ListTab(UnreadManage)";
4211 ex.Data["IsTerminatePermission"] = false;
4218 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
4220 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
4221 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
4222 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
4224 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
4225 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
4226 _fntUnread = this._cfgLocal.FontUnread;
4227 _clUnread = this._cfgLocal.ColorUnread;
4228 _fntReaded = this._cfgLocal.FontRead;
4229 _clReaded = this._cfgLocal.ColorRead;
4230 _clFav = this._cfgLocal.ColorFav;
4231 _clOWL = this._cfgLocal.ColorOWL;
4232 _clRetweet = this._cfgLocal.ColorRetweet;
4233 _fntDetail = this._cfgLocal.FontDetail;
4234 _clDetail = this._cfgLocal.ColorDetail;
4235 _clDetailLink = this._cfgLocal.ColorDetailLink;
4236 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
4237 _clSelf = this._cfgLocal.ColorSelf;
4238 _clAtSelf = this._cfgLocal.ColorAtSelf;
4239 _clTarget = this._cfgLocal.ColorTarget;
4240 _clAtTarget = this._cfgLocal.ColorAtTarget;
4241 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
4242 _clAtTo = this._cfgLocal.ColorAtTo;
4243 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
4244 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
4245 _clInputFont = this._cfgLocal.ColorInputFont;
4246 _fntInputFont = this._cfgLocal.FontInputFont;
4247 _brsBackColorMine.Dispose();
4248 _brsBackColorAt.Dispose();
4249 _brsBackColorYou.Dispose();
4250 _brsBackColorAtYou.Dispose();
4251 _brsBackColorAtFromTarget.Dispose();
4252 _brsBackColorAtTo.Dispose();
4253 _brsBackColorNone.Dispose();
4254 _brsBackColorMine = new SolidBrush(_clSelf);
4255 _brsBackColorAt = new SolidBrush(_clAtSelf);
4256 _brsBackColorYou = new SolidBrush(_clTarget);
4257 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4258 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4259 _brsBackColorAtTo = new SolidBrush(_clAtTo);
4260 _brsBackColorNone = new SolidBrush(_clListBackcolor);
4264 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4265 StatusText.Font = _fntInputFont;
4266 StatusText.ForeColor = _clInputFont;
4268 catch (Exception ex)
4270 MessageBox.Show(ex.Message);
4275 InitDetailHtmlFormat();
4277 catch (Exception ex)
4279 ex.Data["Instance"] = "Font";
4280 ex.Data["IsTerminatePermission"] = false;
4286 foreach (TabPage tb in ListTab.TabPages)
4288 if (this._cfgCommon.TabIconDisp)
4290 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4297 catch (Exception ex)
4299 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4300 ex.Data["IsTerminatePermission"] = false;
4306 var oldIconCol = _iconCol;
4308 if (this._cfgCommon.IconSize != oldIconSz)
4309 ApplyListViewIconSize(this._cfgCommon.IconSize);
4311 foreach (TabPage tp in ListTab.TabPages)
4313 DetailsListView lst = (DetailsListView)tp.Tag;
4315 using (ControlTransaction.Update(lst))
4317 lst.GridLines = this._cfgCommon.ShowGrid;
4318 lst.Font = _fntReaded;
4319 lst.BackColor = _clListBackcolor;
4321 if (_iconCol != oldIconCol)
4326 catch (Exception ex)
4328 ex.Data["Instance"] = "ListView(IconSize)";
4329 ex.Data["IsTerminatePermission"] = false;
4333 SetMainWindowTitle();
4334 SetNotifyIconText();
4336 this.PurgeListViewItemCache();
4337 _curList?.Refresh();
4340 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4341 if (this._cfgCommon.HotkeyEnabled)
4343 ///グローバルホットキーの登録。設定で変更可能にするかも
4344 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4345 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4346 modKey |= HookGlobalHotkey.ModKeys.Alt;
4347 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4348 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4349 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4350 modKey |= HookGlobalHotkey.ModKeys.Shift;
4351 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4352 modKey |= HookGlobalHotkey.ModKeys.Win;
4354 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4357 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4360 StatusText_TextChanged(null, null);
4369 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
4370 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
4373 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4375 this.TopMost = this._cfgCommon.AlwaysTop;
4376 SaveConfigsAll(false);
4378 if (tw.Username != oldUser.Username)
4379 await this.doGetFollowersMenu();
4385 private void SetTabAlignment()
4387 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4388 if (ListTab.Alignment == newAlignment) return;
4390 // 各タブのリスト上の選択位置などを退避
4391 var listSelections = this.SaveListViewSelection();
4393 ListTab.Alignment = newAlignment;
4395 foreach (TabPage tab in ListTab.TabPages)
4397 DetailsListView lst = (DetailsListView)tab.Tag;
4398 TabClass tabInfo = _statuses.Tabs[tab.Text];
4399 using (ControlTransaction.Update(lst))
4402 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4407 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4413 case MyCommon.IconSizes.IconNone:
4416 case MyCommon.IconSizes.Icon16:
4419 case MyCommon.IconSizes.Icon24:
4422 case MyCommon.IconSizes.Icon48:
4425 case MyCommon.IconSizes.Icon48_2:
4433 // ディスプレイの DPI 設定を考慮したサイズを設定する
4434 _listViewImageList.ImageSize = new Size(
4436 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4440 _listViewImageList.ImageSize = new Size(1, 1);
4444 private void ResetColumns(DetailsListView list)
4446 using (ControlTransaction.Update(list))
4447 using (ControlTransaction.Layout(list, false))
4450 list.ColumnClick -= MyList_ColumnClick;
4451 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4452 list.ColumnReordered -= MyList_ColumnReordered;
4453 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4455 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4456 list.Columns.Clear();
4457 cols.ForEach(col => col.Dispose());
4460 InitColumns(list, true);
4462 list.ColumnClick += MyList_ColumnClick;
4463 list.DrawColumnHeader += MyList_DrawColumnHeader;
4464 list.ColumnReordered += MyList_ColumnReordered;
4465 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4469 private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4471 if (e.Url.AbsoluteUri != "about:blank")
4473 await this.DispSelectedPost();
4474 await this.OpenUriInBrowserAsync(e.Url.OriginalString);
4478 private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4480 if (e.Url.Scheme == "data")
4482 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4484 else if (e.Url.AbsoluteUri != "about:blank")
4487 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
4488 await this.OpenUriAsync( e.Url, MyCommon.IsKeyDown( Keys.Control ) );
4492 public void AddNewTabForSearch(string searchWord)
4494 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4495 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4497 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4499 foreach (TabPage tp in ListTab.TabPages)
4501 if (tb.TabName == tp.Text)
4503 ListTab.SelectedTab = tp;
4510 string tabName = searchWord;
4511 for (int i = 0; i <= 100; i++)
4513 if (_statuses.ContainsTab(tabName))
4519 _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4520 AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4522 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4524 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4525 cmb.Items.Add(searchWord);
4526 cmb.Text = searchWord;
4529 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4532 private void ShowUserTimeline()
4534 if (!this.ExistCurrentPost) return;
4535 AddNewTabForUserTimeline(_curPost.ScreenName);
4538 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4540 if (e.KeyCode == Keys.Escape)
4542 TabPage relTp = ListTab.SelectedTab;
4543 RemoveSpecifiedTab(relTp.Text, false);
4545 e.SuppressKeyPress = true;
4549 public void AddNewTabForUserTimeline(string user)
4551 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4552 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4554 if (tb.User == user)
4556 foreach (TabPage tp in ListTab.TabPages)
4558 if (tb.TabName == tp.Text)
4560 ListTab.SelectedTab = tp;
4567 string tabName = "user:" + user;
4568 while (_statuses.ContainsTab(tabName))
4573 _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4574 var tab = this._statuses.Tabs[tabName];
4576 AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4578 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4581 this.GetUserTimelineAsync(tab);
4584 public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4587 foreach (TabPage tb in ListTab.TabPages)
4589 if (tb.Text == tabName) return false;
4593 if (tabName == Properties.Resources.AddNewTabText1) return false;
4598 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4599 tabType == MyCommon.TabUsageType.Favorites ||
4600 tabType == MyCommon.TabUsageType.Home ||
4601 tabType == MyCommon.TabUsageType.Mentions ||
4602 tabType == MyCommon.TabUsageType.Related)
4604 if (_statuses.GetTabByType(tabType) != null) return false;
4608 var _tabPage = new TabPage();
4609 var _listCustom = new DetailsListView();
4611 int cnt = ListTab.TabPages.Count;
4613 ///ToDo:Create and set controls follow tabtypes
4615 using (ControlTransaction.Update(_listCustom))
4616 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4617 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4618 using (ControlTransaction.Layout(this.SplitContainer1, false))
4619 using (ControlTransaction.Layout(this.ListTab, false))
4620 using (ControlTransaction.Layout(this))
4621 using (ControlTransaction.Layout(_tabPage, false))
4623 _tabPage.Controls.Add(_listCustom);
4626 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4628 var label = new Label();
4629 label.Dock = DockStyle.Top;
4630 label.Name = "labelUser";
4631 if (tabType == MyCommon.TabUsageType.Lists)
4633 label.Text = listInfo.ToString();
4637 label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4639 label.TextAlign = ContentAlignment.MiddleLeft;
4640 using (ComboBox tmpComboBox = new ComboBox())
4642 label.Height = tmpComboBox.Height;
4644 _tabPage.Controls.Add(label);
4647 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4649 var pnl = new Panel();
4651 var lbl = new Label();
4652 var cmb = new ComboBox();
4653 var btn = new Button();
4654 var cmbLang = new ComboBox();
4656 using (ControlTransaction.Layout(pnl, false))
4658 pnl.Controls.Add(cmb);
4659 pnl.Controls.Add(cmbLang);
4660 pnl.Controls.Add(btn);
4661 pnl.Controls.Add(lbl);
4662 pnl.Name = "panelSearch";
4663 pnl.Dock = DockStyle.Top;
4664 pnl.Height = cmb.Height;
4665 pnl.Enter += SearchControls_Enter;
4666 pnl.Leave += SearchControls_Leave;
4669 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4670 cmb.Dock = DockStyle.Fill;
4671 cmb.Name = "comboSearch";
4672 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4673 cmb.ImeMode = ImeMode.NoControl;
4674 cmb.TabStop = false;
4675 cmb.AutoCompleteMode = AutoCompleteMode.None;
4676 cmb.KeyDown += SearchComboBox_KeyDown;
4679 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4680 cmbLang.Dock = DockStyle.Right;
4682 cmbLang.Name = "comboLang";
4683 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4684 cmbLang.TabStop = false;
4685 cmbLang.Items.Add("");
4686 cmbLang.Items.Add("ja");
4687 cmbLang.Items.Add("en");
4688 cmbLang.Items.Add("ar");
4689 cmbLang.Items.Add("da");
4690 cmbLang.Items.Add("nl");
4691 cmbLang.Items.Add("fa");
4692 cmbLang.Items.Add("fi");
4693 cmbLang.Items.Add("fr");
4694 cmbLang.Items.Add("de");
4695 cmbLang.Items.Add("hu");
4696 cmbLang.Items.Add("is");
4697 cmbLang.Items.Add("it");
4698 cmbLang.Items.Add("no");
4699 cmbLang.Items.Add("pl");
4700 cmbLang.Items.Add("pt");
4701 cmbLang.Items.Add("ru");
4702 cmbLang.Items.Add("es");
4703 cmbLang.Items.Add("sv");
4704 cmbLang.Items.Add("th");
4706 lbl.Text = "Search(C-S-f)";
4707 lbl.Name = "label1";
4708 lbl.Dock = DockStyle.Left;
4710 lbl.Height = cmb.Height;
4711 lbl.TextAlign = ContentAlignment.MiddleLeft;
4713 btn.Text = "Search";
4714 btn.Name = "buttonSearch";
4715 btn.UseVisualStyleBackColor = true;
4716 btn.Dock = DockStyle.Right;
4717 btn.TabStop = false;
4718 btn.Click += SearchButton_Click;
4721 if (_statuses.Tabs.TryGetValue(tabName, out tab))
4723 if (!string.IsNullOrEmpty(tab.SearchWords))
4725 cmb.Items.Add(tab.SearchWords);
4726 cmb.Text = tab.SearchWords;
4729 cmbLang.Text = tab.SearchLang;
4732 _tabPage.Controls.Add(pnl);
4736 _tabPage.Tag = _listCustom;
4737 this.ListTab.Controls.Add(_tabPage);
4739 _tabPage.Location = new Point(4, 4);
4740 _tabPage.Name = "CTab" + cnt.ToString();
4741 _tabPage.Size = new Size(380, 260);
4742 _tabPage.TabIndex = 2 + cnt;
4743 _tabPage.Text = tabName;
4744 _tabPage.UseVisualStyleBackColor = true;
4745 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4747 _listCustom.AllowColumnReorder = true;
4748 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4749 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4750 _listCustom.Dock = DockStyle.Fill;
4751 _listCustom.FullRowSelect = true;
4752 _listCustom.HideSelection = false;
4753 _listCustom.Location = new Point(0, 0);
4754 _listCustom.Margin = new Padding(0);
4755 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4756 _listCustom.ShowItemToolTips = true;
4757 _listCustom.Size = new Size(380, 260);
4758 _listCustom.UseCompatibleStateImageBehavior = false;
4759 _listCustom.View = View.Details;
4760 _listCustom.OwnerDraw = true;
4761 _listCustom.VirtualMode = true;
4762 _listCustom.Font = _fntReaded;
4763 _listCustom.BackColor = _clListBackcolor;
4765 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4766 _listCustom.AllowDrop = true;
4768 _listCustom.SmallImageList = _listViewImageList;
4770 InitColumns(_listCustom, startup);
4772 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4773 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4774 _listCustom.ColumnClick += MyList_ColumnClick;
4775 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4776 _listCustom.DragDrop += TweenMain_DragDrop;
4777 _listCustom.DragEnter += TweenMain_DragEnter;
4778 _listCustom.DragOver += TweenMain_DragOver;
4779 _listCustom.DrawItem += MyList_DrawItem;
4780 _listCustom.MouseClick += MyList_MouseClick;
4781 _listCustom.ColumnReordered += MyList_ColumnReordered;
4782 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4783 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4784 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4785 _listCustom.DrawSubItem += MyList_DrawSubItem;
4786 _listCustom.HScrolled += MyList_HScrolled;
4792 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4794 var tabInfo = _statuses.GetTabByName(TabName);
4795 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4799 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4800 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4801 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4807 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4808 if (_tabPage == null) return false;
4810 SetListProperty(); //他のタブに列幅等を反映
4813 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4814 _tabPage.Tag = null;
4816 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4817 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4818 using (ControlTransaction.Layout(this.SplitContainer1, false))
4819 using (ControlTransaction.Layout(this.ListTab, false))
4820 using (ControlTransaction.Layout(this))
4821 using (ControlTransaction.Layout(_tabPage, false))
4823 if (this.ListTab.SelectedTab == _tabPage)
4825 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4826 this._beforeSelectedTab = null;
4828 this.ListTab.Controls.Remove(_tabPage);
4831 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4833 using (Control label = _tabPage.Controls["labelUser"])
4835 _tabPage.Controls.Remove(label);
4838 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4840 using (Control pnl = _tabPage.Controls["panelSearch"])
4842 pnl.Enter -= SearchControls_Enter;
4843 pnl.Leave -= SearchControls_Leave;
4844 _tabPage.Controls.Remove(pnl);
4846 foreach (Control ctrl in pnl.Controls)
4848 if (ctrl.Name == "buttonSearch")
4850 ctrl.Click -= SearchButton_Click;
4852 else if (ctrl.Name == "comboSearch")
4854 ctrl.KeyDown -= SearchComboBox_KeyDown;
4856 pnl.Controls.Remove(ctrl);
4862 _tabPage.Controls.Remove(_listCustom);
4864 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4865 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4866 _listCustom.ColumnClick -= MyList_ColumnClick;
4867 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4868 _listCustom.DragDrop -= TweenMain_DragDrop;
4869 _listCustom.DragEnter -= TweenMain_DragEnter;
4870 _listCustom.DragOver -= TweenMain_DragOver;
4871 _listCustom.DrawItem -= MyList_DrawItem;
4872 _listCustom.MouseClick -= MyList_MouseClick;
4873 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4874 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4875 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4876 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4877 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4878 _listCustom.HScrolled -= MyList_HScrolled;
4880 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4881 _listCustom.Columns.Clear();
4882 cols.ForEach(col => col.Dispose());
4885 _listCustom.ContextMenuStrip = null;
4886 _listCustom.ColumnHeaderContextMenuStrip = null;
4887 _listCustom.Font = null;
4889 _listCustom.SmallImageList = null;
4890 _listCustom.ListViewItemSorter = null;
4893 if (_curTab.Equals(_tabPage))
4900 this.PurgeListViewItemCache();
4904 _listCustom.Dispose();
4905 _statuses.RemoveTab(TabName);
4907 foreach (TabPage tp in ListTab.TabPages)
4909 DetailsListView lst = (DetailsListView)tp.Tag;
4910 var count = _statuses.Tabs[tp.Text].AllCount;
4911 if (lst.VirtualListSize != count)
4913 lst.VirtualListSize = count;
4920 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4922 this.PurgeListViewItemCache();
4923 _beforeSelectedTab = e.TabPage;
4926 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4930 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4933 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4934 if (!dragEnableRectangle.Contains(e.Location))
4936 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4937 tn = ListTab.SelectedTab.Text;
4940 if (string.IsNullOrEmpty(tn)) return;
4942 foreach (TabPage tb in ListTab.TabPages)
4946 ListTab.DoDragDrop(tb, DragDropEffects.All);
4956 Point cpos = new Point(e.X, e.Y);
4957 for (int i = 0; i < ListTab.TabPages.Count; i++)
4959 Rectangle rect = ListTab.GetTabRect(i);
4960 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4961 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4963 _rclickTabName = ListTab.TabPages[i].Text;
4969 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4971 //_curList.Refresh();
4972 SetMainWindowTitle();
4973 SetStatusLabelUrl();
4974 SetApiStatusLabel();
4975 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4976 TabMenuControl(ListTab.SelectedTab.Text);
4977 this.PushSelectPostChain();
4978 await DispSelectedPost();
4981 private void SetListProperty()
4983 //削除などで見つからない場合は処理せず
4984 if (_curList == null) return;
4985 if (!_isColumnChanged) return;
4987 int[] dispOrder = new int[_curList.Columns.Count];
4988 for (int i = 0; i < _curList.Columns.Count; i++)
4990 for (int j = 0; j < _curList.Columns.Count; j++)
4992 if (_curList.Columns[j].DisplayIndex == i)
5001 foreach (TabPage tb in ListTab.TabPages)
5003 if (!tb.Equals(_curTab))
5005 if (tb.Tag != null && tb.Controls.Count > 0)
5007 DetailsListView lst = (DetailsListView)tb.Tag;
5008 for (int i = 0; i < lst.Columns.Count; i++)
5010 lst.Columns[dispOrder[i]].DisplayIndex = i;
5011 lst.Columns[i].Width = _curList.Columns[i].Width;
5017 _isColumnChanged = false;
5020 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
5024 if (PostBrowser.StatusText.StartsWith("http") || PostBrowser.StatusText.StartsWith("ftp")
5025 || PostBrowser.StatusText.StartsWith("data"))
5027 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
5029 if (string.IsNullOrEmpty(PostBrowser.StatusText))
5031 SetStatusLabelUrl();
5039 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
5041 if (e.KeyChar == '@')
5043 if (!this._cfgCommon.UseAtIdSupplement) return;
5045 int cnt = AtIdSupl.ItemCount;
5046 ShowSuplDialog(StatusText, AtIdSupl);
5047 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
5050 else if (e.KeyChar == '#')
5052 if (!this._cfgCommon.UseHashSupplement) return;
5053 ShowSuplDialog(StatusText, HashSupl);
5058 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
5060 ShowSuplDialog(owner, dialog, 0, "");
5063 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
5065 ShowSuplDialog(owner, dialog, offset, "");
5068 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
5070 dialog.StartsWith = startswith;
5077 dialog.ShowDialog();
5079 this.TopMost = this._cfgCommon.AlwaysTop;
5080 int selStart = owner.SelectionStart;
5083 if (dialog.DialogResult == DialogResult.OK)
5085 if (!string.IsNullOrEmpty(dialog.inputText))
5089 fHalf = owner.Text.Substring(0, selStart - offset);
5091 if (selStart < owner.Text.Length)
5093 eHalf = owner.Text.Substring(selStart);
5095 owner.Text = fHalf + dialog.inputText + eHalf;
5096 owner.SelectionStart = selStart + dialog.inputText.Length;
5103 fHalf = owner.Text.Substring(0, selStart);
5105 if (selStart < owner.Text.Length)
5107 eHalf = owner.Text.Substring(selStart);
5109 owner.Text = fHalf + eHalf;
5112 owner.SelectionStart = selStart;
5118 private void StatusText_KeyUp(object sender, KeyEventArgs e)
5121 if (!e.Alt && !e.Control && !e.Shift)
5123 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
5125 bool isSpace = false;
5126 foreach (char c in StatusText.Text.ToCharArray())
5128 if (c == ' ' || c == ' ')
5141 StatusText.Text = "";
5142 JumpUnreadMenuItem_Click(null, null);
5146 this.StatusText_TextChanged(null, null);
5149 private void StatusText_TextChanged(object sender, EventArgs e)
5152 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
5153 lblLen.Text = pLen.ToString();
5156 StatusText.ForeColor = Color.Red;
5160 StatusText.ForeColor = _clInputFont;
5162 if (string.IsNullOrEmpty(StatusText.Text))
5164 this.inReplyTo = null;
5169 /// ツイート投稿前のフッター付与などの前処理を行います
5171 private string FormatStatusText(string statusText)
5173 statusText = statusText.Replace("\r\n", "\n");
5175 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
5178 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
5181 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
5183 // 文中の全角スペースを半角スペース1個にする
5184 statusText = statusText.Replace(" ", " ");
5187 // DM の場合はこれ以降の処理を行わない
5188 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
5192 if (this._cfgCommon.PostShiftEnter)
5194 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5198 if (this.StatusText.Multiline)
5199 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5201 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
5204 if (statusText.Contains("RT @"))
5205 disableFooter = true;
5210 var hashtag = this.HashMgr.UseHash;
5211 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
5214 header = HashMgr.UseHash + " ";
5216 footer = " " + HashMgr.UseHash;
5221 if (this._cfgLocal.UseRecommendStatus)
5224 footer += this.recommendedStatusFooter;
5226 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
5228 // テキストボックスに入力されている文字列を使用する
5229 footer += " " + this._cfgLocal.StatusText.Trim();
5233 statusText = header + statusText + footer;
5239 /// 投稿欄に表示する入力可能な文字数を計算します
5241 private int GetRestStatusCount(string statusText)
5244 var remainCount = this.tw.GetTextLengthRemain(statusText);
5246 if (this.ImageSelector.Visible && !string.IsNullOrEmpty(this.ImageSelector.ServiceName))
5248 remainCount -= this.tw.Configuration.CharactersReservedPerMedia;
5254 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5256 if (sender != this._curList)
5259 var listCache = this._listItemCache;
5260 if (listCache != null && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
5262 // If the newly requested cache is a subset of the old cache,
5263 // no need to rebuild everything, so do nothing.
5267 // Now we need to rebuild the cache.
5268 this.CreateCache(e.StartIndex, e.EndIndex);
5271 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5273 var listCache = this._listItemCache;
5274 if (listCache != null && listCache.TargetList == sender)
5277 PostClass cacheItemPost;
5278 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
5285 // A cache miss, so create a new ListViewItem and pass it back.
5286 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5289 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
5293 // 不正な要求に対する間に合わせの応答
5294 string[] sitem = {"", "", "", "", "", "", "", ""};
5295 e.Item = new ImageListViewItem(sitem);
5299 private void CreateCache(int startIndex, int endIndex)
5301 var tabInfo = this._statuses.Tabs[this._curTab.Text];
5303 // キャッシュ要求(要求範囲±30を作成)
5304 startIndex = Math.Max(startIndex - 30, 0);
5305 endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
5307 var cacheLength = endIndex - startIndex + 1;
5309 var posts = tabInfo[startIndex, endIndex]; //配列で取得
5310 var listItems = Enumerable.Range(0, cacheLength)
5311 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
5314 var listCache = new ListViewItemCache
5316 TargetList = this._curList,
5317 StartIndex = startIndex,
5318 EndIndex = endIndex,
5320 ListItem = listItems,
5323 Interlocked.Exchange(ref this._listItemCache, listCache);
5327 /// DetailsListView のための ListViewItem のキャッシュを消去する
5329 private void PurgeListViewItemCache()
5331 Interlocked.Exchange(ref this._listItemCache, null);
5334 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5336 StringBuilder mk = new StringBuilder();
5337 //if (Post.IsDeleted) mk.Append("×");
5338 //if (Post.IsMark) mk.Append("♪");
5339 //if (Post.IsProtect) mk.Append("Ю");
5340 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5341 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5342 ImageListViewItem itm;
5343 if (Post.RetweetedId == null)
5345 string[] sitem= {"",
5347 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5348 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5353 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5357 string[] sitem = {"",
5359 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5360 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5361 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5365 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5367 itm.StateIndex = Post.StateIndex;
5369 bool read = Post.IsRead;
5370 //未読管理していなかったら既読として扱う
5371 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5372 ChangeItemStyleRead(read, itm, Post, null);
5373 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5378 /// 全てのタブの振り分けルールを反映し直します
5380 private void ApplyPostFilters()
5382 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5384 this.PurgeListViewItemCache();
5385 this._curPost = null;
5386 this._curItemIndex = -1;
5387 this._statuses.FilterAll();
5389 foreach (TabPage tabPage in this.ListTab.TabPages)
5391 var tab = this._statuses.Tabs[tabPage.Text];
5393 var listview = (DetailsListView)tabPage.Tag;
5394 using (ControlTransaction.Update(listview))
5396 listview.VirtualListSize = tab.AllCount;
5399 if (this._cfgCommon.TabIconDisp)
5401 if (tab.UnreadCount > 0)
5402 tabPage.ImageIndex = 0;
5404 tabPage.ImageIndex = -1;
5408 if (!this._cfgCommon.TabIconDisp)
5409 this.ListTab.Refresh();
5411 SetMainWindowTitle();
5412 SetStatusLabelUrl();
5416 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5418 e.DrawDefault = true;
5421 private void MyList_HScrolled(object sender, EventArgs e)
5423 DetailsListView listView = (DetailsListView)sender;
5427 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5429 if (e.State == 0) return;
5430 e.DrawDefault = false;
5432 SolidBrush brs2 = null;
5433 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5435 if (e.Item.BackColor == _clSelf)
5436 brs2 = _brsBackColorMine;
5437 else if (e.Item.BackColor == _clAtSelf)
5438 brs2 = _brsBackColorAt;
5439 else if (e.Item.BackColor == _clTarget)
5440 brs2 = _brsBackColorYou;
5441 else if (e.Item.BackColor == _clAtTarget)
5442 brs2 = _brsBackColorAtYou;
5443 else if (e.Item.BackColor == _clAtFromTarget)
5444 brs2 = _brsBackColorAtFromTarget;
5445 else if (e.Item.BackColor == _clAtTo)
5446 brs2 = _brsBackColorAtTo;
5448 brs2 = _brsBackColorNone;
5453 if (((Control)sender).Focused)
5454 brs2 = _brsHighLight;
5456 brs2 = _brsDeactiveSelection;
5458 e.Graphics.FillRectangle(brs2, e.Bounds);
5459 e.DrawFocusRectangle();
5460 this.DrawListViewItemIcon(e);
5463 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5465 if (e.ItemState == 0) return;
5467 if (e.ColumnIndex > 0)
5470 RectangleF rct = e.Bounds;
5471 rct.Width = e.Header.Width;
5472 int fontHeight = e.Item.Font.Height;
5475 rct.Y += fontHeight;
5476 rct.Height -= fontHeight;
5480 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5482 //if (heightDiff > fontHeight * 0.7)
5484 // rct.Height += fontHeight;
5485 // drawLineCount += 1;
5488 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5489 if (!_iconCol && drawLineCount <= 1)
5491 //rct.Inflate(0, heightDiff / -2);
5492 //rct.Height += fontHeight / 2;
5494 else if (heightDiff < fontHeight * 0.7)
5496 //最終行が70%以上欠けていたら、最終行は表示しない
5497 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5498 rct.Height = (fontHeight * drawLineCount) - 1;
5505 //if (!_iconCol && drawLineCount > 1)
5507 // rct.Y += fontHeight * 0.2;
5508 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5513 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5514 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5519 Rectangle rctB = e.Bounds;
5520 rctB.Width = e.Header.Width;
5521 rctB.Height = fontHeight;
5523 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5525 TextRenderer.DrawText(e.Graphics,
5526 e.Item.SubItems[2].Text,
5528 Rectangle.Round(rct),
5530 TextFormatFlags.WordBreak |
5531 TextFormatFlags.EndEllipsis |
5532 TextFormatFlags.GlyphOverhangPadding |
5533 TextFormatFlags.NoPrefix);
5534 TextRenderer.DrawText(e.Graphics,
5535 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 + "]",
5539 TextFormatFlags.SingleLine |
5540 TextFormatFlags.EndEllipsis |
5541 TextFormatFlags.GlyphOverhangPadding |
5542 TextFormatFlags.NoPrefix);
5545 else if (drawLineCount == 1)
5547 TextRenderer.DrawText(e.Graphics,
5550 Rectangle.Round(rct),
5552 TextFormatFlags.SingleLine |
5553 TextFormatFlags.EndEllipsis |
5554 TextFormatFlags.GlyphOverhangPadding |
5555 TextFormatFlags.NoPrefix |
5556 TextFormatFlags.VerticalCenter);
5560 TextRenderer.DrawText(e.Graphics,
5563 Rectangle.Round(rct),
5565 TextFormatFlags.WordBreak |
5566 TextFormatFlags.EndEllipsis |
5567 TextFormatFlags.GlyphOverhangPadding |
5568 TextFormatFlags.NoPrefix);
5570 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5575 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5577 if (_iconSz == 0) return;
5579 ImageListViewItem item = (ImageListViewItem)e.Item;
5581 //e.Bounds.Leftが常に0を指すから自前で計算
5582 Rectangle itemRect = item.Bounds;
5583 var col0 = e.Item.ListView.Columns[0];
5584 itemRect.Width = col0.Width;
5586 if (col0.DisplayIndex > 0)
5588 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5590 if (clm.DisplayIndex < col0.DisplayIndex)
5591 itemRect.X += clm.Width;
5595 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5596 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5597 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5600 var img = item.Image;
5603 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5604 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5606 if (iconRect.Width > 0)
5608 e.Graphics.FillRectangle(Brushes.White, iconRect);
5609 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5612 e.Graphics.DrawImage(img.Image, iconRect);
5614 catch (ArgumentException)
5616 item.RefreshImageAsync();
5622 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5623 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5625 item.GetImageAsync();
5628 if (item.StateIndex > -1)
5630 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5631 if (stateRect.Width > 0)
5633 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5634 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5635 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5640 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5642 base.ScaleControl(factor, specified);
5644 ScaleChildControl(this.TabImage, factor);
5646 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5647 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5649 foreach (var listview in listviews)
5651 ScaleChildControl(listview, factor);
5655 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5657 // ImageListViewItem item = (ImageListViewItem)e.Item;
5658 // if (item.StateImageIndex > -1)
5660 // ////e.Bounds.Leftが常に0を指すから自前で計算
5661 // //Rectangle itemRect = item.Bounds;
5662 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5664 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5666 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5668 // // itemRect.X += clm.Width;
5672 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5673 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5675 // if (rct.Width > 0)
5677 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5678 // //e.Graphics.FillRectangle(Brushes.White, rct);
5679 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5680 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5685 private void DoTabSearch(string _word,
5695 if (_curList.VirtualListSize == 0)
5697 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5700 if (_curList.SelectedIndices.Count > 0)
5702 cidx = _curList.SelectedIndices[0];
5704 toIdx = _curList.VirtualListSize;
5708 case SEARCHTYPE.DialogSearch: //ダイアログからの検索
5709 if (_curList.SelectedIndices.Count > 0)
5710 cidx = _curList.SelectedIndices[0];
5714 case SEARCHTYPE.NextSearch: //次を検索
5715 if (_curList.SelectedIndices.Count > 0)
5717 cidx = _curList.SelectedIndices[0] + 1;
5718 if (cidx > toIdx) cidx = toIdx;
5725 case SEARCHTYPE.PrevSearch: //前を検索
5726 if (_curList.SelectedIndices.Count > 0)
5728 cidx = _curList.SelectedIndices[0] - 1;
5729 if (cidx < 0) cidx = 0;
5740 RegexOptions regOpt = RegexOptions.None;
5741 StringComparison fndOpt = StringComparison.Ordinal;
5744 regOpt = RegexOptions.IgnoreCase;
5745 fndOpt = StringComparison.OrdinalIgnoreCase;
5756 _search = new Regex(_word, regOpt);
5757 for (int idx = cidx; idx != toIdx; idx += stp)
5762 post = _statuses.Tabs[_curTab.Text][idx];
5768 if (_search.IsMatch(post.Nickname)
5769 || _search.IsMatch(post.TextFromApi)
5770 || _search.IsMatch(post.ScreenName))
5772 SelectListItem(_curList, idx);
5773 _curList.EnsureVisible(idx);
5778 catch (ArgumentException)
5780 MessageBox.Show(Properties.Resources.DoTabSearchText1, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
5787 for (int idx = cidx; idx != toIdx; idx += stp)
5792 post = _statuses.Tabs[_curTab.Text][idx];
5798 if (post.Nickname.IndexOf(_word, fndOpt) > -1
5799 || post.TextFromApi.IndexOf(_word, fndOpt) > -1
5800 || post.ScreenName.IndexOf(_word, fndOpt) > -1)
5802 SelectListItem(_curList, idx);
5803 _curList.EnsureVisible(idx);
5813 case SEARCHTYPE.DialogSearch:
5814 case SEARCHTYPE.NextSearch:
5818 case SEARCHTYPE.PrevSearch:
5820 cidx = _curList.VirtualListSize - 1;
5827 catch (ArgumentOutOfRangeException)
5830 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5833 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5836 this.ShowSearchDialog();
5839 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5841 var previousSearch = this.SearchDialog.ResultOptions;
5842 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5844 this.SearchDialog.Reset();
5845 this.ShowSearchDialog();
5851 previousSearch.Query,
5852 previousSearch.CaseSensitive,
5853 previousSearch.UseRegex,
5854 SEARCHTYPE.NextSearch);
5857 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5859 var previousSearch = this.SearchDialog.ResultOptions;
5860 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5862 this.SearchDialog.Reset();
5863 this.ShowSearchDialog();
5869 previousSearch.Query,
5870 previousSearch.CaseSensitive,
5871 previousSearch.UseRegex,
5872 SEARCHTYPE.PrevSearch);
5876 /// 検索ダイアログを表示し、検索を実行します
5878 private void ShowSearchDialog()
5880 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5882 this.TopMost = this._cfgCommon.AlwaysTop;
5885 this.TopMost = this._cfgCommon.AlwaysTop;
5887 var searchOptions = this.SearchDialog.ResultOptions;
5888 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5890 if (searchOptions.NewTab)
5892 var tabName = Properties.Resources.SearchResults_TabName;
5896 tabName = this._statuses.MakeTabName(tabName);
5898 catch (TabException ex)
5900 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5903 this.AddNewTab(tabName, false, MyCommon.TabUsageType.SearchResults);
5904 this._statuses.AddTab(tabName, MyCommon.TabUsageType.SearchResults, null);
5906 var filter = new PostFilterRule
5908 FilterBody = new[] { searchOptions.Query },
5909 UseRegex = searchOptions.UseRegex,
5910 CaseSensitive = searchOptions.CaseSensitive,
5913 var targetTab = this._statuses.Tabs[this._curTab.Text];
5914 var posts = targetTab.Posts.Values
5915 .Where(x => filter.ExecFilter(x) == MyCommon.HITRESULT.CopyAndMark)
5916 .Where(x => targetTab.Contains(x.StatusId));
5918 var resultTab = this._statuses.Tabs[tabName];
5919 foreach (var post in posts)
5921 resultTab.AddPostToInnerStorage(post);
5924 this._statuses.DistributePosts();
5925 this.RefreshTimeline();
5927 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5928 .First(x => x.Text == tabName);
5930 this.ListTab.SelectedTab = tabPage;
5935 searchOptions.Query,
5936 searchOptions.CaseSensitive,
5937 searchOptions.UseRegex,
5938 SEARCHTYPE.DialogSearch);
5941 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5943 this.AddNewTabForSearch(searchOptions.Query);
5947 private void AboutMenuItem_Click(object sender, EventArgs e)
5949 using (TweenAboutBox about = new TweenAboutBox())
5951 about.ShowDialog(this);
5953 this.TopMost = this._cfgCommon.AlwaysTop;
5956 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5958 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5960 DetailsListView lst = null;
5962 if (ImageSelector.Enabled)
5966 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5969 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5972 ListTab.SelectedIndex = i;
5973 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5974 //_curTab = ListTab.TabPages[i];
5979 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5980 if (idx == -1 && bgnIdx > 0)
5982 for (int i = 0; i < bgnIdx; i++)
5984 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5987 ListTab.SelectedIndex = i;
5988 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5989 //_curTab = ListTab.TabPages[i];
5995 //全部調べたが未読見つからず→先頭タブの最新発言へ
5998 ListTab.SelectedIndex = 0;
5999 lst = (DetailsListView)ListTab.TabPages[0].Tag;
6000 //_curTab = ListTab.TabPages[0];
6001 if (_statuses.SortOrder == SortOrder.Ascending)
6002 idx = lst.VirtualListSize - 1;
6007 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
6009 SelectListItem(lst, idx);
6010 if (_statuses.SortMode == ComparerMode.Id)
6012 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
6013 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
6019 lst.EnsureVisible(idx);
6024 lst.EnsureVisible(idx);
6030 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
6032 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
6034 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6035 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
6039 private async void FavorareMenuItem_Click(object sender, EventArgs e)
6041 if (_curList.SelectedIndices.Count > 0)
6043 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6044 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
6048 private async void VerUpMenuItem_Click(object sender, EventArgs e)
6050 await this.CheckNewVersion(false);
6053 private void RunTweenUp()
6055 ProcessStartInfo pinfo = new ProcessStartInfo();
6056 pinfo.UseShellExecute = true;
6057 pinfo.WorkingDirectory = MyCommon.settingPath;
6058 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
6059 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
6062 Process.Start(pinfo);
6066 MessageBox.Show("Failed to execute TweenUp3.exe.");
6070 public class VersionInfo
6072 public Version Version { get; set; }
6073 public Uri DownloadUri { get; set; }
6074 public string ReleaseNote { get; set; }
6078 /// OpenTween の最新バージョンの情報を取得します
6080 public async Task<VersionInfo> GetVersionInfoAsync()
6082 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
6083 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
6085 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
6086 .ConfigureAwait(false);
6088 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
6089 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
6091 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
6092 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
6094 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
6096 return new VersionInfo
6098 Version = Version.Parse(msgHeader[0]),
6099 DownloadUri = new Uri(msgHeader[1]),
6100 ReleaseNote = msgBody,
6104 private async Task CheckNewVersion(bool startup = false)
6106 if (ApplicationSettings.VersionInfoUrl == null)
6107 return; // 更新チェック無効化
6111 var versionInfo = await this.GetVersionInfoAsync();
6113 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
6118 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
6119 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
6120 msgtext = MyCommon.ReplaceAppName(msgtext);
6122 MessageBox.Show(msgtext,
6123 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6124 MessageBoxButtons.OK, MessageBoxIcon.Information);
6129 using (var dialog = new UpdateDialog())
6131 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
6132 MyCommon.GetReadableVersion(versionInfo.Version));
6133 dialog.DetailsText = versionInfo.ReleaseNote;
6135 if (dialog.ShowDialog(this) == DialogResult.Yes)
6137 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
6143 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
6146 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
6147 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6148 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
6153 private async Task Colorize()
6156 await this.DispSelectedPost();
6157 //件数関連の場合、タイトル即時書き換え
6158 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
6159 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6160 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6161 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6163 SetMainWindowTitle();
6165 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6166 foreach (TabPage tb in ListTab.TabPages)
6168 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6170 if (this._cfgCommon.TabIconDisp)
6172 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6176 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
6179 public string createDetailHtml(string orgdata)
6181 if (this._cfgLocal.UseTwemoji)
6182 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
6184 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6187 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6189 if (sender.Equals(displayItem))
6191 this.ClearUserPicture();
6193 var img = displayItem.Image;
6197 img = await img.CloneAsync();
6199 UserPicture.Image = img;
6203 UserPicture.ShowErrorImage();
6208 private Task DispSelectedPost()
6210 return this.DispSelectedPost(false);
6213 private PostClass displayPost = new PostClass();
6216 /// サムネイル表示に使用する CancellationToken の生成元
6218 private CancellationTokenSource thumbnailTokenSource = null;
6220 private async Task DispSelectedPost(bool forceupdate)
6222 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6225 var oldDisplayPost = this.displayPost;
6226 this.displayPost = this._curPost;
6228 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6231 if (displayItem != null)
6233 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6236 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6237 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6239 using (ControlTransaction.Update(this.TableLayoutPanel1))
6241 SourceLinkLabel.Text = this._curPost.Source;
6242 SourceLinkLabel.Tag = this._curPost.SourceUri;
6243 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6249 nameText = "DM FROM <- ";
6251 nameText = "DM TO -> ";
6257 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6258 if (_curPost.RetweetedId != null)
6259 nameText += " (RT:" + _curPost.RetweetedBy + ")";
6261 NameLabel.Text = nameText;
6262 NameLabel.Tag = _curPost.ScreenName;
6264 var nameForeColor = SystemColors.ControlText;
6265 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6266 nameForeColor = this._clOWL;
6267 if (_curPost.RetweetedId != null)
6268 nameForeColor = this._clRetweet;
6270 nameForeColor = this._clFav;
6271 NameLabel.ForeColor = nameForeColor;
6273 this.ClearUserPicture();
6275 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6277 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6280 UserPicture.Image = image?.Clone();
6284 UserPicture.ShowErrorImage();
6288 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6291 if (DumpPostClassToolStripMenuItem.Checked)
6293 StringBuilder sb = new StringBuilder(512);
6295 sb.Append("-----Start PostClass Dump<br>");
6296 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
6297 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6298 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
6299 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
6300 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
6301 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
6302 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
6303 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
6304 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
6305 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
6306 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
6307 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
6308 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
6309 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
6310 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
6312 foreach (string nm in _curPost.ReplyToList)
6314 sb.AppendFormat("ReplyToList : {0}<br>", nm);
6317 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
6318 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
6319 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
6320 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
6321 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
6322 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
6323 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
6324 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
6325 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
6326 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
6328 sb.AppendFormat("Media.Count : {0}<br>", _curPost.Media.Count);
6329 if (_curPost.Media.Count > 0)
6331 for (int i = 0; i < _curPost.Media.Count; i++)
6333 var info = _curPost.Media[i];
6334 sb.AppendFormat("Media[{0}].Url : {1}<br>", i, info.Url);
6335 sb.AppendFormat("Media[{0}].VideoUrl : {1}<br>", i, info.VideoUrl ?? "---");
6338 sb.Append("-----End PostClass Dump<br>");
6340 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6344 var loadTasks = new List<Task>();
6346 // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6347 // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6348 if (_curPost.StatusId != oldDisplayPost.StatusId)
6350 using (ControlTransaction.Update(this.PostBrowser))
6352 this.PostBrowser.DocumentText =
6353 this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6355 this.PostBrowser.Document.Window.ScrollTo(0, 0);
6358 this.SplitContainer3.Panel2Collapsed = true;
6360 if (this._cfgCommon.PreviewEnable)
6362 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
6363 oldTokenSource?.Cancel();
6365 var token = this.thumbnailTokenSource.Token;
6366 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
6369 loadTasks.Add(this.AppendQuoteTweetAsync(this._curPost));
6374 await Task.WhenAll(loadTasks);
6376 catch (OperationCanceledException) { }
6380 /// 発言詳細欄のツイートURLを展開する
6382 private async Task AppendQuoteTweetAsync(PostClass post)
6384 var statusIds = post.QuoteStatusIds;
6385 if (statusIds.Length == 0)
6389 var loadingQuoteHtml = statusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText));
6390 var body = post.Text + string.Concat(loadingQuoteHtml);
6392 using (ControlTransaction.Update(this.PostBrowser))
6393 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6396 var quoteHtmls = await Task.WhenAll(statusIds.Select(x => this.CreateQuoteTweetHtml(x)));
6398 // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
6399 if (this._curPost != post || this._curPost.IsDeleted)
6402 body = post.Text + string.Concat(quoteHtmls);
6404 using (ControlTransaction.Update(this.PostBrowser))
6405 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6408 private async Task<string> CreateQuoteTweetHtml(long statusId)
6410 PostClass post = this._statuses[statusId];
6415 post = await Task.Run(() => this.tw.GetStatusApi(false, statusId))
6416 .ConfigureAwait(false);
6418 catch (WebApiException ex)
6420 return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode(ex.Message));
6424 if (!this._statuses.AddQuoteTweet(post))
6425 return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.");
6428 return FormatQuoteTweetHtml(post);
6431 internal static string FormatQuoteTweetHtml(PostClass post)
6433 var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
6434 " — " + WebUtility.HtmlEncode(post.Nickname) +
6435 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
6436 WebUtility.HtmlEncode(post.CreatedAt.ToString());
6438 return FormatQuoteTweetHtml(post.StatusId, innerHtml);
6441 internal static string FormatQuoteTweetHtml(long statusId, string innerHtml)
6443 return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
6444 "<blockquote class=\"quote-tweet\">" + innerHtml + "</blockquote>" +
6449 /// 指定されたHTMLからリンクを除去します
6451 internal static string StripLinkTagHtml(string html)
6453 // a 要素はネストされていない前提の正規表現パターン
6454 return Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1");
6457 private async void MatomeMenuItem_Click(object sender, EventArgs e)
6459 await this.OpenApplicationWebsite();
6462 private async Task OpenApplicationWebsite()
6464 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
6467 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6469 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
6472 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
6474 if (ListTab.SelectedTab != null)
6476 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6478 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6479 if (pnl.Controls["comboSearch"].Focused ||
6480 pnl.Controls["comboLang"].Focused ||
6481 pnl.Controls["buttonSearch"].Focused) return;
6484 if (e.Control || e.Shift || e.Alt)
6485 this._anchorFlag = false;
6488 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
6491 e.SuppressKeyPress = true;
6494 if (asyncTask != null)
6499 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
6501 private void InitializeShortcuts()
6503 this.shortcutCommands = new[]
6505 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6506 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
6507 .FocusedOn(FocusedControl.ListTab)
6508 .Do(() => SendKeys.Send("{DOWN}")),
6510 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
6511 .FocusedOn(FocusedControl.ListTab)
6512 .Do(() => SendKeys.Send("{UP}")),
6514 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
6515 .FocusedOn(FocusedControl.ListTab)
6516 .Do(() => SendKeys.Send("{PGDN}")),
6518 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
6519 .FocusedOn(FocusedControl.ListTab)
6520 .Do(() => SendKeys.Send("{PGUP}")),
6522 ShortcutCommand.Create(Keys.F1)
6523 .Do(() => this.OpenApplicationWebsite()),
6525 ShortcutCommand.Create(Keys.F3)
6526 .Do(() => this.MenuItemSearchNext_Click(null, null)),
6528 ShortcutCommand.Create(Keys.F5)
6529 .Do(() => this.DoRefresh()),
6531 ShortcutCommand.Create(Keys.F6)
6532 .Do(() => this.GetReplyAsync()),
6534 ShortcutCommand.Create(Keys.F7)
6535 .Do(() => this.GetDirectMessagesAsync()),
6537 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
6538 .NotFocusedOn(FocusedControl.StatusText)
6539 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
6541 ShortcutCommand.Create(Keys.G)
6542 .NotFocusedOn(FocusedControl.StatusText)
6543 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
6545 ShortcutCommand.Create(Keys.Right, Keys.N)
6546 .FocusedOn(FocusedControl.ListTab)
6547 .Do(() => this.GoRelPost(forward: true)),
6549 ShortcutCommand.Create(Keys.Left, Keys.P)
6550 .FocusedOn(FocusedControl.ListTab)
6551 .Do(() => this.GoRelPost(forward: false)),
6553 ShortcutCommand.Create(Keys.OemPeriod)
6554 .FocusedOn(FocusedControl.ListTab)
6555 .Do(() => this.GoAnchor()),
6557 ShortcutCommand.Create(Keys.I)
6558 .FocusedOn(FocusedControl.ListTab)
6559 .OnlyWhen(() => this.StatusText.Enabled)
6560 .Do(() => this.StatusText.Focus()),
6562 ShortcutCommand.Create(Keys.Enter)
6563 .FocusedOn(FocusedControl.ListTab)
6564 .Do(() => this.MakeReplyOrDirectStatus()),
6566 ShortcutCommand.Create(Keys.R)
6567 .FocusedOn(FocusedControl.ListTab)
6568 .Do(() => this.DoRefresh()),
6570 ShortcutCommand.Create(Keys.L)
6571 .FocusedOn(FocusedControl.ListTab)
6572 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
6574 ShortcutCommand.Create(Keys.H)
6575 .FocusedOn(FocusedControl.ListTab)
6576 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6578 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6579 .FocusedOn(FocusedControl.ListTab)
6580 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6582 ShortcutCommand.Create(Keys.S)
6583 .FocusedOn(FocusedControl.ListTab)
6584 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6586 ShortcutCommand.Create(Keys.A)
6587 .FocusedOn(FocusedControl.ListTab)
6588 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6590 // ] in_reply_to参照元へ戻る
6591 ShortcutCommand.Create(Keys.Oem4)
6592 .FocusedOn(FocusedControl.ListTab)
6593 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6595 // [ in_reply_toへジャンプ
6596 ShortcutCommand.Create(Keys.Oem6)
6597 .FocusedOn(FocusedControl.ListTab)
6598 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6600 ShortcutCommand.Create(Keys.Escape)
6601 .FocusedOn(FocusedControl.ListTab)
6603 this._anchorFlag = false;
6604 if (ListTab.SelectedTab != null)
6606 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6607 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6609 var relTp = ListTab.SelectedTab;
6610 RemoveSpecifiedTab(relTp.Text, false);
6616 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
6617 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
6618 .FocusedOn(FocusedControl.ListTab)
6619 .Do(() => this._anchorFlag = false, preventDefault: false),
6621 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6622 ShortcutCommand.Create(Keys.Up, Keys.Down)
6623 .FocusedOn(FocusedControl.PostBrowser)
6626 ShortcutCommand.Create(Keys.Control | Keys.R)
6627 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6629 ShortcutCommand.Create(Keys.Control | Keys.D)
6630 .Do(() => this.doStatusDelete()),
6632 ShortcutCommand.Create(Keys.Control | Keys.M)
6633 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6635 ShortcutCommand.Create(Keys.Control | Keys.S)
6636 .Do(() => this.FavoriteChange(FavAdd: true)),
6638 ShortcutCommand.Create(Keys.Control | Keys.I)
6639 .Do(() => this.doRepliedStatusOpen()),
6641 ShortcutCommand.Create(Keys.Control | Keys.Q)
6642 .Do(() => this.doQuoteOfficial()),
6644 ShortcutCommand.Create(Keys.Control | Keys.B)
6645 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6647 ShortcutCommand.Create(Keys.Control | Keys.T)
6648 .Do(() => this.HashManageMenuItem_Click(null, null)),
6650 ShortcutCommand.Create(Keys.Control | Keys.L)
6651 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6653 ShortcutCommand.Create(Keys.Control | Keys.Y)
6654 .NotFocusedOn(FocusedControl.PostBrowser)
6655 .Do(() => this.MultiLineMenuItem_Click(null, null)),
6657 ShortcutCommand.Create(Keys.Control | Keys.F)
6658 .Do(() => this.MenuItemSubSearch_Click(null, null)),
6660 ShortcutCommand.Create(Keys.Control | Keys.U)
6661 .Do(() => this.ShowUserTimeline()),
6663 ShortcutCommand.Create(Keys.Control | Keys.H)
6664 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6666 ShortcutCommand.Create(Keys.Control | Keys.G)
6667 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6669 ShortcutCommand.Create(Keys.Control | Keys.O)
6670 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6672 ShortcutCommand.Create(Keys.Control | Keys.E)
6673 .Do(() => this.OpenURLMenuItem_Click(null, null)),
6675 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6676 .FocusedOn(FocusedControl.ListTab)
6677 .Do(() => this._colorize = true, preventDefault: false),
6679 ShortcutCommand.Create(Keys.Control | Keys.N)
6680 .FocusedOn(FocusedControl.ListTab)
6681 .Do(() => this.GoNextTab(forward: true)),
6683 ShortcutCommand.Create(Keys.Control | Keys.P)
6684 .FocusedOn(FocusedControl.ListTab)
6685 .Do(() => this.GoNextTab(forward: false)),
6687 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6688 .FocusedOn(FocusedControl.ListTab)
6689 .Do(() => this.CopyStot()),
6691 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6692 ShortcutCommand.Create(Keys.Control | Keys.D1)
6693 .FocusedOn(FocusedControl.ListTab)
6694 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6695 .Do(() => this.ListTab.SelectedIndex = 0),
6697 ShortcutCommand.Create(Keys.Control | Keys.D2)
6698 .FocusedOn(FocusedControl.ListTab)
6699 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6700 .Do(() => this.ListTab.SelectedIndex = 1),
6702 ShortcutCommand.Create(Keys.Control | Keys.D3)
6703 .FocusedOn(FocusedControl.ListTab)
6704 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6705 .Do(() => this.ListTab.SelectedIndex = 2),
6707 ShortcutCommand.Create(Keys.Control | Keys.D4)
6708 .FocusedOn(FocusedControl.ListTab)
6709 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6710 .Do(() => this.ListTab.SelectedIndex = 3),
6712 ShortcutCommand.Create(Keys.Control | Keys.D5)
6713 .FocusedOn(FocusedControl.ListTab)
6714 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6715 .Do(() => this.ListTab.SelectedIndex = 4),
6717 ShortcutCommand.Create(Keys.Control | Keys.D6)
6718 .FocusedOn(FocusedControl.ListTab)
6719 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6720 .Do(() => this.ListTab.SelectedIndex = 5),
6722 ShortcutCommand.Create(Keys.Control | Keys.D7)
6723 .FocusedOn(FocusedControl.ListTab)
6724 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6725 .Do(() => this.ListTab.SelectedIndex = 6),
6727 ShortcutCommand.Create(Keys.Control | Keys.D8)
6728 .FocusedOn(FocusedControl.ListTab)
6729 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6730 .Do(() => this.ListTab.SelectedIndex = 7),
6732 ShortcutCommand.Create(Keys.Control | Keys.D9)
6733 .FocusedOn(FocusedControl.ListTab)
6734 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6736 ShortcutCommand.Create(Keys.Control | Keys.A)
6737 .FocusedOn(FocusedControl.StatusText)
6738 .Do(() => this.StatusText.SelectAll()),
6740 ShortcutCommand.Create(Keys.Control | Keys.V)
6741 .FocusedOn(FocusedControl.StatusText)
6742 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6744 ShortcutCommand.Create(Keys.Control | Keys.Up)
6745 .FocusedOn(FocusedControl.StatusText)
6747 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6749 var inReplyToStatusId = this.inReplyTo?.Item1;
6750 var inReplyToScreenName = this.inReplyTo?.Item2;
6751 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6754 if (_hisIdx < 0) _hisIdx = 0;
6756 var historyItem = this._history[this._hisIdx];
6757 StatusText.Text = historyItem.status;
6758 StatusText.SelectionStart = StatusText.Text.Length;
6759 if (historyItem.inReplyToId != null)
6760 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6762 this.inReplyTo = null;
6765 ShortcutCommand.Create(Keys.Control | Keys.Down)
6766 .FocusedOn(FocusedControl.StatusText)
6768 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6770 var inReplyToStatusId = this.inReplyTo?.Item1;
6771 var inReplyToScreenName = this.inReplyTo?.Item2;
6772 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6775 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6777 var historyItem = this._history[this._hisIdx];
6778 StatusText.Text = historyItem.status;
6779 StatusText.SelectionStart = StatusText.Text.Length;
6780 if (historyItem.inReplyToId != null)
6781 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6783 this.inReplyTo = null;
6786 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6787 .FocusedOn(FocusedControl.StatusText)
6789 if (ListTab.SelectedIndex == 0)
6791 ListTab.SelectedIndex = ListTab.TabCount - 1;
6795 ListTab.SelectedIndex -= 1;
6800 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6801 .FocusedOn(FocusedControl.StatusText)
6803 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6805 ListTab.SelectedIndex = 0;
6809 ListTab.SelectedIndex += 1;
6814 ShortcutCommand.Create(Keys.Control | Keys.Y)
6815 .FocusedOn(FocusedControl.PostBrowser)
6817 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6818 MultiLineMenuItem_Click(null, null);
6821 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6822 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6824 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6825 .Do(() => this.DoRefreshMore()),
6827 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6828 .Do(() => this.GetReplyAsync(loadMore: true)),
6830 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6831 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6833 ShortcutCommand.Create(Keys.Shift | Keys.R)
6834 .NotFocusedOn(FocusedControl.StatusText)
6835 .Do(() => this.DoRefreshMore()),
6837 ShortcutCommand.Create(Keys.Shift | Keys.H)
6838 .FocusedOn(FocusedControl.ListTab)
6839 .Do(() => this.GoTopEnd(GoTop: true)),
6841 ShortcutCommand.Create(Keys.Shift | Keys.L)
6842 .FocusedOn(FocusedControl.ListTab)
6843 .Do(() => this.GoTopEnd(GoTop: false)),
6845 ShortcutCommand.Create(Keys.Shift | Keys.M)
6846 .FocusedOn(FocusedControl.ListTab)
6847 .Do(() => this.GoMiddle()),
6849 ShortcutCommand.Create(Keys.Shift | Keys.G)
6850 .FocusedOn(FocusedControl.ListTab)
6851 .Do(() => this.GoLast()),
6853 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6854 .FocusedOn(FocusedControl.ListTab)
6855 .Do(() => this.MoveMiddle()),
6857 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6858 .FocusedOn(FocusedControl.ListTab)
6859 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6861 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6862 .FocusedOn(FocusedControl.ListTab)
6863 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6865 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6866 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6867 .FocusedOn(FocusedControl.ListTab)
6868 .Do(() => this.GoFav(forward: true)),
6870 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6871 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6872 .FocusedOn(FocusedControl.ListTab)
6873 .Do(() => this.GoFav(forward: false)),
6875 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6876 .FocusedOn(FocusedControl.ListTab)
6877 .Do(() => this.GoBackSelectPostChain()),
6879 ShortcutCommand.Create(Keys.Alt | Keys.R)
6880 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6882 ShortcutCommand.Create(Keys.Alt | Keys.P)
6883 .OnlyWhen(() => this._curPost != null)
6884 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6886 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6887 .Do(() => this.ScrollDownPostBrowser(forward: false)),
6889 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6890 .Do(() => this.ScrollDownPostBrowser(forward: true)),
6892 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6893 .Do(() => this.PageDownPostBrowser(forward: false)),
6895 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6896 .Do(() => this.PageDownPostBrowser(forward: true)),
6898 // 別タブの同じ書き込みへ(ALT+←/→)
6899 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6900 .FocusedOn(FocusedControl.ListTab)
6901 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6903 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6904 .FocusedOn(FocusedControl.ListTab)
6905 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6907 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6908 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6910 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6911 .Do(() => this.CopyIdUri()),
6913 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6914 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6915 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6916 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6918 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6919 .Do(() => this.FavoriteChange(FavAdd: false)),
6921 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6922 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6924 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6925 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6927 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6928 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6930 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6931 .Do(() => this.doMoveToRTHome()),
6933 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6934 .Do(() => this.FavorareMenuItem_Click(null, null)),
6936 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6937 .FocusedOn(FocusedControl.StatusText)
6939 if (_curList != null && _curList.VirtualListSize != 0 &&
6940 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6942 var idx = _curList.SelectedIndices[0] - 1;
6943 SelectListItem(_curList, idx);
6944 _curList.EnsureVisible(idx);
6948 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6949 .FocusedOn(FocusedControl.StatusText)
6951 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6952 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6954 var idx = _curList.SelectedIndices[0] + 1;
6955 SelectListItem(_curList, idx);
6956 _curList.EnsureVisible(idx);
6960 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6961 .FocusedOn(FocusedControl.StatusText)
6963 if (StatusText.SelectionStart > 0)
6965 int endidx = StatusText.SelectionStart - 1;
6966 string startstr = "";
6967 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6969 char c = StatusText.Text[i];
6970 if (Char.IsLetterOrDigit(c) || c == '_')
6976 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6977 int cnt = AtIdSupl.ItemCount;
6978 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6979 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6983 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6984 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6994 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6995 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6996 .FocusedOn(FocusedControl.ListTab)
6997 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6999 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
7000 .FocusedOn(FocusedControl.ListTab)
7001 .Do(() => this.SetSortColumnByDisplayIndex(1)),
7003 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
7004 .FocusedOn(FocusedControl.ListTab)
7005 .Do(() => this.SetSortColumnByDisplayIndex(2)),
7007 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
7008 .FocusedOn(FocusedControl.ListTab)
7009 .Do(() => this.SetSortColumnByDisplayIndex(3)),
7011 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
7012 .FocusedOn(FocusedControl.ListTab)
7013 .Do(() => this.SetSortColumnByDisplayIndex(4)),
7015 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
7016 .FocusedOn(FocusedControl.ListTab)
7017 .Do(() => this.SetSortColumnByDisplayIndex(5)),
7019 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
7020 .FocusedOn(FocusedControl.ListTab)
7021 .Do(() => this.SetSortColumnByDisplayIndex(6)),
7023 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
7024 .FocusedOn(FocusedControl.ListTab)
7025 .Do(() => this.SetSortColumnByDisplayIndex(7)),
7027 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
7028 .FocusedOn(FocusedControl.ListTab)
7029 .Do(() => this.SetSortLastColumn()),
7031 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
7032 .Do(() => this.FavoritesRetweetOfficial()),
7034 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
7035 .Do(() => this.FavoritesRetweetUnofficial()),
7037 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
7038 .Do(() => this.OpenUserAppointUrl()),
7040 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7041 .FocusedOn(FocusedControl.PostBrowser)
7042 .Do(() => this.doReTweetUnofficial()),
7044 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
7045 .OnlyWhen(() => this.ExistCurrentPost)
7046 .Do(() => this.doTranslation(_curPost.TextFromApi)),
7048 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7049 .Do(() => this.doReTweetUnofficial()),
7051 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
7052 .Do(() => this.CopyUserId()),
7054 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
7055 .Do(() => this.tweetThumbnail1.ScrollUp()),
7057 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
7058 .Do(() => this.tweetThumbnail1.ScrollDown()),
7060 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
7061 .FocusedOn(FocusedControl.ListTab)
7062 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
7063 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
7067 private bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
7069 // Task を返す非同期処理があれば asyncTask に代入する
7072 // ShortcutCommand に対応しているコマンドはここで処理される
7073 foreach (var command in this.shortcutCommands)
7075 if (command.IsMatch(keyData, focusedOn))
7077 asyncTask = command.RunCommand();
7078 return command.PreventDefault;
7085 private void ScrollDownPostBrowser(bool forward)
7087 var doc = PostBrowser.Document;
7088 if (doc == null) return;
7090 var tags = doc.GetElementsByTagName("html");
7094 tags[0].ScrollTop += this._fntDetail.Height;
7096 tags[0].ScrollTop -= this._fntDetail.Height;
7100 private void PageDownPostBrowser(bool forward)
7102 var doc = PostBrowser.Document;
7103 if (doc == null) return;
7105 var tags = doc.GetElementsByTagName("html");
7109 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7111 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7115 private void GoNextTab(bool forward)
7117 int idx = ListTab.SelectedIndex;
7121 if (idx > ListTab.TabPages.Count - 1) idx = 0;
7126 if (idx < 0) idx = ListTab.TabPages.Count - 1;
7128 ListTab.SelectedIndex = idx;
7131 private void CopyStot()
7134 StringBuilder sb = new StringBuilder();
7135 bool IsProtected = false;
7137 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7138 foreach (int idx in _curList.SelectedIndices)
7140 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7146 if (post.IsDeleted) continue;
7149 if (post.RetweetedId != null)
7150 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7152 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7156 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7161 MessageBox.Show(Properties.Resources.CopyStotText1);
7165 clstr = sb.ToString();
7168 Clipboard.SetDataObject(clstr, false, 5, 100);
7170 catch (Exception ex)
7172 MessageBox.Show(ex.Message);
7177 private void CopyIdUri()
7180 StringBuilder sb = new StringBuilder();
7181 if (this._curTab == null) return;
7182 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7183 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7184 foreach (int idx in _curList.SelectedIndices)
7186 var post = _statuses.Tabs[_curTab.Text][idx];
7187 sb.Append(MyCommon.GetStatusUrl(post));
7188 sb.Append(Environment.NewLine);
7192 clstr = sb.ToString();
7195 Clipboard.SetDataObject(clstr, false, 5, 100);
7197 catch (Exception ex)
7199 MessageBox.Show(ex.Message);
7204 private void GoFav(bool forward)
7206 if (_curList.VirtualListSize == 0) return;
7213 if (_curList.SelectedIndices.Count == 0)
7219 fIdx = _curList.SelectedIndices[0] + 1;
7220 if (fIdx > _curList.VirtualListSize - 1) return;
7222 toIdx = _curList.VirtualListSize;
7227 if (_curList.SelectedIndices.Count == 0)
7229 fIdx = _curList.VirtualListSize - 1;
7233 fIdx = _curList.SelectedIndices[0] - 1;
7234 if (fIdx < 0) return;
7240 for (int idx = fIdx; idx != toIdx; idx += stp)
7242 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
7244 SelectListItem(_curList, idx);
7245 _curList.EnsureVisible(idx);
7251 private void GoSamePostToAnotherTab(bool left)
7253 if (_curList.VirtualListSize == 0) return;
7259 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7260 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7262 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7267 if (ListTab.SelectedIndex == 0)
7273 fIdx = ListTab.SelectedIndex - 1;
7281 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7287 fIdx = ListTab.SelectedIndex + 1;
7289 toIdx = ListTab.TabCount;
7294 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7296 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7297 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7299 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
7301 ListTab.SelectedIndex = tabidx;
7302 SelectListItem(_curList, idx);
7303 _curList.EnsureVisible(idx);
7312 private void GoPost(bool forward)
7314 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7321 fIdx = _curList.SelectedIndices[0] + 1;
7322 if (fIdx > _curList.VirtualListSize - 1) return;
7323 toIdx = _curList.VirtualListSize;
7328 fIdx = _curList.SelectedIndices[0] - 1;
7329 if (fIdx < 0) return;
7335 if (_curPost.RetweetedId == null)
7337 name = _curPost.ScreenName;
7341 name = _curPost.RetweetedBy;
7343 for (int idx = fIdx; idx != toIdx; idx += stp)
7345 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
7347 if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
7349 SelectListItem(_curList, idx);
7350 _curList.EnsureVisible(idx);
7356 if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
7358 SelectListItem(_curList, idx);
7359 _curList.EnsureVisible(idx);
7366 private void GoRelPost(bool forward)
7368 if (_curList.SelectedIndices.Count == 0) return;
7375 fIdx = _curList.SelectedIndices[0] + 1;
7376 if (fIdx > _curList.VirtualListSize - 1) return;
7377 toIdx = _curList.VirtualListSize;
7382 fIdx = _curList.SelectedIndices[0] - 1;
7383 if (fIdx < 0) return;
7390 if (_curPost == null) return;
7391 _anchorPost = _curPost;
7396 if (_anchorPost == null) return;
7399 for (int idx = fIdx; idx != toIdx; idx += stp)
7401 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7402 if (post.ScreenName == _anchorPost.ScreenName ||
7403 post.RetweetedBy == _anchorPost.ScreenName ||
7404 post.ScreenName == _anchorPost.RetweetedBy ||
7405 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7406 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLower()) ||
7407 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLower()) ||
7408 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLower()) ||
7409 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLower()))
7411 SelectListItem(_curList, idx);
7412 _curList.EnsureVisible(idx);
7418 private void GoAnchor()
7420 if (_anchorPost == null) return;
7421 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7422 if (idx == -1) return;
7424 SelectListItem(_curList, idx);
7425 _curList.EnsureVisible(idx);
7428 private void GoTopEnd(bool GoTop)
7430 if (_curList.VirtualListSize == 0)
7438 _item = _curList.GetItemAt(0, 25);
7446 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7448 idx = _curList.VirtualListSize - 1;
7452 SelectListItem(_curList, idx);
7455 private void GoMiddle()
7457 if (_curList.VirtualListSize == 0)
7465 _item = _curList.GetItemAt(0, 0);
7475 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7478 idx2 = _curList.VirtualListSize - 1;
7484 idx3 = (idx1 + idx2) / 2;
7486 SelectListItem(_curList, idx3);
7489 private void GoLast()
7491 if (_curList.VirtualListSize == 0) return;
7493 if (_statuses.SortOrder == SortOrder.Ascending)
7495 SelectListItem(_curList, _curList.VirtualListSize - 1);
7496 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7500 SelectListItem(_curList, 0);
7501 _curList.EnsureVisible(0);
7505 private void MoveTop()
7507 if (_curList.SelectedIndices.Count == 0) return;
7508 int idx = _curList.SelectedIndices[0];
7509 if (_statuses.SortOrder == SortOrder.Ascending)
7511 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7515 _curList.EnsureVisible(0);
7517 _curList.EnsureVisible(idx);
7520 private async Task GoInReplyToPostTree()
7522 if (_curPost == null) return;
7524 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7526 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7530 var post = tw.GetStatusApi(false, _curPost.StatusId);
7532 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7533 _curPost.InReplyToUser = post.InReplyToUser;
7534 _curPost.IsReply = post.IsReply;
7535 this.PurgeListViewItemCache();
7536 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7538 catch (WebApiException ex)
7540 this.StatusLabel.Text = ex.Message;
7544 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7546 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7548 replyChains = new Stack<ReplyChain>();
7550 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7553 string inReplyToTabName;
7554 long inReplyToId = _curPost.InReplyToStatusId.Value;
7555 string inReplyToUser = _curPost.InReplyToUser;
7556 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7558 var inReplyToPosts = from tab in _statuses.Tabs.Values
7559 orderby tab != curTabClass
7560 from post in tab.Posts.Values
7561 where post.StatusId == inReplyToId
7562 let index = tab.IndexOf(post.StatusId)
7564 select new {Tab = tab, Index = index};
7566 var inReplyPost = inReplyToPosts.FirstOrDefault();
7567 if (inReplyPost == null)
7571 await Task.Run(() =>
7573 var post = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value);
7576 _statuses.AddPost(post);
7577 _statuses.DistributePosts();
7580 catch (WebApiException ex)
7582 this.StatusLabel.Text = ex.Message;
7583 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7587 this.RefreshTimeline();
7589 inReplyPost = inReplyToPosts.FirstOrDefault();
7590 if (inReplyPost == null)
7592 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7596 inReplyToTabName = inReplyPost.Tab.TabName;
7597 inReplyToIndex = inReplyPost.Index;
7599 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7600 DetailsListView listView = (DetailsListView)tabPage.Tag;
7602 if (_curTab != tabPage)
7604 this.ListTab.SelectTab(tabPage);
7607 this.SelectListItem(listView, inReplyToIndex);
7608 listView.EnsureVisible(inReplyToIndex);
7611 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7613 if (_curPost == null) return;
7615 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7616 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7620 if (_curPost.InReplyToStatusId != null)
7622 var posts = from t in _statuses.Tabs
7623 from p in t.Value.Posts
7624 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7625 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7627 orderby isForward ? indexOf : indexOf * -1
7628 orderby t.Value != curTabClass
7629 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7632 var postList = posts.ToList();
7633 for (int i = postList.Count - 1; i >= 0; i--)
7636 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7638 postList.RemoveAt(index);
7641 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7642 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7643 if (post == null) post = postList.First();
7644 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7645 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7646 SelectListItem(listView, post.Index);
7647 listView.EnsureVisible(post.Index);
7649 catch (InvalidOperationException)
7657 if (replyChains == null || replyChains.Count < 1)
7659 var posts = from t in _statuses.Tabs
7660 from p in t.Value.Posts
7661 where p.Value.InReplyToStatusId == _curPost.StatusId
7662 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7665 orderby t.Value != curTabClass
7666 select new {Tab = t.Value, Index = indexOf};
7669 var post = posts.First();
7670 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7671 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7672 SelectListItem(listView, post.Index);
7673 listView.EnsureVisible(post.Index);
7675 catch (InvalidOperationException)
7682 ReplyChain chainHead = replyChains.Pop();
7683 if (chainHead.InReplyToId == _curPost.StatusId)
7685 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7694 ListTab.SelectTab(chainHead.OriginalTab);
7700 SelectListItem(_curList, idx);
7701 _curList.EnsureVisible(idx);
7707 this.GoBackInReplyToPostTree(parallel);
7713 private void GoBackSelectPostChain()
7715 if (this.selectPostChains.Count > 1)
7724 this.selectPostChains.Pop();
7725 var tabPostPair = this.selectPostChains.Peek();
7727 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7729 if (tabPostPair.Item2 != null)
7731 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7732 if (idx == -1) continue; //該当ポストが存在しないので無視
7735 tp = tabPostPair.Item1;
7737 this.selectPostChains.Pop();
7739 catch (InvalidOperationException)
7745 while (this.selectPostChains.Count > 1);
7750 //履歴が残り1つであればクリアしておく
7751 if (this.selectPostChains.Count == 1)
7752 this.selectPostChains.Clear();
7756 DetailsListView lst = (DetailsListView)tp.Tag;
7757 this.ListTab.SelectedTab = tp;
7760 SelectListItem(lst, idx);
7761 lst.EnsureVisible(idx);
7767 private void PushSelectPostChain()
7769 int count = this.selectPostChains.Count;
7772 var p = this.selectPostChains.Peek();
7773 if (p.Item1 == this._curTab)
7775 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7776 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7779 if (count >= 2500) TrimPostChain();
7780 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7783 private void TrimPostChain()
7785 if (this.selectPostChains.Count <= 2000) return;
7786 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7787 for (int i = 0; i < 2000; i++)
7789 p.Push(this.selectPostChains.Pop());
7791 this.selectPostChains.Clear();
7792 for (int i = 0; i < 2000; i++)
7794 this.selectPostChains.Push(p.Pop());
7798 private bool GoStatus(long statusId)
7800 if (statusId == 0) return false;
7801 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7803 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7805 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7806 ListTab.SelectedIndex = tabidx;
7807 SelectListItem(_curList, idx);
7808 _curList.EnsureVisible(idx);
7815 private bool GoDirectMessage(long statusId)
7817 if (statusId == 0) return false;
7818 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7820 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7822 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7823 ListTab.SelectedIndex = tabidx;
7824 SelectListItem(_curList, idx);
7825 _curList.EnsureVisible(idx);
7832 private void MyList_MouseClick(object sender, MouseEventArgs e)
7834 _anchorFlag = false;
7837 private void StatusText_Enter(object sender, EventArgs e)
7839 // フォーカスの戻り先を StatusText に設定
7840 this.Tag = StatusText;
7841 StatusText.BackColor = _clInputBackcolor;
7844 public Color InputBackColor
7846 get { return _clInputBackcolor; }
7847 set { _clInputBackcolor = value; }
7850 private void StatusText_Leave(object sender, EventArgs e)
7852 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7853 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7854 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7857 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7860 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7863 e.SuppressKeyPress = true;
7866 this.StatusText_TextChanged(null, null);
7868 if (asyncTask != null)
7872 private void SaveConfigsAll(bool ifModified)
7876 SaveConfigsCommon();
7883 if (ModifySettingCommon) SaveConfigsCommon();
7884 if (ModifySettingLocal) SaveConfigsLocal();
7885 if (ModifySettingAtId) SaveConfigsAtId();
7889 private void SaveConfigsAtId()
7891 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7893 ModifySettingAtId = false;
7894 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7898 private void SaveConfigsCommon()
7900 if (_ignoreConfigSave) return;
7902 ModifySettingCommon = false;
7905 _cfgCommon.UserName = tw.Username;
7906 _cfgCommon.UserId = tw.UserId;
7907 _cfgCommon.Password = tw.Password;
7908 _cfgCommon.Token = tw.AccessToken;
7909 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7911 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7912 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7914 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7917 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7918 switch (_statuses.SortMode)
7920 case ComparerMode.Nickname: //ニックネーム
7921 _cfgCommon.SortColumn = 1;
7923 case ComparerMode.Data: //本文
7924 _cfgCommon.SortColumn = 2;
7926 case ComparerMode.Id: //時刻=発言Id
7927 _cfgCommon.SortColumn = 3;
7929 case ComparerMode.Name: //名前
7930 _cfgCommon.SortColumn = 4;
7932 case ComparerMode.Source: //Source
7933 _cfgCommon.SortColumn = 7;
7937 _cfgCommon.HashTags = HashMgr.HashHistories;
7938 if (HashMgr.IsPermanent)
7940 _cfgCommon.HashSelected = HashMgr.UseHash;
7944 _cfgCommon.HashSelected = "";
7946 _cfgCommon.HashIsHead = HashMgr.IsHead;
7947 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7948 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7949 if (ToolStripFocusLockMenuItem != null &&
7950 ToolStripFocusLockMenuItem.IsDisposed == false)
7952 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7954 _cfgCommon.TrackWord = tw.TrackWord;
7955 _cfgCommon.AllAtReply = tw.AllAtReply;
7956 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7957 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7963 private void SaveConfigsLocal()
7965 if (_ignoreConfigSave) return;
7968 ModifySettingLocal = false;
7969 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7970 _cfgLocal.FormSize = _mySize;
7971 _cfgLocal.FormLocation = _myLoc;
7972 _cfgLocal.SplitterDistance = _mySpDis;
7973 _cfgLocal.PreviewDistance = _mySpDis3;
7974 _cfgLocal.StatusMultiline = StatusText.Multiline;
7975 _cfgLocal.StatusTextHeight = _mySpDis2;
7977 _cfgLocal.FontUnread = _fntUnread;
7978 _cfgLocal.ColorUnread = _clUnread;
7979 _cfgLocal.FontRead = _fntReaded;
7980 _cfgLocal.ColorRead = _clReaded;
7981 _cfgLocal.FontDetail = _fntDetail;
7982 _cfgLocal.ColorDetail = _clDetail;
7983 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7984 _cfgLocal.ColorDetailLink = _clDetailLink;
7985 _cfgLocal.ColorFav = _clFav;
7986 _cfgLocal.ColorOWL = _clOWL;
7987 _cfgLocal.ColorRetweet = _clRetweet;
7988 _cfgLocal.ColorSelf = _clSelf;
7989 _cfgLocal.ColorAtSelf = _clAtSelf;
7990 _cfgLocal.ColorTarget = _clTarget;
7991 _cfgLocal.ColorAtTarget = _clAtTarget;
7992 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7993 _cfgLocal.ColorAtTo = _clAtTo;
7994 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7995 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7996 _cfgLocal.ColorInputFont = _clInputFont;
7997 _cfgLocal.FontInputFont = _fntInputFont;
7999 if (_ignoreConfigSave) return;
8004 private void SaveConfigsTabs()
8006 SettingTabs tabSetting = new SettingTabs();
8007 for (int i = 0; i < ListTab.TabPages.Count; i++)
8009 var tab = _statuses.Tabs[ListTab.TabPages[i].Text];
8010 if (tab.TabType != MyCommon.TabUsageType.Related && tab.TabType != MyCommon.TabUsageType.SearchResults)
8011 tabSetting.Tabs.Add(tab);
8013 tabSetting.Tabs.Add(this._statuses.GetTabByType(MyCommon.TabUsageType.Mute));
8017 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
8020 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
8021 if (ret != DialogResult.OK)
8024 var match = Twitter.StatusUrlRegex.Match(inputText);
8027 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
8028 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8034 var statusId = long.Parse(match.Groups["StatusId"].Value);
8035 await this.OpenRelatedTab(statusId);
8037 catch (TabException ex)
8039 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8043 private void SaveLogMenuItem_Click(object sender, EventArgs e)
8045 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8046 Properties.Resources.SaveLogMenuItem_ClickText2,
8047 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8048 if (rslt == DialogResult.Cancel) return;
8050 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8051 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8052 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8053 SaveFileDialog1.FilterIndex = 0;
8054 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8055 SaveFileDialog1.RestoreDirectory = true;
8057 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8059 if (!SaveFileDialog1.ValidateNames) return;
8060 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8062 if (rslt == DialogResult.Yes)
8065 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8067 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8068 string protect = "";
8069 if (post.IsProtect) protect = "Protect";
8070 sw.WriteLine(post.Nickname + "\t" +
8071 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8072 post.CreatedAt.ToString() + "\t" +
8073 post.ScreenName + "\t" +
8074 post.StatusId.ToString() + "\t" +
8075 post.ImageUrl + "\t" +
8076 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8082 foreach (int idx in _curList.SelectedIndices)
8084 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8085 string protect = "";
8086 if (post.IsProtect) protect = "Protect";
8087 sw.WriteLine(post.Nickname + "\t" +
8088 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8089 post.CreatedAt.ToString() + "\t" +
8090 post.ScreenName + "\t" +
8091 post.StatusId.ToString() + "\t" +
8092 post.ImageUrl + "\t" +
8093 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8099 this.TopMost = this._cfgCommon.AlwaysTop;
8102 private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8105 bool KeyRes = CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out asyncTask);
8108 e.IsInputKey = true;
8112 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
8114 var shortcut = (Shortcut)e.KeyData;
8117 case Shortcut.CtrlA:
8118 case Shortcut.CtrlC:
8119 case Shortcut.CtrlIns:
8123 // その他のショートカットキーは無効にする
8124 e.IsInputKey = true;
8130 if (asyncTask != null)
8133 public bool TabRename(ref string tabName)
8136 string newTabText = null;
8137 using (InputTabName inputName = new InputTabName())
8139 inputName.TabName = tabName;
8140 inputName.ShowDialog();
8141 if (inputName.DialogResult == DialogResult.Cancel) return false;
8142 newTabText = inputName.TabName;
8144 this.TopMost = this._cfgCommon.AlwaysTop;
8145 if (!string.IsNullOrEmpty(newTabText))
8148 for (int i = 0; i < ListTab.TabCount; i++)
8150 if (ListTab.TabPages[i].Text == newTabText)
8152 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8153 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8158 for (int i = 0; i < ListTab.TabCount; i++)
8160 if (ListTab.TabPages[i].Text == tabName)
8162 ListTab.TabPages[i].Text = newTabText;
8166 _statuses.RenameTab(tabName, newTabText);
8168 SaveConfigsCommon();
8170 _rclickTabName = newTabText;
8171 tabName = newTabText;
8180 private void ListTab_MouseClick(object sender, MouseEventArgs e)
8182 if (e.Button == MouseButtons.Middle)
8184 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8186 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8188 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8189 this.SaveConfigsTabs();
8196 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8198 string tn = ListTab.SelectedTab.Text;
8202 private void ListTab_MouseDown(object sender, MouseEventArgs e)
8204 if (this._cfgCommon.TabMouseLock) return;
8205 Point cpos = new Point(e.X, e.Y);
8206 if (e.Button == MouseButtons.Left)
8208 for (int i = 0; i < ListTab.TabPages.Count; i++)
8210 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8213 _tabMouseDownPoint = e.Location;
8224 private void ListTab_DragEnter(object sender, DragEventArgs e)
8226 if (e.Data.GetDataPresent(typeof(TabPage)))
8227 e.Effect = DragDropEffects.Move;
8229 e.Effect = DragDropEffects.None;
8232 private void ListTab_DragDrop(object sender, DragEventArgs e)
8234 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8239 Point cpos = new Point(e.X, e.Y);
8240 Point spos = ListTab.PointToClient(cpos);
8242 for (i = 0; i < ListTab.TabPages.Count; i++)
8244 Rectangle rect = ListTab.GetTabRect(i);
8245 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8246 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8248 tn = ListTab.TabPages[i].Text;
8249 if (spos.X <= (rect.Left + rect.Right) / 2)
8258 //タブのないところにドロップ->最後尾へ移動
8259 if (string.IsNullOrEmpty(tn))
8261 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8263 i = ListTab.TabPages.Count - 1;
8266 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8267 if (tp.Text == tn) return;
8269 ReOrderTab(tp.Text, tn, bef);
8272 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8274 var baseIndex = this.GetTabPageIndex(baseTabText);
8275 if (baseIndex == -1)
8278 var targetIndex = this.GetTabPageIndex(targetTabText);
8279 if (targetIndex == -1)
8282 using (ControlTransaction.Layout(this.ListTab))
8284 var mTp = this.ListTab.TabPages[targetIndex];
8285 this.ListTab.TabPages.Remove(mTp);
8287 if (targetIndex < baseIndex)
8290 if (isBeforeBaseTab)
8291 ListTab.TabPages.Insert(baseIndex, mTp);
8293 ListTab.TabPages.Insert(baseIndex + 1, mTp);
8299 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8301 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8302 //isReply:true=@,false=DM
8303 if (!StatusText.Enabled) return;
8304 if (_curList == null) return;
8305 if (_curTab == null) return;
8306 if (!this.ExistCurrentPost) return;
8308 // 複数あてリプライはReplyではなく通常ポスト
8309 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8310 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8311 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8313 if (_curList.SelectedIndices.Count > 0)
8316 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8319 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8322 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8323 StatusText.SelectionStart = StatusText.Text.Length;
8325 this.inReplyTo = null;
8328 if (string.IsNullOrEmpty(StatusText.Text))
8332 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8333 StatusText.Text = "@" + _curPost.ScreenName + " ";
8335 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8336 var inReplyToScreenName = this._curPost.ScreenName;
8337 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8345 //1件選んでEnter or DoubleClick
8346 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8348 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
8351 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8352 var inReplyToScreenName = this._curPost.ScreenName;
8353 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8357 if (!StatusText.Text.StartsWith("@"))
8360 if (StatusText.Text.StartsWith(". "))
8363 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8364 this.inReplyTo = null;
8369 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8370 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8371 var inReplyToScreenName = this._curPost.ScreenName;
8372 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8379 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8380 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8381 this.inReplyTo = null;
8386 //1件選んでCtrl-Rの場合(返信先操作せず)
8387 int sidx = StatusText.SelectionStart;
8388 string id = "@" + _curPost.ScreenName + " ";
8391 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8396 StatusText.Text = StatusText.Text.Insert(sidx, id);
8398 //if (StatusText.Text.StartsWith("@"))
8401 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8402 // sidx += 5 + _curPost.ScreenName.Length;
8407 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8408 // sidx += 3 + _curPost.ScreenName.Length;
8410 StatusText.SelectionStart = sidx;
8413 //_reply_to_name = null;
8421 if (!isAuto && !isReply) return;
8423 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8427 //Enter or DoubleClick
8429 string sTxt = StatusText.Text;
8430 if (!sTxt.StartsWith(". "))
8433 this.inReplyTo = null;
8435 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8437 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8438 if (!sTxt.Contains("@" + post.ScreenName + " "))
8440 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8441 //sTxt = "@" + post.ScreenName + " " + sTxt;
8444 StatusText.Text = sTxt;
8449 if (_curList.SelectedIndices.Count > 1)
8454 int sidx = StatusText.SelectionStart;
8455 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8457 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8458 if (!ids.Contains("@" + post.ScreenName + " ") &&
8459 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8461 ids += "@" + post.ScreenName + " ";
8465 foreach (string nm in post.ReplyToList)
8467 if (!ids.Contains("@" + nm + " ") &&
8468 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8470 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8472 ids += "@" + m.Result("${id}") + " ";
8474 ids += "@" + nm + " ";
8479 if (ids.Length == 0) return;
8480 if (!StatusText.Text.StartsWith(". "))
8482 StatusText.Text = ". " + StatusText.Text;
8484 this.inReplyTo = null;
8488 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8493 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8495 //if (StatusText.Text.StartsWith("@"))
8497 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8498 // sidx += 2 + ids.Length;
8502 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8503 // sidx += 1 + ids.Length;
8505 StatusText.SelectionStart = sidx;
8511 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8514 int sidx = StatusText.SelectionStart;
8515 PostClass post = _curPost;
8516 if (!ids.Contains("@" + post.ScreenName + " ") &&
8517 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8519 ids += "@" + post.ScreenName + " ";
8521 foreach (string nm in post.ReplyToList)
8523 if (!ids.Contains("@" + nm + " ") &&
8524 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8526 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8528 ids += "@" + m.Result("${id}") + " ";
8530 ids += "@" + nm + " ";
8533 if (!string.IsNullOrEmpty(post.RetweetedBy))
8535 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8536 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8538 ids += "@" + post.RetweetedBy + " ";
8541 if (ids.Length == 0) return;
8542 if (string.IsNullOrEmpty(StatusText.Text))
8545 StatusText.Text = ids;
8546 StatusText.SelectionStart = ids.Length;
8549 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8550 var inReplyToScreenName = this._curPost.ScreenName;
8551 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8557 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8562 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8564 StatusText.SelectionStart = sidx;
8570 StatusText.SelectionStart = StatusText.Text.Length;
8575 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8580 private static int iconCnt = 0;
8581 private static int blinkCnt = 0;
8582 private static bool blink = false;
8583 private static bool idle = false;
8585 private async Task RefreshTasktrayIcon()
8588 await this.Colorize();
8590 if (!TimerRefreshIcon.Enabled) return;
8591 //Static usCheckCnt As int = 0
8593 //Static iconDlListTopItem As ListViewItem = null
8595 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8596 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8598 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8600 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8606 //if (usCheckCnt > 300) //1min
8609 // if (!this.IsReceivedUserStream)
8611 // TraceOut("ReconnectUserStream");
8612 // tw.ReconnectUserStream();
8616 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8618 if (iconCnt >= this.NIconRefresh.Length)
8626 SaveConfigsAll(true);
8631 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8633 _myStatusError = false;
8637 TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8638 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8640 if (blinkCnt > 0) return;
8642 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8644 NotifyIcon1.Icon = ReplyIcon;
8648 NotifyIcon1.Icon = ReplyIconBlink;
8656 //優先度:エラー→オフライン→アイドル
8660 NotifyIcon1.Icon = NIconAtRed;
8663 if (_myStatusOnline)
8665 NotifyIcon1.Icon = NIconAt;
8669 NotifyIcon1.Icon = NIconAtSmoke;
8673 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8676 await this.RefreshTasktrayIcon();
8679 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8681 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8682 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8684 if (ListTab != null && ListTab.SelectedTab != null)
8685 _rclickTabName = ListTab.SelectedTab.Text;
8690 if (_statuses == null) return;
8691 if (_statuses.Tabs == null) return;
8693 TabClass tb = _statuses.Tabs[_rclickTabName];
8694 if (tb == null) return;
8696 NotifyDispMenuItem.Checked = tb.Notify;
8697 this.NotifyTbMenuItem.Checked = tb.Notify;
8699 soundfileListup = true;
8700 SoundFileComboBox.Items.Clear();
8701 this.SoundFileTbComboBox.Items.Clear();
8702 SoundFileComboBox.Items.Add("");
8703 this.SoundFileTbComboBox.Items.Add("");
8704 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8705 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8707 oDir = oDir.GetDirectories("Sounds")[0];
8709 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8711 SoundFileComboBox.Items.Add(oFile.Name);
8712 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8714 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8715 if (idx == -1) idx = 0;
8716 SoundFileComboBox.SelectedIndex = idx;
8717 this.SoundFileTbComboBox.SelectedIndex = idx;
8718 soundfileListup = false;
8719 UreadManageMenuItem.Checked = tb.UnreadManage;
8720 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8722 TabMenuControl(_rclickTabName);
8725 private void TabMenuControl(string tabName)
8727 var tabInfo = _statuses.GetTabByName(tabName);
8729 this.FilterEditMenuItem.Enabled = true;
8730 this.EditRuleTbMenuItem.Enabled = true;
8732 if (tabInfo.IsDefaultTabType)
8734 this.ProtectTabMenuItem.Enabled = false;
8735 this.ProtectTbMenuItem.Enabled = false;
8739 this.ProtectTabMenuItem.Enabled = true;
8740 this.ProtectTbMenuItem.Enabled = true;
8743 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8745 this.ProtectTabMenuItem.Checked = true;
8746 this.ProtectTbMenuItem.Checked = true;
8747 this.DeleteTabMenuItem.Enabled = false;
8748 this.DeleteTbMenuItem.Enabled = false;
8752 this.ProtectTabMenuItem.Checked = false;
8753 this.ProtectTbMenuItem.Checked = false;
8754 this.DeleteTabMenuItem.Enabled = true;
8755 this.DeleteTbMenuItem.Enabled = true;
8759 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8761 var checkState = ((ToolStripMenuItem)sender).Checked;
8764 this.ProtectTbMenuItem.Checked = checkState;
8765 this.ProtectTabMenuItem.Checked = checkState;
8768 this.DeleteTabMenuItem.Enabled = !checkState;
8769 this.DeleteTbMenuItem.Enabled = !checkState;
8771 if (string.IsNullOrEmpty(_rclickTabName)) return;
8772 _statuses.Tabs[_rclickTabName].Protected = checkState;
8777 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8779 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8780 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8782 if (string.IsNullOrEmpty(_rclickTabName)) return;
8783 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8788 public void ChangeTabUnreadManage(string tabName, bool isManage)
8790 var idx = this.GetTabPageIndex(tabName);
8794 _statuses.Tabs[tabName].UnreadManage = isManage;
8795 if (this._cfgCommon.TabIconDisp)
8797 if (_statuses.Tabs[tabName].UnreadCount > 0)
8798 ListTab.TabPages[idx].ImageIndex = 0;
8800 ListTab.TabPages[idx].ImageIndex = -1;
8803 if (_curTab.Text == tabName)
8805 this.PurgeListViewItemCache();
8809 SetMainWindowTitle();
8810 SetStatusLabelUrl();
8811 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8814 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8816 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8817 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8819 if (string.IsNullOrEmpty(_rclickTabName)) return;
8821 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8826 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8828 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8830 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8835 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8837 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8839 RemoveSpecifiedTab(_rclickTabName, true);
8843 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8845 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8847 using (var fltDialog = new FilterDialog())
8849 fltDialog.Owner = this;
8850 fltDialog.SetCurrent(_rclickTabName);
8851 fltDialog.ShowDialog(this);
8853 this.TopMost = this._cfgCommon.AlwaysTop;
8855 this.ApplyPostFilters();
8859 private void AddTabMenuItem_Click(object sender, EventArgs e)
8861 string tabName = null;
8862 MyCommon.TabUsageType tabUsage;
8863 using (InputTabName inputName = new InputTabName())
8865 inputName.TabName = _statuses.MakeTabName("MyTab");
8866 inputName.IsShowUsage = true;
8867 inputName.ShowDialog();
8868 if (inputName.DialogResult == DialogResult.Cancel) return;
8869 tabName = inputName.TabName;
8870 tabUsage = inputName.Usage;
8872 this.TopMost = this._cfgCommon.AlwaysTop;
8873 if (!string.IsNullOrEmpty(tabName))
8876 ListElement list = null;
8877 if (tabUsage == MyCommon.TabUsageType.Lists)
8879 using (ListAvailable listAvail = new ListAvailable())
8881 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8882 if (listAvail.SelectedList == null) return;
8883 list = listAvail.SelectedList;
8886 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8888 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8889 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8895 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8897 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8898 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8900 if (tabUsage == MyCommon.TabUsageType.Lists)
8902 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8903 var tab = this._statuses.Tabs[this._curTab.Text];
8904 this.GetListTimelineAsync(tab);
8910 private void TabMenuItem_Click(object sender, EventArgs e)
8912 using (var fltDialog = new FilterDialog())
8914 fltDialog.Owner = this;
8917 foreach (int idx in _curList.SelectedIndices)
8921 if (!SelectTab(out tabName)) return;
8923 fltDialog.SetCurrent(tabName);
8924 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8926 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8930 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8932 fltDialog.ShowDialog(this);
8933 this.TopMost = this._cfgCommon.AlwaysTop;
8937 this.ApplyPostFilters();
8939 if (this.ListTab.SelectedTab != null &&
8940 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8942 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8946 protected override bool ProcessDialogKey(Keys keyData)
8948 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8949 if ((keyData & Keys.KeyCode) == Keys.Enter)
8951 if (StatusText.Focused)
8953 bool _NewLine = false;
8956 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8958 if (StatusText.Multiline)
8960 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8962 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8966 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8970 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8972 if (StatusText.Multiline)
8974 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8976 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8980 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8986 if (StatusText.Multiline)
8988 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8990 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8991 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8995 if (((keyData & Keys.Shift) == Keys.Shift) ||
8996 (((keyData & Keys.Control) != Keys.Control) &&
8997 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
9003 int pos1 = StatusText.SelectionStart;
9004 if (StatusText.SelectionLength > 0)
9006 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
9008 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
9009 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
9014 PostButton_Click(null, null);
9018 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
9019 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
9020 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
9022 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
9027 return base.ProcessDialogKey(keyData);
9030 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9032 MakeReplyOrDirectStatus(false, true, true);
9035 private void IDRuleMenuItem_Click(object sender, EventArgs e)
9040 if (_curList.SelectedIndices.Count == 0) return;
9043 if (!SelectTab(out tabName)) return;
9045 var tab = this._statuses.Tabs[tabName];
9049 if (tab.TabType != MyCommon.TabUsageType.Mute)
9051 this.MoveOrCopy(out mv, out mk);
9055 // ミュートタブでは常に MoveMatches を true にする
9060 List<string> ids = new List<string>();
9061 foreach (int idx in _curList.SelectedIndices)
9063 PostClass post = _statuses.Tabs[_curTab.Text][idx];
9064 if (!ids.Contains(post.ScreenName))
9066 PostFilterRule fc = new PostFilterRule();
9067 ids.Add(post.ScreenName);
9068 if (post.RetweetedId == null)
9070 fc.FilterName = post.ScreenName;
9074 fc.FilterName = post.RetweetedBy;
9076 fc.UseNameField = true;
9077 fc.MoveMatches = mv;
9078 fc.MarkMatches = mk;
9079 fc.UseRegex = false;
9080 fc.FilterByUrl = false;
9086 List<string> atids = new List<string>();
9087 foreach (string id in ids)
9089 atids.Add("@" + id);
9091 int cnt = AtIdSupl.ItemCount;
9092 AtIdSupl.AddRangeItem(atids.ToArray());
9093 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
9096 this.ApplyPostFilters();
9100 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
9102 if (this._curList.SelectedIndices.Count == 0)
9105 // タブ選択ダイアログを表示(or追加)
9107 if (!this.SelectTab(out tabName))
9110 var currentTab = this._statuses.Tabs[this._curTab.Text];
9111 var filterTab = this._statuses.Tabs[tabName];
9115 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
9117 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
9118 this.MoveOrCopy(out mv, out mk);
9122 // ミュートタブでは常に MoveMatches を true にする
9127 // 振り分けルールに追加するSource
9128 var sources = new HashSet<string>();
9130 foreach (var idx in this._curList.SelectedIndices.Cast<int>())
9132 var post = currentTab[idx];
9133 var filterSource = post.Source;
9135 if (sources.Add(filterSource))
9137 var filter = new PostFilterRule
9139 FilterSource = filterSource,
9143 FilterByUrl = false,
9145 filterTab.AddFilter(filter);
9149 this.ApplyPostFilters();
9150 this.SaveConfigsTabs();
9153 private bool SelectTab(out string tabName)
9160 using (var dialog = new TabsDialog(_statuses))
9162 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9164 var selectedTab = dialog.SelectedTab;
9165 tabName = selectedTab == null ? null : selectedTab.TabName;
9168 ListTab.SelectedTab.Focus();
9170 if (tabName == null)
9172 using (InputTabName inputName = new InputTabName())
9174 inputName.TabName = _statuses.MakeTabName("MyTab");
9175 inputName.ShowDialog();
9176 if (inputName.DialogResult == DialogResult.Cancel) return false;
9177 tabName = inputName.TabName;
9179 this.TopMost = this._cfgCommon.AlwaysTop;
9180 if (!string.IsNullOrEmpty(tabName))
9182 if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9184 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9185 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9203 private void MoveOrCopy(out bool move, out bool mark)
9207 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9208 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9216 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9217 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9227 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9232 private void CopyURLMenuItem_Click(object sender, EventArgs e)
9237 private void SelectAllMenuItem_Click(object sender, EventArgs e)
9239 if (StatusText.Focused)
9242 StatusText.SelectAll();
9246 // ListView上でのCtrl+A
9247 NativeMethods.SelectAllItems(this._curList);
9251 private void MoveMiddle()
9257 if (_curList.SelectedIndices.Count == 0) return;
9259 int idx = _curList.SelectedIndices[0];
9261 _item = _curList.GetItemAt(0, 25);
9267 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9269 idx2 = _curList.VirtualListSize - 1;
9273 idx -= Math.Abs(idx1 - idx2) / 2;
9274 if (idx < 0) idx = 0;
9276 _curList.EnsureVisible(_curList.VirtualListSize - 1);
9277 _curList.EnsureVisible(idx);
9280 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
9282 var linkElements = this.PostBrowser.Document.Links.Cast<HtmlElement>()
9283 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
9286 if (linkElements.Length > 0)
9288 UrlDialog.ClearUrl();
9290 string openUrlStr = "";
9292 if (linkElements.Length == 1)
9294 // ツイートに含まれる URL が 1 つのみの場合
9295 // => OpenURL ダイアログを表示せずにリンクを開く
9300 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
9302 catch (ArgumentException)
9311 if (string.IsNullOrEmpty(urlStr)) return;
9312 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9314 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
9315 await this.OpenUriAsync(new Uri(openUrlStr));
9319 // ツイートに含まれる URL が複数ある場合
9320 // => OpenURL を表示しユーザーが選択したリンクを開く
9322 foreach (var linkElm in linkElements)
9325 string linkText = "";
9329 urlStr = linkElm.GetAttribute("title");
9330 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9331 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9332 linkText = linkElm.InnerText;
9334 catch (ArgumentException)
9343 if (string.IsNullOrEmpty(urlStr)) continue;
9344 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9348 if (UrlDialog.ShowDialog() == DialogResult.OK)
9350 openUrlStr = UrlDialog.SelectedUrl;
9352 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
9353 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
9360 this.TopMost = this._cfgCommon.AlwaysTop;
9365 private void ClearTabMenuItem_Click(object sender, EventArgs e)
9367 if (string.IsNullOrEmpty(_rclickTabName)) return;
9368 ClearTab(_rclickTabName, true);
9371 private void ClearTab(string tabName, bool showWarning)
9375 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9376 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9382 _statuses.ClearTabIds(tabName);
9383 if (ListTab.SelectedTab.Text == tabName)
9386 _anchorFlag = false;
9387 this.PurgeListViewItemCache();
9391 foreach (TabPage tb in ListTab.TabPages)
9393 if (tb.Text == tabName)
9396 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9400 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9402 SetMainWindowTitle();
9403 SetStatusLabelUrl();
9406 private static long followers = 0;
9408 private void SetMainWindowTitle()
9411 StringBuilder ttl = new StringBuilder(256);
9414 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9415 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9416 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9417 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9419 foreach (var tab in _statuses.Tabs.Values)
9421 ur += tab.UnreadCount;
9426 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9427 ttl.Append(Application.ProductName);
9429 switch (this._cfgCommon.DispLatestPost)
9431 case MyCommon.DispTitleEnum.Ver:
9432 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9434 case MyCommon.DispTitleEnum.Post:
9435 if (_history != null && _history.Count > 1)
9436 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9438 case MyCommon.DispTitleEnum.UnreadRepCount:
9439 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9441 case MyCommon.DispTitleEnum.UnreadAllCount:
9442 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9444 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9445 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9447 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9448 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9450 case MyCommon.DispTitleEnum.OwnStatus:
9451 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9452 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9458 this.Text = ttl.ToString();
9460 catch (AccessViolationException)
9462 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9466 private string GetStatusLabelText()
9469 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9470 if (_statuses == null) return "";
9471 TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9472 TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9473 if (tbRep == null || tbDm == null) return "";
9474 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9479 StringBuilder slbl = new StringBuilder(256);
9482 foreach (var tab in _statuses.Tabs.Values)
9484 ur += tab.UnreadCount;
9486 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9488 tur = tab.UnreadCount;
9499 UnreadAtCounter = urat;
9501 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9502 if (this._cfgCommon.TimelinePeriod == 0)
9504 slbl.Append(Properties.Resources.SetStatusLabelText2);
9508 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9510 return slbl.ToString();
9513 private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9517 if (this.InvokeRequired && !this.IsDisposed)
9519 this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9523 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9524 SetApiStatusLabel(endpointName);
9527 catch (ObjectDisposedException)
9531 catch (InvalidOperationException)
9537 private void SetApiStatusLabel(string endpointName = null)
9539 if (_curTab == null)
9541 this.toolStripApiGauge.ApiEndpoint = null;
9545 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9547 if (endpointName == null)
9552 case MyCommon.TabUsageType.Home:
9553 case MyCommon.TabUsageType.UserDefined:
9554 endpointName = "/statuses/home_timeline";
9557 case MyCommon.TabUsageType.Mentions:
9558 endpointName = "/statuses/mentions_timeline";
9561 case MyCommon.TabUsageType.Favorites:
9562 endpointName = "/favorites/list";
9565 case MyCommon.TabUsageType.DirectMessage:
9566 endpointName = "/direct_messages";
9569 case MyCommon.TabUsageType.UserTimeline:
9570 endpointName = "/statuses/user_timeline";
9573 case MyCommon.TabUsageType.Lists:
9574 endpointName = "/lists/statuses";
9577 case MyCommon.TabUsageType.PublicSearch:
9578 endpointName = "/search/tweets";
9581 case MyCommon.TabUsageType.Related:
9582 endpointName = "/statuses/show/:id";
9589 this.toolStripApiGauge.ApiEndpoint = endpointName;
9593 // 表示中のタブに関連する endpoint であれば更新
9596 switch (endpointName)
9598 case "/statuses/home_timeline":
9599 update = tabType == MyCommon.TabUsageType.Home ||
9600 tabType == MyCommon.TabUsageType.UserDefined;
9603 case "/statuses/mentions_timeline":
9604 update = tabType == MyCommon.TabUsageType.Mentions;
9607 case "/favorites/list":
9608 update = tabType == MyCommon.TabUsageType.Favorites;
9611 case "/direct_messages:":
9612 update = tabType == MyCommon.TabUsageType.DirectMessage;
9615 case "/statuses/user_timeline":
9616 update = tabType == MyCommon.TabUsageType.UserTimeline;
9619 case "/lists/statuses":
9620 update = tabType == MyCommon.TabUsageType.Lists;
9623 case "/search/tweets":
9624 update = tabType == MyCommon.TabUsageType.PublicSearch;
9627 case "/statuses/show/:id":
9628 update = tabType == MyCommon.TabUsageType.Related;
9637 this.toolStripApiGauge.ApiEndpoint = endpointName;
9643 private void SetStatusLabelUrl()
9645 StatusLabelUrl.Text = GetStatusLabelText();
9648 public void SetStatusLabel(string text)
9650 StatusLabel.Text = text;
9653 private static StringBuilder ur = new StringBuilder(64);
9655 private void SetNotifyIconText()
9657 // タスクトレイアイコンのツールチップテキスト書き換え
9659 ur.Remove(0, ur.Length);
9660 if (this._cfgCommon.DispUsername)
9662 ur.Append(tw.Username);
9665 ur.Append(Application.ProductName);
9667 ur.Append("(Debug Build)");
9669 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9672 ur.Append(UnreadCounter);
9674 ur.Append(UnreadAtCounter);
9677 NotifyIcon1.Text = ur.ToString();
9680 internal void CheckReplyTo(string StatusText)
9684 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9686 foreach (Match hm in m)
9688 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9690 hstr += "#" + hm.Result("$3") + " ";
9691 HashSupl.AddItem("#" + hm.Result("$3"));
9694 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9696 hstr += HashMgr.UseHash;
9698 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9700 // 本当にリプライ先指定すべきかどうかの判定
9701 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9703 if (this._cfgCommon.UseAtIdSupplement)
9705 int bCnt = AtIdSupl.ItemCount;
9706 foreach (Match mid in m)
9708 AtIdSupl.AddItem(mid.Result("${id}"));
9710 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9713 // リプライ先ステータスIDの指定がない場合は指定しない
9714 if (this.inReplyTo == null)
9718 // 次の条件を満たす場合に in_reply_to_status_id 指定
9719 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9720 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9721 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9725 var inReplyToScreenName = this.inReplyTo.Item2;
9726 if (StatusText.StartsWith("@"))
9728 if (StatusText.StartsWith("@" + inReplyToScreenName)) return;
9732 foreach (Match mid in m)
9734 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9739 this.inReplyTo = null;
9742 private void TweenMain_Resize(object sender, EventArgs e)
9744 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9746 this.Visible = false;
9748 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9750 // 現在の DPI と設定保存時の DPI との比を取得する
9751 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9753 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9754 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9755 this.DesktopLocation = _cfgLocal.FormLocation;
9756 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9759 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9760 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9761 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9763 this.SplitContainer1.SplitterDistance = splitterDistance;
9767 StatusText.Multiline = _cfgLocal.StatusMultiline;
9768 if (StatusText.Multiline)
9770 var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9771 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9772 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9774 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9776 StatusText.Height = statusTextHeight;
9780 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9782 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9786 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9787 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9789 this.SplitContainer3.SplitterDistance = previewDistance;
9792 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9793 this.SplitContainer3.Panel2Collapsed = true;
9795 _initialLayout = false;
9797 if (this.WindowState != FormWindowState.Minimized)
9799 _formWindowState = this.WindowState;
9803 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9805 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9806 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9807 if (PlaySoundMenuItem.Checked)
9809 this._cfgCommon.PlaySound = true;
9813 this._cfgCommon.PlaySound = false;
9815 ModifySettingCommon = true;
9818 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9820 if (this._initialLayout)
9823 int splitterDistance;
9824 switch (this.WindowState)
9826 case FormWindowState.Normal:
9827 splitterDistance = this.SplitContainer1.SplitterDistance;
9829 case FormWindowState.Maximized:
9830 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9831 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9832 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9833 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9839 this._mySpDis = splitterDistance;
9840 this.ModifySettingLocal = true;
9843 private async Task doRepliedStatusOpen()
9845 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9847 if (MyCommon.IsKeyDown(Keys.Shift))
9849 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9852 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9854 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9855 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9859 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9861 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9862 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9863 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9866 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9871 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9873 await this.doRepliedStatusOpen();
9877 /// UserPicture.Image に設定されている画像を破棄します。
9879 private void ClearUserPicture()
9881 if (this.UserPicture.Image != null)
9883 var oldImage = this.UserPicture.Image;
9884 this.UserPicture.Image = null;
9889 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9891 //発言詳細のアイコン右クリック時のメニュー制御
9892 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9894 string name = _curPost.ImageUrl;
9895 if (name != null && name.Length > 0)
9897 int idx = name.LastIndexOf('/');
9900 name = Path.GetFileName(name.Substring(idx));
9901 if (name.Contains("_normal.") || name.EndsWith("_normal"))
9903 name = name.Replace("_normal", "");
9904 this.IconNameToolStripMenuItem.Text = name;
9905 this.IconNameToolStripMenuItem.Enabled = true;
9909 this.IconNameToolStripMenuItem.Enabled = false;
9910 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9915 this.IconNameToolStripMenuItem.Enabled = false;
9916 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9919 this.ReloadIconToolStripMenuItem.Enabled = true;
9921 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9923 this.SaveIconPictureToolStripMenuItem.Enabled = true;
9927 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9932 this.IconNameToolStripMenuItem.Enabled = false;
9933 this.ReloadIconToolStripMenuItem.Enabled = false;
9934 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9935 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9940 this.IconNameToolStripMenuItem.Enabled = false;
9941 this.ReloadIconToolStripMenuItem.Enabled = false;
9942 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9943 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9945 if (NameLabel.Tag != null)
9947 string id = (string)NameLabel.Tag;
9948 if (id == tw.Username)
9950 FollowToolStripMenuItem.Enabled = false;
9951 UnFollowToolStripMenuItem.Enabled = false;
9952 ShowFriendShipToolStripMenuItem.Enabled = false;
9953 ShowUserStatusToolStripMenuItem.Enabled = true;
9954 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9955 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9956 ListManageUserContextToolStripMenuItem3.Enabled = true;
9960 FollowToolStripMenuItem.Enabled = true;
9961 UnFollowToolStripMenuItem.Enabled = true;
9962 ShowFriendShipToolStripMenuItem.Enabled = true;
9963 ShowUserStatusToolStripMenuItem.Enabled = true;
9964 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9965 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9966 ListManageUserContextToolStripMenuItem3.Enabled = true;
9971 FollowToolStripMenuItem.Enabled = false;
9972 UnFollowToolStripMenuItem.Enabled = false;
9973 ShowFriendShipToolStripMenuItem.Enabled = false;
9974 ShowUserStatusToolStripMenuItem.Enabled = false;
9975 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9976 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9977 ListManageUserContextToolStripMenuItem3.Enabled = false;
9981 private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9983 if (_curPost == null) return;
9984 string name = _curPost.ImageUrl;
9985 await this.OpenUriInBrowserAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9988 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9990 if (this._curPost == null) return;
9992 await this.UserPicture.SetImageFromTask(async () =>
9994 var imageUrl = this._curPost.ImageUrl;
9996 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
9997 .ConfigureAwait(false);
9999 return await image.CloneAsync()
10000 .ConfigureAwait(false);
10004 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10006 if (_curPost == null) return;
10007 string name = _curPost.ImageUrl;
10008 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
10010 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
10012 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10018 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10020 if (_curPost == null) return;
10021 string name = _curPost.ImageUrl;
10023 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
10025 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10029 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
10031 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
10033 using (Graphics g = Graphics.FromImage(bmp2))
10035 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
10036 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
10038 bmp2.Save(this.SaveFileDialog1.FileName);
10044 //処理中にキャッシュアウトする可能性あり
10049 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
10051 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
10052 if (multiline != this.StatusText.Multiline)
10054 this.StatusText.Multiline = multiline;
10055 MultiLineMenuItem.Checked = multiline;
10056 ModifySettingLocal = true;
10060 private void StatusText_MultilineChanged(object sender, EventArgs e)
10062 if (this.StatusText.Multiline)
10063 this.StatusText.ScrollBars = ScrollBars.Vertical;
10065 this.StatusText.ScrollBars = ScrollBars.None;
10067 ModifySettingLocal = true;
10070 private void MultiLineMenuItem_Click(object sender, EventArgs e)
10073 StatusText.Multiline = MultiLineMenuItem.Checked;
10074 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
10075 if (MultiLineMenuItem.Checked)
10077 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
10078 SplitContainer2.SplitterDistance = 0;
10080 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
10084 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
10086 ModifySettingLocal = true;
10089 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
10091 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
10092 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
10094 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
10095 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
10096 //Appendix A. Collected ABNF for URI
10097 //http://www.ietf.org/rfc/rfc3986.txt
10099 string result = "";
10101 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
10103 if (StatusText.SelectionLength > 0)
10105 string tmp = StatusText.SelectedText;
10106 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
10107 if (tmp.StartsWith("http"))
10109 // 文字列が選択されている場合はその文字列について処理
10111 //nico.ms使用、nicovideoにマッチしたら変換
10112 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10114 result = nicoms.Shorten(tmp);
10116 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10118 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10121 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10122 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10123 result = resultUri.AbsoluteUri;
10125 catch (WebApiException e)
10127 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10130 catch (UriFormatException e)
10132 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10141 if (!string.IsNullOrEmpty(result))
10143 urlUndo undotmp = new urlUndo();
10145 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
10146 StatusText.SelectedText = result;
10149 undotmp.Before = tmp;
10150 undotmp.After = result;
10152 if (urlUndoBuffer == null)
10154 urlUndoBuffer = new List<urlUndo>();
10155 UrlUndoToolStripMenuItem.Enabled = true;
10158 urlUndoBuffer.Add(undotmp);
10164 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
10165 @"(?<url>(?<protocol>https?://)" +
10166 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
10167 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
10168 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
10169 // 正規表現にマッチしたURL文字列をtinyurl化
10170 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
10172 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
10173 string tmp = mt.Result("${url}");
10174 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
10175 urlUndo undotmp = new urlUndo();
10178 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10180 //nico.ms使用、nicovideoにマッチしたら変換
10181 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10183 result = nicoms.Shorten(tmp);
10185 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10187 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10190 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10191 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10192 result = resultUri.AbsoluteUri;
10194 catch (HttpRequestException e)
10196 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
10197 // のように長いので「:」が含まれていればそれ以降のみを抽出する
10198 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
10200 this.StatusLabel.Text = Converter_Type + ":" + message;
10203 catch (WebApiException e)
10205 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10208 catch (UriFormatException e)
10210 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10219 if (!string.IsNullOrEmpty(result))
10221 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10222 StatusText.SelectedText = result;
10224 undotmp.Before = mt.Result("${url}");
10225 undotmp.After = result;
10227 if (urlUndoBuffer == null)
10229 urlUndoBuffer = new List<urlUndo>();
10230 UrlUndoToolStripMenuItem.Enabled = true;
10233 urlUndoBuffer.Add(undotmp);
10241 private void doUrlUndo()
10243 if (urlUndoBuffer != null)
10245 string tmp = StatusText.Text;
10246 foreach (urlUndo data in urlUndoBuffer)
10248 tmp = tmp.Replace(data.After, data.Before);
10250 StatusText.Text = tmp;
10251 urlUndoBuffer = null;
10252 UrlUndoToolStripMenuItem.Enabled = false;
10253 StatusText.SelectionStart = 0;
10254 StatusText.SelectionLength = 0;
10258 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10260 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10263 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10265 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10268 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10270 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10273 private async void UxnuMenuItem_Click(object sender, EventArgs e)
10275 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10278 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10280 if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
10282 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
10283 Random rnd = new Random();
10284 // 前回使用した短縮URLサービス以外を選択する
10287 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10289 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10290 await UrlConvertAsync(svc);
10294 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10299 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10301 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10302 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10303 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10304 ModifySettingCommon = true;
10307 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10309 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10310 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10311 _cfgCommon.ListLock = ListLockMenuItem.Checked;
10312 ModifySettingCommon = true;
10315 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10317 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10318 MenuStrip1.Tag = new Object();
10319 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10322 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10324 if (this.Tag != null) // 設定された戻り先へ遷移
10326 if (this.Tag == this.ListTab.SelectedTab)
10327 ((Control)this.ListTab.SelectedTab.Tag).Select();
10329 ((Control)this.Tag).Select();
10331 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10333 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10335 this.Tag = ListTab.SelectedTab.Tag;
10336 ((Control)this.Tag).Select();
10339 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10340 MenuStrip1.Tag = null;
10343 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10345 DetailsListView lst = (DetailsListView)sender;
10346 if (_cfgLocal == null) return;
10350 _cfgLocal.Width1 = lst.Columns[0].Width;
10351 _cfgLocal.Width3 = lst.Columns[1].Width;
10355 int[] darr = new int[lst.Columns.Count];
10356 for (int i = 0; i < lst.Columns.Count; i++)
10358 darr[lst.Columns[i].DisplayIndex] = i;
10360 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10362 for (int i = 0; i < lst.Columns.Count; i++)
10367 _cfgLocal.DisplayIndex1 = i;
10370 _cfgLocal.DisplayIndex2 = i;
10373 _cfgLocal.DisplayIndex3 = i;
10376 _cfgLocal.DisplayIndex4 = i;
10379 _cfgLocal.DisplayIndex5 = i;
10382 _cfgLocal.DisplayIndex6 = i;
10385 _cfgLocal.DisplayIndex7 = i;
10388 _cfgLocal.DisplayIndex8 = i;
10392 _cfgLocal.Width1 = lst.Columns[0].Width;
10393 _cfgLocal.Width2 = lst.Columns[1].Width;
10394 _cfgLocal.Width3 = lst.Columns[2].Width;
10395 _cfgLocal.Width4 = lst.Columns[3].Width;
10396 _cfgLocal.Width5 = lst.Columns[4].Width;
10397 _cfgLocal.Width6 = lst.Columns[5].Width;
10398 _cfgLocal.Width7 = lst.Columns[6].Width;
10399 _cfgLocal.Width8 = lst.Columns[7].Width;
10401 ModifySettingLocal = true;
10402 _isColumnChanged = true;
10405 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10407 DetailsListView lst = (DetailsListView)sender;
10408 if (_cfgLocal == null) return;
10411 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10413 _cfgLocal.Width1 = lst.Columns[0].Width;
10414 ModifySettingLocal = true;
10415 _isColumnChanged = true;
10417 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10419 _cfgLocal.Width3 = lst.Columns[1].Width;
10420 ModifySettingLocal = true;
10421 _isColumnChanged = true;
10426 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10428 _cfgLocal.Width1 = lst.Columns[0].Width;
10429 ModifySettingLocal = true;
10430 _isColumnChanged = true;
10432 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10434 _cfgLocal.Width2 = lst.Columns[1].Width;
10435 ModifySettingLocal = true;
10436 _isColumnChanged = true;
10438 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10440 _cfgLocal.Width3 = lst.Columns[2].Width;
10441 ModifySettingLocal = true;
10442 _isColumnChanged = true;
10444 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10446 _cfgLocal.Width4 = lst.Columns[3].Width;
10447 ModifySettingLocal = true;
10448 _isColumnChanged = true;
10450 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10452 _cfgLocal.Width5 = lst.Columns[4].Width;
10453 ModifySettingLocal = true;
10454 _isColumnChanged = true;
10456 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10458 _cfgLocal.Width6 = lst.Columns[5].Width;
10459 ModifySettingLocal = true;
10460 _isColumnChanged = true;
10462 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10464 _cfgLocal.Width7 = lst.Columns[6].Width;
10465 ModifySettingLocal = true;
10466 _isColumnChanged = true;
10468 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10470 _cfgLocal.Width8 = lst.Columns[7].Width;
10471 ModifySettingLocal = true;
10472 _isColumnChanged = true;
10475 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10478 // SaveConfigsLocal();
10482 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10485 string _selText = this.PostBrowser.GetSelectedText();
10488 Clipboard.SetDataObject(_selText, false, 5, 100);
10490 catch (Exception ex)
10492 MessageBox.Show(ex.Message);
10496 private async Task doSearchToolStrip(string url)
10498 //発言詳細で「選択文字列で検索」(選択文字列取得)
10499 string _selText = this.PostBrowser.GetSelectedText();
10501 if (_selText != null)
10503 if (url == Properties.Resources.SearchItem4Url)
10506 AddNewTabForSearch(_selText);
10510 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10511 await this.OpenUriInBrowserAsync(tmp);
10515 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10518 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10521 private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10523 await this.doSearchToolStrip(Properties.Resources.SearchItem1Url);
10526 private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10528 await this.doSearchToolStrip(Properties.Resources.SearchItem2Url);
10531 private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10533 await this.doSearchToolStrip(Properties.Resources.SearchItem4Url);
10536 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10540 foreach (var link in this.PostBrowser.Document.Links.Cast<HtmlElement>())
10542 if (link.GetAttribute("href") == this._postBrowserStatusText)
10544 Clipboard.SetDataObject(link.GetAttribute("title"), false, 5, 100);
10549 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10551 catch (Exception ex)
10553 MessageBox.Show(ex.Message);
10557 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10559 // URLコピーの項目の表示/非表示
10560 if (PostBrowser.StatusText.StartsWith("http"))
10562 this._postBrowserStatusText = PostBrowser.StatusText;
10563 string name = GetUserId();
10564 UrlCopyContextMenuItem.Enabled = true;
10567 FollowContextMenuItem.Enabled = true;
10568 RemoveContextMenuItem.Enabled = true;
10569 FriendshipContextMenuItem.Enabled = true;
10570 ShowUserStatusContextMenuItem.Enabled = true;
10571 SearchPostsDetailToolStripMenuItem.Enabled = true;
10572 IdFilterAddMenuItem.Enabled = true;
10573 ListManageUserContextToolStripMenuItem.Enabled = true;
10574 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10578 FollowContextMenuItem.Enabled = false;
10579 RemoveContextMenuItem.Enabled = false;
10580 FriendshipContextMenuItem.Enabled = false;
10581 ShowUserStatusContextMenuItem.Enabled = false;
10582 SearchPostsDetailToolStripMenuItem.Enabled = false;
10583 IdFilterAddMenuItem.Enabled = false;
10584 ListManageUserContextToolStripMenuItem.Enabled = false;
10585 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10588 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10589 UseHashtagMenuItem.Enabled = true;
10591 UseHashtagMenuItem.Enabled = false;
10595 this._postBrowserStatusText = "";
10596 UrlCopyContextMenuItem.Enabled = false;
10597 FollowContextMenuItem.Enabled = false;
10598 RemoveContextMenuItem.Enabled = false;
10599 FriendshipContextMenuItem.Enabled = false;
10600 ShowUserStatusContextMenuItem.Enabled = false;
10601 SearchPostsDetailToolStripMenuItem.Enabled = false;
10602 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10603 UseHashtagMenuItem.Enabled = false;
10604 IdFilterAddMenuItem.Enabled = false;
10605 ListManageUserContextToolStripMenuItem.Enabled = false;
10607 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10608 string _selText = this.PostBrowser.GetSelectedText();
10609 if (_selText == null)
10611 SelectionSearchContextMenuItem.Enabled = false;
10612 SelectionCopyContextMenuItem.Enabled = false;
10613 SelectionTranslationToolStripMenuItem.Enabled = false;
10617 SelectionSearchContextMenuItem.Enabled = true;
10618 SelectionCopyContextMenuItem.Enabled = true;
10619 SelectionTranslationToolStripMenuItem.Enabled = true;
10621 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10622 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10623 bool fAllFlag = false;
10624 foreach (Match mu in ma)
10626 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
10632 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10634 if (_curPost == null)
10635 TranslationToolStripMenuItem.Enabled = false;
10637 TranslationToolStripMenuItem.Enabled = true;
10642 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10644 //発言詳細の選択文字列で現在のタブを検索
10645 string _selText = this.PostBrowser.GetSelectedText();
10647 if (_selText != null)
10649 var searchOptions = new SearchWordDialog.SearchOptions(
10650 SearchWordDialog.SearchType.Timeline,
10653 caseSensitive: false,
10656 this.SearchDialog.ResultOptions = searchOptions;
10659 searchOptions.Query,
10660 searchOptions.CaseSensitive,
10661 searchOptions.UseRegex,
10662 SEARCHTYPE.NextSearch);
10666 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10668 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10669 ModifySettingLocal = true;
10672 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10674 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10676 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10678 SelectMedia_DragDrop(e);
10681 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10683 var url = GetUrlFromDataObject(e.Data);
10686 if (url.Item2 == null)
10687 appendText = url.Item1;
10689 appendText = url.Item2 + " " + url.Item1;
10691 if (this.StatusText.TextLength == 0)
10692 this.StatusText.Text = appendText;
10694 this.StatusText.Text += " " + appendText;
10696 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10698 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10700 this.StatusText.Text += text;
10702 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10704 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10705 if (data != null) StatusText.Text += data;
10710 /// IDataObject から URL とタイトルの対を取得します
10713 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10715 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10716 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10717 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10719 if (data.GetDataPresent("text/x-moz-url"))
10721 // Firefox, Google Chrome で利用可能
10722 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10724 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10726 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10727 if (lines.Length < 2)
10728 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
10730 return new Tuple<string, string>(lines[0], lines[1]);
10733 else if (data.GetDataPresent("IESiteModeToUrl"))
10735 // Internet Exproler 用
10736 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10738 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10740 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10741 if (lines.Length < 2)
10742 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
10744 return new Tuple<string, string>(lines[0], lines[1]);
10747 else if (data.GetDataPresent("UniformResourceLocatorW"))
10751 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10753 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10754 return new Tuple<string, string>(url, null);
10758 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10761 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10763 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10765 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10767 SelectMedia_DragEnter(e);
10771 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10773 e.Effect = DragDropEffects.Copy;
10776 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10778 e.Effect = DragDropEffects.Copy;
10781 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10783 e.Effect = DragDropEffects.Copy;
10787 e.Effect = DragDropEffects.None;
10790 private void TweenMain_DragOver(object sender, DragEventArgs e)
10794 public bool IsNetworkAvailable()
10797 nw = MyCommon.IsNetworkAvailable();
10798 _myStatusOnline = nw;
10802 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
10804 var uriStr = uri.AbsoluteUri;
10806 // OpenTween 内部で使用する URL
10807 if (uri.Authority == "opentween")
10809 await this.OpenInternalUriAsync(uri);
10813 // ハッシュタグを含む Twitter 検索
10814 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
10816 // ハッシュタグの場合は、タブで開く
10817 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
10818 var pos = unescapedQuery.IndexOf('#');
10819 if (pos == -1) return;
10821 var hash = unescapedQuery.Substring(pos);
10822 this.HashSupl.AddItem(hash);
10823 this.HashMgr.AddHashToHistory(hash.Trim(), false);
10824 this.AddNewTabForSearch(hash);
10829 // フラグが立っている場合は設定と逆の動作をする
10830 if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
10831 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
10833 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
10834 if (userUriMatch.Success)
10836 var screenName = userUriMatch.Groups["ScreenName"].Value;
10837 if (this.IsTwitterId(screenName))
10839 this.AddNewTabForUserTimeline(screenName);
10845 // どのパターンにも該当しないURL
10846 await this.OpenUriInBrowserAsync(uriStr);
10850 /// OpenTween 内部の機能を呼び出すための URL を開きます
10852 private async Task OpenInternalUriAsync(Uri uri)
10854 // ツイートを開く (//opentween/status/:status_id)
10855 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
10858 var statusId = long.Parse(match.Groups[1].Value);
10859 await this.OpenRelatedTab(statusId);
10864 public Task OpenUriInBrowserAsync(string UriString)
10866 return Task.Run(() =>
10868 string myPath = UriString;
10872 var configBrowserPath = this._cfgLocal.BrowserPath;
10873 if (!string.IsNullOrEmpty(configBrowserPath))
10875 if (configBrowserPath.StartsWith("\"") && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2) > -1)
10877 int sep = configBrowserPath.IndexOf("\"", 2);
10878 string browserPath = configBrowserPath.Substring(1, sep - 1);
10880 if (sep < configBrowserPath.Length - 1)
10882 arg = configBrowserPath.Substring(sep + 1);
10884 myPath = arg + " " + myPath;
10885 System.Diagnostics.Process.Start(browserPath, myPath);
10889 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10894 System.Diagnostics.Process.Start(myPath);
10899 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10904 private void ListTabSelect(TabPage _tab)
10908 this.PurgeListViewItemCache();
10911 _curList = (DetailsListView)_tab.Tag;
10912 if (_curList.SelectedIndices.Count > 0)
10914 _curItemIndex = _curList.SelectedIndices[0];
10915 _curPost = GetCurTabPost(_curItemIndex);
10919 _curItemIndex = -1;
10923 _anchorPost = null;
10924 _anchorFlag = false;
10928 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10932 for (int i = 0; i < _curList.Columns.Count; i++)
10934 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10939 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10941 ListTabSelect(e.TabPage);
10944 private void SelectListItem(DetailsListView LView, int Index)
10947 Rectangle bnd = new Rectangle();
10949 var item = LView.FocusedItem;
10958 LView.SelectedIndices.Clear();
10960 while (LView.SelectedIndices.Count > 0);
10961 item = LView.Items[Index];
10962 item.Selected = true;
10963 item.Focused = true;
10965 if (flg) LView.Invalidate(bnd);
10968 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
10971 Rectangle bnd = new Rectangle();
10973 var item = LView.FocusedItem;
10984 LView.SelectedIndices.Clear();
10986 while (LView.SelectedIndices.Count > 0);
10987 LView.SelectItems(Index);
10989 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
10991 LView.SelectionMark = selectionMarkIndex;
10993 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
10995 LView.Items[focusedIndex].Focused = true;
10997 else if (Index != null && Index.Length != 0)
10999 LView.Items[Index.Last()].Focused = true;
11002 if (flg) LView.Invalidate(bnd);
11005 private void StartUserStream()
11007 tw.NewPostFromStream += tw_NewPostFromStream;
11008 tw.UserStreamStarted += tw_UserStreamStarted;
11009 tw.UserStreamStopped += tw_UserStreamStopped;
11010 tw.PostDeleted += tw_PostDeleted;
11011 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
11013 MenuItemUserStream.Text = "&UserStream ■";
11014 MenuItemUserStream.Enabled = true;
11015 StopToolStripMenuItem.Text = "&Start";
11016 StopToolStripMenuItem.Enabled = true;
11017 if (this._cfgCommon.UserstreamStartup) tw.StartUserStream();
11020 private async void TweenMain_Shown(object sender, EventArgs e)
11024 using (ControlTransaction.Update(this.PostBrowser))
11026 PostBrowser.Url = new Uri("about:blank");
11027 PostBrowser.DocumentText = ""; //発言詳細部初期化
11034 NotifyIcon1.Visible = true;
11036 if (this.IsNetworkAvailable())
11040 var loadTasks = new List<Task>
11042 this.RefreshMuteUserIdsAsync(),
11043 this.RefreshBlockIdsAsync(),
11044 this.RefreshNoRetweetIdsAsync(),
11045 this.RefreshTwitterConfigurationAsync(),
11046 this.GetHomeTimelineAsync(),
11047 this.GetReplyAsync(),
11048 this.GetDirectMessagesAsync(),
11049 this.GetPublicSearchAllAsync(),
11050 this.GetUserTimelineAllAsync(),
11051 this.GetListTimelineAllAsync(),
11054 if (this._cfgCommon.StartupFollowers)
11055 loadTasks.Add(this.RefreshFollowerIdsAsync());
11057 if (this._cfgCommon.GetFav)
11058 loadTasks.Add(this.GetFavoritesAsync());
11060 var allTasks = Task.WhenAll(loadTasks);
11065 var timeout = Task.Delay(5000);
11066 if (await Task.WhenAny(allTasks, timeout) != timeout)
11070 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
11072 if (MyCommon._endingFlag)
11076 if (MyCommon._endingFlag) return;
11078 if (ApplicationSettings.VersionInfoUrl != null)
11080 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
11081 if (this._cfgCommon.StartupVersion)
11082 await this.CheckNewVersion(true);
11086 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
11087 this.VerUpMenuItem.Enabled = false;
11088 this.VerUpMenuItem.Available = false;
11089 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
11092 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
11093 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
11095 MessageBox.Show(Properties.Resources.ReAuthorizeText);
11096 SettingStripMenuItem_Click(null, null);
11100 var reloadTasks = new List<Task>();
11102 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
11103 reloadTasks.Add(this.RefreshFollowerIdsAsync());
11105 if (!tw.GetNoRetweetSuccess)
11106 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
11108 if (this.tw.Configuration.PhotoSizeLimit == 0)
11109 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
11111 await Task.WhenAll(reloadTasks);
11116 TimerTimeline.Enabled = true;
11119 private async Task doGetFollowersMenu()
11121 await this.RefreshFollowerIdsAsync();
11122 await this.DispSelectedPost(true);
11125 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
11127 await this.doGetFollowersMenu();
11130 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
11132 doReTweetUnofficial();
11135 private async Task doReTweetOfficial(bool isConfirm)
11138 if (this.ExistCurrentPost)
11140 if (_curPost.IsProtect)
11142 MessageBox.Show("Protected.");
11143 _DoFavRetweetFlags = false;
11146 if (_curList.SelectedIndices.Count > 15)
11148 MessageBox.Show(Properties.Resources.RetweetLimitText);
11149 _DoFavRetweetFlags = false;
11152 else if (_curList.SelectedIndices.Count > 1)
11154 string QuestionText = Properties.Resources.RetweetQuestion2;
11155 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
11156 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
11158 case DialogResult.Cancel:
11159 case DialogResult.No:
11160 _DoFavRetweetFlags = false;
11166 if (_curPost.IsDm || _curPost.IsMe)
11168 _DoFavRetweetFlags = false;
11171 if (!this._cfgCommon.RetweetNoConfirm)
11173 string Questiontext = Properties.Resources.RetweetQuestion1;
11174 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11175 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11177 _DoFavRetweetFlags = false;
11183 var statusIds = new List<long>();
11184 foreach (int idx in _curList.SelectedIndices)
11186 PostClass post = GetCurTabPost(idx);
11187 if (!post.IsMe && !post.IsProtect && !post.IsDm)
11188 statusIds.Add(post.StatusId);
11191 await this.RetweetAsync(statusIds);
11195 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
11197 await this.doReTweetOfficial(true);
11200 private async Task FavoritesRetweetOfficial()
11202 if (!this.ExistCurrentPost) return;
11203 _DoFavRetweetFlags = true;
11204 var retweetTask = this.doReTweetOfficial(true);
11205 if (_DoFavRetweetFlags)
11207 _DoFavRetweetFlags = false;
11208 var favoriteTask = this.FavoriteChange(true, false);
11210 await Task.WhenAll(retweetTask, favoriteTask);
11218 private async Task FavoritesRetweetUnofficial()
11220 if (this.ExistCurrentPost && !_curPost.IsDm)
11222 _DoFavRetweetFlags = true;
11223 var favoriteTask = this.FavoriteChange(true);
11224 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11226 _DoFavRetweetFlags = false;
11227 doReTweetUnofficial();
11230 await favoriteTask;
11235 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11237 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11238 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11239 /// <returns>復元されたツイート本文</returns>
11240 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11242 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11245 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11247 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11249 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11253 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11255 statusHtml = statusHtml.Replace("<br>", " ");
11257 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11258 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
11259 statusHtml = statusHtml.Replace(" ", " ");
11261 return WebUtility.HtmlDecode(statusHtml);
11264 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11266 if (_curPost != null)
11267 await this.DispSelectedPost(true);
11270 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11272 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11273 DebugModeToolStripMenuItem.Visible = true;
11275 DebugModeToolStripMenuItem.Visible = false;
11278 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11280 this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11283 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11285 ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
11288 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11290 if (TraceOutToolStripMenuItem.Checked)
11291 MyCommon.TraceFlag = true;
11293 MyCommon.TraceFlag = false;
11296 private void TweenMain_Deactivate(object sender, EventArgs e)
11298 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11299 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11302 private void TabRenameMenuItem_Click(object sender, EventArgs e)
11304 if (string.IsNullOrEmpty(_rclickTabName)) return;
11305 TabRename(ref _rclickTabName);
11308 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11310 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11313 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11315 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11318 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11320 TwitterApiStatus apiStatus;
11322 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
11324 var cancellationToken = dialog.EnableCancellation();
11328 var task = Task.Run(() => this.tw.GetInfoApi());
11329 apiStatus = await dialog.WaitForAsync(this, task);
11331 catch (WebApiException)
11336 if (cancellationToken.IsCancellationRequested)
11339 if (apiStatus == null)
11341 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11346 using (var apiDlg = new ApiInfoDialog())
11348 apiDlg.ShowDialog(this);
11352 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
11354 var id = _curPost?.ScreenName ?? "";
11356 await this.FollowCommand(id);
11359 private async Task FollowCommand(string id)
11361 using (var inputName = new InputTabName())
11363 inputName.FormTitle = "Follow";
11364 inputName.FormDescription = Properties.Resources.FRMessage1;
11365 inputName.TabName = id;
11367 if (inputName.ShowDialog(this) != DialogResult.OK)
11369 if (string.IsNullOrWhiteSpace(inputName.TabName))
11372 id = inputName.TabName.Trim();
11375 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
11379 var task = Task.Run(() => this.tw.PostFollowCommand(id));
11380 await dialog.WaitForAsync(this, task);
11382 catch (WebApiException ex)
11384 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11389 MessageBox.Show(Properties.Resources.FRMessage3);
11392 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11394 var id = _curPost?.ScreenName ?? "";
11396 await this.RemoveCommand(id, false);
11399 private async Task RemoveCommand(string id, bool skipInput)
11403 using (var inputName = new InputTabName())
11405 inputName.FormTitle = "Unfollow";
11406 inputName.FormDescription = Properties.Resources.FRMessage1;
11407 inputName.TabName = id;
11409 if (inputName.ShowDialog(this) != DialogResult.OK)
11411 if (string.IsNullOrWhiteSpace(inputName.TabName))
11414 id = inputName.TabName.Trim();
11418 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
11422 var task = Task.Run(() => this.tw.PostRemoveCommand(id));
11423 await dialog.WaitForAsync(this, task);
11425 catch (WebApiException ex)
11427 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11432 MessageBox.Show(Properties.Resources.FRMessage3);
11435 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
11437 var id = _curPost?.ScreenName ?? "";
11439 await this.ShowFriendship(id);
11442 private async Task ShowFriendship(string id)
11444 using (var inputName = new InputTabName())
11446 inputName.FormTitle = "Show Friendships";
11447 inputName.FormDescription = Properties.Resources.FRMessage1;
11448 inputName.TabName = id;
11450 if (inputName.ShowDialog(this) != DialogResult.OK)
11452 if (string.IsNullOrWhiteSpace(inputName.TabName))
11455 id = inputName.TabName.Trim();
11458 bool isFollowing, isFollowed;
11460 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11462 var cancellationToken = dialog.EnableCancellation();
11466 var task = Task.Run(() => this.tw.GetFriendshipInfo(id));
11467 var friendship = await dialog.WaitForAsync(this, task);
11469 isFollowing = friendship.Relationship.Source.Following;
11470 isFollowed = friendship.Relationship.Source.FollowedBy;
11472 catch (WebApiException ex)
11474 if (!cancellationToken.IsCancellationRequested)
11475 MessageBox.Show(ex.Message);
11479 if (cancellationToken.IsCancellationRequested)
11483 string result = "";
11486 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11490 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11494 result += Properties.Resources.GetFriendshipInfo3;
11498 result += Properties.Resources.GetFriendshipInfo4;
11500 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11501 MessageBox.Show(result);
11504 private async Task ShowFriendship(string[] ids)
11506 foreach (string id in ids)
11508 bool isFollowing, isFollowed;
11510 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11512 var cancellationToken = dialog.EnableCancellation();
11516 var task = Task.Run(() => this.tw.GetFriendshipInfo(id));
11517 var friendship = await dialog.WaitForAsync(this, task);
11519 isFollowing = friendship.Relationship.Source.Following;
11520 isFollowed = friendship.Relationship.Source.FollowedBy;
11522 catch (WebApiException ex)
11524 if (!cancellationToken.IsCancellationRequested)
11525 MessageBox.Show(ex.Message);
11529 if (cancellationToken.IsCancellationRequested)
11533 string result = "";
11539 ff += Properties.Resources.GetFriendshipInfo1;
11543 ff += Properties.Resources.GetFriendshipInfo2;
11546 ff += System.Environment.NewLine + " ";
11549 ff += Properties.Resources.GetFriendshipInfo3;
11553 ff += Properties.Resources.GetFriendshipInfo4;
11555 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11558 if (MessageBox.Show(
11559 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11560 MessageBoxButtons.YesNo,
11561 MessageBoxIcon.Question,
11562 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11564 await this.RemoveCommand(id, true);
11569 MessageBox.Show(result);
11574 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
11576 await this.doShowUserStatus(tw.Username, false);
11577 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11579 // doShowUserStatus(tw.Username, false);
11583 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11588 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11589 // URLから切り出した文字列を渡す
11591 public bool IsTwitterId(string name)
11593 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11594 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11596 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLower());
11599 private string GetUserId()
11601 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11602 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11603 return m.Result("${ScreenName}");
11608 private async void FollowContextMenuItem_Click(object sender, EventArgs e)
11610 string name = GetUserId();
11612 await this.FollowCommand(name);
11615 private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
11617 string name = GetUserId();
11619 await this.RemoveCommand(name, false);
11622 private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11624 string name = GetUserId();
11626 await this.ShowFriendship(name);
11629 private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11631 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11632 List<string> ids = new List<string>();
11633 foreach (Match mu in ma)
11635 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11637 ids.Add(mu.Result("${ScreenName}"));
11641 await this.ShowFriendship(ids.ToArray());
11644 private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11646 string name = GetUserId();
11648 await this.ShowUserStatus(name);
11651 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11653 string name = GetUserId();
11654 if (name != null) AddNewTabForUserTimeline(name);
11657 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11659 string name = GetUserId();
11660 if (name != null) AddNewTabForSearch("@" + name);
11663 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11665 ModifySettingCommon = true;
11668 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11670 ModifySettingCommon = true;
11673 private void doQuoteOfficial()
11675 if (this.ExistCurrentPost)
11677 if (_curPost.IsDm ||
11678 !StatusText.Enabled) return;
11680 if (_curPost.IsProtect)
11682 MessageBox.Show("Protected.");
11686 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
11688 this.inReplyTo = null;
11690 StatusText.SelectionStart = 0;
11691 StatusText.Focus();
11695 private void doReTweetUnofficial()
11698 if (this.ExistCurrentPost)
11700 if (_curPost.IsDm || !StatusText.Enabled)
11703 if (_curPost.IsProtect)
11705 MessageBox.Show("Protected.");
11708 string rtdata = _curPost.Text;
11709 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11711 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
11713 // 投稿時に in_reply_to_status_id を付加する
11714 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11715 var inReplyToScreenName = this._curPost.ScreenName;
11716 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
11718 StatusText.SelectionStart = 0;
11719 StatusText.Focus();
11723 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11728 private void SearchButton_Click(object sender, EventArgs e)
11731 Control pnl = ((Control)sender).Parent;
11732 if (pnl == null) return;
11733 string tbName = pnl.Parent.Text;
11734 TabClass tb = _statuses.Tabs[tbName];
11735 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11736 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11737 cmb.Text = cmb.Text.Trim();
11738 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11739 bool Quote = false;
11740 StringBuilder buf = new StringBuilder();
11741 char[] c = cmb.Text.ToCharArray();
11742 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11744 if (cnt > cmb.Text.Length - 4)
11746 buf.Append(cmb.Text.Substring(cnt));
11755 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11757 buf.Append(" OR ");
11762 buf.Append(c[cnt]);
11764 cmb.Text = buf.ToString();
11766 var listView = (DetailsListView)pnl.Parent.Tag;
11768 tb.SearchWords = cmb.Text;
11769 tb.SearchLang = cmbLang.Text;
11770 if (string.IsNullOrEmpty(cmb.Text))
11776 if (tb.IsSearchQueryChanged)
11778 int idx = cmb.Items.IndexOf(tb.SearchWords);
11779 if (idx > -1) cmb.Items.RemoveAt(idx);
11780 cmb.Items.Insert(0, tb.SearchWords);
11781 cmb.Text = tb.SearchWords;
11783 this.PurgeListViewItemCache();
11784 listView.VirtualListSize = 0;
11785 _statuses.ClearTabIds(tbName);
11786 SaveConfigsTabs(); //検索条件の保存
11789 this.GetPublicSearchAsync(tb);
11793 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11796 await this.DoRefreshMore();
11800 /// 指定されたタブのListTabにおける位置を返します
11803 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
11805 public int GetTabPageIndex(string tabName)
11808 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
11810 if (tabPage.Text == tabName)
11819 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11821 if (_statuses.RemovedTab.Count == 0)
11823 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11828 DetailsListView listView = null;
11830 TabClass tb = _statuses.RemovedTab.Pop();
11831 if (tb.TabType == MyCommon.TabUsageType.Related)
11833 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11834 if (relatedTab != null)
11836 // 関連発言なら既存のタブを置き換える
11837 tb.TabName = relatedTab.TabName;
11838 this.ClearTab(tb.TabName, false);
11839 _statuses.Tabs[tb.TabName] = tb;
11841 for (int i = 0; i < ListTab.TabPages.Count; i++)
11843 var tabPage = ListTab.TabPages[i];
11844 if (tb.TabName == tabPage.Text)
11846 listView = (DetailsListView)tabPage.Tag;
11847 ListTab.SelectedIndex = i;
11854 const string TabName = "Related Tweets";
11855 string renamed = TabName;
11856 for (int i = 2; i <= 100; i++)
11858 if (!_statuses.ContainsTab(renamed)) break;
11859 renamed = TabName + i.ToString();
11861 tb.TabName = renamed;
11862 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11863 _statuses.Tabs.Add(renamed, tb); // 後に
11865 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11866 listView = (DetailsListView)tabPage.Tag;
11867 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11872 string renamed = tb.TabName;
11873 for (int i = 1; i < int.MaxValue; i++)
11875 if (!_statuses.ContainsTab(renamed)) break;
11876 renamed = tb.TabName + "(" + i.ToString() + ")";
11878 tb.TabName = renamed;
11879 _statuses.Tabs.Add(renamed, tb); // 先に
11880 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11882 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11883 listView = (DetailsListView)tabPage.Tag;
11884 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11888 if (listView != null)
11890 using (ControlTransaction.Update(listView))
11892 listView.VirtualListSize = tb.AllCount;
11898 private async Task doMoveToRTHome()
11900 if (_curList.SelectedIndices.Count > 0)
11902 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11903 if (post.RetweetedId != null)
11905 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11910 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11912 await this.doMoveToRTHome();
11915 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11917 string name = GetUserId();
11923 if (_curList.SelectedIndices.Count == 0) return;
11926 if (!SelectTab(out tabName)) return;
11928 var tab = this._statuses.Tabs[tabName];
11932 if (tab.TabType != MyCommon.TabUsageType.Mute)
11934 this.MoveOrCopy(out mv, out mk);
11938 // ミュートタブでは常に MoveMatches を true にする
11943 PostFilterRule fc = new PostFilterRule();
11944 fc.FilterName = name;
11945 fc.UseNameField = true;
11946 fc.MoveMatches = mv;
11947 fc.MarkMatches = mk;
11948 fc.UseRegex = false;
11949 fc.FilterByUrl = false;
11952 this.ApplyPostFilters();
11957 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11961 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11963 if (menuItem.Owner == this.ContextMenuPostBrowser)
11965 user = GetUserId();
11966 if (user == null) return;
11968 else if (this._curPost != null)
11970 user = this._curPost.ScreenName;
11977 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11981 this.tw.GetListsApi();
11983 catch (WebApiException ex)
11985 MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
11990 using (MyLists listSelectForm = new MyLists(user, this.tw))
11992 listSelectForm.ShowDialog(this);
11996 private void SearchControls_Enter(object sender, EventArgs e)
11998 Control pnl = (Control)sender;
11999 foreach (Control ctl in pnl.Controls)
12001 ctl.TabStop = true;
12005 private void SearchControls_Leave(object sender, EventArgs e)
12007 Control pnl = (Control)sender;
12008 foreach (Control ctl in pnl.Controls)
12010 ctl.TabStop = false;
12014 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
12016 if (ListTab.SelectedTab != null)
12018 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
12019 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
12023 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
12025 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
12028 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
12029 HashStripSplitButton.Text = HashMgr.UseHash;
12030 HashToggleMenuItem.Checked = true;
12031 HashToggleToolStripMenuItem.Checked = true;
12033 ModifySettingCommon = true;
12037 private void StatusLabel_DoubleClick(object sender, EventArgs e)
12039 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
12042 private void HashManageMenuItem_Click(object sender, EventArgs e)
12044 DialogResult rslt = DialogResult.Cancel;
12047 rslt = HashMgr.ShowDialog();
12053 this.TopMost = this._cfgCommon.AlwaysTop;
12054 if (rslt == DialogResult.Cancel) return;
12055 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12057 HashStripSplitButton.Text = HashMgr.UseHash;
12058 HashToggleMenuItem.Checked = true;
12059 HashToggleToolStripMenuItem.Checked = true;
12063 HashStripSplitButton.Text = "#[-]";
12064 HashToggleMenuItem.Checked = false;
12065 HashToggleToolStripMenuItem.Checked = false;
12067 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
12069 // int sidx = StatusText.SelectionStart;
12070 // string hash = HashMgr.UseHash + " ";
12073 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
12074 // hash = " " + hash;
12076 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
12077 // sidx += hash.Length;
12078 // StatusText.SelectionStart = sidx;
12079 // StatusText.Focus();
12081 ModifySettingCommon = true;
12082 this.StatusText_TextChanged(null, null);
12085 private void HashToggleMenuItem_Click(object sender, EventArgs e)
12087 HashMgr.ToggleHash();
12088 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12090 HashStripSplitButton.Text = HashMgr.UseHash;
12091 HashToggleMenuItem.Checked = true;
12092 HashToggleToolStripMenuItem.Checked = true;
12096 HashStripSplitButton.Text = "#[-]";
12097 HashToggleMenuItem.Checked = false;
12098 HashToggleToolStripMenuItem.Checked = false;
12100 ModifySettingCommon = true;
12101 this.StatusText_TextChanged(null, null);
12104 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
12106 HashToggleMenuItem_Click(null, null);
12109 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
12111 if (ListTab.SelectedTab == null) return;
12112 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
12113 if (!this.ExistCurrentPost)
12115 this.ReplyOpMenuItem.Enabled = false;
12116 this.ReplyAllOpMenuItem.Enabled = false;
12117 this.DmOpMenuItem.Enabled = false;
12118 this.ShowProfMenuItem.Enabled = false;
12119 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
12120 this.ListManageMenuItem.Enabled = false;
12121 this.OpenFavOpMenuItem.Enabled = false;
12122 this.CreateTabRuleOpMenuItem.Enabled = false;
12123 this.CreateIdRuleOpMenuItem.Enabled = false;
12124 this.CreateSourceRuleOpMenuItem.Enabled = false;
12125 this.ReadOpMenuItem.Enabled = false;
12126 this.UnreadOpMenuItem.Enabled = false;
12130 this.ReplyOpMenuItem.Enabled = true;
12131 this.ReplyAllOpMenuItem.Enabled = true;
12132 this.DmOpMenuItem.Enabled = true;
12133 this.ShowProfMenuItem.Enabled = true;
12134 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
12135 this.ListManageMenuItem.Enabled = true;
12136 this.OpenFavOpMenuItem.Enabled = true;
12137 this.CreateTabRuleOpMenuItem.Enabled = true;
12138 this.CreateIdRuleOpMenuItem.Enabled = true;
12139 this.CreateSourceRuleOpMenuItem.Enabled = true;
12140 this.ReadOpMenuItem.Enabled = true;
12141 this.UnreadOpMenuItem.Enabled = true;
12144 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
12146 this.FavOpMenuItem.Enabled = false;
12147 this.UnFavOpMenuItem.Enabled = false;
12148 this.OpenStatusOpMenuItem.Enabled = false;
12149 this.OpenFavotterOpMenuItem.Enabled = false;
12150 this.ShowRelatedStatusesMenuItem2.Enabled = false;
12151 this.RtOpMenuItem.Enabled = false;
12152 this.RtUnOpMenuItem.Enabled = false;
12153 this.QtOpMenuItem.Enabled = false;
12154 this.FavoriteRetweetMenuItem.Enabled = false;
12155 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12159 this.FavOpMenuItem.Enabled = true;
12160 this.UnFavOpMenuItem.Enabled = true;
12161 this.OpenStatusOpMenuItem.Enabled = true;
12162 this.OpenFavotterOpMenuItem.Enabled = true;
12163 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
12167 this.RtOpMenuItem.Enabled = false; //公式RTは無効に
12168 this.RtUnOpMenuItem.Enabled = true;
12169 this.QtOpMenuItem.Enabled = true;
12170 this.FavoriteRetweetMenuItem.Enabled = false; //公式RTは無効に
12171 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12175 if (_curPost.IsProtect)
12177 this.RtOpMenuItem.Enabled = false;
12178 this.RtUnOpMenuItem.Enabled = false;
12179 this.QtOpMenuItem.Enabled = false;
12180 this.FavoriteRetweetMenuItem.Enabled = false;
12181 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12185 this.RtOpMenuItem.Enabled = true;
12186 this.RtUnOpMenuItem.Enabled = true;
12187 this.QtOpMenuItem.Enabled = true;
12188 this.FavoriteRetweetMenuItem.Enabled = true;
12189 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12194 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
12196 this.RefreshPrevOpMenuItem.Enabled = true;
12200 this.RefreshPrevOpMenuItem.Enabled = false;
12202 if (!this.ExistCurrentPost
12203 || _curPost.InReplyToStatusId == null)
12205 OpenRepSourceOpMenuItem.Enabled = false;
12209 OpenRepSourceOpMenuItem.Enabled = true;
12211 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12213 OpenRterHomeMenuItem.Enabled = false;
12217 OpenRterHomeMenuItem.Enabled = true;
12220 if (this.ExistCurrentPost)
12222 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
12226 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12228 ContextMenuTabProperty_Opening(sender, null);
12231 public Twitter TwitterInstance
12236 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12238 if (this._initialLayout)
12241 int splitterDistance;
12242 switch (this.WindowState)
12244 case FormWindowState.Normal:
12245 splitterDistance = this.SplitContainer3.SplitterDistance;
12247 case FormWindowState.Maximized:
12248 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
12249 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
12250 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
12251 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
12257 this._mySpDis3 = splitterDistance;
12258 this.ModifySettingLocal = true;
12261 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12263 if (_statuses.RemovedTab.Count == 0)
12265 UndoRemoveTabMenuItem.Enabled = false;
12269 UndoRemoveTabMenuItem.Enabled = true;
12271 if (ListTab.SelectedTab != null)
12273 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12274 PublicSearchQueryMenuItem.Enabled = true;
12276 PublicSearchQueryMenuItem.Enabled = false;
12280 PublicSearchQueryMenuItem.Enabled = false;
12282 if (!this.ExistCurrentPost)
12284 this.CopySTOTMenuItem.Enabled = false;
12285 this.CopyURLMenuItem.Enabled = false;
12286 this.CopyUserIdStripMenuItem.Enabled = false;
12290 this.CopySTOTMenuItem.Enabled = true;
12291 this.CopyURLMenuItem.Enabled = true;
12292 this.CopyUserIdStripMenuItem.Enabled = true;
12293 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12294 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12298 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12300 SetNotifyIconText();
12303 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12305 var id = _curPost?.ScreenName ?? "";
12307 await this.ShowUserStatus(id);
12310 private async Task doShowUserStatus(string id, bool ShowInputDialog)
12312 TwitterUser user = null;
12314 if (ShowInputDialog)
12316 using (var inputName = new InputTabName())
12318 inputName.FormTitle = "Show UserStatus";
12319 inputName.FormDescription = Properties.Resources.FRMessage1;
12320 inputName.TabName = id;
12322 if (inputName.ShowDialog(this) != DialogResult.OK)
12324 if (string.IsNullOrWhiteSpace(inputName.TabName))
12327 id = inputName.TabName.Trim();
12331 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
12333 var cancellationToken = dialog.EnableCancellation();
12337 var task = Task.Run(() => this.tw.GetUserInfo(id));
12338 user = await dialog.WaitForAsync(this, task);
12340 catch (WebApiException ex)
12342 if (!cancellationToken.IsCancellationRequested)
12343 MessageBox.Show(ex.Message);
12347 if (cancellationToken.IsCancellationRequested)
12351 await this.doShowUserStatus(user);
12354 private async Task doShowUserStatus(TwitterUser user)
12356 using (var userDialog = new UserInfoDialog(this, this.tw))
12358 var showUserTask = userDialog.ShowUserAsync(user);
12359 userDialog.ShowDialog(this);
12362 this.BringToFront();
12364 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12365 await showUserTask;
12369 private Task ShowUserStatus(string id, bool ShowInputDialog)
12371 return this.doShowUserStatus(id, ShowInputDialog);
12374 private Task ShowUserStatus(string id)
12376 return this.doShowUserStatus(id, true);
12379 private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12381 if (NameLabel.Tag != null)
12383 string id = (string)NameLabel.Tag;
12384 if (id != tw.Username)
12386 await this.FollowCommand(id);
12391 private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12393 if (NameLabel.Tag != null)
12395 string id = (string)NameLabel.Tag;
12396 if (id != tw.Username)
12398 await this.RemoveCommand(id, false);
12403 private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12405 if (NameLabel.Tag != null)
12407 string id = (string)NameLabel.Tag;
12408 if (id != tw.Username)
12410 await this.ShowFriendship(id);
12415 private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12417 if (NameLabel.Tag != null)
12419 string id = (string)NameLabel.Tag;
12420 await this.ShowUserStatus(id, false);
12424 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12426 if (NameLabel.Tag != null)
12428 string id = (string)NameLabel.Tag;
12429 AddNewTabForUserTimeline(id);
12433 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12435 if (NameLabel.Tag != null)
12437 string id = (string)NameLabel.Tag;
12438 AddNewTabForSearch("@" + id);
12442 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
12444 if (_curPost != null)
12446 await this.ShowUserStatus(_curPost.ScreenName, false);
12450 private async void RtCountMenuItem_Click(object sender, EventArgs e)
12452 if (!this.ExistCurrentPost)
12455 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
12456 int retweetCount = 0;
12458 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
12460 var cancellationToken = dialog.EnableCancellation();
12464 var task = Task.Run(() => this.tw.GetStatus_Retweeted_Count(statusId));
12465 retweetCount = await dialog.WaitForAsync(this, task);
12467 catch (WebApiException ex)
12469 if (!cancellationToken.IsCancellationRequested)
12470 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + ex.Message);
12474 if (cancellationToken.IsCancellationRequested)
12478 MessageBox.Show(retweetCount + Properties.Resources.RtCountText1);
12481 private HookGlobalHotkey _hookGlobalHotkey;
12484 _hookGlobalHotkey = new HookGlobalHotkey(this);
12486 // この呼び出しは、Windows フォーム デザイナで必要です。
12487 InitializeComponent();
12489 // InitializeComponent() 呼び出しの後で初期化を追加します。
12491 if (!this.DesignMode)
12493 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12494 this.StatusText.Dock = DockStyle.Fill;
12497 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12498 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12499 this.gh.NotifyClicked += GrowlHelper_Callback;
12501 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12502 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12504 this.ImageSelector.Visible = false;
12505 this.ImageSelector.Enabled = false;
12506 this.ImageSelector.FilePickDialog = OpenFileDialog1;
12508 this.ReplaceAppName();
12509 this.InitializeShortcuts();
12512 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12514 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12517 this.Visible = false;
12519 else if (Form.ActiveForm == null)
12521 this.Visible = true;
12522 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12524 this.BringToFront();
12525 this.StatusText.Focus();
12529 private void UserPicture_MouseEnter(object sender, EventArgs e)
12531 this.UserPicture.Cursor = Cursors.Hand;
12534 private void UserPicture_MouseLeave(object sender, EventArgs e)
12536 this.UserPicture.Cursor = Cursors.Default;
12539 private async void UserPicture_DoubleClick(object sender, EventArgs e)
12541 if (NameLabel.Tag != null)
12543 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12547 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12549 this.MultiLineMenuItem.PerformClick();
12552 public PostClass CurPost
12554 get { return _curPost; }
12558 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12560 if (ImageSelector.Visible)
12561 ImageSelector.EndSelection();
12563 ImageSelector.BeginSelection();
12566 private void SelectMedia_DragEnter(DragEventArgs e)
12568 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12570 e.Effect = DragDropEffects.Copy;
12573 e.Effect = DragDropEffects.None;
12576 private void SelectMedia_DragDrop(DragEventArgs e)
12579 this.BringToFront();
12580 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12581 StatusText.Focus();
12584 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12586 TimelinePanel.Visible = false;
12587 TimelinePanel.Enabled = false;
12590 private void ImageSelector_EndSelecting(object sender, EventArgs e)
12592 TimelinePanel.Visible = true;
12593 TimelinePanel.Enabled = true;
12594 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12597 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12599 this.AllowDrop = false;
12602 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12604 this.AllowDrop = true;
12607 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12609 if (ImageSelector.Visible)
12611 ModifySettingCommon = true;
12612 SaveConfigsAll(true);
12614 if (ImageSelector.ServiceName.Equals("Twitter"))
12615 this.StatusText_TextChanged(null, null);
12619 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12621 this.StatusText_TextChanged(null, null);
12625 /// StatusTextでCtrl+Vが押下された時の処理
12627 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
12629 if (Clipboard.ContainsText())
12631 // clipboardにテキストがある場合は貼り付け処理
12632 this.StatusText.Paste(Clipboard.GetText());
12634 else if (Clipboard.ContainsImage())
12637 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
12638 Properties.Resources.PostPictureWarn4,
12639 MessageBoxButtons.OKCancel,
12640 MessageBoxIcon.Question,
12641 MessageBoxDefaultButton.Button2)
12642 == DialogResult.OK)
12644 // clipboardから画像を取得
12645 using (var image = Clipboard.GetImage())
12647 this.ImageSelector.BeginSelection(image);
12654 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12656 using (ListManage form = new ListManage(tw))
12658 form.ShowDialog(this);
12662 public bool ModifySettingCommon { get; set; }
12663 public bool ModifySettingLocal { get; set; }
12664 public bool ModifySettingAtId { get; set; }
12666 private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12668 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12669 if (sourceUri != null && e.Button == MouseButtons.Left)
12671 await this.OpenUriInBrowserAsync(sourceUri.AbsoluteUri);
12675 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12677 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12678 if (sourceUri != null)
12680 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri);
12684 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12686 SetStatusLabelUrl();
12689 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12691 if (this.ExistCurrentPost && !_curPost.IsDm)
12692 RtCountMenuItem.Enabled = true;
12694 RtCountMenuItem.Enabled = false;
12696 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12697 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12699 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12702 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12707 private void CopyUserId()
12709 if (_curPost == null) return;
12710 string clstr = _curPost.ScreenName;
12713 Clipboard.SetDataObject(clstr, false, 5, 100);
12715 catch (Exception ex)
12717 MessageBox.Show(ex.Message);
12721 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12723 if (this.ExistCurrentPost && !_curPost.IsDm)
12727 await this.OpenRelatedTab(this._curPost);
12729 catch (TabException ex)
12731 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12737 /// 指定されたツイートに対する関連発言タブを開きます
12739 /// <param name="statusId">表示するツイートのID</param>
12740 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12741 private async Task OpenRelatedTab(long statusId)
12743 var post = this._statuses[statusId];
12748 post = await Task.Run(() => this.tw.GetStatusApi(false, statusId));
12750 catch (WebApiException ex)
12752 this.StatusLabel.Text = ex.Message;
12757 await this.OpenRelatedTab(post);
12761 /// 指定されたツイートに対する関連発言タブを開きます
12763 /// <param name="post">表示する対象となるツイート</param>
12764 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12765 private async Task OpenRelatedTab(PostClass post)
12767 var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12770 if (tabRelated == null)
12772 tabName = this._statuses.MakeTabName("Related Tweets");
12774 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12775 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12777 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12778 tabRelated.UnreadManage = false;
12779 tabRelated.Notify = false;
12783 tabName = tabRelated.TabName;
12786 tabRelated.RelationTargetPost = post;
12787 this.ClearTab(tabName, false);
12789 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12791 var tabPage = this.ListTab.TabPages[i];
12792 if (tabName == tabPage.Text)
12794 this.ListTab.SelectedIndex = i;
12799 await this.GetRelatedTweetsAsync(tabRelated);
12802 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12804 StringBuilder buf = new StringBuilder();
12805 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12806 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12807 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12808 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12809 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12812 private void tw_UserIdChanged()
12814 this.ModifySettingCommon = true;
12817 #region "Userstream"
12818 private bool _isActiveUserstream = false;
12820 private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12824 if (InvokeRequired && !IsDisposed)
12826 Invoke((Action) (async () =>
12828 _statuses.RemovePostReserve(e.StatusId);
12829 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12831 this.PurgeListViewItemCache();
12832 ((DetailsListView)_curTab.Tag).Update();
12833 if (_curPost != null && _curPost.StatusId == e.StatusId)
12834 await this.DispSelectedPost(true);
12840 catch (ObjectDisposedException)
12844 catch (InvalidOperationException)
12850 private int userStreamsRefreshing = 0;
12852 private async void tw_NewPostFromStream(object sender, EventArgs e)
12854 if (this._cfgCommon.ReadOldPosts)
12856 _statuses.SetReadHomeTab(); //新着時未読クリア
12859 int rsltAddCount = _statuses.DistributePosts();
12861 this.UpdateTimelineSpeed(rsltAddCount);
12863 if (this._cfgCommon.UserstreamPeriod > 0) return;
12865 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
12866 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
12870 await this.InvokeAsync(() => this.RefreshTimeline())
12871 .ConfigureAwait(false);
12875 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
12880 private void tw_UserStreamStarted(object sender, EventArgs e)
12882 this._isActiveUserstream = true;
12885 if (InvokeRequired && !IsDisposed)
12887 Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12891 catch (ObjectDisposedException)
12895 catch (InvalidOperationException)
12900 MenuItemUserStream.Text = "&UserStream ▶";
12901 MenuItemUserStream.Enabled = true;
12902 StopToolStripMenuItem.Text = "&Stop";
12903 StopToolStripMenuItem.Enabled = true;
12905 StatusLabel.Text = "UserStream Started.";
12908 private void tw_UserStreamStopped(object sender, EventArgs e)
12910 this._isActiveUserstream = false;
12913 if (InvokeRequired && !IsDisposed)
12915 Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12919 catch (ObjectDisposedException)
12923 catch (InvalidOperationException)
12928 MenuItemUserStream.Text = "&UserStream ■";
12929 MenuItemUserStream.Enabled = true;
12930 StopToolStripMenuItem.Text = "&Start";
12931 StopToolStripMenuItem.Enabled = true;
12933 StatusLabel.Text = "UserStream Stopped.";
12936 private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12940 if (InvokeRequired && !IsDisposed)
12942 Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12946 catch (ObjectDisposedException)
12950 catch (InvalidOperationException)
12954 var ev = e.EventData;
12955 StatusLabel.Text = "Event: " + ev.Event;
12956 //if (ev.Event == "favorite")
12958 // NotifyFavorite(ev);
12961 if (ev.Event == "favorite" || ev.Event == "unfavorite")
12963 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12965 this.PurgeListViewItemCache();
12966 ((DetailsListView)_curTab.Tag).Update();
12968 if (ev.Event == "unfavorite" && ev.Username.ToLower().Equals(tw.Username.ToLower()))
12970 RemovePostFromFavTab(new long[] {ev.Id});
12975 private void NotifyEvent(Twitter.FormattedEvent ev)
12978 if (BalloonRequired(ev))
12980 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
12981 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
12982 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
12983 StringBuilder title = new StringBuilder();
12984 if (this._cfgCommon.DispUsername)
12986 title.Append(tw.Username);
12987 title.Append(" - ");
12993 title.Append(Application.ProductName);
12994 title.Append(" [");
12995 title.Append(ev.Event.ToUpper());
12996 title.Append("] by ");
12997 if (!string.IsNullOrEmpty(ev.Username))
12999 title.Append(ev.Username.ToString());
13003 //title.Append("");
13006 if (!string.IsNullOrEmpty(ev.Target))
13008 //NotifyIcon1.BalloonTipText = ev.Target;
13013 //NotifyIcon1.BalloonTipText = " ";
13016 //NotifyIcon1.ShowBalloonTip(500);
13017 if (this._cfgCommon.IsUseNotifyGrowl)
13019 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13020 ev.Id.ToString(), title.ToString(), text);
13024 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13025 NotifyIcon1.BalloonTipTitle = title.ToString();
13026 NotifyIcon1.BalloonTipText = text;
13027 NotifyIcon1.ShowBalloonTip(500);
13032 string snd = this._cfgCommon.EventSoundFile;
13033 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
13035 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13039 string dir = Application.StartupPath;
13040 if (Directory.Exists(Path.Combine(dir, "Sounds")))
13042 dir = Path.Combine(dir, "Sounds");
13044 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13056 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13058 MenuItemUserStream.Enabled = false;
13059 if (StopRefreshAllMenuItem.Checked)
13061 StopRefreshAllMenuItem.Checked = false;
13064 if (this._isActiveUserstream)
13066 tw.StopUserStream();
13070 tw.StartUserStream();
13074 private static string inputTrack = "";
13076 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13078 if (TrackToolStripMenuItem.Checked)
13080 using (InputTabName inputForm = new InputTabName())
13082 inputForm.TabName = inputTrack;
13083 inputForm.FormTitle = "Input track word";
13084 inputForm.FormDescription = "Track word";
13085 if (inputForm.ShowDialog() != DialogResult.OK)
13087 TrackToolStripMenuItem.Checked = false;
13090 inputTrack = inputForm.TabName.Trim();
13092 if (!inputTrack.Equals(tw.TrackWord))
13094 tw.TrackWord = inputTrack;
13095 this.ModifySettingCommon = true;
13096 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13097 tw.ReconnectUserStream();
13103 tw.ReconnectUserStream();
13105 this.ModifySettingCommon = true;
13108 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13110 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13111 this.ModifySettingCommon = true;
13112 tw.ReconnectUserStream();
13115 private void EventViewerMenuItem_Click(object sender, EventArgs e)
13117 if (evtDialog == null || evtDialog.IsDisposed)
13120 evtDialog = new EventViewerDialog();
13121 evtDialog.Owner = this;
13123 Point pos = evtDialog.Location;
13124 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13125 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13126 evtDialog.Location = pos;
13128 evtDialog.EventSource = tw.StoredEvent;
13129 if (!evtDialog.Visible)
13131 evtDialog.Show(this);
13135 evtDialog.Activate();
13137 this.TopMost = this._cfgCommon.AlwaysTop;
13141 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13143 MyCommon._endingFlag = true;
13147 Application.Restart();
13151 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13155 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13157 if (!string.IsNullOrEmpty(tw.Username))
13158 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13161 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13163 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
13166 private async Task doTranslation(string str)
13168 if (string.IsNullOrEmpty(str))
13171 var bing = new Bing();
13174 var translatedText = await bing.TranslateAsync(str,
13176 langTo: this._cfgCommon.TranslateLanguage);
13178 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
13180 catch (HttpRequestException e)
13182 this.StatusLabel.Text = "Err:" + e.Message;
13186 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13188 if (!this.ExistCurrentPost)
13191 await this.doTranslation(this._curPost.TextFromApi);
13194 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13196 var text = this.PostBrowser.GetSelectedText();
13197 await this.doTranslation(text);
13200 private bool ExistCurrentPost
13204 if (_curPost == null) return false;
13205 if (_curPost.IsDeleted) return false;
13210 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13212 ShowUserTimeline();
13215 private string GetUserIdFromCurPostOrInput(string caption)
13217 var id = _curPost?.ScreenName ?? "";
13219 using (InputTabName inputName = new InputTabName())
13221 inputName.FormTitle = caption;
13222 inputName.FormDescription = Properties.Resources.FRMessage1;
13223 inputName.TabName = id;
13224 if (inputName.ShowDialog() == DialogResult.OK &&
13225 !string.IsNullOrEmpty(inputName.TabName.Trim()))
13227 id = inputName.TabName.Trim();
13237 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13239 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13240 if (!string.IsNullOrEmpty(id))
13242 AddNewTabForUserTimeline(id);
13246 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13248 string id = GetUserIdFromCurPostOrInput("Show Favstar");
13249 if (!string.IsNullOrEmpty(id))
13251 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13255 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13257 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13260 private void TimelineRefreshEnableChange(bool isEnable)
13264 tw.StartUserStream();
13268 tw.StopUserStream();
13270 TimerTimeline.Enabled = isEnable;
13273 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13275 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13278 private async Task OpenUserAppointUrl()
13280 if (this._cfgCommon.UserAppointUrl != null)
13282 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
13284 if (_curPost != null)
13286 string xUrl = this._cfgCommon.UserAppointUrl;
13287 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13289 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
13290 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
13292 await this.OpenUriInBrowserAsync(xUrl);
13297 await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
13302 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13304 await this.OpenUserAppointUrl();
13307 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13309 string selText = SourceLinkLabel.Text;
13312 Clipboard.SetDataObject(selText, false, 5, 100);
13314 catch (Exception ex)
13316 MessageBox.Show(ex.Message);
13320 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13322 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
13325 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
13327 catch (Exception ex)
13329 MessageBox.Show(ex.Message);
13333 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13335 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13337 SourceCopyMenuItem.Enabled = false;
13338 SourceUrlCopyMenuItem.Enabled = false;
13342 SourceCopyMenuItem.Enabled = true;
13343 SourceUrlCopyMenuItem.Enabled = true;
13347 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13349 if (Form.ActiveForm == null)
13351 this.BeginInvoke((Action) (() =>
13353 this.Visible = true;
13354 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13356 this.BringToFront();
13357 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13359 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13363 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13369 private void ReplaceAppName()
13371 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13372 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13375 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13377 this.SplitContainer3.Panel2Collapsed = false;
13380 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13382 await this.OpenThumbnailPicture(e.Thumbnail);
13385 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13387 await this.OpenUriInBrowserAsync(e.ImageUrl);
13390 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
13392 var url = thumbnail.FullSizeImageUrl ?? thumbnail.ImageUrl;
13394 await this.OpenUriInBrowserAsync(url);
13397 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13399 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
13402 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13404 if (e.KeyCode == Keys.Space)
13406 this.JumpUnreadMenuItem_Click(null, null);
13408 e.SuppressKeyPress = true;
13412 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13414 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13415 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13416 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13417 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13418 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13420 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13423 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13425 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13428 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13430 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13433 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13435 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13438 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13440 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13443 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13445 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13448 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13450 if (this._cfgCommon.IconSize == iconSize) return;
13452 var oldIconCol = _iconCol;
13454 this._cfgCommon.IconSize = iconSize;
13455 ApplyListViewIconSize(iconSize);
13457 if (_iconCol != oldIconCol)
13459 foreach (TabPage tp in ListTab.TabPages)
13461 ResetColumns((DetailsListView)tp.Tag);
13465 _curList?.Refresh();
13467 ModifySettingCommon = true;
13470 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13472 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13473 if (this._cfgCommon.SortOrderLock == state) return;
13475 this._cfgCommon.SortOrderLock = state;
13477 ModifySettingCommon = true;