1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
28 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
29 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
32 using System.Collections.Concurrent;
33 using System.Collections.Generic;
34 using System.ComponentModel;
35 using System.Diagnostics;
37 using System.Globalization;
42 using System.Net.Http;
43 using System.Reflection;
45 using System.Text.RegularExpressions;
46 using System.Threading;
47 using System.Threading.Tasks;
48 using System.Windows.Forms;
50 using OpenTween.Api.DataModel;
51 using OpenTween.Connection;
52 using OpenTween.Models;
53 using OpenTween.OpenTweenCustomControl;
54 using OpenTween.Thumbnail;
58 public partial class TweenMain : OTBaseForm
61 private Size _mySize; //画面サイズ
62 private Point _myLoc; //画面位置
63 private int _mySpDis; //区切り位置
64 private int _mySpDis2; //発言欄区切り位置
65 private int _mySpDis3; //プレビュー区切り位置
66 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
67 private bool _iconCol; //1列表示の時true(48サイズのとき)
70 private bool _initial; //true:起動時処理中
71 private bool _initialLayout = true;
72 private bool _ignoreConfigSave; //true:起動時処理中
73 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
74 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
75 private Point _tabMouseDownPoint;
76 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
77 private readonly object _syncObject = new object(); //ロック用
79 private const string detailHtmlFormatHeaderMono =
80 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
81 + "<style type=\"text/css\"><!-- "
82 + "body, p, pre {margin: 0;} "
83 + "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%);} "
84 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
85 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
86 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
87 + ".quote-tweet.reply {border-color: #f33;} "
88 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
90 + "</head><body><pre>";
91 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
92 private const string detailHtmlFormatHeaderColor =
93 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
94 + "<style type=\"text/css\"><!-- "
95 + "body, p, pre {margin: 0;} "
96 + "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%);} "
97 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
98 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
99 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
100 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
101 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
103 + "</head><body><p>";
104 private const string detailHtmlFormatFooterColor = "</p></body></html>";
105 private string detailHtmlFormatHeader;
106 private string detailHtmlFormatFooter;
108 private bool _myStatusError = false;
109 private bool _myStatusOnline = false;
110 private bool soundfileListup = false;
111 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
114 //private SettingToConfig _cfg; //旧
115 private SettingLocal _cfgLocal;
116 private SettingCommon _cfgCommon;
119 private TwitterApi twitterApi = new TwitterApi();
123 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
126 private SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
127 private OpenURL UrlDialog = new OpenURL();
128 public AtIdSupplement AtIdSupl; //@id補助
129 public AtIdSupplement HashSupl; //Hashtag補助
130 public HashtagManage HashMgr;
131 private EventViewerDialog evtDialog;
134 private Font _fntUnread; //未読用フォント
135 private Color _clUnread; //未読用文字色
136 private Font _fntReaded; //既読用フォント
137 private Color _clReaded; //既読用文字色
138 private Color _clFav; //Fav用文字色
139 private Color _clOWL; //片思い用文字色
140 private Color _clRetweet; //Retweet用文字色
141 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
142 private Font _fntDetail; //発言詳細部用フォント
143 private Color _clDetail; //発言詳細部用色
144 private Color _clDetailLink; //発言詳細部用リンク文字色
145 private Color _clDetailBackcolor; //発言詳細部用背景色
146 private Color _clSelf; //自分の発言用背景色
147 private Color _clAtSelf; //自分宛返信用背景色
148 private Color _clTarget; //選択発言者の他の発言用背景色
149 private Color _clAtTarget; //選択発言中の返信先用背景色
150 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
151 private Color _clAtTo; //選択発言の唯一@先
152 private Color _clListBackcolor; //リスト部通常発言背景色
153 private Color _clInputBackcolor; //入力欄背景色
154 private Color _clInputFont; //入力欄文字色
155 private Font _fntInputFont; //入力欄フォント
156 private ImageCache IconCache; //アイコン画像リスト
157 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
158 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
159 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
160 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
161 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
162 private Icon MainIcon; //Main.ico 画面左上のアイコン
163 private Icon ReplyIcon; //5g
164 private Icon ReplyIconBlink; //6g
166 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
168 private PostClass _anchorPost;
169 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
171 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
172 private int _hisIdx; //発言履歴カレントインデックス
174 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
175 private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
178 private List<DateTime> _postTimestamps = new List<DateTime>();
179 private List<DateTime> _favTimestamps = new List<DateTime>();
182 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
183 private SolidBrush _brsBackColorMine;
184 private SolidBrush _brsBackColorAt;
185 private SolidBrush _brsBackColorYou;
186 private SolidBrush _brsBackColorAtYou;
187 private SolidBrush _brsBackColorAtFromTarget;
188 private SolidBrush _brsBackColorAtTo;
189 private SolidBrush _brsBackColorNone;
190 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
191 private StringFormat sfTab = new StringFormat();
193 //////////////////////////////////////////////////////////////////////////////////////////////////////////
194 private TabInformations _statuses;
197 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
200 /// キャッシュクリアのために null が代入されることがあるため、
201 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
202 /// 一旦ローカル変数に代入してから参照すること。
204 private ListViewItemCache _listItemCache = null;
206 internal class ListViewItemCache
208 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
209 public ListView TargetList { get; set; }
211 /// <summary>キャッシュする範囲の開始インデックス</summary>
212 public int StartIndex { get; set; }
214 /// <summary>キャッシュする範囲の終了インデックス</summary>
215 public int EndIndex { get; set; }
217 /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
218 public ListViewItem[] ListItem { get; set; }
220 /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
221 public PostClass[] Post { get; set; }
223 /// <summary>キャッシュされたアイテムの件数</summary>
225 => this.EndIndex - this.StartIndex + 1;
227 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
228 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
229 public bool Contains(int index)
230 => index >= this.StartIndex && index <= this.EndIndex;
232 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
233 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
234 public bool IsSupersetOf(int rangeStart, int rangeEnd)
235 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
237 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
238 /// <returns>取得に成功すれば true、それ以外は false</returns>
239 public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
241 if (this.Contains(index))
243 item = this.ListItem[index - this.StartIndex];
244 post = this.Post[index - this.StartIndex];
256 private TabPage _curTab;
257 private int _curItemIndex;
258 private DetailsListView _curList;
259 private PostClass _curPost;
260 private bool _isColumnChanged = false;
262 private const int MAX_WORKER_THREADS = 20;
263 private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
264 private CancellationTokenSource workerCts = new CancellationTokenSource();
265 private IProgress<string> workerProgress;
267 private int UnreadCounter = -1;
268 private int UnreadAtCounter = -1;
270 private string[] ColumnOrgText = new string[9];
271 private string[] ColumnText = new string[9];
273 private bool _DoFavRetweetFlags = false;
274 private bool osResumed = false;
276 //////////////////////////////////////////////////////////////////////////////////////////////////////////
277 private string _postBrowserStatusText = "";
279 private bool _colorize = false;
281 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
283 private ImageListViewItem displayItem;
285 private string recommendedStatusFooter;
288 private struct urlUndo
290 public string Before;
294 private List<urlUndo> urlUndoBuffer = null;
296 private struct ReplyChain
298 public long OriginalId;
299 public long InReplyToId;
300 public TabPage OriginalTab;
302 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
304 this.OriginalId = originalId;
305 this.InReplyToId = inReplyToId;
306 this.OriginalTab = originalTab;
310 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
311 private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
314 private enum SEARCHTYPE
321 private class PostingStatus
323 public string status = "";
324 public long? inReplyToId = null;
325 public string inReplyToName = null;
326 public string imageService = ""; //画像投稿サービス名
327 public IMediaItem[] mediaItems = null;
328 public PostingStatus()
331 public PostingStatus(string status, long? replyToId, string replyToName)
333 this.status = status;
334 this.inReplyToId = replyToId;
335 this.inReplyToName = replyToName;
339 private void TweenMain_Activated(object sender, EventArgs e)
341 //画面がアクティブになったら、発言欄の背景色戻す
342 if (StatusText.Focused)
344 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
348 private bool disposed = false;
351 /// 使用中のリソースをすべてクリーンアップします。
353 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
354 protected override void Dispose(bool disposing)
356 base.Dispose(disposing);
363 this.components?.Dispose();
366 SearchDialog.Dispose();
369 NIconAtRed?.Dispose();
370 NIconAtSmoke?.Dispose();
371 foreach (var iconRefresh in this.NIconRefresh)
373 iconRefresh?.Dispose();
377 ReplyIcon?.Dispose();
378 ReplyIconBlink?.Dispose();
379 _listViewImageList.Dispose();
380 _brsHighLight.Dispose();
381 _brsBackColorMine?.Dispose();
382 _brsBackColorAt?.Dispose();
383 _brsBackColorYou?.Dispose();
384 _brsBackColorAtYou?.Dispose();
385 _brsBackColorAtFromTarget?.Dispose();
386 _brsBackColorAtTo?.Dispose();
387 _brsBackColorNone?.Dispose();
388 _brsDeactiveSelection?.Dispose();
392 this.workerCts.Cancel();
394 if (IconCache != null)
396 this.IconCache.CancelAsync();
397 this.IconCache.Dispose();
400 this.thumbnailTokenSource?.Dispose();
403 this.twitterApi.Dispose();
404 this._hookGlobalHotkey.Dispose();
407 // 終了時にRemoveHandlerしておかないとメモリリークする
408 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
409 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
411 this.disposed = true;
414 private void LoadIcons()
416 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
417 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
420 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
423 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
426 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
429 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
431 // タスクトレイ: オフライン時アイコン
432 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
434 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
435 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
436 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
438 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
439 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
440 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
441 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
442 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
444 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
446 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
447 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
448 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
449 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
450 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
452 if (iconReply != null && iconReplyBlink != null)
454 this.ReplyIcon = iconReply;
455 this.ReplyIconBlink = iconReplyBlink;
459 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
460 this.ReplyIconBlink = this.NIconAt;
463 if (iconRefresh1 == null)
465 this.NIconRefresh = new[] {
466 Properties.Resources.Refresh, Properties.Resources.Refresh2,
467 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
470 else if (iconRefresh2 == null)
472 this.NIconRefresh = new[] { iconRefresh1 };
474 else if (iconRefresh3 == null)
476 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
478 else if (iconRefresh4 == null)
480 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
482 else // iconRefresh1 から iconRefresh4 まで全て揃っている
484 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
488 private Icon LoadIcon(string filePath)
490 if (!File.Exists(filePath))
495 return new Icon(filePath);
503 private void InitColumns(ListView list, bool startup)
505 this.InitColumnText();
507 ColumnHeader[] columns = null;
514 new ColumnHeader(), // アイコン
515 new ColumnHeader(), // 本文
518 columns[0].Text = this.ColumnText[0];
519 columns[1].Text = this.ColumnText[2];
523 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
525 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
526 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
527 columns[0].DisplayIndex = 0;
528 columns[1].DisplayIndex = 1;
533 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
535 columns[idx].Width = curListColumn.Width;
536 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
545 new ColumnHeader(), // アイコン
546 new ColumnHeader(), // ニックネーム
547 new ColumnHeader(), // 本文
548 new ColumnHeader(), // 日付
549 new ColumnHeader(), // ユーザID
550 new ColumnHeader(), // 未読
551 new ColumnHeader(), // マーク&プロテクト
552 new ColumnHeader(), // ソース
555 foreach (var i in Enumerable.Range(0, columns.Length))
556 columns[i].Text = this.ColumnText[i];
560 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
562 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
563 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
564 columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
565 columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
566 columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
567 columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
568 columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
569 columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
571 var displayIndex = new[] {
572 this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
573 this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
574 this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
575 this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
578 foreach (var i in Enumerable.Range(0, displayIndex.Length))
580 columns[i].DisplayIndex = displayIndex[i];
586 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
588 columns[idx].Width = curListColumn.Width;
589 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
595 list.Columns.AddRange(columns);
603 foreach (var column in columns)
609 private void InitColumnText()
612 ColumnText[1] = Properties.Resources.AddNewTabText2;
613 ColumnText[2] = Properties.Resources.AddNewTabText3;
614 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
615 ColumnText[4] = Properties.Resources.AddNewTabText5;
618 ColumnText[7] = "Source";
620 ColumnOrgText[0] = "";
621 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
622 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
623 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
624 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
625 ColumnOrgText[5] = "";
626 ColumnOrgText[6] = "";
627 ColumnOrgText[7] = "Source";
630 switch (_statuses.SortMode)
632 case ComparerMode.Nickname: //ニックネーム
635 case ComparerMode.Data: //本文
638 case ComparerMode.Id: //時刻=発言Id
641 case ComparerMode.Name: //名前
644 case ComparerMode.Source: //Source
651 if (_statuses.SortOrder == SortOrder.Descending)
653 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
654 ColumnText[2] = ColumnOrgText[2] + "▾";
658 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
659 ColumnText[2] = ColumnOrgText[2] + "▴";
664 if (_statuses.SortOrder == SortOrder.Descending)
666 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
667 ColumnText[c] = ColumnOrgText[c] + "▾";
671 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
672 ColumnText[c] = ColumnOrgText[c] + "▴";
677 private void InitializeTraceFrag()
680 TraceOutToolStripMenuItem.Checked = true;
681 MyCommon.TraceFlag = true;
683 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
685 TraceOutToolStripMenuItem.Checked = true;
686 MyCommon.TraceFlag = true;
690 private void TweenMain_Load(object sender, EventArgs e)
692 _ignoreConfigSave = true;
693 this.Visible = false;
695 if (MyApplication.StartupOptions.ContainsKey("d"))
696 MyCommon.TraceFlag = true;
698 InitializeTraceFrag();
700 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
702 new InternetSecurityManager(PostBrowser);
703 this.PostBrowser.AllowWebBrowserDrop = false; // COMException を回避するため、ActiveX の初期化が終わってから設定する
705 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
706 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
708 Regex.CacheSize = 100;
711 _statuses = TabInformations.GetInstance();
715 this.Icon = MainIcon; //メインフォーム(TweenMain)
716 NotifyIcon1.Icon = NIconAt; //タスクトレイ
717 TabImage.Images.Add(TabIcon); //タブ見出し
719 //<<<<<<<<<設定関連>>>>>>>>>
723 // 現在の DPI と設定保存時の DPI との比を取得する
724 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
727 var fontUIGlobal = this._cfgLocal.FontUIGlobal;
728 if (fontUIGlobal != null)
730 OTBaseForm.GlobalFont = fontUIGlobal;
731 this.Font = fontUIGlobal;
735 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
737 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
738 this._cfgCommon.TimelinePeriod = 15;
740 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
741 this._cfgCommon.ReplyPeriod = 15;
743 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
744 this._cfgCommon.DMPeriod = 15;
746 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
747 this._cfgCommon.PubSearchPeriod = 30;
749 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
750 this._cfgCommon.UserTimelinePeriod = 15;
752 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
753 this._cfgCommon.ListsPeriod = 15;
756 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
757 this._cfgCommon.CountApi = 60;
758 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
759 this._cfgCommon.CountApiReply = 40;
761 if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
762 this._cfgCommon.MoreCountApi = 200;
763 if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
764 this._cfgCommon.FirstCountApi = 100;
766 if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
767 this._cfgCommon.FavoritesCountApi = 40;
768 if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
769 this._cfgCommon.ListCountApi = 100;
770 if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
771 this._cfgCommon.SearchCountApi = 100;
772 if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
773 this._cfgCommon.UserTimelineCountApi = 20;
775 //廃止サービスが選択されていた場合ux.nuへ読み替え
776 if (this._cfgCommon.AutoShortUrlFirst < 0)
777 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
779 TwitterApiConnection.RestApiBase = this._cfgCommon.TwitterApiBaseUri;
780 this.tw = new Twitter(this.twitterApi);
783 if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
784 tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
788 Networking.Initialize();
790 bool saveRequired = false;
791 bool firstRun = false;
793 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
794 if (string.IsNullOrEmpty(tw.Username))
799 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
800 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
801 string.IsNullOrEmpty(tw.Username))
803 Application.Exit(); //強制終了
809 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
810 Networking.SetWebProxy(this._cfgLocal.ProxyType,
811 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
812 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
813 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
815 TwitterApiConnection.RestApiBase = this._cfgCommon.TwitterApiBaseUri;
816 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
817 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
818 tw.TrackWord = this._cfgCommon.TrackWord;
819 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
820 tw.AllAtReply = this._cfgCommon.AllAtReply;
821 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
822 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
823 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
824 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
826 // アクセストークンが有効であるか確認する
827 // ここが Twitter API への最初のアクセスになるようにすること
830 this.tw.VerifyCredentials();
832 catch (WebApiException ex)
834 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
835 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
839 //プロキシ設定等の通信まわりの初期化が済んでから処理する
840 ThumbnailGenerator.InitializeGenerator();
842 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
843 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
844 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
846 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
849 ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
852 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
853 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
854 HashMgr = new HashtagManage(HashSupl,
855 _cfgCommon.HashTags.ToArray(),
856 _cfgCommon.HashSelected,
857 _cfgCommon.HashIsPermanent,
858 _cfgCommon.HashIsHead,
859 _cfgCommon.HashIsNotAddToAtReply);
860 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
863 this.IconCache = new ImageCache();
866 _fntUnread = this._cfgLocal.FontUnread;
867 _clUnread = this._cfgLocal.ColorUnread;
868 _fntReaded = this._cfgLocal.FontRead;
869 _clReaded = this._cfgLocal.ColorRead;
870 _clFav = this._cfgLocal.ColorFav;
871 _clOWL = this._cfgLocal.ColorOWL;
872 _clRetweet = this._cfgLocal.ColorRetweet;
873 _fntDetail = this._cfgLocal.FontDetail;
874 _clDetail = this._cfgLocal.ColorDetail;
875 _clDetailLink = this._cfgLocal.ColorDetailLink;
876 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
877 _clSelf = this._cfgLocal.ColorSelf;
878 _clAtSelf = this._cfgLocal.ColorAtSelf;
879 _clTarget = this._cfgLocal.ColorTarget;
880 _clAtTarget = this._cfgLocal.ColorAtTarget;
881 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
882 _clAtTo = this._cfgLocal.ColorAtTo;
883 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
884 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
885 _clInputFont = this._cfgLocal.ColorInputFont;
886 _fntInputFont = this._cfgLocal.FontInputFont;
888 _brsBackColorMine = new SolidBrush(_clSelf);
889 _brsBackColorAt = new SolidBrush(_clAtSelf);
890 _brsBackColorYou = new SolidBrush(_clTarget);
891 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
892 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
893 _brsBackColorAtTo = new SolidBrush(_clAtTo);
894 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
895 _brsBackColorNone = new SolidBrush(_clListBackcolor);
897 // StringFormatオブジェクトへの事前設定
898 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
899 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
900 //sf.FormatFlags = StringFormatFlags.LineLimit; //
901 sfTab.Alignment = StringAlignment.Center;
902 sfTab.LineAlignment = StringAlignment.Center;
904 InitDetailHtmlFormat();
906 //Regex statregex = new Regex("^0*");
907 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
909 _history.Add(new PostingStatus());
911 this.inReplyTo = null;
914 SearchDialog.Owner = this;
915 UrlDialog.Owner = this;
918 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
919 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
921 //新着取得時のリストスクロールをするか。trueならスクロールしない
922 ListLockMenuItem.Checked = _cfgCommon.ListLock;
923 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
925 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
926 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
928 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
929 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
932 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
933 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
934 _myLoc = _cfgLocal.FormLocation;
936 if (this.WindowState != FormWindowState.Minimized)
938 this.DesktopLocation = _cfgLocal.FormLocation;
939 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
940 bool outOfScreen = true;
941 if (Screen.AllScreens.Length == 1) //ハングするとの報告
943 foreach (Screen scr in Screen.AllScreens)
945 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
953 this.DesktopLocation = new Point(0, 0);
954 _myLoc = this.DesktopLocation;
958 this.TopMost = this._cfgCommon.AlwaysTop;
959 _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
960 _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
961 if (_cfgLocal.PreviewDistance == -1)
963 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
964 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
965 _cfgLocal.PreviewDistance = _mySpDis3;
969 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
971 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
972 //this.Tween_ClientSizeChanged(this, null);
973 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
974 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
976 StatusText.Font = _fntInputFont;
977 StatusText.ForeColor = _clInputFont;
979 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
980 this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
981 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
983 // NameLabel のフォントを OTBaseForm.GlobalFont に変更
984 this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
986 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
987 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
989 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
990 if (this._cfgCommon.UnreadManage == false)
992 ReadedStripMenuItem.Enabled = false;
993 UnreadStripMenuItem.Enabled = false;
998 DateTimeLabel.Text = "";
999 SourceLinkLabel.Text = "";
1001 //リンク先URL表示部の初期化(画面左下)
1002 StatusLabelUrl.Text = "";
1004 StatusLabel.Text = "";
1005 StatusLabel.AutoToolTip = false;
1006 StatusLabel.ToolTipText = "";
1008 lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
1010 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1011 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1012 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1013 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1015 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1016 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1017 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1018 this.SplitContainer2.Panel2.AccessibleName = "";
1020 ////////////////////////////////////////////////////////////////////////////////
1021 var sortOrder = (SortOrder)_cfgCommon.SortOrder;
1022 var mode = ComparerMode.Id;
1023 switch (_cfgCommon.SortColumn)
1025 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1029 mode = ComparerMode.Id; //Idソートに読み替え
1032 mode = ComparerMode.Nickname;
1035 mode = ComparerMode.Data;
1038 mode = ComparerMode.Id;
1041 mode = ComparerMode.Name;
1044 mode = ComparerMode.Source;
1047 _statuses.SetSortMode(mode, sortOrder);
1048 ////////////////////////////////////////////////////////////////////////////////
1050 ApplyListViewIconSize(this._cfgCommon.IconSize);
1052 //<<<<<<<<タブ関連>>>>>>>
1056 //デフォルトタブの存在チェック、ない場合には追加
1057 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1058 this._statuses.AddTab(new HomeTabModel());
1060 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1061 this._statuses.AddTab(new MentionsTabModel());
1063 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1064 this._statuses.AddTab(new DirectMessagesTabModel());
1066 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1067 this._statuses.AddTab(new FavoritesTabModel());
1069 if (this._statuses.GetTabByType<MuteTabModel>() == null)
1070 this._statuses.AddTab(new MuteTabModel());
1072 foreach (var tab in _statuses.Tabs.Values)
1075 if (tab.TabType == MyCommon.TabUsageType.Mute)
1078 if (!AddNewTab(tab, startup: true))
1079 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1082 _curTab = ListTab.SelectedTab;
1084 _curList = (DetailsListView)_curTab.Tag;
1086 if (this._cfgCommon.TabIconDisp)
1088 ListTab.DrawMode = TabDrawMode.Normal;
1092 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1093 ListTab.DrawItem += ListTab_DrawItem;
1094 ListTab.ImageList = null;
1097 if (this._cfgCommon.HotkeyEnabled)
1100 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1101 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1102 modKey |= HookGlobalHotkey.ModKeys.Alt;
1103 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1104 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1105 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1106 modKey |= HookGlobalHotkey.ModKeys.Shift;
1107 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1108 modKey |= HookGlobalHotkey.ModKeys.Win;
1110 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1113 if (this._cfgCommon.IsUseNotifyGrowl)
1116 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1118 SetMainWindowTitle();
1119 SetNotifyIconText();
1121 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1123 this.Visible = true;
1127 TimerTimeline.AutoReset = true;
1128 TimerTimeline.SynchronizingObject = this;
1130 TimerTimeline.Interval = 1000;
1131 TimerTimeline.Enabled = true;
1133 TimerRefreshIcon.Interval = 200;
1134 TimerRefreshIcon.Enabled = true;
1136 _ignoreConfigSave = false;
1137 this.TweenMain_Resize(null, null);
1138 if (saveRequired) SaveConfigsAll(false);
1140 foreach (var ua in this._cfgCommon.UserAccounts)
1142 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1144 ua.UserId = tw.UserId;
1151 // 初回起動時だけ右下のメニューを目立たせる
1152 HashStripSplitButton.ShowDropDown();
1156 private void InitDetailHtmlFormat()
1158 if (this._cfgCommon.IsMonospace)
1160 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1161 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1165 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1166 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1169 detailHtmlFormatHeader = detailHtmlFormatHeader
1170 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1171 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1172 .Replace("%FONT_COLOR%", _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString())
1173 .Replace("%LINK_COLOR%", _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString())
1174 .Replace("%BG_COLOR%", _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString())
1175 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1178 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1183 txt = ListTab.TabPages[e.Index].Text;
1190 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1191 if (e.State == DrawItemState.Selected)
1193 e.DrawFocusRectangle();
1198 if (_statuses.Tabs[txt].UnreadCount > 0)
1201 fore = System.Drawing.SystemBrushes.ControlText;
1205 fore = System.Drawing.SystemBrushes.ControlText;
1207 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1210 private void LoadConfig()
1212 _cfgCommon = SettingCommon.Load();
1213 SettingCommon.Instance = this._cfgCommon;
1214 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1216 _cfgCommon.UserAccounts = new List<UserAccount>();
1217 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1219 UserAccount account = new UserAccount();
1220 account.Username = _cfgCommon.UserName;
1221 account.UserId = _cfgCommon.UserId;
1222 account.Token = _cfgCommon.Token;
1223 account.TokenSecret = _cfgCommon.TokenSecret;
1225 _cfgCommon.UserAccounts.Add(account);
1229 _cfgLocal = SettingLocal.Load();
1231 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1232 if (_cfgLocal.ScaleDimension.IsEmpty)
1233 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1235 var tabsSetting = SettingTabs.Load().Tabs;
1236 foreach (var tabSetting in tabsSetting)
1239 switch (tabSetting.TabType)
1241 case MyCommon.TabUsageType.Home:
1242 tab = new HomeTabModel(tabSetting.TabName);
1244 case MyCommon.TabUsageType.Mentions:
1245 tab = new MentionsTabModel(tabSetting.TabName);
1247 case MyCommon.TabUsageType.DirectMessage:
1248 tab = new DirectMessagesTabModel(tabSetting.TabName);
1250 case MyCommon.TabUsageType.Favorites:
1251 tab = new FavoritesTabModel(tabSetting.TabName);
1253 case MyCommon.TabUsageType.UserDefined:
1254 tab = new FilterTabModel(tabSetting.TabName);
1256 case MyCommon.TabUsageType.UserTimeline:
1257 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1259 case MyCommon.TabUsageType.PublicSearch:
1260 tab = new PublicSearchTabModel(tabSetting.TabName)
1262 SearchWords = tabSetting.SearchWords,
1263 SearchLang = tabSetting.SearchLang,
1266 case MyCommon.TabUsageType.Lists:
1267 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1269 case MyCommon.TabUsageType.Mute:
1270 tab = new MuteTabModel(tabSetting.TabName);
1276 tab.UnreadManage = tabSetting.UnreadManage;
1277 tab.Protected = tabSetting.Protected;
1278 tab.Notify = tabSetting.Notify;
1279 tab.SoundFile = tabSetting.SoundFile;
1281 if (tab.IsDistributableTabType)
1283 var filterTab = (FilterTabModel)tab;
1284 filterTab.FilterArray = tabSetting.FilterArray;
1285 filterTab.FilterModified = false;
1288 if (this._statuses.ContainsTab(tab.TabName))
1289 tab.TabName = this._statuses.MakeTabName("MyTab");
1291 this._statuses.AddTab(tab);
1293 if (_statuses.Tabs.Count == 0)
1295 _statuses.AddTab(new HomeTabModel());
1296 _statuses.AddTab(new MentionsTabModel());
1297 _statuses.AddTab(new DirectMessagesTabModel());
1298 _statuses.AddTab(new FavoritesTabModel());
1302 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1304 if (!TimerTimeline.Enabled) return;
1308 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1310 private static int homeCounter = 0;
1311 private static int mentionCounter = 0;
1312 private static int dmCounter = 0;
1313 private static int pubSearchCounter = 0;
1314 private static int userTimelineCounter = 0;
1315 private static int listsCounter = 0;
1316 private static int usCounter = 0;
1317 private static int ResumeWait = 0;
1318 private static int refreshFollowers = 0;
1320 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1322 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1323 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1324 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1325 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1326 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1327 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1328 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1329 Interlocked.Increment(ref refreshFollowers);
1331 var refreshTasks = new List<Task>();
1334 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1336 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1337 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1338 refreshTasks.Add(this.GetHomeTimelineAsync());
1339 ResetTimers.Timeline = false;
1341 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1343 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1344 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1345 refreshTasks.Add(this.GetReplyAsync());
1346 ResetTimers.Reply = false;
1348 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1350 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1351 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1352 refreshTasks.Add(this.GetDirectMessagesAsync());
1353 ResetTimers.DirectMessage = false;
1355 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1357 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1358 if (!ResetTimers.PublicSearch)
1359 refreshTasks.Add(this.GetPublicSearchAllAsync());
1360 ResetTimers.PublicSearch = false;
1362 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1364 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1365 if (!ResetTimers.UserTimeline)
1366 refreshTasks.Add(this.GetUserTimelineAllAsync());
1367 ResetTimers.UserTimeline = false;
1369 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1371 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1372 if (!ResetTimers.Lists)
1373 refreshTasks.Add(this.GetListTimelineAllAsync());
1374 ResetTimers.Lists = false;
1376 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1378 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1379 if (this.tw.UserStreamActive)
1380 this.RefreshTimeline();
1381 ResetTimers.UserStream = false;
1383 if (refreshFollowers > 6 * 3600)
1385 Interlocked.Exchange(ref refreshFollowers, 0);
1386 refreshTasks.AddRange(new[]
1388 this.doGetFollowersMenu(),
1389 this.RefreshNoRetweetIdsAsync(),
1390 this.RefreshTwitterConfigurationAsync(),
1395 Interlocked.Increment(ref ResumeWait);
1396 if (ResumeWait > 30)
1399 Interlocked.Exchange(ref ResumeWait, 0);
1400 refreshTasks.AddRange(new[]
1402 this.GetHomeTimelineAsync(),
1403 this.GetReplyAsync(),
1404 this.GetDirectMessagesAsync(),
1405 this.GetPublicSearchAllAsync(),
1406 this.GetUserTimelineAllAsync(),
1407 this.GetListTimelineAllAsync(),
1408 this.doGetFollowersMenu(),
1409 this.RefreshTwitterConfigurationAsync(),
1414 await Task.WhenAll(refreshTasks);
1417 private void RefreshTimeline()
1419 // 現在表示中のタブのスクロール位置を退避
1420 var curListScroll = this.SaveListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text]);
1422 // 各タブのリスト上の選択位置などを退避
1423 var listSelections = this.SaveListViewSelection();
1426 PostClass[] notifyPosts;
1429 bool newMentionOrDm;
1431 addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1433 if (MyCommon._endingFlag) return;
1438 foreach (TabPage tab in ListTab.TabPages)
1440 DetailsListView lst = (DetailsListView)tab.Tag;
1441 TabModel tabInfo = _statuses.Tabs[tab.Text];
1442 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1444 using (ControlTransaction.Update(lst))
1446 if (lst.Equals(_curList))
1448 this.PurgeListViewItemCache();
1452 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1460 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
1463 if (tabInfo.UnreadCount > 0)
1464 if (this._cfgCommon.TabIconDisp)
1465 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1467 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1471 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1476 this.RestoreListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text], curListScroll);
1479 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1481 SetMainWindowTitle();
1482 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1484 HashSupl.AddRangeItem(tw.GetHashList());
1488 internal struct ListViewScroll
1490 public ScrollLockMode ScrollLockMode { get; set; }
1491 public long? TopItemStatusId { get; set; }
1494 internal enum ScrollLockMode
1496 /// <summary>固定しない</summary>
1499 /// <summary>最上部に固定する</summary>
1502 /// <summary>最下部に固定する</summary>
1505 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1510 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1512 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1514 var listScroll = new ListViewScroll
1516 ScrollLockMode = this.GetScrollLockMode(listView),
1519 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1521 var topItem = listView.TopItem;
1522 if (topItem != null)
1523 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItem.Index);
1529 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1531 if (this._statuses.SortMode == ComparerMode.Id)
1533 if (this._statuses.SortOrder == SortOrder.Ascending)
1536 if (this.ListLockMenuItem.Checked)
1537 return ScrollLockMode.None;
1539 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1542 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1543 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1544 return ScrollLockMode.FixedToBottom;
1546 return ScrollLockMode.None;
1551 if (this.ListLockMenuItem.Checked)
1552 return ScrollLockMode.FixedToItem;
1554 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1555 var topItem = listView.TopItem;
1556 if (topItem == null || topItem.Index == 0)
1557 return ScrollLockMode.FixedToTop;
1559 return ScrollLockMode.FixedToItem;
1564 return ScrollLockMode.FixedToItem;
1568 internal struct ListViewSelection
1570 public long[] SelectedStatusIds { get; set; }
1571 public long? SelectionMarkStatusId { get; set; }
1572 public long? FocusedStatusId { get; set; }
1576 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1578 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1580 var listsDict = new Dictionary<string, ListViewSelection>();
1582 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1584 var listView = (DetailsListView)tabPage.Tag;
1585 var tab = _statuses.Tabs[tabPage.Text];
1587 ListViewSelection listStatus;
1588 if (listView.VirtualListSize != 0)
1590 listStatus = new ListViewSelection
1592 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1593 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1594 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1599 listStatus = new ListViewSelection
1601 SelectedStatusIds = new long[0],
1602 SelectionMarkStatusId = null,
1603 FocusedStatusId = null,
1607 listsDict[tab.TabName] = listStatus;
1613 private long[] GetSelectedStatusIds(DetailsListView listView, TabModel tab)
1615 var selectedIndices = listView.SelectedIndices;
1616 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1617 return tab.GetStatusIdAt(selectedIndices.Cast<int>());
1622 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1624 var focusedItem = listView.FocusedItem;
1626 return focusedItem != null ? tab.GetStatusIdAt(focusedItem.Index) : (long?)null;
1629 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1631 var selectionMarkIndex = listView.SelectionMark;
1633 return selectionMarkIndex != -1 ? tab.GetStatusIdAt(selectionMarkIndex) : (long?)null;
1637 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1639 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1641 if (listView.VirtualListSize == 0)
1644 switch (listScroll.ScrollLockMode)
1646 case ScrollLockMode.FixedToTop:
1647 listView.EnsureVisible(0);
1649 case ScrollLockMode.FixedToBottom:
1650 listView.EnsureVisible(listView.VirtualListSize - 1);
1652 case ScrollLockMode.FixedToItem:
1653 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1655 listView.TopItem = listView.Items[topIndex];
1657 case ScrollLockMode.None:
1664 /// <see cref="SaveListViewStatus"/> によって保存された選択状態を復元します
1666 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1668 // status_id から ListView 上のインデックスに変換
1669 int[] selectedIndices = null;
1670 if (listSelection.SelectedStatusIds != null)
1671 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1673 var focusedIndex = -1;
1674 if (listSelection.FocusedStatusId != null)
1675 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1677 var selectionMarkIndex = -1;
1678 if (listSelection.SelectionMarkStatusId != null)
1679 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1681 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1684 private bool BalloonRequired()
1686 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1687 ev.Eventtype = MyCommon.EVENTTYPE.None;
1689 return BalloonRequired(ev);
1692 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1694 if (type == MyCommon.EVENTTYPE.None)
1697 if (!this._cfgCommon.EventNotifyEnabled)
1700 return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1703 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1708 return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1711 private bool BalloonRequired(Twitter.FormattedEvent ev)
1716 if (NativeMethods.IsScreenSaverRunning())
1720 if (!this.NewPostPopMenuItem.Checked)
1722 // 「新着通知が無効でもイベントを通知する」にも該当しない
1723 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1727 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1728 if (this._cfgCommon.LimitBalloon)
1730 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1734 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1737 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1739 if (this._cfgCommon.ReadOwnPost)
1741 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1746 if (BalloonRequired())
1748 if (notifyPosts != null && notifyPosts.Length > 0)
1750 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1751 if (this._cfgCommon.IsUseNotifyGrowl)
1753 StringBuilder sb = new StringBuilder();
1757 foreach (PostClass post in notifyPosts)
1759 if (!(notifyPosts.Length > 3))
1765 if (post.IsReply && !post.IsExcludeReply) reply = true;
1766 if (post.IsDm) dm = true;
1767 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1768 switch (this._cfgCommon.NameBalloon)
1770 case MyCommon.NameBalloonEnum.UserID:
1771 sb.Append(post.ScreenName).Append(" : ");
1773 case MyCommon.NameBalloonEnum.NickName:
1774 sb.Append(post.Nickname).Append(" : ");
1777 sb.Append(post.TextFromApi);
1778 if (notifyPosts.Length > 3)
1780 if (notifyPosts.Last() != post) continue;
1783 StringBuilder title = new StringBuilder();
1784 GrowlHelper.NotifyType nt;
1785 if (this._cfgCommon.DispUsername)
1787 title.Append(tw.Username);
1788 title.Append(" - ");
1796 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1797 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1798 title.Append(Application.ProductName);
1799 title.Append(" [DM] ");
1800 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1801 nt = GrowlHelper.NotifyType.DirectMessage;
1805 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1806 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1807 title.Append(Application.ProductName);
1808 title.Append(" [Reply!] ");
1809 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1810 nt = GrowlHelper.NotifyType.Reply;
1814 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1815 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1816 title.Append(Application.ProductName);
1818 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1819 nt = GrowlHelper.NotifyType.Notify;
1821 string bText = sb.ToString();
1822 if (string.IsNullOrEmpty(bText)) return;
1824 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1825 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1830 StringBuilder sb = new StringBuilder();
1833 foreach (PostClass post in notifyPosts)
1835 if (post.IsReply && !post.IsExcludeReply) reply = true;
1836 if (post.IsDm) dm = true;
1837 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1838 switch (this._cfgCommon.NameBalloon)
1840 case MyCommon.NameBalloonEnum.UserID:
1841 sb.Append(post.ScreenName).Append(" : ");
1843 case MyCommon.NameBalloonEnum.NickName:
1844 sb.Append(post.Nickname).Append(" : ");
1847 sb.Append(post.TextFromApi);
1850 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1851 StringBuilder title = new StringBuilder();
1853 if (this._cfgCommon.DispUsername)
1855 title.Append(tw.Username);
1856 title.Append(" - ");
1864 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1865 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1866 ntIcon = ToolTipIcon.Warning;
1867 title.Append(Application.ProductName);
1868 title.Append(" [DM] ");
1869 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1873 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1874 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1875 ntIcon = ToolTipIcon.Warning;
1876 title.Append(Application.ProductName);
1877 title.Append(" [Reply!] ");
1878 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1882 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1883 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1884 ntIcon = ToolTipIcon.Info;
1885 title.Append(Application.ProductName);
1887 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1889 string bText = sb.ToString();
1890 if (string.IsNullOrEmpty(bText)) return;
1891 //NotifyIcon1.BalloonTipText = sb.ToString();
1892 //NotifyIcon1.ShowBalloonTip(500);
1893 NotifyIcon1.BalloonTipTitle = title.ToString();
1894 NotifyIcon1.BalloonTipText = bText;
1895 NotifyIcon1.BalloonTipIcon = ntIcon;
1896 NotifyIcon1.ShowBalloonTip(500);
1902 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1906 string dir = Application.StartupPath;
1907 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1909 dir = Path.Combine(dir, "Sounds");
1911 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1921 //mentions新着時に画面ブリンク
1922 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1924 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1928 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1930 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1932 _curItemIndex = _curList.SelectedIndices[0];
1933 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1937 this._curPost = GetCurTabPost(_curItemIndex);
1939 catch (ArgumentException)
1944 this.PushSelectPostChain();
1946 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1948 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1954 private void ChangeCacheStyleRead(bool Read, int Index)
1956 var tabInfo = _statuses.Tabs[_curTab.Text];
1957 //Read:true=既読 false=未読
1958 //未読管理していなかったら既読として扱う
1959 if (!tabInfo.UnreadManage ||
1960 !this._cfgCommon.UnreadManage) Read = true;
1962 var listCache = this._listItemCache;
1963 if (listCache == null)
1966 // キャッシュに含まれていないアイテムは対象外
1969 if (!listCache.TryGetValue(Index, out itm, out post))
1972 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1975 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1982 Item.SubItems[5].Text = "";
1987 Item.SubItems[5].Text = "★";
1993 else if (Post.RetweetedId != null)
1995 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1997 else if (Read || !this._cfgCommon.UseUnreadStyle)
2002 if (DList == null || Item.Index == -1)
2004 Item.ForeColor = cl;
2005 if (this._cfgCommon.UseUnreadStyle)
2011 if (this._cfgCommon.UseUnreadStyle)
2012 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2014 DList.ChangeItemForeColor(Item.Index, cl);
2015 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2019 private void ColorizeList()
2021 //Index:更新対象のListviewItem.Index。Colorを返す。
2022 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2025 _post = _anchorPost;
2029 if (_post == null) return;
2031 var listCache = this._listItemCache;
2032 if (listCache == null)
2035 var index = listCache.StartIndex;
2036 foreach (var cachedPost in listCache.Post)
2038 var backColor = this.JudgeColor(_post, cachedPost);
2039 this._curList.ChangeItemBackColor(index++, backColor);
2043 private void ColorizeList(ListViewItem Item, int Index)
2045 //Index:更新対象のListviewItem.Index。Colorを返す。
2046 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2049 _post = _anchorPost;
2053 PostClass tPost = GetCurTabPost(Index);
2055 if (_post == null) return;
2057 if (Item.Index == -1)
2058 Item.BackColor = JudgeColor(_post, tPost);
2060 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2063 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2066 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2069 else if (TargetPost.IsMe)
2072 else if (TargetPost.IsReply)
2075 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2077 cl = _clAtFromTarget;
2078 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2081 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2086 cl = _clListBackcolor;
2091 private async void PostButton_Click(object sender, EventArgs e)
2093 if (StatusText.Text.Trim().Length == 0)
2095 if (!ImageSelector.Enabled)
2097 await this.DoRefresh();
2102 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2104 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2106 MessageBoxButtons.YesNoCancel,
2107 MessageBoxIcon.Question);
2110 case DialogResult.Yes:
2111 StatusText.Text = "";
2112 await this.doReTweetOfficial(false);
2114 case DialogResult.Cancel:
2119 var inReplyToStatusId = this.inReplyTo?.Item1;
2120 var inReplyToScreenName = this.inReplyTo?.Item2;
2121 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2123 if (this._cfgCommon.Nicoms)
2125 StatusText.SelectionStart = StatusText.Text.Length;
2126 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2128 //if (SettingDialog.UrlConvertAuto)
2130 // StatusText.SelectionStart = StatusText.Text.Length;
2131 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2133 //else if (SettingDialog.Nicoms)
2135 // StatusText.SelectionStart = StatusText.Text.Length;
2136 // UrlConvert(UrlConverter.Nicoms);
2138 StatusText.SelectionStart = StatusText.Text.Length;
2139 CheckReplyTo(StatusText.Text);
2141 var statusText = this.FormatStatusText(this.StatusText.Text);
2143 if (this.GetRestStatusCount(statusText) < 0)
2145 // 文字数制限を超えているが強制的に投稿するか
2146 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2147 if (ret != DialogResult.OK)
2151 var status = new PostingStatus();
2152 status.status = statusText;
2154 status.inReplyToId = this.inReplyTo?.Item1;
2155 status.inReplyToName = this.inReplyTo?.Item2;
2156 if (ImageSelector.Visible)
2159 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2163 this.inReplyTo = null;
2164 StatusText.Text = "";
2165 _history.Add(new PostingStatus());
2166 _hisIdx = _history.Count - 1;
2167 if (!ToolStripFocusLockMenuItem.Checked)
2168 ((Control)ListTab.SelectedTab.Tag).Focus();
2169 urlUndoBuffer = null;
2170 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2173 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2175 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2176 await this.OpenUriInBrowserAsync(tmp);
2179 await this.PostMessageAsync(status);
2182 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2184 MyCommon._endingFlag = true;
2188 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2190 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2192 //_endingFlag=false:フォームの×ボタン
2194 this.Visible = false;
2198 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2199 _ignoreConfigSave = true;
2200 MyCommon._endingFlag = true;
2201 TimerTimeline.Enabled = false;
2202 TimerRefreshIcon.Enabled = false;
2206 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2208 this.Visible = true;
2209 if (this.WindowState == FormWindowState.Minimized)
2211 this.WindowState = FormWindowState.Normal;
2214 this.BringToFront();
2217 private static int errorCount = 0;
2219 private static bool CheckAccountValid()
2221 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2227 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2236 private Task GetHomeTimelineAsync()
2238 return this.GetHomeTimelineAsync(loadMore: false);
2241 private async Task GetHomeTimelineAsync(bool loadMore)
2243 await this.workerSemaphore.WaitAsync();
2247 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
2248 await homeTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2250 this.RefreshTimeline();
2252 catch (WebApiException ex)
2254 this._myStatusError = true;
2255 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2259 this.workerSemaphore.Release();
2263 private Task GetReplyAsync()
2265 return this.GetReplyAsync(loadMore: false);
2268 private async Task GetReplyAsync(bool loadMore)
2270 await this.workerSemaphore.WaitAsync();
2274 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
2275 await replyTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2277 this.RefreshTimeline();
2279 catch (WebApiException ex)
2281 this._myStatusError = true;
2282 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2286 this.workerSemaphore.Release();
2290 private Task GetDirectMessagesAsync()
2292 return this.GetDirectMessagesAsync(loadMore: false);
2295 private async Task GetDirectMessagesAsync(bool loadMore)
2297 await this.workerSemaphore.WaitAsync();
2301 var dmTab = this._statuses.GetTabByType<DirectMessagesTabModel>();
2302 await dmTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2304 this.RefreshTimeline();
2306 catch (WebApiException ex)
2308 this._myStatusError = true;
2309 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2313 this.workerSemaphore.Release();
2317 private Task GetFavoritesAsync()
2319 return this.GetFavoritesAsync(loadMore: false);
2322 private async Task GetFavoritesAsync(bool loadMore)
2324 await this.workerSemaphore.WaitAsync();
2328 var favTab = this._statuses.GetTabByType<FavoritesTabModel>();
2329 await favTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2331 this.RefreshTimeline();
2333 catch (WebApiException ex)
2335 this._myStatusError = true;
2336 this.StatusLabel.Text = ex.Message;
2340 this.workerSemaphore.Release();
2344 private Task GetPublicSearchAllAsync()
2346 var tabs = this._statuses.GetTabsByType<PublicSearchTabModel>();
2348 return this.GetPublicSearchAsync(tabs, loadMore: false);
2351 private Task GetPublicSearchAsync(PublicSearchTabModel tab)
2353 return this.GetPublicSearchAsync(tab, loadMore: false);
2356 private Task GetPublicSearchAsync(PublicSearchTabModel tab, bool loadMore)
2358 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2361 private async Task GetPublicSearchAsync(IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2363 await this.workerSemaphore.WaitAsync();
2367 foreach (var tab in tabs)
2368 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2370 this.RefreshTimeline();
2372 catch (WebApiException ex)
2374 this._myStatusError = true;
2375 this.StatusLabel.Text = ex.Message;
2379 this.workerSemaphore.Release();
2383 private Task GetUserTimelineAllAsync()
2385 var tabs = this._statuses.GetTabsByType<UserTimelineTabModel>();
2387 return this.GetUserTimelineAsync(tabs, loadMore: false);
2390 private Task GetUserTimelineAsync(UserTimelineTabModel tab)
2392 return this.GetUserTimelineAsync(tab, loadMore: false);
2395 private Task GetUserTimelineAsync(UserTimelineTabModel tab, bool loadMore)
2397 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2400 private async Task GetUserTimelineAsync(IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2402 await this.workerSemaphore.WaitAsync();
2406 foreach (var tab in tabs)
2407 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2409 this.RefreshTimeline();
2411 catch (WebApiException ex)
2413 this._myStatusError = true;
2414 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2418 this.workerSemaphore.Release();
2422 private Task GetListTimelineAllAsync()
2424 var tabs = this._statuses.GetTabsByType<ListTimelineTabModel>();
2426 return this.GetListTimelineAsync(tabs, loadMore: false);
2429 private Task GetListTimelineAsync(ListTimelineTabModel tab)
2431 return this.GetListTimelineAsync(tab, loadMore: false);
2434 private Task GetListTimelineAsync(ListTimelineTabModel tab, bool loadMore)
2436 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2439 private async Task GetListTimelineAsync(IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2441 await this.workerSemaphore.WaitAsync();
2445 foreach (var tab in tabs)
2446 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2448 this.RefreshTimeline();
2450 catch (WebApiException ex)
2452 this._myStatusError = true;
2453 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2457 this.workerSemaphore.Release();
2461 private async Task GetRelatedTweetsAsync(RelatedPostsTabModel tab)
2463 await this.workerSemaphore.WaitAsync();
2467 await tab.RefreshAsync(this.tw, this._initial, this.workerProgress);
2469 this.RefreshTimeline();
2471 catch (WebApiException ex)
2473 this._myStatusError = true;
2474 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2478 this.workerSemaphore.Release();
2482 private async Task FavAddAsync(long statusId, TabModel tab)
2484 await this.workerSemaphore.WaitAsync();
2488 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2490 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2492 catch (WebApiException ex)
2494 this._myStatusError = true;
2495 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2499 this.workerSemaphore.Release();
2503 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2505 if (ct.IsCancellationRequested)
2508 if (!CheckAccountValid())
2509 throw new WebApiException("Auth error. Check your account");
2512 if (!tab.Posts.TryGetValue(statusId, out post))
2518 await Task.Run(async () =>
2520 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2524 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2526 .ConfigureAwait(false);
2528 if (this._cfgCommon.RestrictFavCheck)
2530 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2531 .ConfigureAwait(false);
2533 if (status.Favorited != true)
2534 throw new WebApiException("NG(Restricted?)");
2537 this._favTimestamps.Add(DateTime.Now);
2540 if (this._statuses.ContainsKey(statusId))
2542 var postTl = this._statuses[statusId];
2543 postTl.IsFav = true;
2545 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2546 favTab.AddPostQueue(postTl);
2549 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2550 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2552 if (tb.Contains(statusId))
2553 tb.Posts[statusId].IsFav = true;
2556 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2558 catch (WebApiException)
2560 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2565 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2566 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2568 if (this._favTimestamps[i] < oneHour)
2569 this._favTimestamps.RemoveAt(i);
2572 this._statuses.DistributePosts();
2575 if (ct.IsCancellationRequested)
2578 this.RefreshTimeline();
2580 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2582 using (ControlTransaction.Update(this._curList))
2584 var idx = tab.IndexOf(statusId);
2586 this.ChangeCacheStyleRead(post.IsRead, idx);
2589 if (statusId == this._curPost.StatusId)
2590 await this.DispSelectedPost(true); // 選択アイテム再表示
2594 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2596 await this.workerSemaphore.WaitAsync();
2600 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2602 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2604 catch (WebApiException ex)
2606 this._myStatusError = true;
2607 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2611 this.workerSemaphore.Release();
2615 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2617 if (ct.IsCancellationRequested)
2620 if (!CheckAccountValid())
2621 throw new WebApiException("Auth error. Check your account");
2623 var successIds = new List<long>();
2625 await Task.Run(async () =>
2629 var failedCount = 0;
2630 foreach (var statusId in statusIds)
2634 var post = tab.Posts[statusId];
2636 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2643 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2645 .ConfigureAwait(false);
2647 catch (WebApiException)
2653 successIds.Add(statusId);
2654 post.IsFav = false; // リスト再描画必要
2656 if (this._statuses.ContainsKey(statusId))
2658 this._statuses[statusId].IsFav = false;
2661 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2662 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2664 if (tb.Contains(statusId))
2665 tb.Posts[statusId].IsFav = false;
2670 if (ct.IsCancellationRequested)
2673 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2674 foreach (var statusId in successIds)
2676 // ツイートが削除された訳ではないので IsDeleted はセットしない
2677 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2680 this.RefreshTimeline();
2682 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2684 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2690 using (ControlTransaction.Update(this._curList))
2692 foreach (var statusId in successIds)
2694 var idx = tab.IndexOf(statusId);
2698 var post = tab.Posts[statusId];
2699 this.ChangeCacheStyleRead(post.IsRead, idx);
2703 if (successIds.Contains(this._curPost.StatusId))
2704 await this.DispSelectedPost(true); // 選択アイテム再表示
2709 private async Task PostMessageAsync(PostingStatus status)
2711 await this.workerSemaphore.WaitAsync();
2715 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2717 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
2719 catch (WebApiException ex)
2721 this._myStatusError = true;
2722 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2726 this.workerSemaphore.Release();
2730 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
2732 if (ct.IsCancellationRequested)
2735 if (!CheckAccountValid())
2736 throw new WebApiException("Auth error. Check your account");
2738 p.Report("Posting...");
2744 await Task.Run(async () =>
2746 if (status.mediaItems == null || status.mediaItems.Length == 0)
2748 await this.tw.PostStatus(status.status, status.inReplyToId)
2749 .ConfigureAwait(false);
2753 var service = ImageSelector.GetService(status.imageService);
2754 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
2755 .ConfigureAwait(false);
2759 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2761 catch (WebApiException ex)
2763 // 処理は中断せずエラーの表示のみ行う
2764 errMsg = $"Err:{ex.Message}(PostMessage)";
2766 this._myStatusError = true;
2770 // 使い終わった MediaItem は破棄する
2771 if (status.mediaItems != null)
2773 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
2775 disposableItem.Dispose();
2780 if (ct.IsCancellationRequested)
2783 if (!string.IsNullOrEmpty(errMsg) &&
2784 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2785 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2787 var ret = MessageBox.Show(
2789 "{0} ---> [ " + errMsg + " ]" + Environment.NewLine +
2790 "\"" + status.status + "\"" + Environment.NewLine +
2792 Properties.Resources.StatusUpdateFailed1,
2793 Properties.Resources.StatusUpdateFailed2),
2794 "Failed to update status",
2795 MessageBoxButtons.RetryCancel,
2796 MessageBoxIcon.Question);
2798 if (ret == DialogResult.Retry)
2800 await this.PostMessageAsync(status);
2804 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2805 if (this.ToolStripFocusLockMenuItem.Checked)
2806 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2811 this._postTimestamps.Add(DateTime.Now);
2813 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2814 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2816 if (this._postTimestamps[i] < oneHour)
2817 this._postTimestamps.RemoveAt(i);
2820 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2822 this.HashMgr.ClearHashtag();
2823 this.HashStripSplitButton.Text = "#[-]";
2824 this.HashToggleMenuItem.Checked = false;
2825 this.HashToggleToolStripMenuItem.Checked = false;
2828 this.SetMainWindowTitle();
2830 if (this._cfgCommon.PostAndGet)
2832 if (this.tw.UserStreamActive)
2833 this.RefreshTimeline();
2835 await this.GetHomeTimelineAsync();
2839 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2841 await this.workerSemaphore.WaitAsync();
2845 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2847 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2849 catch (WebApiException ex)
2851 this._myStatusError = true;
2852 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2856 this.workerSemaphore.Release();
2860 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2862 if (ct.IsCancellationRequested)
2865 if (!CheckAccountValid())
2866 throw new WebApiException("Auth error. Check your account");
2869 if (!this._cfgCommon.UnreadManage)
2872 read = this._initial && this._cfgCommon.Read;
2874 p.Report("Posting...");
2876 var retweetTasks = from statusId in statusIds
2877 select this.tw.PostRetweet(statusId, read);
2879 await Task.WhenAll(retweetTasks)
2880 .ConfigureAwait(false);
2882 if (ct.IsCancellationRequested)
2885 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2887 this._postTimestamps.Add(DateTime.Now);
2889 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2890 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2892 if (this._postTimestamps[i] < oneHour)
2893 this._postTimestamps.RemoveAt(i);
2896 if (this._cfgCommon.PostAndGet && !this.tw.UserStreamActive)
2897 await this.GetHomeTimelineAsync();
2900 private async Task RefreshFollowerIdsAsync()
2902 await this.workerSemaphore.WaitAsync();
2905 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2907 await this.tw.RefreshFollowerIds();
2909 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2911 this.RefreshTimeline();
2912 this.PurgeListViewItemCache();
2913 this._curList?.Refresh();
2915 catch (WebApiException ex)
2917 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2921 this.workerSemaphore.Release();
2925 private async Task RefreshNoRetweetIdsAsync()
2927 await this.workerSemaphore.WaitAsync();
2930 await this.tw.RefreshNoRetweetIds();
2932 this.StatusLabel.Text = "NoRetweetIds refreshed";
2934 catch (WebApiException ex)
2936 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2940 this.workerSemaphore.Release();
2944 private async Task RefreshBlockIdsAsync()
2946 await this.workerSemaphore.WaitAsync();
2949 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2951 await this.tw.RefreshBlockIds();
2953 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2955 catch (WebApiException ex)
2957 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2961 this.workerSemaphore.Release();
2965 private async Task RefreshTwitterConfigurationAsync()
2967 await this.workerSemaphore.WaitAsync();
2970 await this.tw.RefreshConfiguration();
2972 if (this.tw.Configuration.PhotoSizeLimit != 0)
2974 foreach (var service in this.ImageSelector.GetServices())
2976 service.UpdateTwitterConfiguration(this.tw.Configuration);
2980 this.PurgeListViewItemCache();
2982 this._curList?.Refresh();
2984 catch (WebApiException ex)
2986 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2990 this.workerSemaphore.Release();
2994 private async Task RefreshMuteUserIdsAsync()
2996 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3000 await tw.RefreshMuteUserIdsAsync();
3002 catch (WebApiException ex)
3004 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3008 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3011 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3013 if (e.Button == MouseButtons.Left)
3015 this.Visible = true;
3016 if (this.WindowState == FormWindowState.Minimized)
3018 this.WindowState = _formWindowState;
3021 this.BringToFront();
3025 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3027 switch (this._cfgCommon.ListDoubleClickAction)
3030 MakeReplyOrDirectStatus();
3033 await this.FavoriteChange(true);
3036 if (_curPost != null)
3037 await this.ShowUserStatus(_curPost.ScreenName, false);
3043 ShowRelatedStatusesMenuItem_Click(null, null);
3046 MoveToHomeToolStripMenuItem_Click(null, null);
3049 StatusOpenMenuItem_Click(null, null);
3057 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3059 await this.FavoriteChange(true);
3062 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3064 await this.FavoriteChange(false);
3068 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3070 await this.FavoritesRetweetOfficial();
3073 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3075 await this.FavoritesRetweetUnofficial();
3078 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3081 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3084 //trueでFavAdd,falseでFavRemove
3085 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3086 || !this.ExistCurrentPost) return;
3088 if (this._curList.SelectedIndices.Count > 1)
3093 // https://support.twitter.com/articles/76915#favoriting
3094 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3095 _DoFavRetweetFlags = false;
3100 if (multiFavoriteChangeDialogEnable)
3102 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3103 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3104 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3106 if (confirm == DialogResult.Cancel)
3114 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3115 if (selectedPost.IsFav)
3117 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3121 await this.FavAddAsync(selectedPost.StatusId, tab);
3125 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3126 .Select(x => this.GetCurTabPost(x))
3127 .Where(x => x.IsFav);
3129 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3130 if (statusIds.Length == 0)
3132 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3136 await this.FavRemoveAsync(statusIds, tab);
3140 private PostClass GetCurTabPost(int Index)
3142 var listCache = this._listItemCache;
3143 if (listCache != null)
3147 if (listCache.TryGetValue(Index, out item, out post))
3151 return _statuses.Tabs[_curTab.Text][Index];
3154 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3156 if (_curList.SelectedIndices.Count > 0)
3157 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3158 else if (_curList.SelectedIndices.Count == 0)
3159 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3162 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3164 if (_curList.SelectedIndices.Count > 0)
3165 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3168 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3170 if ((!_initialLayout) && this.Visible)
3172 if (this.WindowState == FormWindowState.Normal)
3174 _mySize = this.ClientSize;
3175 _mySpDis = this.SplitContainer1.SplitterDistance;
3176 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3177 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3178 ModifySettingLocal = true;
3183 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3185 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3186 if (comparerMode == null)
3189 this.SetSortColumn(comparerMode.Value);
3193 /// 列インデックスからソートを行う ComparerMode を求める
3195 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3196 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3197 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3200 return ComparerMode.Id;
3202 switch (columnIndex)
3205 return ComparerMode.Nickname;
3207 return ComparerMode.Data;
3209 return ComparerMode.Id;
3211 return ComparerMode.Name;
3213 return ComparerMode.Source;
3215 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3221 /// 発言一覧の指定した位置の列でソートする
3223 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3224 private void SetSortColumnByDisplayIndex(int columnIndex)
3226 // 表示上の列の位置から ColumnHeader を求める
3227 var col = this._curList.Columns.Cast<ColumnHeader>()
3228 .Where(x => x.DisplayIndex == columnIndex)
3234 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3235 if (comparerMode == null)
3238 this.SetSortColumn(comparerMode.Value);
3242 /// 発言一覧の最後列の項目でソートする
3244 private void SetSortLastColumn()
3246 // 表示上の最後列にある ColumnHeader を求める
3247 var col = this._curList.Columns.Cast<ColumnHeader>()
3248 .OrderByDescending(x => x.DisplayIndex)
3251 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3252 if (comparerMode == null)
3255 this.SetSortColumn(comparerMode.Value);
3259 /// 発言一覧を指定された ComparerMode に基づいてソートする
3261 private void SetSortColumn(ComparerMode sortColumn)
3263 if (this._cfgCommon.SortOrderLock)
3266 this._statuses.ToggleSortOrder(sortColumn);
3267 this.InitColumnText();
3269 var list = this._curList;
3272 list.Columns[0].Text = this.ColumnText[0];
3273 list.Columns[1].Text = this.ColumnText[2];
3277 for (var i = 0; i <= 7; i++)
3279 list.Columns[i].Text = this.ColumnText[i];
3283 this.PurgeListViewItemCache();
3285 var tab = this._statuses.Tabs[this._curTab.Text];
3286 if (tab.AllCount > 0 && this._curPost != null)
3288 var idx = tab.IndexOf(this._curPost.StatusId);
3291 this.SelectListItem(list, idx);
3292 list.EnsureVisible(idx);
3297 this.ModifySettingCommon = true;
3300 private void TweenMain_LocationChanged(object sender, EventArgs e)
3302 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3304 _myLoc = this.DesktopLocation;
3305 ModifySettingLocal = true;
3309 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3311 if (ListTab.SelectedTab == null) return;
3312 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3313 if (!this.ExistCurrentPost)
3315 ReplyStripMenuItem.Enabled = false;
3316 ReplyAllStripMenuItem.Enabled = false;
3317 DMStripMenuItem.Enabled = false;
3318 ShowProfileMenuItem.Enabled = false;
3319 ShowUserTimelineContextMenuItem.Enabled = false;
3320 ListManageUserContextToolStripMenuItem2.Enabled = false;
3321 MoveToFavToolStripMenuItem.Enabled = false;
3322 TabMenuItem.Enabled = false;
3323 IDRuleMenuItem.Enabled = false;
3324 SourceRuleMenuItem.Enabled = false;
3325 ReadedStripMenuItem.Enabled = false;
3326 UnreadStripMenuItem.Enabled = false;
3330 ShowProfileMenuItem.Enabled = true;
3331 ListManageUserContextToolStripMenuItem2.Enabled = true;
3332 ReplyStripMenuItem.Enabled = true;
3333 ReplyAllStripMenuItem.Enabled = true;
3334 DMStripMenuItem.Enabled = true;
3335 ShowUserTimelineContextMenuItem.Enabled = true;
3336 MoveToFavToolStripMenuItem.Enabled = true;
3337 TabMenuItem.Enabled = true;
3338 IDRuleMenuItem.Enabled = true;
3339 SourceRuleMenuItem.Enabled = true;
3340 ReadedStripMenuItem.Enabled = true;
3341 UnreadStripMenuItem.Enabled = true;
3343 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3345 FavAddToolStripMenuItem.Enabled = false;
3346 FavRemoveToolStripMenuItem.Enabled = false;
3347 StatusOpenMenuItem.Enabled = false;
3348 FavorareMenuItem.Enabled = false;
3349 ShowRelatedStatusesMenuItem.Enabled = false;
3351 ReTweetStripMenuItem.Enabled = false;
3352 ReTweetUnofficialStripMenuItem.Enabled = false;
3353 QuoteStripMenuItem.Enabled = false;
3354 FavoriteRetweetContextMenu.Enabled = false;
3355 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3359 FavAddToolStripMenuItem.Enabled = true;
3360 FavRemoveToolStripMenuItem.Enabled = true;
3361 StatusOpenMenuItem.Enabled = true;
3362 FavorareMenuItem.Enabled = true;
3363 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3367 ReTweetStripMenuItem.Enabled = false; //公式RTは無効に
3368 ReTweetUnofficialStripMenuItem.Enabled = true;
3369 QuoteStripMenuItem.Enabled = true;
3370 FavoriteRetweetContextMenu.Enabled = false; //公式RTは無効に
3371 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3375 if (_curPost.IsProtect)
3377 ReTweetStripMenuItem.Enabled = false;
3378 ReTweetUnofficialStripMenuItem.Enabled = false;
3379 QuoteStripMenuItem.Enabled = false;
3380 FavoriteRetweetContextMenu.Enabled = false;
3381 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3385 ReTweetStripMenuItem.Enabled = true;
3386 ReTweetUnofficialStripMenuItem.Enabled = true;
3387 QuoteStripMenuItem.Enabled = true;
3388 FavoriteRetweetContextMenu.Enabled = true;
3389 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3393 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3395 // RefreshMoreStripMenuItem.Enabled = true;
3399 // RefreshMoreStripMenuItem.Enabled = false;
3401 if (!this.ExistCurrentPost
3402 || _curPost.InReplyToStatusId == null)
3404 RepliedStatusOpenMenuItem.Enabled = false;
3408 RepliedStatusOpenMenuItem.Enabled = true;
3410 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3412 MoveToRTHomeMenuItem.Enabled = false;
3416 MoveToRTHomeMenuItem.Enabled = true;
3419 if (this.ExistCurrentPost)
3421 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3422 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3423 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3425 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3429 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3431 MakeReplyOrDirectStatus(false, true);
3434 private void DMStripMenuItem_Click(object sender, EventArgs e)
3436 MakeReplyOrDirectStatus(false, false);
3439 private async Task doStatusDelete()
3441 if (this._curTab == null || this._curList == null)
3444 if (this._curList.SelectedIndices.Count == 0)
3447 var posts = this._curList.SelectedIndices.Cast<int>()
3448 .Select(x => this.GetCurTabPost(x))
3451 // 選択されたツイートの中に削除可能なものが一つでもあるか
3452 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3455 var ret = MessageBox.Show(this,
3456 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3457 Properties.Resources.DeleteStripMenuItem_ClickText2,
3458 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3460 if (ret != DialogResult.OK)
3463 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3465 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3467 Exception lastException = null;
3468 foreach (var post in posts)
3470 if (!post.CanDeleteBy(this.tw.UserId))
3477 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3482 if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3483 // 他人に RT された自分のツイート
3484 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3487 // 自分のツイート or 自分が RT したツイート
3488 await this.twitterApi.StatusesDestroy(post.StatusId)
3492 catch (WebApiException ex)
3498 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3501 if (lastException == null)
3502 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3504 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3506 this.PurgeListViewItemCache();
3507 this._curPost = null;
3508 this._curItemIndex = -1;
3510 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3512 var listView = (DetailsListView)tabPage.Tag;
3513 var tab = this._statuses.Tabs[tabPage.Text];
3515 using (ControlTransaction.Update(listView))
3517 listView.VirtualListSize = tab.AllCount;
3519 if (tabPage == this._curTab)
3521 listView.SelectedIndices.Clear();
3523 if (tab.AllCount != 0)
3526 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3527 selectedIndex = focusedIndex;
3529 selectedIndex = tab.AllCount - 1;
3531 listView.SelectedIndices.Add(selectedIndex);
3532 listView.EnsureVisible(selectedIndex);
3533 listView.FocusedItem = listView.Items[selectedIndex];
3538 if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3540 if (tabPage.ImageIndex == 0)
3541 tabPage.ImageIndex = -1; // タブアイコン
3545 if (!this._cfgCommon.TabIconDisp)
3546 this.ListTab.Refresh();
3550 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3552 await this.doStatusDelete();
3555 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3557 using (ControlTransaction.Update(this._curList))
3559 foreach (int idx in _curList.SelectedIndices)
3561 var post = this._statuses.Tabs[this._curTab.Text][idx];
3562 this._statuses.SetReadAllTab(post.StatusId, read: true);
3563 ChangeCacheStyleRead(true, idx);
3567 foreach (TabPage tb in ListTab.TabPages)
3569 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3571 if (this._cfgCommon.TabIconDisp)
3573 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3577 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3580 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3582 using (ControlTransaction.Update(this._curList))
3584 foreach (int idx in _curList.SelectedIndices)
3586 var post = this._statuses.Tabs[this._curTab.Text][idx];
3587 this._statuses.SetReadAllTab(post.StatusId, read: false);
3588 ChangeCacheStyleRead(false, idx);
3592 foreach (TabPage tb in ListTab.TabPages)
3594 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3596 if (this._cfgCommon.TabIconDisp)
3598 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3602 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3605 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3607 await this.DoRefresh();
3610 private async Task DoRefresh()
3612 if (_curTab != null)
3615 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3618 switch (_statuses.Tabs[_curTab.Text].TabType)
3620 case MyCommon.TabUsageType.Mentions:
3621 await this.GetReplyAsync();
3623 case MyCommon.TabUsageType.DirectMessage:
3624 await this.GetDirectMessagesAsync();
3626 case MyCommon.TabUsageType.Favorites:
3627 await this.GetFavoritesAsync();
3629 //case MyCommon.TabUsageType.Profile:
3631 case MyCommon.TabUsageType.PublicSearch:
3632 var searchTab = (PublicSearchTabModel)tab;
3633 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3634 await this.GetPublicSearchAsync(searchTab);
3636 case MyCommon.TabUsageType.UserTimeline:
3637 await this.GetUserTimelineAsync((UserTimelineTabModel)tab);
3639 case MyCommon.TabUsageType.Lists:
3640 var listTab = (ListTimelineTabModel)tab;
3641 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3642 await this.GetListTimelineAsync(listTab);
3645 await this.GetHomeTimelineAsync();
3651 await this.GetHomeTimelineAsync();
3655 private async Task DoRefreshMore()
3658 if (_curTab != null)
3661 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3664 switch (_statuses.Tabs[_curTab.Text].TabType)
3666 case MyCommon.TabUsageType.Mentions:
3667 await this.GetReplyAsync(loadMore: true);
3669 case MyCommon.TabUsageType.DirectMessage:
3670 await this.GetDirectMessagesAsync(loadMore: true);
3672 case MyCommon.TabUsageType.Favorites:
3673 await this.GetFavoritesAsync(loadMore: true);
3675 case MyCommon.TabUsageType.Profile:
3678 case MyCommon.TabUsageType.PublicSearch:
3679 var searchTab = (PublicSearchTabModel)tab;
3680 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3681 await this.GetPublicSearchAsync(searchTab, loadMore: true);
3683 case MyCommon.TabUsageType.UserTimeline:
3684 await this.GetUserTimelineAsync((UserTimelineTabModel)tab, loadMore: true);
3686 case MyCommon.TabUsageType.Lists:
3687 var listTab = (ListTimelineTabModel)tab;
3688 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3689 await this.GetListTimelineAsync(listTab, loadMore: true);
3692 await this.GetHomeTimelineAsync(loadMore: true);
3698 await this.GetHomeTimelineAsync(loadMore: true);
3702 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3704 DialogResult result = DialogResult.Abort;
3706 using (var settingDialog = new AppendSettingDialog())
3708 settingDialog.Icon = this.MainIcon;
3709 settingDialog.Owner = this;
3710 settingDialog.ShowInTaskbar = showTaskbarIcon;
3711 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3713 settingDialog.tw = this.tw;
3714 settingDialog.twitterApi = this.twitterApi;
3716 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
3720 result = settingDialog.ShowDialog(this);
3724 return DialogResult.Abort;
3727 if (result == DialogResult.OK)
3731 settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
3739 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3742 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3744 var oldIconSz = this._cfgCommon.IconSize;
3746 if (ShowSettingDialog() == DialogResult.OK)
3750 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
3751 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
3752 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
3753 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
3754 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
3755 TwitterApiConnection.RestApiBase = this._cfgCommon.TwitterApiBaseUri;
3757 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
3758 Networking.SetWebProxy(this._cfgLocal.ProxyType,
3759 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
3760 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
3761 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
3763 ImageSelector.Reset(tw, this.tw.Configuration);
3767 if (this._cfgCommon.TabIconDisp)
3769 ListTab.DrawItem -= ListTab_DrawItem;
3770 ListTab.DrawMode = TabDrawMode.Normal;
3771 ListTab.ImageList = this.TabImage;
3775 ListTab.DrawItem -= ListTab_DrawItem;
3776 ListTab.DrawItem += ListTab_DrawItem;
3777 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3778 ListTab.ImageList = null;
3781 catch (Exception ex)
3783 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3784 ex.Data["IsTerminatePermission"] = false;
3790 if (!this._cfgCommon.UnreadManage)
3792 ReadedStripMenuItem.Enabled = false;
3793 UnreadStripMenuItem.Enabled = false;
3794 if (this._cfgCommon.TabIconDisp)
3796 foreach (TabPage myTab in ListTab.TabPages)
3798 myTab.ImageIndex = -1;
3804 ReadedStripMenuItem.Enabled = true;
3805 UnreadStripMenuItem.Enabled = true;
3808 catch (Exception ex)
3810 ex.Data["Instance"] = "ListTab(UnreadManage)";
3811 ex.Data["IsTerminatePermission"] = false;
3818 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
3820 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3821 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
3822 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
3824 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
3825 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
3826 _fntUnread = this._cfgLocal.FontUnread;
3827 _clUnread = this._cfgLocal.ColorUnread;
3828 _fntReaded = this._cfgLocal.FontRead;
3829 _clReaded = this._cfgLocal.ColorRead;
3830 _clFav = this._cfgLocal.ColorFav;
3831 _clOWL = this._cfgLocal.ColorOWL;
3832 _clRetweet = this._cfgLocal.ColorRetweet;
3833 _fntDetail = this._cfgLocal.FontDetail;
3834 _clDetail = this._cfgLocal.ColorDetail;
3835 _clDetailLink = this._cfgLocal.ColorDetailLink;
3836 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
3837 _clSelf = this._cfgLocal.ColorSelf;
3838 _clAtSelf = this._cfgLocal.ColorAtSelf;
3839 _clTarget = this._cfgLocal.ColorTarget;
3840 _clAtTarget = this._cfgLocal.ColorAtTarget;
3841 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
3842 _clAtTo = this._cfgLocal.ColorAtTo;
3843 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
3844 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
3845 _clInputFont = this._cfgLocal.ColorInputFont;
3846 _fntInputFont = this._cfgLocal.FontInputFont;
3847 _brsBackColorMine.Dispose();
3848 _brsBackColorAt.Dispose();
3849 _brsBackColorYou.Dispose();
3850 _brsBackColorAtYou.Dispose();
3851 _brsBackColorAtFromTarget.Dispose();
3852 _brsBackColorAtTo.Dispose();
3853 _brsBackColorNone.Dispose();
3854 _brsBackColorMine = new SolidBrush(_clSelf);
3855 _brsBackColorAt = new SolidBrush(_clAtSelf);
3856 _brsBackColorYou = new SolidBrush(_clTarget);
3857 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3858 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3859 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3860 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3864 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3865 StatusText.Font = _fntInputFont;
3866 StatusText.ForeColor = _clInputFont;
3868 catch (Exception ex)
3870 MessageBox.Show(ex.Message);
3875 InitDetailHtmlFormat();
3877 catch (Exception ex)
3879 ex.Data["Instance"] = "Font";
3880 ex.Data["IsTerminatePermission"] = false;
3886 foreach (TabPage tb in ListTab.TabPages)
3888 if (this._cfgCommon.TabIconDisp)
3890 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3897 catch (Exception ex)
3899 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3900 ex.Data["IsTerminatePermission"] = false;
3906 var oldIconCol = _iconCol;
3908 if (this._cfgCommon.IconSize != oldIconSz)
3909 ApplyListViewIconSize(this._cfgCommon.IconSize);
3911 foreach (TabPage tp in ListTab.TabPages)
3913 DetailsListView lst = (DetailsListView)tp.Tag;
3915 using (ControlTransaction.Update(lst))
3917 lst.GridLines = this._cfgCommon.ShowGrid;
3918 lst.Font = _fntReaded;
3919 lst.BackColor = _clListBackcolor;
3921 if (_iconCol != oldIconCol)
3926 catch (Exception ex)
3928 ex.Data["Instance"] = "ListView(IconSize)";
3929 ex.Data["IsTerminatePermission"] = false;
3933 SetMainWindowTitle();
3934 SetNotifyIconText();
3936 this.PurgeListViewItemCache();
3937 _curList?.Refresh();
3940 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3941 if (this._cfgCommon.HotkeyEnabled)
3943 ///グローバルホットキーの登録。設定で変更可能にするかも
3944 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
3945 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
3946 modKey |= HookGlobalHotkey.ModKeys.Alt;
3947 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
3948 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3949 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
3950 modKey |= HookGlobalHotkey.ModKeys.Shift;
3951 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
3952 modKey |= HookGlobalHotkey.ModKeys.Win;
3954 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
3957 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
3960 StatusText_TextChanged(null, null);
3969 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3970 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3973 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3975 this.TopMost = this._cfgCommon.AlwaysTop;
3976 SaveConfigsAll(false);
3978 if (tw.Username != oldUser.Username)
3979 await this.doGetFollowersMenu();
3985 private void SetTabAlignment()
3987 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3988 if (ListTab.Alignment == newAlignment) return;
3990 // 各タブのリスト上の選択位置などを退避
3991 var listSelections = this.SaveListViewSelection();
3993 ListTab.Alignment = newAlignment;
3995 foreach (TabPage tab in ListTab.TabPages)
3997 DetailsListView lst = (DetailsListView)tab.Tag;
3998 TabModel tabInfo = _statuses.Tabs[tab.Text];
3999 using (ControlTransaction.Update(lst))
4002 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4007 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4013 case MyCommon.IconSizes.IconNone:
4016 case MyCommon.IconSizes.Icon16:
4019 case MyCommon.IconSizes.Icon24:
4022 case MyCommon.IconSizes.Icon48:
4025 case MyCommon.IconSizes.Icon48_2:
4033 // ディスプレイの DPI 設定を考慮したサイズを設定する
4034 _listViewImageList.ImageSize = new Size(
4036 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4040 _listViewImageList.ImageSize = new Size(1, 1);
4044 private void ResetColumns(DetailsListView list)
4046 using (ControlTransaction.Update(list))
4047 using (ControlTransaction.Layout(list, false))
4050 list.ColumnClick -= MyList_ColumnClick;
4051 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4052 list.ColumnReordered -= MyList_ColumnReordered;
4053 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4055 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4056 list.Columns.Clear();
4057 cols.ForEach(col => col.Dispose());
4060 InitColumns(list, true);
4062 list.ColumnClick += MyList_ColumnClick;
4063 list.DrawColumnHeader += MyList_DrawColumnHeader;
4064 list.ColumnReordered += MyList_ColumnReordered;
4065 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4069 private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4071 if (e.Url.AbsoluteUri != "about:blank")
4073 await this.DispSelectedPost();
4074 await this.OpenUriInBrowserAsync(e.Url.OriginalString);
4078 private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4080 if (e.Url.Scheme == "data")
4082 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4084 else if (e.Url.AbsoluteUri != "about:blank")
4087 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
4088 await this.OpenUriAsync( e.Url, MyCommon.IsKeyDown( Keys.Control ) );
4092 public void AddNewTabForSearch(string searchWord)
4094 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4095 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4097 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4099 foreach (TabPage tp in ListTab.TabPages)
4101 if (tb.TabName == tp.Text)
4103 ListTab.SelectedTab = tp;
4110 string tabName = searchWord;
4111 for (int i = 0; i <= 100; i++)
4113 if (_statuses.ContainsTab(tabName))
4119 var tab = new PublicSearchTabModel(tabName);
4120 _statuses.AddTab(tab);
4121 AddNewTab(tab, startup: false);
4123 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4125 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4126 cmb.Items.Add(searchWord);
4127 cmb.Text = searchWord;
4130 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4133 private void ShowUserTimeline()
4135 if (!this.ExistCurrentPost) return;
4136 AddNewTabForUserTimeline(_curPost.ScreenName);
4139 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4141 if (e.KeyCode == Keys.Escape)
4143 TabPage relTp = ListTab.SelectedTab;
4144 RemoveSpecifiedTab(relTp.Text, false);
4146 e.SuppressKeyPress = true;
4150 public void AddNewTabForUserTimeline(string user)
4152 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4153 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4155 if (tb.ScreenName == user)
4157 foreach (TabPage tp in ListTab.TabPages)
4159 if (tb.TabName == tp.Text)
4161 ListTab.SelectedTab = tp;
4168 string tabName = "user:" + user;
4169 while (_statuses.ContainsTab(tabName))
4174 var tab = new UserTimelineTabModel(tabName, user);
4175 this._statuses.AddTab(tab);
4176 this.AddNewTab(tab, startup: false);
4178 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4181 this.GetUserTimelineAsync(tab);
4184 public bool AddNewTab(TabModel tab, bool startup)
4187 foreach (TabPage tb in ListTab.TabPages)
4189 if (tb.Text == tab.TabName) return false;
4193 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4195 var _tabPage = new TabPage();
4196 var _listCustom = new DetailsListView();
4198 int cnt = ListTab.TabPages.Count;
4200 ///ToDo:Create and set controls follow tabtypes
4202 using (ControlTransaction.Update(_listCustom))
4203 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4204 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4205 using (ControlTransaction.Layout(this.SplitContainer1, false))
4206 using (ControlTransaction.Layout(this.ListTab, false))
4207 using (ControlTransaction.Layout(this))
4208 using (ControlTransaction.Layout(_tabPage, false))
4210 _tabPage.Controls.Add(_listCustom);
4213 var userTab = tab as UserTimelineTabModel;
4214 var listTab = tab as ListTimelineTabModel;
4215 var searchTab = tab as PublicSearchTabModel;
4217 if (userTab != null || listTab != null)
4219 var label = new Label();
4220 label.Dock = DockStyle.Top;
4221 label.Name = "labelUser";
4224 if (listTab != null)
4226 label.Text = listTab.ListInfo.ToString();
4228 else if (userTab != null)
4230 label.Text = userTab.ScreenName + "'s Timeline";
4232 label.TextAlign = ContentAlignment.MiddleLeft;
4233 using (ComboBox tmpComboBox = new ComboBox())
4235 label.Height = tmpComboBox.Height;
4237 _tabPage.Controls.Add(label);
4240 else if (searchTab != null)
4242 var pnl = new Panel();
4244 var lbl = new Label();
4245 var cmb = new ComboBox();
4246 var btn = new Button();
4247 var cmbLang = new ComboBox();
4249 using (ControlTransaction.Layout(pnl, false))
4251 pnl.Controls.Add(cmb);
4252 pnl.Controls.Add(cmbLang);
4253 pnl.Controls.Add(btn);
4254 pnl.Controls.Add(lbl);
4255 pnl.Name = "panelSearch";
4257 pnl.Dock = DockStyle.Top;
4258 pnl.Height = cmb.Height;
4259 pnl.Enter += SearchControls_Enter;
4260 pnl.Leave += SearchControls_Leave;
4263 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4264 cmb.Dock = DockStyle.Fill;
4265 cmb.Name = "comboSearch";
4266 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4267 cmb.ImeMode = ImeMode.NoControl;
4268 cmb.TabStop = false;
4270 cmb.AutoCompleteMode = AutoCompleteMode.None;
4271 cmb.KeyDown += SearchComboBox_KeyDown;
4274 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4275 cmbLang.Dock = DockStyle.Right;
4277 cmbLang.Name = "comboLang";
4278 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4279 cmbLang.TabStop = false;
4280 cmbLang.TabIndex = 2;
4281 cmbLang.Items.Add("");
4282 cmbLang.Items.Add("ja");
4283 cmbLang.Items.Add("en");
4284 cmbLang.Items.Add("ar");
4285 cmbLang.Items.Add("da");
4286 cmbLang.Items.Add("nl");
4287 cmbLang.Items.Add("fa");
4288 cmbLang.Items.Add("fi");
4289 cmbLang.Items.Add("fr");
4290 cmbLang.Items.Add("de");
4291 cmbLang.Items.Add("hu");
4292 cmbLang.Items.Add("is");
4293 cmbLang.Items.Add("it");
4294 cmbLang.Items.Add("no");
4295 cmbLang.Items.Add("pl");
4296 cmbLang.Items.Add("pt");
4297 cmbLang.Items.Add("ru");
4298 cmbLang.Items.Add("es");
4299 cmbLang.Items.Add("sv");
4300 cmbLang.Items.Add("th");
4302 lbl.Text = "Search(C-S-f)";
4303 lbl.Name = "label1";
4304 lbl.Dock = DockStyle.Left;
4306 lbl.Height = cmb.Height;
4307 lbl.TextAlign = ContentAlignment.MiddleLeft;
4310 btn.Text = "Search";
4311 btn.Name = "buttonSearch";
4312 btn.UseVisualStyleBackColor = true;
4313 btn.Dock = DockStyle.Right;
4314 btn.TabStop = false;
4316 btn.Click += SearchButton_Click;
4318 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4320 cmb.Items.Add(searchTab.SearchWords);
4321 cmb.Text = searchTab.SearchWords;
4324 cmbLang.Text = searchTab.SearchLang;
4326 _tabPage.Controls.Add(pnl);
4330 _tabPage.Tag = _listCustom;
4331 this.ListTab.Controls.Add(_tabPage);
4333 _tabPage.Location = new Point(4, 4);
4334 _tabPage.Name = "CTab" + cnt.ToString();
4335 _tabPage.Size = new Size(380, 260);
4336 _tabPage.TabIndex = 2 + cnt;
4337 _tabPage.Text = tab.TabName;
4338 _tabPage.UseVisualStyleBackColor = true;
4339 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4341 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4342 _listCustom.TabIndex = 1;
4343 _listCustom.AllowColumnReorder = true;
4344 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4345 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4346 _listCustom.Dock = DockStyle.Fill;
4347 _listCustom.FullRowSelect = true;
4348 _listCustom.HideSelection = false;
4349 _listCustom.Location = new Point(0, 0);
4350 _listCustom.Margin = new Padding(0);
4351 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4352 _listCustom.ShowItemToolTips = true;
4353 _listCustom.Size = new Size(380, 260);
4354 _listCustom.UseCompatibleStateImageBehavior = false;
4355 _listCustom.View = View.Details;
4356 _listCustom.OwnerDraw = true;
4357 _listCustom.VirtualMode = true;
4358 _listCustom.Font = _fntReaded;
4359 _listCustom.BackColor = _clListBackcolor;
4361 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4362 _listCustom.AllowDrop = true;
4364 _listCustom.SmallImageList = _listViewImageList;
4366 InitColumns(_listCustom, startup);
4368 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4369 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4370 _listCustom.ColumnClick += MyList_ColumnClick;
4371 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4372 _listCustom.DragDrop += TweenMain_DragDrop;
4373 _listCustom.DragEnter += TweenMain_DragEnter;
4374 _listCustom.DragOver += TweenMain_DragOver;
4375 _listCustom.DrawItem += MyList_DrawItem;
4376 _listCustom.MouseClick += MyList_MouseClick;
4377 _listCustom.ColumnReordered += MyList_ColumnReordered;
4378 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4379 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4380 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4381 _listCustom.DrawSubItem += MyList_DrawSubItem;
4382 _listCustom.HScrolled += MyList_HScrolled;
4388 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4390 var tabInfo = _statuses.GetTabByName(TabName);
4391 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4395 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4396 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4397 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4403 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4404 if (_tabPage == null) return false;
4406 SetListProperty(); //他のタブに列幅等を反映
4409 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4410 _tabPage.Tag = null;
4412 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4413 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4414 using (ControlTransaction.Layout(this.SplitContainer1, false))
4415 using (ControlTransaction.Layout(this.ListTab, false))
4416 using (ControlTransaction.Layout(this))
4417 using (ControlTransaction.Layout(_tabPage, false))
4419 if (this.ListTab.SelectedTab == _tabPage)
4421 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4422 this._beforeSelectedTab = null;
4424 this.ListTab.Controls.Remove(_tabPage);
4427 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4429 using (Control label = _tabPage.Controls["labelUser"])
4431 _tabPage.Controls.Remove(label);
4434 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4436 using (Control pnl = _tabPage.Controls["panelSearch"])
4438 pnl.Enter -= SearchControls_Enter;
4439 pnl.Leave -= SearchControls_Leave;
4440 _tabPage.Controls.Remove(pnl);
4442 foreach (Control ctrl in pnl.Controls)
4444 if (ctrl.Name == "buttonSearch")
4446 ctrl.Click -= SearchButton_Click;
4448 else if (ctrl.Name == "comboSearch")
4450 ctrl.KeyDown -= SearchComboBox_KeyDown;
4452 pnl.Controls.Remove(ctrl);
4458 _tabPage.Controls.Remove(_listCustom);
4460 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4461 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4462 _listCustom.ColumnClick -= MyList_ColumnClick;
4463 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4464 _listCustom.DragDrop -= TweenMain_DragDrop;
4465 _listCustom.DragEnter -= TweenMain_DragEnter;
4466 _listCustom.DragOver -= TweenMain_DragOver;
4467 _listCustom.DrawItem -= MyList_DrawItem;
4468 _listCustom.MouseClick -= MyList_MouseClick;
4469 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4470 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4471 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4472 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4473 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4474 _listCustom.HScrolled -= MyList_HScrolled;
4476 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4477 _listCustom.Columns.Clear();
4478 cols.ForEach(col => col.Dispose());
4481 _listCustom.ContextMenuStrip = null;
4482 _listCustom.ColumnHeaderContextMenuStrip = null;
4483 _listCustom.Font = null;
4485 _listCustom.SmallImageList = null;
4486 _listCustom.ListViewItemSorter = null;
4489 if (_curTab.Equals(_tabPage))
4496 this.PurgeListViewItemCache();
4500 _listCustom.Dispose();
4501 _statuses.RemoveTab(TabName);
4503 foreach (TabPage tp in ListTab.TabPages)
4505 DetailsListView lst = (DetailsListView)tp.Tag;
4506 var count = _statuses.Tabs[tp.Text].AllCount;
4507 if (lst.VirtualListSize != count)
4509 lst.VirtualListSize = count;
4516 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4518 this.PurgeListViewItemCache();
4519 _beforeSelectedTab = e.TabPage;
4522 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4526 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4529 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4530 if (!dragEnableRectangle.Contains(e.Location))
4532 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4533 tn = ListTab.SelectedTab.Text;
4536 if (string.IsNullOrEmpty(tn)) return;
4538 foreach (TabPage tb in ListTab.TabPages)
4542 ListTab.DoDragDrop(tb, DragDropEffects.All);
4552 Point cpos = new Point(e.X, e.Y);
4553 for (int i = 0; i < ListTab.TabPages.Count; i++)
4555 Rectangle rect = ListTab.GetTabRect(i);
4556 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4557 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4559 _rclickTabName = ListTab.TabPages[i].Text;
4565 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4567 //_curList.Refresh();
4568 SetMainWindowTitle();
4569 SetStatusLabelUrl();
4570 SetApiStatusLabel();
4571 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4572 TabMenuControl(ListTab.SelectedTab.Text);
4573 this.PushSelectPostChain();
4574 await DispSelectedPost();
4577 private void SetListProperty()
4579 //削除などで見つからない場合は処理せず
4580 if (_curList == null) return;
4581 if (!_isColumnChanged) return;
4583 int[] dispOrder = new int[_curList.Columns.Count];
4584 for (int i = 0; i < _curList.Columns.Count; i++)
4586 for (int j = 0; j < _curList.Columns.Count; j++)
4588 if (_curList.Columns[j].DisplayIndex == i)
4597 foreach (TabPage tb in ListTab.TabPages)
4599 if (!tb.Equals(_curTab))
4601 if (tb.Tag != null && tb.Controls.Count > 0)
4603 DetailsListView lst = (DetailsListView)tb.Tag;
4604 for (int i = 0; i < lst.Columns.Count; i++)
4606 lst.Columns[dispOrder[i]].DisplayIndex = i;
4607 lst.Columns[i].Width = _curList.Columns[i].Width;
4613 _isColumnChanged = false;
4616 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
4620 if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal)
4621 || PostBrowser.StatusText.StartsWith("ftp", StringComparison.Ordinal)
4622 || PostBrowser.StatusText.StartsWith("data", StringComparison.Ordinal))
4624 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4626 if (string.IsNullOrEmpty(PostBrowser.StatusText))
4628 SetStatusLabelUrl();
4636 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4638 if (e.KeyChar == '@')
4640 if (!this._cfgCommon.UseAtIdSupplement) return;
4642 int cnt = AtIdSupl.ItemCount;
4643 ShowSuplDialog(StatusText, AtIdSupl);
4644 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
4647 else if (e.KeyChar == '#')
4649 if (!this._cfgCommon.UseHashSupplement) return;
4650 ShowSuplDialog(StatusText, HashSupl);
4655 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4657 ShowSuplDialog(owner, dialog, 0, "");
4660 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4662 ShowSuplDialog(owner, dialog, offset, "");
4665 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4667 dialog.StartsWith = startswith;
4674 dialog.ShowDialog();
4676 this.TopMost = this._cfgCommon.AlwaysTop;
4677 int selStart = owner.SelectionStart;
4680 if (dialog.DialogResult == DialogResult.OK)
4682 if (!string.IsNullOrEmpty(dialog.inputText))
4686 fHalf = owner.Text.Substring(0, selStart - offset);
4688 if (selStart < owner.Text.Length)
4690 eHalf = owner.Text.Substring(selStart);
4692 owner.Text = fHalf + dialog.inputText + eHalf;
4693 owner.SelectionStart = selStart + dialog.inputText.Length;
4700 fHalf = owner.Text.Substring(0, selStart);
4702 if (selStart < owner.Text.Length)
4704 eHalf = owner.Text.Substring(selStart);
4706 owner.Text = fHalf + eHalf;
4709 owner.SelectionStart = selStart;
4715 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4718 if (!e.Alt && !e.Control && !e.Shift)
4720 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4722 bool isSpace = false;
4723 foreach (char c in StatusText.Text.ToCharArray())
4725 if (c == ' ' || c == ' ')
4738 StatusText.Text = "";
4739 JumpUnreadMenuItem_Click(null, null);
4743 this.StatusText_TextChanged(null, null);
4746 private void StatusText_TextChanged(object sender, EventArgs e)
4749 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
4750 lblLen.Text = pLen.ToString();
4753 StatusText.ForeColor = Color.Red;
4757 StatusText.ForeColor = _clInputFont;
4759 if (string.IsNullOrEmpty(StatusText.Text))
4761 this.inReplyTo = null;
4766 /// ツイート投稿前のフッター付与などの前処理を行います
4768 private string FormatStatusText(string statusText)
4770 statusText = statusText.Replace("\r\n", "\n");
4772 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
4775 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4778 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
4780 // 文中の全角スペースを半角スペース1個にする
4781 statusText = statusText.Replace(" ", " ");
4784 // DM の場合はこれ以降の処理を行わない
4785 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4789 if (this._cfgCommon.PostShiftEnter)
4791 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4795 if (this.StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
4796 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4798 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4801 if (statusText.Contains("RT @"))
4802 disableFooter = true;
4807 var hashtag = this.HashMgr.UseHash;
4808 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4811 header = HashMgr.UseHash + " ";
4813 footer = " " + HashMgr.UseHash;
4818 if (this._cfgLocal.UseRecommendStatus)
4821 footer += this.recommendedStatusFooter;
4823 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
4825 // テキストボックスに入力されている文字列を使用する
4826 footer += " " + this._cfgLocal.StatusText.Trim();
4830 statusText = header + statusText + footer;
4832 if (this.ToolStripMenuItemPreventSmsCommand.Checked)
4834 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4835 // 参照: https://support.twitter.com/articles/14020
4837 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4838 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4840 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4841 statusText = '\u200b' + statusText;
4849 /// 投稿欄に表示する入力可能な文字数を計算します
4851 private int GetRestStatusCount(string statusText)
4854 var remainCount = this.tw.GetTextLengthRemain(statusText);
4856 if (this.ImageSelector.Visible && !string.IsNullOrEmpty(this.ImageSelector.ServiceName))
4858 remainCount -= this.tw.Configuration.CharactersReservedPerMedia;
4864 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4866 if (sender != this._curList)
4869 var listCache = this._listItemCache;
4870 if (listCache != null && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4872 // If the newly requested cache is a subset of the old cache,
4873 // no need to rebuild everything, so do nothing.
4877 // Now we need to rebuild the cache.
4878 this.CreateCache(e.StartIndex, e.EndIndex);
4881 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4883 var listCache = this._listItemCache;
4884 if (listCache != null && listCache.TargetList == sender)
4887 PostClass cacheItemPost;
4888 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
4895 // A cache miss, so create a new ListViewItem and pass it back.
4896 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4899 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4903 // 不正な要求に対する間に合わせの応答
4904 string[] sitem = {"", "", "", "", "", "", "", ""};
4905 e.Item = new ImageListViewItem(sitem);
4909 private void CreateCache(int startIndex, int endIndex)
4911 var tabInfo = this._statuses.Tabs[this._curTab.Text];
4913 if (tabInfo.AllCount == 0)
4916 // キャッシュ要求(要求範囲±30を作成)
4917 startIndex = Math.Max(startIndex - 30, 0);
4918 endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
4920 var cacheLength = endIndex - startIndex + 1;
4922 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4923 var listItems = Enumerable.Range(0, cacheLength)
4924 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4927 var listCache = new ListViewItemCache
4929 TargetList = this._curList,
4930 StartIndex = startIndex,
4931 EndIndex = endIndex,
4933 ListItem = listItems,
4936 Interlocked.Exchange(ref this._listItemCache, listCache);
4940 /// DetailsListView のための ListViewItem のキャッシュを消去する
4942 private void PurgeListViewItemCache()
4944 Interlocked.Exchange(ref this._listItemCache, null);
4947 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
4949 StringBuilder mk = new StringBuilder();
4950 //if (Post.IsDeleted) mk.Append("×");
4951 //if (Post.IsMark) mk.Append("♪");
4952 //if (Post.IsProtect) mk.Append("Ю");
4953 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4954 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
4955 ImageListViewItem itm;
4956 if (Post.RetweetedId == null)
4958 string[] sitem= {"",
4960 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
4961 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
4966 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4970 string[] sitem = {"",
4972 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
4973 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
4974 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4978 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4980 itm.StateIndex = Post.StateIndex;
4982 bool read = Post.IsRead;
4983 //未読管理していなかったら既読として扱う
4984 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
4985 ChangeItemStyleRead(read, itm, Post, null);
4986 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
4991 /// 全てのタブの振り分けルールを反映し直します
4993 private void ApplyPostFilters()
4995 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4997 this.PurgeListViewItemCache();
4998 this._curPost = null;
4999 this._curItemIndex = -1;
5000 this._statuses.FilterAll();
5002 foreach (TabPage tabPage in this.ListTab.TabPages)
5004 var tab = this._statuses.Tabs[tabPage.Text];
5006 var listview = (DetailsListView)tabPage.Tag;
5007 using (ControlTransaction.Update(listview))
5009 listview.VirtualListSize = tab.AllCount;
5012 if (this._cfgCommon.TabIconDisp)
5014 if (tab.UnreadCount > 0)
5015 tabPage.ImageIndex = 0;
5017 tabPage.ImageIndex = -1;
5021 if (!this._cfgCommon.TabIconDisp)
5022 this.ListTab.Refresh();
5024 SetMainWindowTitle();
5025 SetStatusLabelUrl();
5029 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5031 e.DrawDefault = true;
5034 private void MyList_HScrolled(object sender, EventArgs e)
5036 DetailsListView listView = (DetailsListView)sender;
5040 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5042 if (e.State == 0) return;
5043 e.DrawDefault = false;
5045 SolidBrush brs2 = null;
5046 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5048 if (e.Item.BackColor == _clSelf)
5049 brs2 = _brsBackColorMine;
5050 else if (e.Item.BackColor == _clAtSelf)
5051 brs2 = _brsBackColorAt;
5052 else if (e.Item.BackColor == _clTarget)
5053 brs2 = _brsBackColorYou;
5054 else if (e.Item.BackColor == _clAtTarget)
5055 brs2 = _brsBackColorAtYou;
5056 else if (e.Item.BackColor == _clAtFromTarget)
5057 brs2 = _brsBackColorAtFromTarget;
5058 else if (e.Item.BackColor == _clAtTo)
5059 brs2 = _brsBackColorAtTo;
5061 brs2 = _brsBackColorNone;
5066 if (((Control)sender).Focused)
5067 brs2 = _brsHighLight;
5069 brs2 = _brsDeactiveSelection;
5071 e.Graphics.FillRectangle(brs2, e.Bounds);
5072 e.DrawFocusRectangle();
5073 this.DrawListViewItemIcon(e);
5076 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5078 if (e.ItemState == 0) return;
5080 if (e.ColumnIndex > 0)
5083 RectangleF rct = e.Bounds;
5084 rct.Width = e.Header.Width;
5085 int fontHeight = e.Item.Font.Height;
5088 rct.Y += fontHeight;
5089 rct.Height -= fontHeight;
5093 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5095 //if (heightDiff > fontHeight * 0.7)
5097 // rct.Height += fontHeight;
5098 // drawLineCount += 1;
5101 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5102 if (!_iconCol && drawLineCount <= 1)
5104 //rct.Inflate(0, heightDiff / -2);
5105 //rct.Height += fontHeight / 2;
5107 else if (heightDiff < fontHeight * 0.7)
5109 //最終行が70%以上欠けていたら、最終行は表示しない
5110 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5111 rct.Height = (fontHeight * drawLineCount) - 1;
5118 //if (!_iconCol && drawLineCount > 1)
5120 // rct.Y += fontHeight * 0.2;
5121 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5126 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5127 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5132 Rectangle rctB = e.Bounds;
5133 rctB.Width = e.Header.Width;
5134 rctB.Height = fontHeight;
5136 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5138 TextRenderer.DrawText(e.Graphics,
5139 e.Item.SubItems[2].Text,
5141 Rectangle.Round(rct),
5143 TextFormatFlags.WordBreak |
5144 TextFormatFlags.EndEllipsis |
5145 TextFormatFlags.GlyphOverhangPadding |
5146 TextFormatFlags.NoPrefix);
5147 TextRenderer.DrawText(e.Graphics,
5148 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 + "]",
5152 TextFormatFlags.SingleLine |
5153 TextFormatFlags.EndEllipsis |
5154 TextFormatFlags.GlyphOverhangPadding |
5155 TextFormatFlags.NoPrefix);
5158 else if (drawLineCount == 1)
5160 TextRenderer.DrawText(e.Graphics,
5163 Rectangle.Round(rct),
5165 TextFormatFlags.SingleLine |
5166 TextFormatFlags.EndEllipsis |
5167 TextFormatFlags.GlyphOverhangPadding |
5168 TextFormatFlags.NoPrefix |
5169 TextFormatFlags.VerticalCenter);
5173 TextRenderer.DrawText(e.Graphics,
5176 Rectangle.Round(rct),
5178 TextFormatFlags.WordBreak |
5179 TextFormatFlags.EndEllipsis |
5180 TextFormatFlags.GlyphOverhangPadding |
5181 TextFormatFlags.NoPrefix);
5183 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5188 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5190 if (_iconSz == 0) return;
5192 ImageListViewItem item = (ImageListViewItem)e.Item;
5194 //e.Bounds.Leftが常に0を指すから自前で計算
5195 Rectangle itemRect = item.Bounds;
5196 var col0 = e.Item.ListView.Columns[0];
5197 itemRect.Width = col0.Width;
5199 if (col0.DisplayIndex > 0)
5201 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5203 if (clm.DisplayIndex < col0.DisplayIndex)
5204 itemRect.X += clm.Width;
5208 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5209 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5210 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5213 var img = item.Image;
5216 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5217 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5219 if (iconRect.Width > 0)
5221 e.Graphics.FillRectangle(Brushes.White, iconRect);
5222 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5225 e.Graphics.DrawImage(img.Image, iconRect);
5227 catch (ArgumentException)
5229 item.RefreshImageAsync();
5235 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5236 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5238 item.GetImageAsync();
5241 if (item.StateIndex > -1)
5243 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5244 if (stateRect.Width > 0)
5246 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5247 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5248 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5253 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5255 base.ScaleControl(factor, specified);
5257 ScaleChildControl(this.TabImage, factor);
5259 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5260 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5262 foreach (var listview in listviews)
5264 ScaleChildControl(listview, factor);
5268 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5270 // ImageListViewItem item = (ImageListViewItem)e.Item;
5271 // if (item.StateImageIndex > -1)
5273 // ////e.Bounds.Leftが常に0を指すから自前で計算
5274 // //Rectangle itemRect = item.Bounds;
5275 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5277 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5279 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5281 // // itemRect.X += clm.Width;
5285 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5286 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5288 // if (rct.Width > 0)
5290 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5291 // //e.Graphics.FillRectangle(Brushes.White, rct);
5292 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5293 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5298 private void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5300 var tab = this._statuses.Tabs[this._curTab.Text];
5302 if (tab.AllCount == 0)
5304 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5308 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5313 case SEARCHTYPE.NextSearch: // 次を検索
5314 if (selectedIndex != -1)
5315 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5319 case SEARCHTYPE.PrevSearch: // 前を検索
5320 if (selectedIndex != -1)
5321 startIndex = Math.Max(selectedIndex - 1, 0);
5323 startIndex = tab.AllCount - 1;
5325 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5327 if (selectedIndex != -1)
5328 startIndex = selectedIndex;
5334 Func<string, bool> stringComparer;
5337 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5339 catch (ArgumentException)
5341 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5345 var reverse = searchType == SEARCHTYPE.PrevSearch;
5346 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5347 .DefaultIfEmpty(-1).First();
5349 if (foundIndex == -1)
5351 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5355 this.SelectListItem(this._curList, foundIndex);
5356 this._curList.EnsureVisible(foundIndex);
5359 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5362 this.ShowSearchDialog();
5365 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5367 var previousSearch = this.SearchDialog.ResultOptions;
5368 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5370 this.SearchDialog.Reset();
5371 this.ShowSearchDialog();
5377 previousSearch.Query,
5378 previousSearch.CaseSensitive,
5379 previousSearch.UseRegex,
5380 SEARCHTYPE.NextSearch);
5383 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5385 var previousSearch = this.SearchDialog.ResultOptions;
5386 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5388 this.SearchDialog.Reset();
5389 this.ShowSearchDialog();
5395 previousSearch.Query,
5396 previousSearch.CaseSensitive,
5397 previousSearch.UseRegex,
5398 SEARCHTYPE.PrevSearch);
5402 /// 検索ダイアログを表示し、検索を実行します
5404 private void ShowSearchDialog()
5406 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5408 this.TopMost = this._cfgCommon.AlwaysTop;
5411 this.TopMost = this._cfgCommon.AlwaysTop;
5413 var searchOptions = this.SearchDialog.ResultOptions;
5414 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5416 if (searchOptions.NewTab)
5418 var tabName = Properties.Resources.SearchResults_TabName;
5422 tabName = this._statuses.MakeTabName(tabName);
5424 catch (TabException ex)
5426 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5429 var resultTab = new LocalSearchTabModel(tabName);
5430 this.AddNewTab(resultTab, startup: false);
5431 this._statuses.AddTab(resultTab);
5433 var targetTab = this._statuses.Tabs[this._curTab.Text];
5435 Func<string, bool> stringComparer;
5438 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5440 catch (ArgumentException)
5442 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5446 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5447 if (foundIndices.Length == 0)
5449 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5453 var foundPosts = foundIndices.Select(x => targetTab[x]);
5454 foreach (var post in foundPosts)
5456 resultTab.AddPostQueue(post);
5459 this._statuses.DistributePosts();
5460 this.RefreshTimeline();
5462 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5463 .First(x => x.Text == tabName);
5465 this.ListTab.SelectedTab = tabPage;
5470 searchOptions.Query,
5471 searchOptions.CaseSensitive,
5472 searchOptions.UseRegex,
5473 SEARCHTYPE.DialogSearch);
5476 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5478 this.AddNewTabForSearch(searchOptions.Query);
5482 /// <summary>発言検索に使用するメソッドを生成します</summary>
5483 /// <exception cref="ArgumentException">
5484 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"> が不正な正規表現な場合
5486 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5490 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5491 var regex = new Regex(query, regexOption);
5493 return x => regex.IsMatch(x);
5497 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5499 return x => x.IndexOf(query, comparisonType) != -1;
5503 private void AboutMenuItem_Click(object sender, EventArgs e)
5505 using (TweenAboutBox about = new TweenAboutBox())
5507 about.ShowDialog(this);
5509 this.TopMost = this._cfgCommon.AlwaysTop;
5512 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5514 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5516 DetailsListView lst = null;
5518 if (ImageSelector.Enabled)
5522 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5525 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5528 ListTab.SelectedIndex = i;
5529 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5530 //_curTab = ListTab.TabPages[i];
5535 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5536 if (idx == -1 && bgnIdx > 0)
5538 for (int i = 0; i < bgnIdx; i++)
5540 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5543 ListTab.SelectedIndex = i;
5544 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5545 //_curTab = ListTab.TabPages[i];
5551 //全部調べたが未読見つからず→先頭タブの最新発言へ
5554 ListTab.SelectedIndex = 0;
5555 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5556 //_curTab = ListTab.TabPages[0];
5557 if (_statuses.SortOrder == SortOrder.Ascending)
5558 idx = lst.VirtualListSize - 1;
5563 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5565 SelectListItem(lst, idx);
5566 if (_statuses.SortMode == ComparerMode.Id)
5568 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5569 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5575 lst.EnsureVisible(idx);
5580 lst.EnsureVisible(idx);
5586 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5588 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5590 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5591 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5595 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5597 if (_curList.SelectedIndices.Count > 0)
5599 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5600 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5604 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5606 await this.CheckNewVersion(false);
5609 private void RunTweenUp()
5611 ProcessStartInfo pinfo = new ProcessStartInfo();
5612 pinfo.UseShellExecute = true;
5613 pinfo.WorkingDirectory = MyCommon.settingPath;
5614 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5615 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5618 Process.Start(pinfo);
5622 MessageBox.Show("Failed to execute TweenUp3.exe.");
5626 public class VersionInfo
5628 public Version Version { get; set; }
5629 public Uri DownloadUri { get; set; }
5630 public string ReleaseNote { get; set; }
5634 /// OpenTween の最新バージョンの情報を取得します
5636 public async Task<VersionInfo> GetVersionInfoAsync()
5638 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5639 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5641 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5642 .ConfigureAwait(false);
5644 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5645 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5647 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5648 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5650 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5652 return new VersionInfo
5654 Version = Version.Parse(msgHeader[0]),
5655 DownloadUri = new Uri(msgHeader[1]),
5656 ReleaseNote = msgBody,
5660 private async Task CheckNewVersion(bool startup = false)
5662 if (ApplicationSettings.VersionInfoUrl == null)
5663 return; // 更新チェック無効化
5667 var versionInfo = await this.GetVersionInfoAsync();
5669 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5674 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5675 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5676 msgtext = MyCommon.ReplaceAppName(msgtext);
5678 MessageBox.Show(msgtext,
5679 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5680 MessageBoxButtons.OK, MessageBoxIcon.Information);
5685 using (var dialog = new UpdateDialog())
5687 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5688 MyCommon.GetReadableVersion(versionInfo.Version));
5689 dialog.DetailsText = versionInfo.ReleaseNote;
5691 if (dialog.ShowDialog(this) == DialogResult.Yes)
5693 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5699 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5702 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5703 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5704 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5709 private async Task Colorize()
5712 await this.DispSelectedPost();
5713 //件数関連の場合、タイトル即時書き換え
5714 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
5715 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5716 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5717 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5719 SetMainWindowTitle();
5721 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
5722 foreach (TabPage tb in ListTab.TabPages)
5724 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5726 if (this._cfgCommon.TabIconDisp)
5728 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5732 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
5735 public string createDetailHtml(string orgdata)
5737 if (this._cfgLocal.UseTwemoji)
5738 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5740 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5743 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
5745 if (sender.Equals(displayItem))
5747 this.ClearUserPicture();
5749 var img = displayItem.Image;
5753 img = await img.CloneAsync();
5755 UserPicture.Image = img;
5759 UserPicture.ShowErrorImage();
5764 private Task DispSelectedPost()
5766 return this.DispSelectedPost(false);
5769 private PostClass displayPost = new PostClass();
5772 /// サムネイル表示に使用する CancellationToken の生成元
5774 private CancellationTokenSource thumbnailTokenSource = null;
5776 private async Task DispSelectedPost(bool forceupdate)
5778 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5781 var oldDisplayPost = this.displayPost;
5782 this.displayPost = this._curPost;
5784 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5787 if (displayItem != null)
5789 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
5792 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
5793 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
5795 using (ControlTransaction.Update(this.TableLayoutPanel1))
5797 SourceLinkLabel.Text = this._curPost.Source;
5798 SourceLinkLabel.Tag = this._curPost.SourceUri;
5799 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
5805 nameText = "DM FROM <- ";
5807 nameText = "DM TO -> ";
5813 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
5814 if (_curPost.RetweetedId != null)
5815 nameText += " (RT:" + _curPost.RetweetedBy + ")";
5817 NameLabel.Text = nameText;
5818 NameLabel.Tag = _curPost.ScreenName;
5820 var nameForeColor = SystemColors.ControlText;
5821 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
5822 nameForeColor = this._clOWL;
5823 if (_curPost.RetweetedId != null)
5824 nameForeColor = this._clRetweet;
5826 nameForeColor = this._clFav;
5827 NameLabel.ForeColor = nameForeColor;
5829 this.ClearUserPicture();
5831 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
5833 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
5836 UserPicture.Image = image?.Clone();
5840 UserPicture.ShowErrorImage();
5844 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
5847 if (DumpPostClassToolStripMenuItem.Checked)
5849 StringBuilder sb = new StringBuilder(512);
5851 sb.Append("-----Start PostClass Dump<br>");
5852 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
5853 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
5854 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
5855 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
5856 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
5857 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
5858 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
5859 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
5860 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
5861 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
5862 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
5863 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
5864 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
5865 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
5866 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
5868 foreach (string nm in _curPost.ReplyToList)
5870 sb.AppendFormat("ReplyToList : {0}<br>", nm);
5873 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
5874 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
5875 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
5876 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
5877 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
5878 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
5879 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
5880 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
5881 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
5882 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
5884 sb.AppendFormat("Media.Count : {0}<br>", _curPost.Media.Count);
5885 if (_curPost.Media.Count > 0)
5887 for (int i = 0; i < _curPost.Media.Count; i++)
5889 var info = _curPost.Media[i];
5890 sb.AppendFormat("Media[{0}].Url : {1}<br>", i, info.Url);
5891 sb.AppendFormat("Media[{0}].VideoUrl : {1}<br>", i, info.VideoUrl ?? "---");
5894 sb.Append("-----End PostClass Dump<br>");
5896 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
5900 var loadTasks = new List<Task>();
5902 // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
5903 // (同一ツイートの RT は文面が同じであるため同様に更新しない)
5904 if (_curPost.StatusId != oldDisplayPost.StatusId)
5906 using (ControlTransaction.Update(this.PostBrowser))
5908 this.PostBrowser.DocumentText =
5909 this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
5911 this.PostBrowser.Document.Window.ScrollTo(0, 0);
5914 this.SplitContainer3.Panel2Collapsed = true;
5916 if (this._cfgCommon.PreviewEnable)
5918 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5919 oldTokenSource?.Cancel();
5921 var token = this.thumbnailTokenSource.Token;
5922 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5925 loadTasks.Add(this.AppendQuoteTweetAsync(this._curPost));
5930 await Task.WhenAll(loadTasks);
5932 catch (OperationCanceledException) { }
5936 /// 発言詳細欄のツイートURLを展開する
5938 private async Task AppendQuoteTweetAsync(PostClass post)
5940 var quoteStatusIds = post.QuoteStatusIds;
5941 if (quoteStatusIds.Length == 0 && post.InReplyToStatusId == null)
5945 var loadingQuoteHtml = quoteStatusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText, isReply: false));
5947 var loadingReplyHtml = string.Empty;
5948 if (post.InReplyToStatusId != null)
5949 loadingReplyHtml = FormatQuoteTweetHtml(post.InReplyToStatusId.Value, Properties.Resources.LoadingText, isReply: true);
5951 var body = post.Text + string.Concat(loadingQuoteHtml) + loadingReplyHtml;
5953 using (ControlTransaction.Update(this.PostBrowser))
5954 this.PostBrowser.DocumentText = this.createDetailHtml(body);
5957 var loadTweetTasks = quoteStatusIds.Select(x => this.CreateQuoteTweetHtml(x, isReply: false)).ToList();
5959 if (post.InReplyToStatusId != null)
5960 loadTweetTasks.Add(this.CreateQuoteTweetHtml(post.InReplyToStatusId.Value, isReply: true));
5962 var quoteHtmls = await Task.WhenAll(loadTweetTasks);
5964 // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
5965 if (this._curPost != post || this._curPost.IsDeleted)
5968 body = post.Text + string.Concat(quoteHtmls);
5970 using (ControlTransaction.Update(this.PostBrowser))
5971 this.PostBrowser.DocumentText = this.createDetailHtml(body);
5974 private async Task<string> CreateQuoteTweetHtml(long statusId, bool isReply)
5976 PostClass post = this._statuses[statusId];
5981 post = await this.tw.GetStatusApi(false, statusId)
5982 .ConfigureAwait(false);
5984 catch (WebApiException ex)
5986 return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode($"Err:{ex.Message}(GetStatus)"), isReply);
5990 if (!this._statuses.AddQuoteTweet(post))
5991 return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.", isReply);
5994 return FormatQuoteTweetHtml(post, isReply);
5997 internal static string FormatQuoteTweetHtml(PostClass post, bool isReply)
5999 var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
6000 " — " + WebUtility.HtmlEncode(post.Nickname) +
6001 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
6002 WebUtility.HtmlEncode(post.CreatedAt.ToString());
6004 return FormatQuoteTweetHtml(post.StatusId, innerHtml, isReply);
6007 internal static string FormatQuoteTweetHtml(long statusId, string innerHtml, bool isReply)
6009 var blockClassName = "quote-tweet";
6012 blockClassName += " reply";
6014 return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
6015 $"<blockquote class=\"{blockClassName}\">{innerHtml}</blockquote>" +
6020 /// 指定されたHTMLからリンクを除去します
6022 internal static string StripLinkTagHtml(string html)
6024 // a 要素はネストされていない前提の正規表現パターン
6025 return Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1");
6028 private async void MatomeMenuItem_Click(object sender, EventArgs e)
6030 await this.OpenApplicationWebsite();
6033 private async Task OpenApplicationWebsite()
6035 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
6038 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6040 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
6043 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
6045 if (ListTab.SelectedTab != null)
6047 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6049 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6050 if (pnl.Controls["comboSearch"].Focused ||
6051 pnl.Controls["comboLang"].Focused ||
6052 pnl.Controls["buttonSearch"].Focused) return;
6055 if (e.Control || e.Shift || e.Alt)
6056 this._anchorFlag = false;
6059 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
6062 e.SuppressKeyPress = true;
6065 if (asyncTask != null)
6070 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
6072 private void InitializeShortcuts()
6074 this.shortcutCommands = new[]
6076 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6077 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
6078 .FocusedOn(FocusedControl.ListTab)
6079 .Do(() => SendKeys.Send("{DOWN}")),
6081 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
6082 .FocusedOn(FocusedControl.ListTab)
6083 .Do(() => SendKeys.Send("{UP}")),
6085 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
6086 .FocusedOn(FocusedControl.ListTab)
6087 .Do(() => SendKeys.Send("{PGDN}")),
6089 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
6090 .FocusedOn(FocusedControl.ListTab)
6091 .Do(() => SendKeys.Send("{PGUP}")),
6093 ShortcutCommand.Create(Keys.F1)
6094 .Do(() => this.OpenApplicationWebsite()),
6096 ShortcutCommand.Create(Keys.F3)
6097 .Do(() => this.MenuItemSearchNext_Click(null, null)),
6099 ShortcutCommand.Create(Keys.F5)
6100 .Do(() => this.DoRefresh()),
6102 ShortcutCommand.Create(Keys.F6)
6103 .Do(() => this.GetReplyAsync()),
6105 ShortcutCommand.Create(Keys.F7)
6106 .Do(() => this.GetDirectMessagesAsync()),
6108 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
6109 .NotFocusedOn(FocusedControl.StatusText)
6110 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
6112 ShortcutCommand.Create(Keys.G)
6113 .NotFocusedOn(FocusedControl.StatusText)
6114 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
6116 ShortcutCommand.Create(Keys.Right, Keys.N)
6117 .FocusedOn(FocusedControl.ListTab)
6118 .Do(() => this.GoRelPost(forward: true)),
6120 ShortcutCommand.Create(Keys.Left, Keys.P)
6121 .FocusedOn(FocusedControl.ListTab)
6122 .Do(() => this.GoRelPost(forward: false)),
6124 ShortcutCommand.Create(Keys.OemPeriod)
6125 .FocusedOn(FocusedControl.ListTab)
6126 .Do(() => this.GoAnchor()),
6128 ShortcutCommand.Create(Keys.I)
6129 .FocusedOn(FocusedControl.ListTab)
6130 .OnlyWhen(() => this.StatusText.Enabled)
6131 .Do(() => this.StatusText.Focus()),
6133 ShortcutCommand.Create(Keys.Enter)
6134 .FocusedOn(FocusedControl.ListTab)
6135 .Do(() => this.MakeReplyOrDirectStatus()),
6137 ShortcutCommand.Create(Keys.R)
6138 .FocusedOn(FocusedControl.ListTab)
6139 .Do(() => this.DoRefresh()),
6141 ShortcutCommand.Create(Keys.L)
6142 .FocusedOn(FocusedControl.ListTab)
6143 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
6145 ShortcutCommand.Create(Keys.H)
6146 .FocusedOn(FocusedControl.ListTab)
6147 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6149 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6150 .FocusedOn(FocusedControl.ListTab)
6151 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6153 ShortcutCommand.Create(Keys.S)
6154 .FocusedOn(FocusedControl.ListTab)
6155 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6157 ShortcutCommand.Create(Keys.A)
6158 .FocusedOn(FocusedControl.ListTab)
6159 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6161 // ] in_reply_to参照元へ戻る
6162 ShortcutCommand.Create(Keys.Oem4)
6163 .FocusedOn(FocusedControl.ListTab)
6164 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6166 // [ in_reply_toへジャンプ
6167 ShortcutCommand.Create(Keys.Oem6)
6168 .FocusedOn(FocusedControl.ListTab)
6169 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6171 ShortcutCommand.Create(Keys.Escape)
6172 .FocusedOn(FocusedControl.ListTab)
6174 this._anchorFlag = false;
6175 if (ListTab.SelectedTab != null)
6177 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6178 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6180 var relTp = ListTab.SelectedTab;
6181 RemoveSpecifiedTab(relTp.Text, false);
6187 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
6188 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
6189 .FocusedOn(FocusedControl.ListTab)
6190 .Do(() => this._anchorFlag = false, preventDefault: false),
6192 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6193 ShortcutCommand.Create(Keys.Up, Keys.Down)
6194 .FocusedOn(FocusedControl.PostBrowser)
6197 ShortcutCommand.Create(Keys.Control | Keys.R)
6198 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6200 ShortcutCommand.Create(Keys.Control | Keys.D)
6201 .Do(() => this.doStatusDelete()),
6203 ShortcutCommand.Create(Keys.Control | Keys.M)
6204 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6206 ShortcutCommand.Create(Keys.Control | Keys.S)
6207 .Do(() => this.FavoriteChange(FavAdd: true)),
6209 ShortcutCommand.Create(Keys.Control | Keys.I)
6210 .Do(() => this.doRepliedStatusOpen()),
6212 ShortcutCommand.Create(Keys.Control | Keys.Q)
6213 .Do(() => this.doQuoteOfficial()),
6215 ShortcutCommand.Create(Keys.Control | Keys.B)
6216 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6218 ShortcutCommand.Create(Keys.Control | Keys.T)
6219 .Do(() => this.HashManageMenuItem_Click(null, null)),
6221 ShortcutCommand.Create(Keys.Control | Keys.L)
6222 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6224 ShortcutCommand.Create(Keys.Control | Keys.Y)
6225 .NotFocusedOn(FocusedControl.PostBrowser)
6226 .Do(() => this.MultiLineMenuItem_Click(null, null)),
6228 ShortcutCommand.Create(Keys.Control | Keys.F)
6229 .Do(() => this.MenuItemSubSearch_Click(null, null)),
6231 ShortcutCommand.Create(Keys.Control | Keys.U)
6232 .Do(() => this.ShowUserTimeline()),
6234 ShortcutCommand.Create(Keys.Control | Keys.H)
6235 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6237 ShortcutCommand.Create(Keys.Control | Keys.G)
6238 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6240 ShortcutCommand.Create(Keys.Control | Keys.O)
6241 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6243 ShortcutCommand.Create(Keys.Control | Keys.E)
6244 .Do(() => this.OpenURLMenuItem_Click(null, null)),
6246 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6247 .FocusedOn(FocusedControl.ListTab)
6248 .Do(() => this._colorize = true, preventDefault: false),
6250 ShortcutCommand.Create(Keys.Control | Keys.N)
6251 .FocusedOn(FocusedControl.ListTab)
6252 .Do(() => this.GoNextTab(forward: true)),
6254 ShortcutCommand.Create(Keys.Control | Keys.P)
6255 .FocusedOn(FocusedControl.ListTab)
6256 .Do(() => this.GoNextTab(forward: false)),
6258 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6259 .FocusedOn(FocusedControl.ListTab)
6260 .Do(() => this.CopyStot()),
6262 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6263 ShortcutCommand.Create(Keys.Control | Keys.D1)
6264 .FocusedOn(FocusedControl.ListTab)
6265 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6266 .Do(() => this.ListTab.SelectedIndex = 0),
6268 ShortcutCommand.Create(Keys.Control | Keys.D2)
6269 .FocusedOn(FocusedControl.ListTab)
6270 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6271 .Do(() => this.ListTab.SelectedIndex = 1),
6273 ShortcutCommand.Create(Keys.Control | Keys.D3)
6274 .FocusedOn(FocusedControl.ListTab)
6275 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6276 .Do(() => this.ListTab.SelectedIndex = 2),
6278 ShortcutCommand.Create(Keys.Control | Keys.D4)
6279 .FocusedOn(FocusedControl.ListTab)
6280 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6281 .Do(() => this.ListTab.SelectedIndex = 3),
6283 ShortcutCommand.Create(Keys.Control | Keys.D5)
6284 .FocusedOn(FocusedControl.ListTab)
6285 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6286 .Do(() => this.ListTab.SelectedIndex = 4),
6288 ShortcutCommand.Create(Keys.Control | Keys.D6)
6289 .FocusedOn(FocusedControl.ListTab)
6290 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6291 .Do(() => this.ListTab.SelectedIndex = 5),
6293 ShortcutCommand.Create(Keys.Control | Keys.D7)
6294 .FocusedOn(FocusedControl.ListTab)
6295 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6296 .Do(() => this.ListTab.SelectedIndex = 6),
6298 ShortcutCommand.Create(Keys.Control | Keys.D8)
6299 .FocusedOn(FocusedControl.ListTab)
6300 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6301 .Do(() => this.ListTab.SelectedIndex = 7),
6303 ShortcutCommand.Create(Keys.Control | Keys.D9)
6304 .FocusedOn(FocusedControl.ListTab)
6305 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6307 ShortcutCommand.Create(Keys.Control | Keys.A)
6308 .FocusedOn(FocusedControl.StatusText)
6309 .Do(() => this.StatusText.SelectAll()),
6311 ShortcutCommand.Create(Keys.Control | Keys.V)
6312 .FocusedOn(FocusedControl.StatusText)
6313 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6315 ShortcutCommand.Create(Keys.Control | Keys.Up)
6316 .FocusedOn(FocusedControl.StatusText)
6318 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6320 var inReplyToStatusId = this.inReplyTo?.Item1;
6321 var inReplyToScreenName = this.inReplyTo?.Item2;
6322 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6325 if (_hisIdx < 0) _hisIdx = 0;
6327 var historyItem = this._history[this._hisIdx];
6328 StatusText.Text = historyItem.status;
6329 StatusText.SelectionStart = StatusText.Text.Length;
6330 if (historyItem.inReplyToId != null)
6331 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6333 this.inReplyTo = null;
6336 ShortcutCommand.Create(Keys.Control | Keys.Down)
6337 .FocusedOn(FocusedControl.StatusText)
6339 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6341 var inReplyToStatusId = this.inReplyTo?.Item1;
6342 var inReplyToScreenName = this.inReplyTo?.Item2;
6343 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6346 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6348 var historyItem = this._history[this._hisIdx];
6349 StatusText.Text = historyItem.status;
6350 StatusText.SelectionStart = StatusText.Text.Length;
6351 if (historyItem.inReplyToId != null)
6352 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6354 this.inReplyTo = null;
6357 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6358 .FocusedOn(FocusedControl.StatusText)
6360 if (ListTab.SelectedIndex == 0)
6362 ListTab.SelectedIndex = ListTab.TabCount - 1;
6366 ListTab.SelectedIndex -= 1;
6371 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6372 .FocusedOn(FocusedControl.StatusText)
6374 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6376 ListTab.SelectedIndex = 0;
6380 ListTab.SelectedIndex += 1;
6385 ShortcutCommand.Create(Keys.Control | Keys.Y)
6386 .FocusedOn(FocusedControl.PostBrowser)
6388 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6389 MultiLineMenuItem_Click(null, null);
6392 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6393 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6395 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6396 .Do(() => this.DoRefreshMore()),
6398 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6399 .Do(() => this.GetReplyAsync(loadMore: true)),
6401 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6402 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6404 ShortcutCommand.Create(Keys.Shift | Keys.R)
6405 .NotFocusedOn(FocusedControl.StatusText)
6406 .Do(() => this.DoRefreshMore()),
6408 ShortcutCommand.Create(Keys.Shift | Keys.H)
6409 .FocusedOn(FocusedControl.ListTab)
6410 .Do(() => this.GoTopEnd(GoTop: true)),
6412 ShortcutCommand.Create(Keys.Shift | Keys.L)
6413 .FocusedOn(FocusedControl.ListTab)
6414 .Do(() => this.GoTopEnd(GoTop: false)),
6416 ShortcutCommand.Create(Keys.Shift | Keys.M)
6417 .FocusedOn(FocusedControl.ListTab)
6418 .Do(() => this.GoMiddle()),
6420 ShortcutCommand.Create(Keys.Shift | Keys.G)
6421 .FocusedOn(FocusedControl.ListTab)
6422 .Do(() => this.GoLast()),
6424 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6425 .FocusedOn(FocusedControl.ListTab)
6426 .Do(() => this.MoveMiddle()),
6428 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6429 .FocusedOn(FocusedControl.ListTab)
6430 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6432 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6433 .FocusedOn(FocusedControl.ListTab)
6434 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6436 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6437 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6438 .FocusedOn(FocusedControl.ListTab)
6439 .Do(() => this.GoFav(forward: true)),
6441 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6442 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6443 .FocusedOn(FocusedControl.ListTab)
6444 .Do(() => this.GoFav(forward: false)),
6446 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6447 .FocusedOn(FocusedControl.ListTab)
6448 .Do(() => this.GoBackSelectPostChain()),
6450 ShortcutCommand.Create(Keys.Alt | Keys.R)
6451 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6453 ShortcutCommand.Create(Keys.Alt | Keys.P)
6454 .OnlyWhen(() => this._curPost != null)
6455 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6457 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6458 .Do(() => this.ScrollDownPostBrowser(forward: false)),
6460 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6461 .Do(() => this.ScrollDownPostBrowser(forward: true)),
6463 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6464 .Do(() => this.PageDownPostBrowser(forward: false)),
6466 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6467 .Do(() => this.PageDownPostBrowser(forward: true)),
6469 // 別タブの同じ書き込みへ(ALT+←/→)
6470 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6471 .FocusedOn(FocusedControl.ListTab)
6472 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6474 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6475 .FocusedOn(FocusedControl.ListTab)
6476 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6478 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6479 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6481 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6482 .Do(() => this.CopyIdUri()),
6484 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6485 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6486 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6487 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6489 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6490 .Do(() => this.FavoriteChange(FavAdd: false)),
6492 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6493 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6495 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6496 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6498 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6499 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6501 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6502 .Do(() => this.doMoveToRTHome()),
6504 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6505 .Do(() => this.FavorareMenuItem_Click(null, null)),
6507 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6508 .FocusedOn(FocusedControl.StatusText)
6510 if (_curList != null && _curList.VirtualListSize != 0 &&
6511 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6513 var idx = _curList.SelectedIndices[0] - 1;
6514 SelectListItem(_curList, idx);
6515 _curList.EnsureVisible(idx);
6519 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6520 .FocusedOn(FocusedControl.StatusText)
6522 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6523 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6525 var idx = _curList.SelectedIndices[0] + 1;
6526 SelectListItem(_curList, idx);
6527 _curList.EnsureVisible(idx);
6531 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6532 .FocusedOn(FocusedControl.StatusText)
6534 if (StatusText.SelectionStart > 0)
6536 int endidx = StatusText.SelectionStart - 1;
6537 string startstr = "";
6538 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6540 char c = StatusText.Text[i];
6541 if (Char.IsLetterOrDigit(c) || c == '_')
6547 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6548 int cnt = AtIdSupl.ItemCount;
6549 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6550 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6554 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6555 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6565 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6566 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6567 .FocusedOn(FocusedControl.ListTab)
6568 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6570 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6571 .FocusedOn(FocusedControl.ListTab)
6572 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6574 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6575 .FocusedOn(FocusedControl.ListTab)
6576 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6578 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6579 .FocusedOn(FocusedControl.ListTab)
6580 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6582 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6583 .FocusedOn(FocusedControl.ListTab)
6584 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6586 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6587 .FocusedOn(FocusedControl.ListTab)
6588 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6590 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6591 .FocusedOn(FocusedControl.ListTab)
6592 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6594 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6595 .FocusedOn(FocusedControl.ListTab)
6596 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6598 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6599 .FocusedOn(FocusedControl.ListTab)
6600 .Do(() => this.SetSortLastColumn()),
6602 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6603 .Do(() => this.FavoritesRetweetOfficial()),
6605 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6606 .Do(() => this.FavoritesRetweetUnofficial()),
6608 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6609 .Do(() => this.OpenUserAppointUrl()),
6611 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6612 .FocusedOn(FocusedControl.PostBrowser)
6613 .Do(() => this.doReTweetUnofficial()),
6615 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6616 .OnlyWhen(() => this.ExistCurrentPost)
6617 .Do(() => this.doTranslation(_curPost.TextFromApi)),
6619 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6620 .Do(() => this.doReTweetUnofficial()),
6622 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6623 .Do(() => this.CopyUserId()),
6625 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6626 .Do(() => this.tweetThumbnail1.ScrollUp()),
6628 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6629 .Do(() => this.tweetThumbnail1.ScrollDown()),
6631 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6632 .FocusedOn(FocusedControl.ListTab)
6633 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6634 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6638 private bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6640 // Task を返す非同期処理があれば asyncTask に代入する
6643 // ShortcutCommand に対応しているコマンドはここで処理される
6644 foreach (var command in this.shortcutCommands)
6646 if (command.IsMatch(keyData, focusedOn))
6648 asyncTask = command.RunCommand();
6649 return command.PreventDefault;
6656 private void ScrollDownPostBrowser(bool forward)
6658 var doc = PostBrowser.Document;
6659 if (doc == null) return;
6661 var tags = doc.GetElementsByTagName("html");
6665 tags[0].ScrollTop += this._fntDetail.Height;
6667 tags[0].ScrollTop -= this._fntDetail.Height;
6671 private void PageDownPostBrowser(bool forward)
6673 var doc = PostBrowser.Document;
6674 if (doc == null) return;
6676 var tags = doc.GetElementsByTagName("html");
6680 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
6682 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
6686 private void GoNextTab(bool forward)
6688 int idx = ListTab.SelectedIndex;
6692 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6697 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6699 ListTab.SelectedIndex = idx;
6702 private void CopyStot()
6705 StringBuilder sb = new StringBuilder();
6706 bool IsProtected = false;
6708 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6709 foreach (int idx in _curList.SelectedIndices)
6711 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6717 if (post.IsDeleted) continue;
6720 if (post.RetweetedId != null)
6721 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6723 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6727 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6732 MessageBox.Show(Properties.Resources.CopyStotText1);
6736 clstr = sb.ToString();
6739 Clipboard.SetDataObject(clstr, false, 5, 100);
6741 catch (Exception ex)
6743 MessageBox.Show(ex.Message);
6748 private void CopyIdUri()
6751 StringBuilder sb = new StringBuilder();
6752 if (this._curTab == null) return;
6753 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
6754 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
6755 foreach (int idx in _curList.SelectedIndices)
6757 var post = _statuses.Tabs[_curTab.Text][idx];
6758 sb.Append(MyCommon.GetStatusUrl(post));
6759 sb.Append(Environment.NewLine);
6763 clstr = sb.ToString();
6766 Clipboard.SetDataObject(clstr, false, 5, 100);
6768 catch (Exception ex)
6770 MessageBox.Show(ex.Message);
6775 private void GoFav(bool forward)
6777 if (_curList.VirtualListSize == 0) return;
6784 if (_curList.SelectedIndices.Count == 0)
6790 fIdx = _curList.SelectedIndices[0] + 1;
6791 if (fIdx > _curList.VirtualListSize - 1) return;
6793 toIdx = _curList.VirtualListSize;
6798 if (_curList.SelectedIndices.Count == 0)
6800 fIdx = _curList.VirtualListSize - 1;
6804 fIdx = _curList.SelectedIndices[0] - 1;
6805 if (fIdx < 0) return;
6811 for (int idx = fIdx; idx != toIdx; idx += stp)
6813 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6815 SelectListItem(_curList, idx);
6816 _curList.EnsureVisible(idx);
6822 private void GoSamePostToAnotherTab(bool left)
6824 if (_curList.VirtualListSize == 0) return;
6830 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
6831 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
6833 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
6838 if (ListTab.SelectedIndex == 0)
6844 fIdx = ListTab.SelectedIndex - 1;
6852 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6858 fIdx = ListTab.SelectedIndex + 1;
6860 toIdx = ListTab.TabCount;
6865 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6867 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
6868 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
6870 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
6872 ListTab.SelectedIndex = tabidx;
6873 SelectListItem(_curList, idx);
6874 _curList.EnsureVisible(idx);
6883 private void GoPost(bool forward)
6885 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
6892 fIdx = _curList.SelectedIndices[0] + 1;
6893 if (fIdx > _curList.VirtualListSize - 1) return;
6894 toIdx = _curList.VirtualListSize;
6899 fIdx = _curList.SelectedIndices[0] - 1;
6900 if (fIdx < 0) return;
6906 if (_curPost.RetweetedId == null)
6908 name = _curPost.ScreenName;
6912 name = _curPost.RetweetedBy;
6914 for (int idx = fIdx; idx != toIdx; idx += stp)
6916 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
6918 if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
6920 SelectListItem(_curList, idx);
6921 _curList.EnsureVisible(idx);
6927 if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
6929 SelectListItem(_curList, idx);
6930 _curList.EnsureVisible(idx);
6937 private void GoRelPost(bool forward)
6939 if (_curList.SelectedIndices.Count == 0) return;
6946 fIdx = _curList.SelectedIndices[0] + 1;
6947 if (fIdx > _curList.VirtualListSize - 1) return;
6948 toIdx = _curList.VirtualListSize;
6953 fIdx = _curList.SelectedIndices[0] - 1;
6954 if (fIdx < 0) return;
6961 if (_curPost == null) return;
6962 _anchorPost = _curPost;
6967 if (_anchorPost == null) return;
6970 for (int idx = fIdx; idx != toIdx; idx += stp)
6972 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6973 if (post.ScreenName == _anchorPost.ScreenName ||
6974 post.RetweetedBy == _anchorPost.ScreenName ||
6975 post.ScreenName == _anchorPost.RetweetedBy ||
6976 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6977 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
6978 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
6979 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
6980 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
6982 SelectListItem(_curList, idx);
6983 _curList.EnsureVisible(idx);
6989 private void GoAnchor()
6991 if (_anchorPost == null) return;
6992 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6993 if (idx == -1) return;
6995 SelectListItem(_curList, idx);
6996 _curList.EnsureVisible(idx);
6999 private void GoTopEnd(bool GoTop)
7001 if (_curList.VirtualListSize == 0)
7009 _item = _curList.GetItemAt(0, 25);
7017 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7019 idx = _curList.VirtualListSize - 1;
7023 SelectListItem(_curList, idx);
7026 private void GoMiddle()
7028 if (_curList.VirtualListSize == 0)
7036 _item = _curList.GetItemAt(0, 0);
7046 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7049 idx2 = _curList.VirtualListSize - 1;
7055 idx3 = (idx1 + idx2) / 2;
7057 SelectListItem(_curList, idx3);
7060 private void GoLast()
7062 if (_curList.VirtualListSize == 0) return;
7064 if (_statuses.SortOrder == SortOrder.Ascending)
7066 SelectListItem(_curList, _curList.VirtualListSize - 1);
7067 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7071 SelectListItem(_curList, 0);
7072 _curList.EnsureVisible(0);
7076 private void MoveTop()
7078 if (_curList.SelectedIndices.Count == 0) return;
7079 int idx = _curList.SelectedIndices[0];
7080 if (_statuses.SortOrder == SortOrder.Ascending)
7082 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7086 _curList.EnsureVisible(0);
7088 _curList.EnsureVisible(idx);
7091 private async Task GoInReplyToPostTree()
7093 if (_curPost == null) return;
7095 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
7097 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7101 var post = await tw.GetStatusApi(false, _curPost.StatusId);
7103 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7104 _curPost.InReplyToUser = post.InReplyToUser;
7105 _curPost.IsReply = post.IsReply;
7106 this.PurgeListViewItemCache();
7107 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7109 catch (WebApiException ex)
7111 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
7115 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7117 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7119 replyChains = new Stack<ReplyChain>();
7121 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7124 string inReplyToTabName;
7125 long inReplyToId = _curPost.InReplyToStatusId.Value;
7126 string inReplyToUser = _curPost.InReplyToUser;
7127 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7129 var inReplyToPosts = from tab in _statuses.Tabs.Values
7130 orderby tab != curTabClass
7131 from post in tab.Posts.Values
7132 where post.StatusId == inReplyToId
7133 let index = tab.IndexOf(post.StatusId)
7135 select new {Tab = tab, Index = index};
7137 var inReplyPost = inReplyToPosts.FirstOrDefault();
7138 if (inReplyPost == null)
7142 await Task.Run(async () =>
7144 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
7145 .ConfigureAwait(false);
7148 _statuses.AddPost(post);
7149 _statuses.DistributePosts();
7152 catch (WebApiException ex)
7154 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
7155 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7159 this.RefreshTimeline();
7161 inReplyPost = inReplyToPosts.FirstOrDefault();
7162 if (inReplyPost == null)
7164 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7168 inReplyToTabName = inReplyPost.Tab.TabName;
7169 inReplyToIndex = inReplyPost.Index;
7171 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7172 DetailsListView listView = (DetailsListView)tabPage.Tag;
7174 if (_curTab != tabPage)
7176 this.ListTab.SelectTab(tabPage);
7179 this.SelectListItem(listView, inReplyToIndex);
7180 listView.EnsureVisible(inReplyToIndex);
7183 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7185 if (_curPost == null) return;
7187 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
7188 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7192 if (_curPost.InReplyToStatusId != null)
7194 var posts = from t in _statuses.Tabs
7195 from p in t.Value.Posts
7196 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7197 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7199 orderby isForward ? indexOf : indexOf * -1
7200 orderby t.Value != curTabClass
7201 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7204 var postList = posts.ToList();
7205 for (int i = postList.Count - 1; i >= 0; i--)
7208 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7210 postList.RemoveAt(index);
7213 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7214 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7215 if (post == null) post = postList.First();
7216 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7217 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7218 SelectListItem(listView, post.Index);
7219 listView.EnsureVisible(post.Index);
7221 catch (InvalidOperationException)
7229 if (replyChains == null || replyChains.Count < 1)
7231 var posts = from t in _statuses.Tabs
7232 from p in t.Value.Posts
7233 where p.Value.InReplyToStatusId == _curPost.StatusId
7234 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7237 orderby t.Value != curTabClass
7238 select new {Tab = t.Value, Index = indexOf};
7241 var post = posts.First();
7242 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7243 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7244 SelectListItem(listView, post.Index);
7245 listView.EnsureVisible(post.Index);
7247 catch (InvalidOperationException)
7254 ReplyChain chainHead = replyChains.Pop();
7255 if (chainHead.InReplyToId == _curPost.StatusId)
7257 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7266 ListTab.SelectTab(chainHead.OriginalTab);
7272 SelectListItem(_curList, idx);
7273 _curList.EnsureVisible(idx);
7279 this.GoBackInReplyToPostTree(parallel);
7285 private void GoBackSelectPostChain()
7287 if (this.selectPostChains.Count > 1)
7296 this.selectPostChains.Pop();
7297 var tabPostPair = this.selectPostChains.Peek();
7299 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7301 if (tabPostPair.Item2 != null)
7303 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7304 if (idx == -1) continue; //該当ポストが存在しないので無視
7307 tp = tabPostPair.Item1;
7309 this.selectPostChains.Pop();
7311 catch (InvalidOperationException)
7317 while (this.selectPostChains.Count > 1);
7322 //履歴が残り1つであればクリアしておく
7323 if (this.selectPostChains.Count == 1)
7324 this.selectPostChains.Clear();
7328 DetailsListView lst = (DetailsListView)tp.Tag;
7329 this.ListTab.SelectedTab = tp;
7332 SelectListItem(lst, idx);
7333 lst.EnsureVisible(idx);
7339 private void PushSelectPostChain()
7341 int count = this.selectPostChains.Count;
7344 var p = this.selectPostChains.Peek();
7345 if (p.Item1 == this._curTab)
7347 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7348 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7351 if (count >= 2500) TrimPostChain();
7352 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7355 private void TrimPostChain()
7357 if (this.selectPostChains.Count <= 2000) return;
7358 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7359 for (int i = 0; i < 2000; i++)
7361 p.Push(this.selectPostChains.Pop());
7363 this.selectPostChains.Clear();
7364 for (int i = 0; i < 2000; i++)
7366 this.selectPostChains.Push(p.Pop());
7370 private bool GoStatus(long statusId)
7372 if (statusId == 0) return false;
7373 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7375 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7377 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7378 ListTab.SelectedIndex = tabidx;
7379 SelectListItem(_curList, idx);
7380 _curList.EnsureVisible(idx);
7387 private bool GoDirectMessage(long statusId)
7389 if (statusId == 0) return false;
7390 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7392 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7394 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7395 ListTab.SelectedIndex = tabidx;
7396 SelectListItem(_curList, idx);
7397 _curList.EnsureVisible(idx);
7404 private void MyList_MouseClick(object sender, MouseEventArgs e)
7406 _anchorFlag = false;
7409 private void StatusText_Enter(object sender, EventArgs e)
7411 // フォーカスの戻り先を StatusText に設定
7412 this.Tag = StatusText;
7413 StatusText.BackColor = _clInputBackcolor;
7416 public Color InputBackColor
7418 get { return _clInputBackcolor; }
7419 set { _clInputBackcolor = value; }
7422 private void StatusText_Leave(object sender, EventArgs e)
7424 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7425 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7426 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7429 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7432 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7435 e.SuppressKeyPress = true;
7438 this.StatusText_TextChanged(null, null);
7440 if (asyncTask != null)
7444 private void SaveConfigsAll(bool ifModified)
7448 SaveConfigsCommon();
7455 if (ModifySettingCommon) SaveConfigsCommon();
7456 if (ModifySettingLocal) SaveConfigsLocal();
7457 if (ModifySettingAtId) SaveConfigsAtId();
7461 private void SaveConfigsAtId()
7463 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7465 ModifySettingAtId = false;
7466 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7470 private void SaveConfigsCommon()
7472 if (_ignoreConfigSave) return;
7474 ModifySettingCommon = false;
7477 _cfgCommon.UserName = tw.Username;
7478 _cfgCommon.UserId = tw.UserId;
7479 _cfgCommon.Token = tw.AccessToken;
7480 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7482 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7483 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7485 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7488 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7489 switch (_statuses.SortMode)
7491 case ComparerMode.Nickname: //ニックネーム
7492 _cfgCommon.SortColumn = 1;
7494 case ComparerMode.Data: //本文
7495 _cfgCommon.SortColumn = 2;
7497 case ComparerMode.Id: //時刻=発言Id
7498 _cfgCommon.SortColumn = 3;
7500 case ComparerMode.Name: //名前
7501 _cfgCommon.SortColumn = 4;
7503 case ComparerMode.Source: //Source
7504 _cfgCommon.SortColumn = 7;
7508 _cfgCommon.HashTags = HashMgr.HashHistories;
7509 if (HashMgr.IsPermanent)
7511 _cfgCommon.HashSelected = HashMgr.UseHash;
7515 _cfgCommon.HashSelected = "";
7517 _cfgCommon.HashIsHead = HashMgr.IsHead;
7518 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7519 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7520 if (ToolStripFocusLockMenuItem != null &&
7521 ToolStripFocusLockMenuItem.IsDisposed == false)
7523 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7525 _cfgCommon.TrackWord = tw.TrackWord;
7526 _cfgCommon.AllAtReply = tw.AllAtReply;
7527 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7528 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7534 private void SaveConfigsLocal()
7536 if (_ignoreConfigSave) return;
7539 ModifySettingLocal = false;
7540 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7541 _cfgLocal.FormSize = _mySize;
7542 _cfgLocal.FormLocation = _myLoc;
7543 _cfgLocal.SplitterDistance = _mySpDis;
7544 _cfgLocal.PreviewDistance = _mySpDis3;
7545 _cfgLocal.StatusMultiline = StatusText.Multiline;
7546 _cfgLocal.StatusTextHeight = _mySpDis2;
7548 _cfgLocal.FontUnread = _fntUnread;
7549 _cfgLocal.ColorUnread = _clUnread;
7550 _cfgLocal.FontRead = _fntReaded;
7551 _cfgLocal.ColorRead = _clReaded;
7552 _cfgLocal.FontDetail = _fntDetail;
7553 _cfgLocal.ColorDetail = _clDetail;
7554 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7555 _cfgLocal.ColorDetailLink = _clDetailLink;
7556 _cfgLocal.ColorFav = _clFav;
7557 _cfgLocal.ColorOWL = _clOWL;
7558 _cfgLocal.ColorRetweet = _clRetweet;
7559 _cfgLocal.ColorSelf = _clSelf;
7560 _cfgLocal.ColorAtSelf = _clAtSelf;
7561 _cfgLocal.ColorTarget = _clTarget;
7562 _cfgLocal.ColorAtTarget = _clAtTarget;
7563 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7564 _cfgLocal.ColorAtTo = _clAtTo;
7565 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7566 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7567 _cfgLocal.ColorInputFont = _clInputFont;
7568 _cfgLocal.FontInputFont = _fntInputFont;
7570 if (_ignoreConfigSave) return;
7575 private void SaveConfigsTabs()
7577 var tabsSetting = new SettingTabs();
7579 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7580 .Select(x => this._statuses.Tabs[x.Text])
7581 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7583 foreach (var tab in tabs)
7585 if (!tab.IsPermanentTabType)
7588 var tabSetting = new SettingTabs.SettingTabItem
7590 TabName = tab.TabName,
7591 TabType = tab.TabType,
7592 UnreadManage = tab.UnreadManage,
7593 Protected = tab.Protected,
7594 Notify = tab.Notify,
7595 SoundFile = tab.SoundFile,
7598 var filterTab = tab as FilterTabModel;
7599 if (filterTab != null)
7600 tabSetting.FilterArray = filterTab.FilterArray;
7602 var userTab = tab as UserTimelineTabModel;
7603 if (userTab != null)
7604 tabSetting.User = userTab.ScreenName;
7606 var searchTab = tab as PublicSearchTabModel;
7607 if (searchTab != null)
7609 tabSetting.SearchWords = searchTab.SearchWords;
7610 tabSetting.SearchLang = searchTab.SearchLang;
7613 var listTab = tab as ListTimelineTabModel;
7614 if (listTab != null)
7615 tabSetting.ListInfo = listTab.ListInfo;
7617 tabsSetting.Tabs.Add(tabSetting);
7623 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7626 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7627 if (ret != DialogResult.OK)
7630 var match = Twitter.StatusUrlRegex.Match(inputText);
7633 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7634 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7640 var statusId = long.Parse(match.Groups["StatusId"].Value);
7641 await this.OpenRelatedTab(statusId);
7643 catch (TabException ex)
7645 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7649 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7651 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7652 Properties.Resources.SaveLogMenuItem_ClickText2,
7653 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7654 if (rslt == DialogResult.Cancel) return;
7656 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7657 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7658 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7659 SaveFileDialog1.FilterIndex = 0;
7660 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7661 SaveFileDialog1.RestoreDirectory = true;
7663 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7665 if (!SaveFileDialog1.ValidateNames) return;
7666 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7668 if (rslt == DialogResult.Yes)
7671 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7673 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7674 string protect = "";
7675 if (post.IsProtect) protect = "Protect";
7676 sw.WriteLine(post.Nickname + "\t" +
7677 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7678 post.CreatedAt.ToString() + "\t" +
7679 post.ScreenName + "\t" +
7680 post.StatusId.ToString() + "\t" +
7681 post.ImageUrl + "\t" +
7682 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7688 foreach (int idx in _curList.SelectedIndices)
7690 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7691 string protect = "";
7692 if (post.IsProtect) protect = "Protect";
7693 sw.WriteLine(post.Nickname + "\t" +
7694 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7695 post.CreatedAt.ToString() + "\t" +
7696 post.ScreenName + "\t" +
7697 post.StatusId.ToString() + "\t" +
7698 post.ImageUrl + "\t" +
7699 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7705 this.TopMost = this._cfgCommon.AlwaysTop;
7708 private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
7711 bool KeyRes = CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out asyncTask);
7714 e.IsInputKey = true;
7718 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
7720 var shortcut = (Shortcut)e.KeyData;
7723 case Shortcut.CtrlA:
7724 case Shortcut.CtrlC:
7725 case Shortcut.CtrlIns:
7729 // その他のショートカットキーは無効にする
7730 e.IsInputKey = true;
7736 if (asyncTask != null)
7739 public bool TabRename(ref string tabName)
7742 string newTabText = null;
7743 using (InputTabName inputName = new InputTabName())
7745 inputName.TabName = tabName;
7746 inputName.ShowDialog();
7747 if (inputName.DialogResult == DialogResult.Cancel) return false;
7748 newTabText = inputName.TabName;
7750 this.TopMost = this._cfgCommon.AlwaysTop;
7751 if (!string.IsNullOrEmpty(newTabText))
7754 for (int i = 0; i < ListTab.TabCount; i++)
7756 if (ListTab.TabPages[i].Text == newTabText)
7758 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
7759 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7764 for (int i = 0; i < ListTab.TabCount; i++)
7766 if (ListTab.TabPages[i].Text == tabName)
7768 ListTab.TabPages[i].Text = newTabText;
7772 _statuses.RenameTab(tabName, newTabText);
7774 SaveConfigsCommon();
7776 _rclickTabName = newTabText;
7777 tabName = newTabText;
7786 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7788 if (e.Button == MouseButtons.Middle)
7790 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7792 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7794 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7795 this.SaveConfigsTabs();
7802 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7804 string tn = ListTab.SelectedTab.Text;
7808 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7810 if (this._cfgCommon.TabMouseLock) return;
7811 Point cpos = new Point(e.X, e.Y);
7812 if (e.Button == MouseButtons.Left)
7814 for (int i = 0; i < ListTab.TabPages.Count; i++)
7816 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7819 _tabMouseDownPoint = e.Location;
7830 private void ListTab_DragEnter(object sender, DragEventArgs e)
7832 if (e.Data.GetDataPresent(typeof(TabPage)))
7833 e.Effect = DragDropEffects.Move;
7835 e.Effect = DragDropEffects.None;
7838 private void ListTab_DragDrop(object sender, DragEventArgs e)
7840 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7845 Point cpos = new Point(e.X, e.Y);
7846 Point spos = ListTab.PointToClient(cpos);
7848 for (i = 0; i < ListTab.TabPages.Count; i++)
7850 Rectangle rect = ListTab.GetTabRect(i);
7851 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7852 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7854 tn = ListTab.TabPages[i].Text;
7855 if (spos.X <= (rect.Left + rect.Right) / 2)
7864 //タブのないところにドロップ->最後尾へ移動
7865 if (string.IsNullOrEmpty(tn))
7867 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7869 i = ListTab.TabPages.Count - 1;
7872 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7873 if (tp.Text == tn) return;
7875 ReOrderTab(tp.Text, tn, bef);
7878 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7880 var baseIndex = this.GetTabPageIndex(baseTabText);
7881 if (baseIndex == -1)
7884 var targetIndex = this.GetTabPageIndex(targetTabText);
7885 if (targetIndex == -1)
7888 using (ControlTransaction.Layout(this.ListTab))
7890 var mTp = this.ListTab.TabPages[targetIndex];
7891 this.ListTab.TabPages.Remove(mTp);
7893 if (targetIndex < baseIndex)
7896 if (isBeforeBaseTab)
7897 ListTab.TabPages.Insert(baseIndex, mTp);
7899 ListTab.TabPages.Insert(baseIndex + 1, mTp);
7905 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7907 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7908 //isReply:true=@,false=DM
7909 if (!StatusText.Enabled) return;
7910 if (_curList == null) return;
7911 if (_curTab == null) return;
7912 if (!this.ExistCurrentPost) return;
7914 // 複数あてリプライはReplyではなく通常ポスト
7915 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7916 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7917 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7919 if (_curList.SelectedIndices.Count > 0)
7922 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7925 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7928 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7929 StatusText.SelectionStart = StatusText.Text.Length;
7931 this.inReplyTo = null;
7934 if (string.IsNullOrEmpty(StatusText.Text))
7938 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7939 StatusText.Text = "@" + _curPost.ScreenName + " ";
7941 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7942 var inReplyToScreenName = this._curPost.ScreenName;
7943 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7951 //1件選んでEnter or DoubleClick
7952 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7954 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7957 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7958 var inReplyToScreenName = this._curPost.ScreenName;
7959 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7963 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7966 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7969 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7970 this.inReplyTo = null;
7975 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7976 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7977 var inReplyToScreenName = this._curPost.ScreenName;
7978 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7985 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7986 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7987 this.inReplyTo = null;
7992 //1件選んでCtrl-Rの場合(返信先操作せず)
7993 int sidx = StatusText.SelectionStart;
7994 string id = "@" + _curPost.ScreenName + " ";
7997 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8002 StatusText.Text = StatusText.Text.Insert(sidx, id);
8004 //if (StatusText.Text.StartsWith("@"))
8007 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8008 // sidx += 5 + _curPost.ScreenName.Length;
8013 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8014 // sidx += 3 + _curPost.ScreenName.Length;
8016 StatusText.SelectionStart = sidx;
8019 //_reply_to_name = null;
8027 if (!isAuto && !isReply) return;
8029 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8033 //Enter or DoubleClick
8035 string sTxt = StatusText.Text;
8036 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
8039 this.inReplyTo = null;
8041 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8043 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8044 if (!sTxt.Contains("@" + post.ScreenName + " "))
8046 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8047 //sTxt = "@" + post.ScreenName + " " + sTxt;
8050 StatusText.Text = sTxt;
8055 if (_curList.SelectedIndices.Count > 1)
8060 int sidx = StatusText.SelectionStart;
8061 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8063 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8064 if (!ids.Contains("@" + post.ScreenName + " ") &&
8065 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8067 ids += "@" + post.ScreenName + " ";
8071 foreach (string nm in post.ReplyToList)
8073 if (!ids.Contains("@" + nm + " ") &&
8074 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8076 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8078 ids += "@" + m.Result("${id}") + " ";
8080 ids += "@" + nm + " ";
8085 if (ids.Length == 0) return;
8086 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8088 StatusText.Text = ". " + StatusText.Text;
8090 this.inReplyTo = null;
8094 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8099 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8101 //if (StatusText.Text.StartsWith("@"))
8103 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8104 // sidx += 2 + ids.Length;
8108 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8109 // sidx += 1 + ids.Length;
8111 StatusText.SelectionStart = sidx;
8117 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8120 int sidx = StatusText.SelectionStart;
8121 PostClass post = _curPost;
8122 if (!ids.Contains("@" + post.ScreenName + " ") &&
8123 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8125 ids += "@" + post.ScreenName + " ";
8127 foreach (string nm in post.ReplyToList)
8129 if (!ids.Contains("@" + nm + " ") &&
8130 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8132 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8134 ids += "@" + m.Result("${id}") + " ";
8136 ids += "@" + nm + " ";
8139 if (!string.IsNullOrEmpty(post.RetweetedBy))
8141 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8142 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8144 ids += "@" + post.RetweetedBy + " ";
8147 if (ids.Length == 0) return;
8148 if (string.IsNullOrEmpty(StatusText.Text))
8151 StatusText.Text = ids;
8152 StatusText.SelectionStart = ids.Length;
8155 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8156 var inReplyToScreenName = this._curPost.ScreenName;
8157 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8163 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8168 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8170 StatusText.SelectionStart = sidx;
8176 StatusText.SelectionStart = StatusText.Text.Length;
8181 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8186 private static int iconCnt = 0;
8187 private static int blinkCnt = 0;
8188 private static bool blink = false;
8189 private static bool idle = false;
8191 private async Task RefreshTasktrayIcon()
8194 await this.Colorize();
8196 if (!TimerRefreshIcon.Enabled) return;
8197 //Static usCheckCnt As int = 0
8199 //Static iconDlListTopItem As ListViewItem = null
8201 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8202 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8204 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8206 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8212 //if (usCheckCnt > 300) //1min
8215 // if (!this.IsReceivedUserStream)
8217 // TraceOut("ReconnectUserStream");
8218 // tw.ReconnectUserStream();
8222 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8224 if (iconCnt >= this.NIconRefresh.Length)
8232 SaveConfigsAll(true);
8237 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8239 _myStatusError = false;
8243 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8244 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8246 if (blinkCnt > 0) return;
8248 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8250 NotifyIcon1.Icon = ReplyIcon;
8254 NotifyIcon1.Icon = ReplyIconBlink;
8262 //優先度:エラー→オフライン→アイドル
8266 NotifyIcon1.Icon = NIconAtRed;
8269 if (_myStatusOnline)
8271 NotifyIcon1.Icon = NIconAt;
8275 NotifyIcon1.Icon = NIconAtSmoke;
8279 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8282 await this.RefreshTasktrayIcon();
8285 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8287 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8288 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8290 if (ListTab != null && ListTab.SelectedTab != null)
8291 _rclickTabName = ListTab.SelectedTab.Text;
8296 if (_statuses == null) return;
8297 if (_statuses.Tabs == null) return;
8299 TabModel tb = _statuses.Tabs[_rclickTabName];
8300 if (tb == null) return;
8302 NotifyDispMenuItem.Checked = tb.Notify;
8303 this.NotifyTbMenuItem.Checked = tb.Notify;
8305 soundfileListup = true;
8306 SoundFileComboBox.Items.Clear();
8307 this.SoundFileTbComboBox.Items.Clear();
8308 SoundFileComboBox.Items.Add("");
8309 this.SoundFileTbComboBox.Items.Add("");
8310 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8311 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8313 oDir = oDir.GetDirectories("Sounds")[0];
8315 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8317 SoundFileComboBox.Items.Add(oFile.Name);
8318 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8320 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8321 if (idx == -1) idx = 0;
8322 SoundFileComboBox.SelectedIndex = idx;
8323 this.SoundFileTbComboBox.SelectedIndex = idx;
8324 soundfileListup = false;
8325 UreadManageMenuItem.Checked = tb.UnreadManage;
8326 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8328 TabMenuControl(_rclickTabName);
8331 private void TabMenuControl(string tabName)
8333 var tabInfo = _statuses.GetTabByName(tabName);
8335 this.FilterEditMenuItem.Enabled = true;
8336 this.EditRuleTbMenuItem.Enabled = true;
8338 if (tabInfo.IsDefaultTabType)
8340 this.ProtectTabMenuItem.Enabled = false;
8341 this.ProtectTbMenuItem.Enabled = false;
8345 this.ProtectTabMenuItem.Enabled = true;
8346 this.ProtectTbMenuItem.Enabled = true;
8349 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8351 this.ProtectTabMenuItem.Checked = true;
8352 this.ProtectTbMenuItem.Checked = true;
8353 this.DeleteTabMenuItem.Enabled = false;
8354 this.DeleteTbMenuItem.Enabled = false;
8358 this.ProtectTabMenuItem.Checked = false;
8359 this.ProtectTbMenuItem.Checked = false;
8360 this.DeleteTabMenuItem.Enabled = true;
8361 this.DeleteTbMenuItem.Enabled = true;
8365 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8367 var checkState = ((ToolStripMenuItem)sender).Checked;
8370 this.ProtectTbMenuItem.Checked = checkState;
8371 this.ProtectTabMenuItem.Checked = checkState;
8374 this.DeleteTabMenuItem.Enabled = !checkState;
8375 this.DeleteTbMenuItem.Enabled = !checkState;
8377 if (string.IsNullOrEmpty(_rclickTabName)) return;
8378 _statuses.Tabs[_rclickTabName].Protected = checkState;
8383 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8385 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8386 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8388 if (string.IsNullOrEmpty(_rclickTabName)) return;
8389 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8394 public void ChangeTabUnreadManage(string tabName, bool isManage)
8396 var idx = this.GetTabPageIndex(tabName);
8400 _statuses.Tabs[tabName].UnreadManage = isManage;
8401 if (this._cfgCommon.TabIconDisp)
8403 if (_statuses.Tabs[tabName].UnreadCount > 0)
8404 ListTab.TabPages[idx].ImageIndex = 0;
8406 ListTab.TabPages[idx].ImageIndex = -1;
8409 if (_curTab.Text == tabName)
8411 this.PurgeListViewItemCache();
8415 SetMainWindowTitle();
8416 SetStatusLabelUrl();
8417 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8420 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8422 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8423 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8425 if (string.IsNullOrEmpty(_rclickTabName)) return;
8427 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8432 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8434 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8436 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8441 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8443 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8445 RemoveSpecifiedTab(_rclickTabName, true);
8449 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8451 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8453 using (var fltDialog = new FilterDialog())
8455 fltDialog.Owner = this;
8456 fltDialog.SetCurrent(_rclickTabName);
8457 fltDialog.ShowDialog(this);
8459 this.TopMost = this._cfgCommon.AlwaysTop;
8461 this.ApplyPostFilters();
8465 private void AddTabMenuItem_Click(object sender, EventArgs e)
8467 string tabName = null;
8468 MyCommon.TabUsageType tabUsage;
8469 using (InputTabName inputName = new InputTabName())
8471 inputName.TabName = _statuses.MakeTabName("MyTab");
8472 inputName.IsShowUsage = true;
8473 inputName.ShowDialog();
8474 if (inputName.DialogResult == DialogResult.Cancel) return;
8475 tabName = inputName.TabName;
8476 tabUsage = inputName.Usage;
8478 this.TopMost = this._cfgCommon.AlwaysTop;
8479 if (!string.IsNullOrEmpty(tabName))
8482 ListElement list = null;
8483 if (tabUsage == MyCommon.TabUsageType.Lists)
8485 using (ListAvailable listAvail = new ListAvailable())
8487 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8488 if (listAvail.SelectedList == null) return;
8489 list = listAvail.SelectedList;
8496 case MyCommon.TabUsageType.UserDefined:
8497 tab = new FilterTabModel(tabName);
8499 case MyCommon.TabUsageType.PublicSearch:
8500 tab = new PublicSearchTabModel(tabName);
8502 case MyCommon.TabUsageType.Lists:
8503 tab = new ListTimelineTabModel(tabName, list);
8509 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8511 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8512 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8518 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8520 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8521 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8523 if (tabUsage == MyCommon.TabUsageType.Lists)
8525 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8526 var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8527 this.GetListTimelineAsync(listTab);
8533 private void TabMenuItem_Click(object sender, EventArgs e)
8535 using (var fltDialog = new FilterDialog())
8537 fltDialog.Owner = this;
8540 foreach (int idx in _curList.SelectedIndices)
8544 if (!SelectTab(out tabName)) return;
8546 fltDialog.SetCurrent(tabName);
8547 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8549 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8553 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8555 fltDialog.ShowDialog(this);
8556 this.TopMost = this._cfgCommon.AlwaysTop;
8560 this.ApplyPostFilters();
8562 if (this.ListTab.SelectedTab != null &&
8563 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8565 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8569 protected override bool ProcessDialogKey(Keys keyData)
8571 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8572 if ((keyData & Keys.KeyCode) == Keys.Enter)
8574 if (StatusText.Focused)
8576 bool _NewLine = false;
8579 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8581 if (StatusText.Multiline)
8583 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8585 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8589 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8593 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8595 if (StatusText.Multiline)
8597 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8599 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8603 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8609 if (StatusText.Multiline)
8611 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8613 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8614 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8618 if (((keyData & Keys.Shift) == Keys.Shift) ||
8619 (((keyData & Keys.Control) != Keys.Control) &&
8620 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8626 int pos1 = StatusText.SelectionStart;
8627 if (StatusText.SelectionLength > 0)
8629 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8631 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8632 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8637 PostButton_Click(null, null);
8641 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8642 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8643 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8645 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8650 return base.ProcessDialogKey(keyData);
8653 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8655 MakeReplyOrDirectStatus(false, true, true);
8658 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8663 if (_curList.SelectedIndices.Count == 0) return;
8666 if (!SelectTab(out tabName)) return;
8668 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8672 if (tab.TabType != MyCommon.TabUsageType.Mute)
8674 this.MoveOrCopy(out mv, out mk);
8678 // ミュートタブでは常に MoveMatches を true にする
8683 List<string> ids = new List<string>();
8684 foreach (int idx in _curList.SelectedIndices)
8686 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8687 if (!ids.Contains(post.ScreenName))
8689 PostFilterRule fc = new PostFilterRule();
8690 ids.Add(post.ScreenName);
8691 if (post.RetweetedId == null)
8693 fc.FilterName = post.ScreenName;
8697 fc.FilterName = post.RetweetedBy;
8699 fc.UseNameField = true;
8700 fc.MoveMatches = mv;
8701 fc.MarkMatches = mk;
8702 fc.UseRegex = false;
8703 fc.FilterByUrl = false;
8709 List<string> atids = new List<string>();
8710 foreach (string id in ids)
8712 atids.Add("@" + id);
8714 int cnt = AtIdSupl.ItemCount;
8715 AtIdSupl.AddRangeItem(atids.ToArray());
8716 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8719 this.ApplyPostFilters();
8723 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8725 if (this._curList.SelectedIndices.Count == 0)
8728 // タブ選択ダイアログを表示(or追加)
8730 if (!this.SelectTab(out tabName))
8733 var currentTab = this._statuses.Tabs[this._curTab.Text];
8734 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8738 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8740 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8741 this.MoveOrCopy(out mv, out mk);
8745 // ミュートタブでは常に MoveMatches を true にする
8750 // 振り分けルールに追加するSource
8751 var sources = new HashSet<string>();
8753 foreach (var idx in this._curList.SelectedIndices.Cast<int>())
8755 var post = currentTab[idx];
8756 var filterSource = post.Source;
8758 if (sources.Add(filterSource))
8760 var filter = new PostFilterRule
8762 FilterSource = filterSource,
8766 FilterByUrl = false,
8768 filterTab.AddFilter(filter);
8772 this.ApplyPostFilters();
8773 this.SaveConfigsTabs();
8776 private bool SelectTab(out string tabName)
8783 using (var dialog = new TabsDialog(_statuses))
8785 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8787 var selectedTab = dialog.SelectedTab;
8788 tabName = selectedTab == null ? null : selectedTab.TabName;
8791 ListTab.SelectedTab.Focus();
8793 if (tabName == null)
8795 using (InputTabName inputName = new InputTabName())
8797 inputName.TabName = _statuses.MakeTabName("MyTab");
8798 inputName.ShowDialog();
8799 if (inputName.DialogResult == DialogResult.Cancel) return false;
8800 tabName = inputName.TabName;
8802 this.TopMost = this._cfgCommon.AlwaysTop;
8803 if (!string.IsNullOrEmpty(tabName))
8805 var tab = new FilterTabModel(tabName);
8806 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8808 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8809 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8827 private void MoveOrCopy(out bool move, out bool mark)
8831 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8832 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8840 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8841 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8851 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8856 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8861 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8863 if (StatusText.Focused)
8866 StatusText.SelectAll();
8870 // ListView上でのCtrl+A
8871 NativeMethods.SelectAllItems(this._curList);
8875 private void MoveMiddle()
8881 if (_curList.SelectedIndices.Count == 0) return;
8883 int idx = _curList.SelectedIndices[0];
8885 _item = _curList.GetItemAt(0, 25);
8891 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8893 idx2 = _curList.VirtualListSize - 1;
8897 idx -= Math.Abs(idx1 - idx2) / 2;
8898 if (idx < 0) idx = 0;
8900 _curList.EnsureVisible(_curList.VirtualListSize - 1);
8901 _curList.EnsureVisible(idx);
8904 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8906 var linkElements = this.PostBrowser.Document.Links.Cast<HtmlElement>()
8907 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
8910 if (linkElements.Length > 0)
8912 UrlDialog.ClearUrl();
8914 string openUrlStr = "";
8916 if (linkElements.Length == 1)
8918 // ツイートに含まれる URL が 1 つのみの場合
8919 // => OpenURL ダイアログを表示せずにリンクを開く
8924 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8926 catch (ArgumentException)
8935 if (string.IsNullOrEmpty(urlStr)) return;
8936 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8938 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8939 await this.OpenUriAsync(new Uri(openUrlStr));
8943 // ツイートに含まれる URL が複数ある場合
8944 // => OpenURL を表示しユーザーが選択したリンクを開く
8946 foreach (var linkElm in linkElements)
8949 string linkText = "";
8953 urlStr = linkElm.GetAttribute("title");
8954 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8955 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8956 linkText = linkElm.InnerText;
8958 catch (ArgumentException)
8967 if (string.IsNullOrEmpty(urlStr)) continue;
8968 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8972 if (UrlDialog.ShowDialog() == DialogResult.OK)
8974 openUrlStr = UrlDialog.SelectedUrl;
8976 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8977 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8984 this.TopMost = this._cfgCommon.AlwaysTop;
8989 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8991 if (string.IsNullOrEmpty(_rclickTabName)) return;
8992 ClearTab(_rclickTabName, true);
8995 private void ClearTab(string tabName, bool showWarning)
8999 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9000 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9006 _statuses.ClearTabIds(tabName);
9007 if (ListTab.SelectedTab.Text == tabName)
9010 _anchorFlag = false;
9011 this.PurgeListViewItemCache();
9015 foreach (TabPage tb in ListTab.TabPages)
9017 if (tb.Text == tabName)
9020 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9024 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9026 SetMainWindowTitle();
9027 SetStatusLabelUrl();
9030 private static long followers = 0;
9032 private void SetMainWindowTitle()
9035 StringBuilder ttl = new StringBuilder(256);
9038 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9039 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9040 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9041 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9043 foreach (var tab in _statuses.Tabs.Values)
9045 ur += tab.UnreadCount;
9050 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9051 ttl.Append(Application.ProductName);
9053 switch (this._cfgCommon.DispLatestPost)
9055 case MyCommon.DispTitleEnum.Ver:
9056 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9058 case MyCommon.DispTitleEnum.Post:
9059 if (_history != null && _history.Count > 1)
9060 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9062 case MyCommon.DispTitleEnum.UnreadRepCount:
9063 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9065 case MyCommon.DispTitleEnum.UnreadAllCount:
9066 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9068 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9069 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9071 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9072 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9074 case MyCommon.DispTitleEnum.OwnStatus:
9075 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9076 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9082 this.Text = ttl.ToString();
9084 catch (AccessViolationException)
9086 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9090 private string GetStatusLabelText()
9093 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9094 if (_statuses == null) return "";
9095 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9096 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9097 if (tbRep == null || tbDm == null) return "";
9098 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9103 StringBuilder slbl = new StringBuilder(256);
9106 foreach (var tab in _statuses.Tabs.Values)
9108 ur += tab.UnreadCount;
9110 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9112 tur = tab.UnreadCount;
9123 UnreadAtCounter = urat;
9125 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
9127 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
9128 if (this._cfgCommon.TimelinePeriod == 0)
9130 slbl.Append(Properties.Resources.SetStatusLabelText2);
9134 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9136 return slbl.ToString();
9139 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9143 if (this.InvokeRequired && !this.IsDisposed)
9145 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
9149 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9150 SetApiStatusLabel(endpointName);
9153 catch (ObjectDisposedException)
9157 catch (InvalidOperationException)
9163 private void SetApiStatusLabel(string endpointName = null)
9165 if (_curTab == null)
9167 this.toolStripApiGauge.ApiEndpoint = null;
9171 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9173 if (endpointName == null)
9178 case MyCommon.TabUsageType.Home:
9179 case MyCommon.TabUsageType.UserDefined:
9180 endpointName = "/statuses/home_timeline";
9183 case MyCommon.TabUsageType.Mentions:
9184 endpointName = "/statuses/mentions_timeline";
9187 case MyCommon.TabUsageType.Favorites:
9188 endpointName = "/favorites/list";
9191 case MyCommon.TabUsageType.DirectMessage:
9192 endpointName = "/direct_messages";
9195 case MyCommon.TabUsageType.UserTimeline:
9196 endpointName = "/statuses/user_timeline";
9199 case MyCommon.TabUsageType.Lists:
9200 endpointName = "/lists/statuses";
9203 case MyCommon.TabUsageType.PublicSearch:
9204 endpointName = "/search/tweets";
9207 case MyCommon.TabUsageType.Related:
9208 endpointName = "/statuses/show/:id";
9215 this.toolStripApiGauge.ApiEndpoint = endpointName;
9219 // 表示中のタブに関連する endpoint であれば更新
9222 switch (endpointName)
9224 case "/statuses/home_timeline":
9225 update = tabType == MyCommon.TabUsageType.Home ||
9226 tabType == MyCommon.TabUsageType.UserDefined;
9229 case "/statuses/mentions_timeline":
9230 update = tabType == MyCommon.TabUsageType.Mentions;
9233 case "/favorites/list":
9234 update = tabType == MyCommon.TabUsageType.Favorites;
9237 case "/direct_messages:":
9238 update = tabType == MyCommon.TabUsageType.DirectMessage;
9241 case "/statuses/user_timeline":
9242 update = tabType == MyCommon.TabUsageType.UserTimeline;
9245 case "/lists/statuses":
9246 update = tabType == MyCommon.TabUsageType.Lists;
9249 case "/search/tweets":
9250 update = tabType == MyCommon.TabUsageType.PublicSearch;
9253 case "/statuses/show/:id":
9254 update = tabType == MyCommon.TabUsageType.Related;
9263 this.toolStripApiGauge.ApiEndpoint = endpointName;
9269 private void SetStatusLabelUrl()
9271 StatusLabelUrl.Text = GetStatusLabelText();
9274 public void SetStatusLabel(string text)
9276 StatusLabel.Text = text;
9279 private static StringBuilder ur = new StringBuilder(64);
9281 private void SetNotifyIconText()
9283 // タスクトレイアイコンのツールチップテキスト書き換え
9285 ur.Remove(0, ur.Length);
9286 if (this._cfgCommon.DispUsername)
9288 ur.Append(tw.Username);
9291 ur.Append(Application.ProductName);
9293 ur.Append("(Debug Build)");
9295 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9298 ur.Append(UnreadCounter);
9300 ur.Append(UnreadAtCounter);
9303 NotifyIcon1.Text = ur.ToString();
9306 internal void CheckReplyTo(string StatusText)
9310 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9312 foreach (Match hm in m)
9314 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9316 hstr += "#" + hm.Result("$3") + " ";
9317 HashSupl.AddItem("#" + hm.Result("$3"));
9320 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9322 hstr += HashMgr.UseHash;
9324 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9326 // 本当にリプライ先指定すべきかどうかの判定
9327 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9329 if (this._cfgCommon.UseAtIdSupplement)
9331 int bCnt = AtIdSupl.ItemCount;
9332 foreach (Match mid in m)
9334 AtIdSupl.AddItem(mid.Result("${id}"));
9336 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9339 // リプライ先ステータスIDの指定がない場合は指定しない
9340 if (this.inReplyTo == null)
9344 // 次の条件を満たす場合に in_reply_to_status_id 指定
9345 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9346 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9347 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9351 var inReplyToScreenName = this.inReplyTo.Item2;
9352 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9354 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9358 foreach (Match mid in m)
9360 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9365 this.inReplyTo = null;
9368 private void TweenMain_Resize(object sender, EventArgs e)
9370 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9372 this.Visible = false;
9374 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9376 // 現在の DPI と設定保存時の DPI との比を取得する
9377 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9379 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9380 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9381 this.DesktopLocation = _cfgLocal.FormLocation;
9382 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9385 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9386 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9387 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9389 this.SplitContainer1.SplitterDistance = splitterDistance;
9393 StatusText.Multiline = _cfgLocal.StatusMultiline;
9394 if (StatusText.Multiline)
9396 var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9397 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9398 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9400 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9402 StatusText.Height = statusTextHeight;
9406 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9408 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9412 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9413 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9415 this.SplitContainer3.SplitterDistance = previewDistance;
9418 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9419 this.SplitContainer3.Panel2Collapsed = true;
9421 _initialLayout = false;
9423 if (this.WindowState != FormWindowState.Minimized)
9425 _formWindowState = this.WindowState;
9429 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9431 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9432 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9433 if (PlaySoundMenuItem.Checked)
9435 this._cfgCommon.PlaySound = true;
9439 this._cfgCommon.PlaySound = false;
9441 ModifySettingCommon = true;
9444 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9446 if (this._initialLayout)
9449 int splitterDistance;
9450 switch (this.WindowState)
9452 case FormWindowState.Normal:
9453 splitterDistance = this.SplitContainer1.SplitterDistance;
9455 case FormWindowState.Maximized:
9456 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9457 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9458 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9459 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9465 this._mySpDis = splitterDistance;
9466 this.ModifySettingLocal = true;
9469 private async Task doRepliedStatusOpen()
9471 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9473 if (MyCommon.IsKeyDown(Keys.Shift))
9475 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9478 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9480 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9481 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9485 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9487 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9488 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9489 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9492 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9497 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9499 await this.doRepliedStatusOpen();
9503 /// UserPicture.Image に設定されている画像を破棄します。
9505 private void ClearUserPicture()
9507 if (this.UserPicture.Image != null)
9509 var oldImage = this.UserPicture.Image;
9510 this.UserPicture.Image = null;
9515 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9517 //発言詳細のアイコン右クリック時のメニュー制御
9518 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9520 string name = _curPost.ImageUrl;
9521 if (name != null && name.Length > 0)
9523 int idx = name.LastIndexOf('/');
9526 name = Path.GetFileName(name.Substring(idx));
9527 if (name.Contains("_normal.") || name.EndsWith("_normal", StringComparison.Ordinal))
9529 name = name.Replace("_normal", "");
9530 this.IconNameToolStripMenuItem.Text = name;
9531 this.IconNameToolStripMenuItem.Enabled = true;
9535 this.IconNameToolStripMenuItem.Enabled = false;
9536 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9541 this.IconNameToolStripMenuItem.Enabled = false;
9542 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9545 this.ReloadIconToolStripMenuItem.Enabled = true;
9547 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9549 this.SaveIconPictureToolStripMenuItem.Enabled = true;
9553 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9558 this.IconNameToolStripMenuItem.Enabled = false;
9559 this.ReloadIconToolStripMenuItem.Enabled = false;
9560 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9561 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9566 this.IconNameToolStripMenuItem.Enabled = false;
9567 this.ReloadIconToolStripMenuItem.Enabled = false;
9568 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9569 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9571 if (NameLabel.Tag != null)
9573 string id = (string)NameLabel.Tag;
9574 if (id == tw.Username)
9576 FollowToolStripMenuItem.Enabled = false;
9577 UnFollowToolStripMenuItem.Enabled = false;
9578 ShowFriendShipToolStripMenuItem.Enabled = false;
9579 ShowUserStatusToolStripMenuItem.Enabled = true;
9580 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9581 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9582 ListManageUserContextToolStripMenuItem3.Enabled = true;
9586 FollowToolStripMenuItem.Enabled = true;
9587 UnFollowToolStripMenuItem.Enabled = true;
9588 ShowFriendShipToolStripMenuItem.Enabled = true;
9589 ShowUserStatusToolStripMenuItem.Enabled = true;
9590 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9591 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9592 ListManageUserContextToolStripMenuItem3.Enabled = true;
9597 FollowToolStripMenuItem.Enabled = false;
9598 UnFollowToolStripMenuItem.Enabled = false;
9599 ShowFriendShipToolStripMenuItem.Enabled = false;
9600 ShowUserStatusToolStripMenuItem.Enabled = false;
9601 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9602 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9603 ListManageUserContextToolStripMenuItem3.Enabled = false;
9607 private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9609 if (_curPost == null) return;
9610 string name = _curPost.ImageUrl;
9611 await this.OpenUriInBrowserAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9614 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9616 if (this._curPost == null) return;
9618 await this.UserPicture.SetImageFromTask(async () =>
9620 var imageUrl = this._curPost.ImageUrl;
9622 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
9623 .ConfigureAwait(false);
9625 return await image.CloneAsync()
9626 .ConfigureAwait(false);
9630 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9632 if (_curPost == null) return;
9633 string name = _curPost.ImageUrl;
9634 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
9636 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
9638 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9644 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9646 if (_curPost == null) return;
9647 string name = _curPost.ImageUrl;
9649 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
9651 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9655 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
9657 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
9659 using (Graphics g = Graphics.FromImage(bmp2))
9661 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
9662 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
9664 bmp2.Save(this.SaveFileDialog1.FileName);
9670 //処理中にキャッシュアウトする可能性あり
9675 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9677 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9678 if (multiline != this.StatusText.Multiline)
9680 this.StatusText.Multiline = multiline;
9681 MultiLineMenuItem.Checked = multiline;
9682 ModifySettingLocal = true;
9686 private void StatusText_MultilineChanged(object sender, EventArgs e)
9688 if (this.StatusText.Multiline)
9689 this.StatusText.ScrollBars = ScrollBars.Vertical;
9691 this.StatusText.ScrollBars = ScrollBars.None;
9693 ModifySettingLocal = true;
9696 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9699 StatusText.Multiline = MultiLineMenuItem.Checked;
9700 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
9701 if (MultiLineMenuItem.Checked)
9703 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9704 SplitContainer2.SplitterDistance = 0;
9706 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9710 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9712 ModifySettingLocal = true;
9715 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9717 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9718 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9720 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9721 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9722 //Appendix A. Collected ABNF for URI
9723 //http://www.ietf.org/rfc/rfc3986.txt
9727 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9729 if (StatusText.SelectionLength > 0)
9731 string tmp = StatusText.SelectedText;
9732 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9733 if (tmp.StartsWith("http"))
9735 // 文字列が選択されている場合はその文字列について処理
9737 //nico.ms使用、nicovideoにマッチしたら変換
9738 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
9740 result = nicoms.Shorten(tmp);
9742 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9744 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9747 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9748 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9749 result = resultUri.AbsoluteUri;
9751 catch (WebApiException e)
9753 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9756 catch (UriFormatException e)
9758 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9767 if (!string.IsNullOrEmpty(result))
9769 urlUndo undotmp = new urlUndo();
9771 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
9772 StatusText.SelectedText = result;
9775 undotmp.Before = tmp;
9776 undotmp.After = result;
9778 if (urlUndoBuffer == null)
9780 urlUndoBuffer = new List<urlUndo>();
9781 UrlUndoToolStripMenuItem.Enabled = true;
9784 urlUndoBuffer.Add(undotmp);
9790 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9791 @"(?<url>(?<protocol>https?://)" +
9792 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9793 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9794 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9795 // 正規表現にマッチしたURL文字列をtinyurl化
9796 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9798 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9799 string tmp = mt.Result("${url}");
9800 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9801 urlUndo undotmp = new urlUndo();
9804 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9806 //nico.ms使用、nicovideoにマッチしたら変換
9807 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
9809 result = nicoms.Shorten(tmp);
9811 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9813 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9816 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9817 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9818 result = resultUri.AbsoluteUri;
9820 catch (HttpRequestException e)
9822 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9823 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9824 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9826 this.StatusLabel.Text = Converter_Type + ":" + message;
9829 catch (WebApiException e)
9831 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9834 catch (UriFormatException e)
9836 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9845 if (!string.IsNullOrEmpty(result))
9847 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9848 StatusText.SelectedText = result;
9850 undotmp.Before = mt.Result("${url}");
9851 undotmp.After = result;
9853 if (urlUndoBuffer == null)
9855 urlUndoBuffer = new List<urlUndo>();
9856 UrlUndoToolStripMenuItem.Enabled = true;
9859 urlUndoBuffer.Add(undotmp);
9867 private void doUrlUndo()
9869 if (urlUndoBuffer != null)
9871 string tmp = StatusText.Text;
9872 foreach (urlUndo data in urlUndoBuffer)
9874 tmp = tmp.Replace(data.After, data.Before);
9876 StatusText.Text = tmp;
9877 urlUndoBuffer = null;
9878 UrlUndoToolStripMenuItem.Enabled = false;
9879 StatusText.SelectionStart = 0;
9880 StatusText.SelectionLength = 0;
9884 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9886 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9889 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9891 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9894 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9896 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9899 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9901 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9904 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9906 if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
9908 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
9909 Random rnd = new Random();
9910 // 前回使用した短縮URLサービス以外を選択する
9913 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9915 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9916 await UrlConvertAsync(svc);
9920 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9925 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9927 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9928 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9929 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
9930 ModifySettingCommon = true;
9933 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9935 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9936 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9937 _cfgCommon.ListLock = ListLockMenuItem.Checked;
9938 ModifySettingCommon = true;
9941 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9943 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9944 MenuStrip1.Tag = new Object();
9945 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9948 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9950 if (this.Tag != null) // 設定された戻り先へ遷移
9952 if (this.Tag == this.ListTab.SelectedTab)
9953 ((Control)this.ListTab.SelectedTab.Tag).Select();
9955 ((Control)this.Tag).Select();
9957 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9959 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9961 this.Tag = ListTab.SelectedTab.Tag;
9962 ((Control)this.Tag).Select();
9965 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9966 MenuStrip1.Tag = null;
9969 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9971 DetailsListView lst = (DetailsListView)sender;
9972 if (_cfgLocal == null) return;
9976 _cfgLocal.Width1 = lst.Columns[0].Width;
9977 _cfgLocal.Width3 = lst.Columns[1].Width;
9981 int[] darr = new int[lst.Columns.Count];
9982 for (int i = 0; i < lst.Columns.Count; i++)
9984 darr[lst.Columns[i].DisplayIndex] = i;
9986 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9988 for (int i = 0; i < lst.Columns.Count; i++)
9993 _cfgLocal.DisplayIndex1 = i;
9996 _cfgLocal.DisplayIndex2 = i;
9999 _cfgLocal.DisplayIndex3 = i;
10002 _cfgLocal.DisplayIndex4 = i;
10005 _cfgLocal.DisplayIndex5 = i;
10008 _cfgLocal.DisplayIndex6 = i;
10011 _cfgLocal.DisplayIndex7 = i;
10014 _cfgLocal.DisplayIndex8 = i;
10018 _cfgLocal.Width1 = lst.Columns[0].Width;
10019 _cfgLocal.Width2 = lst.Columns[1].Width;
10020 _cfgLocal.Width3 = lst.Columns[2].Width;
10021 _cfgLocal.Width4 = lst.Columns[3].Width;
10022 _cfgLocal.Width5 = lst.Columns[4].Width;
10023 _cfgLocal.Width6 = lst.Columns[5].Width;
10024 _cfgLocal.Width7 = lst.Columns[6].Width;
10025 _cfgLocal.Width8 = lst.Columns[7].Width;
10027 ModifySettingLocal = true;
10028 _isColumnChanged = true;
10031 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10033 DetailsListView lst = (DetailsListView)sender;
10034 if (_cfgLocal == null) return;
10037 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10039 _cfgLocal.Width1 = lst.Columns[0].Width;
10040 ModifySettingLocal = true;
10041 _isColumnChanged = true;
10043 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10045 _cfgLocal.Width3 = lst.Columns[1].Width;
10046 ModifySettingLocal = true;
10047 _isColumnChanged = true;
10052 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10054 _cfgLocal.Width1 = lst.Columns[0].Width;
10055 ModifySettingLocal = true;
10056 _isColumnChanged = true;
10058 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10060 _cfgLocal.Width2 = lst.Columns[1].Width;
10061 ModifySettingLocal = true;
10062 _isColumnChanged = true;
10064 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10066 _cfgLocal.Width3 = lst.Columns[2].Width;
10067 ModifySettingLocal = true;
10068 _isColumnChanged = true;
10070 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10072 _cfgLocal.Width4 = lst.Columns[3].Width;
10073 ModifySettingLocal = true;
10074 _isColumnChanged = true;
10076 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10078 _cfgLocal.Width5 = lst.Columns[4].Width;
10079 ModifySettingLocal = true;
10080 _isColumnChanged = true;
10082 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10084 _cfgLocal.Width6 = lst.Columns[5].Width;
10085 ModifySettingLocal = true;
10086 _isColumnChanged = true;
10088 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10090 _cfgLocal.Width7 = lst.Columns[6].Width;
10091 ModifySettingLocal = true;
10092 _isColumnChanged = true;
10094 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10096 _cfgLocal.Width8 = lst.Columns[7].Width;
10097 ModifySettingLocal = true;
10098 _isColumnChanged = true;
10101 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10104 // SaveConfigsLocal();
10108 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10111 string _selText = this.PostBrowser.GetSelectedText();
10114 Clipboard.SetDataObject(_selText, false, 5, 100);
10116 catch (Exception ex)
10118 MessageBox.Show(ex.Message);
10122 private async Task doSearchToolStrip(string url)
10124 //発言詳細で「選択文字列で検索」(選択文字列取得)
10125 string _selText = this.PostBrowser.GetSelectedText();
10127 if (_selText != null)
10129 if (url == Properties.Resources.SearchItem4Url)
10132 AddNewTabForSearch(_selText);
10136 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10137 await this.OpenUriInBrowserAsync(tmp);
10141 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10144 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10147 private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10149 await this.doSearchToolStrip(Properties.Resources.SearchItem1Url);
10152 private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10154 await this.doSearchToolStrip(Properties.Resources.SearchItem2Url);
10157 private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10159 await this.doSearchToolStrip(Properties.Resources.SearchItem4Url);
10162 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10166 foreach (var link in this.PostBrowser.Document.Links.Cast<HtmlElement>())
10168 if (link.GetAttribute("href") == this._postBrowserStatusText)
10170 var linkStr = link.GetAttribute("title");
10171 if (string.IsNullOrEmpty(linkStr))
10172 linkStr = link.GetAttribute("href");
10174 Clipboard.SetDataObject(linkStr, false, 5, 100);
10179 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10181 catch (Exception ex)
10183 MessageBox.Show(ex.Message);
10187 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10189 // URLコピーの項目の表示/非表示
10190 if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal))
10192 this._postBrowserStatusText = PostBrowser.StatusText;
10193 string name = GetUserId();
10194 UrlCopyContextMenuItem.Enabled = true;
10197 FollowContextMenuItem.Enabled = true;
10198 RemoveContextMenuItem.Enabled = true;
10199 FriendshipContextMenuItem.Enabled = true;
10200 ShowUserStatusContextMenuItem.Enabled = true;
10201 SearchPostsDetailToolStripMenuItem.Enabled = true;
10202 IdFilterAddMenuItem.Enabled = true;
10203 ListManageUserContextToolStripMenuItem.Enabled = true;
10204 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10208 FollowContextMenuItem.Enabled = false;
10209 RemoveContextMenuItem.Enabled = false;
10210 FriendshipContextMenuItem.Enabled = false;
10211 ShowUserStatusContextMenuItem.Enabled = false;
10212 SearchPostsDetailToolStripMenuItem.Enabled = false;
10213 IdFilterAddMenuItem.Enabled = false;
10214 ListManageUserContextToolStripMenuItem.Enabled = false;
10215 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10218 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10219 UseHashtagMenuItem.Enabled = true;
10221 UseHashtagMenuItem.Enabled = false;
10225 this._postBrowserStatusText = "";
10226 UrlCopyContextMenuItem.Enabled = false;
10227 FollowContextMenuItem.Enabled = false;
10228 RemoveContextMenuItem.Enabled = false;
10229 FriendshipContextMenuItem.Enabled = false;
10230 ShowUserStatusContextMenuItem.Enabled = false;
10231 SearchPostsDetailToolStripMenuItem.Enabled = false;
10232 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10233 UseHashtagMenuItem.Enabled = false;
10234 IdFilterAddMenuItem.Enabled = false;
10235 ListManageUserContextToolStripMenuItem.Enabled = false;
10237 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10238 string _selText = this.PostBrowser.GetSelectedText();
10239 if (_selText == null)
10241 SelectionSearchContextMenuItem.Enabled = false;
10242 SelectionCopyContextMenuItem.Enabled = false;
10243 SelectionTranslationToolStripMenuItem.Enabled = false;
10247 SelectionSearchContextMenuItem.Enabled = true;
10248 SelectionCopyContextMenuItem.Enabled = true;
10249 SelectionTranslationToolStripMenuItem.Enabled = true;
10251 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10252 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10253 bool fAllFlag = false;
10254 foreach (Match mu in ma)
10256 if (mu.Result("${ScreenName}").ToLowerInvariant() != tw.Username.ToLowerInvariant())
10262 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10264 if (_curPost == null)
10265 TranslationToolStripMenuItem.Enabled = false;
10267 TranslationToolStripMenuItem.Enabled = true;
10272 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10274 //発言詳細の選択文字列で現在のタブを検索
10275 string _selText = this.PostBrowser.GetSelectedText();
10277 if (_selText != null)
10279 var searchOptions = new SearchWordDialog.SearchOptions(
10280 SearchWordDialog.SearchType.Timeline,
10283 caseSensitive: false,
10286 this.SearchDialog.ResultOptions = searchOptions;
10289 searchOptions.Query,
10290 searchOptions.CaseSensitive,
10291 searchOptions.UseRegex,
10292 SEARCHTYPE.NextSearch);
10296 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10298 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10299 ModifySettingLocal = true;
10302 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10304 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10306 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10308 SelectMedia_DragDrop(e);
10311 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10313 var url = GetUrlFromDataObject(e.Data);
10316 if (url.Item2 == null)
10317 appendText = url.Item1;
10319 appendText = url.Item2 + " " + url.Item1;
10321 if (this.StatusText.TextLength == 0)
10322 this.StatusText.Text = appendText;
10324 this.StatusText.Text += " " + appendText;
10326 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10328 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10330 this.StatusText.Text += text;
10332 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10334 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10335 if (data != null) StatusText.Text += data;
10340 /// IDataObject から URL とタイトルの対を取得します
10343 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10345 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10346 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10347 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10349 if (data.GetDataPresent("text/x-moz-url"))
10351 // Firefox, Google Chrome で利用可能
10352 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10354 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10356 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10357 if (lines.Length < 2)
10358 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
10360 return new Tuple<string, string>(lines[0], lines[1]);
10363 else if (data.GetDataPresent("IESiteModeToUrl"))
10365 // Internet Exproler 用
10366 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10368 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10370 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10371 if (lines.Length < 2)
10372 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
10374 return new Tuple<string, string>(lines[0], lines[1]);
10377 else if (data.GetDataPresent("UniformResourceLocatorW"))
10381 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10383 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10384 return new Tuple<string, string>(url, null);
10388 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10391 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10393 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10395 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10397 SelectMedia_DragEnter(e);
10401 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10403 e.Effect = DragDropEffects.Copy;
10406 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10408 e.Effect = DragDropEffects.Copy;
10411 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10413 e.Effect = DragDropEffects.Copy;
10417 e.Effect = DragDropEffects.None;
10420 private void TweenMain_DragOver(object sender, DragEventArgs e)
10424 public bool IsNetworkAvailable()
10427 nw = MyCommon.IsNetworkAvailable();
10428 _myStatusOnline = nw;
10432 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
10434 var uriStr = uri.AbsoluteUri;
10436 // OpenTween 内部で使用する URL
10437 if (uri.Authority == "opentween")
10439 await this.OpenInternalUriAsync(uri);
10443 // ハッシュタグを含む Twitter 検索
10444 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
10446 // ハッシュタグの場合は、タブで開く
10447 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
10448 var pos = unescapedQuery.IndexOf('#');
10449 if (pos == -1) return;
10451 var hash = unescapedQuery.Substring(pos);
10452 this.HashSupl.AddItem(hash);
10453 this.HashMgr.AddHashToHistory(hash.Trim(), false);
10454 this.AddNewTabForSearch(hash);
10459 // フラグが立っている場合は設定と逆の動作をする
10460 if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
10461 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
10463 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
10464 if (userUriMatch.Success)
10466 var screenName = userUriMatch.Groups["ScreenName"].Value;
10467 if (this.IsTwitterId(screenName))
10469 this.AddNewTabForUserTimeline(screenName);
10475 // どのパターンにも該当しないURL
10476 await this.OpenUriInBrowserAsync(uriStr);
10480 /// OpenTween 内部の機能を呼び出すための URL を開きます
10482 private async Task OpenInternalUriAsync(Uri uri)
10484 // ツイートを開く (//opentween/status/:status_id)
10485 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
10488 var statusId = long.Parse(match.Groups[1].Value);
10489 await this.OpenRelatedTab(statusId);
10494 public Task OpenUriInBrowserAsync(string UriString)
10496 return Task.Run(() =>
10498 string myPath = UriString;
10502 var configBrowserPath = this._cfgLocal.BrowserPath;
10503 if (!string.IsNullOrEmpty(configBrowserPath))
10505 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
10507 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
10508 string browserPath = configBrowserPath.Substring(1, sep - 1);
10510 if (sep < configBrowserPath.Length - 1)
10512 arg = configBrowserPath.Substring(sep + 1);
10514 myPath = arg + " " + myPath;
10515 System.Diagnostics.Process.Start(browserPath, myPath);
10519 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10524 System.Diagnostics.Process.Start(myPath);
10529 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10534 private void ListTabSelect(TabPage _tab)
10538 this.PurgeListViewItemCache();
10541 _curList = (DetailsListView)_tab.Tag;
10542 if (_curList.SelectedIndices.Count > 0)
10544 _curItemIndex = _curList.SelectedIndices[0];
10545 _curPost = GetCurTabPost(_curItemIndex);
10549 _curItemIndex = -1;
10553 _anchorPost = null;
10554 _anchorFlag = false;
10558 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10562 for (int i = 0; i < _curList.Columns.Count; i++)
10564 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10569 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10571 ListTabSelect(e.TabPage);
10574 private void SelectListItem(DetailsListView LView, int Index)
10577 Rectangle bnd = new Rectangle();
10579 var item = LView.FocusedItem;
10588 LView.SelectedIndices.Clear();
10590 while (LView.SelectedIndices.Count > 0);
10591 item = LView.Items[Index];
10592 item.Selected = true;
10593 item.Focused = true;
10595 if (flg) LView.Invalidate(bnd);
10598 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
10601 Rectangle bnd = new Rectangle();
10603 var item = LView.FocusedItem;
10614 LView.SelectedIndices.Clear();
10616 while (LView.SelectedIndices.Count > 0);
10617 LView.SelectItems(Index);
10619 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
10621 LView.SelectionMark = selectionMarkIndex;
10623 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
10625 LView.Items[focusedIndex].Focused = true;
10627 else if (Index != null && Index.Length != 0)
10629 LView.Items[Index.Last()].Focused = true;
10632 if (flg) LView.Invalidate(bnd);
10635 private void StartUserStream()
10637 tw.NewPostFromStream += tw_NewPostFromStream;
10638 tw.UserStreamStarted += tw_UserStreamStarted;
10639 tw.UserStreamStopped += tw_UserStreamStopped;
10640 tw.PostDeleted += tw_PostDeleted;
10641 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
10643 this.RefreshUserStreamsMenu();
10645 if (this._cfgCommon.UserstreamStartup)
10646 tw.StartUserStream();
10649 private async void TweenMain_Shown(object sender, EventArgs e)
10653 using (ControlTransaction.Update(this.PostBrowser))
10655 PostBrowser.Url = new Uri("about:blank");
10656 PostBrowser.DocumentText = ""; //発言詳細部初期化
10663 NotifyIcon1.Visible = true;
10665 if (this.IsNetworkAvailable())
10669 var loadTasks = new List<Task>
10671 this.RefreshMuteUserIdsAsync(),
10672 this.RefreshBlockIdsAsync(),
10673 this.RefreshNoRetweetIdsAsync(),
10674 this.RefreshTwitterConfigurationAsync(),
10675 this.GetHomeTimelineAsync(),
10676 this.GetReplyAsync(),
10677 this.GetDirectMessagesAsync(),
10678 this.GetPublicSearchAllAsync(),
10679 this.GetUserTimelineAllAsync(),
10680 this.GetListTimelineAllAsync(),
10683 if (this._cfgCommon.StartupFollowers)
10684 loadTasks.Add(this.RefreshFollowerIdsAsync());
10686 if (this._cfgCommon.GetFav)
10687 loadTasks.Add(this.GetFavoritesAsync());
10689 var allTasks = Task.WhenAll(loadTasks);
10694 var timeout = Task.Delay(5000);
10695 if (await Task.WhenAny(allTasks, timeout) != timeout)
10699 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10701 if (MyCommon._endingFlag)
10705 if (MyCommon._endingFlag) return;
10707 if (ApplicationSettings.VersionInfoUrl != null)
10709 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10710 if (this._cfgCommon.StartupVersion)
10711 await this.CheckNewVersion(true);
10715 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10716 this.VerUpMenuItem.Enabled = false;
10717 this.VerUpMenuItem.Available = false;
10718 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10721 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10722 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10724 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10725 SettingStripMenuItem_Click(null, null);
10729 var reloadTasks = new List<Task>();
10731 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
10732 reloadTasks.Add(this.RefreshFollowerIdsAsync());
10734 if (!tw.GetNoRetweetSuccess)
10735 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10737 if (this.tw.Configuration.PhotoSizeLimit == 0)
10738 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10740 await Task.WhenAll(reloadTasks);
10745 TimerTimeline.Enabled = true;
10748 private async Task doGetFollowersMenu()
10750 await this.RefreshFollowerIdsAsync();
10751 await this.DispSelectedPost(true);
10754 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10756 await this.doGetFollowersMenu();
10759 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10761 doReTweetUnofficial();
10764 private async Task doReTweetOfficial(bool isConfirm)
10767 if (this.ExistCurrentPost)
10769 if (_curPost.IsProtect)
10771 MessageBox.Show("Protected.");
10772 _DoFavRetweetFlags = false;
10775 if (_curList.SelectedIndices.Count > 15)
10777 MessageBox.Show(Properties.Resources.RetweetLimitText);
10778 _DoFavRetweetFlags = false;
10781 else if (_curList.SelectedIndices.Count > 1)
10783 string QuestionText = Properties.Resources.RetweetQuestion2;
10784 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10785 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10787 case DialogResult.Cancel:
10788 case DialogResult.No:
10789 _DoFavRetweetFlags = false;
10795 if (_curPost.IsDm || _curPost.IsMe)
10797 _DoFavRetweetFlags = false;
10800 if (!this._cfgCommon.RetweetNoConfirm)
10802 string Questiontext = Properties.Resources.RetweetQuestion1;
10803 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10804 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10806 _DoFavRetweetFlags = false;
10812 var statusIds = new List<long>();
10813 foreach (int idx in _curList.SelectedIndices)
10815 PostClass post = GetCurTabPost(idx);
10816 if (!post.IsMe && !post.IsProtect && !post.IsDm)
10817 statusIds.Add(post.StatusId);
10820 await this.RetweetAsync(statusIds);
10824 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10826 await this.doReTweetOfficial(true);
10829 private async Task FavoritesRetweetOfficial()
10831 if (!this.ExistCurrentPost) return;
10832 _DoFavRetweetFlags = true;
10833 var retweetTask = this.doReTweetOfficial(true);
10834 if (_DoFavRetweetFlags)
10836 _DoFavRetweetFlags = false;
10837 var favoriteTask = this.FavoriteChange(true, false);
10839 await Task.WhenAll(retweetTask, favoriteTask);
10847 private async Task FavoritesRetweetUnofficial()
10849 if (this.ExistCurrentPost && !_curPost.IsDm)
10851 _DoFavRetweetFlags = true;
10852 var favoriteTask = this.FavoriteChange(true);
10853 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10855 _DoFavRetweetFlags = false;
10856 doReTweetUnofficial();
10859 await favoriteTask;
10864 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10866 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10867 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10868 /// <returns>復元されたツイート本文</returns>
10869 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10871 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10874 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10876 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10878 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10882 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10884 statusHtml = statusHtml.Replace("<br>", " ");
10886 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10887 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10888 statusHtml = statusHtml.Replace(" ", " ");
10890 return WebUtility.HtmlDecode(statusHtml);
10893 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10895 if (_curPost != null)
10896 await this.DispSelectedPost(true);
10899 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10901 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10902 DebugModeToolStripMenuItem.Visible = true;
10904 DebugModeToolStripMenuItem.Visible = false;
10907 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
10909 this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
10912 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10914 ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
10917 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10919 if (TraceOutToolStripMenuItem.Checked)
10920 MyCommon.TraceFlag = true;
10922 MyCommon.TraceFlag = false;
10925 private void TweenMain_Deactivate(object sender, EventArgs e)
10927 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10928 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10931 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10933 if (string.IsNullOrEmpty(_rclickTabName)) return;
10934 TabRename(ref _rclickTabName);
10937 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10939 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10942 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10944 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10947 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10949 TwitterApiStatus apiStatus;
10951 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10953 var cancellationToken = dialog.EnableCancellation();
10957 var task = this.tw.GetInfoApi();
10958 apiStatus = await dialog.WaitForAsync(this, task);
10960 catch (WebApiException)
10965 if (cancellationToken.IsCancellationRequested)
10968 if (apiStatus == null)
10970 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10975 using (var apiDlg = new ApiInfoDialog())
10977 apiDlg.ShowDialog(this);
10981 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10983 var id = _curPost?.ScreenName ?? "";
10985 await this.FollowCommand(id);
10988 private async Task FollowCommand(string id)
10990 using (var inputName = new InputTabName())
10992 inputName.FormTitle = "Follow";
10993 inputName.FormDescription = Properties.Resources.FRMessage1;
10994 inputName.TabName = id;
10996 if (inputName.ShowDialog(this) != DialogResult.OK)
10998 if (string.IsNullOrWhiteSpace(inputName.TabName))
11001 id = inputName.TabName.Trim();
11004 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
11008 var task = this.twitterApi.FriendshipsCreate(id);
11009 await dialog.WaitForAsync(this, task);
11011 catch (WebApiException ex)
11013 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11018 MessageBox.Show(Properties.Resources.FRMessage3);
11021 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11023 var id = _curPost?.ScreenName ?? "";
11025 await this.RemoveCommand(id, false);
11028 private async Task RemoveCommand(string id, bool skipInput)
11032 using (var inputName = new InputTabName())
11034 inputName.FormTitle = "Unfollow";
11035 inputName.FormDescription = Properties.Resources.FRMessage1;
11036 inputName.TabName = id;
11038 if (inputName.ShowDialog(this) != DialogResult.OK)
11040 if (string.IsNullOrWhiteSpace(inputName.TabName))
11043 id = inputName.TabName.Trim();
11047 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
11051 var task = this.twitterApi.FriendshipsDestroy(id);
11052 await dialog.WaitForAsync(this, task);
11054 catch (WebApiException ex)
11056 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11061 MessageBox.Show(Properties.Resources.FRMessage3);
11064 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
11066 var id = _curPost?.ScreenName ?? "";
11068 await this.ShowFriendship(id);
11071 private async Task ShowFriendship(string id)
11073 using (var inputName = new InputTabName())
11075 inputName.FormTitle = "Show Friendships";
11076 inputName.FormDescription = Properties.Resources.FRMessage1;
11077 inputName.TabName = id;
11079 if (inputName.ShowDialog(this) != DialogResult.OK)
11081 if (string.IsNullOrWhiteSpace(inputName.TabName))
11084 id = inputName.TabName.Trim();
11087 bool isFollowing, isFollowed;
11089 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11091 var cancellationToken = dialog.EnableCancellation();
11095 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11096 var friendship = await dialog.WaitForAsync(this, task);
11098 isFollowing = friendship.Relationship.Source.Following;
11099 isFollowed = friendship.Relationship.Source.FollowedBy;
11101 catch (WebApiException ex)
11103 if (!cancellationToken.IsCancellationRequested)
11104 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
11108 if (cancellationToken.IsCancellationRequested)
11112 string result = "";
11115 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11119 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11123 result += Properties.Resources.GetFriendshipInfo3;
11127 result += Properties.Resources.GetFriendshipInfo4;
11129 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11130 MessageBox.Show(result);
11133 private async Task ShowFriendship(string[] ids)
11135 foreach (string id in ids)
11137 bool isFollowing, isFollowed;
11139 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11141 var cancellationToken = dialog.EnableCancellation();
11145 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11146 var friendship = await dialog.WaitForAsync(this, task);
11148 isFollowing = friendship.Relationship.Source.Following;
11149 isFollowed = friendship.Relationship.Source.FollowedBy;
11151 catch (WebApiException ex)
11153 if (!cancellationToken.IsCancellationRequested)
11154 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
11158 if (cancellationToken.IsCancellationRequested)
11162 string result = "";
11168 ff += Properties.Resources.GetFriendshipInfo1;
11172 ff += Properties.Resources.GetFriendshipInfo2;
11175 ff += System.Environment.NewLine + " ";
11178 ff += Properties.Resources.GetFriendshipInfo3;
11182 ff += Properties.Resources.GetFriendshipInfo4;
11184 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11187 if (MessageBox.Show(
11188 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11189 MessageBoxButtons.YesNo,
11190 MessageBoxIcon.Question,
11191 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11193 await this.RemoveCommand(id, true);
11198 MessageBox.Show(result);
11203 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
11205 await this.doShowUserStatus(tw.Username, false);
11206 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11208 // doShowUserStatus(tw.Username, false);
11212 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11217 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11218 // URLから切り出した文字列を渡す
11220 public bool IsTwitterId(string name)
11222 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11223 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11225 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
11228 private string GetUserId()
11230 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11231 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11232 return m.Result("${ScreenName}");
11237 private async void FollowContextMenuItem_Click(object sender, EventArgs e)
11239 string name = GetUserId();
11241 await this.FollowCommand(name);
11244 private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
11246 string name = GetUserId();
11248 await this.RemoveCommand(name, false);
11251 private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11253 string name = GetUserId();
11255 await this.ShowFriendship(name);
11258 private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11260 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11261 List<string> ids = new List<string>();
11262 foreach (Match mu in ma)
11264 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11266 ids.Add(mu.Result("${ScreenName}"));
11270 await this.ShowFriendship(ids.ToArray());
11273 private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11275 string name = GetUserId();
11277 await this.ShowUserStatus(name);
11280 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11282 string name = GetUserId();
11283 if (name != null) AddNewTabForUserTimeline(name);
11286 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11288 string name = GetUserId();
11289 if (name != null) AddNewTabForSearch("@" + name);
11292 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11294 ModifySettingCommon = true;
11297 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11299 ModifySettingCommon = true;
11302 private void doQuoteOfficial()
11304 if (this.ExistCurrentPost)
11306 if (_curPost.IsDm ||
11307 !StatusText.Enabled) return;
11309 if (_curPost.IsProtect)
11311 MessageBox.Show("Protected.");
11315 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
11317 this.inReplyTo = null;
11319 StatusText.SelectionStart = 0;
11320 StatusText.Focus();
11324 private void doReTweetUnofficial()
11327 if (this.ExistCurrentPost)
11329 if (_curPost.IsDm || !StatusText.Enabled)
11332 if (_curPost.IsProtect)
11334 MessageBox.Show("Protected.");
11337 string rtdata = _curPost.Text;
11338 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11340 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
11342 // 投稿時に in_reply_to_status_id を付加する
11343 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11344 var inReplyToScreenName = this._curPost.ScreenName;
11345 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
11347 StatusText.SelectionStart = 0;
11348 StatusText.Focus();
11352 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11357 private void SearchButton_Click(object sender, EventArgs e)
11360 Control pnl = ((Control)sender).Parent;
11361 if (pnl == null) return;
11362 string tbName = pnl.Parent.Text;
11363 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
11364 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11365 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11366 cmb.Text = cmb.Text.Trim();
11367 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11368 bool Quote = false;
11369 StringBuilder buf = new StringBuilder();
11370 char[] c = cmb.Text.ToCharArray();
11371 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11373 if (cnt > cmb.Text.Length - 4)
11375 buf.Append(cmb.Text.Substring(cnt));
11384 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11386 buf.Append(" OR ");
11391 buf.Append(c[cnt]);
11393 cmb.Text = buf.ToString();
11395 var listView = (DetailsListView)pnl.Parent.Tag;
11397 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
11399 tb.SearchWords = cmb.Text;
11400 tb.SearchLang = cmbLang.Text;
11401 if (string.IsNullOrEmpty(cmb.Text))
11409 int idx = cmb.Items.IndexOf(tb.SearchWords);
11410 if (idx > -1) cmb.Items.RemoveAt(idx);
11411 cmb.Items.Insert(0, tb.SearchWords);
11412 cmb.Text = tb.SearchWords;
11414 this.PurgeListViewItemCache();
11415 listView.VirtualListSize = 0;
11416 _statuses.ClearTabIds(tbName);
11417 SaveConfigsTabs(); //検索条件の保存
11420 this.GetPublicSearchAsync(tb);
11424 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11427 await this.DoRefreshMore();
11431 /// 指定されたタブのListTabにおける位置を返します
11434 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
11436 public int GetTabPageIndex(string tabName)
11439 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
11441 if (tabPage.Text == tabName)
11450 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11452 if (_statuses.RemovedTab.Count == 0)
11454 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11459 DetailsListView listView = null;
11461 TabModel tb = _statuses.RemovedTab.Pop();
11462 if (tb.TabType == MyCommon.TabUsageType.Related)
11464 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11465 if (relatedTab != null)
11467 // 関連発言なら既存のタブを置き換える
11468 tb.TabName = relatedTab.TabName;
11469 this.ClearTab(tb.TabName, false);
11470 _statuses.Tabs[tb.TabName] = tb;
11472 for (int i = 0; i < ListTab.TabPages.Count; i++)
11474 var tabPage = ListTab.TabPages[i];
11475 if (tb.TabName == tabPage.Text)
11477 listView = (DetailsListView)tabPage.Tag;
11478 ListTab.SelectedIndex = i;
11485 const string TabName = "Related Tweets";
11486 string renamed = TabName;
11487 for (int i = 2; i <= 100; i++)
11489 if (!_statuses.ContainsTab(renamed)) break;
11490 renamed = TabName + i.ToString();
11492 tb.TabName = renamed;
11494 _statuses.AddTab(tb);
11495 AddNewTab(tb, startup: false);
11497 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11498 listView = (DetailsListView)tabPage.Tag;
11499 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11504 string renamed = tb.TabName;
11505 for (int i = 1; i < int.MaxValue; i++)
11507 if (!_statuses.ContainsTab(renamed)) break;
11508 renamed = tb.TabName + "(" + i.ToString() + ")";
11510 tb.TabName = renamed;
11512 _statuses.AddTab(tb);
11513 AddNewTab(tb, startup: false);
11515 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11516 listView = (DetailsListView)tabPage.Tag;
11517 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11521 if (listView != null)
11523 using (ControlTransaction.Update(listView))
11525 listView.VirtualListSize = tb.AllCount;
11531 private async Task doMoveToRTHome()
11533 if (_curList.SelectedIndices.Count > 0)
11535 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11536 if (post.RetweetedId != null)
11538 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11543 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11545 await this.doMoveToRTHome();
11548 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11550 string name = GetUserId();
11556 if (_curList.SelectedIndices.Count == 0) return;
11559 if (!SelectTab(out tabName)) return;
11561 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
11565 if (tab.TabType != MyCommon.TabUsageType.Mute)
11567 this.MoveOrCopy(out mv, out mk);
11571 // ミュートタブでは常に MoveMatches を true にする
11576 PostFilterRule fc = new PostFilterRule();
11577 fc.FilterName = name;
11578 fc.UseNameField = true;
11579 fc.MoveMatches = mv;
11580 fc.MarkMatches = mk;
11581 fc.UseRegex = false;
11582 fc.FilterByUrl = false;
11585 this.ApplyPostFilters();
11590 private async void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11594 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11596 if (menuItem.Owner == this.ContextMenuPostBrowser)
11598 user = GetUserId();
11599 if (user == null) return;
11601 else if (this._curPost != null)
11603 user = this._curPost.ScreenName;
11610 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11614 using (var dialog = new WaitingDialog(Properties.Resources.ListsGetting))
11616 var cancellationToken = dialog.EnableCancellation();
11618 var task = this.tw.GetListsApi();
11619 await dialog.WaitForAsync(this, task);
11621 cancellationToken.ThrowIfCancellationRequested();
11624 catch (OperationCanceledException) { return; }
11625 catch (WebApiException ex)
11627 MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
11632 using (MyLists listSelectForm = new MyLists(user, this.tw))
11634 listSelectForm.ShowDialog(this);
11638 private void SearchControls_Enter(object sender, EventArgs e)
11640 Control pnl = (Control)sender;
11641 foreach (Control ctl in pnl.Controls)
11643 ctl.TabStop = true;
11647 private void SearchControls_Leave(object sender, EventArgs e)
11649 Control pnl = (Control)sender;
11650 foreach (Control ctl in pnl.Controls)
11652 ctl.TabStop = false;
11656 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
11658 if (ListTab.SelectedTab != null)
11660 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
11661 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
11665 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
11667 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
11670 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
11671 HashStripSplitButton.Text = HashMgr.UseHash;
11672 HashToggleMenuItem.Checked = true;
11673 HashToggleToolStripMenuItem.Checked = true;
11675 ModifySettingCommon = true;
11679 private void StatusLabel_DoubleClick(object sender, EventArgs e)
11681 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
11684 private void HashManageMenuItem_Click(object sender, EventArgs e)
11686 DialogResult rslt = DialogResult.Cancel;
11689 rslt = HashMgr.ShowDialog();
11695 this.TopMost = this._cfgCommon.AlwaysTop;
11696 if (rslt == DialogResult.Cancel) return;
11697 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11699 HashStripSplitButton.Text = HashMgr.UseHash;
11700 HashToggleMenuItem.Checked = true;
11701 HashToggleToolStripMenuItem.Checked = true;
11705 HashStripSplitButton.Text = "#[-]";
11706 HashToggleMenuItem.Checked = false;
11707 HashToggleToolStripMenuItem.Checked = false;
11709 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
11711 // int sidx = StatusText.SelectionStart;
11712 // string hash = HashMgr.UseHash + " ";
11715 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
11716 // hash = " " + hash;
11718 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
11719 // sidx += hash.Length;
11720 // StatusText.SelectionStart = sidx;
11721 // StatusText.Focus();
11723 ModifySettingCommon = true;
11724 this.StatusText_TextChanged(null, null);
11727 private void HashToggleMenuItem_Click(object sender, EventArgs e)
11729 HashMgr.ToggleHash();
11730 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11732 HashStripSplitButton.Text = HashMgr.UseHash;
11733 HashToggleMenuItem.Checked = true;
11734 HashToggleToolStripMenuItem.Checked = true;
11738 HashStripSplitButton.Text = "#[-]";
11739 HashToggleMenuItem.Checked = false;
11740 HashToggleToolStripMenuItem.Checked = false;
11742 ModifySettingCommon = true;
11743 this.StatusText_TextChanged(null, null);
11746 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
11748 HashToggleMenuItem_Click(null, null);
11751 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
11753 if (ListTab.SelectedTab == null) return;
11754 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
11755 if (!this.ExistCurrentPost)
11757 this.ReplyOpMenuItem.Enabled = false;
11758 this.ReplyAllOpMenuItem.Enabled = false;
11759 this.DmOpMenuItem.Enabled = false;
11760 this.ShowProfMenuItem.Enabled = false;
11761 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
11762 this.ListManageMenuItem.Enabled = false;
11763 this.OpenFavOpMenuItem.Enabled = false;
11764 this.CreateTabRuleOpMenuItem.Enabled = false;
11765 this.CreateIdRuleOpMenuItem.Enabled = false;
11766 this.CreateSourceRuleOpMenuItem.Enabled = false;
11767 this.ReadOpMenuItem.Enabled = false;
11768 this.UnreadOpMenuItem.Enabled = false;
11772 this.ReplyOpMenuItem.Enabled = true;
11773 this.ReplyAllOpMenuItem.Enabled = true;
11774 this.DmOpMenuItem.Enabled = true;
11775 this.ShowProfMenuItem.Enabled = true;
11776 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
11777 this.ListManageMenuItem.Enabled = true;
11778 this.OpenFavOpMenuItem.Enabled = true;
11779 this.CreateTabRuleOpMenuItem.Enabled = true;
11780 this.CreateIdRuleOpMenuItem.Enabled = true;
11781 this.CreateSourceRuleOpMenuItem.Enabled = true;
11782 this.ReadOpMenuItem.Enabled = true;
11783 this.UnreadOpMenuItem.Enabled = true;
11786 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
11788 this.FavOpMenuItem.Enabled = false;
11789 this.UnFavOpMenuItem.Enabled = false;
11790 this.OpenStatusOpMenuItem.Enabled = false;
11791 this.OpenFavotterOpMenuItem.Enabled = false;
11792 this.ShowRelatedStatusesMenuItem2.Enabled = false;
11793 this.RtOpMenuItem.Enabled = false;
11794 this.RtUnOpMenuItem.Enabled = false;
11795 this.QtOpMenuItem.Enabled = false;
11796 this.FavoriteRetweetMenuItem.Enabled = false;
11797 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11801 this.FavOpMenuItem.Enabled = true;
11802 this.UnFavOpMenuItem.Enabled = true;
11803 this.OpenStatusOpMenuItem.Enabled = true;
11804 this.OpenFavotterOpMenuItem.Enabled = true;
11805 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
11809 this.RtOpMenuItem.Enabled = false; //公式RTは無効に
11810 this.RtUnOpMenuItem.Enabled = true;
11811 this.QtOpMenuItem.Enabled = true;
11812 this.FavoriteRetweetMenuItem.Enabled = false; //公式RTは無効に
11813 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11817 if (_curPost.IsProtect)
11819 this.RtOpMenuItem.Enabled = false;
11820 this.RtUnOpMenuItem.Enabled = false;
11821 this.QtOpMenuItem.Enabled = false;
11822 this.FavoriteRetweetMenuItem.Enabled = false;
11823 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11827 this.RtOpMenuItem.Enabled = true;
11828 this.RtUnOpMenuItem.Enabled = true;
11829 this.QtOpMenuItem.Enabled = true;
11830 this.FavoriteRetweetMenuItem.Enabled = true;
11831 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11836 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11838 this.RefreshPrevOpMenuItem.Enabled = true;
11842 this.RefreshPrevOpMenuItem.Enabled = false;
11844 if (!this.ExistCurrentPost
11845 || _curPost.InReplyToStatusId == null)
11847 OpenRepSourceOpMenuItem.Enabled = false;
11851 OpenRepSourceOpMenuItem.Enabled = true;
11853 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11855 OpenRterHomeMenuItem.Enabled = false;
11859 OpenRterHomeMenuItem.Enabled = true;
11862 if (this.ExistCurrentPost)
11864 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11868 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11870 ContextMenuTabProperty_Opening(sender, null);
11873 public Twitter TwitterInstance
11878 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11880 if (this._initialLayout)
11883 int splitterDistance;
11884 switch (this.WindowState)
11886 case FormWindowState.Normal:
11887 splitterDistance = this.SplitContainer3.SplitterDistance;
11889 case FormWindowState.Maximized:
11890 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11891 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11892 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11893 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11899 this._mySpDis3 = splitterDistance;
11900 this.ModifySettingLocal = true;
11903 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11905 if (_statuses.RemovedTab.Count == 0)
11907 UndoRemoveTabMenuItem.Enabled = false;
11911 UndoRemoveTabMenuItem.Enabled = true;
11913 if (ListTab.SelectedTab != null)
11915 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11916 PublicSearchQueryMenuItem.Enabled = true;
11918 PublicSearchQueryMenuItem.Enabled = false;
11922 PublicSearchQueryMenuItem.Enabled = false;
11924 if (!this.ExistCurrentPost)
11926 this.CopySTOTMenuItem.Enabled = false;
11927 this.CopyURLMenuItem.Enabled = false;
11928 this.CopyUserIdStripMenuItem.Enabled = false;
11932 this.CopySTOTMenuItem.Enabled = true;
11933 this.CopyURLMenuItem.Enabled = true;
11934 this.CopyUserIdStripMenuItem.Enabled = true;
11935 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11936 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11940 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11942 SetNotifyIconText();
11945 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11947 var id = _curPost?.ScreenName ?? "";
11949 await this.ShowUserStatus(id);
11952 private async Task doShowUserStatus(string id, bool ShowInputDialog)
11954 TwitterUser user = null;
11956 if (ShowInputDialog)
11958 using (var inputName = new InputTabName())
11960 inputName.FormTitle = "Show UserStatus";
11961 inputName.FormDescription = Properties.Resources.FRMessage1;
11962 inputName.TabName = id;
11964 if (inputName.ShowDialog(this) != DialogResult.OK)
11966 if (string.IsNullOrWhiteSpace(inputName.TabName))
11969 id = inputName.TabName.Trim();
11973 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11975 var cancellationToken = dialog.EnableCancellation();
11979 var task = this.twitterApi.UsersShow(id);
11980 user = await dialog.WaitForAsync(this, task);
11982 catch (WebApiException ex)
11984 if (!cancellationToken.IsCancellationRequested)
11985 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11989 if (cancellationToken.IsCancellationRequested)
11993 await this.doShowUserStatus(user);
11996 private async Task doShowUserStatus(TwitterUser user)
11998 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
12000 var showUserTask = userDialog.ShowUserAsync(user);
12001 userDialog.ShowDialog(this);
12004 this.BringToFront();
12006 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12007 await showUserTask;
12011 private Task ShowUserStatus(string id, bool ShowInputDialog)
12013 return this.doShowUserStatus(id, ShowInputDialog);
12016 private Task ShowUserStatus(string id)
12018 return this.doShowUserStatus(id, true);
12021 private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12023 if (NameLabel.Tag != null)
12025 string id = (string)NameLabel.Tag;
12026 if (id != tw.Username)
12028 await this.FollowCommand(id);
12033 private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12035 if (NameLabel.Tag != null)
12037 string id = (string)NameLabel.Tag;
12038 if (id != tw.Username)
12040 await this.RemoveCommand(id, false);
12045 private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12047 if (NameLabel.Tag != null)
12049 string id = (string)NameLabel.Tag;
12050 if (id != tw.Username)
12052 await this.ShowFriendship(id);
12057 private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12059 if (NameLabel.Tag != null)
12061 string id = (string)NameLabel.Tag;
12062 await this.ShowUserStatus(id, false);
12066 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12068 if (NameLabel.Tag != null)
12070 string id = (string)NameLabel.Tag;
12071 AddNewTabForUserTimeline(id);
12075 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12077 if (NameLabel.Tag != null)
12079 string id = (string)NameLabel.Tag;
12080 AddNewTabForSearch("@" + id);
12084 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
12086 if (_curPost != null)
12088 await this.ShowUserStatus(_curPost.ScreenName, false);
12092 private async void RtCountMenuItem_Click(object sender, EventArgs e)
12094 if (!this.ExistCurrentPost)
12097 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
12098 TwitterStatus status;
12100 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
12102 var cancellationToken = dialog.EnableCancellation();
12106 var task = this.twitterApi.StatusesShow(statusId);
12107 status = await dialog.WaitForAsync(this, task);
12109 catch (WebApiException ex)
12111 if (!cancellationToken.IsCancellationRequested)
12112 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
12116 if (cancellationToken.IsCancellationRequested)
12120 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
12123 private HookGlobalHotkey _hookGlobalHotkey;
12126 _hookGlobalHotkey = new HookGlobalHotkey(this);
12128 // この呼び出しは、Windows フォーム デザイナで必要です。
12129 InitializeComponent();
12131 // InitializeComponent() 呼び出しの後で初期化を追加します。
12133 if (!this.DesignMode)
12135 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12136 this.StatusText.Dock = DockStyle.Fill;
12139 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12140 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12141 this.gh.NotifyClicked += GrowlHelper_Callback;
12143 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12144 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12146 this.ImageSelector.Visible = false;
12147 this.ImageSelector.Enabled = false;
12148 this.ImageSelector.FilePickDialog = OpenFileDialog1;
12150 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
12152 this.ReplaceAppName();
12153 this.InitializeShortcuts();
12156 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12158 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12161 this.Visible = false;
12163 else if (Form.ActiveForm == null)
12165 this.Visible = true;
12166 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12168 this.BringToFront();
12169 this.StatusText.Focus();
12173 private void UserPicture_MouseEnter(object sender, EventArgs e)
12175 this.UserPicture.Cursor = Cursors.Hand;
12178 private void UserPicture_MouseLeave(object sender, EventArgs e)
12180 this.UserPicture.Cursor = Cursors.Default;
12183 private async void UserPicture_DoubleClick(object sender, EventArgs e)
12185 if (NameLabel.Tag != null)
12187 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12191 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12193 this.MultiLineMenuItem.PerformClick();
12196 public PostClass CurPost
12198 get { return _curPost; }
12202 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12204 if (ImageSelector.Visible)
12205 ImageSelector.EndSelection();
12207 ImageSelector.BeginSelection();
12210 private void SelectMedia_DragEnter(DragEventArgs e)
12212 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12214 e.Effect = DragDropEffects.Copy;
12217 e.Effect = DragDropEffects.None;
12220 private void SelectMedia_DragDrop(DragEventArgs e)
12223 this.BringToFront();
12224 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12225 StatusText.Focus();
12228 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12230 TimelinePanel.Visible = false;
12231 TimelinePanel.Enabled = false;
12234 private void ImageSelector_EndSelecting(object sender, EventArgs e)
12236 TimelinePanel.Visible = true;
12237 TimelinePanel.Enabled = true;
12238 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12241 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12243 this.AllowDrop = false;
12246 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12248 this.AllowDrop = true;
12251 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12253 if (ImageSelector.Visible)
12255 ModifySettingCommon = true;
12256 SaveConfigsAll(true);
12258 if (ImageSelector.ServiceName.Equals("Twitter"))
12259 this.StatusText_TextChanged(null, null);
12263 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12265 this.StatusText_TextChanged(null, null);
12269 /// StatusTextでCtrl+Vが押下された時の処理
12271 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
12273 if (Clipboard.ContainsText())
12275 // clipboardにテキストがある場合は貼り付け処理
12276 this.StatusText.Paste(Clipboard.GetText());
12278 else if (Clipboard.ContainsImage())
12281 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
12282 Properties.Resources.PostPictureWarn4,
12283 MessageBoxButtons.OKCancel,
12284 MessageBoxIcon.Question,
12285 MessageBoxDefaultButton.Button2)
12286 == DialogResult.OK)
12288 // clipboardから画像を取得
12289 using (var image = Clipboard.GetImage())
12291 this.ImageSelector.BeginSelection(image);
12298 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12300 using (ListManage form = new ListManage(tw))
12302 form.ShowDialog(this);
12306 public bool ModifySettingCommon { get; set; }
12307 public bool ModifySettingLocal { get; set; }
12308 public bool ModifySettingAtId { get; set; }
12310 private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12312 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12313 if (sourceUri != null && e.Button == MouseButtons.Left)
12315 await this.OpenUriInBrowserAsync(sourceUri.AbsoluteUri);
12319 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12321 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12322 if (sourceUri != null)
12324 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri);
12328 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12330 SetStatusLabelUrl();
12333 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12335 if (this.ExistCurrentPost && !_curPost.IsDm)
12336 RtCountMenuItem.Enabled = true;
12338 RtCountMenuItem.Enabled = false;
12340 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12341 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12343 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12346 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12351 private void CopyUserId()
12353 if (_curPost == null) return;
12354 string clstr = _curPost.ScreenName;
12357 Clipboard.SetDataObject(clstr, false, 5, 100);
12359 catch (Exception ex)
12361 MessageBox.Show(ex.Message);
12365 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12367 if (this.ExistCurrentPost && !_curPost.IsDm)
12371 await this.OpenRelatedTab(this._curPost);
12373 catch (TabException ex)
12375 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12381 /// 指定されたツイートに対する関連発言タブを開きます
12383 /// <param name="statusId">表示するツイートのID</param>
12384 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12385 private async Task OpenRelatedTab(long statusId)
12387 var post = this._statuses[statusId];
12392 post = await this.tw.GetStatusApi(false, statusId);
12394 catch (WebApiException ex)
12396 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
12401 await this.OpenRelatedTab(post);
12405 /// 指定されたツイートに対する関連発言タブを開きます
12407 /// <param name="post">表示する対象となるツイート</param>
12408 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12409 private async Task OpenRelatedTab(PostClass post)
12411 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
12412 if (tabRelated != null)
12414 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
12417 var tabName = this._statuses.MakeTabName("Related Tweets");
12419 tabRelated = new RelatedPostsTabModel(tabName, post);
12420 tabRelated.UnreadManage = false;
12421 tabRelated.Notify = false;
12423 this._statuses.AddTab(tabRelated);
12424 this.AddNewTab(tabRelated, startup: false);
12427 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12429 tabPage = this.ListTab.TabPages[i];
12430 if (tabName == tabPage.Text)
12432 this.ListTab.SelectedIndex = i;
12437 await this.GetRelatedTweetsAsync(tabRelated);
12439 tabPage = this.ListTab.TabPages.Cast<TabPage>()
12440 .FirstOrDefault(x => x.Text == tabRelated.TabName);
12442 if (tabPage != null)
12444 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
12446 var listView = (DetailsListView)tabPage.Tag;
12447 var targetPost = tabRelated.TargetPost;
12448 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
12450 if (index != -1 && index < listView.Items.Count)
12452 listView.SelectedIndices.Add(index);
12453 listView.Items[index].Focused = true;
12458 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12460 StringBuilder buf = new StringBuilder();
12461 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12462 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12463 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12464 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12465 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12468 private void tw_UserIdChanged()
12470 this.ModifySettingCommon = true;
12473 #region "Userstream"
12474 private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12478 if (InvokeRequired && !IsDisposed)
12480 Invoke((Action) (async () =>
12482 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
12483 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12485 this.PurgeListViewItemCache();
12486 ((DetailsListView)_curTab.Tag).Update();
12487 if (_curPost != null && _curPost.StatusId == e.StatusId)
12488 await this.DispSelectedPost(true);
12494 catch (ObjectDisposedException)
12498 catch (InvalidOperationException)
12504 private int userStreamsRefreshing = 0;
12506 private async void tw_NewPostFromStream(object sender, EventArgs e)
12508 if (this._cfgCommon.ReadOldPosts)
12510 _statuses.SetReadHomeTab(); //新着時未読クリア
12513 int rsltAddCount = _statuses.DistributePosts();
12515 if (this._cfgCommon.UserstreamPeriod > 0) return;
12517 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
12518 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
12522 await this.InvokeAsync(() => this.RefreshTimeline())
12523 .ConfigureAwait(false);
12527 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
12532 private void tw_UserStreamStarted(object sender, EventArgs e)
12536 if (InvokeRequired && !IsDisposed)
12538 Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12542 catch (ObjectDisposedException)
12546 catch (InvalidOperationException)
12551 this.RefreshUserStreamsMenu();
12552 this.MenuItemUserStream.Enabled = true;
12554 StatusLabel.Text = "UserStream Started.";
12557 private void tw_UserStreamStopped(object sender, EventArgs e)
12561 if (InvokeRequired && !IsDisposed)
12563 Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12567 catch (ObjectDisposedException)
12571 catch (InvalidOperationException)
12576 this.RefreshUserStreamsMenu();
12577 this.MenuItemUserStream.Enabled = true;
12579 StatusLabel.Text = "UserStream Stopped.";
12582 private void RefreshUserStreamsMenu()
12584 if (this.tw.UserStreamActive)
12586 this.MenuItemUserStream.Text = "&UserStream ▶";
12587 this.StopToolStripMenuItem.Text = "&Stop";
12591 this.MenuItemUserStream.Text = "&UserStream ■";
12592 this.StopToolStripMenuItem.Text = "&Start";
12596 private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12600 if (InvokeRequired && !IsDisposed)
12602 Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12606 catch (ObjectDisposedException)
12610 catch (InvalidOperationException)
12614 var ev = e.EventData;
12615 StatusLabel.Text = "Event: " + ev.Event;
12616 //if (ev.Event == "favorite")
12618 // NotifyFavorite(ev);
12621 if (ev.Event == "favorite" || ev.Event == "unfavorite")
12623 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12625 this.PurgeListViewItemCache();
12626 ((DetailsListView)_curTab.Tag).Update();
12628 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
12630 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
12631 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
12636 private void NotifyEvent(Twitter.FormattedEvent ev)
12639 if (BalloonRequired(ev))
12641 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
12642 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
12643 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
12644 StringBuilder title = new StringBuilder();
12645 if (this._cfgCommon.DispUsername)
12647 title.Append(tw.Username);
12648 title.Append(" - ");
12654 title.Append(Application.ProductName);
12655 title.Append(" [");
12656 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
12657 title.Append("] by ");
12658 if (!string.IsNullOrEmpty(ev.Username))
12660 title.Append(ev.Username.ToString());
12664 //title.Append("");
12667 if (!string.IsNullOrEmpty(ev.Target))
12669 //NotifyIcon1.BalloonTipText = ev.Target;
12674 //NotifyIcon1.BalloonTipText = " ";
12677 //NotifyIcon1.ShowBalloonTip(500);
12678 if (this._cfgCommon.IsUseNotifyGrowl)
12680 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
12681 ev.Id.ToString(), title.ToString(), text);
12685 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
12686 NotifyIcon1.BalloonTipTitle = title.ToString();
12687 NotifyIcon1.BalloonTipText = text;
12688 NotifyIcon1.ShowBalloonTip(500);
12693 string snd = this._cfgCommon.EventSoundFile;
12694 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
12696 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
12700 string dir = Application.StartupPath;
12701 if (Directory.Exists(Path.Combine(dir, "Sounds")))
12703 dir = Path.Combine(dir, "Sounds");
12705 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
12717 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
12719 MenuItemUserStream.Enabled = false;
12720 if (StopRefreshAllMenuItem.Checked)
12722 StopRefreshAllMenuItem.Checked = false;
12725 if (this.tw.UserStreamActive)
12727 tw.StopUserStream();
12731 tw.StartUserStream();
12735 private static string inputTrack = "";
12737 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
12739 if (TrackToolStripMenuItem.Checked)
12741 using (InputTabName inputForm = new InputTabName())
12743 inputForm.TabName = inputTrack;
12744 inputForm.FormTitle = "Input track word";
12745 inputForm.FormDescription = "Track word";
12746 if (inputForm.ShowDialog() != DialogResult.OK)
12748 TrackToolStripMenuItem.Checked = false;
12751 inputTrack = inputForm.TabName.Trim();
12753 if (!inputTrack.Equals(tw.TrackWord))
12755 tw.TrackWord = inputTrack;
12756 this.ModifySettingCommon = true;
12757 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
12758 tw.ReconnectUserStream();
12764 tw.ReconnectUserStream();
12766 this.ModifySettingCommon = true;
12769 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
12771 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
12772 this.ModifySettingCommon = true;
12773 tw.ReconnectUserStream();
12776 private void EventViewerMenuItem_Click(object sender, EventArgs e)
12778 if (evtDialog == null || evtDialog.IsDisposed)
12781 evtDialog = new EventViewerDialog();
12782 evtDialog.Owner = this;
12784 Point pos = evtDialog.Location;
12785 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
12786 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
12787 evtDialog.Location = pos;
12789 evtDialog.EventSource = tw.StoredEvent;
12790 if (!evtDialog.Visible)
12792 evtDialog.Show(this);
12796 evtDialog.Activate();
12798 this.TopMost = this._cfgCommon.AlwaysTop;
12802 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
12804 MyCommon._endingFlag = true;
12808 Application.Restart();
12812 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
12816 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
12818 if (!string.IsNullOrEmpty(tw.Username))
12819 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
12822 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
12824 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
12827 private async Task doTranslation(string str)
12829 if (string.IsNullOrEmpty(str))
12832 var bing = new Bing();
12835 var translatedText = await bing.TranslateAsync(str,
12837 langTo: this._cfgCommon.TranslateLanguage);
12839 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
12841 catch (HttpRequestException e)
12843 this.StatusLabel.Text = "Err:" + e.Message;
12845 catch (OperationCanceledException)
12847 this.StatusLabel.Text = "Err:Timeout";
12851 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
12853 if (!this.ExistCurrentPost)
12856 await this.doTranslation(this._curPost.TextFromApi);
12859 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
12861 var text = this.PostBrowser.GetSelectedText();
12862 await this.doTranslation(text);
12865 private bool ExistCurrentPost
12869 if (_curPost == null) return false;
12870 if (_curPost.IsDeleted) return false;
12875 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
12877 ShowUserTimeline();
12880 private string GetUserIdFromCurPostOrInput(string caption)
12882 var id = _curPost?.ScreenName ?? "";
12884 using (InputTabName inputName = new InputTabName())
12886 inputName.FormTitle = caption;
12887 inputName.FormDescription = Properties.Resources.FRMessage1;
12888 inputName.TabName = id;
12889 if (inputName.ShowDialog() == DialogResult.OK &&
12890 !string.IsNullOrEmpty(inputName.TabName.Trim()))
12892 id = inputName.TabName.Trim();
12902 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
12904 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
12905 if (!string.IsNullOrEmpty(id))
12907 AddNewTabForUserTimeline(id);
12911 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
12913 string id = GetUserIdFromCurPostOrInput("Show Favstar");
12914 if (!string.IsNullOrEmpty(id))
12916 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
12920 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
12922 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
12925 private void TimelineRefreshEnableChange(bool isEnable)
12929 tw.StartUserStream();
12933 tw.StopUserStream();
12935 TimerTimeline.Enabled = isEnable;
12938 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
12940 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
12943 private async Task OpenUserAppointUrl()
12945 if (this._cfgCommon.UserAppointUrl != null)
12947 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
12949 if (_curPost != null)
12951 string xUrl = this._cfgCommon.UserAppointUrl;
12952 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
12954 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
12955 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
12957 await this.OpenUriInBrowserAsync(xUrl);
12962 await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
12967 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12969 await this.OpenUserAppointUrl();
12972 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
12974 string selText = SourceLinkLabel.Text;
12977 Clipboard.SetDataObject(selText, false, 5, 100);
12979 catch (Exception ex)
12981 MessageBox.Show(ex.Message);
12985 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
12987 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12990 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
12992 catch (Exception ex)
12994 MessageBox.Show(ex.Message);
12998 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13000 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13002 SourceCopyMenuItem.Enabled = false;
13003 SourceUrlCopyMenuItem.Enabled = false;
13007 SourceCopyMenuItem.Enabled = true;
13008 SourceUrlCopyMenuItem.Enabled = true;
13012 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13014 if (Form.ActiveForm == null)
13016 this.BeginInvoke((Action) (() =>
13018 this.Visible = true;
13019 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13021 this.BringToFront();
13022 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13024 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13028 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13034 private void ReplaceAppName()
13036 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13037 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13040 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13042 this.SplitContainer3.Panel2Collapsed = false;
13045 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13047 await this.OpenThumbnailPicture(e.Thumbnail);
13050 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13052 await this.OpenUriInBrowserAsync(e.ImageUrl);
13055 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
13057 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
13059 await this.OpenUriInBrowserAsync(url);
13062 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13064 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
13067 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13069 if (e.KeyCode == Keys.Space)
13071 this.JumpUnreadMenuItem_Click(null, null);
13073 e.SuppressKeyPress = true;
13077 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13079 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13080 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13081 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13082 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13083 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13085 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13088 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13090 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13093 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13095 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13098 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13100 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13103 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13105 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13108 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13110 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13113 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13115 if (this._cfgCommon.IconSize == iconSize) return;
13117 var oldIconCol = _iconCol;
13119 this._cfgCommon.IconSize = iconSize;
13120 ApplyListViewIconSize(iconSize);
13122 if (_iconCol != oldIconCol)
13124 foreach (TabPage tp in ListTab.TabPages)
13126 ResetColumns((DetailsListView)tp.Tag);
13130 _curList?.Refresh();
13132 ModifySettingCommon = true;
13135 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13137 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13138 if (this._cfgCommon.SortOrderLock == state) return;
13140 this._cfgCommon.SortOrderLock = state;
13142 ModifySettingCommon = true;