1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
28 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
29 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
32 using System.Collections.Generic;
33 using System.ComponentModel;
34 using System.Diagnostics;
40 using System.Net.Http;
41 using System.Reflection;
43 using System.Text.RegularExpressions;
44 using System.Threading;
45 using System.Threading.Tasks;
46 using System.Windows.Forms;
48 using OpenTween.Connection;
49 using OpenTween.OpenTweenCustomControl;
50 using OpenTween.Thumbnail;
54 public partial class TweenMain : OTBaseForm
57 private Size _mySize; //画面サイズ
58 private Point _myLoc; //画面位置
59 private int _mySpDis; //区切り位置
60 private int _mySpDis2; //発言欄区切り位置
61 private int _mySpDis3; //プレビュー区切り位置
62 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
63 private bool _iconCol; //1列表示の時true(48サイズのとき)
66 private bool _initial; //true:起動時処理中
67 private bool _initialLayout = true;
68 private bool _ignoreConfigSave; //true:起動時処理中
69 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
70 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
71 private Point _tabMouseDownPoint;
72 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
73 private readonly object _syncObject = new object(); //ロック用
75 private const string detailHtmlFormatHeaderMono =
76 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
77 + "<style type=\"text/css\"><!-- "
78 + "body, p, pre {margin: 0;} "
79 + "pre {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
80 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
81 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
82 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
83 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
85 + "</head><body><pre>";
86 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
87 private const string detailHtmlFormatHeaderColor =
88 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
89 + "<style type=\"text/css\"><!-- "
90 + "body, p, pre {margin: 0;} "
91 + "body {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); margin: 0; word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
92 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
93 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
94 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
95 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
98 private const string detailHtmlFormatFooterColor = "</p></body></html>";
99 private string detailHtmlFormatHeader;
100 private string detailHtmlFormatFooter;
102 private bool _myStatusError = false;
103 private bool _myStatusOnline = false;
104 private bool soundfileListup = false;
105 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
108 //private SettingToConfig _cfg; //旧
109 private SettingLocal _cfgLocal;
110 private SettingCommon _cfgCommon;
111 private bool _modifySettingLocal = false;
112 private bool _modifySettingCommon = false;
113 private bool _modifySettingAtId = false;
116 private Twitter tw = new Twitter();
119 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
122 private SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
123 private OpenURL UrlDialog = new OpenURL();
124 public AtIdSupplement AtIdSupl; //@id補助
125 public AtIdSupplement HashSupl; //Hashtag補助
126 public HashtagManage HashMgr;
127 private EventViewerDialog evtDialog;
130 private Font _fntUnread; //未読用フォント
131 private Color _clUnread; //未読用文字色
132 private Font _fntReaded; //既読用フォント
133 private Color _clReaded; //既読用文字色
134 private Color _clFav; //Fav用文字色
135 private Color _clOWL; //片思い用文字色
136 private Color _clRetweet; //Retweet用文字色
137 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
138 private Font _fntDetail; //発言詳細部用フォント
139 private Color _clDetail; //発言詳細部用色
140 private Color _clDetailLink; //発言詳細部用リンク文字色
141 private Color _clDetailBackcolor; //発言詳細部用背景色
142 private Color _clSelf; //自分の発言用背景色
143 private Color _clAtSelf; //自分宛返信用背景色
144 private Color _clTarget; //選択発言者の他の発言用背景色
145 private Color _clAtTarget; //選択発言中の返信先用背景色
146 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
147 private Color _clAtTo; //選択発言の唯一@先
148 private Color _clListBackcolor; //リスト部通常発言背景色
149 private Color _clInputBackcolor; //入力欄背景色
150 private Color _clInputFont; //入力欄文字色
151 private Font _fntInputFont; //入力欄フォント
152 private ImageCache IconCache; //アイコン画像リスト
153 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
154 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
155 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
156 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
157 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
158 private Icon MainIcon; //Main.ico 画面左上のアイコン
159 private Icon ReplyIcon; //5g
160 private Icon ReplyIconBlink; //6g
162 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
164 private PostClass _anchorPost;
165 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
167 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
168 private int _hisIdx; //発言履歴カレントインデックス
170 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
171 private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
174 private List<DateTime> _postTimestamps = new List<DateTime>();
175 private List<DateTime> _favTimestamps = new List<DateTime>();
176 private Dictionary<DateTime, int> _tlTimestamps = new Dictionary<DateTime, int>();
177 private int _tlCount;
180 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
181 private SolidBrush _brsBackColorMine;
182 private SolidBrush _brsBackColorAt;
183 private SolidBrush _brsBackColorYou;
184 private SolidBrush _brsBackColorAtYou;
185 private SolidBrush _brsBackColorAtFromTarget;
186 private SolidBrush _brsBackColorAtTo;
187 private SolidBrush _brsBackColorNone;
188 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
189 private StringFormat sfTab = new StringFormat();
191 //////////////////////////////////////////////////////////////////////////////////////////////////////////
192 private TabInformations _statuses;
194 // ListViewItem のキャッシュ関連
195 private int _itemCacheIndex;
196 private ListViewItem[] _itemCache;
197 private PostClass[] _postCache;
198 private ReaderWriterLockSlim itemCacheLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
200 private TabPage _curTab;
201 private int _curItemIndex;
202 private DetailsListView _curList;
203 private PostClass _curPost;
204 private bool _isColumnChanged = false;
206 private const int MAX_WORKER_THREADS = 20;
207 private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
208 private CancellationTokenSource workerCts = new CancellationTokenSource();
210 private int UnreadCounter = -1;
211 private int UnreadAtCounter = -1;
213 private string[] ColumnOrgText = new string[9];
214 private string[] ColumnText = new string[9];
216 private bool _DoFavRetweetFlags = false;
217 private bool osResumed = false;
219 //////////////////////////////////////////////////////////////////////////////////////////////////////////
220 private string _postBrowserStatusText = "";
222 private bool _colorize = false;
224 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
226 private ImageListViewItem displayItem;
228 private string recommendedStatusFooter;
231 private struct urlUndo
233 public string Before;
237 private List<urlUndo> urlUndoBuffer = null;
239 private struct ReplyChain
241 public long OriginalId;
242 public long InReplyToId;
243 public TabPage OriginalTab;
245 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
247 this.OriginalId = originalId;
248 this.InReplyToId = inReplyToId;
249 this.OriginalTab = originalTab;
253 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
254 private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
257 private enum SEARCHTYPE
264 private class PostingStatus
266 public string status = "";
267 public long? inReplyToId = null;
268 public string inReplyToName = null;
269 public string imageService = ""; //画像投稿サービス名
270 public IMediaItem[] mediaItems = null;
271 public PostingStatus()
274 public PostingStatus(string status, long? replyToId, string replyToName)
276 this.status = status;
277 this.inReplyToId = replyToId;
278 this.inReplyToName = replyToName;
282 private void TweenMain_Activated(object sender, EventArgs e)
284 //画面がアクティブになったら、発言欄の背景色戻す
285 if (StatusText.Focused)
287 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
291 private bool disposed = false;
294 /// 使用中のリソースをすべてクリーンアップします。
296 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
297 protected override void Dispose(bool disposing)
299 base.Dispose(disposing);
306 this.components?.Dispose();
309 SearchDialog.Dispose();
312 NIconAtRed?.Dispose();
313 NIconAtSmoke?.Dispose();
314 foreach (var iconRefresh in this.NIconRefresh)
316 iconRefresh?.Dispose();
320 ReplyIcon?.Dispose();
321 ReplyIconBlink?.Dispose();
322 _listViewImageList.Dispose();
323 _brsHighLight.Dispose();
324 _brsBackColorMine?.Dispose();
325 _brsBackColorAt?.Dispose();
326 _brsBackColorYou?.Dispose();
327 _brsBackColorAtYou?.Dispose();
328 _brsBackColorAtFromTarget?.Dispose();
329 _brsBackColorAtTo?.Dispose();
330 _brsBackColorNone?.Dispose();
331 _brsDeactiveSelection?.Dispose();
335 this.workerCts.Cancel();
337 if (IconCache != null)
339 this.IconCache.CancelAsync();
340 this.IconCache.Dispose();
343 this.thumbnailTokenSource?.Dispose();
345 this.itemCacheLock.Dispose();
347 this._hookGlobalHotkey.Dispose();
350 // 終了時にRemoveHandlerしておかないとメモリリークする
351 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
352 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
354 this.disposed = true;
357 private void LoadIcons()
359 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
360 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
363 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
366 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
369 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
372 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
374 // タスクトレイ: オフライン時アイコン
375 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
377 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
378 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
379 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
381 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
382 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
383 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
384 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
385 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
387 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
389 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
390 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
391 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
392 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
393 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
395 if (iconReply != null && iconReplyBlink != null)
397 this.ReplyIcon = iconReply;
398 this.ReplyIconBlink = iconReplyBlink;
402 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
403 this.ReplyIconBlink = this.NIconAt;
406 if (iconRefresh1 == null)
408 this.NIconRefresh = new[] {
409 Properties.Resources.Refresh, Properties.Resources.Refresh2,
410 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
413 else if (iconRefresh2 == null)
415 this.NIconRefresh = new[] { iconRefresh1 };
417 else if (iconRefresh3 == null)
419 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
421 else if (iconRefresh4 == null)
423 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
425 else // iconRefresh1 から iconRefresh4 まで全て揃っている
427 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
431 private Icon LoadIcon(string filePath)
433 if (!File.Exists(filePath))
438 return new Icon(filePath);
446 private void InitColumns(ListView list, bool startup)
448 this.InitColumnText();
450 ColumnHeader[] columns;
455 new ColumnHeader { Text = this.ColumnText[0], Width = 48 }, // アイコン
456 new ColumnHeader { Text = this.ColumnText[2], Width = 300 }, // 本文
461 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
463 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
464 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
465 columns[0].DisplayIndex = 0;
466 columns[1].DisplayIndex = 1;
471 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
473 columns[idx].Width = curListColumn.Width;
474 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
483 new ColumnHeader { Text = this.ColumnText[0], Width = 48 }, // アイコン
484 new ColumnHeader { Text = this.ColumnText[1], Width = 80 }, // ニックネーム
485 new ColumnHeader { Text = this.ColumnText[2], Width = 300 }, // 本文
486 new ColumnHeader { Text = this.ColumnText[3], Width = 50 }, // 日付
487 new ColumnHeader { Text = this.ColumnText[4], Width = 50 }, // ユーザID
488 new ColumnHeader { Text = this.ColumnText[5], Width = 16 }, // 未読
489 new ColumnHeader { Text = this.ColumnText[6], Width = 16 }, // マーク&プロテクト
490 new ColumnHeader { Text = this.ColumnText[7], Width = 50 }, // ソース
495 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
497 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
498 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
499 columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
500 columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
501 columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
502 columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
503 columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
504 columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
506 var displayIndex = new[] {
507 this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
508 this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
509 this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
510 this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
513 foreach (var i in Enumerable.Range(0, displayIndex.Length))
515 columns[i].DisplayIndex = displayIndex[i];
521 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
523 columns[idx].Width = curListColumn.Width;
524 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
530 list.Columns.AddRange(columns);
533 private void InitColumnText()
536 ColumnText[1] = Properties.Resources.AddNewTabText2;
537 ColumnText[2] = Properties.Resources.AddNewTabText3;
538 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
539 ColumnText[4] = Properties.Resources.AddNewTabText5;
542 ColumnText[7] = "Source";
544 ColumnOrgText[0] = "";
545 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
546 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
547 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
548 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
549 ColumnOrgText[5] = "";
550 ColumnOrgText[6] = "";
551 ColumnOrgText[7] = "Source";
554 switch (_statuses.SortMode)
556 case ComparerMode.Nickname: //ニックネーム
559 case ComparerMode.Data: //本文
562 case ComparerMode.Id: //時刻=発言Id
565 case ComparerMode.Name: //名前
568 case ComparerMode.Source: //Source
575 if (_statuses.SortOrder == SortOrder.Descending)
577 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
578 ColumnText[2] = ColumnOrgText[2] + "▾";
582 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
583 ColumnText[2] = ColumnOrgText[2] + "▴";
588 if (_statuses.SortOrder == SortOrder.Descending)
590 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
591 ColumnText[c] = ColumnOrgText[c] + "▾";
595 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
596 ColumnText[c] = ColumnOrgText[c] + "▴";
601 private void InitializeTraceFrag()
604 TraceOutToolStripMenuItem.Checked = true;
605 MyCommon.TraceFlag = true;
607 if (!MyCommon.FileVersion.EndsWith("0"))
609 TraceOutToolStripMenuItem.Checked = true;
610 MyCommon.TraceFlag = true;
614 private void TweenMain_Load(object sender, EventArgs e)
616 _ignoreConfigSave = true;
617 this.Visible = false;
619 if (MyApplication.StartupOptions.ContainsKey("d"))
620 MyCommon.TraceFlag = true;
622 InitializeTraceFrag();
624 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
626 new InternetSecurityManager(PostBrowser);
627 this.PostBrowser.AllowWebBrowserDrop = false; // COMException を回避するため、ActiveX の初期化が終わってから設定する
629 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
630 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
632 Regex.CacheSize = 100;
635 _statuses = TabInformations.GetInstance();
639 this.Icon = MainIcon; //メインフォーム(TweenMain)
640 NotifyIcon1.Icon = NIconAt; //タスクトレイ
641 TabImage.Images.Add(TabIcon); //タブ見出し
643 //<<<<<<<<<設定関連>>>>>>>>>
647 // 現在の DPI と設定保存時の DPI との比を取得する
648 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
651 var fontUIGlobal = this._cfgLocal.FontUIGlobal;
652 if (fontUIGlobal != null)
654 OTBaseForm.GlobalFont = fontUIGlobal;
655 this.Font = fontUIGlobal;
659 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
661 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
662 this._cfgCommon.TimelinePeriod = 15;
664 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
665 this._cfgCommon.ReplyPeriod = 15;
667 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
668 this._cfgCommon.DMPeriod = 15;
670 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
671 this._cfgCommon.PubSearchPeriod = 30;
673 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
674 this._cfgCommon.UserTimelinePeriod = 15;
676 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
677 this._cfgCommon.ListsPeriod = 15;
680 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
681 this._cfgCommon.CountApi = 60;
682 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
683 this._cfgCommon.CountApiReply = 40;
685 if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
686 this._cfgCommon.MoreCountApi = 200;
687 if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
688 this._cfgCommon.FirstCountApi = 100;
690 if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
691 this._cfgCommon.FavoritesCountApi = 40;
692 if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
693 this._cfgCommon.ListCountApi = 100;
694 if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
695 this._cfgCommon.SearchCountApi = 100;
696 if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
697 this._cfgCommon.UserTimelineCountApi = 20;
699 //廃止サービスが選択されていた場合ux.nuへ読み替え
700 if (this._cfgCommon.AutoShortUrlFirst < 0)
701 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
703 HttpTwitter.TwitterUrl = this._cfgCommon.TwitterUrl;
706 if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
707 tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
711 Networking.Initialize();
713 bool saveRequired = false;
714 bool firstRun = false;
716 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
717 if (string.IsNullOrEmpty(tw.Username))
722 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
723 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
724 string.IsNullOrEmpty(tw.Username))
726 Application.Exit(); //強制終了
732 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
733 Networking.SetWebProxy(this._cfgLocal.ProxyType,
734 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
735 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
736 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
738 HttpTwitter.TwitterUrl = this._cfgCommon.TwitterUrl;
739 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
740 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
741 tw.TrackWord = this._cfgCommon.TrackWord;
742 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
743 tw.AllAtReply = this._cfgCommon.AllAtReply;
744 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
745 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
746 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
747 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
750 //プロキシ設定等の通信まわりの初期化が済んでから処理する
751 ThumbnailGenerator.InitializeGenerator();
753 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
754 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
755 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
757 Thumbnail.Services.TonTwitterCom.InitializeOAuthToken = x =>
758 x.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
759 this.tw.AccessToken, this.tw.AccessTokenSecret, "", "");
762 ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
765 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
766 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
767 HashMgr = new HashtagManage(HashSupl,
768 _cfgCommon.HashTags.ToArray(),
769 _cfgCommon.HashSelected,
770 _cfgCommon.HashIsPermanent,
771 _cfgCommon.HashIsHead,
772 _cfgCommon.HashIsNotAddToAtReply);
773 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
776 this.IconCache = new ImageCache();
779 _fntUnread = this._cfgLocal.FontUnread;
780 _clUnread = this._cfgLocal.ColorUnread;
781 _fntReaded = this._cfgLocal.FontRead;
782 _clReaded = this._cfgLocal.ColorRead;
783 _clFav = this._cfgLocal.ColorFav;
784 _clOWL = this._cfgLocal.ColorOWL;
785 _clRetweet = this._cfgLocal.ColorRetweet;
786 _fntDetail = this._cfgLocal.FontDetail;
787 _clDetail = this._cfgLocal.ColorDetail;
788 _clDetailLink = this._cfgLocal.ColorDetailLink;
789 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
790 _clSelf = this._cfgLocal.ColorSelf;
791 _clAtSelf = this._cfgLocal.ColorAtSelf;
792 _clTarget = this._cfgLocal.ColorTarget;
793 _clAtTarget = this._cfgLocal.ColorAtTarget;
794 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
795 _clAtTo = this._cfgLocal.ColorAtTo;
796 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
797 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
798 _clInputFont = this._cfgLocal.ColorInputFont;
799 _fntInputFont = this._cfgLocal.FontInputFont;
801 _brsBackColorMine = new SolidBrush(_clSelf);
802 _brsBackColorAt = new SolidBrush(_clAtSelf);
803 _brsBackColorYou = new SolidBrush(_clTarget);
804 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
805 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
806 _brsBackColorAtTo = new SolidBrush(_clAtTo);
807 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
808 _brsBackColorNone = new SolidBrush(_clListBackcolor);
810 // StringFormatオブジェクトへの事前設定
811 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
812 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
813 //sf.FormatFlags = StringFormatFlags.LineLimit; //
814 sfTab.Alignment = StringAlignment.Center;
815 sfTab.LineAlignment = StringAlignment.Center;
817 InitDetailHtmlFormat();
819 //Regex statregex = new Regex("^0*");
820 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
822 _history.Add(new PostingStatus());
824 this.inReplyTo = null;
827 SearchDialog.Owner = this;
828 UrlDialog.Owner = this;
831 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
832 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
834 //新着取得時のリストスクロールをするか。trueならスクロールしない
835 ListLockMenuItem.Checked = _cfgCommon.ListLock;
836 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
838 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
839 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
841 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
842 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
845 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
846 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
847 _myLoc = _cfgLocal.FormLocation;
849 if (this.WindowState != FormWindowState.Minimized)
851 this.DesktopLocation = _cfgLocal.FormLocation;
852 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
853 bool outOfScreen = true;
854 if (Screen.AllScreens.Length == 1) //ハングするとの報告
856 foreach (Screen scr in Screen.AllScreens)
858 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
866 this.DesktopLocation = new Point(0, 0);
867 _myLoc = this.DesktopLocation;
871 this.TopMost = this._cfgCommon.AlwaysTop;
872 _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
873 _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
874 if (_cfgLocal.PreviewDistance == -1)
876 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
877 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
878 _cfgLocal.PreviewDistance = _mySpDis3;
882 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
884 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
885 //this.Tween_ClientSizeChanged(this, null);
886 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
887 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
889 StatusText.Font = _fntInputFont;
890 StatusText.ForeColor = _clInputFont;
892 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
893 this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
894 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
896 // NameLabel のフォントを OTBaseForm.GlobalFont に変更
897 this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
899 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
900 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
902 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
903 if (this._cfgCommon.UnreadManage == false)
905 ReadedStripMenuItem.Enabled = false;
906 UnreadStripMenuItem.Enabled = false;
911 DateTimeLabel.Text = "";
912 SourceLinkLabel.Text = "";
914 //リンク先URL表示部の初期化(画面左下)
915 StatusLabelUrl.Text = "";
917 StatusLabel.Text = "";
918 StatusLabel.AutoToolTip = false;
919 StatusLabel.ToolTipText = "";
921 lblLen.Text = GetRestStatusCount(true, false).ToString();
923 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
924 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
925 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
926 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
928 ////////////////////////////////////////////////////////////////////////////////
929 _statuses.SortOrder = (SortOrder)_cfgCommon.SortOrder;
930 var mode = ComparerMode.Id;
931 switch (_cfgCommon.SortColumn)
933 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
937 mode = ComparerMode.Id; //Idソートに読み替え
940 mode = ComparerMode.Nickname;
943 mode = ComparerMode.Data;
946 mode = ComparerMode.Id;
949 mode = ComparerMode.Name;
952 mode = ComparerMode.Source;
955 _statuses.SortMode = mode;
956 ////////////////////////////////////////////////////////////////////////////////
958 ApplyListViewIconSize(this._cfgCommon.IconSize);
960 //<<<<<<<<タブ関連>>>>>>>
964 //デフォルトタブの存在チェック、ない場合には追加
965 if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
968 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
970 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
974 tab.TabType = MyCommon.TabUsageType.Home;
977 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
980 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
982 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
986 tab.TabType = MyCommon.TabUsageType.Mentions;
989 if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
992 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
994 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
998 tab.TabType = MyCommon.TabUsageType.DirectMessage;
1001 if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1004 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1006 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1010 tab.TabType = MyCommon.TabUsageType.Favorites;
1013 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mute) == null)
1016 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.MUTE, out tab))
1018 _statuses.AddTab(MyCommon.DEFAULTTAB.MUTE, MyCommon.TabUsageType.Mute, null);
1022 tab.TabType = MyCommon.TabUsageType.Mute;
1026 foreach (var tab in _statuses.Tabs.Values)
1029 if (tab.TabType == MyCommon.TabUsageType.Mute)
1032 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1034 tab.TabType = MyCommon.TabUsageType.UserDefined;
1036 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo))
1037 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1040 _curTab = ListTab.SelectedTab;
1042 _curList = (DetailsListView)_curTab.Tag;
1044 if (this._cfgCommon.TabIconDisp)
1046 ListTab.DrawMode = TabDrawMode.Normal;
1050 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1051 ListTab.DrawItem += ListTab_DrawItem;
1052 ListTab.ImageList = null;
1055 if (this._cfgCommon.HotkeyEnabled)
1058 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1059 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1060 modKey |= HookGlobalHotkey.ModKeys.Alt;
1061 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1062 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1063 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1064 modKey |= HookGlobalHotkey.ModKeys.Shift;
1065 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1066 modKey |= HookGlobalHotkey.ModKeys.Win;
1068 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1071 if (this._cfgCommon.IsUseNotifyGrowl)
1074 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1076 SetMainWindowTitle();
1077 SetNotifyIconText();
1079 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1081 this.Visible = true;
1085 TimerTimeline.AutoReset = true;
1086 TimerTimeline.SynchronizingObject = this;
1088 TimerTimeline.Interval = 1000;
1089 TimerTimeline.Enabled = true;
1091 TimerRefreshIcon.Interval = 200;
1092 TimerRefreshIcon.Enabled = true;
1094 _ignoreConfigSave = false;
1095 this.TweenMain_Resize(null, null);
1096 if (saveRequired) SaveConfigsAll(false);
1099 tw.VerifyCredentials();
1101 foreach (var ua in this._cfgCommon.UserAccounts)
1103 if (ua.UserId == 0 && ua.Username.ToLower() == tw.Username.ToLower())
1105 ua.UserId = tw.UserId;
1112 // 初回起動時だけ右下のメニューを目立たせる
1113 HashStripSplitButton.ShowDropDown();
1117 private void InitDetailHtmlFormat()
1119 if (this._cfgCommon.IsMonospace)
1121 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1122 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1126 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1127 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1130 detailHtmlFormatHeader = detailHtmlFormatHeader
1131 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1132 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1133 .Replace("%FONT_COLOR%", _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString())
1134 .Replace("%LINK_COLOR%", _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString())
1135 .Replace("%BG_COLOR%", _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString());
1138 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1143 txt = ListTab.TabPages[e.Index].Text;
1150 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1151 if (e.State == DrawItemState.Selected)
1153 e.DrawFocusRectangle();
1158 if (_statuses.Tabs[txt].UnreadCount > 0)
1161 fore = System.Drawing.SystemBrushes.ControlText;
1165 fore = System.Drawing.SystemBrushes.ControlText;
1167 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1170 private void LoadConfig()
1172 _cfgCommon = SettingCommon.Load();
1173 SettingCommon.Instance = this._cfgCommon;
1174 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1176 _cfgCommon.UserAccounts = new List<UserAccount>();
1177 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1179 UserAccount account = new UserAccount();
1180 account.Username = _cfgCommon.UserName;
1181 account.UserId = _cfgCommon.UserId;
1182 account.Token = _cfgCommon.Token;
1183 account.TokenSecret = _cfgCommon.TokenSecret;
1185 _cfgCommon.UserAccounts.Add(account);
1189 _cfgLocal = SettingLocal.Load();
1191 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1192 if (_cfgLocal.ScaleDimension.IsEmpty)
1193 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1195 List<TabClass> tabs = SettingTabs.Load().Tabs;
1196 foreach (TabClass tb in tabs)
1200 tb.FilterModified = false;
1201 _statuses.Tabs.Add(tb.TabName, tb);
1205 tb.TabName = _statuses.GetUniqueTabName();
1206 _statuses.Tabs.Add(tb.TabName, tb);
1209 if (_statuses.Tabs.Count == 0)
1211 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1212 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1213 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1214 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1218 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1220 if (!TimerTimeline.Enabled) return;
1224 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1226 private static int homeCounter = 0;
1227 private static int mentionCounter = 0;
1228 private static int dmCounter = 0;
1229 private static int pubSearchCounter = 0;
1230 private static int userTimelineCounter = 0;
1231 private static int listsCounter = 0;
1232 private static int usCounter = 0;
1233 private static int ResumeWait = 0;
1234 private static int refreshFollowers = 0;
1236 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1238 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1239 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1240 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1241 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1242 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1243 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1244 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1245 Interlocked.Increment(ref refreshFollowers);
1247 var refreshTasks = new List<Task>();
1250 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1252 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1253 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1254 refreshTasks.Add(this.GetHomeTimelineAsync());
1255 ResetTimers.Timeline = false;
1257 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1259 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1260 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1261 refreshTasks.Add(this.GetReplyAsync());
1262 ResetTimers.Reply = false;
1264 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1266 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1267 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1268 refreshTasks.Add(this.GetDirectMessagesAsync());
1269 ResetTimers.DirectMessage = false;
1271 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1273 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1274 if (!ResetTimers.PublicSearch)
1275 refreshTasks.Add(this.GetPublicSearchAllAsync());
1276 ResetTimers.PublicSearch = false;
1278 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1280 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1281 if (!ResetTimers.UserTimeline)
1282 refreshTasks.Add(this.GetUserTimelineAllAsync());
1283 ResetTimers.UserTimeline = false;
1285 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1287 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1288 if (!ResetTimers.Lists)
1289 refreshTasks.Add(this.GetListTimelineAllAsync());
1290 ResetTimers.Lists = false;
1292 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1294 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1295 if (this._isActiveUserstream)
1297 refreshTasks.Add(this.RefreshTasktrayIcon(true));
1298 this.RefreshTimeline(true);
1300 ResetTimers.UserStream = false;
1302 if (refreshFollowers > 6 * 3600)
1304 Interlocked.Exchange(ref refreshFollowers, 0);
1305 refreshTasks.AddRange(new[]
1307 this.doGetFollowersMenu(),
1308 this.RefreshNoRetweetIdsAsync(),
1309 this.RefreshTwitterConfigurationAsync(),
1314 Interlocked.Increment(ref ResumeWait);
1315 if (ResumeWait > 30)
1318 Interlocked.Exchange(ref ResumeWait, 0);
1319 refreshTasks.AddRange(new[]
1321 this.GetHomeTimelineAsync(),
1322 this.GetReplyAsync(),
1323 this.GetDirectMessagesAsync(),
1324 this.GetPublicSearchAllAsync(),
1325 this.GetUserTimelineAllAsync(),
1326 this.GetListTimelineAllAsync(),
1327 this.doGetFollowersMenu(),
1328 this.RefreshTwitterConfigurationAsync(),
1333 await Task.WhenAll(refreshTasks);
1336 private void RefreshTimeline(bool isUserStream)
1339 int smode = -1; //-1:制御しない,-2:最新へ,その他:topitem使用
1340 long topId = GetScrollPos(ref smode);
1341 int befCnt = _curList.VirtualListSize;
1344 var selId = new Dictionary<string, long[]>();
1345 var focusedId = new Dictionary<string, Tuple<long, long>>();
1346 SaveSelectedStatus(selId, focusedId);
1349 int dmCount = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount;
1352 PostClass[] notifyPosts = null;
1353 string soundFile = "";
1355 bool isMention = false;
1356 bool isDelete = false;
1357 addCount = _statuses.SubmitUpdate(ref soundFile, ref notifyPosts, ref isMention, ref isDelete, isUserStream);
1359 if (MyCommon._endingFlag) return;
1364 foreach (TabPage tab in ListTab.TabPages)
1366 DetailsListView lst = (DetailsListView)tab.Tag;
1367 TabClass tabInfo = _statuses.Tabs[tab.Text];
1368 using (ControlTransaction.Update(lst))
1370 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1372 if (lst.Equals(_curList))
1374 this.PurgeListViewItemCache();
1378 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1385 // status_id から ListView 上のインデックスに変換
1386 var selectedIndices = selId[tab.Text] != null
1387 ? tabInfo.IndexOf(selId[tab.Text]).Where(x => x != -1).ToArray()
1389 var focusedIndex = tabInfo.IndexOf(focusedId[tab.Text].Item1);
1390 var selectionMarkIndex = tabInfo.IndexOf(focusedId[tab.Text].Item2);
1392 this.SelectListItem(lst, selectedIndices, focusedIndex, selectionMarkIndex);
1395 if (tabInfo.UnreadCount > 0)
1396 if (this._cfgCommon.TabIconDisp)
1397 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1399 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1403 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1412 if (befCnt != _curList.VirtualListSize)
1418 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(0);
1422 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(_curList.VirtualListSize - 1);
1429 if (_curList.VirtualListSize > 0 && _statuses.Tabs[_curTab.Text].IndexOf(topId) > -1)
1431 _curList.EnsureVisible(_curList.VirtualListSize - 1);
1432 _curList.EnsureVisible(_statuses.Tabs[_curTab.Text].IndexOf(topId));
1438 catch (Exception ex)
1440 ex.Data["Msg"] = "Ref2";
1446 NotifyNewPosts(notifyPosts,
1449 isMention || dmCount != _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount);
1451 SetMainWindowTitle();
1452 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
1454 HashSupl.AddRangeItem(tw.GetHashList());
1458 private long GetScrollPos(ref int smode)
1461 if (_curList != null && _curTab != null && _curList.VirtualListSize > 0)
1463 if (_statuses.SortMode == ComparerMode.Id)
1465 if (_statuses.SortOrder == SortOrder.Ascending)
1468 if (ListLockMenuItem.Checked)
1473 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1478 //最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1480 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1); //一番下
1481 if (_item == null) _item = _curList.Items[_curList.VirtualListSize - 1];
1482 if (_item.Index == _curList.VirtualListSize - 1)
1489 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1497 if (ListLockMenuItem.Checked)
1500 if (_curList.TopItem != null) topId = _statuses.Tabs[_curTab.Text].GetId(_curList.TopItem.Index);
1505 //最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1508 _item = _curList.GetItemAt(0, 10); //一番上
1509 if (_item == null) _item = _curList.Items[0];
1510 if (_item.Index == 0)
1516 if (_curList.TopItem != null) topId = _statuses.Tabs[_curTab.Text].GetId(_curList.TopItem.Index);
1525 if (_curList.TopItem != null) topId = _statuses.Tabs[_curTab.Text].GetId(_curList.TopItem.Index);
1536 private void SaveSelectedStatus(Dictionary<string, long[]> selId, Dictionary<string, Tuple<long, long>> focusedIdDict)
1538 if (MyCommon._endingFlag) return;
1539 foreach (TabPage tab in ListTab.TabPages)
1541 var lst = (DetailsListView)tab.Tag;
1542 var tabInfo = _statuses.Tabs[tab.Text];
1543 if (lst.SelectedIndices.Count > 0 && lst.SelectedIndices.Count < 61)
1545 selId.Add(tab.Text, tabInfo.GetId(lst.SelectedIndices));
1549 selId.Add(tab.Text, null);
1552 var focusedItem = lst.FocusedItem;
1553 var focusedId = focusedItem != null ? tabInfo.GetId(focusedItem.Index) : -2;
1555 var selectionMarkIndex = lst.SelectionMark;
1556 var selectionMarkId = selectionMarkIndex != -1 ? tabInfo.GetId(selectionMarkIndex) : -2;
1558 focusedIdDict[tab.Text] = Tuple.Create(focusedId, selectionMarkId);
1563 private bool BalloonRequired()
1565 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1566 ev.Eventtype = MyCommon.EVENTTYPE.None;
1568 return BalloonRequired(ev);
1571 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1573 return this._cfgCommon.EventNotifyEnabled && (type & this._cfgCommon.EventNotifyFlag) != 0 || type == MyCommon.EVENTTYPE.None;
1576 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1578 return (ev.Eventtype & this._cfgCommon.IsMyEventNotifyFlag) != 0 ? true : !ev.IsMe;
1581 private bool BalloonRequired(Twitter.FormattedEvent ev)
1584 IsEventNotifyAsEventType(ev.Eventtype) && IsMyEventNotityAsEventType(ev) &&
1585 (NewPostPopMenuItem.Checked || (this._cfgCommon.ForceEventNotify && ev.Eventtype != MyCommon.EVENTTYPE.None)) &&
1589 this._cfgCommon.LimitBalloon &&
1591 this.WindowState == FormWindowState.Minimized ||
1593 Form.ActiveForm == null
1596 !this._cfgCommon.LimitBalloon
1599 !NativeMethods.IsScreenSaverRunning())
1609 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1611 if (notifyPosts != null &&
1612 notifyPosts.Length > 0 &&
1613 this._cfgCommon.ReadOwnPost &&
1614 notifyPosts.All((post) => { return post.UserId == tw.UserId || post.ScreenName == tw.Username; }))
1620 if (BalloonRequired())
1622 if (notifyPosts != null && notifyPosts.Length > 0)
1624 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1625 if (this._cfgCommon.IsUseNotifyGrowl)
1627 StringBuilder sb = new StringBuilder();
1631 foreach (PostClass post in notifyPosts)
1633 if (!(notifyPosts.Length > 3))
1639 if (post.IsReply && !post.IsExcludeReply) reply = true;
1640 if (post.IsDm) dm = true;
1641 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1642 switch (this._cfgCommon.NameBalloon)
1644 case MyCommon.NameBalloonEnum.UserID:
1645 sb.Append(post.ScreenName).Append(" : ");
1647 case MyCommon.NameBalloonEnum.NickName:
1648 sb.Append(post.Nickname).Append(" : ");
1651 sb.Append(post.TextFromApi);
1652 if (notifyPosts.Length > 3)
1654 if (notifyPosts.Last() != post) continue;
1657 StringBuilder title = new StringBuilder();
1658 GrowlHelper.NotifyType nt;
1659 if (this._cfgCommon.DispUsername)
1661 title.Append(tw.Username);
1662 title.Append(" - ");
1670 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1671 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1672 title.Append(Application.ProductName);
1673 title.Append(" [DM] ");
1674 title.Append(Properties.Resources.RefreshDirectMessageText1);
1676 title.Append(addCount);
1677 title.Append(Properties.Resources.RefreshDirectMessageText2);
1678 nt = GrowlHelper.NotifyType.DirectMessage;
1682 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1683 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1684 title.Append(Application.ProductName);
1685 title.Append(" [Reply!] ");
1686 title.Append(Properties.Resources.RefreshTimelineText1);
1688 title.Append(addCount);
1689 title.Append(Properties.Resources.RefreshTimelineText2);
1690 nt = GrowlHelper.NotifyType.Reply;
1694 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1695 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1696 title.Append(Application.ProductName);
1698 title.Append(Properties.Resources.RefreshTimelineText1);
1700 title.Append(addCount);
1701 title.Append(Properties.Resources.RefreshTimelineText2);
1702 nt = GrowlHelper.NotifyType.Notify;
1704 string bText = sb.ToString();
1705 if (string.IsNullOrEmpty(bText)) return;
1707 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1708 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1713 StringBuilder sb = new StringBuilder();
1716 foreach (PostClass post in notifyPosts)
1718 if (post.IsReply && !post.IsExcludeReply) reply = true;
1719 if (post.IsDm) dm = true;
1720 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1721 switch (this._cfgCommon.NameBalloon)
1723 case MyCommon.NameBalloonEnum.UserID:
1724 sb.Append(post.ScreenName).Append(" : ");
1726 case MyCommon.NameBalloonEnum.NickName:
1727 sb.Append(post.Nickname).Append(" : ");
1730 sb.Append(post.TextFromApi);
1733 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1734 StringBuilder title = new StringBuilder();
1736 if (this._cfgCommon.DispUsername)
1738 title.Append(tw.Username);
1739 title.Append(" - ");
1747 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1748 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1749 ntIcon = ToolTipIcon.Warning;
1750 title.Append(Application.ProductName);
1751 title.Append(" [DM] ");
1752 title.Append(Properties.Resources.RefreshDirectMessageText1);
1754 title.Append(addCount);
1755 title.Append(Properties.Resources.RefreshDirectMessageText2);
1759 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1760 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1761 ntIcon = ToolTipIcon.Warning;
1762 title.Append(Application.ProductName);
1763 title.Append(" [Reply!] ");
1764 title.Append(Properties.Resources.RefreshTimelineText1);
1766 title.Append(addCount);
1767 title.Append(Properties.Resources.RefreshTimelineText2);
1771 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1772 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1773 ntIcon = ToolTipIcon.Info;
1774 title.Append(Application.ProductName);
1776 title.Append(Properties.Resources.RefreshTimelineText1);
1778 title.Append(addCount);
1779 title.Append(Properties.Resources.RefreshTimelineText2);
1781 string bText = sb.ToString();
1782 if (string.IsNullOrEmpty(bText)) return;
1783 //NotifyIcon1.BalloonTipText = sb.ToString();
1784 //NotifyIcon1.ShowBalloonTip(500);
1785 NotifyIcon1.BalloonTipTitle = title.ToString();
1786 NotifyIcon1.BalloonTipText = bText;
1787 NotifyIcon1.BalloonTipIcon = ntIcon;
1788 NotifyIcon1.ShowBalloonTip(500);
1794 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1798 string dir = Application.StartupPath;
1799 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1801 dir = Path.Combine(dir, "Sounds");
1803 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1813 //mentions新着時に画面ブリンク
1814 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1816 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1820 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1822 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1824 _curItemIndex = _curList.SelectedIndices[0];
1825 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1829 _curPost = GetCurTabPost(_curItemIndex);
1831 catch (ArgumentException)
1836 this.PushSelectPostChain();
1838 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1840 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1846 private void ChangeCacheStyleRead(bool Read, int Index)
1848 var tabInfo = _statuses.Tabs[_curTab.Text];
1849 //Read:true=既読 false=未読
1850 //未読管理していなかったら既読として扱う
1851 if (!tabInfo.UnreadManage ||
1852 !this._cfgCommon.UnreadManage) Read = true;
1855 ListViewItem itm = null;
1856 PostClass post = null;
1858 this.TryGetListViewItemCache(Index, out itm, out post);
1860 // キャッシュに含まれていないアイテムは対象外
1864 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1867 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1874 Item.SubItems[5].Text = "";
1879 Item.SubItems[5].Text = "★";
1885 else if (Post.RetweetedId != null)
1887 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1889 else if (Read || !this._cfgCommon.UseUnreadStyle)
1894 if (DList == null || Item.Index == -1)
1896 Item.ForeColor = cl;
1897 if (this._cfgCommon.UseUnreadStyle)
1903 if (this._cfgCommon.UseUnreadStyle)
1904 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1906 DList.ChangeItemForeColor(Item.Index, cl);
1907 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
1911 private void ColorizeList()
1913 //Index:更新対象のListviewItem.Index。Colorを返す。
1914 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
1917 _post = _anchorPost;
1921 if (_post == null) return;
1923 var itemColors = new Color[] { };
1926 this.itemCacheLock.EnterReadLock();
1929 if (this._itemCache == null) return;
1932 from i in Enumerable.Range(0, this._itemCache.Length)
1933 select this.JudgeColor(_post, this._postCache[i]);
1935 itemColors = query.ToArray();
1936 itemIndex = _itemCacheIndex;
1938 finally { this.itemCacheLock.ExitReadLock(); }
1940 if (itemIndex < 0) return;
1942 foreach (var backColor in itemColors)
1944 // この処理中に MyList_CacheVirtualItems が呼ばれることがあるため、
1945 // 同一スレッド内での二重ロックを避けるためにロックの外で実行する必要がある
1946 _curList.ChangeItemBackColor(itemIndex++, backColor);
1950 private void ColorizeList(ListViewItem Item, int Index)
1952 //Index:更新対象のListviewItem.Index。Colorを返す。
1953 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
1956 _post = _anchorPost;
1960 PostClass tPost = GetCurTabPost(Index);
1962 if (_post == null) return;
1964 if (Item.Index == -1)
1965 Item.BackColor = JudgeColor(_post, tPost);
1967 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
1970 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
1973 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
1976 else if (TargetPost.IsMe)
1979 else if (TargetPost.IsReply)
1982 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLower()))
1984 cl = _clAtFromTarget;
1985 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLower()))
1988 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
1993 cl = _clListBackcolor;
1998 private async void PostButton_Click(object sender, EventArgs e)
2000 if (StatusText.Text.Trim().Length == 0)
2002 if (!ImageSelector.Enabled)
2009 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2011 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2013 MessageBoxButtons.YesNoCancel,
2014 MessageBoxIcon.Question);
2017 case DialogResult.Yes:
2018 StatusText.Text = "";
2019 await this.doReTweetOfficial(false);
2021 case DialogResult.Cancel:
2026 var inReplyToStatusId = this.inReplyTo?.Item1;
2027 var inReplyToScreenName = this.inReplyTo?.Item2;
2028 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2030 if (this._cfgCommon.Nicoms)
2032 StatusText.SelectionStart = StatusText.Text.Length;
2033 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2035 //if (SettingDialog.UrlConvertAuto)
2037 // StatusText.SelectionStart = StatusText.Text.Length;
2038 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2040 //else if (SettingDialog.Nicoms)
2042 // StatusText.SelectionStart = StatusText.Text.Length;
2043 // UrlConvert(UrlConverter.Nicoms);
2045 StatusText.SelectionStart = StatusText.Text.Length;
2046 CheckReplyTo(StatusText.Text);
2049 int adjustCount = 0;
2050 string tmpStatus = StatusText.Text.Trim();
2051 if (ToolStripMenuItemApiCommandEvasion.Checked)
2054 if (Regex.IsMatch(tmpStatus,
2055 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2056 RegexOptions.IgnoreCase)
2057 && tmpStatus.EndsWith(" .") == false) adjustCount += 2;
2060 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2063 adjustCount += Regex.Matches(tmpStatus, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+").Count;
2066 bool isCutOff = false;
2067 bool isRemoveFooter = MyCommon.IsKeyDown(Keys.Shift);
2068 if (StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
2070 //複数行でEnter投稿の場合、Ctrlも押されていたらフッタ付加しない
2071 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2073 if (this._cfgCommon.PostShiftEnter)
2075 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2077 if (!isRemoveFooter && (StatusText.Text.Contains("RT @") || StatusText.Text.Contains("QT @")))
2079 isRemoveFooter = true;
2081 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2083 if (MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
2086 //if (!SettingDialog.UrlConvertAuto) UrlConvertAutoToolStripMenuItem_Click(null, null);
2087 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2089 isRemoveFooter = true;
2100 if (StatusText.Text.StartsWith("D ") || StatusText.Text.StartsWith("d "))
2108 if (HashMgr.IsNotAddToAtReply)
2110 if (!string.IsNullOrEmpty(HashMgr.UseHash) && this.inReplyTo == null)
2113 header = HashMgr.UseHash + " ";
2115 footer = " " + HashMgr.UseHash;
2120 if (!string.IsNullOrEmpty(HashMgr.UseHash))
2123 header = HashMgr.UseHash + " ";
2125 footer = " " + HashMgr.UseHash;
2128 if (!isRemoveFooter)
2130 if (this._cfgLocal.UseRecommendStatus)
2133 footer += this.recommendedStatusFooter;
2135 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
2137 // テキストボックスに入力されている文字列を使用する
2138 footer += " " + this._cfgLocal.StatusText.Trim();
2143 var status = new PostingStatus();
2144 status.status = header + StatusText.Text + footer;
2146 if (ToolStripMenuItemApiCommandEvasion.Checked)
2149 if (Regex.IsMatch(status.status,
2150 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2151 RegexOptions.IgnoreCase)
2152 && status.status.EndsWith(" .") == false) status.status += " .";
2155 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2158 Match mc2 = Regex.Match(status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+");
2159 if (mc2.Success) status.status = Regex.Replace(status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
2162 if (IdeographicSpaceToSpaceToolStripMenuItem.Checked)
2164 // 文中の全角スペースを半角スペース1個にする
2165 status.status = status.status.Replace(" ", " ");
2168 if (isCutOff && status.status.Length > 140)
2170 status.status = status.status.Substring(0, 140);
2171 string AtId = @"(@|@)[a-z0-9_/]+$";
2172 string HashTag = @"(^|[^0-9A-Z&\/\?]+)(#|#)([0-9A-Z_]*[A-Z_]+)$";
2173 string Url = @"https?:\/\/[a-z0-9!\*'\(\);:&=\+\$\/%#\[\]\-_\.,~?]+$"; //簡易判定
2174 string pattern = string.Format("({0})|({1})|({2})", AtId, HashTag, Url);
2175 Match mc = Regex.Match(status.status, pattern, RegexOptions.IgnoreCase);
2178 //さらに@ID、ハッシュタグ、URLと推測される文字列をカットする
2179 status.status = status.status.Substring(0, 140 - mc.Value.Length);
2181 if (MessageBox.Show(status.status, "Post or Cancel?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return;
2184 status.inReplyToId = this.inReplyTo?.Item1;
2185 status.inReplyToName = this.inReplyTo?.Item2;
2186 if (ImageSelector.Visible)
2189 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2193 this.inReplyTo = null;
2194 StatusText.Text = "";
2195 _history.Add(new PostingStatus());
2196 _hisIdx = _history.Count - 1;
2197 if (!ToolStripFocusLockMenuItem.Checked)
2198 ((Control)ListTab.SelectedTab.Tag).Focus();
2199 urlUndoBuffer = null;
2200 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2203 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2205 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2206 await this.OpenUriInBrowserAsync(tmp);
2209 await this.PostMessageAsync(status);
2212 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2214 MyCommon._endingFlag = true;
2218 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2220 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2222 //_endingFlag=false:フォームの×ボタン
2224 this.Visible = false;
2228 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2229 _ignoreConfigSave = true;
2230 MyCommon._endingFlag = true;
2231 TimerTimeline.Enabled = false;
2232 TimerRefreshIcon.Enabled = false;
2236 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2238 this.Visible = true;
2239 if (this.WindowState == FormWindowState.Minimized)
2241 this.WindowState = FormWindowState.Normal;
2244 this.BringToFront();
2247 private static int errorCount = 0;
2249 private static bool CheckAccountValid()
2251 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2257 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2266 private Task GetHomeTimelineAsync()
2268 return this.GetHomeTimelineAsync(loadMore: false);
2271 private async Task GetHomeTimelineAsync(bool loadMore)
2273 await this.workerSemaphore.WaitAsync();
2277 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2279 await this.GetHomeTimelineAsyncInternal(progress, this.workerCts.Token, loadMore);
2281 catch (WebApiException ex)
2283 this._myStatusError = true;
2284 this.StatusLabel.Text = ex.Message;
2288 this.workerSemaphore.Release();
2292 private async Task GetHomeTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2294 if (ct.IsCancellationRequested)
2297 if (!CheckAccountValid())
2298 throw new WebApiException("Auth error. Check your account");
2301 if (!this._cfgCommon.UnreadManage)
2304 read = this._initial && this._cfgCommon.Read;
2306 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5 +
2307 (loadMore ? "-1" : "1") +
2308 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6);
2310 await Task.Run(() =>
2312 this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Timeline, loadMore, this._initial);
2315 if (this._cfgCommon.ReadOldPosts)
2316 this._statuses.SetReadHomeTab();
2318 var addCount = this._statuses.DistributePosts();
2322 lock (this._syncObject)
2324 var tm = DateTime.Now;
2325 if (this._tlTimestamps.ContainsKey(tm))
2326 this._tlTimestamps[tm] += addCount;
2328 this._tlTimestamps[tm] = addCount;
2330 var removeKeys = new List<DateTime>();
2331 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2334 foreach (var pair in this._tlTimestamps)
2336 if (pair.Key < oneHour)
2337 removeKeys.Add(pair.Key);
2339 this._tlCount += pair.Value;
2342 foreach (var key in removeKeys)
2343 this._tlTimestamps.Remove(key);
2348 if (ct.IsCancellationRequested)
2351 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1);
2353 this.RefreshTimeline(false);
2356 private Task GetReplyAsync()
2358 return this.GetReplyAsync(loadMore: false);
2361 private async Task GetReplyAsync(bool loadMore)
2363 await this.workerSemaphore.WaitAsync();
2367 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2369 await this.GetReplyAsyncInternal(progress, this.workerCts.Token, loadMore);
2371 catch (WebApiException ex)
2373 this._myStatusError = true;
2374 this.StatusLabel.Text = ex.Message;
2378 this.workerSemaphore.Release();
2382 private async Task GetReplyAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2384 if (ct.IsCancellationRequested)
2387 if (!CheckAccountValid())
2388 throw new WebApiException("Auth error. Check your account");
2391 if (!this._cfgCommon.UnreadManage)
2394 read = this._initial && this._cfgCommon.Read;
2396 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4 +
2397 (loadMore ? "-1" : "1") +
2398 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6);
2400 await Task.Run(() =>
2402 this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Reply, loadMore, this._initial);
2404 this._statuses.DistributePosts();
2407 if (ct.IsCancellationRequested)
2410 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9);
2412 this.RefreshTimeline(false);
2415 private Task GetDirectMessagesAsync()
2417 return this.GetDirectMessagesAsync(loadMore: false);
2420 private async Task GetDirectMessagesAsync(bool loadMore)
2422 await this.workerSemaphore.WaitAsync();
2426 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2428 await this.GetDirectMessagesAsyncInternal(progress, this.workerCts.Token, loadMore);
2430 catch (WebApiException ex)
2432 this._myStatusError = true;
2433 this.StatusLabel.Text = ex.Message;
2437 this.workerSemaphore.Release();
2441 private async Task GetDirectMessagesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2443 if (ct.IsCancellationRequested)
2446 if (!CheckAccountValid())
2447 throw new WebApiException("Auth error. Check your account");
2450 if (!this._cfgCommon.UnreadManage)
2453 read = this._initial && this._cfgCommon.Read;
2455 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8 +
2456 (loadMore ? "-1" : "1") +
2457 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6);
2459 await Task.Run(() =>
2461 this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, loadMore);
2462 this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, loadMore);
2464 this._statuses.DistributePosts();
2467 if (ct.IsCancellationRequested)
2470 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11);
2472 this.RefreshTimeline(false);
2475 private Task GetFavoritesAsync()
2477 return this.GetFavoritesAsync(loadMore: false);
2480 private async Task GetFavoritesAsync(bool loadMore)
2482 await this.workerSemaphore.WaitAsync();
2486 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2488 await this.GetFavoritesAsyncInternal(progress, this.workerCts.Token, loadMore);
2490 catch (WebApiException ex)
2492 this._myStatusError = true;
2493 this.StatusLabel.Text = ex.Message;
2497 this.workerSemaphore.Release();
2501 private async Task GetFavoritesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2503 if (ct.IsCancellationRequested)
2506 if (!CheckAccountValid())
2507 throw new WebApiException("Auth error. Check your account");
2510 if (!this._cfgCommon.UnreadManage)
2513 read = this._initial && this._cfgCommon.Read;
2515 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19);
2517 await Task.Run(() =>
2519 this.tw.GetFavoritesApi(read, loadMore);
2521 this._statuses.DistributePosts();
2524 if (ct.IsCancellationRequested)
2527 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20);
2529 this.RefreshTimeline(false);
2532 private Task GetPublicSearchAllAsync()
2534 return this.GetPublicSearchAsync(null, loadMore: false);
2537 private Task GetPublicSearchAsync(TabClass tab)
2539 return this.GetPublicSearchAsync(tab, loadMore: false);
2542 private async Task GetPublicSearchAsync(TabClass tab, bool loadMore)
2544 await this.workerSemaphore.WaitAsync();
2548 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2550 var tabs = tab != null
2551 ? new[] { tab }.AsEnumerable()
2552 : this._statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch);
2554 await this.GetPublicSearchAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2556 catch (WebApiException ex)
2558 this._myStatusError = true;
2559 this.StatusLabel.Text = ex.Message;
2563 this.workerSemaphore.Release();
2567 private async Task GetPublicSearchAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2569 if (ct.IsCancellationRequested)
2572 if (!CheckAccountValid())
2573 throw new WebApiException("Auth error. Check your account");
2576 if (!this._cfgCommon.UnreadManage)
2579 read = this._initial && this._cfgCommon.Read;
2581 p.Report("Search refreshing...");
2583 await Task.Run(() =>
2585 foreach (var tab in tabs)
2587 if (string.IsNullOrEmpty(tab.SearchWords))
2590 this.tw.GetSearch(read, tab, false);
2593 this.tw.GetSearch(read, tab, true);
2596 this._statuses.DistributePosts();
2599 if (ct.IsCancellationRequested)
2602 p.Report("Search refreshed");
2604 this.RefreshTimeline(false);
2607 private Task GetUserTimelineAllAsync()
2609 return this.GetUserTimelineAsync(null, loadMore: false);
2612 private Task GetUserTimelineAsync(TabClass tab)
2614 return this.GetUserTimelineAsync(tab, loadMore: false);
2617 private async Task GetUserTimelineAsync(TabClass tab, bool loadMore)
2619 await this.workerSemaphore.WaitAsync();
2623 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2625 var tabs = tab != null
2626 ? new[] { tab }.AsEnumerable()
2627 : this._statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline);
2629 await this.GetUserTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2631 catch (WebApiException ex)
2633 this._myStatusError = true;
2634 this.StatusLabel.Text = ex.Message;
2638 this.workerSemaphore.Release();
2642 private async Task GetUserTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2644 if (ct.IsCancellationRequested)
2647 if (!CheckAccountValid())
2648 throw new WebApiException("Auth error. Check your account");
2651 if (!this._cfgCommon.UnreadManage)
2654 read = this._initial && this._cfgCommon.Read;
2656 p.Report("UserTimeline refreshing...");
2658 await Task.Run(() =>
2660 foreach (var tab in tabs)
2662 if (string.IsNullOrEmpty(tab.User))
2665 this.tw.GetUserTimelineApi(read, tab.User, tab, loadMore);
2668 this._statuses.DistributePosts();
2671 if (ct.IsCancellationRequested)
2674 p.Report("UserTimeline refreshed");
2676 this.RefreshTimeline(false);
2679 private Task GetListTimelineAllAsync()
2681 return this.GetListTimelineAsync(null, loadMore: false);
2684 private Task GetListTimelineAsync(TabClass tab)
2686 return this.GetListTimelineAsync(tab, loadMore: false);
2689 private async Task GetListTimelineAsync(TabClass tab, bool loadMore)
2691 await this.workerSemaphore.WaitAsync();
2695 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2697 var tabs = tab != null
2698 ? new[] { tab }.AsEnumerable()
2699 : this._statuses.GetTabsByType(MyCommon.TabUsageType.Lists);
2701 await this.GetListTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2703 catch (WebApiException ex)
2705 this._myStatusError = true;
2706 this.StatusLabel.Text = ex.Message;
2710 this.workerSemaphore.Release();
2714 private async Task GetListTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2716 if (ct.IsCancellationRequested)
2719 if (!CheckAccountValid())
2720 throw new WebApiException("Auth error. Check your account");
2723 if (!this._cfgCommon.UnreadManage)
2726 read = this._initial && this._cfgCommon.Read;
2728 p.Report("List refreshing...");
2730 await Task.Run(() =>
2732 foreach (var tab in tabs)
2734 if (tab.ListInfo == null || tab.ListInfo.Id == 0)
2737 this.tw.GetListStatus(read, tab, loadMore, this._initial);
2740 this._statuses.DistributePosts();
2743 if (ct.IsCancellationRequested)
2746 p.Report("List refreshed");
2748 this.RefreshTimeline(false);
2751 private async Task GetRelatedTweetsAsync(TabClass tab)
2753 await this.workerSemaphore.WaitAsync();
2757 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2759 await this.GetRelatedTweetsAsyncInternal(progress, this.workerCts.Token, tab);
2761 catch (WebApiException ex)
2763 this._myStatusError = true;
2764 this.StatusLabel.Text = ex.Message;
2768 this.workerSemaphore.Release();
2772 private async Task GetRelatedTweetsAsyncInternal(IProgress<string> p, CancellationToken ct, TabClass tab)
2774 if (ct.IsCancellationRequested)
2777 if (!CheckAccountValid())
2778 throw new WebApiException("Auth error. Check your account");
2781 if (!this._cfgCommon.UnreadManage)
2784 read = this._initial && this._cfgCommon.Read;
2786 p.Report("Related refreshing...");
2788 await Task.Run(() =>
2790 this.tw.GetRelatedResult(read, tab);
2792 this._statuses.DistributePosts();
2795 if (ct.IsCancellationRequested)
2798 p.Report("Related refreshed");
2800 this.RefreshTimeline(false);
2802 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
2803 .FirstOrDefault(x => x.Text == tab.TabName);
2805 if (tabPage != null)
2807 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
2809 var listView = (DetailsListView)tabPage.Tag;
2810 var index = tab.IndexOf(tab.RelationTargetPost.RetweetedId ?? tab.RelationTargetPost.StatusId);
2812 if (index != -1 && index < listView.Items.Count)
2814 listView.SelectedIndices.Add(index);
2815 listView.Items[index].Focused = true;
2820 private async Task FavAddAsync(IReadOnlyList<long> statusIds, TabClass tab)
2822 await this.workerSemaphore.WaitAsync();
2826 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2828 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2830 catch (WebApiException ex)
2832 this._myStatusError = true;
2833 this.StatusLabel.Text = ex.Message;
2837 this.workerSemaphore.Release();
2841 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2843 if (ct.IsCancellationRequested)
2846 if (!CheckAccountValid())
2847 throw new WebApiException("Auth error. Check your account");
2849 var successIds = new List<long>();
2851 await Task.Run(() =>
2855 var failedCount = 0;
2857 foreach (var statusId in statusIds)
2861 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15 +
2862 allCount + "/" + statusIds.Count +
2863 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText16 +
2866 var post = tab.Posts[statusId];
2873 this.tw.PostFavAdd(post.RetweetedId ?? post.StatusId);
2875 catch (WebApiException)
2881 successIds.Add(statusId);
2882 post.IsFav = true; // リスト再描画必要
2884 this._favTimestamps.Add(DateTime.Now);
2887 if (this._statuses.ContainsKey(statusId))
2889 var postTl = this._statuses[statusId];
2890 postTl.IsFav = true;
2892 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2893 favTab.Add(statusId, postTl.IsRead, false);
2896 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2897 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2899 if (tb.Contains(statusId))
2900 tb.Posts[statusId].IsFav = true;
2905 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2906 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2908 if (this._favTimestamps[i] < oneHour)
2909 this._favTimestamps.RemoveAt(i);
2912 this._statuses.DistributePosts();
2915 if (ct.IsCancellationRequested)
2918 this.RefreshTimeline(false);
2920 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2922 using (ControlTransaction.Update(this._curList))
2924 foreach (var statusId in successIds)
2926 var idx = tab.IndexOf(statusId);
2930 var post = tab.Posts[statusId];
2931 this.ChangeCacheStyleRead(post.IsRead, idx);
2935 if (successIds.Contains(this._curPost.StatusId))
2936 await this.DispSelectedPost(true); // 選択アイテム再表示
2940 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabClass tab)
2942 await this.workerSemaphore.WaitAsync();
2946 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2948 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2950 catch (WebApiException ex)
2952 this._myStatusError = true;
2953 this.StatusLabel.Text = ex.Message;
2957 this.workerSemaphore.Release();
2961 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2963 if (ct.IsCancellationRequested)
2966 if (!CheckAccountValid())
2967 throw new WebApiException("Auth error. Check your account");
2969 var successIds = new List<long>();
2971 await Task.Run(() =>
2975 var failedCount = 0;
2976 foreach (var statusId in statusIds)
2980 var post = tab.Posts[statusId];
2982 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17 +
2983 allCount + "/" + statusIds.Count +
2984 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText18 +
2992 this.tw.PostFavRemove(post.RetweetedId ?? post.StatusId);
2994 catch (WebApiException)
3000 successIds.Add(statusId);
3001 post.IsFav = false; // リスト再描画必要
3003 if (this._statuses.ContainsKey(statusId))
3005 this._statuses[statusId].IsFav = false;
3008 // 検索,リスト,UserTimeline,Relatedの各タブに反映
3009 foreach (var tb in this._statuses.GetTabsInnerStorageType())
3011 if (tb.Contains(statusId))
3012 tb.Posts[statusId].IsFav = false;
3017 if (ct.IsCancellationRequested)
3020 this.RemovePostFromFavTab(successIds.ToArray());
3022 this.RefreshTimeline(false);
3024 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
3026 if (tab.TabType == MyCommon.TabUsageType.Favorites)
3032 using (ControlTransaction.Update(this._curList))
3034 foreach (var statusId in successIds)
3036 var idx = tab.IndexOf(statusId);
3040 var post = tab.Posts[statusId];
3041 this.ChangeCacheStyleRead(post.IsRead, idx);
3045 if (successIds.Contains(this._curPost.StatusId))
3046 await this.DispSelectedPost(true); // 選択アイテム再表示
3051 private async Task PostMessageAsync(PostingStatus status)
3053 await this.workerSemaphore.WaitAsync();
3057 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3059 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
3061 catch (WebApiException ex)
3063 this._myStatusError = true;
3064 this.StatusLabel.Text = ex.Message;
3068 this.workerSemaphore.Release();
3072 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
3074 if (ct.IsCancellationRequested)
3077 if (!CheckAccountValid())
3078 throw new WebApiException("Auth error. Check your account");
3080 p.Report("Posting...");
3086 await Task.Run(async () =>
3088 if (status.mediaItems == null || status.mediaItems.Length == 0)
3090 this.tw.PostStatus(status.status, status.inReplyToId);
3094 var service = ImageSelector.GetService(status.imageService);
3095 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
3096 .ConfigureAwait(false);
3100 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3102 catch (WebApiException ex)
3104 // 処理は中断せずエラーの表示のみ行う
3105 errMsg = ex.Message;
3107 this._myStatusError = true;
3111 // 使い終わった MediaItem は破棄する
3112 if (status.mediaItems != null)
3114 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
3116 disposableItem.Dispose();
3121 if (ct.IsCancellationRequested)
3124 if (!string.IsNullOrEmpty(errMsg) &&
3125 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
3126 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
3128 var ret = MessageBox.Show(
3130 "{0} ---> [ " + errMsg + " ]" + Environment.NewLine +
3131 "\"" + status.status + "\"" + Environment.NewLine +
3133 Properties.Resources.StatusUpdateFailed1,
3134 Properties.Resources.StatusUpdateFailed2),
3135 "Failed to update status",
3136 MessageBoxButtons.RetryCancel,
3137 MessageBoxIcon.Question);
3139 if (ret == DialogResult.Retry)
3141 await this.PostMessageAsync(status);
3145 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3146 if (this.ToolStripFocusLockMenuItem.Checked)
3147 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
3152 this._postTimestamps.Add(DateTime.Now);
3154 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3155 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3157 if (this._postTimestamps[i] < oneHour)
3158 this._postTimestamps.RemoveAt(i);
3161 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
3163 this.HashMgr.ClearHashtag();
3164 this.HashStripSplitButton.Text = "#[-]";
3165 this.HashToggleMenuItem.Checked = false;
3166 this.HashToggleToolStripMenuItem.Checked = false;
3169 this.SetMainWindowTitle();
3171 if (this._cfgCommon.PostAndGet)
3173 if (this._isActiveUserstream)
3174 this.RefreshTimeline(true);
3176 await this.GetHomeTimelineAsync();
3180 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
3182 await this.workerSemaphore.WaitAsync();
3186 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3188 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
3190 catch (WebApiException ex)
3192 this._myStatusError = true;
3193 this.StatusLabel.Text = ex.Message;
3197 this.workerSemaphore.Release();
3201 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
3203 if (ct.IsCancellationRequested)
3206 if (!CheckAccountValid())
3207 throw new WebApiException("Auth error. Check your account");
3210 if (!this._cfgCommon.UnreadManage)
3213 read = this._initial && this._cfgCommon.Read;
3215 p.Report("Posting...");
3217 await Task.Run(() =>
3219 foreach (var statusId in statusIds)
3221 this.tw.PostRetweet(statusId, read);
3225 if (ct.IsCancellationRequested)
3228 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3230 this._postTimestamps.Add(DateTime.Now);
3232 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3233 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3235 if (this._postTimestamps[i] < oneHour)
3236 this._postTimestamps.RemoveAt(i);
3239 if (this._cfgCommon.PostAndGet && !this._isActiveUserstream)
3240 await this.GetHomeTimelineAsync();
3243 private async Task RefreshFollowerIdsAsync()
3245 await this.workerSemaphore.WaitAsync();
3248 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
3250 await Task.Run(() => tw.RefreshFollowerIds());
3252 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
3254 this.RefreshTimeline(false);
3255 this.PurgeListViewItemCache();
3256 this._curList?.Refresh();
3258 catch (WebApiException ex)
3260 this.StatusLabel.Text = ex.Message;
3264 this.workerSemaphore.Release();
3268 private async Task RefreshNoRetweetIdsAsync()
3270 await this.workerSemaphore.WaitAsync();
3273 await Task.Run(() => tw.RefreshNoRetweetIds());
3275 this.StatusLabel.Text = "NoRetweetIds refreshed";
3277 catch (WebApiException ex)
3279 this.StatusLabel.Text = ex.Message;
3283 this.workerSemaphore.Release();
3287 private async Task RefreshBlockIdsAsync()
3289 await this.workerSemaphore.WaitAsync();
3292 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
3294 await Task.Run(() => tw.RefreshBlockIds());
3296 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
3298 catch (WebApiException ex)
3300 this.StatusLabel.Text = ex.Message;
3304 this.workerSemaphore.Release();
3308 private async Task RefreshTwitterConfigurationAsync()
3310 await this.workerSemaphore.WaitAsync();
3313 await Task.Run(() => tw.RefreshConfiguration());
3315 if (this.tw.Configuration.PhotoSizeLimit != 0)
3317 foreach (var service in this.ImageSelector.GetServices())
3319 service.UpdateTwitterConfiguration(this.tw.Configuration);
3323 this.PurgeListViewItemCache();
3325 this._curList?.Refresh();
3327 catch (WebApiException ex)
3329 this.StatusLabel.Text = ex.Message;
3333 this.workerSemaphore.Release();
3337 private async Task RefreshMuteUserIdsAsync()
3339 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3343 await tw.RefreshMuteUserIdsAsync();
3345 catch (WebApiException ex)
3347 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3351 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3354 private void RemovePostFromFavTab(Int64[] ids)
3356 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
3357 string favTabName = favTab.TabName;
3359 if (_curTab.Text.Equals(favTabName))
3361 fidx = _curList.FocusedItem?.Index ?? _curList.TopItem?.Index ?? 0;
3364 foreach (long i in ids)
3368 _statuses.RemoveFavPost(i);
3375 if (_curTab != null && _curTab.Text.Equals(favTabName))
3377 this.PurgeListViewItemCache();
3379 //_curItemIndex = -1;
3381 foreach (TabPage tp in ListTab.TabPages)
3383 if (tp.Text == favTabName)
3385 ((DetailsListView)tp.Tag).VirtualListSize = favTab.AllCount;
3389 if (_curTab.Text.Equals(favTabName))
3393 _curList.SelectedIndices.Clear();
3395 while (_curList.SelectedIndices.Count > 0);
3397 if (favTab.AllCount > 0)
3399 if (favTab.AllCount - 1 > fidx && fidx > -1)
3401 _curList.SelectedIndices.Add(fidx);
3405 _curList.SelectedIndices.Add(favTab.AllCount - 1);
3407 if (_curList.SelectedIndices.Count > 0)
3409 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3410 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3416 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3418 if (e.Button == MouseButtons.Left)
3420 this.Visible = true;
3421 if (this.WindowState == FormWindowState.Minimized)
3423 this.WindowState = _formWindowState;
3426 this.BringToFront();
3430 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3432 switch (this._cfgCommon.ListDoubleClickAction)
3435 MakeReplyOrDirectStatus();
3438 await this.FavoriteChange(true);
3441 if (_curPost != null)
3442 await this.ShowUserStatus(_curPost.ScreenName, false);
3448 ShowRelatedStatusesMenuItem_Click(null, null);
3451 MoveToHomeToolStripMenuItem_Click(null, null);
3454 StatusOpenMenuItem_Click(null, null);
3462 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3464 await this.FavoriteChange(true);
3467 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3469 await this.FavoriteChange(false);
3473 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3475 await this.FavoritesRetweetOfficial();
3478 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3480 await this.FavoritesRetweetUnofficial();
3483 private async Task FavoriteChange(bool FavAdd , bool multiFavoriteChangeDialogEnable = true)
3486 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3489 //trueでFavAdd,falseでFavRemove
3490 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3491 || !this.ExistCurrentPost) return;
3493 // 誤ふぁぼ・故意によるふぁぼ爆対策 (変更しないこと)
3494 // https://support.twitter.com/articles/76915#favoriting
3495 const int MultiSelectFavLimit = 1;
3498 if (_curList.SelectedIndices.Count > MultiSelectFavLimit && FavAdd)
3500 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, MultiSelectFavLimit));
3501 _DoFavRetweetFlags = false;
3504 else if (multiFavoriteChangeDialogEnable && _curList.SelectedIndices.Count > 1)
3508 string QuestionText = Properties.Resources.FavAddToolStripMenuItem_ClickText1;
3509 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText3;
3510 if (MessageBox.Show(QuestionText, Properties.Resources.FavAddToolStripMenuItem_ClickText2,
3511 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3513 _DoFavRetweetFlags = false;
3519 if (MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1, Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3520 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3527 var statusIds = new List<long>();
3528 foreach (int idx in _curList.SelectedIndices)
3530 PostClass post = GetCurTabPost(idx);
3534 statusIds.Add(post.StatusId);
3539 statusIds.Add(post.StatusId);
3542 if (statusIds.Count == 0)
3545 StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3547 StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3553 await this.FavAddAsync(statusIds, tab);
3555 await this.FavRemoveAsync(statusIds, tab);
3558 private PostClass GetCurTabPost(int Index)
3560 this.itemCacheLock.EnterReadLock();
3563 if (_postCache != null && Index >= _itemCacheIndex && Index < _itemCacheIndex + _postCache.Length)
3564 return _postCache[Index - _itemCacheIndex];
3566 finally { this.itemCacheLock.ExitReadLock(); }
3568 return _statuses.Tabs[_curTab.Text][Index];
3572 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3574 if (_curList.SelectedIndices.Count > 0)
3575 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3576 else if (_curList.SelectedIndices.Count == 0)
3577 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3580 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3582 if (_curList.SelectedIndices.Count > 0)
3583 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3586 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3588 if ((!_initialLayout) && this.Visible)
3590 if (this.WindowState == FormWindowState.Normal)
3592 _mySize = this.ClientSize;
3593 _mySpDis = this.SplitContainer1.SplitterDistance;
3594 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3595 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3596 _modifySettingLocal = true;
3601 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3603 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3604 if (comparerMode == null)
3607 this.SetSortColumn(comparerMode.Value);
3611 /// 列インデックスからソートを行う ComparerMode を求める
3613 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3614 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3615 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3618 return ComparerMode.Id;
3620 switch (columnIndex)
3623 return ComparerMode.Nickname;
3625 return ComparerMode.Data;
3627 return ComparerMode.Id;
3629 return ComparerMode.Name;
3631 return ComparerMode.Source;
3633 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3639 /// 発言一覧の指定した位置の列でソートする
3641 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3642 private void SetSortColumnByDisplayIndex(int columnIndex)
3644 // 表示上の列の位置から ColumnHeader を求める
3645 var col = this._curList.Columns.Cast<ColumnHeader>()
3646 .Where(x => x.DisplayIndex == columnIndex)
3652 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3653 if (comparerMode == null)
3656 this.SetSortColumn(comparerMode.Value);
3660 /// 発言一覧の最後列の項目でソートする
3662 private void SetSortLastColumn()
3664 // 表示上の最後列にある ColumnHeader を求める
3665 var col = this._curList.Columns.Cast<ColumnHeader>()
3666 .OrderByDescending(x => x.DisplayIndex)
3669 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3670 if (comparerMode == null)
3673 this.SetSortColumn(comparerMode.Value);
3677 /// 発言一覧を指定された ComparerMode に基づいてソートする
3679 private void SetSortColumn(ComparerMode sortColumn)
3681 if (this._cfgCommon.SortOrderLock)
3684 this._statuses.ToggleSortOrder(sortColumn);
3685 this.InitColumnText();
3687 var list = this._curList;
3690 list.Columns[0].Text = this.ColumnText[0];
3691 list.Columns[1].Text = this.ColumnText[2];
3695 for (var i = 0; i <= 7; i++)
3697 list.Columns[i].Text = this.ColumnText[i];
3701 this.PurgeListViewItemCache();
3703 var tab = this._statuses.Tabs[this._curTab.Text];
3704 if (tab.AllCount > 0 && this._curPost != null)
3706 var idx = tab.IndexOf(this._curPost.StatusId);
3709 this.SelectListItem(list, idx);
3710 list.EnsureVisible(idx);
3715 this._modifySettingCommon = true;
3718 private void TweenMain_LocationChanged(object sender, EventArgs e)
3720 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3722 _myLoc = this.DesktopLocation;
3723 _modifySettingLocal = true;
3727 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3729 if (ListTab.SelectedTab == null) return;
3730 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3731 if (!this.ExistCurrentPost)
3733 ReplyStripMenuItem.Enabled = false;
3734 ReplyAllStripMenuItem.Enabled = false;
3735 DMStripMenuItem.Enabled = false;
3736 ShowProfileMenuItem.Enabled = false;
3737 ShowUserTimelineContextMenuItem.Enabled = false;
3738 ListManageUserContextToolStripMenuItem2.Enabled = false;
3739 MoveToFavToolStripMenuItem.Enabled = false;
3740 TabMenuItem.Enabled = false;
3741 IDRuleMenuItem.Enabled = false;
3742 SourceRuleMenuItem.Enabled = false;
3743 ReadedStripMenuItem.Enabled = false;
3744 UnreadStripMenuItem.Enabled = false;
3748 ShowProfileMenuItem.Enabled = true;
3749 ListManageUserContextToolStripMenuItem2.Enabled = true;
3750 ReplyStripMenuItem.Enabled = true;
3751 ReplyAllStripMenuItem.Enabled = true;
3752 DMStripMenuItem.Enabled = true;
3753 ShowUserTimelineContextMenuItem.Enabled = true;
3754 MoveToFavToolStripMenuItem.Enabled = true;
3755 TabMenuItem.Enabled = true;
3756 IDRuleMenuItem.Enabled = true;
3757 SourceRuleMenuItem.Enabled = true;
3758 ReadedStripMenuItem.Enabled = true;
3759 UnreadStripMenuItem.Enabled = true;
3761 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3763 FavAddToolStripMenuItem.Enabled = false;
3764 FavRemoveToolStripMenuItem.Enabled = false;
3765 StatusOpenMenuItem.Enabled = false;
3766 FavorareMenuItem.Enabled = false;
3767 ShowRelatedStatusesMenuItem.Enabled = false;
3769 ReTweetStripMenuItem.Enabled = false;
3770 ReTweetUnofficialStripMenuItem.Enabled = false;
3771 QuoteStripMenuItem.Enabled = false;
3772 FavoriteRetweetContextMenu.Enabled = false;
3773 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3777 FavAddToolStripMenuItem.Enabled = true;
3778 FavRemoveToolStripMenuItem.Enabled = true;
3779 StatusOpenMenuItem.Enabled = true;
3780 FavorareMenuItem.Enabled = true;
3781 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3785 ReTweetStripMenuItem.Enabled = false; //公式RTは無効に
3786 ReTweetUnofficialStripMenuItem.Enabled = true;
3787 QuoteStripMenuItem.Enabled = true;
3788 FavoriteRetweetContextMenu.Enabled = false; //公式RTは無効に
3789 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3793 if (_curPost.IsProtect)
3795 ReTweetStripMenuItem.Enabled = false;
3796 ReTweetUnofficialStripMenuItem.Enabled = false;
3797 QuoteStripMenuItem.Enabled = false;
3798 FavoriteRetweetContextMenu.Enabled = false;
3799 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3803 ReTweetStripMenuItem.Enabled = true;
3804 ReTweetUnofficialStripMenuItem.Enabled = true;
3805 QuoteStripMenuItem.Enabled = true;
3806 FavoriteRetweetContextMenu.Enabled = true;
3807 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3811 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3813 // RefreshMoreStripMenuItem.Enabled = true;
3817 // RefreshMoreStripMenuItem.Enabled = false;
3819 if (!this.ExistCurrentPost
3820 || _curPost.InReplyToStatusId == null)
3822 RepliedStatusOpenMenuItem.Enabled = false;
3826 RepliedStatusOpenMenuItem.Enabled = true;
3828 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3830 MoveToRTHomeMenuItem.Enabled = false;
3834 MoveToRTHomeMenuItem.Enabled = true;
3837 if (this.ExistCurrentPost)
3839 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3840 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3841 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3843 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3847 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3849 MakeReplyOrDirectStatus(false, true);
3852 private void DMStripMenuItem_Click(object sender, EventArgs e)
3854 MakeReplyOrDirectStatus(false, false);
3857 private void doStatusDelete()
3859 if (this._curTab == null || this._curList == null)
3862 if (this._curList.SelectedIndices.Count == 0)
3865 var posts = this._curList.SelectedIndices.Cast<int>()
3866 .Select(x => this.GetCurTabPost(x))
3869 // 選択されたツイートの中に削除可能なものが一つでもあるか
3870 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3873 var ret = MessageBox.Show(this,
3874 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3875 Properties.Resources.DeleteStripMenuItem_ClickText2,
3876 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3878 if (ret != DialogResult.OK)
3881 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3883 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3885 Exception lastException = null;
3886 foreach (var post in posts)
3888 if (!post.CanDeleteBy(this.tw.UserId))
3895 this.tw.RemoveDirectMessage(post.StatusId, post);
3899 if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3900 // 他人に RT された自分のツイート
3901 this.tw.RemoveStatus(post.RetweetedId.Value);
3903 // 自分のツイート or 自分が RT したツイート
3904 this.tw.RemoveStatus(post.StatusId);
3907 catch (WebApiException ex)
3913 this._statuses.RemovePost(post.StatusId);
3916 if (lastException == null)
3917 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3919 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3921 this.PurgeListViewItemCache();
3922 this._curPost = null;
3923 this._curItemIndex = -1;
3925 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3927 var listView = (DetailsListView)tabPage.Tag;
3928 var tab = this._statuses.Tabs[tabPage.Text];
3930 using (ControlTransaction.Update(listView))
3932 listView.VirtualListSize = tab.AllCount;
3934 if (tabPage == this._curTab)
3936 listView.SelectedIndices.Clear();
3938 if (tab.AllCount != 0)
3941 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3942 selectedIndex = focusedIndex;
3944 selectedIndex = tab.AllCount - 1;
3946 listView.SelectedIndices.Add(selectedIndex);
3947 listView.EnsureVisible(selectedIndex);
3948 listView.FocusedItem = listView.Items[selectedIndex];
3953 if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3955 if (tabPage.ImageIndex == 0)
3956 tabPage.ImageIndex = -1; // タブアイコン
3960 if (!this._cfgCommon.TabIconDisp)
3961 this.ListTab.Refresh();
3965 private void DeleteStripMenuItem_Click(object sender, EventArgs e)
3970 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3972 using (ControlTransaction.Update(this._curList))
3974 foreach (int idx in _curList.SelectedIndices)
3976 var post = this._statuses.Tabs[this._curTab.Text][idx];
3977 this._statuses.SetReadAllTab(post.StatusId, read: true);
3978 ChangeCacheStyleRead(true, idx);
3982 foreach (TabPage tb in ListTab.TabPages)
3984 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3986 if (this._cfgCommon.TabIconDisp)
3988 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3992 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3995 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3997 using (ControlTransaction.Update(this._curList))
3999 foreach (int idx in _curList.SelectedIndices)
4001 var post = this._statuses.Tabs[this._curTab.Text][idx];
4002 this._statuses.SetReadAllTab(post.StatusId, read: false);
4003 ChangeCacheStyleRead(false, idx);
4007 foreach (TabPage tb in ListTab.TabPages)
4009 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
4011 if (this._cfgCommon.TabIconDisp)
4013 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
4017 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
4020 private void RefreshStripMenuItem_Click(object sender, EventArgs e)
4025 private void DoRefresh()
4027 if (_curTab != null)
4030 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4033 switch (_statuses.Tabs[_curTab.Text].TabType)
4035 case MyCommon.TabUsageType.Mentions:
4036 this.GetReplyAsync();
4038 case MyCommon.TabUsageType.DirectMessage:
4039 this.GetDirectMessagesAsync();
4041 case MyCommon.TabUsageType.Favorites:
4042 this.GetFavoritesAsync();
4044 //case MyCommon.TabUsageType.Profile:
4046 case MyCommon.TabUsageType.PublicSearch:
4048 if (string.IsNullOrEmpty(tab.SearchWords)) return;
4049 this.GetPublicSearchAsync(tab);
4051 case MyCommon.TabUsageType.UserTimeline:
4052 this.GetUserTimelineAsync(tab);
4054 case MyCommon.TabUsageType.Lists:
4056 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4057 this.GetListTimelineAsync(tab);
4060 this.GetHomeTimelineAsync();
4066 this.GetHomeTimelineAsync();
4070 private async Task DoRefreshMore()
4073 if (_curTab != null)
4076 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4079 switch (_statuses.Tabs[_curTab.Text].TabType)
4081 case MyCommon.TabUsageType.Mentions:
4082 await this.GetReplyAsync(loadMore: true);
4084 case MyCommon.TabUsageType.DirectMessage:
4085 await this.GetDirectMessagesAsync(loadMore: true);
4087 case MyCommon.TabUsageType.Favorites:
4088 await this.GetFavoritesAsync(loadMore: true);
4090 case MyCommon.TabUsageType.Profile:
4093 case MyCommon.TabUsageType.PublicSearch:
4095 if (string.IsNullOrEmpty(tab.SearchWords)) return;
4096 await this.GetPublicSearchAsync(tab, loadMore: true);
4098 case MyCommon.TabUsageType.UserTimeline:
4099 await this.GetUserTimelineAsync(tab, loadMore: true);
4101 case MyCommon.TabUsageType.Lists:
4103 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4104 await this.GetListTimelineAsync(tab, loadMore: true);
4107 await this.GetHomeTimelineAsync(loadMore: true);
4113 await this.GetHomeTimelineAsync(loadMore: true);
4117 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
4119 DialogResult result = DialogResult.Abort;
4121 using (var settingDialog = new AppendSettingDialog())
4123 settingDialog.Icon = this.MainIcon;
4124 settingDialog.Owner = this;
4125 settingDialog.ShowInTaskbar = showTaskbarIcon;
4126 settingDialog.IntervalChanged += this.TimerInterval_Changed;
4128 settingDialog.tw = this.tw;
4129 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
4133 result = settingDialog.ShowDialog(this);
4137 return DialogResult.Abort;
4140 if (result == DialogResult.OK)
4144 settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
4152 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
4155 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
4157 var oldIconSz = this._cfgCommon.IconSize;
4159 if (ShowSettingDialog() == DialogResult.OK)
4163 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
4164 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
4165 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
4166 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
4167 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
4168 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
4170 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
4171 Networking.SetWebProxy(this._cfgLocal.ProxyType,
4172 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
4173 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
4174 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
4176 ImageSelector.Reset(tw, this.tw.Configuration);
4180 if (this._cfgCommon.TabIconDisp)
4182 ListTab.DrawItem -= ListTab_DrawItem;
4183 ListTab.DrawMode = TabDrawMode.Normal;
4184 ListTab.ImageList = this.TabImage;
4188 ListTab.DrawItem -= ListTab_DrawItem;
4189 ListTab.DrawItem += ListTab_DrawItem;
4190 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
4191 ListTab.ImageList = null;
4194 catch (Exception ex)
4196 ex.Data["Instance"] = "ListTab(TabIconDisp)";
4197 ex.Data["IsTerminatePermission"] = false;
4203 if (!this._cfgCommon.UnreadManage)
4205 ReadedStripMenuItem.Enabled = false;
4206 UnreadStripMenuItem.Enabled = false;
4207 if (this._cfgCommon.TabIconDisp)
4209 foreach (TabPage myTab in ListTab.TabPages)
4211 myTab.ImageIndex = -1;
4217 ReadedStripMenuItem.Enabled = true;
4218 UnreadStripMenuItem.Enabled = true;
4221 catch (Exception ex)
4223 ex.Data["Instance"] = "ListTab(UnreadManage)";
4224 ex.Data["IsTerminatePermission"] = false;
4231 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
4233 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
4234 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
4235 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
4237 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
4238 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
4239 _fntUnread = this._cfgLocal.FontUnread;
4240 _clUnread = this._cfgLocal.ColorUnread;
4241 _fntReaded = this._cfgLocal.FontRead;
4242 _clReaded = this._cfgLocal.ColorRead;
4243 _clFav = this._cfgLocal.ColorFav;
4244 _clOWL = this._cfgLocal.ColorOWL;
4245 _clRetweet = this._cfgLocal.ColorRetweet;
4246 _fntDetail = this._cfgLocal.FontDetail;
4247 _clDetail = this._cfgLocal.ColorDetail;
4248 _clDetailLink = this._cfgLocal.ColorDetailLink;
4249 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
4250 _clSelf = this._cfgLocal.ColorSelf;
4251 _clAtSelf = this._cfgLocal.ColorAtSelf;
4252 _clTarget = this._cfgLocal.ColorTarget;
4253 _clAtTarget = this._cfgLocal.ColorAtTarget;
4254 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
4255 _clAtTo = this._cfgLocal.ColorAtTo;
4256 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
4257 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
4258 _clInputFont = this._cfgLocal.ColorInputFont;
4259 _fntInputFont = this._cfgLocal.FontInputFont;
4260 _brsBackColorMine.Dispose();
4261 _brsBackColorAt.Dispose();
4262 _brsBackColorYou.Dispose();
4263 _brsBackColorAtYou.Dispose();
4264 _brsBackColorAtFromTarget.Dispose();
4265 _brsBackColorAtTo.Dispose();
4266 _brsBackColorNone.Dispose();
4267 _brsBackColorMine = new SolidBrush(_clSelf);
4268 _brsBackColorAt = new SolidBrush(_clAtSelf);
4269 _brsBackColorYou = new SolidBrush(_clTarget);
4270 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4271 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4272 _brsBackColorAtTo = new SolidBrush(_clAtTo);
4273 _brsBackColorNone = new SolidBrush(_clListBackcolor);
4277 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4278 StatusText.Font = _fntInputFont;
4279 StatusText.ForeColor = _clInputFont;
4281 catch (Exception ex)
4283 MessageBox.Show(ex.Message);
4288 InitDetailHtmlFormat();
4290 catch (Exception ex)
4292 ex.Data["Instance"] = "Font";
4293 ex.Data["IsTerminatePermission"] = false;
4299 foreach (TabPage tb in ListTab.TabPages)
4301 if (this._cfgCommon.TabIconDisp)
4303 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4310 catch (Exception ex)
4312 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4313 ex.Data["IsTerminatePermission"] = false;
4319 var oldIconCol = _iconCol;
4321 if (this._cfgCommon.IconSize != oldIconSz)
4322 ApplyListViewIconSize(this._cfgCommon.IconSize);
4324 foreach (TabPage tp in ListTab.TabPages)
4326 DetailsListView lst = (DetailsListView)tp.Tag;
4328 using (ControlTransaction.Update(lst))
4330 lst.GridLines = this._cfgCommon.ShowGrid;
4331 lst.Font = _fntReaded;
4332 lst.BackColor = _clListBackcolor;
4334 if (_iconCol != oldIconCol)
4339 catch (Exception ex)
4341 ex.Data["Instance"] = "ListView(IconSize)";
4342 ex.Data["IsTerminatePermission"] = false;
4346 SetMainWindowTitle();
4347 SetNotifyIconText();
4349 this.PurgeListViewItemCache();
4350 _curList?.Refresh();
4353 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4354 if (this._cfgCommon.HotkeyEnabled)
4356 ///グローバルホットキーの登録。設定で変更可能にするかも
4357 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4358 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4359 modKey |= HookGlobalHotkey.ModKeys.Alt;
4360 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4361 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4362 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4363 modKey |= HookGlobalHotkey.ModKeys.Shift;
4364 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4365 modKey |= HookGlobalHotkey.ModKeys.Win;
4367 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4370 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4373 StatusText_TextChanged(null, null);
4382 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
4383 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
4386 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4388 this.TopMost = this._cfgCommon.AlwaysTop;
4389 SaveConfigsAll(false);
4391 if (tw.Username != oldUser.Username)
4392 await this.doGetFollowersMenu();
4398 private void SetTabAlignment()
4400 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4401 if (ListTab.Alignment == newAlignment) return;
4404 var selId = new Dictionary<string, long[]>();
4405 var focusedId = new Dictionary<string, Tuple<long, long>>();
4406 SaveSelectedStatus(selId, focusedId);
4408 ListTab.Alignment = newAlignment;
4411 foreach (TabPage tab in ListTab.TabPages)
4413 DetailsListView lst = (DetailsListView)tab.Tag;
4414 TabClass tabInfo = _statuses.Tabs[tab.Text];
4415 using (ControlTransaction.Update(lst))
4417 // status_id から ListView 上のインデックスに変換
4418 var selectedIndices = selId[tab.Text] != null
4419 ? tabInfo.IndexOf(selId[tab.Text]).Where(x => x != -1).ToArray()
4421 var focusedIndex = tabInfo.IndexOf(focusedId[tab.Text].Item1);
4422 var selectionMarkIndex = tabInfo.IndexOf(focusedId[tab.Text].Item2);
4424 this.SelectListItem(lst, selectedIndices, focusedIndex, selectionMarkIndex);
4429 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4435 case MyCommon.IconSizes.IconNone:
4438 case MyCommon.IconSizes.Icon16:
4441 case MyCommon.IconSizes.Icon24:
4444 case MyCommon.IconSizes.Icon48:
4447 case MyCommon.IconSizes.Icon48_2:
4455 // ディスプレイの DPI 設定を考慮したサイズを設定する
4456 _listViewImageList.ImageSize = new Size(
4458 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4462 _listViewImageList.ImageSize = new Size(1, 1);
4466 private void ResetColumns(DetailsListView list)
4468 using (ControlTransaction.Update(list))
4469 using (ControlTransaction.Layout(list, false))
4472 list.ColumnClick -= MyList_ColumnClick;
4473 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4474 list.ColumnReordered -= MyList_ColumnReordered;
4475 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4477 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4478 list.Columns.Clear();
4479 cols.ForEach(col => col.Dispose());
4482 InitColumns(list, true);
4484 list.ColumnClick += MyList_ColumnClick;
4485 list.DrawColumnHeader += MyList_DrawColumnHeader;
4486 list.ColumnReordered += MyList_ColumnReordered;
4487 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4491 private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4493 if (e.Url.AbsoluteUri != "about:blank")
4495 await this.DispSelectedPost();
4496 await this.OpenUriInBrowserAsync(e.Url.OriginalString);
4500 private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4502 if (e.Url.Scheme == "data")
4504 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4506 else if (e.Url.AbsoluteUri != "about:blank")
4509 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
4510 await this.OpenUriAsync( e.Url, MyCommon.IsKeyDown( Keys.Control ) );
4514 public void AddNewTabForSearch(string searchWord)
4516 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4517 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4519 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4521 foreach (TabPage tp in ListTab.TabPages)
4523 if (tb.TabName == tp.Text)
4525 ListTab.SelectedTab = tp;
4532 string tabName = searchWord;
4533 for (int i = 0; i <= 100; i++)
4535 if (_statuses.ContainsTab(tabName))
4541 _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4542 AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4544 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4546 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4547 cmb.Items.Add(searchWord);
4548 cmb.Text = searchWord;
4551 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4554 private void ShowUserTimeline()
4556 if (!this.ExistCurrentPost) return;
4557 AddNewTabForUserTimeline(_curPost.ScreenName);
4560 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4562 if (e.KeyCode == Keys.Escape)
4564 TabPage relTp = ListTab.SelectedTab;
4565 RemoveSpecifiedTab(relTp.Text, false);
4567 e.SuppressKeyPress = true;
4571 public void AddNewTabForUserTimeline(string user)
4573 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4574 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4576 if (tb.User == user)
4578 foreach (TabPage tp in ListTab.TabPages)
4580 if (tb.TabName == tp.Text)
4582 ListTab.SelectedTab = tp;
4589 string tabName = "user:" + user;
4590 while (_statuses.ContainsTab(tabName))
4595 _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4596 var tab = this._statuses.Tabs[tabName];
4598 AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4600 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4603 this.GetUserTimelineAsync(tab);
4606 public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4609 foreach (TabPage tb in ListTab.TabPages)
4611 if (tb.Text == tabName) return false;
4615 if (tabName == Properties.Resources.AddNewTabText1) return false;
4620 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4621 tabType == MyCommon.TabUsageType.Favorites ||
4622 tabType == MyCommon.TabUsageType.Home ||
4623 tabType == MyCommon.TabUsageType.Mentions ||
4624 tabType == MyCommon.TabUsageType.Related)
4626 if (_statuses.GetTabByType(tabType) != null) return false;
4630 var _tabPage = new TabPage();
4631 var _listCustom = new DetailsListView();
4633 int cnt = ListTab.TabPages.Count;
4635 ///ToDo:Create and set controls follow tabtypes
4637 using (ControlTransaction.Update(_listCustom))
4638 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4639 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4640 using (ControlTransaction.Layout(this.SplitContainer1, false))
4641 using (ControlTransaction.Layout(this.ListTab, false))
4642 using (ControlTransaction.Layout(this))
4643 using (ControlTransaction.Layout(_tabPage, false))
4645 _tabPage.Controls.Add(_listCustom);
4648 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4650 var label = new Label();
4651 label.Dock = DockStyle.Top;
4652 label.Name = "labelUser";
4653 if (tabType == MyCommon.TabUsageType.Lists)
4655 label.Text = listInfo.ToString();
4659 label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4661 label.TextAlign = ContentAlignment.MiddleLeft;
4662 using (ComboBox tmpComboBox = new ComboBox())
4664 label.Height = tmpComboBox.Height;
4666 _tabPage.Controls.Add(label);
4669 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4671 var pnl = new Panel();
4673 var lbl = new Label();
4674 var cmb = new ComboBox();
4675 var btn = new Button();
4676 var cmbLang = new ComboBox();
4678 using (ControlTransaction.Layout(pnl, false))
4680 pnl.Controls.Add(cmb);
4681 pnl.Controls.Add(cmbLang);
4682 pnl.Controls.Add(btn);
4683 pnl.Controls.Add(lbl);
4684 pnl.Name = "panelSearch";
4685 pnl.Dock = DockStyle.Top;
4686 pnl.Height = cmb.Height;
4687 pnl.Enter += SearchControls_Enter;
4688 pnl.Leave += SearchControls_Leave;
4691 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4692 cmb.Dock = DockStyle.Fill;
4693 cmb.Name = "comboSearch";
4694 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4695 cmb.ImeMode = ImeMode.NoControl;
4696 cmb.TabStop = false;
4697 cmb.AutoCompleteMode = AutoCompleteMode.None;
4698 cmb.KeyDown += SearchComboBox_KeyDown;
4701 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4702 cmbLang.Dock = DockStyle.Right;
4704 cmbLang.Name = "comboLang";
4705 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4706 cmbLang.TabStop = false;
4707 cmbLang.Items.Add("");
4708 cmbLang.Items.Add("ja");
4709 cmbLang.Items.Add("en");
4710 cmbLang.Items.Add("ar");
4711 cmbLang.Items.Add("da");
4712 cmbLang.Items.Add("nl");
4713 cmbLang.Items.Add("fa");
4714 cmbLang.Items.Add("fi");
4715 cmbLang.Items.Add("fr");
4716 cmbLang.Items.Add("de");
4717 cmbLang.Items.Add("hu");
4718 cmbLang.Items.Add("is");
4719 cmbLang.Items.Add("it");
4720 cmbLang.Items.Add("no");
4721 cmbLang.Items.Add("pl");
4722 cmbLang.Items.Add("pt");
4723 cmbLang.Items.Add("ru");
4724 cmbLang.Items.Add("es");
4725 cmbLang.Items.Add("sv");
4726 cmbLang.Items.Add("th");
4728 lbl.Text = "Search(C-S-f)";
4729 lbl.Name = "label1";
4730 lbl.Dock = DockStyle.Left;
4732 lbl.Height = cmb.Height;
4733 lbl.TextAlign = ContentAlignment.MiddleLeft;
4735 btn.Text = "Search";
4736 btn.Name = "buttonSearch";
4737 btn.UseVisualStyleBackColor = true;
4738 btn.Dock = DockStyle.Right;
4739 btn.TabStop = false;
4740 btn.Click += SearchButton_Click;
4743 if (_statuses.Tabs.TryGetValue(tabName, out tab))
4745 if (!string.IsNullOrEmpty(tab.SearchWords))
4747 cmb.Items.Add(tab.SearchWords);
4748 cmb.Text = tab.SearchWords;
4751 cmbLang.Text = tab.SearchLang;
4754 _tabPage.Controls.Add(pnl);
4758 _tabPage.Tag = _listCustom;
4759 this.ListTab.Controls.Add(_tabPage);
4761 _tabPage.Location = new Point(4, 4);
4762 _tabPage.Name = "CTab" + cnt.ToString();
4763 _tabPage.Size = new Size(380, 260);
4764 _tabPage.TabIndex = 2 + cnt;
4765 _tabPage.Text = tabName;
4766 _tabPage.UseVisualStyleBackColor = true;
4768 _listCustom.AllowColumnReorder = true;
4769 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4770 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4771 _listCustom.Dock = DockStyle.Fill;
4772 _listCustom.FullRowSelect = true;
4773 _listCustom.HideSelection = false;
4774 _listCustom.Location = new Point(0, 0);
4775 _listCustom.Margin = new Padding(0);
4776 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4777 _listCustom.ShowItemToolTips = true;
4778 _listCustom.Size = new Size(380, 260);
4779 _listCustom.UseCompatibleStateImageBehavior = false;
4780 _listCustom.View = View.Details;
4781 _listCustom.OwnerDraw = true;
4782 _listCustom.VirtualMode = true;
4783 _listCustom.Font = _fntReaded;
4784 _listCustom.BackColor = _clListBackcolor;
4786 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4787 _listCustom.AllowDrop = true;
4789 _listCustom.SmallImageList = _listViewImageList;
4791 InitColumns(_listCustom, startup);
4793 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4794 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4795 _listCustom.ColumnClick += MyList_ColumnClick;
4796 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4797 _listCustom.DragDrop += TweenMain_DragDrop;
4798 _listCustom.DragEnter += TweenMain_DragEnter;
4799 _listCustom.DragOver += TweenMain_DragOver;
4800 _listCustom.DrawItem += MyList_DrawItem;
4801 _listCustom.MouseClick += MyList_MouseClick;
4802 _listCustom.ColumnReordered += MyList_ColumnReordered;
4803 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4804 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4805 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4806 _listCustom.DrawSubItem += MyList_DrawSubItem;
4807 _listCustom.HScrolled += MyList_HScrolled;
4813 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4815 var tabInfo = _statuses.GetTabByName(TabName);
4816 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4820 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4821 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4822 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4828 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4829 if (_tabPage == null) return false;
4831 SetListProperty(); //他のタブに列幅等を反映
4834 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4835 _tabPage.Tag = null;
4837 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4838 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4839 using (ControlTransaction.Layout(this.SplitContainer1, false))
4840 using (ControlTransaction.Layout(this.ListTab, false))
4841 using (ControlTransaction.Layout(this))
4842 using (ControlTransaction.Layout(_tabPage, false))
4844 if (this.ListTab.SelectedTab == _tabPage)
4846 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4847 this._beforeSelectedTab = null;
4849 this.ListTab.Controls.Remove(_tabPage);
4852 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4854 using (Control label = _tabPage.Controls["labelUser"])
4856 _tabPage.Controls.Remove(label);
4859 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4861 using (Control pnl = _tabPage.Controls["panelSearch"])
4863 pnl.Enter -= SearchControls_Enter;
4864 pnl.Leave -= SearchControls_Leave;
4865 _tabPage.Controls.Remove(pnl);
4867 foreach (Control ctrl in pnl.Controls)
4869 if (ctrl.Name == "buttonSearch")
4871 ctrl.Click -= SearchButton_Click;
4873 else if (ctrl.Name == "comboSearch")
4875 ctrl.KeyDown -= SearchComboBox_KeyDown;
4877 pnl.Controls.Remove(ctrl);
4883 _tabPage.Controls.Remove(_listCustom);
4885 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4886 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4887 _listCustom.ColumnClick -= MyList_ColumnClick;
4888 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4889 _listCustom.DragDrop -= TweenMain_DragDrop;
4890 _listCustom.DragEnter -= TweenMain_DragEnter;
4891 _listCustom.DragOver -= TweenMain_DragOver;
4892 _listCustom.DrawItem -= MyList_DrawItem;
4893 _listCustom.MouseClick -= MyList_MouseClick;
4894 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4895 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4896 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4897 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4898 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4899 _listCustom.HScrolled -= MyList_HScrolled;
4901 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4902 _listCustom.Columns.Clear();
4903 cols.ForEach(col => col.Dispose());
4906 _listCustom.ContextMenuStrip = null;
4907 _listCustom.ColumnHeaderContextMenuStrip = null;
4908 _listCustom.Font = null;
4910 _listCustom.SmallImageList = null;
4911 _listCustom.ListViewItemSorter = null;
4914 if (_curTab.Equals(_tabPage))
4921 this.PurgeListViewItemCache();
4925 _listCustom.Dispose();
4926 _statuses.RemoveTab(TabName);
4928 foreach (TabPage tp in ListTab.TabPages)
4930 DetailsListView lst = (DetailsListView)tp.Tag;
4931 var count = _statuses.Tabs[tp.Text].AllCount;
4932 if (lst.VirtualListSize != count)
4934 lst.VirtualListSize = count;
4941 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4943 this.PurgeListViewItemCache();
4944 _beforeSelectedTab = e.TabPage;
4947 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4951 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4954 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4955 if (!dragEnableRectangle.Contains(e.Location))
4957 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4958 tn = ListTab.SelectedTab.Text;
4961 if (string.IsNullOrEmpty(tn)) return;
4963 foreach (TabPage tb in ListTab.TabPages)
4967 ListTab.DoDragDrop(tb, DragDropEffects.All);
4977 Point cpos = new Point(e.X, e.Y);
4978 for (int i = 0; i < ListTab.TabPages.Count; i++)
4980 Rectangle rect = ListTab.GetTabRect(i);
4981 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4982 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4984 _rclickTabName = ListTab.TabPages[i].Text;
4990 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4992 //_curList.Refresh();
4993 SetMainWindowTitle();
4994 SetStatusLabelUrl();
4995 SetApiStatusLabel();
4996 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4997 TabMenuControl(ListTab.SelectedTab.Text);
4998 this.PushSelectPostChain();
4999 await DispSelectedPost();
5002 private void SetListProperty()
5004 //削除などで見つからない場合は処理せず
5005 if (_curList == null) return;
5006 if (!_isColumnChanged) return;
5008 int[] dispOrder = new int[_curList.Columns.Count];
5009 for (int i = 0; i < _curList.Columns.Count; i++)
5011 for (int j = 0; j < _curList.Columns.Count; j++)
5013 if (_curList.Columns[j].DisplayIndex == i)
5022 foreach (TabPage tb in ListTab.TabPages)
5024 if (!tb.Equals(_curTab))
5026 if (tb.Tag != null && tb.Controls.Count > 0)
5028 DetailsListView lst = (DetailsListView)tb.Tag;
5029 for (int i = 0; i < lst.Columns.Count; i++)
5031 lst.Columns[dispOrder[i]].DisplayIndex = i;
5032 lst.Columns[i].Width = _curList.Columns[i].Width;
5038 _isColumnChanged = false;
5041 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
5045 if (PostBrowser.StatusText.StartsWith("http") || PostBrowser.StatusText.StartsWith("ftp")
5046 || PostBrowser.StatusText.StartsWith("data"))
5048 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
5050 if (string.IsNullOrEmpty(PostBrowser.StatusText))
5052 SetStatusLabelUrl();
5060 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
5062 if (e.KeyChar == '@')
5064 if (!this._cfgCommon.UseAtIdSupplement) return;
5066 int cnt = AtIdSupl.ItemCount;
5067 ShowSuplDialog(StatusText, AtIdSupl);
5068 if (cnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
5071 else if (e.KeyChar == '#')
5073 if (!this._cfgCommon.UseHashSupplement) return;
5074 ShowSuplDialog(StatusText, HashSupl);
5079 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
5081 ShowSuplDialog(owner, dialog, 0, "");
5084 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
5086 ShowSuplDialog(owner, dialog, offset, "");
5089 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
5091 dialog.StartsWith = startswith;
5098 dialog.ShowDialog();
5100 this.TopMost = this._cfgCommon.AlwaysTop;
5101 int selStart = owner.SelectionStart;
5104 if (dialog.DialogResult == DialogResult.OK)
5106 if (!string.IsNullOrEmpty(dialog.inputText))
5110 fHalf = owner.Text.Substring(0, selStart - offset);
5112 if (selStart < owner.Text.Length)
5114 eHalf = owner.Text.Substring(selStart);
5116 owner.Text = fHalf + dialog.inputText + eHalf;
5117 owner.SelectionStart = selStart + dialog.inputText.Length;
5124 fHalf = owner.Text.Substring(0, selStart);
5126 if (selStart < owner.Text.Length)
5128 eHalf = owner.Text.Substring(selStart);
5130 owner.Text = fHalf + eHalf;
5133 owner.SelectionStart = selStart;
5139 private void StatusText_KeyUp(object sender, KeyEventArgs e)
5142 if (!e.Alt && !e.Control && !e.Shift)
5144 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
5146 bool isSpace = false;
5147 foreach (char c in StatusText.Text.ToCharArray())
5149 if (c == ' ' || c == ' ')
5162 StatusText.Text = "";
5163 JumpUnreadMenuItem_Click(null, null);
5167 this.StatusText_TextChanged(null, null);
5170 private void StatusText_TextChanged(object sender, EventArgs e)
5173 int pLen = GetRestStatusCount(true, false);
5174 lblLen.Text = pLen.ToString();
5177 StatusText.ForeColor = Color.Red;
5181 StatusText.ForeColor = _clInputFont;
5183 if (string.IsNullOrEmpty(StatusText.Text))
5185 this.inReplyTo = null;
5189 private int GetRestStatusCount(bool isAuto, bool isAddFooter)
5192 var statusText = this.StatusText.Text;
5193 statusText = statusText.Replace("\r\n", "\n");
5195 int pLen = 140 - statusText.Length;
5196 if (this.NotifyIcon1 == null || !this.NotifyIcon1.Visible) return pLen;
5197 if ((isAuto && !MyCommon.IsKeyDown(Keys.Control) && this._cfgCommon.PostShiftEnter) ||
5198 (isAuto && !MyCommon.IsKeyDown(Keys.Shift) && !this._cfgCommon.PostShiftEnter) ||
5199 (!isAuto && isAddFooter))
5201 if (this._cfgLocal.UseRecommendStatus)
5202 pLen -= this.recommendedStatusFooter.Length;
5203 else if (this._cfgLocal.StatusText.Length > 0)
5204 pLen -= this._cfgLocal.StatusText.Length + 1;
5206 if (!string.IsNullOrEmpty(HashMgr.UseHash))
5208 pLen -= HashMgr.UseHash.Length + 1;
5210 //foreach (Match m in Regex.Matches(statusText, "https?:\/\/[-_.!~*//()a-zA-Z0-9;\/?:\@&=+\$,%#^]+"))
5212 // pLen += m.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
5214 foreach (Match m in Regex.Matches(statusText, Twitter.rgUrl, RegexOptions.IgnoreCase))
5216 string before = m.Result("${before}");
5217 string url = m.Result("${url}");
5218 string protocol = m.Result("${protocol}");
5219 string domain = m.Result("${domain}");
5220 string path = m.Result("${path}");
5221 if (protocol.Length == 0)
5223 if (Regex.IsMatch(before, Twitter.url_invalid_without_protocol_preceding_chars))
5228 bool last_url_invalid_match = false;
5229 string lasturl = null;
5230 foreach (Match mm in Regex.Matches(domain, Twitter.url_valid_ascii_domain, RegexOptions.IgnoreCase))
5232 lasturl = mm.ToString();
5233 last_url_invalid_match = Regex.IsMatch(lasturl, Twitter.url_invalid_short_domain, RegexOptions.IgnoreCase);
5234 if (!last_url_invalid_match)
5236 pLen += lasturl.Length - this.tw.Configuration.ShortUrlLength;
5240 if (path.Length != 0)
5242 if (last_url_invalid_match)
5244 pLen += lasturl.Length - this.tw.Configuration.ShortUrlLength;
5246 pLen += path.Length;
5251 int shortUrlLength = protocol == "https://"
5252 ? this.tw.Configuration.ShortUrlLengthHttps
5253 : this.tw.Configuration.ShortUrlLength;
5255 pLen += url.Length - shortUrlLength;
5258 //if (m.Result("${url}").Length > SettingDialog.TwitterConfiguration.ShortUrlLength)
5260 // pLen += m.Result("${url}").Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
5263 if (ImageSelector.Visible && !string.IsNullOrEmpty(ImageSelector.ServiceName))
5265 pLen -= this.tw.Configuration.CharactersReservedPerMedia;
5270 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5272 this.itemCacheLock.EnterUpgradeableReadLock();
5275 if (_curList.Equals(sender))
5277 if (_itemCache != null &&
5278 e.StartIndex >= _itemCacheIndex &&
5279 e.EndIndex < _itemCacheIndex + _itemCache.Length)
5281 //If the newly requested cache is a subset of the old cache,
5282 //no need to rebuild everything, so do nothing.
5286 //Now we need to rebuild the cache.
5287 CreateCache(e.StartIndex, e.EndIndex);
5290 finally { this.itemCacheLock.ExitUpgradeableReadLock(); }
5293 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5295 ListViewItem item = null;
5296 PostClass cacheItemPost = null;
5298 if (_curList.Equals(sender))
5299 this.TryGetListViewItemCache(e.ItemIndex, out item, out cacheItemPost);
5303 //A cache miss, so create a new ListViewItem and pass it back.
5304 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5307 item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
5312 string[] sitem = {"", "", "", "", "", "", "", ""};
5313 item = new ImageListViewItem(sitem);
5320 private void CreateCache(int StartIndex, int EndIndex)
5322 this.itemCacheLock.EnterWriteLock();
5325 var tabInfo = _statuses.Tabs[_curTab.Text];
5327 //キャッシュ要求(要求範囲±30を作成)
5329 if (StartIndex < 0) StartIndex = 0;
5331 if (EndIndex >= tabInfo.AllCount) EndIndex = tabInfo.AllCount - 1;
5332 _postCache = tabInfo[StartIndex, EndIndex]; //配列で取得
5333 _itemCacheIndex = StartIndex;
5335 _itemCache = new ListViewItem[0] {};
5336 Array.Resize(ref _itemCache, _postCache.Length);
5338 for (int i = 0; i < _postCache.Length; i++)
5340 _itemCache[i] = CreateItem(_curTab, _postCache[i], StartIndex + i);
5345 //キャッシュ要求が実データとずれるため(イベントの遅延?)
5347 _itemCacheIndex = -1;
5350 finally { this.itemCacheLock.ExitWriteLock(); }
5354 /// DetailsListView のための ListViewItem のキャッシュを消去する
5356 private void PurgeListViewItemCache()
5358 this.itemCacheLock.EnterWriteLock();
5361 this._itemCache = null;
5362 this._itemCacheIndex = -1;
5363 this._postCache = null;
5365 finally { this.itemCacheLock.ExitWriteLock(); }
5368 private bool TryGetListViewItemCache(int index, out ListViewItem item, out PostClass post)
5370 this.itemCacheLock.EnterReadLock();
5373 if (this._itemCache != null && index >= this._itemCacheIndex && index < this._itemCacheIndex + this._itemCache.Length)
5375 item = this._itemCache[index - _itemCacheIndex];
5376 post = this._postCache[index - _itemCacheIndex];
5380 finally { this.itemCacheLock.ExitReadLock(); }
5387 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5389 StringBuilder mk = new StringBuilder();
5390 //if (Post.IsDeleted) mk.Append("×");
5391 //if (Post.IsMark) mk.Append("♪");
5392 //if (Post.IsProtect) mk.Append("Ю");
5393 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5394 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5395 ImageListViewItem itm;
5396 if (Post.RetweetedId == null)
5398 string[] sitem= {"",
5400 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5401 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5406 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5410 string[] sitem = {"",
5412 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5413 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5414 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5418 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5420 itm.StateIndex = Post.StateIndex;
5422 bool read = Post.IsRead;
5423 //未読管理していなかったら既読として扱う
5424 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5425 ChangeItemStyleRead(read, itm, Post, null);
5426 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5431 /// 全てのタブの振り分けルールを反映し直します
5433 private void ApplyPostFilters()
5435 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5437 this.PurgeListViewItemCache();
5438 this._curPost = null;
5439 this._curItemIndex = -1;
5440 this._statuses.FilterAll();
5442 foreach (TabPage tabPage in this.ListTab.TabPages)
5444 var tab = this._statuses.Tabs[tabPage.Text];
5446 var listview = (DetailsListView)tabPage.Tag;
5447 using (ControlTransaction.Update(listview))
5449 listview.VirtualListSize = tab.AllCount;
5452 if (this._cfgCommon.TabIconDisp)
5454 if (tab.UnreadCount > 0)
5455 tabPage.ImageIndex = 0;
5457 tabPage.ImageIndex = -1;
5461 if (!this._cfgCommon.TabIconDisp)
5462 this.ListTab.Refresh();
5464 SetMainWindowTitle();
5465 SetStatusLabelUrl();
5469 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5471 e.DrawDefault = true;
5474 private void MyList_HScrolled(object sender, EventArgs e)
5476 DetailsListView listView = (DetailsListView)sender;
5480 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5482 if (e.State == 0) return;
5483 e.DrawDefault = false;
5485 SolidBrush brs2 = null;
5486 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5488 if (e.Item.BackColor == _clSelf)
5489 brs2 = _brsBackColorMine;
5490 else if (e.Item.BackColor == _clAtSelf)
5491 brs2 = _brsBackColorAt;
5492 else if (e.Item.BackColor == _clTarget)
5493 brs2 = _brsBackColorYou;
5494 else if (e.Item.BackColor == _clAtTarget)
5495 brs2 = _brsBackColorAtYou;
5496 else if (e.Item.BackColor == _clAtFromTarget)
5497 brs2 = _brsBackColorAtFromTarget;
5498 else if (e.Item.BackColor == _clAtTo)
5499 brs2 = _brsBackColorAtTo;
5501 brs2 = _brsBackColorNone;
5506 if (((Control)sender).Focused)
5507 brs2 = _brsHighLight;
5509 brs2 = _brsDeactiveSelection;
5511 e.Graphics.FillRectangle(brs2, e.Bounds);
5512 e.DrawFocusRectangle();
5513 this.DrawListViewItemIcon(e);
5516 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5518 if (e.ItemState == 0) return;
5520 if (e.ColumnIndex > 0)
5523 RectangleF rct = e.Bounds;
5524 rct.Width = e.Header.Width;
5525 int fontHeight = e.Item.Font.Height;
5528 rct.Y += fontHeight;
5529 rct.Height -= fontHeight;
5533 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5535 //if (heightDiff > fontHeight * 0.7)
5537 // rct.Height += fontHeight;
5538 // drawLineCount += 1;
5541 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5542 if (!_iconCol && drawLineCount <= 1)
5544 //rct.Inflate(0, heightDiff / -2);
5545 //rct.Height += fontHeight / 2;
5547 else if (heightDiff < fontHeight * 0.7)
5549 //最終行が70%以上欠けていたら、最終行は表示しない
5550 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5551 rct.Height = (fontHeight * drawLineCount) - 1;
5558 //if (!_iconCol && drawLineCount > 1)
5560 // rct.Y += fontHeight * 0.2;
5561 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5566 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5567 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5572 Rectangle rctB = e.Bounds;
5573 rctB.Width = e.Header.Width;
5574 rctB.Height = fontHeight;
5576 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5578 TextRenderer.DrawText(e.Graphics,
5579 e.Item.SubItems[2].Text,
5581 Rectangle.Round(rct),
5583 TextFormatFlags.WordBreak |
5584 TextFormatFlags.EndEllipsis |
5585 TextFormatFlags.GlyphOverhangPadding |
5586 TextFormatFlags.NoPrefix);
5587 TextRenderer.DrawText(e.Graphics,
5588 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 + "]",
5592 TextFormatFlags.SingleLine |
5593 TextFormatFlags.EndEllipsis |
5594 TextFormatFlags.GlyphOverhangPadding |
5595 TextFormatFlags.NoPrefix);
5598 else if (drawLineCount == 1)
5600 TextRenderer.DrawText(e.Graphics,
5603 Rectangle.Round(rct),
5605 TextFormatFlags.SingleLine |
5606 TextFormatFlags.EndEllipsis |
5607 TextFormatFlags.GlyphOverhangPadding |
5608 TextFormatFlags.NoPrefix |
5609 TextFormatFlags.VerticalCenter);
5613 TextRenderer.DrawText(e.Graphics,
5616 Rectangle.Round(rct),
5618 TextFormatFlags.WordBreak |
5619 TextFormatFlags.EndEllipsis |
5620 TextFormatFlags.GlyphOverhangPadding |
5621 TextFormatFlags.NoPrefix);
5623 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5628 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5630 if (_iconSz == 0) return;
5632 ImageListViewItem item = (ImageListViewItem)e.Item;
5634 //e.Bounds.Leftが常に0を指すから自前で計算
5635 Rectangle itemRect = item.Bounds;
5636 var col0 = e.Item.ListView.Columns[0];
5637 itemRect.Width = col0.Width;
5639 if (col0.DisplayIndex > 0)
5641 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5643 if (clm.DisplayIndex < col0.DisplayIndex)
5644 itemRect.X += clm.Width;
5648 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5649 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5650 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5653 var img = item.Image;
5656 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5657 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5659 if (iconRect.Width > 0)
5661 e.Graphics.FillRectangle(Brushes.White, iconRect);
5662 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5665 e.Graphics.DrawImage(img.Image, iconRect);
5667 catch (ArgumentException)
5669 item.RefreshImageAsync();
5675 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5676 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5678 item.GetImageAsync();
5681 if (item.StateIndex > -1)
5683 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5684 if (stateRect.Width > 0)
5686 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5687 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5688 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5693 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5695 base.ScaleControl(factor, specified);
5697 ScaleChildControl(this.TabImage, factor);
5699 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5700 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5702 foreach (var listview in listviews)
5704 ScaleChildControl(listview, factor);
5708 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5710 // ImageListViewItem item = (ImageListViewItem)e.Item;
5711 // if (item.StateImageIndex > -1)
5713 // ////e.Bounds.Leftが常に0を指すから自前で計算
5714 // //Rectangle itemRect = item.Bounds;
5715 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5717 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5719 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5721 // // itemRect.X += clm.Width;
5725 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5726 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5728 // if (rct.Width > 0)
5730 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5731 // //e.Graphics.FillRectangle(Brushes.White, rct);
5732 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5733 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5738 private void DoTabSearch(string _word,
5748 if (_curList.VirtualListSize == 0)
5750 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5753 if (_curList.SelectedIndices.Count > 0)
5755 cidx = _curList.SelectedIndices[0];
5757 toIdx = _curList.VirtualListSize;
5761 case SEARCHTYPE.DialogSearch: //ダイアログからの検索
5762 if (_curList.SelectedIndices.Count > 0)
5763 cidx = _curList.SelectedIndices[0];
5767 case SEARCHTYPE.NextSearch: //次を検索
5768 if (_curList.SelectedIndices.Count > 0)
5770 cidx = _curList.SelectedIndices[0] + 1;
5771 if (cidx > toIdx) cidx = toIdx;
5778 case SEARCHTYPE.PrevSearch: //前を検索
5779 if (_curList.SelectedIndices.Count > 0)
5781 cidx = _curList.SelectedIndices[0] - 1;
5782 if (cidx < 0) cidx = 0;
5793 RegexOptions regOpt = RegexOptions.None;
5794 StringComparison fndOpt = StringComparison.Ordinal;
5797 regOpt = RegexOptions.IgnoreCase;
5798 fndOpt = StringComparison.OrdinalIgnoreCase;
5809 _search = new Regex(_word, regOpt);
5810 for (int idx = cidx; idx != toIdx; idx += stp)
5815 post = _statuses.Tabs[_curTab.Text][idx];
5821 if (_search.IsMatch(post.Nickname)
5822 || _search.IsMatch(post.TextFromApi)
5823 || _search.IsMatch(post.ScreenName))
5825 SelectListItem(_curList, idx);
5826 _curList.EnsureVisible(idx);
5831 catch (ArgumentException)
5833 MessageBox.Show(Properties.Resources.DoTabSearchText1, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
5840 for (int idx = cidx; idx != toIdx; idx += stp)
5845 post = _statuses.Tabs[_curTab.Text][idx];
5851 if (post.Nickname.IndexOf(_word, fndOpt) > -1
5852 || post.TextFromApi.IndexOf(_word, fndOpt) > -1
5853 || post.ScreenName.IndexOf(_word, fndOpt) > -1)
5855 SelectListItem(_curList, idx);
5856 _curList.EnsureVisible(idx);
5866 case SEARCHTYPE.DialogSearch:
5867 case SEARCHTYPE.NextSearch:
5871 case SEARCHTYPE.PrevSearch:
5873 cidx = _curList.VirtualListSize - 1;
5880 catch (ArgumentOutOfRangeException)
5883 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5886 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5889 this.ShowSearchDialog();
5892 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5894 var previousSearch = this.SearchDialog.ResultOptions;
5895 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5897 this.SearchDialog.Reset();
5898 this.ShowSearchDialog();
5904 previousSearch.Query,
5905 previousSearch.CaseSensitive,
5906 previousSearch.UseRegex,
5907 SEARCHTYPE.NextSearch);
5910 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5912 var previousSearch = this.SearchDialog.ResultOptions;
5913 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5915 this.SearchDialog.Reset();
5916 this.ShowSearchDialog();
5922 previousSearch.Query,
5923 previousSearch.CaseSensitive,
5924 previousSearch.UseRegex,
5925 SEARCHTYPE.PrevSearch);
5929 /// 検索ダイアログを表示し、検索を実行します
5931 private void ShowSearchDialog()
5933 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5935 this.TopMost = this._cfgCommon.AlwaysTop;
5938 this.TopMost = this._cfgCommon.AlwaysTop;
5940 var searchOptions = this.SearchDialog.ResultOptions;
5941 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5943 if (searchOptions.NewTab)
5945 var tabName = Properties.Resources.SearchResults_TabName;
5949 tabName = this._statuses.MakeTabName(tabName);
5951 catch (TabException ex)
5953 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5956 this.AddNewTab(tabName, false, MyCommon.TabUsageType.SearchResults);
5957 this._statuses.AddTab(tabName, MyCommon.TabUsageType.SearchResults, null);
5959 var filter = new PostFilterRule
5961 FilterBody = new[] { searchOptions.Query },
5962 UseRegex = searchOptions.UseRegex,
5963 CaseSensitive = searchOptions.CaseSensitive,
5966 var targetTab = this._statuses.Tabs[this._curTab.Text];
5967 var posts = targetTab.Posts.Values
5968 .Where(x => filter.ExecFilter(x) == MyCommon.HITRESULT.CopyAndMark)
5969 .Where(x => targetTab.Contains(x.StatusId));
5971 var resultTab = this._statuses.Tabs[tabName];
5972 foreach (var post in posts)
5974 resultTab.AddPostToInnerStorage(post.Clone());
5977 this._statuses.DistributePosts();
5978 this.RefreshTimeline(false);
5980 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5981 .First(x => x.Text == tabName);
5983 this.ListTab.SelectedTab = tabPage;
5988 searchOptions.Query,
5989 searchOptions.CaseSensitive,
5990 searchOptions.UseRegex,
5991 SEARCHTYPE.DialogSearch);
5994 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5996 this.AddNewTabForSearch(searchOptions.Query);
6000 private void AboutMenuItem_Click(object sender, EventArgs e)
6002 using (TweenAboutBox about = new TweenAboutBox())
6004 about.ShowDialog(this);
6006 this.TopMost = this._cfgCommon.AlwaysTop;
6009 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
6011 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
6013 DetailsListView lst = null;
6015 if (ImageSelector.Enabled)
6019 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
6022 idx = _statuses.Tabs[ListTab.TabPages[i].Text].OldestUnreadIndex;
6025 ListTab.SelectedIndex = i;
6026 lst = (DetailsListView)ListTab.TabPages[i].Tag;
6027 //_curTab = ListTab.TabPages[i];
6032 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
6033 if (idx == -1 && bgnIdx > 0)
6035 for (int i = 0; i < bgnIdx; i++)
6037 idx = _statuses.Tabs[ListTab.TabPages[i].Text].OldestUnreadIndex;
6040 ListTab.SelectedIndex = i;
6041 lst = (DetailsListView)ListTab.TabPages[i].Tag;
6042 //_curTab = ListTab.TabPages[i];
6048 //全部調べたが未読見つからず→先頭タブの最新発言へ
6051 ListTab.SelectedIndex = 0;
6052 lst = (DetailsListView)ListTab.TabPages[0].Tag;
6053 //_curTab = ListTab.TabPages[0];
6054 if (_statuses.SortOrder == SortOrder.Ascending)
6055 idx = lst.VirtualListSize - 1;
6060 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
6062 SelectListItem(lst, idx);
6063 if (_statuses.SortMode == ComparerMode.Id)
6065 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
6066 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
6072 lst.EnsureVisible(idx);
6077 lst.EnsureVisible(idx);
6083 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
6085 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
6087 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6088 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
6092 private async void FavorareMenuItem_Click(object sender, EventArgs e)
6094 if (_curList.SelectedIndices.Count > 0)
6096 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6097 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
6101 private async void VerUpMenuItem_Click(object sender, EventArgs e)
6103 await this.CheckNewVersion(false);
6106 private void RunTweenUp()
6108 ProcessStartInfo pinfo = new ProcessStartInfo();
6109 pinfo.UseShellExecute = true;
6110 pinfo.WorkingDirectory = MyCommon.settingPath;
6111 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
6112 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
6115 Process.Start(pinfo);
6119 MessageBox.Show("Failed to execute TweenUp3.exe.");
6123 public class VersionInfo
6125 public Version Version { get; set; }
6126 public Uri DownloadUri { get; set; }
6127 public string ReleaseNote { get; set; }
6131 /// OpenTween の最新バージョンの情報を取得します
6133 public async Task<VersionInfo> GetVersionInfoAsync()
6135 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
6136 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
6138 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
6139 .ConfigureAwait(false);
6141 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
6142 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
6144 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
6145 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
6147 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
6149 return new VersionInfo
6151 Version = Version.Parse(msgHeader[0]),
6152 DownloadUri = new Uri(msgHeader[1]),
6153 ReleaseNote = msgBody,
6157 private async Task CheckNewVersion(bool startup = false)
6159 if (ApplicationSettings.VersionInfoUrl == null)
6160 return; // 更新チェック無効化
6164 var versionInfo = await this.GetVersionInfoAsync();
6166 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
6171 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
6172 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
6173 msgtext = MyCommon.ReplaceAppName(msgtext);
6175 MessageBox.Show(msgtext,
6176 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6177 MessageBoxButtons.OK, MessageBoxIcon.Information);
6182 using (var dialog = new UpdateDialog())
6184 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
6185 MyCommon.GetReadableVersion(versionInfo.Version));
6186 dialog.DetailsText = versionInfo.ReleaseNote;
6188 if (dialog.ShowDialog(this) == DialogResult.Yes)
6190 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
6196 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
6199 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
6200 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6201 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
6206 private async Task Colorize()
6209 await this.DispSelectedPost();
6210 //件数関連の場合、タイトル即時書き換え
6211 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
6212 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6213 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6214 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6216 SetMainWindowTitle();
6218 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6219 foreach (TabPage tb in ListTab.TabPages)
6221 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6223 if (this._cfgCommon.TabIconDisp)
6225 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6229 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
6232 public string createDetailHtml(string orgdata)
6234 if (this._cfgLocal.UseTwemoji)
6235 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
6237 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6240 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6242 if (sender.Equals(displayItem))
6244 this.ClearUserPicture();
6246 var img = displayItem.Image;
6250 img = await img.CloneAsync();
6252 UserPicture.Image = img;
6256 UserPicture.ShowErrorImage();
6261 private Task DispSelectedPost()
6263 return this.DispSelectedPost(false);
6266 private PostClass displayPost = new PostClass();
6269 /// サムネイル表示に使用する CancellationToken の生成元
6271 private CancellationTokenSource thumbnailTokenSource = null;
6273 private async Task DispSelectedPost(bool forceupdate)
6275 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6278 var oldDisplayPost = this.displayPost;
6279 this.displayPost = this._curPost;
6281 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6284 if (displayItem != null)
6286 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6289 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6290 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6292 using (ControlTransaction.Update(this.TableLayoutPanel1))
6294 SourceLinkLabel.Text = this._curPost.Source;
6295 SourceLinkLabel.Tag = this._curPost.SourceUri;
6296 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6302 nameText = "DM FROM <- ";
6304 nameText = "DM TO -> ";
6310 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6311 if (_curPost.RetweetedId != null)
6312 nameText += " (RT:" + _curPost.RetweetedBy + ")";
6314 NameLabel.Text = nameText;
6315 NameLabel.Tag = _curPost.ScreenName;
6317 var nameForeColor = SystemColors.ControlText;
6318 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6319 nameForeColor = this._clOWL;
6320 if (_curPost.RetweetedId != null)
6321 nameForeColor = this._clRetweet;
6323 nameForeColor = this._clFav;
6324 NameLabel.ForeColor = nameForeColor;
6326 this.ClearUserPicture();
6328 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6330 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6333 UserPicture.Image = image?.Clone();
6337 UserPicture.ShowErrorImage();
6341 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6344 if (DumpPostClassToolStripMenuItem.Checked)
6346 StringBuilder sb = new StringBuilder(512);
6348 sb.Append("-----Start PostClass Dump<br>");
6349 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
6350 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6351 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
6352 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
6353 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
6354 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
6355 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
6356 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
6357 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
6358 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
6359 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
6360 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
6361 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
6362 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
6363 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
6365 foreach (string nm in _curPost.ReplyToList)
6367 sb.AppendFormat("ReplyToList : {0}<br>", nm);
6370 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
6371 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
6372 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
6373 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
6374 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
6375 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
6376 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
6377 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
6378 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
6379 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
6380 sb.AppendFormat("SearchTabName : {0}<br>", _curPost.RelTabName);
6382 sb.AppendFormat("Media.Count : {0}<br>", _curPost.Media.Count);
6383 if (_curPost.Media.Count > 0)
6385 for (int i = 0; i < _curPost.Media.Count; i++)
6387 var info = _curPost.Media[i];
6388 sb.AppendFormat("Media[{0}].Url : {1}<br>", i, info.Url);
6389 sb.AppendFormat("Media[{0}].VideoUrl : {1}<br>", i, info.VideoUrl ?? "---");
6392 sb.Append("-----End PostClass Dump<br>");
6394 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6398 var loadTasks = new List<Task>();
6400 // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6401 // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6402 if (_curPost.StatusId != oldDisplayPost.StatusId)
6404 using (ControlTransaction.Update(this.PostBrowser))
6406 this.PostBrowser.DocumentText =
6407 this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6409 this.PostBrowser.Document.Window.ScrollTo(0, 0);
6412 this.SplitContainer3.Panel2Collapsed = true;
6414 if (this._cfgCommon.PreviewEnable)
6416 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
6417 oldTokenSource?.Cancel();
6419 var token = this.thumbnailTokenSource.Token;
6420 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
6423 loadTasks.Add(this.AppendQuoteTweetAsync(this._curPost));
6428 await Task.WhenAll(loadTasks);
6430 catch (OperationCanceledException) { }
6434 /// 発言詳細欄のツイートURLを展開する
6436 private async Task AppendQuoteTweetAsync(PostClass post)
6438 var statusIds = post.QuoteStatusIds;
6439 if (statusIds.Length == 0)
6443 var loadingQuoteHtml = statusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText));
6444 var body = post.Text + string.Concat(loadingQuoteHtml);
6446 using (ControlTransaction.Update(this.PostBrowser))
6447 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6450 var quoteHtmls = await Task.WhenAll(statusIds.Select(x => this.CreateQuoteTweetHtml(x)));
6452 // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
6453 if (this._curPost != post || this._curPost.IsDeleted)
6456 body = post.Text + string.Concat(quoteHtmls);
6458 using (ControlTransaction.Update(this.PostBrowser))
6459 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6462 private async Task<string> CreateQuoteTweetHtml(long statusId)
6464 PostClass post = this._statuses[statusId];
6469 post = await Task.Run(() => this.tw.GetStatusApi(false, statusId))
6470 .ConfigureAwait(false);
6472 catch (WebApiException ex)
6474 return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode(ex.Message));
6478 if (!this._statuses.AddQuoteTweet(post))
6479 return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.");
6482 return FormatQuoteTweetHtml(post);
6485 internal static string FormatQuoteTweetHtml(PostClass post)
6487 var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
6488 " — " + WebUtility.HtmlEncode(post.Nickname) +
6489 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
6490 WebUtility.HtmlEncode(post.CreatedAt.ToString());
6492 return FormatQuoteTweetHtml(post.StatusId, innerHtml);
6495 internal static string FormatQuoteTweetHtml(long statusId, string innerHtml)
6497 return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
6498 "<blockquote class=\"quote-tweet\">" + innerHtml + "</blockquote>" +
6503 /// 指定されたHTMLからリンクを除去します
6505 internal static string StripLinkTagHtml(string html)
6507 // a 要素はネストされていない前提の正規表現パターン
6508 return Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1");
6511 private async void MatomeMenuItem_Click(object sender, EventArgs e)
6513 await this.OpenApplicationWebsite();
6516 private async Task OpenApplicationWebsite()
6518 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
6521 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6523 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
6526 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
6528 if (ListTab.SelectedTab != null)
6530 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6532 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6533 if (pnl.Controls["comboSearch"].Focused ||
6534 pnl.Controls["comboLang"].Focused ||
6535 pnl.Controls["buttonSearch"].Focused) return;
6538 if (e.Control || e.Shift || e.Alt)
6539 this._anchorFlag = false;
6542 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
6545 e.SuppressKeyPress = true;
6548 if (asyncTask != null)
6553 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
6555 private void InitializeShortcuts()
6557 this.shortcutCommands = new[]
6559 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6560 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
6561 .FocusedOn(FocusedControl.ListTab)
6562 .Do(() => SendKeys.Send("{DOWN}")),
6564 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
6565 .FocusedOn(FocusedControl.ListTab)
6566 .Do(() => SendKeys.Send("{UP}")),
6568 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
6569 .FocusedOn(FocusedControl.ListTab)
6570 .Do(() => SendKeys.Send("{PGDN}")),
6572 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
6573 .FocusedOn(FocusedControl.ListTab)
6574 .Do(() => SendKeys.Send("{PGUP}")),
6576 ShortcutCommand.Create(Keys.F1)
6577 .Do(() => this.OpenApplicationWebsite()),
6579 ShortcutCommand.Create(Keys.F3)
6580 .Do(() => this.MenuItemSearchNext_Click(null, null)),
6582 ShortcutCommand.Create(Keys.F5)
6583 .Do(() => this.DoRefresh()),
6585 ShortcutCommand.Create(Keys.F6)
6586 .Do(() => this.GetReplyAsync()),
6588 ShortcutCommand.Create(Keys.F7)
6589 .Do(() => this.GetDirectMessagesAsync()),
6591 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
6592 .NotFocusedOn(FocusedControl.StatusText)
6593 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
6595 ShortcutCommand.Create(Keys.G)
6596 .NotFocusedOn(FocusedControl.StatusText)
6597 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
6599 ShortcutCommand.Create(Keys.Right, Keys.N)
6600 .FocusedOn(FocusedControl.ListTab)
6601 .Do(() => this.GoRelPost(forward: true)),
6603 ShortcutCommand.Create(Keys.Left, Keys.P)
6604 .FocusedOn(FocusedControl.ListTab)
6605 .Do(() => this.GoRelPost(forward: false)),
6607 ShortcutCommand.Create(Keys.OemPeriod)
6608 .FocusedOn(FocusedControl.ListTab)
6609 .Do(() => this.GoAnchor()),
6611 ShortcutCommand.Create(Keys.I)
6612 .FocusedOn(FocusedControl.ListTab)
6613 .OnlyWhen(() => this.StatusText.Enabled)
6614 .Do(() => this.StatusText.Focus()),
6616 ShortcutCommand.Create(Keys.Enter)
6617 .FocusedOn(FocusedControl.ListTab)
6618 .Do(() => this.MakeReplyOrDirectStatus()),
6620 ShortcutCommand.Create(Keys.R)
6621 .FocusedOn(FocusedControl.ListTab)
6622 .Do(() => this.DoRefresh()),
6624 ShortcutCommand.Create(Keys.L)
6625 .FocusedOn(FocusedControl.ListTab)
6626 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
6628 ShortcutCommand.Create(Keys.H)
6629 .FocusedOn(FocusedControl.ListTab)
6630 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6632 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6633 .FocusedOn(FocusedControl.ListTab)
6634 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6636 ShortcutCommand.Create(Keys.S)
6637 .FocusedOn(FocusedControl.ListTab)
6638 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6640 ShortcutCommand.Create(Keys.A)
6641 .FocusedOn(FocusedControl.ListTab)
6642 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6644 // ] in_reply_to参照元へ戻る
6645 ShortcutCommand.Create(Keys.Oem4)
6646 .FocusedOn(FocusedControl.ListTab)
6647 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6649 // [ in_reply_toへジャンプ
6650 ShortcutCommand.Create(Keys.Oem6)
6651 .FocusedOn(FocusedControl.ListTab)
6652 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6654 ShortcutCommand.Create(Keys.Escape)
6655 .FocusedOn(FocusedControl.ListTab)
6657 this._anchorFlag = false;
6658 if (ListTab.SelectedTab != null)
6660 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6661 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6663 var relTp = ListTab.SelectedTab;
6664 RemoveSpecifiedTab(relTp.Text, false);
6670 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6671 ShortcutCommand.Create(Keys.Up, Keys.Down)
6672 .FocusedOn(FocusedControl.PostBrowser)
6675 ShortcutCommand.Create(Keys.Control | Keys.R)
6676 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6678 ShortcutCommand.Create(Keys.Control | Keys.D)
6679 .Do(() => this.doStatusDelete()),
6681 ShortcutCommand.Create(Keys.Control | Keys.M)
6682 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6684 ShortcutCommand.Create(Keys.Control | Keys.S)
6685 .Do(() => this.FavoriteChange(FavAdd: true)),
6687 ShortcutCommand.Create(Keys.Control | Keys.I)
6688 .Do(() => this.doRepliedStatusOpen()),
6690 ShortcutCommand.Create(Keys.Control | Keys.Q)
6691 .Do(() => this.doQuoteOfficial()),
6693 ShortcutCommand.Create(Keys.Control | Keys.B)
6694 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6696 ShortcutCommand.Create(Keys.Control | Keys.T)
6697 .Do(() => this.HashManageMenuItem_Click(null, null)),
6699 ShortcutCommand.Create(Keys.Control | Keys.L)
6700 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6702 ShortcutCommand.Create(Keys.Control | Keys.Y)
6703 .NotFocusedOn(FocusedControl.PostBrowser)
6704 .Do(() => this.MultiLineMenuItem_Click(null, null)),
6706 ShortcutCommand.Create(Keys.Control | Keys.F)
6707 .Do(() => this.MenuItemSubSearch_Click(null, null)),
6709 ShortcutCommand.Create(Keys.Control | Keys.U)
6710 .Do(() => this.ShowUserTimeline()),
6712 ShortcutCommand.Create(Keys.Control | Keys.H)
6713 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6715 ShortcutCommand.Create(Keys.Control | Keys.G)
6716 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6718 ShortcutCommand.Create(Keys.Control | Keys.O)
6719 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6721 ShortcutCommand.Create(Keys.Control | Keys.E)
6722 .Do(() => this.OpenURLMenuItem_Click(null, null)),
6724 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6725 .FocusedOn(FocusedControl.ListTab)
6726 .Do(() => this._colorize = true, preventDefault: false),
6728 ShortcutCommand.Create(Keys.Control | Keys.N)
6729 .FocusedOn(FocusedControl.ListTab)
6730 .Do(() => this.GoNextTab(forward: true)),
6732 ShortcutCommand.Create(Keys.Control | Keys.P)
6733 .FocusedOn(FocusedControl.ListTab)
6734 .Do(() => this.GoNextTab(forward: false)),
6736 ShortcutCommand.Create(Keys.Control | Keys.C)
6737 .FocusedOn(FocusedControl.ListTab)
6738 .Do(() => this.CopyStot()),
6740 ShortcutCommand.Create(Keys.Control | Keys.C)
6741 .FocusedOn(FocusedControl.ListTab)
6742 .Do(() => this.CopyStot()),
6744 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6745 ShortcutCommand.Create(Keys.Control | Keys.D1)
6746 .FocusedOn(FocusedControl.ListTab)
6747 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6748 .Do(() => this.ListTab.SelectedIndex = 0),
6750 ShortcutCommand.Create(Keys.Control | Keys.D2)
6751 .FocusedOn(FocusedControl.ListTab)
6752 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6753 .Do(() => this.ListTab.SelectedIndex = 1),
6755 ShortcutCommand.Create(Keys.Control | Keys.D3)
6756 .FocusedOn(FocusedControl.ListTab)
6757 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6758 .Do(() => this.ListTab.SelectedIndex = 2),
6760 ShortcutCommand.Create(Keys.Control | Keys.D4)
6761 .FocusedOn(FocusedControl.ListTab)
6762 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6763 .Do(() => this.ListTab.SelectedIndex = 3),
6765 ShortcutCommand.Create(Keys.Control | Keys.D5)
6766 .FocusedOn(FocusedControl.ListTab)
6767 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6768 .Do(() => this.ListTab.SelectedIndex = 4),
6770 ShortcutCommand.Create(Keys.Control | Keys.D6)
6771 .FocusedOn(FocusedControl.ListTab)
6772 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6773 .Do(() => this.ListTab.SelectedIndex = 5),
6775 ShortcutCommand.Create(Keys.Control | Keys.D7)
6776 .FocusedOn(FocusedControl.ListTab)
6777 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6778 .Do(() => this.ListTab.SelectedIndex = 6),
6780 ShortcutCommand.Create(Keys.Control | Keys.D8)
6781 .FocusedOn(FocusedControl.ListTab)
6782 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6783 .Do(() => this.ListTab.SelectedIndex = 7),
6785 ShortcutCommand.Create(Keys.Control | Keys.D9)
6786 .FocusedOn(FocusedControl.ListTab)
6787 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6789 ShortcutCommand.Create(Keys.Control | Keys.A)
6790 .FocusedOn(FocusedControl.StatusText)
6791 .Do(() => this.StatusText.SelectAll()),
6793 ShortcutCommand.Create(Keys.Control | Keys.V)
6794 .FocusedOn(FocusedControl.StatusText)
6795 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6797 ShortcutCommand.Create(Keys.Control | Keys.Up)
6798 .FocusedOn(FocusedControl.StatusText)
6800 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6802 var inReplyToStatusId = this.inReplyTo?.Item1;
6803 var inReplyToScreenName = this.inReplyTo?.Item2;
6804 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6807 if (_hisIdx < 0) _hisIdx = 0;
6809 var historyItem = this._history[this._hisIdx];
6810 StatusText.Text = historyItem.status;
6811 StatusText.SelectionStart = StatusText.Text.Length;
6812 if (historyItem.inReplyToId != null)
6813 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6815 this.inReplyTo = null;
6818 ShortcutCommand.Create(Keys.Control | Keys.Down)
6819 .FocusedOn(FocusedControl.StatusText)
6821 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6823 var inReplyToStatusId = this.inReplyTo?.Item1;
6824 var inReplyToScreenName = this.inReplyTo?.Item2;
6825 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6828 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6830 var historyItem = this._history[this._hisIdx];
6831 StatusText.Text = historyItem.status;
6832 StatusText.SelectionStart = StatusText.Text.Length;
6833 if (historyItem.inReplyToId != null)
6834 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6836 this.inReplyTo = null;
6839 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6840 .FocusedOn(FocusedControl.StatusText)
6842 if (ListTab.SelectedIndex == 0)
6844 ListTab.SelectedIndex = ListTab.TabCount - 1;
6848 ListTab.SelectedIndex -= 1;
6853 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6854 .FocusedOn(FocusedControl.StatusText)
6856 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6858 ListTab.SelectedIndex = 0;
6862 ListTab.SelectedIndex += 1;
6867 ShortcutCommand.Create(Keys.Control | Keys.Y)
6868 .FocusedOn(FocusedControl.PostBrowser)
6870 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6871 MultiLineMenuItem_Click(null, null);
6874 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6875 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6877 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6878 .Do(() => this.DoRefreshMore()),
6880 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6881 .Do(() => this.GetReplyAsync(loadMore: true)),
6883 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6884 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6886 ShortcutCommand.Create(Keys.Shift | Keys.R)
6887 .NotFocusedOn(FocusedControl.StatusText)
6888 .Do(() => this.DoRefreshMore()),
6890 ShortcutCommand.Create(Keys.Shift | Keys.H)
6891 .FocusedOn(FocusedControl.ListTab)
6892 .Do(() => this.GoTopEnd(GoTop: true)),
6894 ShortcutCommand.Create(Keys.Shift | Keys.L)
6895 .FocusedOn(FocusedControl.ListTab)
6896 .Do(() => this.GoTopEnd(GoTop: false)),
6898 ShortcutCommand.Create(Keys.Shift | Keys.M)
6899 .FocusedOn(FocusedControl.ListTab)
6900 .Do(() => this.GoMiddle()),
6902 ShortcutCommand.Create(Keys.Shift | Keys.G)
6903 .FocusedOn(FocusedControl.ListTab)
6904 .Do(() => this.GoLast()),
6906 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6907 .FocusedOn(FocusedControl.ListTab)
6908 .Do(() => this.MoveMiddle()),
6910 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6911 .FocusedOn(FocusedControl.ListTab)
6912 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6914 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6915 .FocusedOn(FocusedControl.ListTab)
6916 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6918 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6919 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6920 .FocusedOn(FocusedControl.ListTab)
6921 .Do(() => this.GoFav(forward: true)),
6923 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6924 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6925 .FocusedOn(FocusedControl.ListTab)
6926 .Do(() => this.GoFav(forward: false)),
6928 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6929 .FocusedOn(FocusedControl.ListTab)
6930 .Do(() => this.GoBackSelectPostChain()),
6932 ShortcutCommand.Create(Keys.Alt | Keys.R)
6933 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6935 ShortcutCommand.Create(Keys.Alt | Keys.P)
6936 .OnlyWhen(() => this._curPost != null)
6937 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6939 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6940 .Do(() => this.ScrollDownPostBrowser(forward: false)),
6942 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6943 .Do(() => this.ScrollDownPostBrowser(forward: true)),
6945 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6946 .Do(() => this.PageDownPostBrowser(forward: false)),
6948 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6949 .Do(() => this.PageDownPostBrowser(forward: true)),
6951 // 別タブの同じ書き込みへ(ALT+←/→)
6952 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6953 .FocusedOn(FocusedControl.ListTab)
6954 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6956 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6957 .FocusedOn(FocusedControl.ListTab)
6958 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6960 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6961 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6963 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C)
6964 .Do(() => this.CopyIdUri()),
6966 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6967 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6968 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6969 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6971 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6972 .Do(() => this.FavoriteChange(FavAdd: false)),
6974 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6975 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6977 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6978 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6980 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6981 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6983 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6984 .Do(() => this.doMoveToRTHome()),
6986 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6987 .Do(() => this.FavorareMenuItem_Click(null, null)),
6989 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6990 .FocusedOn(FocusedControl.StatusText)
6992 if (_curList != null && _curList.VirtualListSize != 0 &&
6993 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6995 var idx = _curList.SelectedIndices[0] - 1;
6996 SelectListItem(_curList, idx);
6997 _curList.EnsureVisible(idx);
7001 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
7002 .FocusedOn(FocusedControl.StatusText)
7004 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
7005 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
7007 var idx = _curList.SelectedIndices[0] + 1;
7008 SelectListItem(_curList, idx);
7009 _curList.EnsureVisible(idx);
7013 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
7014 .FocusedOn(FocusedControl.StatusText)
7016 if (StatusText.SelectionStart > 0)
7018 int endidx = StatusText.SelectionStart - 1;
7019 string startstr = "";
7020 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
7022 char c = StatusText.Text[i];
7023 if (Char.IsLetterOrDigit(c) || c == '_')
7029 startstr = StatusText.Text.Substring(i + 1, endidx - i);
7030 int cnt = AtIdSupl.ItemCount;
7031 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
7032 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
7036 startstr = StatusText.Text.Substring(i + 1, endidx - i);
7037 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
7047 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
7048 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
7049 .FocusedOn(FocusedControl.ListTab)
7050 .Do(() => this.SetSortColumnByDisplayIndex(0)),
7052 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
7053 .FocusedOn(FocusedControl.ListTab)
7054 .Do(() => this.SetSortColumnByDisplayIndex(1)),
7056 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
7057 .FocusedOn(FocusedControl.ListTab)
7058 .Do(() => this.SetSortColumnByDisplayIndex(2)),
7060 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
7061 .FocusedOn(FocusedControl.ListTab)
7062 .Do(() => this.SetSortColumnByDisplayIndex(3)),
7064 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
7065 .FocusedOn(FocusedControl.ListTab)
7066 .Do(() => this.SetSortColumnByDisplayIndex(4)),
7068 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
7069 .FocusedOn(FocusedControl.ListTab)
7070 .Do(() => this.SetSortColumnByDisplayIndex(5)),
7072 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
7073 .FocusedOn(FocusedControl.ListTab)
7074 .Do(() => this.SetSortColumnByDisplayIndex(6)),
7076 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
7077 .FocusedOn(FocusedControl.ListTab)
7078 .Do(() => this.SetSortColumnByDisplayIndex(7)),
7080 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
7081 .FocusedOn(FocusedControl.ListTab)
7082 .Do(() => this.SetSortLastColumn()),
7084 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
7085 .Do(() => this.FavoritesRetweetOfficial()),
7087 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
7088 .Do(() => this.FavoritesRetweetUnofficial()),
7090 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
7091 .Do(() => this.OpenUserAppointUrl()),
7093 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7094 .FocusedOn(FocusedControl.PostBrowser)
7095 .Do(() => this.doReTweetUnofficial()),
7097 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C)
7098 .FocusedOn(FocusedControl.PostBrowser)
7099 .Do(() => this.CopyUserId()),
7101 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
7102 .OnlyWhen(() => this.ExistCurrentPost)
7103 .Do(() => this.doTranslation(_curPost.TextFromApi)),
7105 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7106 .Do(() => this.doReTweetUnofficial()),
7108 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C)
7109 .Do(() => this.CopyUserId()),
7111 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
7112 .Do(() => this.tweetThumbnail1.ScrollUp()),
7114 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
7115 .Do(() => this.tweetThumbnail1.ScrollDown()),
7117 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
7118 .FocusedOn(FocusedControl.ListTab)
7119 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
7120 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
7124 private bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
7126 // Task を返す非同期処理があれば asyncTask に代入する
7129 // ShortcutCommand に対応しているコマンドはここで処理される
7130 foreach (var command in this.shortcutCommands)
7132 if (command.IsMatch(keyData, focusedOn))
7134 asyncTask = command.RunCommand();
7135 return command.PreventDefault;
7142 private void ScrollDownPostBrowser(bool forward)
7144 var doc = PostBrowser.Document;
7145 if (doc == null) return;
7147 var tags = doc.GetElementsByTagName("html");
7151 tags[0].ScrollTop += this._fntDetail.Height;
7153 tags[0].ScrollTop -= this._fntDetail.Height;
7157 private void PageDownPostBrowser(bool forward)
7159 var doc = PostBrowser.Document;
7160 if (doc == null) return;
7162 var tags = doc.GetElementsByTagName("html");
7166 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7168 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7172 private void GoNextTab(bool forward)
7174 int idx = ListTab.SelectedIndex;
7178 if (idx > ListTab.TabPages.Count - 1) idx = 0;
7183 if (idx < 0) idx = ListTab.TabPages.Count - 1;
7185 ListTab.SelectedIndex = idx;
7188 private void CopyStot()
7191 StringBuilder sb = new StringBuilder();
7192 bool IsProtected = false;
7194 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7195 foreach (int idx in _curList.SelectedIndices)
7197 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7203 if (post.IsDeleted) continue;
7206 if (post.RetweetedId != null)
7207 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7209 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7213 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7218 MessageBox.Show(Properties.Resources.CopyStotText1);
7222 clstr = sb.ToString();
7225 Clipboard.SetDataObject(clstr, false, 5, 100);
7227 catch (Exception ex)
7229 MessageBox.Show(ex.Message);
7234 private void CopyIdUri()
7237 StringBuilder sb = new StringBuilder();
7238 if (this._curTab == null) return;
7239 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7240 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7241 foreach (int idx in _curList.SelectedIndices)
7243 var post = _statuses.Tabs[_curTab.Text][idx];
7244 sb.Append(MyCommon.GetStatusUrl(post));
7245 sb.Append(Environment.NewLine);
7249 clstr = sb.ToString();
7252 Clipboard.SetDataObject(clstr, false, 5, 100);
7254 catch (Exception ex)
7256 MessageBox.Show(ex.Message);
7261 private void GoFav(bool forward)
7263 if (_curList.VirtualListSize == 0) return;
7270 if (_curList.SelectedIndices.Count == 0)
7276 fIdx = _curList.SelectedIndices[0] + 1;
7277 if (fIdx > _curList.VirtualListSize - 1) return;
7279 toIdx = _curList.VirtualListSize;
7284 if (_curList.SelectedIndices.Count == 0)
7286 fIdx = _curList.VirtualListSize - 1;
7290 fIdx = _curList.SelectedIndices[0] - 1;
7291 if (fIdx < 0) return;
7297 for (int idx = fIdx; idx != toIdx; idx += stp)
7299 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
7301 SelectListItem(_curList, idx);
7302 _curList.EnsureVisible(idx);
7308 private void GoSamePostToAnotherTab(bool left)
7310 if (_curList.VirtualListSize == 0) return;
7316 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7317 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7319 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7324 if (ListTab.SelectedIndex == 0)
7330 fIdx = ListTab.SelectedIndex - 1;
7338 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7344 fIdx = ListTab.SelectedIndex + 1;
7346 toIdx = ListTab.TabCount;
7351 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7353 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7354 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7356 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
7358 ListTab.SelectedIndex = tabidx;
7359 SelectListItem(_curList, idx);
7360 _curList.EnsureVisible(idx);
7369 private void GoPost(bool forward)
7371 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7378 fIdx = _curList.SelectedIndices[0] + 1;
7379 if (fIdx > _curList.VirtualListSize - 1) return;
7380 toIdx = _curList.VirtualListSize;
7385 fIdx = _curList.SelectedIndices[0] - 1;
7386 if (fIdx < 0) return;
7392 if (_curPost.RetweetedId == null)
7394 name = _curPost.ScreenName;
7398 name = _curPost.RetweetedBy;
7400 for (int idx = fIdx; idx != toIdx; idx += stp)
7402 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
7404 if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
7406 SelectListItem(_curList, idx);
7407 _curList.EnsureVisible(idx);
7413 if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
7415 SelectListItem(_curList, idx);
7416 _curList.EnsureVisible(idx);
7423 private void GoRelPost(bool forward)
7425 if (_curList.SelectedIndices.Count == 0) return;
7432 fIdx = _curList.SelectedIndices[0] + 1;
7433 if (fIdx > _curList.VirtualListSize - 1) return;
7434 toIdx = _curList.VirtualListSize;
7439 fIdx = _curList.SelectedIndices[0] - 1;
7440 if (fIdx < 0) return;
7447 if (_curPost == null) return;
7448 _anchorPost = _curPost;
7453 if (_anchorPost == null) return;
7456 for (int idx = fIdx; idx != toIdx; idx += stp)
7458 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7459 if (post.ScreenName == _anchorPost.ScreenName ||
7460 post.RetweetedBy == _anchorPost.ScreenName ||
7461 post.ScreenName == _anchorPost.RetweetedBy ||
7462 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7463 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLower()) ||
7464 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLower()) ||
7465 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLower()) ||
7466 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLower()))
7468 SelectListItem(_curList, idx);
7469 _curList.EnsureVisible(idx);
7475 private void GoAnchor()
7477 if (_anchorPost == null) return;
7478 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7479 if (idx == -1) return;
7481 SelectListItem(_curList, idx);
7482 _curList.EnsureVisible(idx);
7485 private void GoTopEnd(bool GoTop)
7487 if (_curList.VirtualListSize == 0)
7495 _item = _curList.GetItemAt(0, 25);
7503 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7505 idx = _curList.VirtualListSize - 1;
7509 SelectListItem(_curList, idx);
7512 private void GoMiddle()
7514 if (_curList.VirtualListSize == 0)
7522 _item = _curList.GetItemAt(0, 0);
7532 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7535 idx2 = _curList.VirtualListSize - 1;
7541 idx3 = (idx1 + idx2) / 2;
7543 SelectListItem(_curList, idx3);
7546 private void GoLast()
7548 if (_curList.VirtualListSize == 0) return;
7550 if (_statuses.SortOrder == SortOrder.Ascending)
7552 SelectListItem(_curList, _curList.VirtualListSize - 1);
7553 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7557 SelectListItem(_curList, 0);
7558 _curList.EnsureVisible(0);
7562 private void MoveTop()
7564 if (_curList.SelectedIndices.Count == 0) return;
7565 int idx = _curList.SelectedIndices[0];
7566 if (_statuses.SortOrder == SortOrder.Ascending)
7568 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7572 _curList.EnsureVisible(0);
7574 _curList.EnsureVisible(idx);
7577 private async Task GoInReplyToPostTree()
7579 if (_curPost == null) return;
7581 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7583 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7587 var post = tw.GetStatusApi(false, _curPost.StatusId);
7589 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7590 _curPost.InReplyToUser = post.InReplyToUser;
7591 _curPost.IsReply = post.IsReply;
7592 this.PurgeListViewItemCache();
7593 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7595 catch (WebApiException ex)
7597 this.StatusLabel.Text = ex.Message;
7601 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7603 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7605 replyChains = new Stack<ReplyChain>();
7607 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7610 string inReplyToTabName;
7611 long inReplyToId = _curPost.InReplyToStatusId.Value;
7612 string inReplyToUser = _curPost.InReplyToUser;
7613 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7615 var inReplyToPosts = from tab in _statuses.Tabs.Values
7616 orderby tab != curTabClass
7617 from post in tab.Posts.Values
7618 where post.StatusId == inReplyToId
7619 let index = tab.IndexOf(post.StatusId)
7621 select new {Tab = tab, Index = index};
7623 var inReplyPost = inReplyToPosts.FirstOrDefault();
7624 if (inReplyPost == null)
7629 post = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value);
7631 catch (WebApiException ex)
7633 this.StatusLabel.Text = ex.Message;
7634 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7639 _statuses.AddPost(post);
7640 _statuses.DistributePosts();
7641 //_statuses.SubmitUpdate(null, null, null, false);
7642 this.RefreshTimeline(false);
7644 inReplyPost = inReplyToPosts.FirstOrDefault();
7645 if (inReplyPost == null)
7647 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7650 inReplyToTabName = inReplyPost.Tab.TabName;
7651 inReplyToIndex = inReplyPost.Index;
7653 inReplyToTabName = inReplyPost.Tab.TabName;
7654 inReplyToIndex = inReplyPost.Index;
7656 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7657 DetailsListView listView = (DetailsListView)tabPage.Tag;
7659 if (_curTab != tabPage)
7661 this.ListTab.SelectTab(tabPage);
7664 this.SelectListItem(listView, inReplyToIndex);
7665 listView.EnsureVisible(inReplyToIndex);
7668 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7670 if (_curPost == null) return;
7672 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7673 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7677 if (_curPost.InReplyToStatusId != null)
7679 var posts = from t in _statuses.Tabs
7680 from p in t.Value.Posts
7681 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7682 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7684 orderby isForward ? indexOf : indexOf * -1
7685 orderby t.Value != curTabClass
7686 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7689 var postList = posts.ToList();
7690 for (int i = postList.Count - 1; i >= 0; i--)
7693 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7695 postList.RemoveAt(index);
7698 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7699 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7700 if (post == null) post = postList.First();
7701 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7702 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7703 SelectListItem(listView, post.Index);
7704 listView.EnsureVisible(post.Index);
7706 catch (InvalidOperationException)
7714 if (replyChains == null || replyChains.Count < 1)
7716 var posts = from t in _statuses.Tabs
7717 from p in t.Value.Posts
7718 where p.Value.InReplyToStatusId == _curPost.StatusId
7719 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7722 orderby t.Value != curTabClass
7723 select new {Tab = t.Value, Index = indexOf};
7726 var post = posts.First();
7727 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7728 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7729 SelectListItem(listView, post.Index);
7730 listView.EnsureVisible(post.Index);
7732 catch (InvalidOperationException)
7739 ReplyChain chainHead = replyChains.Pop();
7740 if (chainHead.InReplyToId == _curPost.StatusId)
7742 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7751 ListTab.SelectTab(chainHead.OriginalTab);
7757 SelectListItem(_curList, idx);
7758 _curList.EnsureVisible(idx);
7764 this.GoBackInReplyToPostTree(parallel);
7770 private void GoBackSelectPostChain()
7772 if (this.selectPostChains.Count > 1)
7781 this.selectPostChains.Pop();
7782 var tabPostPair = this.selectPostChains.Peek();
7784 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7786 if (tabPostPair.Item2 != null)
7788 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7789 if (idx == -1) continue; //該当ポストが存在しないので無視
7792 tp = tabPostPair.Item1;
7794 this.selectPostChains.Pop();
7796 catch (InvalidOperationException)
7802 while (this.selectPostChains.Count > 1);
7807 //履歴が残り1つであればクリアしておく
7808 if (this.selectPostChains.Count == 1)
7809 this.selectPostChains.Clear();
7813 DetailsListView lst = (DetailsListView)tp.Tag;
7814 this.ListTab.SelectedTab = tp;
7817 SelectListItem(lst, idx);
7818 lst.EnsureVisible(idx);
7824 private void PushSelectPostChain()
7826 int count = this.selectPostChains.Count;
7829 var p = this.selectPostChains.Peek();
7830 if (p.Item1 == this._curTab)
7832 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7833 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7836 if (count >= 2500) TrimPostChain();
7837 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7840 private void TrimPostChain()
7842 if (this.selectPostChains.Count <= 2000) return;
7843 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7844 for (int i = 0; i < 2000; i++)
7846 p.Push(this.selectPostChains.Pop());
7848 this.selectPostChains.Clear();
7849 for (int i = 0; i < 2000; i++)
7851 this.selectPostChains.Push(p.Pop());
7855 private bool GoStatus(long statusId)
7857 if (statusId == 0) return false;
7858 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7860 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7862 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7863 ListTab.SelectedIndex = tabidx;
7864 SelectListItem(_curList, idx);
7865 _curList.EnsureVisible(idx);
7872 private bool GoDirectMessage(long statusId)
7874 if (statusId == 0) return false;
7875 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7877 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7879 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7880 ListTab.SelectedIndex = tabidx;
7881 SelectListItem(_curList, idx);
7882 _curList.EnsureVisible(idx);
7889 private void MyList_MouseClick(object sender, MouseEventArgs e)
7891 _anchorFlag = false;
7894 private void StatusText_Enter(object sender, EventArgs e)
7896 // フォーカスの戻り先を StatusText に設定
7897 this.Tag = StatusText;
7898 StatusText.BackColor = _clInputBackcolor;
7901 public Color InputBackColor
7903 get { return _clInputBackcolor; }
7904 set { _clInputBackcolor = value; }
7907 private void StatusText_Leave(object sender, EventArgs e)
7909 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7910 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7911 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7914 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7917 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7920 e.SuppressKeyPress = true;
7923 this.StatusText_TextChanged(null, null);
7925 if (asyncTask != null)
7929 private void SaveConfigsAll(bool ifModified)
7933 SaveConfigsCommon();
7940 if (_modifySettingCommon) SaveConfigsCommon();
7941 if (_modifySettingLocal) SaveConfigsLocal();
7942 if (_modifySettingAtId) SaveConfigsAtId();
7946 private void SaveConfigsAtId()
7948 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7950 _modifySettingAtId = false;
7951 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7955 private void SaveConfigsCommon()
7957 if (_ignoreConfigSave) return;
7959 _modifySettingCommon = false;
7962 _cfgCommon.UserName = tw.Username;
7963 _cfgCommon.UserId = tw.UserId;
7964 _cfgCommon.Password = tw.Password;
7965 _cfgCommon.Token = tw.AccessToken;
7966 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7968 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7969 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7971 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7974 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7975 switch (_statuses.SortMode)
7977 case ComparerMode.Nickname: //ニックネーム
7978 _cfgCommon.SortColumn = 1;
7980 case ComparerMode.Data: //本文
7981 _cfgCommon.SortColumn = 2;
7983 case ComparerMode.Id: //時刻=発言Id
7984 _cfgCommon.SortColumn = 3;
7986 case ComparerMode.Name: //名前
7987 _cfgCommon.SortColumn = 4;
7989 case ComparerMode.Source: //Source
7990 _cfgCommon.SortColumn = 7;
7994 _cfgCommon.HashTags = HashMgr.HashHistories;
7995 if (HashMgr.IsPermanent)
7997 _cfgCommon.HashSelected = HashMgr.UseHash;
8001 _cfgCommon.HashSelected = "";
8003 _cfgCommon.HashIsHead = HashMgr.IsHead;
8004 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
8005 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
8006 if (ToolStripFocusLockMenuItem != null &&
8007 ToolStripFocusLockMenuItem.IsDisposed == false)
8009 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
8011 _cfgCommon.TrackWord = tw.TrackWord;
8012 _cfgCommon.AllAtReply = tw.AllAtReply;
8013 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
8014 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
8020 private void SaveConfigsLocal()
8022 if (_ignoreConfigSave) return;
8025 _modifySettingLocal = false;
8026 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
8027 _cfgLocal.FormSize = _mySize;
8028 _cfgLocal.FormLocation = _myLoc;
8029 _cfgLocal.SplitterDistance = _mySpDis;
8030 _cfgLocal.PreviewDistance = _mySpDis3;
8031 _cfgLocal.StatusMultiline = StatusText.Multiline;
8032 _cfgLocal.StatusTextHeight = _mySpDis2;
8034 _cfgLocal.FontUnread = _fntUnread;
8035 _cfgLocal.ColorUnread = _clUnread;
8036 _cfgLocal.FontRead = _fntReaded;
8037 _cfgLocal.ColorRead = _clReaded;
8038 _cfgLocal.FontDetail = _fntDetail;
8039 _cfgLocal.ColorDetail = _clDetail;
8040 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
8041 _cfgLocal.ColorDetailLink = _clDetailLink;
8042 _cfgLocal.ColorFav = _clFav;
8043 _cfgLocal.ColorOWL = _clOWL;
8044 _cfgLocal.ColorRetweet = _clRetweet;
8045 _cfgLocal.ColorSelf = _clSelf;
8046 _cfgLocal.ColorAtSelf = _clAtSelf;
8047 _cfgLocal.ColorTarget = _clTarget;
8048 _cfgLocal.ColorAtTarget = _clAtTarget;
8049 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
8050 _cfgLocal.ColorAtTo = _clAtTo;
8051 _cfgLocal.ColorListBackcolor = _clListBackcolor;
8052 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
8053 _cfgLocal.ColorInputFont = _clInputFont;
8054 _cfgLocal.FontInputFont = _fntInputFont;
8056 if (_ignoreConfigSave) return;
8061 private void SaveConfigsTabs()
8063 SettingTabs tabSetting = new SettingTabs();
8064 for (int i = 0; i < ListTab.TabPages.Count; i++)
8066 var tab = _statuses.Tabs[ListTab.TabPages[i].Text];
8067 if (tab.TabType != MyCommon.TabUsageType.Related && tab.TabType != MyCommon.TabUsageType.SearchResults)
8068 tabSetting.Tabs.Add(tab);
8070 tabSetting.Tabs.Add(this._statuses.GetTabByType(MyCommon.TabUsageType.Mute));
8074 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
8077 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
8078 if (ret != DialogResult.OK)
8081 var match = Twitter.StatusUrlRegex.Match(inputText);
8084 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
8085 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8091 var statusId = long.Parse(match.Groups["StatusId"].Value);
8092 await this.OpenRelatedTab(statusId);
8094 catch (TabException ex)
8096 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8100 private void SaveLogMenuItem_Click(object sender, EventArgs e)
8102 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8103 Properties.Resources.SaveLogMenuItem_ClickText2,
8104 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8105 if (rslt == DialogResult.Cancel) return;
8107 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8108 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8109 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8110 SaveFileDialog1.FilterIndex = 0;
8111 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8112 SaveFileDialog1.RestoreDirectory = true;
8114 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8116 if (!SaveFileDialog1.ValidateNames) return;
8117 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8119 if (rslt == DialogResult.Yes)
8122 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8124 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8125 string protect = "";
8126 if (post.IsProtect) protect = "Protect";
8127 sw.WriteLine(post.Nickname + "\t" +
8128 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8129 post.CreatedAt.ToString() + "\t" +
8130 post.ScreenName + "\t" +
8131 post.StatusId.ToString() + "\t" +
8132 post.ImageUrl + "\t" +
8133 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8139 foreach (int idx in _curList.SelectedIndices)
8141 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8142 string protect = "";
8143 if (post.IsProtect) protect = "Protect";
8144 sw.WriteLine(post.Nickname + "\t" +
8145 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8146 post.CreatedAt.ToString() + "\t" +
8147 post.ScreenName + "\t" +
8148 post.StatusId.ToString() + "\t" +
8149 post.ImageUrl + "\t" +
8150 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8156 this.TopMost = this._cfgCommon.AlwaysTop;
8159 private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8162 bool KeyRes = CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out asyncTask);
8165 e.IsInputKey = true;
8169 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
8171 var shortcut = (Shortcut)e.KeyData;
8174 case Shortcut.CtrlA:
8175 case Shortcut.CtrlC:
8176 case Shortcut.CtrlIns:
8180 // その他のショートカットキーは無効にする
8181 e.IsInputKey = true;
8187 if (asyncTask != null)
8190 public bool TabRename(ref string tabName)
8193 string newTabText = null;
8194 using (InputTabName inputName = new InputTabName())
8196 inputName.TabName = tabName;
8197 inputName.ShowDialog();
8198 if (inputName.DialogResult == DialogResult.Cancel) return false;
8199 newTabText = inputName.TabName;
8201 this.TopMost = this._cfgCommon.AlwaysTop;
8202 if (!string.IsNullOrEmpty(newTabText))
8205 for (int i = 0; i < ListTab.TabCount; i++)
8207 if (ListTab.TabPages[i].Text == newTabText)
8209 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8210 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8215 for (int i = 0; i < ListTab.TabCount; i++)
8217 if (ListTab.TabPages[i].Text == tabName)
8219 ListTab.TabPages[i].Text = newTabText;
8223 _statuses.RenameTab(tabName, newTabText);
8225 SaveConfigsCommon();
8227 _rclickTabName = newTabText;
8228 tabName = newTabText;
8237 private void ListTab_MouseClick(object sender, MouseEventArgs e)
8239 if (e.Button == MouseButtons.Middle)
8241 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8243 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8245 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8246 this.SaveConfigsTabs();
8253 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8255 string tn = ListTab.SelectedTab.Text;
8259 private void ListTab_MouseDown(object sender, MouseEventArgs e)
8261 if (this._cfgCommon.TabMouseLock) return;
8262 Point cpos = new Point(e.X, e.Y);
8263 if (e.Button == MouseButtons.Left)
8265 for (int i = 0; i < ListTab.TabPages.Count; i++)
8267 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8270 _tabMouseDownPoint = e.Location;
8281 private void ListTab_DragEnter(object sender, DragEventArgs e)
8283 if (e.Data.GetDataPresent(typeof(TabPage)))
8284 e.Effect = DragDropEffects.Move;
8286 e.Effect = DragDropEffects.None;
8289 private void ListTab_DragDrop(object sender, DragEventArgs e)
8291 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8296 Point cpos = new Point(e.X, e.Y);
8297 Point spos = ListTab.PointToClient(cpos);
8299 for (i = 0; i < ListTab.TabPages.Count; i++)
8301 Rectangle rect = ListTab.GetTabRect(i);
8302 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8303 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8305 tn = ListTab.TabPages[i].Text;
8306 if (spos.X <= (rect.Left + rect.Right) / 2)
8315 //タブのないところにドロップ->最後尾へ移動
8316 if (string.IsNullOrEmpty(tn))
8318 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8320 i = ListTab.TabPages.Count - 1;
8323 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8324 if (tp.Text == tn) return;
8326 ReOrderTab(tp.Text, tn, bef);
8329 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8331 var baseIndex = this.GetTabPageIndex(baseTabText);
8332 if (baseIndex == -1)
8335 var targetIndex = this.GetTabPageIndex(targetTabText);
8336 if (targetIndex == -1)
8339 using (ControlTransaction.Layout(this.ListTab))
8341 var mTp = this.ListTab.TabPages[targetIndex];
8342 this.ListTab.TabPages.Remove(mTp);
8344 if (targetIndex < baseIndex)
8347 if (isBeforeBaseTab)
8348 ListTab.TabPages.Insert(baseIndex, mTp);
8350 ListTab.TabPages.Insert(baseIndex + 1, mTp);
8356 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8358 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8359 //isReply:true=@,false=DM
8360 if (!StatusText.Enabled) return;
8361 if (_curList == null) return;
8362 if (_curTab == null) return;
8363 if (!this.ExistCurrentPost) return;
8365 // 複数あてリプライはReplyではなく通常ポスト
8366 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8367 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8368 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8370 if (_curList.SelectedIndices.Count > 0)
8373 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8376 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8379 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8380 StatusText.SelectionStart = StatusText.Text.Length;
8382 this.inReplyTo = null;
8385 if (string.IsNullOrEmpty(StatusText.Text))
8389 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8390 StatusText.Text = "@" + _curPost.ScreenName + " ";
8392 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8393 var inReplyToScreenName = this._curPost.ScreenName;
8394 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8402 //1件選んでEnter or DoubleClick
8403 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8405 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
8408 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8409 var inReplyToScreenName = this._curPost.ScreenName;
8410 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8414 if (!StatusText.Text.StartsWith("@"))
8417 if (StatusText.Text.StartsWith(". "))
8420 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8421 this.inReplyTo = null;
8426 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8427 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8428 var inReplyToScreenName = this._curPost.ScreenName;
8429 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8436 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8437 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8438 this.inReplyTo = null;
8443 //1件選んでCtrl-Rの場合(返信先操作せず)
8444 int sidx = StatusText.SelectionStart;
8445 string id = "@" + _curPost.ScreenName + " ";
8448 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8453 StatusText.Text = StatusText.Text.Insert(sidx, id);
8455 //if (StatusText.Text.StartsWith("@"))
8458 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8459 // sidx += 5 + _curPost.ScreenName.Length;
8464 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8465 // sidx += 3 + _curPost.ScreenName.Length;
8467 StatusText.SelectionStart = sidx;
8470 //_reply_to_name = null;
8478 if (!isAuto && !isReply) return;
8480 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8484 //Enter or DoubleClick
8486 string sTxt = StatusText.Text;
8487 if (!sTxt.StartsWith(". "))
8490 this.inReplyTo = null;
8492 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8494 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8495 if (!sTxt.Contains("@" + post.ScreenName + " "))
8497 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8498 //sTxt = "@" + post.ScreenName + " " + sTxt;
8501 StatusText.Text = sTxt;
8506 if (_curList.SelectedIndices.Count > 1)
8511 int sidx = StatusText.SelectionStart;
8512 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8514 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8515 if (!ids.Contains("@" + post.ScreenName + " ") &&
8516 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8518 ids += "@" + post.ScreenName + " ";
8522 foreach (string nm in post.ReplyToList)
8524 if (!ids.Contains("@" + nm + " ") &&
8525 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8527 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8529 ids += "@" + m.Result("${id}") + " ";
8531 ids += "@" + nm + " ";
8536 if (ids.Length == 0) return;
8537 if (!StatusText.Text.StartsWith(". "))
8539 StatusText.Text = ". " + StatusText.Text;
8541 this.inReplyTo = null;
8545 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8550 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8552 //if (StatusText.Text.StartsWith("@"))
8554 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8555 // sidx += 2 + ids.Length;
8559 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8560 // sidx += 1 + ids.Length;
8562 StatusText.SelectionStart = sidx;
8568 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8571 int sidx = StatusText.SelectionStart;
8572 PostClass post = _curPost;
8573 if (!ids.Contains("@" + post.ScreenName + " ") &&
8574 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8576 ids += "@" + post.ScreenName + " ";
8578 foreach (string nm in post.ReplyToList)
8580 if (!ids.Contains("@" + nm + " ") &&
8581 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8583 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8585 ids += "@" + m.Result("${id}") + " ";
8587 ids += "@" + nm + " ";
8590 if (!string.IsNullOrEmpty(post.RetweetedBy))
8592 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8593 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8595 ids += "@" + post.RetweetedBy + " ";
8598 if (ids.Length == 0) return;
8599 if (string.IsNullOrEmpty(StatusText.Text))
8602 StatusText.Text = ids;
8603 StatusText.SelectionStart = ids.Length;
8606 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8607 var inReplyToScreenName = this._curPost.ScreenName;
8608 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8614 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8619 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8621 StatusText.SelectionStart = sidx;
8627 StatusText.SelectionStart = StatusText.Text.Length;
8632 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8637 private static int iconCnt = 0;
8638 private static int blinkCnt = 0;
8639 private static bool blink = false;
8640 private static bool idle = false;
8642 private async Task RefreshTasktrayIcon(bool forceRefresh)
8645 await this.Colorize();
8647 if (!TimerRefreshIcon.Enabled) return;
8648 //Static usCheckCnt As int = 0
8650 //Static iconDlListTopItem As ListViewItem = null
8652 if (forceRefresh) idle = false;
8654 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8655 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8657 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8659 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8665 //if (usCheckCnt > 300) //1min
8668 // if (!this.IsReceivedUserStream)
8670 // TraceOut("ReconnectUserStream");
8671 // tw.ReconnectUserStream();
8675 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8677 if (iconCnt >= this.NIconRefresh.Length)
8685 SaveConfigsAll(true);
8690 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8692 _myStatusError = false;
8696 TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8697 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8699 if (blinkCnt > 0) return;
8701 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8703 NotifyIcon1.Icon = ReplyIcon;
8707 NotifyIcon1.Icon = ReplyIconBlink;
8715 //優先度:エラー→オフライン→アイドル
8719 NotifyIcon1.Icon = NIconAtRed;
8722 if (_myStatusOnline)
8724 NotifyIcon1.Icon = NIconAt;
8728 NotifyIcon1.Icon = NIconAtSmoke;
8732 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8735 await this.RefreshTasktrayIcon(false);
8738 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8740 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8741 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8743 if (ListTab != null && ListTab.SelectedTab != null)
8744 _rclickTabName = ListTab.SelectedTab.Text;
8749 if (_statuses == null) return;
8750 if (_statuses.Tabs == null) return;
8752 TabClass tb = _statuses.Tabs[_rclickTabName];
8753 if (tb == null) return;
8755 NotifyDispMenuItem.Checked = tb.Notify;
8756 this.NotifyTbMenuItem.Checked = tb.Notify;
8758 soundfileListup = true;
8759 SoundFileComboBox.Items.Clear();
8760 this.SoundFileTbComboBox.Items.Clear();
8761 SoundFileComboBox.Items.Add("");
8762 this.SoundFileTbComboBox.Items.Add("");
8763 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8764 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8766 oDir = oDir.GetDirectories("Sounds")[0];
8768 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8770 SoundFileComboBox.Items.Add(oFile.Name);
8771 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8773 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8774 if (idx == -1) idx = 0;
8775 SoundFileComboBox.SelectedIndex = idx;
8776 this.SoundFileTbComboBox.SelectedIndex = idx;
8777 soundfileListup = false;
8778 UreadManageMenuItem.Checked = tb.UnreadManage;
8779 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8781 TabMenuControl(_rclickTabName);
8784 private void TabMenuControl(string tabName)
8786 var tabInfo = _statuses.GetTabByName(tabName);
8788 this.FilterEditMenuItem.Enabled = true;
8789 this.EditRuleTbMenuItem.Enabled = true;
8791 if (tabInfo.IsDefaultTabType)
8793 this.ProtectTabMenuItem.Enabled = false;
8794 this.ProtectTbMenuItem.Enabled = false;
8798 this.ProtectTabMenuItem.Enabled = true;
8799 this.ProtectTbMenuItem.Enabled = true;
8802 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8804 this.ProtectTabMenuItem.Checked = true;
8805 this.ProtectTbMenuItem.Checked = true;
8806 this.DeleteTabMenuItem.Enabled = false;
8807 this.DeleteTbMenuItem.Enabled = false;
8811 this.ProtectTabMenuItem.Checked = false;
8812 this.ProtectTbMenuItem.Checked = false;
8813 this.DeleteTabMenuItem.Enabled = true;
8814 this.DeleteTbMenuItem.Enabled = true;
8818 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8820 var checkState = ((ToolStripMenuItem)sender).Checked;
8823 this.ProtectTbMenuItem.Checked = checkState;
8824 this.ProtectTabMenuItem.Checked = checkState;
8827 this.DeleteTabMenuItem.Enabled = !checkState;
8828 this.DeleteTbMenuItem.Enabled = !checkState;
8830 if (string.IsNullOrEmpty(_rclickTabName)) return;
8831 _statuses.Tabs[_rclickTabName].Protected = checkState;
8836 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8838 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8839 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8841 if (string.IsNullOrEmpty(_rclickTabName)) return;
8842 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8847 public void ChangeTabUnreadManage(string tabName, bool isManage)
8849 var idx = this.GetTabPageIndex(tabName);
8853 _statuses.Tabs[tabName].UnreadManage = isManage;
8854 if (this._cfgCommon.TabIconDisp)
8856 if (_statuses.Tabs[tabName].UnreadCount > 0)
8857 ListTab.TabPages[idx].ImageIndex = 0;
8859 ListTab.TabPages[idx].ImageIndex = -1;
8862 if (_curTab.Text == tabName)
8864 this.PurgeListViewItemCache();
8868 SetMainWindowTitle();
8869 SetStatusLabelUrl();
8870 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8873 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8875 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8876 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8878 if (string.IsNullOrEmpty(_rclickTabName)) return;
8880 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8885 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8887 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8889 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8894 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8896 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8898 RemoveSpecifiedTab(_rclickTabName, true);
8902 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8904 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8906 using (var fltDialog = new FilterDialog())
8908 fltDialog.Owner = this;
8909 fltDialog.SetCurrent(_rclickTabName);
8910 fltDialog.ShowDialog(this);
8912 this.TopMost = this._cfgCommon.AlwaysTop;
8914 this.ApplyPostFilters();
8918 private void AddTabMenuItem_Click(object sender, EventArgs e)
8920 string tabName = null;
8921 MyCommon.TabUsageType tabUsage;
8922 using (InputTabName inputName = new InputTabName())
8924 inputName.TabName = _statuses.GetUniqueTabName();
8925 inputName.IsShowUsage = true;
8926 inputName.ShowDialog();
8927 if (inputName.DialogResult == DialogResult.Cancel) return;
8928 tabName = inputName.TabName;
8929 tabUsage = inputName.Usage;
8931 this.TopMost = this._cfgCommon.AlwaysTop;
8932 if (!string.IsNullOrEmpty(tabName))
8935 ListElement list = null;
8936 if (tabUsage == MyCommon.TabUsageType.Lists)
8938 using (ListAvailable listAvail = new ListAvailable())
8940 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8941 if (listAvail.SelectedList == null) return;
8942 list = listAvail.SelectedList;
8945 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8947 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8948 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8954 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8956 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8957 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8959 if (tabUsage == MyCommon.TabUsageType.Lists)
8961 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8962 var tab = this._statuses.Tabs[this._curTab.Text];
8963 this.GetListTimelineAsync(tab);
8969 private void TabMenuItem_Click(object sender, EventArgs e)
8971 using (var fltDialog = new FilterDialog())
8973 fltDialog.Owner = this;
8976 foreach (int idx in _curList.SelectedIndices)
8980 if (!SelectTab(out tabName)) return;
8982 fltDialog.SetCurrent(tabName);
8983 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8985 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8989 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8991 fltDialog.ShowDialog(this);
8992 this.TopMost = this._cfgCommon.AlwaysTop;
8996 this.ApplyPostFilters();
8998 if (this.ListTab.SelectedTab != null &&
8999 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
9001 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
9005 protected override bool ProcessDialogKey(Keys keyData)
9007 //TextBox1でEnterを押してもビープ音が鳴らないようにする
9008 if ((keyData & Keys.KeyCode) == Keys.Enter)
9010 if (StatusText.Focused)
9012 bool _NewLine = false;
9015 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
9017 if (StatusText.Multiline)
9019 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
9021 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
9025 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
9029 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
9031 if (StatusText.Multiline)
9033 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
9035 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
9039 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
9045 if (StatusText.Multiline)
9047 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
9049 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
9050 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
9054 if (((keyData & Keys.Shift) == Keys.Shift) ||
9055 (((keyData & Keys.Control) != Keys.Control) &&
9056 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
9062 int pos1 = StatusText.SelectionStart;
9063 if (StatusText.SelectionLength > 0)
9065 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
9067 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
9068 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
9073 PostButton_Click(null, null);
9077 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
9078 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
9079 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
9081 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
9086 return base.ProcessDialogKey(keyData);
9089 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9091 MakeReplyOrDirectStatus(false, true, true);
9094 private void IDRuleMenuItem_Click(object sender, EventArgs e)
9099 if (_curList.SelectedIndices.Count == 0) return;
9102 if (!SelectTab(out tabName)) return;
9104 var tab = this._statuses.Tabs[tabName];
9108 if (tab.TabType != MyCommon.TabUsageType.Mute)
9110 this.MoveOrCopy(out mv, out mk);
9114 // ミュートタブでは常に MoveMatches を true にする
9119 List<string> ids = new List<string>();
9120 foreach (int idx in _curList.SelectedIndices)
9122 PostClass post = _statuses.Tabs[_curTab.Text][idx];
9123 if (!ids.Contains(post.ScreenName))
9125 PostFilterRule fc = new PostFilterRule();
9126 ids.Add(post.ScreenName);
9127 if (post.RetweetedId == null)
9129 fc.FilterName = post.ScreenName;
9133 fc.FilterName = post.RetweetedBy;
9135 fc.UseNameField = true;
9136 fc.MoveMatches = mv;
9137 fc.MarkMatches = mk;
9138 fc.UseRegex = false;
9139 fc.FilterByUrl = false;
9145 List<string> atids = new List<string>();
9146 foreach (string id in ids)
9148 atids.Add("@" + id);
9150 int cnt = AtIdSupl.ItemCount;
9151 AtIdSupl.AddRangeItem(atids.ToArray());
9152 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
9155 this.ApplyPostFilters();
9159 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
9161 if (this._curList.SelectedIndices.Count == 0)
9164 // タブ選択ダイアログを表示(or追加)
9166 if (!this.SelectTab(out tabName))
9169 var currentTab = this._statuses.Tabs[this._curTab.Text];
9170 var filterTab = this._statuses.Tabs[tabName];
9174 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
9176 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
9177 this.MoveOrCopy(out mv, out mk);
9181 // ミュートタブでは常に MoveMatches を true にする
9186 // 振り分けルールに追加するSource
9187 var sources = new HashSet<string>();
9189 foreach (var idx in this._curList.SelectedIndices.Cast<int>())
9191 var post = currentTab[idx];
9192 var filterSource = post.Source;
9194 if (sources.Add(filterSource))
9196 var filter = new PostFilterRule
9198 FilterSource = filterSource,
9202 FilterByUrl = false,
9204 filterTab.AddFilter(filter);
9208 this.ApplyPostFilters();
9209 this.SaveConfigsTabs();
9212 private bool SelectTab(out string tabName)
9219 using (var dialog = new TabsDialog(_statuses))
9221 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9223 var selectedTab = dialog.SelectedTab;
9224 tabName = selectedTab == null ? null : selectedTab.TabName;
9227 ListTab.SelectedTab.Focus();
9229 if (tabName == null)
9231 using (InputTabName inputName = new InputTabName())
9233 inputName.TabName = _statuses.GetUniqueTabName();
9234 inputName.ShowDialog();
9235 if (inputName.DialogResult == DialogResult.Cancel) return false;
9236 tabName = inputName.TabName;
9238 this.TopMost = this._cfgCommon.AlwaysTop;
9239 if (!string.IsNullOrEmpty(tabName))
9241 if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9243 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9244 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9262 private void MoveOrCopy(out bool move, out bool mark)
9266 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9267 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9275 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9276 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9286 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9291 private void CopyURLMenuItem_Click(object sender, EventArgs e)
9296 private void SelectAllMenuItem_Click(object sender, EventArgs e)
9298 if (StatusText.Focused)
9301 StatusText.SelectAll();
9305 // ListView上でのCtrl+A
9306 NativeMethods.SelectAllItems(this._curList);
9310 private void MoveMiddle()
9316 if (_curList.SelectedIndices.Count == 0) return;
9318 int idx = _curList.SelectedIndices[0];
9320 _item = _curList.GetItemAt(0, 25);
9326 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9328 idx2 = _curList.VirtualListSize - 1;
9332 idx -= Math.Abs(idx1 - idx2) / 2;
9333 if (idx < 0) idx = 0;
9335 _curList.EnsureVisible(_curList.VirtualListSize - 1);
9336 _curList.EnsureVisible(idx);
9339 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
9341 var linkElements = this.PostBrowser.Document.Links.Cast<HtmlElement>()
9342 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
9345 if (linkElements.Length > 0)
9347 UrlDialog.ClearUrl();
9349 string openUrlStr = "";
9351 if (linkElements.Length == 1)
9353 // ツイートに含まれる URL が 1 つのみの場合
9354 // => OpenURL ダイアログを表示せずにリンクを開く
9359 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
9361 catch (ArgumentException)
9370 if (string.IsNullOrEmpty(urlStr)) return;
9371 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9373 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
9374 await this.OpenUriAsync(new Uri(openUrlStr));
9378 // ツイートに含まれる URL が複数ある場合
9379 // => OpenURL を表示しユーザーが選択したリンクを開く
9381 foreach (var linkElm in linkElements)
9384 string linkText = "";
9388 urlStr = linkElm.GetAttribute("title");
9389 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9390 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9391 linkText = linkElm.InnerText;
9393 catch (ArgumentException)
9402 if (string.IsNullOrEmpty(urlStr)) continue;
9403 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9407 if (UrlDialog.ShowDialog() == DialogResult.OK)
9409 openUrlStr = UrlDialog.SelectedUrl;
9411 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
9412 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
9419 this.TopMost = this._cfgCommon.AlwaysTop;
9424 private void ClearTabMenuItem_Click(object sender, EventArgs e)
9426 if (string.IsNullOrEmpty(_rclickTabName)) return;
9427 ClearTab(_rclickTabName, true);
9430 private void ClearTab(string tabName, bool showWarning)
9434 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9435 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9441 _statuses.ClearTabIds(tabName);
9442 if (ListTab.SelectedTab.Text == tabName)
9445 _anchorFlag = false;
9446 this.PurgeListViewItemCache();
9450 foreach (TabPage tb in ListTab.TabPages)
9452 if (tb.Text == tabName)
9455 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9459 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9461 SetMainWindowTitle();
9462 SetStatusLabelUrl();
9465 private static long followers = 0;
9467 private void SetMainWindowTitle()
9470 StringBuilder ttl = new StringBuilder(256);
9473 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9474 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9475 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9476 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9478 foreach (var tab in _statuses.Tabs.Values)
9480 ur += tab.UnreadCount;
9485 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9486 ttl.Append(Application.ProductName);
9488 switch (this._cfgCommon.DispLatestPost)
9490 case MyCommon.DispTitleEnum.Ver:
9491 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9493 case MyCommon.DispTitleEnum.Post:
9494 if (_history != null && _history.Count > 1)
9495 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9497 case MyCommon.DispTitleEnum.UnreadRepCount:
9498 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9500 case MyCommon.DispTitleEnum.UnreadAllCount:
9501 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9503 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9504 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9506 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9507 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9509 case MyCommon.DispTitleEnum.OwnStatus:
9510 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9511 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9517 this.Text = ttl.ToString();
9519 catch (AccessViolationException)
9521 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9525 private string GetStatusLabelText()
9528 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9529 if (_statuses == null) return "";
9530 TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9531 TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9532 if (tbRep == null || tbDm == null) return "";
9533 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9538 StringBuilder slbl = new StringBuilder(256);
9541 foreach (var tab in _statuses.Tabs.Values)
9543 ur += tab.UnreadCount;
9545 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9547 tur = tab.UnreadCount;
9558 UnreadAtCounter = urat;
9560 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9561 if (this._cfgCommon.TimelinePeriod == 0)
9563 slbl.Append(Properties.Resources.SetStatusLabelText2);
9567 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9569 return slbl.ToString();
9572 private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9576 if (this.InvokeRequired && !this.IsDisposed)
9578 this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9582 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9583 SetApiStatusLabel(endpointName);
9586 catch (ObjectDisposedException)
9590 catch (InvalidOperationException)
9596 private void SetApiStatusLabel(string endpointName = null)
9598 if (_curTab == null)
9600 this.toolStripApiGauge.ApiEndpoint = null;
9604 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9606 if (endpointName == null)
9611 case MyCommon.TabUsageType.Home:
9612 case MyCommon.TabUsageType.UserDefined:
9613 endpointName = "/statuses/home_timeline";
9616 case MyCommon.TabUsageType.Mentions:
9617 endpointName = "/statuses/mentions_timeline";
9620 case MyCommon.TabUsageType.Favorites:
9621 endpointName = "/favorites/list";
9624 case MyCommon.TabUsageType.DirectMessage:
9625 endpointName = "/direct_messages";
9628 case MyCommon.TabUsageType.UserTimeline:
9629 endpointName = "/statuses/user_timeline";
9632 case MyCommon.TabUsageType.Lists:
9633 endpointName = "/lists/statuses";
9636 case MyCommon.TabUsageType.PublicSearch:
9637 endpointName = "/search/tweets";
9640 case MyCommon.TabUsageType.Related:
9641 endpointName = "/statuses/show/:id";
9648 this.toolStripApiGauge.ApiEndpoint = endpointName;
9652 // 表示中のタブに関連する endpoint であれば更新
9655 switch (endpointName)
9657 case "/statuses/home_timeline":
9658 update = tabType == MyCommon.TabUsageType.Home ||
9659 tabType == MyCommon.TabUsageType.UserDefined;
9662 case "/statuses/mentions_timeline":
9663 update = tabType == MyCommon.TabUsageType.Mentions;
9666 case "/favorites/list":
9667 update = tabType == MyCommon.TabUsageType.Favorites;
9670 case "/direct_messages:":
9671 update = tabType == MyCommon.TabUsageType.DirectMessage;
9674 case "/statuses/user_timeline":
9675 update = tabType == MyCommon.TabUsageType.UserTimeline;
9678 case "/lists/statuses":
9679 update = tabType == MyCommon.TabUsageType.Lists;
9682 case "/search/tweets":
9683 update = tabType == MyCommon.TabUsageType.PublicSearch;
9686 case "/statuses/show/:id":
9687 update = tabType == MyCommon.TabUsageType.Related;
9696 this.toolStripApiGauge.ApiEndpoint = endpointName;
9702 private void SetStatusLabelUrl()
9704 StatusLabelUrl.Text = GetStatusLabelText();
9707 public void SetStatusLabel(string text)
9709 StatusLabel.Text = text;
9712 private static StringBuilder ur = new StringBuilder(64);
9714 private void SetNotifyIconText()
9716 // タスクトレイアイコンのツールチップテキスト書き換え
9718 ur.Remove(0, ur.Length);
9719 if (this._cfgCommon.DispUsername)
9721 ur.Append(tw.Username);
9724 ur.Append(Application.ProductName);
9726 ur.Append("(Debug Build)");
9728 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9731 ur.Append(UnreadCounter);
9733 ur.Append(UnreadAtCounter);
9736 NotifyIcon1.Text = ur.ToString();
9739 internal void CheckReplyTo(string StatusText)
9743 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9745 foreach (Match hm in m)
9747 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9749 hstr += "#" + hm.Result("$3") + " ";
9750 HashSupl.AddItem("#" + hm.Result("$3"));
9753 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9755 hstr += HashMgr.UseHash;
9757 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9759 // 本当にリプライ先指定すべきかどうかの判定
9760 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9762 if (this._cfgCommon.UseAtIdSupplement)
9764 int bCnt = AtIdSupl.ItemCount;
9765 foreach (Match mid in m)
9767 AtIdSupl.AddItem(mid.Result("${id}"));
9769 if (bCnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
9772 // リプライ先ステータスIDの指定がない場合は指定しない
9773 if (this.inReplyTo == null)
9777 // 次の条件を満たす場合に in_reply_to_status_id 指定
9778 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9779 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9780 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9784 var inReplyToScreenName = this.inReplyTo.Item2;
9785 if (StatusText.StartsWith("@"))
9787 if (StatusText.StartsWith("@" + inReplyToScreenName)) return;
9791 foreach (Match mid in m)
9793 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9798 this.inReplyTo = null;
9801 private void TweenMain_Resize(object sender, EventArgs e)
9803 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9805 this.Visible = false;
9807 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9809 // 現在の DPI と設定保存時の DPI との比を取得する
9810 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9812 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9813 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9814 this.DesktopLocation = _cfgLocal.FormLocation;
9815 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9818 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9819 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9820 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9822 this.SplitContainer1.SplitterDistance = splitterDistance;
9826 StatusText.Multiline = _cfgLocal.StatusMultiline;
9827 if (StatusText.Multiline)
9829 var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9830 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9831 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9833 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9835 StatusText.Height = statusTextHeight;
9839 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9841 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9845 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9846 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9848 this.SplitContainer3.SplitterDistance = previewDistance;
9850 _initialLayout = false;
9852 if (this.WindowState != FormWindowState.Minimized)
9854 _formWindowState = this.WindowState;
9858 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9860 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9861 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9862 if (PlaySoundMenuItem.Checked)
9864 this._cfgCommon.PlaySound = true;
9868 this._cfgCommon.PlaySound = false;
9870 _modifySettingCommon = true;
9873 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9875 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
9877 _mySpDis = SplitContainer1.SplitterDistance;
9878 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9879 _modifySettingLocal = true;
9883 private async Task doRepliedStatusOpen()
9885 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9887 if (MyCommon.IsKeyDown(Keys.Shift))
9889 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9892 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9894 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9895 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9899 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9901 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9902 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9903 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9906 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9911 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9913 await this.doRepliedStatusOpen();
9917 /// UserPicture.Image に設定されている画像を破棄します。
9919 private void ClearUserPicture()
9921 if (this.UserPicture.Image != null)
9923 var oldImage = this.UserPicture.Image;
9924 this.UserPicture.Image = null;
9929 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9931 //発言詳細のアイコン右クリック時のメニュー制御
9932 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9934 string name = _curPost.ImageUrl;
9935 if (name != null && name.Length > 0)
9937 int idx = name.LastIndexOf('/');
9940 name = Path.GetFileName(name.Substring(idx));
9941 if (name.Contains("_normal.") || name.EndsWith("_normal"))
9943 name = name.Replace("_normal", "");
9944 this.IconNameToolStripMenuItem.Text = name;
9945 this.IconNameToolStripMenuItem.Enabled = true;
9949 this.IconNameToolStripMenuItem.Enabled = false;
9950 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9955 this.IconNameToolStripMenuItem.Enabled = false;
9956 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9959 this.ReloadIconToolStripMenuItem.Enabled = true;
9961 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9963 this.SaveIconPictureToolStripMenuItem.Enabled = true;
9967 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9972 this.IconNameToolStripMenuItem.Enabled = false;
9973 this.ReloadIconToolStripMenuItem.Enabled = false;
9974 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9975 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9980 this.IconNameToolStripMenuItem.Enabled = false;
9981 this.ReloadIconToolStripMenuItem.Enabled = false;
9982 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9983 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9985 if (NameLabel.Tag != null)
9987 string id = (string)NameLabel.Tag;
9988 if (id == tw.Username)
9990 FollowToolStripMenuItem.Enabled = false;
9991 UnFollowToolStripMenuItem.Enabled = false;
9992 ShowFriendShipToolStripMenuItem.Enabled = false;
9993 ShowUserStatusToolStripMenuItem.Enabled = true;
9994 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9995 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9996 ListManageUserContextToolStripMenuItem3.Enabled = true;
10000 FollowToolStripMenuItem.Enabled = true;
10001 UnFollowToolStripMenuItem.Enabled = true;
10002 ShowFriendShipToolStripMenuItem.Enabled = true;
10003 ShowUserStatusToolStripMenuItem.Enabled = true;
10004 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
10005 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
10006 ListManageUserContextToolStripMenuItem3.Enabled = true;
10011 FollowToolStripMenuItem.Enabled = false;
10012 UnFollowToolStripMenuItem.Enabled = false;
10013 ShowFriendShipToolStripMenuItem.Enabled = false;
10014 ShowUserStatusToolStripMenuItem.Enabled = false;
10015 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
10016 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
10017 ListManageUserContextToolStripMenuItem3.Enabled = false;
10021 private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
10023 if (_curPost == null) return;
10024 string name = _curPost.ImageUrl;
10025 await this.OpenUriInBrowserAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
10028 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
10030 if (this._curPost == null) return;
10032 await this.UserPicture.SetImageFromTask(async () =>
10034 var imageUrl = this._curPost.ImageUrl;
10036 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
10037 .ConfigureAwait(false);
10039 return await image.CloneAsync()
10040 .ConfigureAwait(false);
10044 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10046 if (_curPost == null) return;
10047 string name = _curPost.ImageUrl;
10048 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
10050 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
10052 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10058 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10060 if (_curPost == null) return;
10061 string name = _curPost.ImageUrl;
10063 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
10065 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10069 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
10071 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
10073 using (Graphics g = Graphics.FromImage(bmp2))
10075 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
10076 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
10078 bmp2.Save(this.SaveFileDialog1.FileName);
10084 //処理中にキャッシュアウトする可能性あり
10089 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
10091 this.StatusText.Multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
10092 MultiLineMenuItem.Checked = this.StatusText.Multiline;
10093 _modifySettingLocal = true;
10096 private void StatusText_MultilineChanged(object sender, EventArgs e)
10098 if (this.StatusText.Multiline)
10099 this.StatusText.ScrollBars = ScrollBars.Vertical;
10101 this.StatusText.ScrollBars = ScrollBars.None;
10103 _modifySettingLocal = true;
10106 private void MultiLineMenuItem_Click(object sender, EventArgs e)
10109 StatusText.Multiline = MultiLineMenuItem.Checked;
10110 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
10111 if (MultiLineMenuItem.Checked)
10113 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
10114 SplitContainer2.SplitterDistance = 0;
10116 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
10120 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
10122 _modifySettingLocal = true;
10125 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
10127 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
10128 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
10130 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
10131 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
10132 //Appendix A. Collected ABNF for URI
10133 //http://www.ietf.org/rfc/rfc3986.txt
10135 string result = "";
10137 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
10139 if (StatusText.SelectionLength > 0)
10141 string tmp = StatusText.SelectedText;
10142 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
10143 if (tmp.StartsWith("http"))
10145 // 文字列が選択されている場合はその文字列について処理
10147 //nico.ms使用、nicovideoにマッチしたら変換
10148 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10150 result = nicoms.Shorten(tmp);
10152 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10154 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10157 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10158 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10159 result = resultUri.AbsoluteUri;
10161 catch (WebApiException e)
10163 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10166 catch (UriFormatException e)
10168 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10177 if (!string.IsNullOrEmpty(result))
10179 urlUndo undotmp = new urlUndo();
10181 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
10182 StatusText.SelectedText = result;
10185 undotmp.Before = tmp;
10186 undotmp.After = result;
10188 if (urlUndoBuffer == null)
10190 urlUndoBuffer = new List<urlUndo>();
10191 UrlUndoToolStripMenuItem.Enabled = true;
10194 urlUndoBuffer.Add(undotmp);
10200 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
10201 @"(?<url>(?<protocol>https?://)" +
10202 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
10203 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
10204 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
10205 // 正規表現にマッチしたURL文字列をtinyurl化
10206 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
10208 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
10209 string tmp = mt.Result("${url}");
10210 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
10211 urlUndo undotmp = new urlUndo();
10214 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10216 //nico.ms使用、nicovideoにマッチしたら変換
10217 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10219 result = nicoms.Shorten(tmp);
10221 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10223 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10226 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10227 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10228 result = resultUri.AbsoluteUri;
10230 catch (HttpRequestException e)
10232 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
10233 // のように長いので「:」が含まれていればそれ以降のみを抽出する
10234 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
10236 this.StatusLabel.Text = Converter_Type + ":" + message;
10239 catch (WebApiException e)
10241 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10244 catch (UriFormatException e)
10246 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10255 if (!string.IsNullOrEmpty(result))
10257 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10258 StatusText.SelectedText = result;
10260 undotmp.Before = mt.Result("${url}");
10261 undotmp.After = result;
10263 if (urlUndoBuffer == null)
10265 urlUndoBuffer = new List<urlUndo>();
10266 UrlUndoToolStripMenuItem.Enabled = true;
10269 urlUndoBuffer.Add(undotmp);
10277 private void doUrlUndo()
10279 if (urlUndoBuffer != null)
10281 string tmp = StatusText.Text;
10282 foreach (urlUndo data in urlUndoBuffer)
10284 tmp = tmp.Replace(data.After, data.Before);
10286 StatusText.Text = tmp;
10287 urlUndoBuffer = null;
10288 UrlUndoToolStripMenuItem.Enabled = false;
10289 StatusText.SelectionStart = 0;
10290 StatusText.SelectionLength = 0;
10294 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10296 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10299 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10301 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10304 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10306 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10309 private async void UxnuMenuItem_Click(object sender, EventArgs e)
10311 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10314 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10316 if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
10318 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
10319 Random rnd = new Random();
10320 // 前回使用した短縮URLサービス以外を選択する
10323 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10325 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10326 await UrlConvertAsync(svc);
10330 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10335 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10337 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10338 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10339 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10340 _modifySettingCommon = true;
10343 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10345 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10346 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10347 _cfgCommon.ListLock = ListLockMenuItem.Checked;
10348 _modifySettingCommon = true;
10351 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10353 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10354 MenuStrip1.Tag = new Object();
10355 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10358 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10360 if (this.Tag != null) // 設定された戻り先へ遷移
10362 if (this.Tag == this.ListTab.SelectedTab)
10363 ((Control)this.ListTab.SelectedTab.Tag).Select();
10365 ((Control)this.Tag).Select();
10367 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10369 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10371 this.Tag = ListTab.SelectedTab.Tag;
10372 ((Control)this.Tag).Select();
10375 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10376 MenuStrip1.Tag = null;
10379 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10381 DetailsListView lst = (DetailsListView)sender;
10382 if (_cfgLocal == null) return;
10386 _cfgLocal.Width1 = lst.Columns[0].Width;
10387 _cfgLocal.Width3 = lst.Columns[1].Width;
10391 int[] darr = new int[lst.Columns.Count];
10392 for (int i = 0; i < lst.Columns.Count; i++)
10394 darr[lst.Columns[i].DisplayIndex] = i;
10396 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10398 for (int i = 0; i < lst.Columns.Count; i++)
10403 _cfgLocal.DisplayIndex1 = i;
10406 _cfgLocal.DisplayIndex2 = i;
10409 _cfgLocal.DisplayIndex3 = i;
10412 _cfgLocal.DisplayIndex4 = i;
10415 _cfgLocal.DisplayIndex5 = i;
10418 _cfgLocal.DisplayIndex6 = i;
10421 _cfgLocal.DisplayIndex7 = i;
10424 _cfgLocal.DisplayIndex8 = i;
10428 _cfgLocal.Width1 = lst.Columns[0].Width;
10429 _cfgLocal.Width2 = lst.Columns[1].Width;
10430 _cfgLocal.Width3 = lst.Columns[2].Width;
10431 _cfgLocal.Width4 = lst.Columns[3].Width;
10432 _cfgLocal.Width5 = lst.Columns[4].Width;
10433 _cfgLocal.Width6 = lst.Columns[5].Width;
10434 _cfgLocal.Width7 = lst.Columns[6].Width;
10435 _cfgLocal.Width8 = lst.Columns[7].Width;
10437 _modifySettingLocal = true;
10438 _isColumnChanged = true;
10441 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10443 DetailsListView lst = (DetailsListView)sender;
10444 if (_cfgLocal == null) return;
10447 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10449 _cfgLocal.Width1 = lst.Columns[0].Width;
10450 _modifySettingLocal = true;
10451 _isColumnChanged = true;
10453 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10455 _cfgLocal.Width3 = lst.Columns[1].Width;
10456 _modifySettingLocal = true;
10457 _isColumnChanged = true;
10462 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10464 _cfgLocal.Width1 = lst.Columns[0].Width;
10465 _modifySettingLocal = true;
10466 _isColumnChanged = true;
10468 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10470 _cfgLocal.Width2 = lst.Columns[1].Width;
10471 _modifySettingLocal = true;
10472 _isColumnChanged = true;
10474 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10476 _cfgLocal.Width3 = lst.Columns[2].Width;
10477 _modifySettingLocal = true;
10478 _isColumnChanged = true;
10480 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10482 _cfgLocal.Width4 = lst.Columns[3].Width;
10483 _modifySettingLocal = true;
10484 _isColumnChanged = true;
10486 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10488 _cfgLocal.Width5 = lst.Columns[4].Width;
10489 _modifySettingLocal = true;
10490 _isColumnChanged = true;
10492 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10494 _cfgLocal.Width6 = lst.Columns[5].Width;
10495 _modifySettingLocal = true;
10496 _isColumnChanged = true;
10498 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10500 _cfgLocal.Width7 = lst.Columns[6].Width;
10501 _modifySettingLocal = true;
10502 _isColumnChanged = true;
10504 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10506 _cfgLocal.Width8 = lst.Columns[7].Width;
10507 _modifySettingLocal = true;
10508 _isColumnChanged = true;
10511 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10514 // SaveConfigsLocal();
10518 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10521 string _selText = this.PostBrowser.GetSelectedText();
10524 Clipboard.SetDataObject(_selText, false, 5, 100);
10526 catch (Exception ex)
10528 MessageBox.Show(ex.Message);
10532 private async Task doSearchToolStrip(string url)
10534 //発言詳細で「選択文字列で検索」(選択文字列取得)
10535 string _selText = this.PostBrowser.GetSelectedText();
10537 if (_selText != null)
10539 if (url == Properties.Resources.SearchItem4Url)
10542 AddNewTabForSearch(_selText);
10546 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10547 await this.OpenUriInBrowserAsync(tmp);
10551 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10554 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10557 private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10559 await this.doSearchToolStrip(Properties.Resources.SearchItem1Url);
10562 private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10564 await this.doSearchToolStrip(Properties.Resources.SearchItem2Url);
10567 private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10569 await this.doSearchToolStrip(Properties.Resources.SearchItem4Url);
10572 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10576 MatchCollection mc = Regex.Matches(this.PostBrowser.DocumentText, @"<a[^>]*href=""(?<url>" + this._postBrowserStatusText.Replace(".", @"\.") + @")""[^>]*title=""(?<title>https?://[^""]+)""", RegexOptions.IgnoreCase);
10577 foreach (Match m in mc)
10579 if (m.Groups["url"].Value == this._postBrowserStatusText)
10581 Clipboard.SetDataObject(m.Groups["title"].Value, false, 5, 100);
10587 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10589 //Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10591 catch (Exception ex)
10593 MessageBox.Show(ex.Message);
10597 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10599 // URLコピーの項目の表示/非表示
10600 if (PostBrowser.StatusText.StartsWith("http"))
10602 this._postBrowserStatusText = PostBrowser.StatusText;
10603 string name = GetUserId();
10604 UrlCopyContextMenuItem.Enabled = true;
10607 FollowContextMenuItem.Enabled = true;
10608 RemoveContextMenuItem.Enabled = true;
10609 FriendshipContextMenuItem.Enabled = true;
10610 ShowUserStatusContextMenuItem.Enabled = true;
10611 SearchPostsDetailToolStripMenuItem.Enabled = true;
10612 IdFilterAddMenuItem.Enabled = true;
10613 ListManageUserContextToolStripMenuItem.Enabled = true;
10614 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10618 FollowContextMenuItem.Enabled = false;
10619 RemoveContextMenuItem.Enabled = false;
10620 FriendshipContextMenuItem.Enabled = false;
10621 ShowUserStatusContextMenuItem.Enabled = false;
10622 SearchPostsDetailToolStripMenuItem.Enabled = false;
10623 IdFilterAddMenuItem.Enabled = false;
10624 ListManageUserContextToolStripMenuItem.Enabled = false;
10625 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10628 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10629 UseHashtagMenuItem.Enabled = true;
10631 UseHashtagMenuItem.Enabled = false;
10635 this._postBrowserStatusText = "";
10636 UrlCopyContextMenuItem.Enabled = false;
10637 FollowContextMenuItem.Enabled = false;
10638 RemoveContextMenuItem.Enabled = false;
10639 FriendshipContextMenuItem.Enabled = false;
10640 ShowUserStatusContextMenuItem.Enabled = false;
10641 SearchPostsDetailToolStripMenuItem.Enabled = false;
10642 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10643 UseHashtagMenuItem.Enabled = false;
10644 IdFilterAddMenuItem.Enabled = false;
10645 ListManageUserContextToolStripMenuItem.Enabled = false;
10647 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10648 string _selText = this.PostBrowser.GetSelectedText();
10649 if (_selText == null)
10651 SelectionSearchContextMenuItem.Enabled = false;
10652 SelectionCopyContextMenuItem.Enabled = false;
10653 SelectionTranslationToolStripMenuItem.Enabled = false;
10657 SelectionSearchContextMenuItem.Enabled = true;
10658 SelectionCopyContextMenuItem.Enabled = true;
10659 SelectionTranslationToolStripMenuItem.Enabled = true;
10661 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10662 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10663 bool fAllFlag = false;
10664 foreach (Match mu in ma)
10666 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
10672 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10674 if (_curPost == null)
10675 TranslationToolStripMenuItem.Enabled = false;
10677 TranslationToolStripMenuItem.Enabled = true;
10682 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10684 //発言詳細の選択文字列で現在のタブを検索
10685 string _selText = this.PostBrowser.GetSelectedText();
10687 if (_selText != null)
10689 var searchOptions = new SearchWordDialog.SearchOptions(
10690 SearchWordDialog.SearchType.Timeline,
10693 caseSensitive: false,
10696 this.SearchDialog.ResultOptions = searchOptions;
10699 searchOptions.Query,
10700 searchOptions.CaseSensitive,
10701 searchOptions.UseRegex,
10702 SEARCHTYPE.NextSearch);
10706 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10708 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10709 _modifySettingLocal = true;
10712 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10714 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10716 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10718 SelectMedia_DragDrop(e);
10721 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10723 var url = GetUrlFromDataObject(e.Data);
10726 if (url.Item2 == null)
10727 appendText = url.Item1;
10729 appendText = url.Item2 + " " + url.Item1;
10731 if (this.StatusText.TextLength == 0)
10732 this.StatusText.Text = appendText;
10734 this.StatusText.Text += " " + appendText;
10736 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10738 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10740 this.StatusText.Text += text;
10742 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10744 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10745 if (data != null) StatusText.Text += data;
10750 /// IDataObject から URL とタイトルの対を取得します
10753 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10755 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10756 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10757 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10759 if (data.GetDataPresent("text/x-moz-url"))
10761 // Firefox, Google Chrome で利用可能
10762 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10764 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10766 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10767 if (lines.Length < 2)
10768 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
10770 return new Tuple<string, string>(lines[0], lines[1]);
10773 else if (data.GetDataPresent("IESiteModeToUrl"))
10775 // Internet Exproler 用
10776 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10778 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10780 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10781 if (lines.Length < 2)
10782 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
10784 return new Tuple<string, string>(lines[0], lines[1]);
10787 else if (data.GetDataPresent("UniformResourceLocatorW"))
10791 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10793 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10794 return new Tuple<string, string>(url, null);
10798 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10801 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10803 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10805 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10807 SelectMedia_DragEnter(e);
10811 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10813 e.Effect = DragDropEffects.Copy;
10816 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10818 e.Effect = DragDropEffects.Copy;
10821 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10823 e.Effect = DragDropEffects.Copy;
10827 e.Effect = DragDropEffects.None;
10830 private void TweenMain_DragOver(object sender, DragEventArgs e)
10834 public bool IsNetworkAvailable()
10837 nw = MyCommon.IsNetworkAvailable();
10838 _myStatusOnline = nw;
10842 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
10844 var uriStr = uri.AbsoluteUri;
10846 // OpenTween 内部で使用する URL
10847 if (uri.Authority == "opentween")
10849 await this.OpenInternalUriAsync(uri);
10853 // ハッシュタグを含む Twitter 検索
10854 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
10856 // ハッシュタグの場合は、タブで開く
10857 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
10858 var pos = unescapedQuery.IndexOf('#');
10859 if (pos == -1) return;
10861 var hash = unescapedQuery.Substring(pos);
10862 this.HashSupl.AddItem(hash);
10863 this.HashMgr.AddHashToHistory(hash.Trim(), false);
10864 this.AddNewTabForSearch(hash);
10869 // フラグが立っている場合は設定と逆の動作をする
10870 if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
10871 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
10873 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
10874 if (userUriMatch.Success)
10876 var screenName = userUriMatch.Groups["ScreenName"].Value;
10877 if (this.IsTwitterId(screenName))
10879 this.AddNewTabForUserTimeline(screenName);
10885 // どのパターンにも該当しないURL
10886 await this.OpenUriInBrowserAsync(uriStr);
10890 /// OpenTween 内部の機能を呼び出すための URL を開きます
10892 private async Task OpenInternalUriAsync(Uri uri)
10894 // ツイートを開く (//opentween/status/:status_id)
10895 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
10898 var statusId = long.Parse(match.Groups[1].Value);
10899 await this.OpenRelatedTab(statusId);
10904 public Task OpenUriInBrowserAsync(string UriString)
10906 return Task.Run(() =>
10908 string myPath = UriString;
10912 var configBrowserPath = this._cfgLocal.BrowserPath;
10913 if (!string.IsNullOrEmpty(configBrowserPath))
10915 if (configBrowserPath.StartsWith("\"") && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2) > -1)
10917 int sep = configBrowserPath.IndexOf("\"", 2);
10918 string browserPath = configBrowserPath.Substring(1, sep - 1);
10920 if (sep < configBrowserPath.Length - 1)
10922 arg = configBrowserPath.Substring(sep + 1);
10924 myPath = arg + " " + myPath;
10925 System.Diagnostics.Process.Start(browserPath, myPath);
10929 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10934 System.Diagnostics.Process.Start(myPath);
10939 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10944 private void ListTabSelect(TabPage _tab)
10948 this.PurgeListViewItemCache();
10951 _curList = (DetailsListView)_tab.Tag;
10952 if (_curList.SelectedIndices.Count > 0)
10954 _curItemIndex = _curList.SelectedIndices[0];
10955 _curPost = GetCurTabPost(_curItemIndex);
10959 _curItemIndex = -1;
10963 _anchorPost = null;
10964 _anchorFlag = false;
10968 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10972 for (int i = 0; i < _curList.Columns.Count; i++)
10974 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10979 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10981 ListTabSelect(e.TabPage);
10984 private void SelectListItem(DetailsListView LView, int Index)
10987 Rectangle bnd = new Rectangle();
10989 var item = LView.FocusedItem;
10998 LView.SelectedIndices.Clear();
11000 while (LView.SelectedIndices.Count > 0);
11001 item = LView.Items[Index];
11002 item.Selected = true;
11003 item.Focused = true;
11005 if (flg) LView.Invalidate(bnd);
11008 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
11011 Rectangle bnd = new Rectangle();
11013 var item = LView.FocusedItem;
11024 LView.SelectedIndices.Clear();
11026 while (LView.SelectedIndices.Count > 0);
11027 LView.SelectItems(Index);
11029 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
11031 LView.SelectionMark = selectionMarkIndex;
11033 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
11035 LView.Items[focusedIndex].Focused = true;
11037 else if (Index != null && Index.Length != 0)
11039 LView.Items[Index.Last()].Focused = true;
11042 if (flg) LView.Invalidate(bnd);
11045 private void StartUserStream()
11047 tw.NewPostFromStream += tw_NewPostFromStream;
11048 tw.UserStreamStarted += tw_UserStreamStarted;
11049 tw.UserStreamStopped += tw_UserStreamStopped;
11050 tw.PostDeleted += tw_PostDeleted;
11051 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
11053 MenuItemUserStream.Text = "&UserStream ■";
11054 MenuItemUserStream.Enabled = true;
11055 StopToolStripMenuItem.Text = "&Start";
11056 StopToolStripMenuItem.Enabled = true;
11057 if (this._cfgCommon.UserstreamStartup) tw.StartUserStream();
11060 private async void TweenMain_Shown(object sender, EventArgs e)
11064 using (ControlTransaction.Update(this.PostBrowser))
11066 PostBrowser.Url = new Uri("about:blank");
11067 PostBrowser.DocumentText = ""; //発言詳細部初期化
11074 NotifyIcon1.Visible = true;
11076 if (this.IsNetworkAvailable())
11080 var loadTasks = new List<Task>
11082 this.RefreshMuteUserIdsAsync(),
11083 this.RefreshBlockIdsAsync(),
11084 this.RefreshNoRetweetIdsAsync(),
11085 this.RefreshTwitterConfigurationAsync(),
11086 this.GetHomeTimelineAsync(),
11087 this.GetReplyAsync(),
11088 this.GetDirectMessagesAsync(),
11089 this.GetPublicSearchAllAsync(),
11090 this.GetUserTimelineAllAsync(),
11091 this.GetListTimelineAllAsync(),
11094 if (this._cfgCommon.StartupFollowers)
11095 loadTasks.Add(this.RefreshFollowerIdsAsync());
11097 if (this._cfgCommon.GetFav)
11098 loadTasks.Add(this.GetFavoritesAsync());
11100 var allTasks = Task.WhenAll(loadTasks);
11105 var timeout = Task.Delay(5000);
11106 if (await Task.WhenAny(allTasks, timeout) != timeout)
11110 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
11112 if (MyCommon._endingFlag)
11116 if (MyCommon._endingFlag) return;
11118 if (ApplicationSettings.VersionInfoUrl != null)
11120 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
11121 if (this._cfgCommon.StartupVersion)
11122 await this.CheckNewVersion(true);
11126 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
11127 this.VerUpMenuItem.Enabled = false;
11128 this.VerUpMenuItem.Available = false;
11129 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
11132 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
11133 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
11135 MessageBox.Show(Properties.Resources.ReAuthorizeText);
11136 SettingStripMenuItem_Click(null, null);
11140 var reloadTasks = new List<Task>();
11142 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
11143 reloadTasks.Add(this.RefreshFollowerIdsAsync());
11145 if (!tw.GetNoRetweetSuccess)
11146 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
11148 if (this.tw.Configuration.PhotoSizeLimit == 0)
11149 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
11151 await Task.WhenAll(reloadTasks);
11156 TimerTimeline.Enabled = true;
11159 private async Task doGetFollowersMenu()
11161 await this.RefreshFollowerIdsAsync();
11162 await this.DispSelectedPost(true);
11165 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
11167 await this.doGetFollowersMenu();
11170 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
11172 doReTweetUnofficial();
11175 private async Task doReTweetOfficial(bool isConfirm)
11178 if (this.ExistCurrentPost)
11180 if (_curPost.IsProtect)
11182 MessageBox.Show("Protected.");
11183 _DoFavRetweetFlags = false;
11186 if (_curList.SelectedIndices.Count > 15)
11188 MessageBox.Show(Properties.Resources.RetweetLimitText);
11189 _DoFavRetweetFlags = false;
11192 else if (_curList.SelectedIndices.Count > 1)
11194 string QuestionText = Properties.Resources.RetweetQuestion2;
11195 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
11196 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
11198 case DialogResult.Cancel:
11199 case DialogResult.No:
11200 _DoFavRetweetFlags = false;
11206 if (_curPost.IsDm || _curPost.IsMe)
11208 _DoFavRetweetFlags = false;
11211 if (!this._cfgCommon.RetweetNoConfirm)
11213 string Questiontext = Properties.Resources.RetweetQuestion1;
11214 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11215 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11217 _DoFavRetweetFlags = false;
11223 var statusIds = new List<long>();
11224 foreach (int idx in _curList.SelectedIndices)
11226 PostClass post = GetCurTabPost(idx);
11227 if (!post.IsMe && !post.IsProtect && !post.IsDm)
11228 statusIds.Add(post.StatusId);
11231 await this.RetweetAsync(statusIds);
11235 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
11237 await this.doReTweetOfficial(true);
11240 private async Task FavoritesRetweetOfficial()
11242 if (!this.ExistCurrentPost) return;
11243 _DoFavRetweetFlags = true;
11244 var retweetTask = this.doReTweetOfficial(true);
11245 if (_DoFavRetweetFlags)
11247 _DoFavRetweetFlags = false;
11248 var favoriteTask = this.FavoriteChange(true, false);
11250 await Task.WhenAll(retweetTask, favoriteTask);
11258 private async Task FavoritesRetweetUnofficial()
11260 if (this.ExistCurrentPost && !_curPost.IsDm)
11262 _DoFavRetweetFlags = true;
11263 var favoriteTask = this.FavoriteChange(true);
11264 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11266 _DoFavRetweetFlags = false;
11267 doReTweetUnofficial();
11270 await favoriteTask;
11275 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11277 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11278 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11279 /// <returns>復元されたツイート本文</returns>
11280 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11282 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11285 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11287 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11289 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11293 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11295 statusHtml = statusHtml.Replace("<br>", " ");
11297 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11298 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
11299 statusHtml = statusHtml.Replace(" ", " ");
11301 return WebUtility.HtmlDecode(statusHtml);
11304 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11306 if (_curPost != null)
11307 await this.DispSelectedPost(true);
11310 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11312 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11313 DebugModeToolStripMenuItem.Visible = true;
11315 DebugModeToolStripMenuItem.Visible = false;
11318 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11320 this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11323 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11325 ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
11328 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11330 if (TraceOutToolStripMenuItem.Checked)
11331 MyCommon.TraceFlag = true;
11333 MyCommon.TraceFlag = false;
11336 private void TweenMain_Deactivate(object sender, EventArgs e)
11338 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11339 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11342 private void TabRenameMenuItem_Click(object sender, EventArgs e)
11344 if (string.IsNullOrEmpty(_rclickTabName)) return;
11345 TabRename(ref _rclickTabName);
11348 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11350 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11353 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11355 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11358 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11360 TwitterApiStatus apiStatus;
11362 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
11364 var cancellationToken = dialog.EnableCancellation();
11368 var task = Task.Run(() => this.tw.GetInfoApi());
11369 apiStatus = await dialog.WaitForAsync(this, task);
11371 catch (WebApiException)
11376 if (cancellationToken.IsCancellationRequested)
11379 if (apiStatus == null)
11381 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11386 using (var apiDlg = new ApiInfoDialog())
11388 apiDlg.ShowDialog(this);
11392 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
11394 var id = _curPost?.ScreenName ?? "";
11396 await this.FollowCommand(id);
11399 private async Task FollowCommand(string id)
11401 using (var inputName = new InputTabName())
11403 inputName.FormTitle = "Follow";
11404 inputName.FormDescription = Properties.Resources.FRMessage1;
11405 inputName.TabName = id;
11407 if (inputName.ShowDialog(this) != DialogResult.OK)
11409 if (string.IsNullOrWhiteSpace(inputName.TabName))
11412 id = inputName.TabName.Trim();
11415 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
11419 var task = Task.Run(() => this.tw.PostFollowCommand(id));
11420 await dialog.WaitForAsync(this, task);
11422 catch (WebApiException ex)
11424 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11429 MessageBox.Show(Properties.Resources.FRMessage3);
11432 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11434 var id = _curPost?.ScreenName ?? "";
11436 await this.RemoveCommand(id, false);
11439 private async Task RemoveCommand(string id, bool skipInput)
11443 using (var inputName = new InputTabName())
11445 inputName.FormTitle = "Unfollow";
11446 inputName.FormDescription = Properties.Resources.FRMessage1;
11447 inputName.TabName = id;
11449 if (inputName.ShowDialog(this) != DialogResult.OK)
11451 if (string.IsNullOrWhiteSpace(inputName.TabName))
11454 id = inputName.TabName.Trim();
11458 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
11462 var task = Task.Run(() => this.tw.PostRemoveCommand(id));
11463 await dialog.WaitForAsync(this, task);
11465 catch (WebApiException ex)
11467 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11472 MessageBox.Show(Properties.Resources.FRMessage3);
11475 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
11477 var id = _curPost?.ScreenName ?? "";
11479 await this.ShowFriendship(id);
11482 private async Task ShowFriendship(string id)
11484 using (var inputName = new InputTabName())
11486 inputName.FormTitle = "Show Friendships";
11487 inputName.FormDescription = Properties.Resources.FRMessage1;
11488 inputName.TabName = id;
11490 if (inputName.ShowDialog(this) != DialogResult.OK)
11492 if (string.IsNullOrWhiteSpace(inputName.TabName))
11495 id = inputName.TabName.Trim();
11498 bool isFollowing, isFollowed;
11500 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11502 var cancellationToken = dialog.EnableCancellation();
11506 var task = Task.Run(() => this.tw.GetFriendshipInfo(id));
11507 var friendship = await dialog.WaitForAsync(this, task);
11509 isFollowing = friendship.Relationship.Source.Following;
11510 isFollowed = friendship.Relationship.Source.FollowedBy;
11512 catch (WebApiException ex)
11514 if (!cancellationToken.IsCancellationRequested)
11515 MessageBox.Show(ex.Message);
11519 if (cancellationToken.IsCancellationRequested)
11523 string result = "";
11526 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11530 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11534 result += Properties.Resources.GetFriendshipInfo3;
11538 result += Properties.Resources.GetFriendshipInfo4;
11540 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11541 MessageBox.Show(result);
11544 private async Task ShowFriendship(string[] ids)
11546 foreach (string id in ids)
11548 bool isFollowing, isFollowed;
11550 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11552 var cancellationToken = dialog.EnableCancellation();
11556 var task = Task.Run(() => this.tw.GetFriendshipInfo(id));
11557 var friendship = await dialog.WaitForAsync(this, task);
11559 isFollowing = friendship.Relationship.Source.Following;
11560 isFollowed = friendship.Relationship.Source.FollowedBy;
11562 catch (WebApiException ex)
11564 if (!cancellationToken.IsCancellationRequested)
11565 MessageBox.Show(ex.Message);
11569 if (cancellationToken.IsCancellationRequested)
11573 string result = "";
11579 ff += Properties.Resources.GetFriendshipInfo1;
11583 ff += Properties.Resources.GetFriendshipInfo2;
11586 ff += System.Environment.NewLine + " ";
11589 ff += Properties.Resources.GetFriendshipInfo3;
11593 ff += Properties.Resources.GetFriendshipInfo4;
11595 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11598 if (MessageBox.Show(
11599 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11600 MessageBoxButtons.YesNo,
11601 MessageBoxIcon.Question,
11602 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11604 await this.RemoveCommand(id, true);
11609 MessageBox.Show(result);
11614 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
11616 await this.doShowUserStatus(tw.Username, false);
11617 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11619 // doShowUserStatus(tw.Username, false);
11623 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11628 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11629 // URLから切り出した文字列を渡す
11631 public bool IsTwitterId(string name)
11633 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11634 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11636 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLower());
11639 private string GetUserId()
11641 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11642 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11643 return m.Result("${ScreenName}");
11648 private async void FollowContextMenuItem_Click(object sender, EventArgs e)
11650 string name = GetUserId();
11652 await this.FollowCommand(name);
11655 private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
11657 string name = GetUserId();
11659 await this.RemoveCommand(name, false);
11662 private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11664 string name = GetUserId();
11666 await this.ShowFriendship(name);
11669 private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11671 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11672 List<string> ids = new List<string>();
11673 foreach (Match mu in ma)
11675 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11677 ids.Add(mu.Result("${ScreenName}"));
11681 await this.ShowFriendship(ids.ToArray());
11684 private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11686 string name = GetUserId();
11688 await this.ShowUserStatus(name);
11691 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11693 string name = GetUserId();
11694 if (name != null) AddNewTabForUserTimeline(name);
11697 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11699 string name = GetUserId();
11700 if (name != null) AddNewTabForSearch("@" + name);
11703 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11705 _modifySettingCommon = true;
11708 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11710 _modifySettingCommon = true;
11713 private void doQuoteOfficial()
11715 if (this.ExistCurrentPost)
11717 if (_curPost.IsDm ||
11718 !StatusText.Enabled) return;
11720 if (_curPost.IsProtect)
11722 MessageBox.Show("Protected.");
11726 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
11728 this.inReplyTo = null;
11730 StatusText.SelectionStart = 0;
11731 StatusText.Focus();
11735 private void doReTweetUnofficial()
11738 if (this.ExistCurrentPost)
11740 if (_curPost.IsDm || !StatusText.Enabled)
11743 if (_curPost.IsProtect)
11745 MessageBox.Show("Protected.");
11748 string rtdata = _curPost.Text;
11749 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11751 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
11753 // 投稿時に in_reply_to_status_id を付加する
11754 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11755 var inReplyToScreenName = this._curPost.ScreenName;
11756 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
11758 StatusText.SelectionStart = 0;
11759 StatusText.Focus();
11763 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11768 private void SearchButton_Click(object sender, EventArgs e)
11771 Control pnl = ((Control)sender).Parent;
11772 if (pnl == null) return;
11773 string tbName = pnl.Parent.Text;
11774 TabClass tb = _statuses.Tabs[tbName];
11775 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11776 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11777 cmb.Text = cmb.Text.Trim();
11778 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11779 bool Quote = false;
11780 StringBuilder buf = new StringBuilder();
11781 char[] c = cmb.Text.ToCharArray();
11782 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11784 if (cnt > cmb.Text.Length - 4)
11786 buf.Append(cmb.Text.Substring(cnt));
11795 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11797 buf.Append(" OR ");
11802 buf.Append(c[cnt]);
11804 cmb.Text = buf.ToString();
11806 var listView = (DetailsListView)pnl.Parent.Tag;
11808 tb.SearchWords = cmb.Text;
11809 tb.SearchLang = cmbLang.Text;
11810 if (string.IsNullOrEmpty(cmb.Text))
11816 if (tb.IsSearchQueryChanged)
11818 int idx = cmb.Items.IndexOf(tb.SearchWords);
11819 if (idx > -1) cmb.Items.RemoveAt(idx);
11820 cmb.Items.Insert(0, tb.SearchWords);
11821 cmb.Text = tb.SearchWords;
11823 this.PurgeListViewItemCache();
11824 listView.VirtualListSize = 0;
11825 _statuses.ClearTabIds(tbName);
11826 SaveConfigsTabs(); //検索条件の保存
11829 this.GetPublicSearchAsync(tb);
11833 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11836 await this.DoRefreshMore();
11840 /// 指定されたタブのListTabにおける位置を返します
11843 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
11845 public int GetTabPageIndex(string tabName)
11848 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
11850 if (tabPage.Text == tabName)
11859 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11861 if (_statuses.RemovedTab.Count == 0)
11863 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11868 DetailsListView listView = null;
11870 TabClass tb = _statuses.RemovedTab.Pop();
11871 if (tb.TabType == MyCommon.TabUsageType.Related)
11873 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11874 if (relatedTab != null)
11876 // 関連発言なら既存のタブを置き換える
11877 tb.TabName = relatedTab.TabName;
11878 this.ClearTab(tb.TabName, false);
11879 _statuses.Tabs[tb.TabName] = tb;
11881 for (int i = 0; i < ListTab.TabPages.Count; i++)
11883 var tabPage = ListTab.TabPages[i];
11884 if (tb.TabName == tabPage.Text)
11886 listView = (DetailsListView)tabPage.Tag;
11887 ListTab.SelectedIndex = i;
11894 const string TabName = "Related Tweets";
11895 string renamed = TabName;
11896 for (int i = 2; i <= 100; i++)
11898 if (!_statuses.ContainsTab(renamed)) break;
11899 renamed = TabName + i.ToString();
11901 tb.TabName = renamed;
11902 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11903 _statuses.Tabs.Add(renamed, tb); // 後に
11905 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11906 listView = (DetailsListView)tabPage.Tag;
11907 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11912 string renamed = tb.TabName;
11913 for (int i = 1; i < int.MaxValue; i++)
11915 if (!_statuses.ContainsTab(renamed)) break;
11916 renamed = tb.TabName + "(" + i.ToString() + ")";
11918 tb.TabName = renamed;
11919 _statuses.Tabs.Add(renamed, tb); // 先に
11920 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11922 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11923 listView = (DetailsListView)tabPage.Tag;
11924 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11928 if (listView != null)
11930 using (ControlTransaction.Update(listView))
11932 listView.VirtualListSize = tb.AllCount;
11938 private async Task doMoveToRTHome()
11940 if (_curList.SelectedIndices.Count > 0)
11942 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11943 if (post.RetweetedId != null)
11945 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11950 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11952 await this.doMoveToRTHome();
11955 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11957 string name = GetUserId();
11963 if (_curList.SelectedIndices.Count == 0) return;
11966 if (!SelectTab(out tabName)) return;
11968 var tab = this._statuses.Tabs[tabName];
11972 if (tab.TabType != MyCommon.TabUsageType.Mute)
11974 this.MoveOrCopy(out mv, out mk);
11978 // ミュートタブでは常に MoveMatches を true にする
11983 PostFilterRule fc = new PostFilterRule();
11984 fc.FilterName = name;
11985 fc.UseNameField = true;
11986 fc.MoveMatches = mv;
11987 fc.MarkMatches = mk;
11988 fc.UseRegex = false;
11989 fc.FilterByUrl = false;
11992 this.ApplyPostFilters();
11997 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
12001 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
12003 if (menuItem.Owner == this.ContextMenuPostBrowser)
12005 user = GetUserId();
12006 if (user == null) return;
12008 else if (this._curPost != null)
12010 user = this._curPost.ScreenName;
12017 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
12021 this.tw.GetListsApi();
12023 catch (WebApiException ex)
12025 MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
12030 using (MyLists listSelectForm = new MyLists(user, this.tw))
12032 listSelectForm.ShowDialog(this);
12036 private void SearchControls_Enter(object sender, EventArgs e)
12038 Control pnl = (Control)sender;
12039 foreach (Control ctl in pnl.Controls)
12041 ctl.TabStop = true;
12045 private void SearchControls_Leave(object sender, EventArgs e)
12047 Control pnl = (Control)sender;
12048 foreach (Control ctl in pnl.Controls)
12050 ctl.TabStop = false;
12054 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
12056 if (ListTab.SelectedTab != null)
12058 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
12059 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
12063 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
12065 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
12068 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
12069 HashStripSplitButton.Text = HashMgr.UseHash;
12070 HashToggleMenuItem.Checked = true;
12071 HashToggleToolStripMenuItem.Checked = true;
12073 _modifySettingCommon = true;
12077 private void StatusLabel_DoubleClick(object sender, EventArgs e)
12079 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
12082 private void HashManageMenuItem_Click(object sender, EventArgs e)
12084 DialogResult rslt = DialogResult.Cancel;
12087 rslt = HashMgr.ShowDialog();
12093 this.TopMost = this._cfgCommon.AlwaysTop;
12094 if (rslt == DialogResult.Cancel) return;
12095 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12097 HashStripSplitButton.Text = HashMgr.UseHash;
12098 HashToggleMenuItem.Checked = true;
12099 HashToggleToolStripMenuItem.Checked = true;
12103 HashStripSplitButton.Text = "#[-]";
12104 HashToggleMenuItem.Checked = false;
12105 HashToggleToolStripMenuItem.Checked = false;
12107 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
12109 // int sidx = StatusText.SelectionStart;
12110 // string hash = HashMgr.UseHash + " ";
12113 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
12114 // hash = " " + hash;
12116 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
12117 // sidx += hash.Length;
12118 // StatusText.SelectionStart = sidx;
12119 // StatusText.Focus();
12121 _modifySettingCommon = true;
12122 this.StatusText_TextChanged(null, null);
12125 private void HashToggleMenuItem_Click(object sender, EventArgs e)
12127 HashMgr.ToggleHash();
12128 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12130 HashStripSplitButton.Text = HashMgr.UseHash;
12131 HashToggleMenuItem.Checked = true;
12132 HashToggleToolStripMenuItem.Checked = true;
12136 HashStripSplitButton.Text = "#[-]";
12137 HashToggleMenuItem.Checked = false;
12138 HashToggleToolStripMenuItem.Checked = false;
12140 _modifySettingCommon = true;
12141 this.StatusText_TextChanged(null, null);
12144 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
12146 HashToggleMenuItem_Click(null, null);
12149 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
12151 if (ListTab.SelectedTab == null) return;
12152 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
12153 if (!this.ExistCurrentPost)
12155 this.ReplyOpMenuItem.Enabled = false;
12156 this.ReplyAllOpMenuItem.Enabled = false;
12157 this.DmOpMenuItem.Enabled = false;
12158 this.ShowProfMenuItem.Enabled = false;
12159 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
12160 this.ListManageMenuItem.Enabled = false;
12161 this.OpenFavOpMenuItem.Enabled = false;
12162 this.CreateTabRuleOpMenuItem.Enabled = false;
12163 this.CreateIdRuleOpMenuItem.Enabled = false;
12164 this.CreateSourceRuleOpMenuItem.Enabled = false;
12165 this.ReadOpMenuItem.Enabled = false;
12166 this.UnreadOpMenuItem.Enabled = false;
12170 this.ReplyOpMenuItem.Enabled = true;
12171 this.ReplyAllOpMenuItem.Enabled = true;
12172 this.DmOpMenuItem.Enabled = true;
12173 this.ShowProfMenuItem.Enabled = true;
12174 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
12175 this.ListManageMenuItem.Enabled = true;
12176 this.OpenFavOpMenuItem.Enabled = true;
12177 this.CreateTabRuleOpMenuItem.Enabled = true;
12178 this.CreateIdRuleOpMenuItem.Enabled = true;
12179 this.CreateSourceRuleOpMenuItem.Enabled = true;
12180 this.ReadOpMenuItem.Enabled = true;
12181 this.UnreadOpMenuItem.Enabled = true;
12184 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
12186 this.FavOpMenuItem.Enabled = false;
12187 this.UnFavOpMenuItem.Enabled = false;
12188 this.OpenStatusOpMenuItem.Enabled = false;
12189 this.OpenFavotterOpMenuItem.Enabled = false;
12190 this.ShowRelatedStatusesMenuItem2.Enabled = false;
12191 this.RtOpMenuItem.Enabled = false;
12192 this.RtUnOpMenuItem.Enabled = false;
12193 this.QtOpMenuItem.Enabled = false;
12194 this.FavoriteRetweetMenuItem.Enabled = false;
12195 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12199 this.FavOpMenuItem.Enabled = true;
12200 this.UnFavOpMenuItem.Enabled = true;
12201 this.OpenStatusOpMenuItem.Enabled = true;
12202 this.OpenFavotterOpMenuItem.Enabled = true;
12203 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
12207 this.RtOpMenuItem.Enabled = false; //公式RTは無効に
12208 this.RtUnOpMenuItem.Enabled = true;
12209 this.QtOpMenuItem.Enabled = true;
12210 this.FavoriteRetweetMenuItem.Enabled = false; //公式RTは無効に
12211 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12215 if (_curPost.IsProtect)
12217 this.RtOpMenuItem.Enabled = false;
12218 this.RtUnOpMenuItem.Enabled = false;
12219 this.QtOpMenuItem.Enabled = false;
12220 this.FavoriteRetweetMenuItem.Enabled = false;
12221 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12225 this.RtOpMenuItem.Enabled = true;
12226 this.RtUnOpMenuItem.Enabled = true;
12227 this.QtOpMenuItem.Enabled = true;
12228 this.FavoriteRetweetMenuItem.Enabled = true;
12229 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12234 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
12236 this.RefreshPrevOpMenuItem.Enabled = true;
12240 this.RefreshPrevOpMenuItem.Enabled = false;
12242 if (!this.ExistCurrentPost
12243 || _curPost.InReplyToStatusId == null)
12245 OpenRepSourceOpMenuItem.Enabled = false;
12249 OpenRepSourceOpMenuItem.Enabled = true;
12251 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12253 OpenRterHomeMenuItem.Enabled = false;
12257 OpenRterHomeMenuItem.Enabled = true;
12260 if (this.ExistCurrentPost)
12262 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
12266 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12268 ContextMenuTabProperty_Opening(sender, null);
12271 public Twitter TwitterInstance
12276 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12278 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
12280 _mySpDis3 = SplitContainer3.SplitterDistance;
12281 _modifySettingLocal = true;
12285 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12287 if (_statuses.RemovedTab.Count == 0)
12289 UndoRemoveTabMenuItem.Enabled = false;
12293 UndoRemoveTabMenuItem.Enabled = true;
12295 if (ListTab.SelectedTab != null)
12297 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12298 PublicSearchQueryMenuItem.Enabled = true;
12300 PublicSearchQueryMenuItem.Enabled = false;
12304 PublicSearchQueryMenuItem.Enabled = false;
12306 if (!this.ExistCurrentPost)
12308 this.CopySTOTMenuItem.Enabled = false;
12309 this.CopyURLMenuItem.Enabled = false;
12310 this.CopyUserIdStripMenuItem.Enabled = false;
12314 this.CopySTOTMenuItem.Enabled = true;
12315 this.CopyURLMenuItem.Enabled = true;
12316 this.CopyUserIdStripMenuItem.Enabled = true;
12317 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12318 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12322 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12324 SetNotifyIconText();
12327 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12329 var id = _curPost?.ScreenName ?? "";
12331 await this.ShowUserStatus(id);
12334 private async Task doShowUserStatus(string id, bool ShowInputDialog)
12336 TwitterUser user = null;
12338 if (ShowInputDialog)
12340 using (var inputName = new InputTabName())
12342 inputName.FormTitle = "Show UserStatus";
12343 inputName.FormDescription = Properties.Resources.FRMessage1;
12344 inputName.TabName = id;
12346 if (inputName.ShowDialog(this) != DialogResult.OK)
12348 if (string.IsNullOrWhiteSpace(inputName.TabName))
12351 id = inputName.TabName.Trim();
12355 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
12357 var cancellationToken = dialog.EnableCancellation();
12361 var task = Task.Run(() => this.tw.GetUserInfo(id));
12362 user = await dialog.WaitForAsync(this, task);
12364 catch (WebApiException ex)
12366 if (!cancellationToken.IsCancellationRequested)
12367 MessageBox.Show(ex.Message);
12371 if (cancellationToken.IsCancellationRequested)
12375 await this.doShowUserStatus(user);
12378 private async Task doShowUserStatus(TwitterUser user)
12380 using (var userDialog = new UserInfoDialog(this, this.tw))
12382 var showUserTask = userDialog.ShowUserAsync(user);
12383 userDialog.ShowDialog(this);
12386 this.BringToFront();
12388 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12389 await showUserTask;
12393 private Task ShowUserStatus(string id, bool ShowInputDialog)
12395 return this.doShowUserStatus(id, ShowInputDialog);
12398 private Task ShowUserStatus(string id)
12400 return this.doShowUserStatus(id, true);
12403 private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12405 if (NameLabel.Tag != null)
12407 string id = (string)NameLabel.Tag;
12408 if (id != tw.Username)
12410 await this.FollowCommand(id);
12415 private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12417 if (NameLabel.Tag != null)
12419 string id = (string)NameLabel.Tag;
12420 if (id != tw.Username)
12422 await this.RemoveCommand(id, false);
12427 private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12429 if (NameLabel.Tag != null)
12431 string id = (string)NameLabel.Tag;
12432 if (id != tw.Username)
12434 await this.ShowFriendship(id);
12439 private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12441 if (NameLabel.Tag != null)
12443 string id = (string)NameLabel.Tag;
12444 await this.ShowUserStatus(id, false);
12448 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12450 if (NameLabel.Tag != null)
12452 string id = (string)NameLabel.Tag;
12453 AddNewTabForUserTimeline(id);
12457 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12459 if (NameLabel.Tag != null)
12461 string id = (string)NameLabel.Tag;
12462 AddNewTabForSearch("@" + id);
12466 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
12468 if (_curPost != null)
12470 await this.ShowUserStatus(_curPost.ScreenName, false);
12474 private async void RtCountMenuItem_Click(object sender, EventArgs e)
12476 if (!this.ExistCurrentPost)
12479 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
12480 int retweetCount = 0;
12482 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
12484 var cancellationToken = dialog.EnableCancellation();
12488 var task = Task.Run(() => this.tw.GetStatus_Retweeted_Count(statusId));
12489 retweetCount = await dialog.WaitForAsync(this, task);
12491 catch (WebApiException ex)
12493 if (!cancellationToken.IsCancellationRequested)
12494 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + ex.Message);
12498 if (cancellationToken.IsCancellationRequested)
12502 MessageBox.Show(retweetCount + Properties.Resources.RtCountText1);
12505 private HookGlobalHotkey _hookGlobalHotkey;
12508 _hookGlobalHotkey = new HookGlobalHotkey(this);
12510 // この呼び出しは、Windows フォーム デザイナで必要です。
12511 InitializeComponent();
12513 // InitializeComponent() 呼び出しの後で初期化を追加します。
12515 if (!this.DesignMode)
12517 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12518 this.StatusText.Dock = DockStyle.Fill;
12521 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12522 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12523 this.gh.NotifyClicked += GrowlHelper_Callback;
12525 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12526 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12528 this.ImageSelector.Visible = false;
12529 this.ImageSelector.Enabled = false;
12530 this.ImageSelector.FilePickDialog = OpenFileDialog1;
12532 this.ReplaceAppName();
12533 this.InitializeShortcuts();
12536 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12538 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12541 this.Visible = false;
12543 else if (Form.ActiveForm == null)
12545 this.Visible = true;
12546 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12548 this.BringToFront();
12549 this.StatusText.Focus();
12553 private void UserPicture_MouseEnter(object sender, EventArgs e)
12555 this.UserPicture.Cursor = Cursors.Hand;
12558 private void UserPicture_MouseLeave(object sender, EventArgs e)
12560 this.UserPicture.Cursor = Cursors.Default;
12563 private async void UserPicture_DoubleClick(object sender, EventArgs e)
12565 if (NameLabel.Tag != null)
12567 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12571 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12573 this.MultiLineMenuItem.PerformClick();
12576 public PostClass CurPost
12578 get { return _curPost; }
12582 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12584 if (ImageSelector.Visible)
12585 ImageSelector.EndSelection();
12587 ImageSelector.BeginSelection();
12590 private void SelectMedia_DragEnter(DragEventArgs e)
12592 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12594 e.Effect = DragDropEffects.Copy;
12597 e.Effect = DragDropEffects.None;
12600 private void SelectMedia_DragDrop(DragEventArgs e)
12603 this.BringToFront();
12604 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12605 StatusText.Focus();
12608 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12610 TimelinePanel.Visible = false;
12611 TimelinePanel.Enabled = false;
12614 private void ImageSelector_EndSelecting(object sender, EventArgs e)
12616 TimelinePanel.Visible = true;
12617 TimelinePanel.Enabled = true;
12618 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12621 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12623 this.AllowDrop = false;
12626 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12628 this.AllowDrop = true;
12631 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12633 if (ImageSelector.Visible)
12635 _modifySettingCommon = true;
12636 SaveConfigsAll(true);
12638 if (ImageSelector.ServiceName.Equals("Twitter"))
12639 this.StatusText_TextChanged(null, null);
12643 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12645 this.StatusText_TextChanged(null, null);
12649 /// StatusTextでCtrl+Vが押下された時の処理
12651 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
12653 if (Clipboard.ContainsText())
12655 // clipboardにテキストがある場合は貼り付け処理
12656 this.StatusText.Paste(Clipboard.GetText());
12658 else if (Clipboard.ContainsImage())
12661 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
12662 Properties.Resources.PostPictureWarn4,
12663 MessageBoxButtons.OKCancel,
12664 MessageBoxIcon.Question,
12665 MessageBoxDefaultButton.Button2)
12666 == DialogResult.OK)
12668 // clipboardから画像を取得
12669 using (var image = Clipboard.GetImage())
12671 this.ImageSelector.BeginSelection(image);
12678 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12680 using (ListManage form = new ListManage(tw))
12682 form.ShowDialog(this);
12686 public bool ModifySettingCommon
12688 set { _modifySettingCommon = value; }
12691 public bool ModifySettingLocal
12693 set { _modifySettingLocal = value; }
12696 public bool ModifySettingAtId
12698 set { _modifySettingAtId = value; }
12701 private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12703 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12704 if (sourceUri != null && e.Button == MouseButtons.Left)
12706 await this.OpenUriInBrowserAsync(sourceUri.AbsoluteUri);
12710 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12712 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12713 if (sourceUri != null)
12715 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri);
12719 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12721 SetStatusLabelUrl();
12724 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12726 if (this.ExistCurrentPost && !_curPost.IsDm)
12727 RtCountMenuItem.Enabled = true;
12729 RtCountMenuItem.Enabled = false;
12731 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12732 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12734 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12737 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12742 private void CopyUserId()
12744 if (_curPost == null) return;
12745 string clstr = _curPost.ScreenName;
12748 Clipboard.SetDataObject(clstr, false, 5, 100);
12750 catch (Exception ex)
12752 MessageBox.Show(ex.Message);
12756 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12758 if (this.ExistCurrentPost && !_curPost.IsDm)
12762 await this.OpenRelatedTab(this._curPost);
12764 catch (TabException ex)
12766 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12772 /// 指定されたツイートに対する関連発言タブを開きます
12774 /// <param name="statusId">表示するツイートのID</param>
12775 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12776 private async Task OpenRelatedTab(long statusId)
12778 var post = this._statuses[statusId];
12783 post = await Task.Run(() => this.tw.GetStatusApi(false, statusId));
12785 catch (WebApiException ex)
12787 this.StatusLabel.Text = ex.Message;
12792 await this.OpenRelatedTab(post);
12796 /// 指定されたツイートに対する関連発言タブを開きます
12798 /// <param name="post">表示する対象となるツイート</param>
12799 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12800 private async Task OpenRelatedTab(PostClass post)
12802 var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12805 if (tabRelated == null)
12807 tabName = this._statuses.MakeTabName("Related Tweets");
12809 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12810 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12812 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12813 tabRelated.UnreadManage = false;
12814 tabRelated.Notify = false;
12818 tabName = tabRelated.TabName;
12821 tabRelated.RelationTargetPost = post;
12822 this.ClearTab(tabName, false);
12824 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12826 var tabPage = this.ListTab.TabPages[i];
12827 if (tabName == tabPage.Text)
12829 this.ListTab.SelectedIndex = i;
12834 await this.GetRelatedTweetsAsync(tabRelated);
12837 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12839 StringBuilder buf = new StringBuilder();
12840 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12841 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12842 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12843 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12844 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12847 private void tw_UserIdChanged()
12849 this._modifySettingCommon = true;
12852 #region "Userstream"
12853 private bool _isActiveUserstream = false;
12855 private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12859 if (InvokeRequired && !IsDisposed)
12861 Invoke((Action) (async () =>
12863 _statuses.RemovePostReserve(e.StatusId);
12864 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12866 this.PurgeListViewItemCache();
12867 ((DetailsListView)_curTab.Tag).Update();
12868 if (_curPost != null && _curPost.StatusId == e.StatusId)
12869 await this.DispSelectedPost(true);
12875 catch (ObjectDisposedException)
12879 catch (InvalidOperationException)
12885 private void tw_NewPostFromStream(object sender, EventArgs e)
12887 if (this._cfgCommon.ReadOldPosts)
12889 _statuses.SetReadHomeTab(); //新着時未読クリア
12892 int rsltAddCount = _statuses.DistributePosts();
12895 DateTime tm = DateTime.Now;
12896 if (_tlTimestamps.ContainsKey(tm))
12898 _tlTimestamps[tm] += rsltAddCount;
12902 _tlTimestamps.Add(tm, rsltAddCount);
12904 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
12905 List<DateTime> keys = new List<DateTime>();
12907 foreach (DateTime key in _tlTimestamps.Keys)
12909 if (key.CompareTo(oneHour) < 0)
12912 _tlCount += _tlTimestamps[key];
12914 foreach (DateTime key in keys)
12916 _tlTimestamps.Remove(key);
12920 //Static DateTime before = Now;
12921 //if (before.Subtract(Now).Seconds > -5) return;
12925 if (this._cfgCommon.UserstreamPeriod > 0) return;
12929 if (InvokeRequired && !IsDisposed)
12931 Invoke((Action)(async () =>
12933 await this.RefreshTasktrayIcon(true);
12934 this.RefreshTimeline(true);
12939 catch (ObjectDisposedException)
12943 catch (InvalidOperationException)
12949 private void tw_UserStreamStarted(object sender, EventArgs e)
12951 this._isActiveUserstream = true;
12954 if (InvokeRequired && !IsDisposed)
12956 Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12960 catch (ObjectDisposedException)
12964 catch (InvalidOperationException)
12969 MenuItemUserStream.Text = "&UserStream ▶";
12970 MenuItemUserStream.Enabled = true;
12971 StopToolStripMenuItem.Text = "&Stop";
12972 StopToolStripMenuItem.Enabled = true;
12974 StatusLabel.Text = "UserStream Started.";
12977 private void tw_UserStreamStopped(object sender, EventArgs e)
12979 this._isActiveUserstream = false;
12982 if (InvokeRequired && !IsDisposed)
12984 Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12988 catch (ObjectDisposedException)
12992 catch (InvalidOperationException)
12997 MenuItemUserStream.Text = "&UserStream ■";
12998 MenuItemUserStream.Enabled = true;
12999 StopToolStripMenuItem.Text = "&Start";
13000 StopToolStripMenuItem.Enabled = true;
13002 StatusLabel.Text = "UserStream Stopped.";
13005 private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
13009 if (InvokeRequired && !IsDisposed)
13011 Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
13015 catch (ObjectDisposedException)
13019 catch (InvalidOperationException)
13023 var ev = e.EventData;
13024 StatusLabel.Text = "Event: " + ev.Event;
13025 //if (ev.Event == "favorite")
13027 // NotifyFavorite(ev);
13030 if (ev.Event == "favorite" || ev.Event == "unfavorite")
13032 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
13034 this.PurgeListViewItemCache();
13035 ((DetailsListView)_curTab.Tag).Update();
13037 if (ev.Event == "unfavorite" && ev.Username.ToLower().Equals(tw.Username.ToLower()))
13039 RemovePostFromFavTab(new long[] {ev.Id});
13044 private void NotifyEvent(Twitter.FormattedEvent ev)
13047 if (BalloonRequired(ev))
13049 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13050 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
13051 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
13052 StringBuilder title = new StringBuilder();
13053 if (this._cfgCommon.DispUsername)
13055 title.Append(tw.Username);
13056 title.Append(" - ");
13062 title.Append(Application.ProductName);
13063 title.Append(" [");
13064 title.Append(ev.Event.ToUpper());
13065 title.Append("] by ");
13066 if (!string.IsNullOrEmpty(ev.Username))
13068 title.Append(ev.Username.ToString());
13072 //title.Append("");
13075 if (!string.IsNullOrEmpty(ev.Target))
13077 //NotifyIcon1.BalloonTipText = ev.Target;
13082 //NotifyIcon1.BalloonTipText = " ";
13085 //NotifyIcon1.ShowBalloonTip(500);
13086 if (this._cfgCommon.IsUseNotifyGrowl)
13088 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13089 ev.Id.ToString(), title.ToString(), text);
13093 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13094 NotifyIcon1.BalloonTipTitle = title.ToString();
13095 NotifyIcon1.BalloonTipText = text;
13096 NotifyIcon1.ShowBalloonTip(500);
13101 string snd = this._cfgCommon.EventSoundFile;
13102 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
13104 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13108 string dir = Application.StartupPath;
13109 if (Directory.Exists(Path.Combine(dir, "Sounds")))
13111 dir = Path.Combine(dir, "Sounds");
13113 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13125 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13127 MenuItemUserStream.Enabled = false;
13128 if (StopRefreshAllMenuItem.Checked)
13130 StopRefreshAllMenuItem.Checked = false;
13133 if (this._isActiveUserstream)
13135 tw.StopUserStream();
13139 tw.StartUserStream();
13143 private static string inputTrack = "";
13145 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13147 if (TrackToolStripMenuItem.Checked)
13149 using (InputTabName inputForm = new InputTabName())
13151 inputForm.TabName = inputTrack;
13152 inputForm.FormTitle = "Input track word";
13153 inputForm.FormDescription = "Track word";
13154 if (inputForm.ShowDialog() != DialogResult.OK)
13156 TrackToolStripMenuItem.Checked = false;
13159 inputTrack = inputForm.TabName.Trim();
13161 if (!inputTrack.Equals(tw.TrackWord))
13163 tw.TrackWord = inputTrack;
13164 this._modifySettingCommon = true;
13165 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13166 tw.ReconnectUserStream();
13172 tw.ReconnectUserStream();
13174 this._modifySettingCommon = true;
13177 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13179 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13180 this._modifySettingCommon = true;
13181 tw.ReconnectUserStream();
13184 private void EventViewerMenuItem_Click(object sender, EventArgs e)
13186 if (evtDialog == null || evtDialog.IsDisposed)
13189 evtDialog = new EventViewerDialog();
13190 evtDialog.Owner = this;
13192 Point pos = evtDialog.Location;
13193 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13194 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13195 evtDialog.Location = pos;
13197 evtDialog.EventSource = tw.StoredEvent;
13198 if (!evtDialog.Visible)
13200 evtDialog.Show(this);
13204 evtDialog.Activate();
13206 this.TopMost = this._cfgCommon.AlwaysTop;
13210 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13212 MyCommon._endingFlag = true;
13216 Application.Restart();
13220 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13224 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13226 if (!string.IsNullOrEmpty(tw.Username))
13227 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13230 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13232 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
13235 private async Task doTranslation(string str)
13237 if (string.IsNullOrEmpty(str))
13240 var bing = new Bing();
13243 var translatedText = await bing.TranslateAsync(str,
13245 langTo: this._cfgCommon.TranslateLanguage);
13247 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
13249 catch (HttpRequestException e)
13251 this.StatusLabel.Text = "Err:" + e.Message;
13255 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13257 if (!this.ExistCurrentPost)
13260 await this.doTranslation(this._curPost.TextFromApi);
13263 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13265 var text = this.PostBrowser.GetSelectedText();
13266 await this.doTranslation(text);
13269 private bool ExistCurrentPost
13273 if (_curPost == null) return false;
13274 if (_curPost.IsDeleted) return false;
13279 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13281 ShowUserTimeline();
13284 private string GetUserIdFromCurPostOrInput(string caption)
13286 var id = _curPost?.ScreenName ?? "";
13288 using (InputTabName inputName = new InputTabName())
13290 inputName.FormTitle = caption;
13291 inputName.FormDescription = Properties.Resources.FRMessage1;
13292 inputName.TabName = id;
13293 if (inputName.ShowDialog() == DialogResult.OK &&
13294 !string.IsNullOrEmpty(inputName.TabName.Trim()))
13296 id = inputName.TabName.Trim();
13306 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13308 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13309 if (!string.IsNullOrEmpty(id))
13311 AddNewTabForUserTimeline(id);
13315 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13317 string id = GetUserIdFromCurPostOrInput("Show Favstar");
13318 if (!string.IsNullOrEmpty(id))
13320 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13324 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13326 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13329 private void TimelineRefreshEnableChange(bool isEnable)
13333 tw.StartUserStream();
13337 tw.StopUserStream();
13339 TimerTimeline.Enabled = isEnable;
13342 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13344 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13347 private async Task OpenUserAppointUrl()
13349 if (this._cfgCommon.UserAppointUrl != null)
13351 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
13353 if (_curPost != null)
13355 string xUrl = this._cfgCommon.UserAppointUrl;
13356 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13358 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
13359 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
13361 await this.OpenUriInBrowserAsync(xUrl);
13366 await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
13371 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13373 await this.OpenUserAppointUrl();
13376 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13378 string selText = SourceLinkLabel.Text;
13381 Clipboard.SetDataObject(selText, false, 5, 100);
13383 catch (Exception ex)
13385 MessageBox.Show(ex.Message);
13389 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13391 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
13394 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
13396 catch (Exception ex)
13398 MessageBox.Show(ex.Message);
13402 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13404 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13406 SourceCopyMenuItem.Enabled = false;
13407 SourceUrlCopyMenuItem.Enabled = false;
13411 SourceCopyMenuItem.Enabled = true;
13412 SourceUrlCopyMenuItem.Enabled = true;
13416 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13418 if (Form.ActiveForm == null)
13420 this.BeginInvoke((Action) (() =>
13422 this.Visible = true;
13423 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13425 this.BringToFront();
13426 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13428 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13432 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13438 private void ReplaceAppName()
13440 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13441 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13444 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13446 this.SplitContainer3.Panel2Collapsed = false;
13448 // PreviewDistance が起動のたびに広がっていく問題の回避策
13449 // FixedPanel が Panel2 に設定された状態で Panel2 を開くと、初回だけ SplitterDistance が再計算されておかしくなるため、
13450 // None で開いた後に設定するようにする
13451 if (this.SplitContainer3.FixedPanel == FixedPanel.None)
13452 this.SplitContainer3.FixedPanel = FixedPanel.Panel2;
13455 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13457 await this.OpenThumbnailPicture(e.Thumbnail);
13460 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13462 await this.OpenUriInBrowserAsync(e.ImageUrl);
13465 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
13467 var url = thumbnail.FullSizeImageUrl ?? thumbnail.ImageUrl;
13469 await this.OpenUriInBrowserAsync(url);
13472 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13474 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
13477 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13479 if (e.KeyCode == Keys.Space)
13481 this.JumpUnreadMenuItem_Click(null, null);
13483 e.SuppressKeyPress = true;
13487 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13489 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13490 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13491 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13492 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13493 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13495 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13498 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13500 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13503 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13505 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13508 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13510 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13513 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13515 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13518 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13520 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13523 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13525 if (this._cfgCommon.IconSize == iconSize) return;
13527 var oldIconCol = _iconCol;
13529 this._cfgCommon.IconSize = iconSize;
13530 ApplyListViewIconSize(iconSize);
13532 if (_iconCol != oldIconCol)
13534 foreach (TabPage tp in ListTab.TabPages)
13536 ResetColumns((DetailsListView)tp.Tag);
13540 _curList?.Refresh();
13542 _modifySettingCommon = true;
13545 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13547 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13548 if (this._cfgCommon.SortOrderLock == state) return;
13550 this._cfgCommon.SortOrderLock = state;
13552 _modifySettingCommon = true;