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;
44 using System.Runtime.InteropServices;
46 using System.Text.RegularExpressions;
47 using System.Threading;
48 using System.Threading.Tasks;
49 using System.Windows.Forms;
51 using OpenTween.Api.DataModel;
52 using OpenTween.Connection;
53 using OpenTween.Models;
54 using OpenTween.OpenTweenCustomControl;
55 using OpenTween.Setting;
56 using OpenTween.Thumbnail;
60 public partial class TweenMain : OTBaseForm
63 private Size _mySize; //画面サイズ
64 private Point _myLoc; //画面位置
65 private int _mySpDis; //区切り位置
66 private int _mySpDis2; //発言欄区切り位置
67 private int _mySpDis3; //プレビュー区切り位置
68 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
69 private bool _iconCol; //1列表示の時true(48サイズのとき)
72 private bool _initial; //true:起動時処理中
73 private bool _initialLayout = true;
74 private bool _ignoreConfigSave; //true:起動時処理中
75 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
76 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
77 private Point _tabMouseDownPoint;
78 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
79 private readonly object _syncObject = new object(); //ロック用
81 private const string detailHtmlFormatHeaderMono =
82 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
83 + "<style type=\"text/css\"><!-- "
84 + "body, p, pre {margin: 0;} "
85 + "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%);} "
86 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
87 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
88 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
89 + ".quote-tweet.reply {border-color: #f33;} "
90 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
92 + "</head><body><pre>";
93 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
94 private const string detailHtmlFormatHeaderColor =
95 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
96 + "<style type=\"text/css\"><!-- "
97 + "body, p, pre {margin: 0;} "
98 + "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%);} "
99 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
100 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
101 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
102 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
103 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
105 + "</head><body><p>";
106 private const string detailHtmlFormatFooterColor = "</p></body></html>";
107 private string detailHtmlFormatHeader;
108 private string detailHtmlFormatFooter;
110 private bool _myStatusError = false;
111 private bool _myStatusOnline = false;
112 private bool soundfileListup = false;
113 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
116 private TwitterApi twitterApi = new TwitterApi();
120 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
123 internal SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
124 private OpenURL UrlDialog = new OpenURL();
125 public AtIdSupplement AtIdSupl; //@id補助
126 public AtIdSupplement HashSupl; //Hashtag補助
127 public HashtagManage HashMgr;
128 private EventViewerDialog evtDialog;
131 private Font _fntUnread; //未読用フォント
132 private Color _clUnread; //未読用文字色
133 private Font _fntReaded; //既読用フォント
134 private Color _clReaded; //既読用文字色
135 private Color _clFav; //Fav用文字色
136 private Color _clOWL; //片思い用文字色
137 private Color _clRetweet; //Retweet用文字色
138 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
139 private Font _fntDetail; //発言詳細部用フォント
140 private Color _clDetail; //発言詳細部用色
141 private Color _clDetailLink; //発言詳細部用リンク文字色
142 private Color _clDetailBackcolor; //発言詳細部用背景色
143 private Color _clSelf; //自分の発言用背景色
144 private Color _clAtSelf; //自分宛返信用背景色
145 private Color _clTarget; //選択発言者の他の発言用背景色
146 private Color _clAtTarget; //選択発言中の返信先用背景色
147 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
148 private Color _clAtTo; //選択発言の唯一@先
149 private Color _clListBackcolor; //リスト部通常発言背景色
150 private Color _clInputBackcolor; //入力欄背景色
151 private Color _clInputFont; //入力欄文字色
152 private Font _fntInputFont; //入力欄フォント
153 private ImageCache IconCache; //アイコン画像リスト
154 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
155 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
156 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
157 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
158 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
159 private Icon MainIcon; //Main.ico 画面左上のアイコン
160 private Icon ReplyIcon; //5g
161 private Icon ReplyIconBlink; //6g
163 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
165 private PostClass _anchorPost;
166 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
168 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
169 private int _hisIdx; //発言履歴カレントインデックス
171 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
172 private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
175 private List<DateTime> _postTimestamps = new List<DateTime>();
176 private List<DateTime> _favTimestamps = new List<DateTime>();
179 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
180 private SolidBrush _brsBackColorMine;
181 private SolidBrush _brsBackColorAt;
182 private SolidBrush _brsBackColorYou;
183 private SolidBrush _brsBackColorAtYou;
184 private SolidBrush _brsBackColorAtFromTarget;
185 private SolidBrush _brsBackColorAtTo;
186 private SolidBrush _brsBackColorNone;
187 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
188 private StringFormat sfTab = new StringFormat();
190 //////////////////////////////////////////////////////////////////////////////////////////////////////////
191 private TabInformations _statuses;
194 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
197 /// キャッシュクリアのために null が代入されることがあるため、
198 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
199 /// 一旦ローカル変数に代入してから参照すること。
201 private ListViewItemCache _listItemCache = null;
203 internal class ListViewItemCache
205 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
206 public ListView TargetList { get; set; }
208 /// <summary>キャッシュする範囲の開始インデックス</summary>
209 public int StartIndex { get; set; }
211 /// <summary>キャッシュする範囲の終了インデックス</summary>
212 public int EndIndex { get; set; }
214 /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
215 public ListViewItem[] ListItem { get; set; }
217 /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
218 public PostClass[] Post { get; set; }
220 /// <summary>キャッシュされたアイテムの件数</summary>
222 => this.EndIndex - this.StartIndex + 1;
224 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
225 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
226 public bool Contains(int index)
227 => index >= this.StartIndex && index <= this.EndIndex;
229 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
230 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
231 public bool IsSupersetOf(int rangeStart, int rangeEnd)
232 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
234 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
235 /// <returns>取得に成功すれば true、それ以外は false</returns>
236 public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
238 if (this.Contains(index))
240 item = this.ListItem[index - this.StartIndex];
241 post = this.Post[index - this.StartIndex];
253 private TabPage _curTab;
254 private int _curItemIndex;
255 private DetailsListView _curList;
256 private PostClass _curPost;
257 private bool _isColumnChanged = false;
259 private const int MAX_WORKER_THREADS = 20;
260 private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
261 private CancellationTokenSource workerCts = new CancellationTokenSource();
262 private IProgress<string> workerProgress;
264 private int UnreadCounter = -1;
265 private int UnreadAtCounter = -1;
267 private string[] ColumnOrgText = new string[9];
268 private string[] ColumnText = new string[9];
270 private bool _DoFavRetweetFlags = false;
271 private bool osResumed = false;
273 //////////////////////////////////////////////////////////////////////////////////////////////////////////
274 private bool _colorize = false;
276 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
278 private string recommendedStatusFooter;
279 private bool urlMultibyteSplit = false;
280 private bool preventSmsCommand = true;
283 private struct urlUndo
285 public string Before;
289 private List<urlUndo> urlUndoBuffer = null;
291 private struct ReplyChain
293 public long OriginalId;
294 public long InReplyToId;
295 public TabPage OriginalTab;
297 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
299 this.OriginalId = originalId;
300 this.InReplyToId = inReplyToId;
301 this.OriginalTab = originalTab;
305 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
306 private Stack<ValueTuple<TabPage, PostClass>> selectPostChains = new Stack<ValueTuple<TabPage, PostClass>>(); //ポスト選択履歴
309 internal enum SEARCHTYPE
316 private class PostingStatus
318 public string status = "";
319 public long? inReplyToId = null;
320 public string inReplyToName = null;
321 public string imageService = ""; //画像投稿サービス名
322 public IMediaItem[] mediaItems = null;
323 public PostingStatus()
326 public PostingStatus(string status, long? replyToId, string replyToName)
328 this.status = status;
329 this.inReplyToId = replyToId;
330 this.inReplyToName = replyToName;
334 private void TweenMain_Activated(object sender, EventArgs e)
336 //画面がアクティブになったら、発言欄の背景色戻す
337 if (StatusText.Focused)
339 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
343 private bool disposed = false;
346 /// 使用中のリソースをすべてクリーンアップします。
348 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
349 protected override void Dispose(bool disposing)
351 base.Dispose(disposing);
358 this.components?.Dispose();
361 SearchDialog.Dispose();
364 NIconAtRed?.Dispose();
365 NIconAtSmoke?.Dispose();
366 foreach (var iconRefresh in this.NIconRefresh)
368 iconRefresh?.Dispose();
372 ReplyIcon?.Dispose();
373 ReplyIconBlink?.Dispose();
374 _listViewImageList.Dispose();
375 _brsHighLight.Dispose();
376 _brsBackColorMine?.Dispose();
377 _brsBackColorAt?.Dispose();
378 _brsBackColorYou?.Dispose();
379 _brsBackColorAtYou?.Dispose();
380 _brsBackColorAtFromTarget?.Dispose();
381 _brsBackColorAtTo?.Dispose();
382 _brsBackColorNone?.Dispose();
383 _brsDeactiveSelection?.Dispose();
387 this.workerCts.Cancel();
389 if (IconCache != null)
391 this.IconCache.CancelAsync();
392 this.IconCache.Dispose();
395 this.thumbnailTokenSource?.Dispose();
398 this.twitterApi.Dispose();
399 this._hookGlobalHotkey.Dispose();
402 // 終了時にRemoveHandlerしておかないとメモリリークする
403 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
404 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
406 this.disposed = true;
409 private void LoadIcons()
411 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
412 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
415 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
418 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
421 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
424 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
426 // タスクトレイ: オフライン時アイコン
427 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
429 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
430 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
431 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
433 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
434 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
435 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
436 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
437 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
439 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
441 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
442 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
443 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
444 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
445 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
447 if (iconReply != null && iconReplyBlink != null)
449 this.ReplyIcon = iconReply;
450 this.ReplyIconBlink = iconReplyBlink;
454 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
455 this.ReplyIconBlink = this.NIconAt;
458 if (iconRefresh1 == null)
460 this.NIconRefresh = new[] {
461 Properties.Resources.Refresh, Properties.Resources.Refresh2,
462 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
465 else if (iconRefresh2 == null)
467 this.NIconRefresh = new[] { iconRefresh1 };
469 else if (iconRefresh3 == null)
471 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
473 else if (iconRefresh4 == null)
475 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
477 else // iconRefresh1 から iconRefresh4 まで全て揃っている
479 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
483 private Icon LoadIcon(string filePath)
485 if (!File.Exists(filePath))
490 return new Icon(filePath);
498 private void InitColumns(ListView list, bool startup)
500 this.InitColumnText();
502 ColumnHeader[] columns = null;
509 new ColumnHeader(), // アイコン
510 new ColumnHeader(), // 本文
513 columns[0].Text = this.ColumnText[0];
514 columns[1].Text = this.ColumnText[2];
518 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
520 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
521 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
522 columns[0].DisplayIndex = 0;
523 columns[1].DisplayIndex = 1;
528 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
530 columns[idx].Width = curListColumn.Width;
531 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
540 new ColumnHeader(), // アイコン
541 new ColumnHeader(), // ニックネーム
542 new ColumnHeader(), // 本文
543 new ColumnHeader(), // 日付
544 new ColumnHeader(), // ユーザID
545 new ColumnHeader(), // 未読
546 new ColumnHeader(), // マーク&プロテクト
547 new ColumnHeader(), // ソース
550 foreach (var i in Enumerable.Range(0, columns.Length))
551 columns[i].Text = this.ColumnText[i];
555 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
557 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
558 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width2);
559 columns[2].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
560 columns[3].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width4);
561 columns[4].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width5);
562 columns[5].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width6);
563 columns[6].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width7);
564 columns[7].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width8);
566 var displayIndex = new[] {
567 SettingManager.Local.DisplayIndex1, SettingManager.Local.DisplayIndex2,
568 SettingManager.Local.DisplayIndex3, SettingManager.Local.DisplayIndex4,
569 SettingManager.Local.DisplayIndex5, SettingManager.Local.DisplayIndex6,
570 SettingManager.Local.DisplayIndex7, SettingManager.Local.DisplayIndex8
573 foreach (var i in Enumerable.Range(0, displayIndex.Length))
575 columns[i].DisplayIndex = displayIndex[i];
581 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
583 columns[idx].Width = curListColumn.Width;
584 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
590 list.Columns.AddRange(columns);
598 foreach (var column in columns)
604 private void InitColumnText()
607 ColumnText[1] = Properties.Resources.AddNewTabText2;
608 ColumnText[2] = Properties.Resources.AddNewTabText3;
609 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
610 ColumnText[4] = Properties.Resources.AddNewTabText5;
613 ColumnText[7] = "Source";
615 ColumnOrgText[0] = "";
616 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
617 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
618 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
619 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
620 ColumnOrgText[5] = "";
621 ColumnOrgText[6] = "";
622 ColumnOrgText[7] = "Source";
625 switch (_statuses.SortMode)
627 case ComparerMode.Nickname: //ニックネーム
630 case ComparerMode.Data: //本文
633 case ComparerMode.Id: //時刻=発言Id
636 case ComparerMode.Name: //名前
639 case ComparerMode.Source: //Source
646 if (_statuses.SortOrder == SortOrder.Descending)
648 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
649 ColumnText[2] = ColumnOrgText[2] + "▾";
653 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
654 ColumnText[2] = ColumnOrgText[2] + "▴";
659 if (_statuses.SortOrder == SortOrder.Descending)
661 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
662 ColumnText[c] = ColumnOrgText[c] + "▾";
666 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
667 ColumnText[c] = ColumnOrgText[c] + "▴";
672 private void InitializeTraceFrag()
675 TraceOutToolStripMenuItem.Checked = true;
676 MyCommon.TraceFlag = true;
678 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
680 TraceOutToolStripMenuItem.Checked = true;
681 MyCommon.TraceFlag = true;
685 private void TweenMain_Load(object sender, EventArgs e)
687 _ignoreConfigSave = true;
688 this.Visible = false;
690 if (MyApplication.StartupOptions.ContainsKey("d"))
691 MyCommon.TraceFlag = true;
693 InitializeTraceFrag();
695 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
697 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
698 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
700 Regex.CacheSize = 100;
703 _statuses = TabInformations.GetInstance();
707 this.Icon = MainIcon; //メインフォーム(TweenMain)
708 NotifyIcon1.Icon = NIconAt; //タスクトレイ
709 TabImage.Images.Add(TabIcon); //タブ見出し
711 //<<<<<<<<<設定関連>>>>>>>>>
715 // 現在の DPI と設定保存時の DPI との比を取得する
716 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
719 var fontUIGlobal = SettingManager.Local.FontUIGlobal;
720 if (fontUIGlobal != null)
722 OTBaseForm.GlobalFont = fontUIGlobal;
723 this.Font = fontUIGlobal;
727 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
729 if (SettingManager.Common.TimelinePeriod < 15 && SettingManager.Common.TimelinePeriod > 0)
730 SettingManager.Common.TimelinePeriod = 15;
732 if (SettingManager.Common.ReplyPeriod < 15 && SettingManager.Common.ReplyPeriod > 0)
733 SettingManager.Common.ReplyPeriod = 15;
735 if (SettingManager.Common.DMPeriod < 15 && SettingManager.Common.DMPeriod > 0)
736 SettingManager.Common.DMPeriod = 15;
738 if (SettingManager.Common.PubSearchPeriod < 30 && SettingManager.Common.PubSearchPeriod > 0)
739 SettingManager.Common.PubSearchPeriod = 30;
741 if (SettingManager.Common.UserTimelinePeriod < 15 && SettingManager.Common.UserTimelinePeriod > 0)
742 SettingManager.Common.UserTimelinePeriod = 15;
744 if (SettingManager.Common.ListsPeriod < 15 && SettingManager.Common.ListsPeriod > 0)
745 SettingManager.Common.ListsPeriod = 15;
748 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, SettingManager.Common.CountApi))
749 SettingManager.Common.CountApi = 60;
750 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, SettingManager.Common.CountApiReply))
751 SettingManager.Common.CountApiReply = 40;
753 if (SettingManager.Common.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(SettingManager.Common.MoreCountApi))
754 SettingManager.Common.MoreCountApi = 200;
755 if (SettingManager.Common.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(SettingManager.Common.FirstCountApi))
756 SettingManager.Common.FirstCountApi = 100;
758 if (SettingManager.Common.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, SettingManager.Common.FavoritesCountApi))
759 SettingManager.Common.FavoritesCountApi = 40;
760 if (SettingManager.Common.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, SettingManager.Common.ListCountApi))
761 SettingManager.Common.ListCountApi = 100;
762 if (SettingManager.Common.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, SettingManager.Common.SearchCountApi))
763 SettingManager.Common.SearchCountApi = 100;
764 if (SettingManager.Common.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, SettingManager.Common.UserTimelineCountApi))
765 SettingManager.Common.UserTimelineCountApi = 20;
767 //廃止サービスが選択されていた場合ux.nuへ読み替え
768 if (SettingManager.Common.AutoShortUrlFirst < 0)
769 SettingManager.Common.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
771 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
772 this.tw = new Twitter(this.twitterApi);
775 if (string.IsNullOrEmpty(SettingManager.Common.Token)) SettingManager.Common.UserName = "";
776 tw.Initialize(SettingManager.Common.Token, SettingManager.Common.TokenSecret, SettingManager.Common.UserName, SettingManager.Common.UserId);
780 Networking.Initialize();
782 bool saveRequired = false;
783 bool firstRun = false;
785 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
786 if (string.IsNullOrEmpty(tw.Username))
791 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
792 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
793 string.IsNullOrEmpty(tw.Username))
795 Application.Exit(); //強制終了
801 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
802 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
803 Networking.SetWebProxy(SettingManager.Local.ProxyType,
804 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
805 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
806 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
808 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
809 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
810 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
811 tw.TrackWord = SettingManager.Common.TrackWord;
812 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
813 tw.AllAtReply = SettingManager.Common.AllAtReply;
814 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
815 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
816 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
817 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
818 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
820 // アクセストークンが有効であるか確認する
821 // ここが Twitter API への最初のアクセスになるようにすること
824 this.tw.VerifyCredentials();
826 catch (WebApiException ex)
828 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
829 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
833 //プロキシ設定等の通信まわりの初期化が済んでから処理する
834 ThumbnailGenerator.InitializeGenerator();
836 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
837 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
838 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
840 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
843 ImageSelector.Initialize(tw, this.tw.Configuration, SettingManager.Common.UseImageServiceName, SettingManager.Common.UseImageService);
846 AtIdSupl = new AtIdSupplement(SettingManager.AtIdList.AtIdList, "@");
847 HashSupl = new AtIdSupplement(SettingManager.Common.HashTags, "#");
848 HashMgr = new HashtagManage(HashSupl,
849 SettingManager.Common.HashTags.ToArray(),
850 SettingManager.Common.HashSelected,
851 SettingManager.Common.HashIsPermanent,
852 SettingManager.Common.HashIsHead,
853 SettingManager.Common.HashIsNotAddToAtReply);
854 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
857 this.IconCache = new ImageCache();
858 this.tweetDetailsView.IconCache = this.IconCache;
861 _fntUnread = SettingManager.Local.FontUnread;
862 _clUnread = SettingManager.Local.ColorUnread;
863 _fntReaded = SettingManager.Local.FontRead;
864 _clReaded = SettingManager.Local.ColorRead;
865 _clFav = SettingManager.Local.ColorFav;
866 _clOWL = SettingManager.Local.ColorOWL;
867 _clRetweet = SettingManager.Local.ColorRetweet;
868 _fntDetail = SettingManager.Local.FontDetail;
869 _clDetail = SettingManager.Local.ColorDetail;
870 _clDetailLink = SettingManager.Local.ColorDetailLink;
871 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
872 _clSelf = SettingManager.Local.ColorSelf;
873 _clAtSelf = SettingManager.Local.ColorAtSelf;
874 _clTarget = SettingManager.Local.ColorTarget;
875 _clAtTarget = SettingManager.Local.ColorAtTarget;
876 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
877 _clAtTo = SettingManager.Local.ColorAtTo;
878 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
879 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
880 _clInputFont = SettingManager.Local.ColorInputFont;
881 _fntInputFont = SettingManager.Local.FontInputFont;
883 _brsBackColorMine = new SolidBrush(_clSelf);
884 _brsBackColorAt = new SolidBrush(_clAtSelf);
885 _brsBackColorYou = new SolidBrush(_clTarget);
886 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
887 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
888 _brsBackColorAtTo = new SolidBrush(_clAtTo);
889 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
890 _brsBackColorNone = new SolidBrush(_clListBackcolor);
892 // StringFormatオブジェクトへの事前設定
893 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
894 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
895 //sf.FormatFlags = StringFormatFlags.LineLimit; //
896 sfTab.Alignment = StringAlignment.Center;
897 sfTab.LineAlignment = StringAlignment.Center;
899 InitDetailHtmlFormat();
901 //Regex statregex = new Regex("^0*");
902 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
904 _history.Add(new PostingStatus());
906 this.inReplyTo = null;
909 SearchDialog.Owner = this;
910 UrlDialog.Owner = this;
913 NewPostPopMenuItem.Checked = SettingManager.Common.NewAllPop;
914 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
916 //新着取得時のリストスクロールをするか。trueならスクロールしない
917 ListLockMenuItem.Checked = SettingManager.Common.ListLock;
918 this.LockListFileMenuItem.Checked = SettingManager.Common.ListLock;
920 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
921 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
924 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
925 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
926 _myLoc = SettingManager.Local.FormLocation;
928 if (this.WindowState != FormWindowState.Minimized)
930 Rectangle tbarRect = new Rectangle(this._myLoc, new Size(_mySize.Width, SystemInformation.CaptionHeight));
931 bool outOfScreen = true;
932 if (Screen.AllScreens.Length == 1) //ハングするとの報告
934 foreach (Screen scr in Screen.AllScreens)
936 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
944 this._myLoc = new Point(0, 0);
946 this.DesktopLocation = this._myLoc;
948 this.TopMost = SettingManager.Common.AlwaysTop;
949 _mySpDis = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
950 _mySpDis2 = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
951 if (SettingManager.Local.PreviewDistance == -1)
953 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
954 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
955 SettingManager.Local.PreviewDistance = _mySpDis3;
959 _mySpDis3 = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
961 //this.Tween_ClientSizeChanged(this, null);
962 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
963 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
965 StatusText.Font = _fntInputFont;
966 StatusText.ForeColor = _clInputFont;
968 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
969 this.StatusText.Multiline = false; // SettingManager.Local.StatusMultiline の設定は後で反映される
970 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
972 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
973 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
975 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
976 if (SettingManager.Common.UnreadManage == false)
978 ReadedStripMenuItem.Enabled = false;
979 UnreadStripMenuItem.Enabled = false;
982 //リンク先URL表示部の初期化(画面左下)
983 StatusLabelUrl.Text = "";
985 StatusLabel.Text = "";
986 StatusLabel.AutoToolTip = false;
987 StatusLabel.ToolTipText = "";
989 lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
991 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
992 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
993 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
994 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
996 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
997 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
998 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
999 this.SplitContainer2.Panel2.AccessibleName = "";
1001 ////////////////////////////////////////////////////////////////////////////////
1002 var sortOrder = (SortOrder)SettingManager.Common.SortOrder;
1003 var mode = ComparerMode.Id;
1004 switch (SettingManager.Common.SortColumn)
1006 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1010 mode = ComparerMode.Id; //Idソートに読み替え
1013 mode = ComparerMode.Nickname;
1016 mode = ComparerMode.Data;
1019 mode = ComparerMode.Id;
1022 mode = ComparerMode.Name;
1025 mode = ComparerMode.Source;
1028 _statuses.SetSortMode(mode, sortOrder);
1029 ////////////////////////////////////////////////////////////////////////////////
1031 ApplyListViewIconSize(SettingManager.Common.IconSize);
1033 //<<<<<<<<タブ関連>>>>>>>
1037 //デフォルトタブの存在チェック、ない場合には追加
1038 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1039 this._statuses.AddTab(new HomeTabModel());
1041 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1042 this._statuses.AddTab(new MentionsTabModel());
1044 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1045 this._statuses.AddTab(new DirectMessagesTabModel());
1047 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1048 this._statuses.AddTab(new FavoritesTabModel());
1050 if (this._statuses.GetTabByType<MuteTabModel>() == null)
1051 this._statuses.AddTab(new MuteTabModel());
1053 foreach (var tab in _statuses.Tabs.Values)
1056 if (tab.TabType == MyCommon.TabUsageType.Mute)
1059 if (!AddNewTab(tab, startup: true))
1060 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1063 _curTab = ListTab.SelectedTab;
1065 _curList = (DetailsListView)_curTab.Tag;
1067 if (SettingManager.Common.TabIconDisp)
1069 ListTab.DrawMode = TabDrawMode.Normal;
1073 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1074 ListTab.DrawItem += ListTab_DrawItem;
1075 ListTab.ImageList = null;
1078 if (SettingManager.Common.HotkeyEnabled)
1081 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1082 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
1083 modKey |= HookGlobalHotkey.ModKeys.Alt;
1084 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
1085 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1086 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
1087 modKey |= HookGlobalHotkey.ModKeys.Shift;
1088 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
1089 modKey |= HookGlobalHotkey.ModKeys.Win;
1091 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
1094 if (SettingManager.Common.IsUseNotifyGrowl)
1097 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1099 SetMainWindowTitle();
1100 SetNotifyIconText();
1102 if (!SettingManager.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1104 this.Visible = true;
1108 TimerTimeline.AutoReset = true;
1109 TimerTimeline.SynchronizingObject = this;
1111 TimerTimeline.Interval = 1000;
1112 TimerTimeline.Enabled = true;
1114 TimerRefreshIcon.Interval = 200;
1115 TimerRefreshIcon.Enabled = true;
1117 _ignoreConfigSave = false;
1118 this.TweenMain_Resize(null, null);
1119 if (saveRequired) SaveConfigsAll(false);
1121 foreach (var ua in SettingManager.Common.UserAccounts)
1123 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1125 ua.UserId = tw.UserId;
1132 // 初回起動時だけ右下のメニューを目立たせる
1133 HashStripSplitButton.ShowDropDown();
1137 private void InitDetailHtmlFormat()
1139 if (SettingManager.Common.IsMonospace)
1141 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1142 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1146 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1147 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1150 detailHtmlFormatHeader = detailHtmlFormatHeader
1151 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1152 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1153 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1154 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1155 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1156 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1159 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1164 txt = ListTab.TabPages[e.Index].Text;
1171 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1172 if (e.State == DrawItemState.Selected)
1174 e.DrawFocusRectangle();
1179 if (_statuses.Tabs[txt].UnreadCount > 0)
1182 fore = System.Drawing.SystemBrushes.ControlText;
1186 fore = System.Drawing.SystemBrushes.ControlText;
1188 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1191 private void LoadConfig()
1193 SettingManager.Local = SettingManager.Local;
1195 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1196 if (SettingManager.Local.ScaleDimension.IsEmpty)
1197 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
1199 var tabSettings = SettingManager.Tabs;
1200 foreach (var tabSetting in tabSettings.Tabs)
1203 switch (tabSetting.TabType)
1205 case MyCommon.TabUsageType.Home:
1206 tab = new HomeTabModel(tabSetting.TabName);
1208 case MyCommon.TabUsageType.Mentions:
1209 tab = new MentionsTabModel(tabSetting.TabName);
1211 case MyCommon.TabUsageType.DirectMessage:
1212 tab = new DirectMessagesTabModel(tabSetting.TabName);
1214 case MyCommon.TabUsageType.Favorites:
1215 tab = new FavoritesTabModel(tabSetting.TabName);
1217 case MyCommon.TabUsageType.UserDefined:
1218 tab = new FilterTabModel(tabSetting.TabName);
1220 case MyCommon.TabUsageType.UserTimeline:
1221 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1223 case MyCommon.TabUsageType.PublicSearch:
1224 tab = new PublicSearchTabModel(tabSetting.TabName)
1226 SearchWords = tabSetting.SearchWords,
1227 SearchLang = tabSetting.SearchLang,
1230 case MyCommon.TabUsageType.Lists:
1231 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1233 case MyCommon.TabUsageType.Mute:
1234 tab = new MuteTabModel(tabSetting.TabName);
1240 tab.UnreadManage = tabSetting.UnreadManage;
1241 tab.Protected = tabSetting.Protected;
1242 tab.Notify = tabSetting.Notify;
1243 tab.SoundFile = tabSetting.SoundFile;
1245 if (tab.IsDistributableTabType)
1247 var filterTab = (FilterTabModel)tab;
1248 filterTab.FilterArray = tabSetting.FilterArray;
1249 filterTab.FilterModified = false;
1252 if (this._statuses.ContainsTab(tab.TabName))
1253 tab.TabName = this._statuses.MakeTabName("MyTab");
1255 this._statuses.AddTab(tab);
1257 if (_statuses.Tabs.Count == 0)
1259 _statuses.AddTab(new HomeTabModel());
1260 _statuses.AddTab(new MentionsTabModel());
1261 _statuses.AddTab(new DirectMessagesTabModel());
1262 _statuses.AddTab(new FavoritesTabModel());
1266 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1268 if (!TimerTimeline.Enabled) return;
1272 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1274 private static int homeCounter = 0;
1275 private static int mentionCounter = 0;
1276 private static int dmCounter = 0;
1277 private static int pubSearchCounter = 0;
1278 private static int userTimelineCounter = 0;
1279 private static int listsCounter = 0;
1280 private static int usCounter = 0;
1281 private static int ResumeWait = 0;
1282 private static int refreshFollowers = 0;
1284 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1286 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1287 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1288 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1289 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1290 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1291 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1292 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1293 Interlocked.Increment(ref refreshFollowers);
1295 var refreshTasks = new List<Task>();
1298 if (ResetTimers.Timeline || homeCounter <= 0 && SettingManager.Common.TimelinePeriod > 0)
1300 Interlocked.Exchange(ref homeCounter, SettingManager.Common.TimelinePeriod);
1301 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1302 refreshTasks.Add(this.GetHomeTimelineAsync());
1303 ResetTimers.Timeline = false;
1305 if (ResetTimers.Reply || mentionCounter <= 0 && SettingManager.Common.ReplyPeriod > 0)
1307 Interlocked.Exchange(ref mentionCounter, SettingManager.Common.ReplyPeriod);
1308 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1309 refreshTasks.Add(this.GetReplyAsync());
1310 ResetTimers.Reply = false;
1312 if (ResetTimers.DirectMessage || dmCounter <= 0 && SettingManager.Common.DMPeriod > 0)
1314 Interlocked.Exchange(ref dmCounter, SettingManager.Common.DMPeriod);
1315 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1316 refreshTasks.Add(this.GetDirectMessagesAsync());
1317 ResetTimers.DirectMessage = false;
1319 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && SettingManager.Common.PubSearchPeriod > 0)
1321 Interlocked.Exchange(ref pubSearchCounter, SettingManager.Common.PubSearchPeriod);
1322 if (!ResetTimers.PublicSearch)
1323 refreshTasks.Add(this.GetPublicSearchAllAsync());
1324 ResetTimers.PublicSearch = false;
1326 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && SettingManager.Common.UserTimelinePeriod > 0)
1328 Interlocked.Exchange(ref userTimelineCounter, SettingManager.Common.UserTimelinePeriod);
1329 if (!ResetTimers.UserTimeline)
1330 refreshTasks.Add(this.GetUserTimelineAllAsync());
1331 ResetTimers.UserTimeline = false;
1333 if (ResetTimers.Lists || listsCounter <= 0 && SettingManager.Common.ListsPeriod > 0)
1335 Interlocked.Exchange(ref listsCounter, SettingManager.Common.ListsPeriod);
1336 if (!ResetTimers.Lists)
1337 refreshTasks.Add(this.GetListTimelineAllAsync());
1338 ResetTimers.Lists = false;
1340 if (ResetTimers.UserStream || usCounter <= 0 && SettingManager.Common.UserstreamPeriod > 0)
1342 Interlocked.Exchange(ref usCounter, SettingManager.Common.UserstreamPeriod);
1343 if (this.tw.UserStreamActive)
1344 this.RefreshTimeline();
1345 ResetTimers.UserStream = false;
1347 if (refreshFollowers > 6 * 3600)
1349 Interlocked.Exchange(ref refreshFollowers, 0);
1350 refreshTasks.AddRange(new[]
1352 this.doGetFollowersMenu(),
1353 this.RefreshNoRetweetIdsAsync(),
1354 this.RefreshTwitterConfigurationAsync(),
1359 Interlocked.Increment(ref ResumeWait);
1360 if (ResumeWait > 30)
1363 Interlocked.Exchange(ref ResumeWait, 0);
1364 refreshTasks.AddRange(new[]
1366 this.GetHomeTimelineAsync(),
1367 this.GetReplyAsync(),
1368 this.GetDirectMessagesAsync(),
1369 this.GetPublicSearchAllAsync(),
1370 this.GetUserTimelineAllAsync(),
1371 this.GetListTimelineAllAsync(),
1372 this.doGetFollowersMenu(),
1373 this.RefreshTwitterConfigurationAsync(),
1378 await Task.WhenAll(refreshTasks);
1381 private void RefreshTimeline()
1383 var curTabModel = this._statuses.Tabs[this._curTab.Text];
1385 // 現在表示中のタブのスクロール位置を退避
1386 var curListScroll = this.SaveListViewScroll(this._curList, curTabModel);
1388 // 各タブのリスト上の選択位置などを退避
1389 var listSelections = this.SaveListViewSelection();
1393 addCount = _statuses.SubmitUpdate(out var soundFile, out var notifyPosts,
1394 out var newMentionOrDm, out var isDelete);
1396 if (MyCommon._endingFlag) return;
1399 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1401 var listView = (DetailsListView)tabPage.Tag;
1402 var tabModel = this._statuses.Tabs[tabPage.Text];
1404 if (listView.VirtualListSize != tabModel.AllCount || isDelete)
1406 using (ControlTransaction.Update(listView))
1408 if (listView == this._curList)
1409 this.PurgeListViewItemCache();
1414 listView.VirtualListSize = tabModel.AllCount;
1416 catch (NullReferenceException ex)
1418 // WinForms 内部で ListView.set_TopItem が発生させている例外
1419 // https://ja.osdn.net/ticket/browse.php?group_id=6526&tid=36588
1420 MyCommon.TraceOut(ex, $"TabType: {tabModel.TabType}, Count: {tabModel.AllCount}, ListSize: {listView.VirtualListSize}");
1424 this.RestoreListViewSelection(listView, tabModel, listSelections[tabModel.TabName]);
1431 if (SettingManager.Common.TabIconDisp)
1433 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1435 var tabModel = this._statuses.Tabs[tabPage.Text];
1436 if (tabModel.UnreadCount > 0 && tabPage.ImageIndex != 0)
1437 tabPage.ImageIndex = 0; // 未読アイコン
1442 this.ListTab.Refresh();
1447 this.RestoreListViewScroll(this._curList, curTabModel, curListScroll);
1450 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1452 SetMainWindowTitle();
1453 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1455 HashSupl.AddRangeItem(tw.GetHashList());
1459 internal struct ListViewScroll
1461 public ScrollLockMode ScrollLockMode { get; set; }
1462 public long? TopItemStatusId { get; set; }
1465 internal enum ScrollLockMode
1467 /// <summary>固定しない</summary>
1470 /// <summary>最上部に固定する</summary>
1473 /// <summary>最下部に固定する</summary>
1476 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1481 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1483 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1485 var listScroll = new ListViewScroll
1487 ScrollLockMode = this.GetScrollLockMode(listView),
1490 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1492 var topItemIndex = listView.TopItem?.Index ?? -1;
1493 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
1494 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItemIndex);
1500 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1502 if (this._statuses.SortMode == ComparerMode.Id)
1504 if (this._statuses.SortOrder == SortOrder.Ascending)
1507 if (this.ListLockMenuItem.Checked)
1508 return ScrollLockMode.None;
1510 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1513 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1514 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1515 return ScrollLockMode.FixedToBottom;
1517 return ScrollLockMode.None;
1522 if (this.ListLockMenuItem.Checked)
1523 return ScrollLockMode.FixedToItem;
1525 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1526 var topItem = listView.TopItem;
1527 if (topItem == null || topItem.Index == 0)
1528 return ScrollLockMode.FixedToTop;
1530 return ScrollLockMode.FixedToItem;
1535 return ScrollLockMode.FixedToItem;
1539 internal struct ListViewSelection
1541 public long[] SelectedStatusIds { get; set; }
1542 public long? SelectionMarkStatusId { get; set; }
1543 public long? FocusedStatusId { get; set; }
1547 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1549 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1551 var listsDict = new Dictionary<string, ListViewSelection>();
1553 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1555 var listView = (DetailsListView)tabPage.Tag;
1556 var tab = _statuses.Tabs[tabPage.Text];
1558 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1565 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1567 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1569 if (listView.VirtualListSize == 0)
1571 return new ListViewSelection
1573 SelectedStatusIds = new long[0],
1574 SelectionMarkStatusId = null,
1575 FocusedStatusId = null,
1579 return new ListViewSelection
1581 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1582 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1583 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1587 private long[] GetSelectedStatusIds(DetailsListView listView, TabModel tab)
1589 var selectedIndices = listView.SelectedIndices;
1590 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1591 return tab.GetStatusIdAt(selectedIndices.Cast<int>());
1596 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1598 var index = listView.FocusedItem?.Index ?? -1;
1600 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1603 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1605 var index = listView.SelectionMark;
1607 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1611 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1613 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1615 if (listView.VirtualListSize == 0)
1618 switch (listScroll.ScrollLockMode)
1620 case ScrollLockMode.FixedToTop:
1621 listView.EnsureVisible(0);
1623 case ScrollLockMode.FixedToBottom:
1624 listView.EnsureVisible(listView.VirtualListSize - 1);
1626 case ScrollLockMode.FixedToItem:
1627 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1630 var topItem = listView.Items[topIndex];
1633 listView.TopItem = topItem;
1635 catch (NullReferenceException)
1637 listView.EnsureVisible(listView.VirtualListSize - 1);
1638 listView.EnsureVisible(topIndex);
1642 case ScrollLockMode.None:
1649 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1651 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1653 // status_id から ListView 上のインデックスに変換
1654 int[] selectedIndices = null;
1655 if (listSelection.SelectedStatusIds != null)
1656 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1658 var focusedIndex = -1;
1659 if (listSelection.FocusedStatusId != null)
1660 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1662 var selectionMarkIndex = -1;
1663 if (listSelection.SelectionMarkStatusId != null)
1664 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1666 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1669 private bool BalloonRequired()
1671 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1672 ev.Eventtype = MyCommon.EVENTTYPE.None;
1674 return BalloonRequired(ev);
1677 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1679 if (type == MyCommon.EVENTTYPE.None)
1682 if (!SettingManager.Common.EventNotifyEnabled)
1685 return SettingManager.Common.EventNotifyFlag.HasFlag(type);
1688 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1693 return SettingManager.Common.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1696 private bool BalloonRequired(Twitter.FormattedEvent ev)
1701 if (NativeMethods.IsScreenSaverRunning())
1705 if (!this.NewPostPopMenuItem.Checked)
1707 // 「新着通知が無効でもイベントを通知する」にも該当しない
1708 if (!SettingManager.Common.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1712 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1713 if (SettingManager.Common.LimitBalloon)
1715 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1719 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1722 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1724 if (SettingManager.Common.ReadOwnPost)
1726 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1731 if (BalloonRequired())
1733 if (notifyPosts != null && notifyPosts.Length > 0)
1735 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1736 if (SettingManager.Common.IsUseNotifyGrowl)
1738 StringBuilder sb = new StringBuilder();
1742 foreach (PostClass post in notifyPosts)
1744 if (!(notifyPosts.Length > 3))
1750 if (post.IsReply && !post.IsExcludeReply) reply = true;
1751 if (post.IsDm) dm = true;
1752 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1753 switch (SettingManager.Common.NameBalloon)
1755 case MyCommon.NameBalloonEnum.UserID:
1756 sb.Append(post.ScreenName).Append(" : ");
1758 case MyCommon.NameBalloonEnum.NickName:
1759 sb.Append(post.Nickname).Append(" : ");
1762 sb.Append(post.TextFromApi);
1763 if (notifyPosts.Length > 3)
1765 if (notifyPosts.Last() != post) continue;
1768 StringBuilder title = new StringBuilder();
1769 GrowlHelper.NotifyType nt;
1770 if (SettingManager.Common.DispUsername)
1772 title.Append(tw.Username);
1773 title.Append(" - ");
1781 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1782 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1783 title.Append(Application.ProductName);
1784 title.Append(" [DM] ");
1785 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1786 nt = GrowlHelper.NotifyType.DirectMessage;
1790 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1791 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1792 title.Append(Application.ProductName);
1793 title.Append(" [Reply!] ");
1794 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1795 nt = GrowlHelper.NotifyType.Reply;
1799 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1800 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1801 title.Append(Application.ProductName);
1803 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1804 nt = GrowlHelper.NotifyType.Notify;
1806 string bText = sb.ToString();
1807 if (string.IsNullOrEmpty(bText)) return;
1809 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1810 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1815 StringBuilder sb = new StringBuilder();
1818 foreach (PostClass post in notifyPosts)
1820 if (post.IsReply && !post.IsExcludeReply) reply = true;
1821 if (post.IsDm) dm = true;
1822 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1823 switch (SettingManager.Common.NameBalloon)
1825 case MyCommon.NameBalloonEnum.UserID:
1826 sb.Append(post.ScreenName).Append(" : ");
1828 case MyCommon.NameBalloonEnum.NickName:
1829 sb.Append(post.Nickname).Append(" : ");
1832 sb.Append(post.TextFromApi);
1835 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1836 StringBuilder title = new StringBuilder();
1838 if (SettingManager.Common.DispUsername)
1840 title.Append(tw.Username);
1841 title.Append(" - ");
1849 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1850 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1851 ntIcon = ToolTipIcon.Warning;
1852 title.Append(Application.ProductName);
1853 title.Append(" [DM] ");
1854 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1858 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1859 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1860 ntIcon = ToolTipIcon.Warning;
1861 title.Append(Application.ProductName);
1862 title.Append(" [Reply!] ");
1863 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1867 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1868 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1869 ntIcon = ToolTipIcon.Info;
1870 title.Append(Application.ProductName);
1872 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1874 string bText = sb.ToString();
1875 if (string.IsNullOrEmpty(bText)) return;
1876 //NotifyIcon1.BalloonTipText = sb.ToString();
1877 //NotifyIcon1.ShowBalloonTip(500);
1878 NotifyIcon1.BalloonTipTitle = title.ToString();
1879 NotifyIcon1.BalloonTipText = bText;
1880 NotifyIcon1.BalloonTipIcon = ntIcon;
1881 NotifyIcon1.ShowBalloonTip(500);
1887 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(soundFile))
1891 string dir = Application.StartupPath;
1892 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1894 dir = Path.Combine(dir, "Sounds");
1896 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1906 //mentions新着時に画面ブリンク
1907 if (!_initial && SettingManager.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1909 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1913 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1915 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1917 _curItemIndex = _curList.SelectedIndices[0];
1918 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1922 this._curPost = GetCurTabPost(_curItemIndex);
1924 catch (ArgumentException)
1929 this.PushSelectPostChain();
1931 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1933 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1939 private void ChangeCacheStyleRead(bool Read, int Index)
1941 var tabInfo = _statuses.Tabs[_curTab.Text];
1942 //Read:true=既読 false=未読
1943 //未読管理していなかったら既読として扱う
1944 if (!tabInfo.UnreadManage ||
1945 !SettingManager.Common.UnreadManage) Read = true;
1947 var listCache = this._listItemCache;
1948 if (listCache == null)
1951 // キャッシュに含まれていないアイテムは対象外
1952 if (!listCache.TryGetValue(Index, out var itm, out var post))
1955 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1958 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1965 Item.SubItems[5].Text = "";
1970 Item.SubItems[5].Text = "★";
1976 else if (Post.RetweetedId != null)
1978 else if (Post.IsOwl && (Post.IsDm || SettingManager.Common.OneWayLove))
1980 else if (Read || !SettingManager.Common.UseUnreadStyle)
1985 if (DList == null || Item.Index == -1)
1987 Item.ForeColor = cl;
1988 if (SettingManager.Common.UseUnreadStyle)
1994 if (SettingManager.Common.UseUnreadStyle)
1995 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1997 DList.ChangeItemForeColor(Item.Index, cl);
1998 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2002 private void ColorizeList()
2004 //Index:更新対象のListviewItem.Index。Colorを返す。
2005 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2008 _post = _anchorPost;
2012 if (_post == null) return;
2014 var listCache = this._listItemCache;
2015 if (listCache == null)
2018 var index = listCache.StartIndex;
2019 foreach (var cachedPost in listCache.Post)
2021 var backColor = this.JudgeColor(_post, cachedPost);
2022 this._curList.ChangeItemBackColor(index++, backColor);
2026 private void ColorizeList(ListViewItem Item, int Index)
2028 //Index:更新対象のListviewItem.Index。Colorを返す。
2029 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2032 _post = _anchorPost;
2036 PostClass tPost = GetCurTabPost(Index);
2038 if (_post == null) return;
2040 if (Item.Index == -1)
2041 Item.BackColor = JudgeColor(_post, tPost);
2043 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2046 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2049 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2052 else if (TargetPost.IsMe)
2055 else if (TargetPost.IsReply)
2058 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2060 cl = _clAtFromTarget;
2061 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2064 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2069 cl = _clListBackcolor;
2074 private async void PostButton_Click(object sender, EventArgs e)
2076 if (StatusText.Text.Trim().Length == 0)
2078 if (!ImageSelector.Enabled)
2080 await this.DoRefresh();
2085 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2087 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2089 MessageBoxButtons.YesNoCancel,
2090 MessageBoxIcon.Question);
2093 case DialogResult.Yes:
2094 StatusText.Text = "";
2095 await this.doReTweetOfficial(false);
2097 case DialogResult.Cancel:
2102 var inReplyToStatusId = this.inReplyTo?.Item1;
2103 var inReplyToScreenName = this.inReplyTo?.Item2;
2104 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2106 if (SettingManager.Common.Nicoms)
2108 StatusText.SelectionStart = StatusText.Text.Length;
2109 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2111 //if (SettingDialog.UrlConvertAuto)
2113 // StatusText.SelectionStart = StatusText.Text.Length;
2114 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2116 //else if (SettingDialog.Nicoms)
2118 // StatusText.SelectionStart = StatusText.Text.Length;
2119 // UrlConvert(UrlConverter.Nicoms);
2121 StatusText.SelectionStart = StatusText.Text.Length;
2122 CheckReplyTo(StatusText.Text);
2124 var statusText = this.FormatStatusText(this.StatusText.Text);
2126 if (this.GetRestStatusCount(statusText) < 0)
2128 // 文字数制限を超えているが強制的に投稿するか
2129 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2130 if (ret != DialogResult.OK)
2134 var status = new PostingStatus();
2135 status.status = statusText;
2137 status.inReplyToId = this.inReplyTo?.Item1;
2138 status.inReplyToName = this.inReplyTo?.Item2;
2139 if (ImageSelector.Visible)
2142 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2146 this.inReplyTo = null;
2147 StatusText.Text = "";
2148 _history.Add(new PostingStatus());
2149 _hisIdx = _history.Count - 1;
2150 if (!SettingManager.Common.FocusLockToStatusText)
2151 ((Control)ListTab.SelectedTab.Tag).Focus();
2152 urlUndoBuffer = null;
2153 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2156 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2158 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2159 await this.OpenUriInBrowserAsync(tmp);
2162 await this.PostMessageAsync(status);
2165 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2167 MyCommon._endingFlag = true;
2171 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2173 if (!SettingManager.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2175 //_endingFlag=false:フォームの×ボタン
2177 this.Visible = false;
2181 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2182 _ignoreConfigSave = true;
2183 MyCommon._endingFlag = true;
2184 TimerTimeline.Enabled = false;
2185 TimerRefreshIcon.Enabled = false;
2189 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2191 this.Visible = true;
2192 if (this.WindowState == FormWindowState.Minimized)
2194 this.WindowState = FormWindowState.Normal;
2197 this.BringToFront();
2200 private static int errorCount = 0;
2202 private static bool CheckAccountValid()
2204 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2210 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2219 private Task GetHomeTimelineAsync()
2221 return this.GetHomeTimelineAsync(loadMore: false);
2224 private async Task GetHomeTimelineAsync(bool loadMore)
2226 await this.workerSemaphore.WaitAsync();
2230 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
2231 await homeTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2233 this.RefreshTimeline();
2235 catch (WebApiException ex)
2237 this._myStatusError = true;
2238 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2242 this.workerSemaphore.Release();
2246 private Task GetReplyAsync()
2248 return this.GetReplyAsync(loadMore: false);
2251 private async Task GetReplyAsync(bool loadMore)
2253 await this.workerSemaphore.WaitAsync();
2257 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
2258 await replyTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2260 this.RefreshTimeline();
2262 catch (WebApiException ex)
2264 this._myStatusError = true;
2265 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2269 this.workerSemaphore.Release();
2273 private Task GetDirectMessagesAsync()
2275 return this.GetDirectMessagesAsync(loadMore: false);
2278 private async Task GetDirectMessagesAsync(bool loadMore)
2280 await this.workerSemaphore.WaitAsync();
2284 var dmTab = this._statuses.GetTabByType<DirectMessagesTabModel>();
2285 await dmTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2287 this.RefreshTimeline();
2289 catch (WebApiException ex)
2291 this._myStatusError = true;
2292 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2296 this.workerSemaphore.Release();
2300 private Task GetFavoritesAsync()
2302 return this.GetFavoritesAsync(loadMore: false);
2305 private async Task GetFavoritesAsync(bool loadMore)
2307 await this.workerSemaphore.WaitAsync();
2311 var favTab = this._statuses.GetTabByType<FavoritesTabModel>();
2312 await favTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2314 this.RefreshTimeline();
2316 catch (WebApiException ex)
2318 this._myStatusError = true;
2319 this.StatusLabel.Text = ex.Message;
2323 this.workerSemaphore.Release();
2327 private Task GetPublicSearchAllAsync()
2329 var tabs = this._statuses.GetTabsByType<PublicSearchTabModel>();
2331 return this.GetPublicSearchAsync(tabs, loadMore: false);
2334 private Task GetPublicSearchAsync(PublicSearchTabModel tab)
2336 return this.GetPublicSearchAsync(tab, loadMore: false);
2339 private Task GetPublicSearchAsync(PublicSearchTabModel tab, bool loadMore)
2341 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2344 private async Task GetPublicSearchAsync(IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2346 await this.workerSemaphore.WaitAsync();
2350 foreach (var tab in tabs)
2354 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2356 catch (WebApiException ex)
2358 this._myStatusError = true;
2359 this.StatusLabel.Text = $"Err:{ex.Message}(GetSearch)";
2363 this.RefreshTimeline();
2367 this.workerSemaphore.Release();
2371 private Task GetUserTimelineAllAsync()
2373 var tabs = this._statuses.GetTabsByType<UserTimelineTabModel>();
2375 return this.GetUserTimelineAsync(tabs, loadMore: false);
2378 private Task GetUserTimelineAsync(UserTimelineTabModel tab)
2380 return this.GetUserTimelineAsync(tab, loadMore: false);
2383 private Task GetUserTimelineAsync(UserTimelineTabModel tab, bool loadMore)
2385 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2388 private async Task GetUserTimelineAsync(IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2390 await this.workerSemaphore.WaitAsync();
2394 foreach (var tab in tabs)
2398 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2400 catch (WebApiException ex)
2402 this._myStatusError = true;
2403 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2407 this.RefreshTimeline();
2411 this.workerSemaphore.Release();
2415 private Task GetListTimelineAllAsync()
2417 var tabs = this._statuses.GetTabsByType<ListTimelineTabModel>();
2419 return this.GetListTimelineAsync(tabs, loadMore: false);
2422 private Task GetListTimelineAsync(ListTimelineTabModel tab)
2424 return this.GetListTimelineAsync(tab, loadMore: false);
2427 private Task GetListTimelineAsync(ListTimelineTabModel tab, bool loadMore)
2429 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2432 private async Task GetListTimelineAsync(IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2434 await this.workerSemaphore.WaitAsync();
2438 foreach (var tab in tabs)
2442 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2444 catch (WebApiException ex)
2446 this._myStatusError = true;
2447 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2451 this.RefreshTimeline();
2455 this.workerSemaphore.Release();
2459 private async Task GetRelatedTweetsAsync(RelatedPostsTabModel tab)
2461 await this.workerSemaphore.WaitAsync();
2465 await tab.RefreshAsync(this.tw, this._initial, this.workerProgress);
2467 this.RefreshTimeline();
2469 catch (WebApiException ex)
2471 this._myStatusError = true;
2472 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2476 this.workerSemaphore.Release();
2480 private async Task FavAddAsync(long statusId, TabModel tab)
2482 await this.workerSemaphore.WaitAsync();
2486 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2488 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2490 catch (WebApiException ex)
2492 this._myStatusError = true;
2493 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2497 this.workerSemaphore.Release();
2501 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2503 if (ct.IsCancellationRequested)
2506 if (!CheckAccountValid())
2507 throw new WebApiException("Auth error. Check your account");
2509 if (!tab.Posts.TryGetValue(statusId, out var post))
2515 await Task.Run(async () =>
2517 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2523 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2525 .ConfigureAwait(false);
2527 catch (TwitterApiException ex)
2528 when (ex.ErrorResponse.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
2530 // エラーコード 139 のみの場合は成功と見なす
2533 if (SettingManager.Common.RestrictFavCheck)
2535 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2536 .ConfigureAwait(false);
2538 if (status.Favorited != true)
2539 throw new WebApiException("NG(Restricted?)");
2542 this._favTimestamps.Add(DateTime.Now);
2545 if (this._statuses.ContainsKey(statusId))
2547 var postTl = this._statuses[statusId];
2548 postTl.IsFav = true;
2550 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2551 favTab.AddPostQueue(postTl);
2554 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2555 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2557 if (tb.Contains(statusId))
2558 tb.Posts[statusId].IsFav = true;
2561 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2563 catch (WebApiException)
2565 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2570 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2571 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2573 if (this._favTimestamps[i] < oneHour)
2574 this._favTimestamps.RemoveAt(i);
2577 this._statuses.DistributePosts();
2580 if (ct.IsCancellationRequested)
2583 this.RefreshTimeline();
2585 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2587 using (ControlTransaction.Update(this._curList))
2589 var idx = tab.IndexOf(statusId);
2591 this.ChangeCacheStyleRead(post.IsRead, idx);
2594 if (statusId == this._curPost.StatusId)
2595 await this.DispSelectedPost(true); // 選択アイテム再表示
2599 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2601 await this.workerSemaphore.WaitAsync();
2605 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2607 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2609 catch (WebApiException ex)
2611 this._myStatusError = true;
2612 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2616 this.workerSemaphore.Release();
2620 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2622 if (ct.IsCancellationRequested)
2625 if (!CheckAccountValid())
2626 throw new WebApiException("Auth error. Check your account");
2628 var successIds = new List<long>();
2630 await Task.Run(async () =>
2634 var failedCount = 0;
2635 foreach (var statusId in statusIds)
2639 var post = tab.Posts[statusId];
2641 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2648 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2650 .ConfigureAwait(false);
2652 catch (WebApiException)
2658 successIds.Add(statusId);
2659 post.IsFav = false; // リスト再描画必要
2661 if (this._statuses.ContainsKey(statusId))
2663 this._statuses[statusId].IsFav = false;
2666 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2667 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2669 if (tb.Contains(statusId))
2670 tb.Posts[statusId].IsFav = false;
2675 if (ct.IsCancellationRequested)
2678 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2679 foreach (var statusId in successIds)
2681 // ツイートが削除された訳ではないので IsDeleted はセットしない
2682 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2685 this.RefreshTimeline();
2687 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2689 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2695 using (ControlTransaction.Update(this._curList))
2697 foreach (var statusId in successIds)
2699 var idx = tab.IndexOf(statusId);
2703 var post = tab.Posts[statusId];
2704 this.ChangeCacheStyleRead(post.IsRead, idx);
2708 if (successIds.Contains(this._curPost.StatusId))
2709 await this.DispSelectedPost(true); // 選択アイテム再表示
2714 private async Task PostMessageAsync(PostingStatus status)
2716 await this.workerSemaphore.WaitAsync();
2720 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2722 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
2724 catch (WebApiException ex)
2726 this._myStatusError = true;
2727 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2731 this.workerSemaphore.Release();
2735 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
2737 if (ct.IsCancellationRequested)
2740 if (!CheckAccountValid())
2741 throw new WebApiException("Auth error. Check your account");
2743 p.Report("Posting...");
2749 await Task.Run(async () =>
2751 if (status.mediaItems == null || status.mediaItems.Length == 0)
2753 await this.tw.PostStatus(status.status, status.inReplyToId)
2754 .ConfigureAwait(false);
2758 var service = ImageSelector.GetService(status.imageService);
2759 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
2760 .ConfigureAwait(false);
2764 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2766 catch (WebApiException ex)
2768 // 処理は中断せずエラーの表示のみ行う
2769 errMsg = $"Err:{ex.Message}(PostMessage)";
2771 this._myStatusError = true;
2773 catch (UnauthorizedAccessException ex)
2775 // アップロード対象のファイルが開けなかった場合など
2776 errMsg = $"Err:{ex.Message}(PostMessage)";
2778 this._myStatusError = true;
2782 // 使い終わった MediaItem は破棄する
2783 if (status.mediaItems != null)
2785 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
2787 disposableItem.Dispose();
2792 if (ct.IsCancellationRequested)
2795 if (!string.IsNullOrEmpty(errMsg) &&
2796 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2797 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2799 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, status.status);
2801 var ret = MessageBox.Show(
2803 "Failed to update status",
2804 MessageBoxButtons.RetryCancel,
2805 MessageBoxIcon.Question);
2807 if (ret == DialogResult.Retry)
2809 await this.PostMessageAsync(status);
2813 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2814 if (SettingManager.Common.FocusLockToStatusText)
2815 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2820 this._postTimestamps.Add(DateTime.Now);
2822 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2823 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2825 if (this._postTimestamps[i] < oneHour)
2826 this._postTimestamps.RemoveAt(i);
2829 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2831 this.HashMgr.ClearHashtag();
2832 this.HashStripSplitButton.Text = "#[-]";
2833 this.HashTogglePullDownMenuItem.Checked = false;
2834 this.HashToggleMenuItem.Checked = false;
2837 this.SetMainWindowTitle();
2839 if (SettingManager.Common.PostAndGet)
2841 if (this.tw.UserStreamActive)
2842 this.RefreshTimeline();
2844 await this.GetHomeTimelineAsync();
2848 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2850 await this.workerSemaphore.WaitAsync();
2854 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2856 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2858 if (SettingManager.Common.PostAndGet && !this.tw.UserStreamActive)
2859 await this.GetHomeTimelineAsync();
2861 catch (WebApiException ex)
2863 this._myStatusError = true;
2864 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2868 this.workerSemaphore.Release();
2872 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2874 if (ct.IsCancellationRequested)
2877 if (!CheckAccountValid())
2878 throw new WebApiException("Auth error. Check your account");
2881 if (!SettingManager.Common.UnreadManage)
2884 read = this._initial && SettingManager.Common.Read;
2886 p.Report("Posting...");
2888 foreach (var statusId in statusIds)
2890 await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2893 if (ct.IsCancellationRequested)
2896 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2898 this._postTimestamps.Add(DateTime.Now);
2900 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2901 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2903 if (this._postTimestamps[i] < oneHour)
2904 this._postTimestamps.RemoveAt(i);
2908 private async Task RefreshFollowerIdsAsync()
2910 await this.workerSemaphore.WaitAsync();
2913 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2915 await this.tw.RefreshFollowerIds();
2917 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2919 this.RefreshTimeline();
2920 this.PurgeListViewItemCache();
2921 this._curList?.Refresh();
2923 catch (WebApiException ex)
2925 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2929 this.workerSemaphore.Release();
2933 private async Task RefreshNoRetweetIdsAsync()
2935 await this.workerSemaphore.WaitAsync();
2938 await this.tw.RefreshNoRetweetIds();
2940 this.StatusLabel.Text = "NoRetweetIds refreshed";
2942 catch (WebApiException ex)
2944 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2948 this.workerSemaphore.Release();
2952 private async Task RefreshBlockIdsAsync()
2954 await this.workerSemaphore.WaitAsync();
2957 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2959 await this.tw.RefreshBlockIds();
2961 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2963 catch (WebApiException ex)
2965 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2969 this.workerSemaphore.Release();
2973 private async Task RefreshTwitterConfigurationAsync()
2975 await this.workerSemaphore.WaitAsync();
2978 await this.tw.RefreshConfiguration();
2980 if (this.tw.Configuration.PhotoSizeLimit != 0)
2982 foreach (var service in this.ImageSelector.GetServices())
2984 service.UpdateTwitterConfiguration(this.tw.Configuration);
2988 this.PurgeListViewItemCache();
2990 this._curList?.Refresh();
2992 catch (WebApiException ex)
2994 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2998 this.workerSemaphore.Release();
3002 private async Task RefreshMuteUserIdsAsync()
3004 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3008 await tw.RefreshMuteUserIdsAsync();
3010 catch (WebApiException ex)
3012 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3016 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3019 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3021 if (e.Button == MouseButtons.Left)
3023 this.Visible = true;
3024 if (this.WindowState == FormWindowState.Minimized)
3026 this.WindowState = _formWindowState;
3029 this.BringToFront();
3033 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3035 switch (SettingManager.Common.ListDoubleClickAction)
3038 MakeReplyOrDirectStatus();
3041 await this.FavoriteChange(true);
3044 if (_curPost != null)
3045 await this.ShowUserStatus(_curPost.ScreenName, false);
3051 ShowRelatedStatusesMenuItem_Click(null, null);
3054 MoveToHomeToolStripMenuItem_Click(null, null);
3057 StatusOpenMenuItem_Click(null, null);
3065 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3067 await this.FavoriteChange(true);
3070 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3072 await this.FavoriteChange(false);
3076 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3078 await this.FavoritesRetweetOfficial();
3081 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3083 await this.FavoritesRetweetUnofficial();
3086 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3088 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3091 //trueでFavAdd,falseでFavRemove
3092 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3093 || !this.ExistCurrentPost) return;
3095 if (this._curList.SelectedIndices.Count > 1)
3100 // https://support.twitter.com/articles/76915#favoriting
3101 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3102 _DoFavRetweetFlags = false;
3107 if (multiFavoriteChangeDialogEnable)
3109 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3110 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3111 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3113 if (confirm == DialogResult.Cancel)
3121 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3122 if (selectedPost.IsFav)
3124 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3128 await this.FavAddAsync(selectedPost.StatusId, tab);
3132 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3133 .Select(x => this.GetCurTabPost(x))
3134 .Where(x => x.IsFav);
3136 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3137 if (statusIds.Length == 0)
3139 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3143 await this.FavRemoveAsync(statusIds, tab);
3147 private PostClass GetCurTabPost(int Index)
3149 var listCache = this._listItemCache;
3150 if (listCache != null)
3152 if (listCache.TryGetValue(Index, out var item, out var post))
3156 return _statuses.Tabs[_curTab.Text][Index];
3159 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3161 if (_curList.SelectedIndices.Count > 0)
3162 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3163 else if (_curList.SelectedIndices.Count == 0)
3164 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3167 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3169 if (_curList.SelectedIndices.Count > 0)
3170 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3173 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3175 if ((!_initialLayout) && this.Visible)
3177 if (this.WindowState == FormWindowState.Normal)
3179 _mySize = this.ClientSize;
3180 _mySpDis = this.SplitContainer1.SplitterDistance;
3181 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3182 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3183 ModifySettingLocal = true;
3188 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3190 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3191 if (comparerMode == null)
3194 this.SetSortColumn(comparerMode.Value);
3198 /// 列インデックスからソートを行う ComparerMode を求める
3200 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3201 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3202 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3205 return ComparerMode.Id;
3207 switch (columnIndex)
3210 return ComparerMode.Nickname;
3212 return ComparerMode.Data;
3214 return ComparerMode.Id;
3216 return ComparerMode.Name;
3218 return ComparerMode.Source;
3220 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3226 /// 発言一覧の指定した位置の列でソートする
3228 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3229 private void SetSortColumnByDisplayIndex(int columnIndex)
3231 // 表示上の列の位置から ColumnHeader を求める
3232 var col = this._curList.Columns.Cast<ColumnHeader>()
3233 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3238 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3239 if (comparerMode == null)
3242 this.SetSortColumn(comparerMode.Value);
3246 /// 発言一覧の最後列の項目でソートする
3248 private void SetSortLastColumn()
3250 // 表示上の最後列にある ColumnHeader を求める
3251 var col = this._curList.Columns.Cast<ColumnHeader>()
3252 .OrderByDescending(x => x.DisplayIndex)
3255 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3256 if (comparerMode == null)
3259 this.SetSortColumn(comparerMode.Value);
3263 /// 発言一覧を指定された ComparerMode に基づいてソートする
3265 private void SetSortColumn(ComparerMode sortColumn)
3267 if (SettingManager.Common.SortOrderLock)
3270 this._statuses.ToggleSortOrder(sortColumn);
3271 this.InitColumnText();
3273 var list = this._curList;
3276 list.Columns[0].Text = this.ColumnText[0];
3277 list.Columns[1].Text = this.ColumnText[2];
3281 for (var i = 0; i <= 7; i++)
3283 list.Columns[i].Text = this.ColumnText[i];
3287 this.PurgeListViewItemCache();
3289 var tab = this._statuses.Tabs[this._curTab.Text];
3290 if (tab.AllCount > 0 && this._curPost != null)
3292 var idx = tab.IndexOf(this._curPost.StatusId);
3295 this.SelectListItem(list, idx);
3296 list.EnsureVisible(idx);
3301 this.ModifySettingCommon = true;
3304 private void TweenMain_LocationChanged(object sender, EventArgs e)
3306 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3308 _myLoc = this.DesktopLocation;
3309 ModifySettingLocal = true;
3313 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3315 if (ListTab.SelectedTab == null) return;
3316 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3317 if (!this.ExistCurrentPost)
3319 ReplyStripMenuItem.Enabled = false;
3320 ReplyAllStripMenuItem.Enabled = false;
3321 DMStripMenuItem.Enabled = false;
3322 ShowProfileMenuItem.Enabled = false;
3323 ShowUserTimelineContextMenuItem.Enabled = false;
3324 ListManageUserContextToolStripMenuItem2.Enabled = false;
3325 MoveToFavToolStripMenuItem.Enabled = false;
3326 TabMenuItem.Enabled = false;
3327 IDRuleMenuItem.Enabled = false;
3328 SourceRuleMenuItem.Enabled = false;
3329 ReadedStripMenuItem.Enabled = false;
3330 UnreadStripMenuItem.Enabled = false;
3334 ShowProfileMenuItem.Enabled = true;
3335 ListManageUserContextToolStripMenuItem2.Enabled = true;
3336 ReplyStripMenuItem.Enabled = true;
3337 ReplyAllStripMenuItem.Enabled = true;
3338 DMStripMenuItem.Enabled = true;
3339 ShowUserTimelineContextMenuItem.Enabled = true;
3340 MoveToFavToolStripMenuItem.Enabled = true;
3341 TabMenuItem.Enabled = true;
3342 IDRuleMenuItem.Enabled = true;
3343 SourceRuleMenuItem.Enabled = true;
3344 ReadedStripMenuItem.Enabled = true;
3345 UnreadStripMenuItem.Enabled = true;
3347 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3349 FavAddToolStripMenuItem.Enabled = false;
3350 FavRemoveToolStripMenuItem.Enabled = false;
3351 StatusOpenMenuItem.Enabled = false;
3352 FavorareMenuItem.Enabled = false;
3353 ShowRelatedStatusesMenuItem.Enabled = false;
3355 ReTweetStripMenuItem.Enabled = false;
3356 ReTweetUnofficialStripMenuItem.Enabled = false;
3357 QuoteStripMenuItem.Enabled = false;
3358 FavoriteRetweetContextMenu.Enabled = false;
3359 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3363 FavAddToolStripMenuItem.Enabled = true;
3364 FavRemoveToolStripMenuItem.Enabled = true;
3365 StatusOpenMenuItem.Enabled = true;
3366 FavorareMenuItem.Enabled = true;
3367 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3369 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
3371 ReTweetStripMenuItem.Enabled = false;
3372 ReTweetUnofficialStripMenuItem.Enabled = false;
3373 QuoteStripMenuItem.Enabled = false;
3374 FavoriteRetweetContextMenu.Enabled = false;
3375 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3379 ReTweetStripMenuItem.Enabled = true;
3380 ReTweetUnofficialStripMenuItem.Enabled = true;
3381 QuoteStripMenuItem.Enabled = true;
3382 FavoriteRetweetContextMenu.Enabled = true;
3383 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3386 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3388 // RefreshMoreStripMenuItem.Enabled = true;
3392 // RefreshMoreStripMenuItem.Enabled = false;
3394 if (!this.ExistCurrentPost
3395 || _curPost.InReplyToStatusId == null)
3397 RepliedStatusOpenMenuItem.Enabled = false;
3401 RepliedStatusOpenMenuItem.Enabled = true;
3403 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3405 MoveToRTHomeMenuItem.Enabled = false;
3409 MoveToRTHomeMenuItem.Enabled = true;
3412 if (this.ExistCurrentPost)
3414 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3415 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3416 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3418 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3422 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3424 MakeReplyOrDirectStatus(false, true);
3427 private void DMStripMenuItem_Click(object sender, EventArgs e)
3429 MakeReplyOrDirectStatus(false, false);
3432 private async Task doStatusDelete()
3434 if (this._curTab == null || this._curList == null)
3437 if (this._curList.SelectedIndices.Count == 0)
3440 var posts = this._curList.SelectedIndices.Cast<int>()
3441 .Select(x => this.GetCurTabPost(x))
3444 // 選択されたツイートの中に削除可能なものが一つでもあるか
3445 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3448 var ret = MessageBox.Show(this,
3449 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3450 Properties.Resources.DeleteStripMenuItem_ClickText2,
3451 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3453 if (ret != DialogResult.OK)
3456 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3458 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3460 Exception lastException = null;
3461 foreach (var post in posts)
3463 if (!post.CanDeleteBy(this.tw.UserId))
3470 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3475 if (post.RetweetedByUserId == this.tw.UserId)
3477 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3479 await this.twitterApi.StatusesDestroy(post.StatusId)
3484 if (post.UserId == this.tw.UserId)
3486 if (post.RetweetedId != null)
3487 // 他人に RT された自分のツイート
3488 // => RT 元の自分のツイートを削除
3489 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3494 await this.twitterApi.StatusesDestroy(post.StatusId)
3500 catch (WebApiException ex)
3506 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3509 if (lastException == null)
3510 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3512 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3514 this.PurgeListViewItemCache();
3515 this._curPost = null;
3516 this._curItemIndex = -1;
3518 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3520 var listView = (DetailsListView)tabPage.Tag;
3521 var tab = this._statuses.Tabs[tabPage.Text];
3523 using (ControlTransaction.Update(listView))
3525 listView.VirtualListSize = tab.AllCount;
3527 if (tabPage == this._curTab)
3529 listView.SelectedIndices.Clear();
3531 if (tab.AllCount != 0)
3534 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3535 selectedIndex = focusedIndex;
3537 selectedIndex = tab.AllCount - 1;
3539 listView.SelectedIndices.Add(selectedIndex);
3540 listView.EnsureVisible(selectedIndex);
3541 listView.FocusedItem = listView.Items[selectedIndex];
3546 if (SettingManager.Common.TabIconDisp && tab.UnreadCount == 0)
3548 if (tabPage.ImageIndex == 0)
3549 tabPage.ImageIndex = -1; // タブアイコン
3553 if (!SettingManager.Common.TabIconDisp)
3554 this.ListTab.Refresh();
3558 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3560 await this.doStatusDelete();
3563 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3565 using (ControlTransaction.Update(this._curList))
3567 foreach (int idx in _curList.SelectedIndices)
3569 var post = this._statuses.Tabs[this._curTab.Text][idx];
3570 this._statuses.SetReadAllTab(post.StatusId, read: true);
3571 ChangeCacheStyleRead(true, idx);
3575 foreach (TabPage tb in ListTab.TabPages)
3577 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3579 if (SettingManager.Common.TabIconDisp)
3581 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3585 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3588 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3590 using (ControlTransaction.Update(this._curList))
3592 foreach (int idx in _curList.SelectedIndices)
3594 var post = this._statuses.Tabs[this._curTab.Text][idx];
3595 this._statuses.SetReadAllTab(post.StatusId, read: false);
3596 ChangeCacheStyleRead(false, idx);
3600 foreach (TabPage tb in ListTab.TabPages)
3602 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3604 if (SettingManager.Common.TabIconDisp)
3606 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3610 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3613 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3615 await this.DoRefresh();
3618 private async Task DoRefresh()
3620 if (_curTab != null)
3622 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3627 case MentionsTabModel replyTab:
3628 await this.GetReplyAsync();
3630 case DirectMessagesTabModel dmTab:
3631 await this.GetDirectMessagesAsync();
3633 case FavoritesTabModel favTab:
3634 await this.GetFavoritesAsync();
3636 case PublicSearchTabModel searchTab:
3637 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3638 await this.GetPublicSearchAsync(searchTab);
3640 case UserTimelineTabModel userTab:
3641 await this.GetUserTimelineAsync(userTab);
3643 case ListTimelineTabModel listTab:
3644 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3645 await this.GetListTimelineAsync(listTab);
3648 await this.GetHomeTimelineAsync();
3654 await this.GetHomeTimelineAsync();
3658 private async Task DoRefreshMore()
3661 if (_curTab != null)
3663 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3668 case MentionsTabModel replyTab:
3669 await this.GetReplyAsync(loadMore: true);
3671 case DirectMessagesTabModel dmTab:
3672 await this.GetDirectMessagesAsync(loadMore: true);
3674 case FavoritesTabModel favTab:
3675 await this.GetFavoritesAsync(loadMore: true);
3677 case PublicSearchTabModel searchTab:
3678 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3679 await this.GetPublicSearchAsync(searchTab, loadMore: true);
3681 case UserTimelineTabModel userTab:
3682 await this.GetUserTimelineAsync(userTab, loadMore: true);
3684 case ListTimelineTabModel listTab:
3685 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3686 await this.GetListTimelineAsync(listTab, loadMore: true);
3689 await this.GetHomeTimelineAsync(loadMore: true);
3695 await this.GetHomeTimelineAsync(loadMore: true);
3699 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3701 DialogResult result = DialogResult.Abort;
3703 using (var settingDialog = new AppendSettingDialog())
3705 settingDialog.Icon = this.MainIcon;
3706 settingDialog.Owner = this;
3707 settingDialog.ShowInTaskbar = showTaskbarIcon;
3708 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3710 settingDialog.tw = this.tw;
3711 settingDialog.twitterApi = this.twitterApi;
3713 settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
3717 result = settingDialog.ShowDialog(this);
3721 return DialogResult.Abort;
3724 if (result == DialogResult.OK)
3728 settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
3736 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3739 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3741 var oldIconSz = SettingManager.Common.IconSize;
3743 if (ShowSettingDialog() == DialogResult.OK)
3747 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
3748 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
3749 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
3750 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
3751 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
3752 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
3753 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
3755 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
3756 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
3757 Networking.SetWebProxy(SettingManager.Local.ProxyType,
3758 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
3759 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
3760 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
3762 ImageSelector.Reset(tw, this.tw.Configuration);
3766 if (SettingManager.Common.TabIconDisp)
3768 ListTab.DrawItem -= ListTab_DrawItem;
3769 ListTab.DrawMode = TabDrawMode.Normal;
3770 ListTab.ImageList = this.TabImage;
3774 ListTab.DrawItem -= ListTab_DrawItem;
3775 ListTab.DrawItem += ListTab_DrawItem;
3776 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3777 ListTab.ImageList = null;
3780 catch (Exception ex)
3782 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3783 ex.Data["IsTerminatePermission"] = false;
3789 if (!SettingManager.Common.UnreadManage)
3791 ReadedStripMenuItem.Enabled = false;
3792 UnreadStripMenuItem.Enabled = false;
3793 if (SettingManager.Common.TabIconDisp)
3795 foreach (TabPage myTab in ListTab.TabPages)
3797 myTab.ImageIndex = -1;
3803 ReadedStripMenuItem.Enabled = true;
3804 UnreadStripMenuItem.Enabled = true;
3807 catch (Exception ex)
3809 ex.Data["Instance"] = "ListTab(UnreadManage)";
3810 ex.Data["IsTerminatePermission"] = false;
3817 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
3819 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3820 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
3821 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
3823 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
3824 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
3825 _fntUnread = SettingManager.Local.FontUnread;
3826 _clUnread = SettingManager.Local.ColorUnread;
3827 _fntReaded = SettingManager.Local.FontRead;
3828 _clReaded = SettingManager.Local.ColorRead;
3829 _clFav = SettingManager.Local.ColorFav;
3830 _clOWL = SettingManager.Local.ColorOWL;
3831 _clRetweet = SettingManager.Local.ColorRetweet;
3832 _fntDetail = SettingManager.Local.FontDetail;
3833 _clDetail = SettingManager.Local.ColorDetail;
3834 _clDetailLink = SettingManager.Local.ColorDetailLink;
3835 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
3836 _clSelf = SettingManager.Local.ColorSelf;
3837 _clAtSelf = SettingManager.Local.ColorAtSelf;
3838 _clTarget = SettingManager.Local.ColorTarget;
3839 _clAtTarget = SettingManager.Local.ColorAtTarget;
3840 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
3841 _clAtTo = SettingManager.Local.ColorAtTo;
3842 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
3843 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
3844 _clInputFont = SettingManager.Local.ColorInputFont;
3845 _fntInputFont = SettingManager.Local.FontInputFont;
3846 _brsBackColorMine.Dispose();
3847 _brsBackColorAt.Dispose();
3848 _brsBackColorYou.Dispose();
3849 _brsBackColorAtYou.Dispose();
3850 _brsBackColorAtFromTarget.Dispose();
3851 _brsBackColorAtTo.Dispose();
3852 _brsBackColorNone.Dispose();
3853 _brsBackColorMine = new SolidBrush(_clSelf);
3854 _brsBackColorAt = new SolidBrush(_clAtSelf);
3855 _brsBackColorYou = new SolidBrush(_clTarget);
3856 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3857 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3858 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3859 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3863 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3864 StatusText.Font = _fntInputFont;
3865 StatusText.ForeColor = _clInputFont;
3867 catch (Exception ex)
3869 MessageBox.Show(ex.Message);
3874 InitDetailHtmlFormat();
3876 catch (Exception ex)
3878 ex.Data["Instance"] = "Font";
3879 ex.Data["IsTerminatePermission"] = false;
3885 foreach (TabPage tb in ListTab.TabPages)
3887 if (SettingManager.Common.TabIconDisp)
3889 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3896 catch (Exception ex)
3898 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3899 ex.Data["IsTerminatePermission"] = false;
3905 var oldIconCol = _iconCol;
3907 if (SettingManager.Common.IconSize != oldIconSz)
3908 ApplyListViewIconSize(SettingManager.Common.IconSize);
3910 foreach (TabPage tp in ListTab.TabPages)
3912 DetailsListView lst = (DetailsListView)tp.Tag;
3914 using (ControlTransaction.Update(lst))
3916 lst.GridLines = SettingManager.Common.ShowGrid;
3917 lst.Font = _fntReaded;
3918 lst.BackColor = _clListBackcolor;
3920 if (_iconCol != oldIconCol)
3925 catch (Exception ex)
3927 ex.Data["Instance"] = "ListView(IconSize)";
3928 ex.Data["IsTerminatePermission"] = false;
3932 SetMainWindowTitle();
3933 SetNotifyIconText();
3935 this.PurgeListViewItemCache();
3936 _curList?.Refresh();
3939 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3940 if (SettingManager.Common.HotkeyEnabled)
3942 ///グローバルホットキーの登録。設定で変更可能にするかも
3943 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
3944 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
3945 modKey |= HookGlobalHotkey.ModKeys.Alt;
3946 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
3947 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3948 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
3949 modKey |= HookGlobalHotkey.ModKeys.Shift;
3950 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
3951 modKey |= HookGlobalHotkey.ModKeys.Win;
3953 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
3956 if (SettingManager.Common.IsUseNotifyGrowl) gh.RegisterGrowl();
3959 StatusText_TextChanged(null, null);
3968 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3969 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3972 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3974 this.TopMost = SettingManager.Common.AlwaysTop;
3975 SaveConfigsAll(false);
3977 if (tw.Username != oldUser.Username)
3978 await this.doGetFollowersMenu();
3984 private void SetTabAlignment()
3986 var newAlignment = SettingManager.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3987 if (ListTab.Alignment == newAlignment) return;
3989 // 各タブのリスト上の選択位置などを退避
3990 var listSelections = this.SaveListViewSelection();
3992 ListTab.Alignment = newAlignment;
3994 foreach (TabPage tab in ListTab.TabPages)
3996 DetailsListView lst = (DetailsListView)tab.Tag;
3997 TabModel tabInfo = _statuses.Tabs[tab.Text];
3998 using (ControlTransaction.Update(lst))
4001 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4006 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4012 case MyCommon.IconSizes.IconNone:
4015 case MyCommon.IconSizes.Icon16:
4018 case MyCommon.IconSizes.Icon24:
4021 case MyCommon.IconSizes.Icon48:
4024 case MyCommon.IconSizes.Icon48_2:
4032 // ディスプレイの DPI 設定を考慮したサイズを設定する
4033 _listViewImageList.ImageSize = new Size(
4035 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4039 _listViewImageList.ImageSize = new Size(1, 1);
4043 private void ResetColumns(DetailsListView list)
4045 using (ControlTransaction.Update(list))
4046 using (ControlTransaction.Layout(list, false))
4049 list.ColumnClick -= MyList_ColumnClick;
4050 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4051 list.ColumnReordered -= MyList_ColumnReordered;
4052 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4054 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4055 list.Columns.Clear();
4056 cols.ForEach(col => col.Dispose());
4059 InitColumns(list, true);
4061 list.ColumnClick += MyList_ColumnClick;
4062 list.DrawColumnHeader += MyList_DrawColumnHeader;
4063 list.ColumnReordered += MyList_ColumnReordered;
4064 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4068 public void AddNewTabForSearch(string searchWord)
4070 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4071 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4073 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4075 foreach (TabPage tp in ListTab.TabPages)
4077 if (tb.TabName == tp.Text)
4079 ListTab.SelectedTab = tp;
4086 string tabName = searchWord;
4087 for (int i = 0; i <= 100; i++)
4089 if (_statuses.ContainsTab(tabName))
4095 var tab = new PublicSearchTabModel(tabName);
4096 _statuses.AddTab(tab);
4097 AddNewTab(tab, startup: false);
4099 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4101 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4102 cmb.Items.Add(searchWord);
4103 cmb.Text = searchWord;
4106 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4109 private void ShowUserTimeline()
4111 if (!this.ExistCurrentPost) return;
4112 AddNewTabForUserTimeline(_curPost.ScreenName);
4115 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4117 if (e.KeyCode == Keys.Escape)
4119 TabPage relTp = ListTab.SelectedTab;
4120 RemoveSpecifiedTab(relTp.Text, false);
4122 e.SuppressKeyPress = true;
4126 public void AddNewTabForUserTimeline(string user)
4128 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4129 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4131 if (tb.ScreenName == user)
4133 foreach (TabPage tp in ListTab.TabPages)
4135 if (tb.TabName == tp.Text)
4137 ListTab.SelectedTab = tp;
4144 string tabName = "user:" + user;
4145 while (_statuses.ContainsTab(tabName))
4150 var tab = new UserTimelineTabModel(tabName, user);
4151 this._statuses.AddTab(tab);
4152 this.AddNewTab(tab, startup: false);
4154 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4157 this.GetUserTimelineAsync(tab);
4160 public bool AddNewTab(TabModel tab, bool startup)
4163 foreach (TabPage tb in ListTab.TabPages)
4165 if (tb.Text == tab.TabName) return false;
4169 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4171 var _tabPage = new TabPage();
4172 var _listCustom = new DetailsListView();
4174 int cnt = ListTab.TabPages.Count;
4176 ///ToDo:Create and set controls follow tabtypes
4178 using (ControlTransaction.Update(_listCustom))
4179 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4180 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4181 using (ControlTransaction.Layout(this.SplitContainer1, false))
4182 using (ControlTransaction.Layout(this.ListTab, false))
4183 using (ControlTransaction.Layout(this))
4184 using (ControlTransaction.Layout(_tabPage, false))
4186 _tabPage.Controls.Add(_listCustom);
4189 var userTab = tab as UserTimelineTabModel;
4190 var listTab = tab as ListTimelineTabModel;
4191 var searchTab = tab as PublicSearchTabModel;
4193 if (userTab != null || listTab != null)
4195 var label = new Label();
4196 label.Dock = DockStyle.Top;
4197 label.Name = "labelUser";
4200 if (listTab != null)
4202 label.Text = listTab.ListInfo.ToString();
4204 else if (userTab != null)
4206 label.Text = userTab.ScreenName + "'s Timeline";
4208 label.TextAlign = ContentAlignment.MiddleLeft;
4209 using (ComboBox tmpComboBox = new ComboBox())
4211 label.Height = tmpComboBox.Height;
4213 _tabPage.Controls.Add(label);
4216 else if (searchTab != null)
4218 var pnl = new Panel();
4220 var lbl = new Label();
4221 var cmb = new ComboBox();
4222 var btn = new Button();
4223 var cmbLang = new ComboBox();
4225 using (ControlTransaction.Layout(pnl, false))
4227 pnl.Controls.Add(cmb);
4228 pnl.Controls.Add(cmbLang);
4229 pnl.Controls.Add(btn);
4230 pnl.Controls.Add(lbl);
4231 pnl.Name = "panelSearch";
4233 pnl.Dock = DockStyle.Top;
4234 pnl.Height = cmb.Height;
4235 pnl.Enter += SearchControls_Enter;
4236 pnl.Leave += SearchControls_Leave;
4239 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4240 cmb.Dock = DockStyle.Fill;
4241 cmb.Name = "comboSearch";
4242 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4243 cmb.ImeMode = ImeMode.NoControl;
4244 cmb.TabStop = false;
4246 cmb.AutoCompleteMode = AutoCompleteMode.None;
4247 cmb.KeyDown += SearchComboBox_KeyDown;
4250 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4251 cmbLang.Dock = DockStyle.Right;
4253 cmbLang.Name = "comboLang";
4254 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4255 cmbLang.TabStop = false;
4256 cmbLang.TabIndex = 2;
4257 cmbLang.Items.Add("");
4258 cmbLang.Items.Add("ja");
4259 cmbLang.Items.Add("en");
4260 cmbLang.Items.Add("ar");
4261 cmbLang.Items.Add("da");
4262 cmbLang.Items.Add("nl");
4263 cmbLang.Items.Add("fa");
4264 cmbLang.Items.Add("fi");
4265 cmbLang.Items.Add("fr");
4266 cmbLang.Items.Add("de");
4267 cmbLang.Items.Add("hu");
4268 cmbLang.Items.Add("is");
4269 cmbLang.Items.Add("it");
4270 cmbLang.Items.Add("no");
4271 cmbLang.Items.Add("pl");
4272 cmbLang.Items.Add("pt");
4273 cmbLang.Items.Add("ru");
4274 cmbLang.Items.Add("es");
4275 cmbLang.Items.Add("sv");
4276 cmbLang.Items.Add("th");
4278 lbl.Text = "Search(C-S-f)";
4279 lbl.Name = "label1";
4280 lbl.Dock = DockStyle.Left;
4282 lbl.Height = cmb.Height;
4283 lbl.TextAlign = ContentAlignment.MiddleLeft;
4286 btn.Text = "Search";
4287 btn.Name = "buttonSearch";
4288 btn.UseVisualStyleBackColor = true;
4289 btn.Dock = DockStyle.Right;
4290 btn.TabStop = false;
4292 btn.Click += SearchButton_Click;
4294 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4296 cmb.Items.Add(searchTab.SearchWords);
4297 cmb.Text = searchTab.SearchWords;
4300 cmbLang.Text = searchTab.SearchLang;
4302 _tabPage.Controls.Add(pnl);
4306 _tabPage.Tag = _listCustom;
4307 this.ListTab.Controls.Add(_tabPage);
4309 _tabPage.Location = new Point(4, 4);
4310 _tabPage.Name = "CTab" + cnt;
4311 _tabPage.Size = new Size(380, 260);
4312 _tabPage.TabIndex = 2 + cnt;
4313 _tabPage.Text = tab.TabName;
4314 _tabPage.UseVisualStyleBackColor = true;
4315 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4317 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4318 _listCustom.TabIndex = 1;
4319 _listCustom.AllowColumnReorder = true;
4320 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4321 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4322 _listCustom.Dock = DockStyle.Fill;
4323 _listCustom.FullRowSelect = true;
4324 _listCustom.HideSelection = false;
4325 _listCustom.Location = new Point(0, 0);
4326 _listCustom.Margin = new Padding(0);
4327 _listCustom.Name = "CList" + Environment.TickCount;
4328 _listCustom.ShowItemToolTips = true;
4329 _listCustom.Size = new Size(380, 260);
4330 _listCustom.UseCompatibleStateImageBehavior = false;
4331 _listCustom.View = View.Details;
4332 _listCustom.OwnerDraw = true;
4333 _listCustom.VirtualMode = true;
4334 _listCustom.Font = _fntReaded;
4335 _listCustom.BackColor = _clListBackcolor;
4337 _listCustom.GridLines = SettingManager.Common.ShowGrid;
4338 _listCustom.AllowDrop = true;
4340 _listCustom.SmallImageList = _listViewImageList;
4342 InitColumns(_listCustom, startup);
4344 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4345 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4346 _listCustom.ColumnClick += MyList_ColumnClick;
4347 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4348 _listCustom.DragDrop += TweenMain_DragDrop;
4349 _listCustom.DragEnter += TweenMain_DragEnter;
4350 _listCustom.DragOver += TweenMain_DragOver;
4351 _listCustom.DrawItem += MyList_DrawItem;
4352 _listCustom.MouseClick += MyList_MouseClick;
4353 _listCustom.ColumnReordered += MyList_ColumnReordered;
4354 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4355 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4356 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4357 _listCustom.DrawSubItem += MyList_DrawSubItem;
4358 _listCustom.HScrolled += MyList_HScrolled;
4364 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4366 var tabInfo = _statuses.GetTabByName(TabName);
4367 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4371 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4372 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4373 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4379 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4380 if (_tabPage == null) return false;
4382 SetListProperty(); //他のタブに列幅等を反映
4385 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4386 _tabPage.Tag = null;
4388 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4389 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4390 using (ControlTransaction.Layout(this.SplitContainer1, false))
4391 using (ControlTransaction.Layout(this.ListTab, false))
4392 using (ControlTransaction.Layout(this))
4393 using (ControlTransaction.Layout(_tabPage, false))
4395 if (this.ListTab.SelectedTab == _tabPage)
4397 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4398 this._beforeSelectedTab = null;
4400 this.ListTab.Controls.Remove(_tabPage);
4403 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4405 using (Control label = _tabPage.Controls["labelUser"])
4407 _tabPage.Controls.Remove(label);
4410 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4412 using (Control pnl = _tabPage.Controls["panelSearch"])
4414 pnl.Enter -= SearchControls_Enter;
4415 pnl.Leave -= SearchControls_Leave;
4416 _tabPage.Controls.Remove(pnl);
4418 foreach (Control ctrl in pnl.Controls)
4420 if (ctrl.Name == "buttonSearch")
4422 ctrl.Click -= SearchButton_Click;
4424 else if (ctrl.Name == "comboSearch")
4426 ctrl.KeyDown -= SearchComboBox_KeyDown;
4428 pnl.Controls.Remove(ctrl);
4434 _tabPage.Controls.Remove(_listCustom);
4436 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4437 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4438 _listCustom.ColumnClick -= MyList_ColumnClick;
4439 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4440 _listCustom.DragDrop -= TweenMain_DragDrop;
4441 _listCustom.DragEnter -= TweenMain_DragEnter;
4442 _listCustom.DragOver -= TweenMain_DragOver;
4443 _listCustom.DrawItem -= MyList_DrawItem;
4444 _listCustom.MouseClick -= MyList_MouseClick;
4445 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4446 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4447 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4448 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4449 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4450 _listCustom.HScrolled -= MyList_HScrolled;
4452 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4453 _listCustom.Columns.Clear();
4454 cols.ForEach(col => col.Dispose());
4457 _listCustom.ContextMenuStrip = null;
4458 _listCustom.ColumnHeaderContextMenuStrip = null;
4459 _listCustom.Font = null;
4461 _listCustom.SmallImageList = null;
4462 _listCustom.ListViewItemSorter = null;
4465 if (_curTab.Equals(_tabPage))
4472 this.PurgeListViewItemCache();
4476 _listCustom.Dispose();
4477 _statuses.RemoveTab(TabName);
4479 foreach (TabPage tp in ListTab.TabPages)
4481 DetailsListView lst = (DetailsListView)tp.Tag;
4482 var count = _statuses.Tabs[tp.Text].AllCount;
4483 lst.VirtualListSize = count;
4489 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4491 this.PurgeListViewItemCache();
4492 _beforeSelectedTab = e.TabPage;
4495 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4499 if (!SettingManager.Common.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4502 Rectangle dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4503 if (!dragEnableRectangle.Contains(e.Location))
4505 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4506 tn = ListTab.SelectedTab.Text;
4509 if (string.IsNullOrEmpty(tn)) return;
4511 foreach (TabPage tb in ListTab.TabPages)
4515 ListTab.DoDragDrop(tb, DragDropEffects.All);
4525 Point cpos = new Point(e.X, e.Y);
4526 for (int i = 0; i < ListTab.TabPages.Count; i++)
4528 Rectangle rect = ListTab.GetTabRect(i);
4529 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4530 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4532 _rclickTabName = ListTab.TabPages[i].Text;
4538 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4540 //_curList.Refresh();
4541 SetMainWindowTitle();
4542 SetStatusLabelUrl();
4543 SetApiStatusLabel();
4544 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4545 TabMenuControl(ListTab.SelectedTab.Text);
4546 this.PushSelectPostChain();
4547 await DispSelectedPost();
4550 private void SetListProperty()
4552 //削除などで見つからない場合は処理せず
4553 if (_curList == null) return;
4554 if (!_isColumnChanged) return;
4556 int[] dispOrder = new int[_curList.Columns.Count];
4557 for (int i = 0; i < _curList.Columns.Count; i++)
4559 for (int j = 0; j < _curList.Columns.Count; j++)
4561 if (_curList.Columns[j].DisplayIndex == i)
4570 foreach (TabPage tb in ListTab.TabPages)
4572 if (!tb.Equals(_curTab))
4574 if (tb.Tag != null && tb.Controls.Count > 0)
4576 DetailsListView lst = (DetailsListView)tb.Tag;
4577 for (int i = 0; i < lst.Columns.Count; i++)
4579 lst.Columns[dispOrder[i]].DisplayIndex = i;
4580 lst.Columns[i].Width = _curList.Columns[i].Width;
4586 _isColumnChanged = false;
4589 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4591 if (e.KeyChar == '@')
4593 if (!SettingManager.Common.UseAtIdSupplement) return;
4595 int cnt = AtIdSupl.ItemCount;
4596 ShowSuplDialog(StatusText, AtIdSupl);
4597 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
4600 else if (e.KeyChar == '#')
4602 if (!SettingManager.Common.UseHashSupplement) return;
4603 ShowSuplDialog(StatusText, HashSupl);
4608 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4610 ShowSuplDialog(owner, dialog, 0, "");
4613 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4615 ShowSuplDialog(owner, dialog, offset, "");
4618 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4620 dialog.StartsWith = startswith;
4627 dialog.ShowDialog();
4629 this.TopMost = SettingManager.Common.AlwaysTop;
4630 int selStart = owner.SelectionStart;
4633 if (dialog.DialogResult == DialogResult.OK)
4635 if (!string.IsNullOrEmpty(dialog.inputText))
4639 fHalf = owner.Text.Substring(0, selStart - offset);
4641 if (selStart < owner.Text.Length)
4643 eHalf = owner.Text.Substring(selStart);
4645 owner.Text = fHalf + dialog.inputText + eHalf;
4646 owner.SelectionStart = selStart + dialog.inputText.Length;
4653 fHalf = owner.Text.Substring(0, selStart);
4655 if (selStart < owner.Text.Length)
4657 eHalf = owner.Text.Substring(selStart);
4659 owner.Text = fHalf + eHalf;
4662 owner.SelectionStart = selStart;
4668 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4671 if (!e.Alt && !e.Control && !e.Shift)
4673 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4675 bool isSpace = false;
4676 foreach (char c in StatusText.Text)
4678 if (c == ' ' || c == ' ')
4691 StatusText.Text = "";
4692 JumpUnreadMenuItem_Click(null, null);
4696 this.StatusText_TextChanged(null, null);
4699 private void StatusText_TextChanged(object sender, EventArgs e)
4702 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
4703 lblLen.Text = pLen.ToString();
4706 StatusText.ForeColor = Color.Red;
4710 StatusText.ForeColor = _clInputFont;
4713 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4715 if (string.IsNullOrEmpty(StatusText.Text))
4717 this.inReplyTo = null;
4722 /// ツイート投稿前のフッター付与などの前処理を行います
4724 private string FormatStatusText(string statusText)
4726 statusText = statusText.Replace("\r\n", "\n");
4728 if (this.urlMultibyteSplit)
4731 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4734 if (SettingManager.Common.WideSpaceConvert)
4736 // 文中の全角スペースを半角スペース1個にする
4737 statusText = statusText.Replace(" ", " ");
4740 // DM の場合はこれ以降の処理を行わない
4741 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4745 if (SettingManager.Common.PostShiftEnter)
4747 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4751 if (this.StatusText.Multiline && !SettingManager.Common.PostCtrlEnter)
4752 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4754 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4757 if (statusText.Contains("RT @"))
4758 disableFooter = true;
4763 var hashtag = this.HashMgr.UseHash;
4764 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4767 header = HashMgr.UseHash + " ";
4769 footer = " " + HashMgr.UseHash;
4774 if (SettingManager.Local.UseRecommendStatus)
4777 footer += this.recommendedStatusFooter;
4779 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4781 // テキストボックスに入力されている文字列を使用する
4782 footer += " " + SettingManager.Local.StatusText.Trim();
4786 statusText = header + statusText + footer;
4788 if (this.preventSmsCommand)
4790 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4791 // 参照: https://support.twitter.com/articles/14020
4793 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4794 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4796 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4797 statusText = '\u200b' + statusText;
4805 /// 投稿欄に表示する入力可能な文字数を計算します
4807 private int GetRestStatusCount(string statusText)
4810 var remainCount = this.tw.GetTextLengthRemain(statusText);
4812 var uploadService = this.ImageSelector.SelectedService;
4813 if (this.ImageSelector.Visible && uploadService != null)
4815 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4816 remainCount -= uploadService.GetReservedTextLength(1);
4822 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4824 if (sender != this._curList)
4827 var listCache = this._listItemCache;
4828 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4830 // If the newly requested cache is a subset of the old cache,
4831 // no need to rebuild everything, so do nothing.
4835 // Now we need to rebuild the cache.
4836 this.CreateCache(e.StartIndex, e.EndIndex);
4839 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4841 var listCache = this._listItemCache;
4842 if (listCache?.TargetList == sender)
4844 if (listCache.TryGetValue(e.ItemIndex, out var item, out var cacheItemPost))
4851 // A cache miss, so create a new ListViewItem and pass it back.
4852 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4855 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4859 // 不正な要求に対する間に合わせの応答
4860 string[] sitem = {"", "", "", "", "", "", "", ""};
4861 e.Item = new ImageListViewItem(sitem);
4865 private void CreateCache(int startIndex, int endIndex)
4867 var tabInfo = this._statuses.Tabs[this._curTab.Text];
4869 if (tabInfo.AllCount == 0)
4872 // インデックスを 0...(tabInfo.AllCount - 1) の範囲内にする
4873 int FilterRange(int index)
4874 => Math.Max(Math.Min(index, tabInfo.AllCount - 1), 0);
4876 // キャッシュ要求(要求範囲±30を作成)
4877 startIndex = FilterRange(startIndex - 30);
4878 endIndex = FilterRange(endIndex + 30);
4880 var cacheLength = endIndex - startIndex + 1;
4882 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4883 var listItems = Enumerable.Range(0, cacheLength)
4884 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4887 var listCache = new ListViewItemCache
4889 TargetList = this._curList,
4890 StartIndex = startIndex,
4891 EndIndex = endIndex,
4893 ListItem = listItems,
4896 Interlocked.Exchange(ref this._listItemCache, listCache);
4900 /// DetailsListView のための ListViewItem のキャッシュを消去する
4902 private void PurgeListViewItemCache()
4904 Interlocked.Exchange(ref this._listItemCache, null);
4907 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
4909 StringBuilder mk = new StringBuilder();
4910 //if (Post.IsDeleted) mk.Append("×");
4911 //if (Post.IsMark) mk.Append("♪");
4912 //if (Post.IsProtect) mk.Append("Ю");
4913 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4914 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4915 ImageListViewItem itm;
4916 if (Post.RetweetedId == null)
4918 string[] sitem= {"",
4920 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4921 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4926 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4930 string[] sitem = {"",
4932 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4933 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4934 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4938 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4940 itm.StateIndex = Post.StateIndex;
4943 bool read = Post.IsRead;
4944 //未読管理していなかったら既読として扱う
4945 if (!_statuses.Tabs[Tab.Text].UnreadManage || !SettingManager.Common.UnreadManage) read = true;
4946 ChangeItemStyleRead(read, itm, Post, null);
4947 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
4952 /// 全てのタブの振り分けルールを反映し直します
4954 private void ApplyPostFilters()
4956 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4958 this.PurgeListViewItemCache();
4959 this._curPost = null;
4960 this._curItemIndex = -1;
4961 this._statuses.FilterAll();
4963 foreach (TabPage tabPage in this.ListTab.TabPages)
4965 var tab = this._statuses.Tabs[tabPage.Text];
4967 var listview = (DetailsListView)tabPage.Tag;
4968 using (ControlTransaction.Update(listview))
4970 listview.VirtualListSize = tab.AllCount;
4973 if (SettingManager.Common.TabIconDisp)
4975 if (tab.UnreadCount > 0)
4976 tabPage.ImageIndex = 0;
4978 tabPage.ImageIndex = -1;
4982 if (!SettingManager.Common.TabIconDisp)
4983 this.ListTab.Refresh();
4985 SetMainWindowTitle();
4986 SetStatusLabelUrl();
4990 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4992 e.DrawDefault = true;
4995 private void MyList_HScrolled(object sender, EventArgs e)
4997 DetailsListView listView = (DetailsListView)sender;
5001 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5003 if (e.State == 0) return;
5004 e.DrawDefault = false;
5006 SolidBrush brs2 = null;
5007 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5009 if (e.Item.BackColor == _clSelf)
5010 brs2 = _brsBackColorMine;
5011 else if (e.Item.BackColor == _clAtSelf)
5012 brs2 = _brsBackColorAt;
5013 else if (e.Item.BackColor == _clTarget)
5014 brs2 = _brsBackColorYou;
5015 else if (e.Item.BackColor == _clAtTarget)
5016 brs2 = _brsBackColorAtYou;
5017 else if (e.Item.BackColor == _clAtFromTarget)
5018 brs2 = _brsBackColorAtFromTarget;
5019 else if (e.Item.BackColor == _clAtTo)
5020 brs2 = _brsBackColorAtTo;
5022 brs2 = _brsBackColorNone;
5027 if (((Control)sender).Focused)
5028 brs2 = _brsHighLight;
5030 brs2 = _brsDeactiveSelection;
5032 e.Graphics.FillRectangle(brs2, e.Bounds);
5033 e.DrawFocusRectangle();
5034 this.DrawListViewItemIcon(e);
5037 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5039 if (e.ItemState == 0) return;
5041 if (e.ColumnIndex > 0)
5044 var post = (PostClass)e.Item.Tag;
5046 RectangleF rct = e.Bounds;
5047 rct.Width = e.Header.Width;
5048 int fontHeight = e.Item.Font.Height;
5051 rct.Y += fontHeight;
5052 rct.Height -= fontHeight;
5055 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out var heightDiff));
5057 //if (heightDiff > fontHeight * 0.7)
5059 // rct.Height += fontHeight;
5060 // drawLineCount += 1;
5063 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5064 if (!_iconCol && drawLineCount <= 1)
5066 //rct.Inflate(0, heightDiff / -2);
5067 //rct.Height += fontHeight / 2;
5069 else if (heightDiff < fontHeight * 0.7)
5071 //最終行が70%以上欠けていたら、最終行は表示しない
5072 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5073 rct.Height = (fontHeight * drawLineCount) - 1;
5080 //if (!_iconCol && drawLineCount > 1)
5082 // rct.Y += fontHeight * 0.2;
5083 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5088 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5089 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5094 Rectangle rctB = e.Bounds;
5095 rctB.Width = e.Header.Width;
5096 rctB.Height = fontHeight;
5098 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5100 TextRenderer.DrawText(e.Graphics,
5101 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5103 Rectangle.Round(rct),
5105 TextFormatFlags.WordBreak |
5106 TextFormatFlags.EndEllipsis |
5107 TextFormatFlags.GlyphOverhangPadding |
5108 TextFormatFlags.NoPrefix);
5109 TextRenderer.DrawText(e.Graphics,
5110 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 + "]",
5114 TextFormatFlags.SingleLine |
5115 TextFormatFlags.EndEllipsis |
5116 TextFormatFlags.GlyphOverhangPadding |
5117 TextFormatFlags.NoPrefix);
5123 if (e.ColumnIndex != 2)
5124 text = e.SubItem.Text;
5126 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5128 if (drawLineCount == 1)
5130 TextRenderer.DrawText(e.Graphics,
5133 Rectangle.Round(rct),
5135 TextFormatFlags.SingleLine |
5136 TextFormatFlags.EndEllipsis |
5137 TextFormatFlags.GlyphOverhangPadding |
5138 TextFormatFlags.NoPrefix |
5139 TextFormatFlags.VerticalCenter);
5143 TextRenderer.DrawText(e.Graphics,
5146 Rectangle.Round(rct),
5148 TextFormatFlags.WordBreak |
5149 TextFormatFlags.EndEllipsis |
5150 TextFormatFlags.GlyphOverhangPadding |
5151 TextFormatFlags.NoPrefix);
5154 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5159 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5161 if (_iconSz == 0) return;
5163 ImageListViewItem item = (ImageListViewItem)e.Item;
5165 //e.Bounds.Leftが常に0を指すから自前で計算
5166 Rectangle itemRect = item.Bounds;
5167 var col0 = e.Item.ListView.Columns[0];
5168 itemRect.Width = col0.Width;
5170 if (col0.DisplayIndex > 0)
5172 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5174 if (clm.DisplayIndex < col0.DisplayIndex)
5175 itemRect.X += clm.Width;
5179 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5180 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5181 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5184 var img = item.Image;
5187 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5188 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5190 if (iconRect.Width > 0)
5192 e.Graphics.FillRectangle(Brushes.White, iconRect);
5193 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5196 e.Graphics.DrawImage(img.Image, iconRect);
5198 catch (ArgumentException)
5200 item.RefreshImageAsync();
5206 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5207 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5209 item.GetImageAsync();
5212 if (item.StateIndex > -1)
5214 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5215 if (stateRect.Width > 0)
5217 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5218 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5219 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5224 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5226 base.ScaleControl(factor, specified);
5228 ScaleChildControl(this.TabImage, factor);
5230 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5231 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5233 foreach (var listview in listviews)
5235 ScaleChildControl(listview, factor);
5239 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5241 // ImageListViewItem item = (ImageListViewItem)e.Item;
5242 // if (item.StateImageIndex > -1)
5244 // ////e.Bounds.Leftが常に0を指すから自前で計算
5245 // //Rectangle itemRect = item.Bounds;
5246 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5248 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5250 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5252 // // itemRect.X += clm.Width;
5256 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5257 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5259 // if (rct.Width > 0)
5261 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5262 // //e.Graphics.FillRectangle(Brushes.White, rct);
5263 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5264 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5269 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5271 var tab = this._statuses.Tabs[this._curTab.Text];
5273 if (tab.AllCount == 0)
5275 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5279 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5284 case SEARCHTYPE.NextSearch: // 次を検索
5285 if (selectedIndex != -1)
5286 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5290 case SEARCHTYPE.PrevSearch: // 前を検索
5291 if (selectedIndex != -1)
5292 startIndex = Math.Max(selectedIndex - 1, 0);
5294 startIndex = tab.AllCount - 1;
5296 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5298 if (selectedIndex != -1)
5299 startIndex = selectedIndex;
5305 Func<string, bool> stringComparer;
5308 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5310 catch (ArgumentException)
5312 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5316 var reverse = searchType == SEARCHTYPE.PrevSearch;
5317 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5318 .DefaultIfEmpty(-1).First();
5320 if (foundIndex == -1)
5322 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5326 this.SelectListItem(this._curList, foundIndex);
5327 this._curList.EnsureVisible(foundIndex);
5330 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5333 this.ShowSearchDialog();
5336 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5338 var previousSearch = this.SearchDialog.ResultOptions;
5339 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5341 this.SearchDialog.Reset();
5342 this.ShowSearchDialog();
5348 previousSearch.Query,
5349 previousSearch.CaseSensitive,
5350 previousSearch.UseRegex,
5351 SEARCHTYPE.NextSearch);
5354 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5356 var previousSearch = this.SearchDialog.ResultOptions;
5357 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5359 this.SearchDialog.Reset();
5360 this.ShowSearchDialog();
5366 previousSearch.Query,
5367 previousSearch.CaseSensitive,
5368 previousSearch.UseRegex,
5369 SEARCHTYPE.PrevSearch);
5373 /// 検索ダイアログを表示し、検索を実行します
5375 private void ShowSearchDialog()
5377 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5379 this.TopMost = SettingManager.Common.AlwaysTop;
5382 this.TopMost = SettingManager.Common.AlwaysTop;
5384 var searchOptions = this.SearchDialog.ResultOptions;
5385 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5387 if (searchOptions.NewTab)
5389 var tabName = Properties.Resources.SearchResults_TabName;
5393 tabName = this._statuses.MakeTabName(tabName);
5395 catch (TabException ex)
5397 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5400 var resultTab = new LocalSearchTabModel(tabName);
5401 this.AddNewTab(resultTab, startup: false);
5402 this._statuses.AddTab(resultTab);
5404 var targetTab = this._statuses.Tabs[this._curTab.Text];
5406 Func<string, bool> stringComparer;
5409 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5411 catch (ArgumentException)
5413 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5417 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5418 if (foundIndices.Length == 0)
5420 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5424 var foundPosts = foundIndices.Select(x => targetTab[x]);
5425 foreach (var post in foundPosts)
5427 resultTab.AddPostQueue(post);
5430 this._statuses.DistributePosts();
5431 this.RefreshTimeline();
5433 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5434 .First(x => x.Text == tabName);
5436 this.ListTab.SelectedTab = tabPage;
5441 searchOptions.Query,
5442 searchOptions.CaseSensitive,
5443 searchOptions.UseRegex,
5444 SEARCHTYPE.DialogSearch);
5447 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5449 this.AddNewTabForSearch(searchOptions.Query);
5453 /// <summary>発言検索に使用するメソッドを生成します</summary>
5454 /// <exception cref="ArgumentException">
5455 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5457 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5461 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5462 var regex = new Regex(query, regexOption);
5464 return x => regex.IsMatch(x);
5468 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5470 return x => x.IndexOf(query, comparisonType) != -1;
5474 private void AboutMenuItem_Click(object sender, EventArgs e)
5476 using (TweenAboutBox about = new TweenAboutBox())
5478 about.ShowDialog(this);
5480 this.TopMost = SettingManager.Common.AlwaysTop;
5483 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5485 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5487 if (ImageSelector.Enabled)
5490 TabModel foundTab = null;
5493 DetailsListView lst = null;
5496 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5498 var tabPage = this.ListTab.TabPages[i];
5499 var tab = this._statuses.Tabs[tabPage.Text];
5500 var unreadIndex = tab.NextUnreadIndex;
5502 if (unreadIndex != -1)
5504 ListTab.SelectedIndex = i;
5506 foundIndex = unreadIndex;
5507 lst = (DetailsListView)tabPage.Tag;
5512 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5513 if (foundTab == null && bgnIdx > 0)
5515 for (int i = 0; i < bgnIdx; i++)
5517 var tabPage = this.ListTab.TabPages[i];
5518 var tab = this._statuses.Tabs[tabPage.Text];
5519 var unreadIndex = tab.NextUnreadIndex;
5521 if (unreadIndex != -1)
5523 ListTab.SelectedIndex = i;
5525 foundIndex = unreadIndex;
5526 lst = (DetailsListView)tabPage.Tag;
5532 if (foundTab == null)
5534 //全部調べたが未読見つからず→先頭タブの最新発言へ
5535 ListTab.SelectedIndex = 0;
5536 var tabPage = this.ListTab.TabPages[0];
5537 var tab = this._statuses.Tabs[tabPage.Text];
5539 if (tab.AllCount == 0)
5542 if (_statuses.SortOrder == SortOrder.Ascending)
5543 foundIndex = tab.AllCount - 1;
5547 lst = (DetailsListView)tabPage.Tag;
5550 SelectListItem(lst, foundIndex);
5552 if (_statuses.SortMode == ComparerMode.Id)
5554 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5555 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5561 lst.EnsureVisible(foundIndex);
5566 lst.EnsureVisible(foundIndex);
5572 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5574 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5576 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5577 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5581 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5583 if (_curList.SelectedIndices.Count > 0)
5585 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5586 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5590 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5592 await this.CheckNewVersion(false);
5595 private void RunTweenUp()
5597 ProcessStartInfo pinfo = new ProcessStartInfo();
5598 pinfo.UseShellExecute = true;
5599 pinfo.WorkingDirectory = MyCommon.settingPath;
5600 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5601 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5604 Process.Start(pinfo);
5608 MessageBox.Show("Failed to execute TweenUp3.exe.");
5612 public class VersionInfo
5614 public Version Version { get; set; }
5615 public Uri DownloadUri { get; set; }
5616 public string ReleaseNote { get; set; }
5620 /// OpenTween の最新バージョンの情報を取得します
5622 public async Task<VersionInfo> GetVersionInfoAsync()
5624 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5625 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5627 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5628 .ConfigureAwait(false);
5630 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5631 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5633 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5634 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5636 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5638 return new VersionInfo
5640 Version = Version.Parse(msgHeader[0]),
5641 DownloadUri = new Uri(msgHeader[1]),
5642 ReleaseNote = msgBody,
5646 private async Task CheckNewVersion(bool startup = false)
5648 if (ApplicationSettings.VersionInfoUrl == null)
5649 return; // 更新チェック無効化
5653 var versionInfo = await this.GetVersionInfoAsync();
5655 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5660 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5661 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5662 msgtext = MyCommon.ReplaceAppName(msgtext);
5664 MessageBox.Show(msgtext,
5665 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5666 MessageBoxButtons.OK, MessageBoxIcon.Information);
5671 using (var dialog = new UpdateDialog())
5673 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5674 MyCommon.GetReadableVersion(versionInfo.Version));
5675 dialog.DetailsText = versionInfo.ReleaseNote;
5677 if (dialog.ShowDialog(this) == DialogResult.Yes)
5679 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5685 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5688 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5689 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5690 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5695 private async Task Colorize()
5698 await this.DispSelectedPost();
5699 //件数関連の場合、タイトル即時書き換え
5700 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5701 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5702 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5703 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5705 SetMainWindowTitle();
5707 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5708 SetStatusLabelUrl();
5709 foreach (TabPage tb in ListTab.TabPages)
5711 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5713 if (SettingManager.Common.TabIconDisp)
5715 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5719 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
5722 public string createDetailHtml(string orgdata)
5724 if (SettingManager.Local.UseTwemoji)
5725 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5727 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5730 private Task DispSelectedPost()
5732 return this.DispSelectedPost(false);
5735 private PostClass displayPost = new PostClass();
5738 /// サムネイル表示に使用する CancellationToken の生成元
5740 private CancellationTokenSource thumbnailTokenSource = null;
5742 private async Task DispSelectedPost(bool forceupdate)
5744 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5747 var oldDisplayPost = this.displayPost;
5748 this.displayPost = this._curPost;
5750 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5753 var loadTasks = new List<Task>
5755 this.tweetDetailsView.ShowPostDetails(this._curPost),
5758 this.SplitContainer3.Panel2Collapsed = true;
5760 if (SettingManager.Common.PreviewEnable)
5762 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5763 oldTokenSource?.Cancel();
5765 var token = this.thumbnailTokenSource.Token;
5766 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5771 await Task.WhenAll(loadTasks);
5773 catch (OperationCanceledException) { }
5776 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5778 await this.OpenApplicationWebsite();
5781 private async Task OpenApplicationWebsite()
5783 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5786 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5788 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5791 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5793 if (ListTab.SelectedTab != null)
5795 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
5797 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
5798 if (pnl.Controls["comboSearch"].Focused ||
5799 pnl.Controls["comboLang"].Focused ||
5800 pnl.Controls["buttonSearch"].Focused) return;
5803 if (e.Control || e.Shift || e.Alt)
5804 this._anchorFlag = false;
5806 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
5809 e.SuppressKeyPress = true;
5812 if (asyncTask != null)
5817 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
5819 private void InitializeShortcuts()
5821 this.shortcutCommands = new[]
5823 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5824 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5825 .FocusedOn(FocusedControl.ListTab)
5826 .Do(() => SendKeys.Send("{DOWN}")),
5828 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5829 .FocusedOn(FocusedControl.ListTab)
5830 .Do(() => SendKeys.Send("{UP}")),
5832 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5833 .FocusedOn(FocusedControl.ListTab)
5834 .Do(() => SendKeys.Send("{PGDN}")),
5836 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5837 .FocusedOn(FocusedControl.ListTab)
5838 .Do(() => SendKeys.Send("{PGUP}")),
5840 ShortcutCommand.Create(Keys.F1)
5841 .Do(() => this.OpenApplicationWebsite()),
5843 ShortcutCommand.Create(Keys.F3)
5844 .Do(() => this.MenuItemSearchNext_Click(null, null)),
5846 ShortcutCommand.Create(Keys.F5)
5847 .Do(() => this.DoRefresh()),
5849 ShortcutCommand.Create(Keys.F6)
5850 .Do(() => this.GetReplyAsync()),
5852 ShortcutCommand.Create(Keys.F7)
5853 .Do(() => this.GetDirectMessagesAsync()),
5855 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5856 .NotFocusedOn(FocusedControl.StatusText)
5857 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5859 ShortcutCommand.Create(Keys.G)
5860 .NotFocusedOn(FocusedControl.StatusText)
5861 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5863 ShortcutCommand.Create(Keys.Right, Keys.N)
5864 .FocusedOn(FocusedControl.ListTab)
5865 .Do(() => this.GoRelPost(forward: true)),
5867 ShortcutCommand.Create(Keys.Left, Keys.P)
5868 .FocusedOn(FocusedControl.ListTab)
5869 .Do(() => this.GoRelPost(forward: false)),
5871 ShortcutCommand.Create(Keys.OemPeriod)
5872 .FocusedOn(FocusedControl.ListTab)
5873 .Do(() => this.GoAnchor()),
5875 ShortcutCommand.Create(Keys.I)
5876 .FocusedOn(FocusedControl.ListTab)
5877 .OnlyWhen(() => this.StatusText.Enabled)
5878 .Do(() => this.StatusText.Focus()),
5880 ShortcutCommand.Create(Keys.Enter)
5881 .FocusedOn(FocusedControl.ListTab)
5882 .Do(() => this.MakeReplyOrDirectStatus()),
5884 ShortcutCommand.Create(Keys.R)
5885 .FocusedOn(FocusedControl.ListTab)
5886 .Do(() => this.DoRefresh()),
5888 ShortcutCommand.Create(Keys.L)
5889 .FocusedOn(FocusedControl.ListTab)
5890 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5892 ShortcutCommand.Create(Keys.H)
5893 .FocusedOn(FocusedControl.ListTab)
5894 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5896 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5897 .FocusedOn(FocusedControl.ListTab)
5898 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5900 ShortcutCommand.Create(Keys.S)
5901 .FocusedOn(FocusedControl.ListTab)
5902 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5904 ShortcutCommand.Create(Keys.A)
5905 .FocusedOn(FocusedControl.ListTab)
5906 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5908 // ] in_reply_to参照元へ戻る
5909 ShortcutCommand.Create(Keys.Oem4)
5910 .FocusedOn(FocusedControl.ListTab)
5911 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5913 // [ in_reply_toへジャンプ
5914 ShortcutCommand.Create(Keys.Oem6)
5915 .FocusedOn(FocusedControl.ListTab)
5916 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5918 ShortcutCommand.Create(Keys.Escape)
5919 .FocusedOn(FocusedControl.ListTab)
5921 this._anchorFlag = false;
5922 if (ListTab.SelectedTab != null)
5924 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
5925 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5927 var relTp = ListTab.SelectedTab;
5928 RemoveSpecifiedTab(relTp.Text, false);
5934 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5935 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5936 .FocusedOn(FocusedControl.ListTab)
5937 .Do(() => this._anchorFlag = false, preventDefault: false),
5939 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5940 ShortcutCommand.Create(Keys.Up, Keys.Down)
5941 .FocusedOn(FocusedControl.PostBrowser)
5944 ShortcutCommand.Create(Keys.Control | Keys.R)
5945 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5947 ShortcutCommand.Create(Keys.Control | Keys.D)
5948 .Do(() => this.doStatusDelete()),
5950 ShortcutCommand.Create(Keys.Control | Keys.M)
5951 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5953 ShortcutCommand.Create(Keys.Control | Keys.S)
5954 .Do(() => this.FavoriteChange(FavAdd: true)),
5956 ShortcutCommand.Create(Keys.Control | Keys.I)
5957 .Do(() => this.doRepliedStatusOpen()),
5959 ShortcutCommand.Create(Keys.Control | Keys.Q)
5960 .Do(() => this.doQuoteOfficial()),
5962 ShortcutCommand.Create(Keys.Control | Keys.B)
5963 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5965 ShortcutCommand.Create(Keys.Control | Keys.T)
5966 .Do(() => this.HashManageMenuItem_Click(null, null)),
5968 ShortcutCommand.Create(Keys.Control | Keys.L)
5969 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5971 ShortcutCommand.Create(Keys.Control | Keys.Y)
5972 .NotFocusedOn(FocusedControl.PostBrowser)
5973 .Do(() => this.MultiLineMenuItem_Click(null, null)),
5975 ShortcutCommand.Create(Keys.Control | Keys.F)
5976 .Do(() => this.MenuItemSubSearch_Click(null, null)),
5978 ShortcutCommand.Create(Keys.Control | Keys.U)
5979 .Do(() => this.ShowUserTimeline()),
5981 ShortcutCommand.Create(Keys.Control | Keys.H)
5982 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5984 ShortcutCommand.Create(Keys.Control | Keys.G)
5985 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
5987 ShortcutCommand.Create(Keys.Control | Keys.O)
5988 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
5990 ShortcutCommand.Create(Keys.Control | Keys.E)
5991 .Do(() => this.OpenURLMenuItem_Click(null, null)),
5993 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5994 .FocusedOn(FocusedControl.ListTab)
5995 .Do(() => this._colorize = true, preventDefault: false),
5997 ShortcutCommand.Create(Keys.Control | Keys.N)
5998 .FocusedOn(FocusedControl.ListTab)
5999 .Do(() => this.GoNextTab(forward: true)),
6001 ShortcutCommand.Create(Keys.Control | Keys.P)
6002 .FocusedOn(FocusedControl.ListTab)
6003 .Do(() => this.GoNextTab(forward: false)),
6005 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6006 .FocusedOn(FocusedControl.ListTab)
6007 .Do(() => this.CopyStot()),
6009 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6010 ShortcutCommand.Create(Keys.Control | Keys.D1)
6011 .FocusedOn(FocusedControl.ListTab)
6012 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6013 .Do(() => this.ListTab.SelectedIndex = 0),
6015 ShortcutCommand.Create(Keys.Control | Keys.D2)
6016 .FocusedOn(FocusedControl.ListTab)
6017 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6018 .Do(() => this.ListTab.SelectedIndex = 1),
6020 ShortcutCommand.Create(Keys.Control | Keys.D3)
6021 .FocusedOn(FocusedControl.ListTab)
6022 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6023 .Do(() => this.ListTab.SelectedIndex = 2),
6025 ShortcutCommand.Create(Keys.Control | Keys.D4)
6026 .FocusedOn(FocusedControl.ListTab)
6027 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6028 .Do(() => this.ListTab.SelectedIndex = 3),
6030 ShortcutCommand.Create(Keys.Control | Keys.D5)
6031 .FocusedOn(FocusedControl.ListTab)
6032 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6033 .Do(() => this.ListTab.SelectedIndex = 4),
6035 ShortcutCommand.Create(Keys.Control | Keys.D6)
6036 .FocusedOn(FocusedControl.ListTab)
6037 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6038 .Do(() => this.ListTab.SelectedIndex = 5),
6040 ShortcutCommand.Create(Keys.Control | Keys.D7)
6041 .FocusedOn(FocusedControl.ListTab)
6042 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6043 .Do(() => this.ListTab.SelectedIndex = 6),
6045 ShortcutCommand.Create(Keys.Control | Keys.D8)
6046 .FocusedOn(FocusedControl.ListTab)
6047 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6048 .Do(() => this.ListTab.SelectedIndex = 7),
6050 ShortcutCommand.Create(Keys.Control | Keys.D9)
6051 .FocusedOn(FocusedControl.ListTab)
6052 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6054 ShortcutCommand.Create(Keys.Control | Keys.A)
6055 .FocusedOn(FocusedControl.StatusText)
6056 .Do(() => this.StatusText.SelectAll()),
6058 ShortcutCommand.Create(Keys.Control | Keys.V)
6059 .FocusedOn(FocusedControl.StatusText)
6060 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6062 ShortcutCommand.Create(Keys.Control | Keys.Up)
6063 .FocusedOn(FocusedControl.StatusText)
6065 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6067 var inReplyToStatusId = this.inReplyTo?.Item1;
6068 var inReplyToScreenName = this.inReplyTo?.Item2;
6069 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6072 if (_hisIdx < 0) _hisIdx = 0;
6074 var historyItem = this._history[this._hisIdx];
6075 StatusText.Text = historyItem.status;
6076 StatusText.SelectionStart = StatusText.Text.Length;
6077 if (historyItem.inReplyToId != null)
6078 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6080 this.inReplyTo = null;
6083 ShortcutCommand.Create(Keys.Control | Keys.Down)
6084 .FocusedOn(FocusedControl.StatusText)
6086 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6088 var inReplyToStatusId = this.inReplyTo?.Item1;
6089 var inReplyToScreenName = this.inReplyTo?.Item2;
6090 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6093 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6095 var historyItem = this._history[this._hisIdx];
6096 StatusText.Text = historyItem.status;
6097 StatusText.SelectionStart = StatusText.Text.Length;
6098 if (historyItem.inReplyToId != null)
6099 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6101 this.inReplyTo = null;
6104 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6105 .FocusedOn(FocusedControl.StatusText)
6107 if (ListTab.SelectedIndex == 0)
6109 ListTab.SelectedIndex = ListTab.TabCount - 1;
6113 ListTab.SelectedIndex -= 1;
6118 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6119 .FocusedOn(FocusedControl.StatusText)
6121 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6123 ListTab.SelectedIndex = 0;
6127 ListTab.SelectedIndex += 1;
6132 ShortcutCommand.Create(Keys.Control | Keys.Y)
6133 .FocusedOn(FocusedControl.PostBrowser)
6135 var multiline = !SettingManager.Local.StatusMultiline;
6136 SettingManager.Local.StatusMultiline = multiline;
6137 MultiLineMenuItem.Checked = multiline;
6138 MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
6141 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6142 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6144 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6145 .Do(() => this.DoRefreshMore()),
6147 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6148 .Do(() => this.GetReplyAsync(loadMore: true)),
6150 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6151 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6153 ShortcutCommand.Create(Keys.Shift | Keys.R)
6154 .NotFocusedOn(FocusedControl.StatusText)
6155 .Do(() => this.DoRefreshMore()),
6157 ShortcutCommand.Create(Keys.Shift | Keys.H)
6158 .FocusedOn(FocusedControl.ListTab)
6159 .Do(() => this.GoTopEnd(GoTop: true)),
6161 ShortcutCommand.Create(Keys.Shift | Keys.L)
6162 .FocusedOn(FocusedControl.ListTab)
6163 .Do(() => this.GoTopEnd(GoTop: false)),
6165 ShortcutCommand.Create(Keys.Shift | Keys.M)
6166 .FocusedOn(FocusedControl.ListTab)
6167 .Do(() => this.GoMiddle()),
6169 ShortcutCommand.Create(Keys.Shift | Keys.G)
6170 .FocusedOn(FocusedControl.ListTab)
6171 .Do(() => this.GoLast()),
6173 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6174 .FocusedOn(FocusedControl.ListTab)
6175 .Do(() => this.MoveMiddle()),
6177 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6178 .FocusedOn(FocusedControl.ListTab)
6179 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6181 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6182 .FocusedOn(FocusedControl.ListTab)
6183 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6185 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6186 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6187 .FocusedOn(FocusedControl.ListTab)
6188 .Do(() => this.GoFav(forward: true)),
6190 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6191 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6192 .FocusedOn(FocusedControl.ListTab)
6193 .Do(() => this.GoFav(forward: false)),
6195 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6196 .FocusedOn(FocusedControl.ListTab)
6197 .Do(() => this.GoBackSelectPostChain()),
6199 ShortcutCommand.Create(Keys.Alt | Keys.R)
6200 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6202 ShortcutCommand.Create(Keys.Alt | Keys.P)
6203 .OnlyWhen(() => this._curPost != null)
6204 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6206 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6207 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6209 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6210 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6212 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6213 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6215 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6216 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6218 // 別タブの同じ書き込みへ(ALT+←/→)
6219 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6220 .FocusedOn(FocusedControl.ListTab)
6221 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6223 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6224 .FocusedOn(FocusedControl.ListTab)
6225 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6227 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6228 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6230 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6231 .Do(() => this.CopyIdUri()),
6233 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6234 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6235 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6236 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6238 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6239 .Do(() => this.FavoriteChange(FavAdd: false)),
6241 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6242 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6244 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6245 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6247 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6248 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6250 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6251 .Do(() => this.doMoveToRTHome()),
6253 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6254 .Do(() => this.FavorareMenuItem_Click(null, null)),
6256 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6257 .FocusedOn(FocusedControl.StatusText)
6259 if (_curList != null && _curList.VirtualListSize != 0 &&
6260 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6262 var idx = _curList.SelectedIndices[0] - 1;
6263 SelectListItem(_curList, idx);
6264 _curList.EnsureVisible(idx);
6268 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6269 .FocusedOn(FocusedControl.StatusText)
6271 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6272 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6274 var idx = _curList.SelectedIndices[0] + 1;
6275 SelectListItem(_curList, idx);
6276 _curList.EnsureVisible(idx);
6280 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6281 .FocusedOn(FocusedControl.StatusText)
6283 if (StatusText.SelectionStart > 0)
6285 int endidx = StatusText.SelectionStart - 1;
6286 string startstr = "";
6287 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6289 char c = StatusText.Text[i];
6290 if (Char.IsLetterOrDigit(c) || c == '_')
6296 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6297 int cnt = AtIdSupl.ItemCount;
6298 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6299 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6303 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6304 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6314 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6315 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6316 .FocusedOn(FocusedControl.ListTab)
6317 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6319 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6320 .FocusedOn(FocusedControl.ListTab)
6321 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6323 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6324 .FocusedOn(FocusedControl.ListTab)
6325 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6327 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6328 .FocusedOn(FocusedControl.ListTab)
6329 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6331 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6332 .FocusedOn(FocusedControl.ListTab)
6333 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6335 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6336 .FocusedOn(FocusedControl.ListTab)
6337 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6339 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6340 .FocusedOn(FocusedControl.ListTab)
6341 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6343 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6344 .FocusedOn(FocusedControl.ListTab)
6345 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6347 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6348 .FocusedOn(FocusedControl.ListTab)
6349 .Do(() => this.SetSortLastColumn()),
6351 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6352 .Do(() => this.FavoritesRetweetOfficial()),
6354 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6355 .Do(() => this.FavoritesRetweetUnofficial()),
6357 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6358 .Do(() => this.OpenUserAppointUrl()),
6360 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6361 .FocusedOn(FocusedControl.PostBrowser)
6362 .Do(() => this.doReTweetUnofficial()),
6364 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6365 .OnlyWhen(() => this.ExistCurrentPost)
6366 .Do(() => this.tweetDetailsView.DoTranslation()),
6368 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6369 .Do(() => this.doReTweetUnofficial()),
6371 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6372 .Do(() => this.CopyUserId()),
6374 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6375 .Do(() => this.tweetThumbnail1.ScrollUp()),
6377 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6378 .Do(() => this.tweetThumbnail1.ScrollDown()),
6380 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6381 .FocusedOn(FocusedControl.ListTab)
6382 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6383 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6387 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6389 // Task を返す非同期処理があれば asyncTask に代入する
6392 // ShortcutCommand に対応しているコマンドはここで処理される
6393 foreach (var command in this.shortcutCommands)
6395 if (command.IsMatch(keyData, focusedOn))
6397 asyncTask = command.RunCommand();
6398 return command.PreventDefault;
6405 private void GoNextTab(bool forward)
6407 int idx = ListTab.SelectedIndex;
6411 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6416 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6418 ListTab.SelectedIndex = idx;
6421 private void CopyStot()
6424 StringBuilder sb = new StringBuilder();
6425 bool IsProtected = false;
6427 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6428 foreach (int idx in _curList.SelectedIndices)
6430 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6431 if (post.IsDeleted) continue;
6434 if (post.RetweetedId != null)
6435 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6437 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6441 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6446 MessageBox.Show(Properties.Resources.CopyStotText1);
6450 clstr = sb.ToString();
6453 Clipboard.SetDataObject(clstr, false, 5, 100);
6455 catch (Exception ex)
6457 MessageBox.Show(ex.Message);
6462 private void CopyIdUri()
6464 if (this._curTab == null)
6467 var tab = this._statuses.GetTabByName(this._curTab.Text);
6468 if (tab == null || tab is DirectMessagesTabModel)
6471 var copyUrls = new List<string>();
6472 foreach (int idx in _curList.SelectedIndices)
6474 var post = tab[idx];
6475 copyUrls.Add(MyCommon.GetStatusUrl(post));
6478 if (copyUrls.Count == 0)
6483 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6485 catch (ExternalException ex)
6487 MessageBox.Show(ex.Message);
6491 private void GoFav(bool forward)
6493 if (_curList.VirtualListSize == 0) return;
6500 if (_curList.SelectedIndices.Count == 0)
6506 fIdx = _curList.SelectedIndices[0] + 1;
6507 if (fIdx > _curList.VirtualListSize - 1) return;
6509 toIdx = _curList.VirtualListSize;
6514 if (_curList.SelectedIndices.Count == 0)
6516 fIdx = _curList.VirtualListSize - 1;
6520 fIdx = _curList.SelectedIndices[0] - 1;
6521 if (fIdx < 0) return;
6527 for (int idx = fIdx; idx != toIdx; idx += stp)
6529 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6531 SelectListItem(_curList, idx);
6532 _curList.EnsureVisible(idx);
6538 private void GoSamePostToAnotherTab(bool left)
6540 if (this._curList.SelectedIndices.Count == 0)
6543 var tab = this._statuses.Tabs[this._curTab.Text];
6545 // Directタブは対象外(見つかるはずがない)
6546 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6549 var selectedIndex = this._curList.SelectedIndices[0];
6550 var selectedStatusId = tab.GetStatusIdAt(selectedIndex);
6552 int fIdx, toIdx, stp;
6557 if (ListTab.SelectedIndex == 0)
6563 fIdx = ListTab.SelectedIndex - 1;
6571 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6577 fIdx = ListTab.SelectedIndex + 1;
6579 toIdx = ListTab.TabCount;
6583 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6585 var targetTab = this._statuses.Tabs[this.ListTab.TabPages[tabidx].Text];
6588 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6591 var foundIndex = targetTab.IndexOf(selectedStatusId);
6592 if (foundIndex != -1)
6594 ListTab.SelectedIndex = tabidx;
6595 SelectListItem(_curList, foundIndex);
6596 _curList.EnsureVisible(foundIndex);
6602 private void GoPost(bool forward)
6604 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6607 var tab = this._statuses.Tabs[this._curTab.Text];
6608 var selectedIndex = this._curList.SelectedIndices[0];
6610 int fIdx, toIdx, stp;
6614 fIdx = selectedIndex + 1;
6615 if (fIdx > tab.AllCount - 1) return;
6616 toIdx = tab.AllCount;
6621 fIdx = selectedIndex - 1;
6622 if (fIdx < 0) return;
6628 if (_curPost.RetweetedId == null)
6630 name = _curPost.ScreenName;
6634 name = _curPost.RetweetedBy;
6636 for (int idx = fIdx; idx != toIdx; idx += stp)
6638 var post = tab[idx];
6639 if (post.RetweetedId == null)
6641 if (post.ScreenName == name)
6643 SelectListItem(_curList, idx);
6644 _curList.EnsureVisible(idx);
6650 if (post.RetweetedBy == name)
6652 SelectListItem(_curList, idx);
6653 _curList.EnsureVisible(idx);
6660 private void GoRelPost(bool forward)
6662 if (this._curList.SelectedIndices.Count == 0)
6665 var tab = this._statuses.Tabs[this._curTab.Text];
6666 var selectedIndex = this._curList.SelectedIndices[0];
6668 int fIdx, toIdx, stp;
6672 fIdx = selectedIndex + 1;
6673 if (fIdx > tab.AllCount - 1) return;
6674 toIdx = tab.AllCount;
6679 fIdx = selectedIndex - 1;
6680 if (fIdx < 0) return;
6687 if (_curPost == null) return;
6688 _anchorPost = _curPost;
6693 if (_anchorPost == null) return;
6696 for (int idx = fIdx; idx != toIdx; idx += stp)
6698 var post = tab[idx];
6699 if (post.ScreenName == _anchorPost.ScreenName ||
6700 post.RetweetedBy == _anchorPost.ScreenName ||
6701 post.ScreenName == _anchorPost.RetweetedBy ||
6702 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6703 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
6704 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
6705 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
6706 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
6708 SelectListItem(_curList, idx);
6709 _curList.EnsureVisible(idx);
6715 private void GoAnchor()
6717 if (_anchorPost == null) return;
6718 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6719 if (idx == -1) return;
6721 SelectListItem(_curList, idx);
6722 _curList.EnsureVisible(idx);
6725 private void GoTopEnd(bool GoTop)
6727 if (_curList.VirtualListSize == 0)
6735 _item = _curList.GetItemAt(0, 25);
6743 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6745 idx = _curList.VirtualListSize - 1;
6749 SelectListItem(_curList, idx);
6752 private void GoMiddle()
6754 if (_curList.VirtualListSize == 0)
6762 _item = _curList.GetItemAt(0, 0);
6772 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6775 idx2 = _curList.VirtualListSize - 1;
6781 idx3 = (idx1 + idx2) / 2;
6783 SelectListItem(_curList, idx3);
6786 private void GoLast()
6788 if (_curList.VirtualListSize == 0) return;
6790 if (_statuses.SortOrder == SortOrder.Ascending)
6792 SelectListItem(_curList, _curList.VirtualListSize - 1);
6793 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6797 SelectListItem(_curList, 0);
6798 _curList.EnsureVisible(0);
6802 private void MoveTop()
6804 if (_curList.SelectedIndices.Count == 0) return;
6805 int idx = _curList.SelectedIndices[0];
6806 if (_statuses.SortOrder == SortOrder.Ascending)
6808 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6812 _curList.EnsureVisible(0);
6814 _curList.EnsureVisible(idx);
6817 private async Task GoInReplyToPostTree()
6819 if (_curPost == null) return;
6821 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6823 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
6827 var post = await tw.GetStatusApi(false, _curPost.StatusId);
6829 _curPost.InReplyToStatusId = post.InReplyToStatusId;
6830 _curPost.InReplyToUser = post.InReplyToUser;
6831 _curPost.IsReply = post.IsReply;
6832 this.PurgeListViewItemCache();
6833 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
6835 catch (WebApiException ex)
6837 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6841 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
6843 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
6845 replyChains = new Stack<ReplyChain>();
6847 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
6850 string inReplyToTabName;
6851 long inReplyToId = _curPost.InReplyToStatusId.Value;
6852 string inReplyToUser = _curPost.InReplyToUser;
6853 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6855 var inReplyToPosts = from tab in _statuses.Tabs.Values
6856 orderby tab != curTabClass
6857 from post in tab.Posts.Values
6858 where post.StatusId == inReplyToId
6859 let index = tab.IndexOf(post.StatusId)
6861 select new {Tab = tab, Index = index};
6863 var inReplyPost = inReplyToPosts.FirstOrDefault();
6864 if (inReplyPost == null)
6868 await Task.Run(async () =>
6870 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
6871 .ConfigureAwait(false);
6874 _statuses.AddPost(post);
6875 _statuses.DistributePosts();
6878 catch (WebApiException ex)
6880 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6881 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6885 this.RefreshTimeline();
6887 inReplyPost = inReplyToPosts.FirstOrDefault();
6888 if (inReplyPost == null)
6890 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6894 inReplyToTabName = inReplyPost.Tab.TabName;
6895 inReplyToIndex = inReplyPost.Index;
6897 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
6898 DetailsListView listView = (DetailsListView)tabPage.Tag;
6900 if (_curTab != tabPage)
6902 this.ListTab.SelectTab(tabPage);
6905 this.SelectListItem(listView, inReplyToIndex);
6906 listView.EnsureVisible(inReplyToIndex);
6909 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6911 if (_curPost == null) return;
6913 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6914 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6918 if (_curPost.InReplyToStatusId != null)
6920 var posts = from t in _statuses.Tabs
6921 from p in t.Value.Posts
6922 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
6923 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6925 orderby isForward ? indexOf : indexOf * -1
6926 orderby t.Value != curTabClass
6927 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
6930 var postList = posts.ToList();
6931 for (int i = postList.Count - 1; i >= 0; i--)
6934 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
6936 postList.RemoveAt(index);
6939 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
6940 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
6941 if (post == null) post = postList.First();
6942 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6943 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6944 SelectListItem(listView, post.Index);
6945 listView.EnsureVisible(post.Index);
6947 catch (InvalidOperationException)
6955 if (replyChains == null || replyChains.Count < 1)
6957 var posts = from t in _statuses.Tabs
6958 from p in t.Value.Posts
6959 where p.Value.InReplyToStatusId == _curPost.StatusId
6960 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6963 orderby t.Value != curTabClass
6964 select new {Tab = t.Value, Index = indexOf};
6967 var post = posts.First();
6968 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6969 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6970 SelectListItem(listView, post.Index);
6971 listView.EnsureVisible(post.Index);
6973 catch (InvalidOperationException)
6980 ReplyChain chainHead = replyChains.Pop();
6981 if (chainHead.InReplyToId == _curPost.StatusId)
6983 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
6992 ListTab.SelectTab(chainHead.OriginalTab);
6998 SelectListItem(_curList, idx);
6999 _curList.EnsureVisible(idx);
7005 this.GoBackInReplyToPostTree(parallel);
7011 private void GoBackSelectPostChain()
7013 if (this.selectPostChains.Count > 1)
7022 this.selectPostChains.Pop();
7023 var (tabPage, post) = this.selectPostChains.Peek();
7025 if (!this.ListTab.TabPages.Contains(tabPage)) continue; //該当タブが存在しないので無視
7029 idx = this._statuses.Tabs[tabPage.Text].IndexOf(post.StatusId);
7030 if (idx == -1) continue; //該当ポストが存在しないので無視
7035 this.selectPostChains.Pop();
7037 catch (InvalidOperationException)
7043 while (this.selectPostChains.Count > 1);
7048 //履歴が残り1つであればクリアしておく
7049 if (this.selectPostChains.Count == 1)
7050 this.selectPostChains.Clear();
7054 DetailsListView lst = (DetailsListView)tp.Tag;
7055 this.ListTab.SelectedTab = tp;
7058 SelectListItem(lst, idx);
7059 lst.EnsureVisible(idx);
7065 private void PushSelectPostChain()
7067 int count = this.selectPostChains.Count;
7070 var (tabPage, post) = this.selectPostChains.Peek();
7071 if (tabPage == this._curTab)
7073 if (post == this._curPost) return; //最新の履歴と同一
7074 if (post == null) this.selectPostChains.Pop(); //置き換えるため削除
7077 if (count >= 2500) TrimPostChain();
7078 this.selectPostChains.Push((this._curTab, this._curPost));
7081 private void TrimPostChain()
7083 if (this.selectPostChains.Count <= 2000) return;
7084 var p = new Stack<ValueTuple<TabPage, PostClass>>(2000);
7085 for (int i = 0; i < 2000; i++)
7087 p.Push(this.selectPostChains.Pop());
7089 this.selectPostChains.Clear();
7090 for (int i = 0; i < 2000; i++)
7092 this.selectPostChains.Push(p.Pop());
7096 private bool GoStatus(long statusId)
7098 if (statusId == 0) return false;
7099 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7101 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7103 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7104 ListTab.SelectedIndex = tabidx;
7105 SelectListItem(_curList, idx);
7106 _curList.EnsureVisible(idx);
7113 private bool GoDirectMessage(long statusId)
7115 if (statusId == 0) return false;
7116 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7118 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7120 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7121 ListTab.SelectedIndex = tabidx;
7122 SelectListItem(_curList, idx);
7123 _curList.EnsureVisible(idx);
7130 private void MyList_MouseClick(object sender, MouseEventArgs e)
7132 _anchorFlag = false;
7135 private void StatusText_Enter(object sender, EventArgs e)
7137 // フォーカスの戻り先を StatusText に設定
7138 this.Tag = StatusText;
7139 StatusText.BackColor = _clInputBackcolor;
7142 public Color InputBackColor
7144 get => _clInputBackcolor;
7145 set => _clInputBackcolor = value;
7148 private void StatusText_Leave(object sender, EventArgs e)
7150 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7151 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7152 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7155 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7157 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
7160 e.SuppressKeyPress = true;
7163 this.StatusText_TextChanged(null, null);
7165 if (asyncTask != null)
7169 private void SaveConfigsAll(bool ifModified)
7173 SaveConfigsCommon();
7180 if (ModifySettingCommon) SaveConfigsCommon();
7181 if (ModifySettingLocal) SaveConfigsLocal();
7182 if (ModifySettingAtId) SaveConfigsAtId();
7186 private void SaveConfigsAtId()
7188 if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7190 ModifySettingAtId = false;
7191 SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7192 SettingManager.SaveAtIdList();
7195 private void SaveConfigsCommon()
7197 if (_ignoreConfigSave) return;
7199 ModifySettingCommon = false;
7202 SettingManager.Common.UserName = tw.Username;
7203 SettingManager.Common.UserId = tw.UserId;
7204 SettingManager.Common.Token = tw.AccessToken;
7205 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7206 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7207 switch (_statuses.SortMode)
7209 case ComparerMode.Nickname: //ニックネーム
7210 SettingManager.Common.SortColumn = 1;
7212 case ComparerMode.Data: //本文
7213 SettingManager.Common.SortColumn = 2;
7215 case ComparerMode.Id: //時刻=発言Id
7216 SettingManager.Common.SortColumn = 3;
7218 case ComparerMode.Name: //名前
7219 SettingManager.Common.SortColumn = 4;
7221 case ComparerMode.Source: //Source
7222 SettingManager.Common.SortColumn = 7;
7226 SettingManager.Common.HashTags = HashMgr.HashHistories;
7227 if (HashMgr.IsPermanent)
7229 SettingManager.Common.HashSelected = HashMgr.UseHash;
7233 SettingManager.Common.HashSelected = "";
7235 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7236 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7237 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7238 SettingManager.Common.TrackWord = tw.TrackWord;
7239 SettingManager.Common.AllAtReply = tw.AllAtReply;
7240 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7241 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7243 SettingManager.SaveCommon();
7247 private void SaveConfigsLocal()
7249 if (_ignoreConfigSave) return;
7252 ModifySettingLocal = false;
7253 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7254 SettingManager.Local.FormSize = _mySize;
7255 SettingManager.Local.FormLocation = _myLoc;
7256 SettingManager.Local.SplitterDistance = _mySpDis;
7257 SettingManager.Local.PreviewDistance = _mySpDis3;
7258 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7259 SettingManager.Local.StatusTextHeight = _mySpDis2;
7261 SettingManager.Local.FontUnread = _fntUnread;
7262 SettingManager.Local.ColorUnread = _clUnread;
7263 SettingManager.Local.FontRead = _fntReaded;
7264 SettingManager.Local.ColorRead = _clReaded;
7265 SettingManager.Local.FontDetail = _fntDetail;
7266 SettingManager.Local.ColorDetail = _clDetail;
7267 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7268 SettingManager.Local.ColorDetailLink = _clDetailLink;
7269 SettingManager.Local.ColorFav = _clFav;
7270 SettingManager.Local.ColorOWL = _clOWL;
7271 SettingManager.Local.ColorRetweet = _clRetweet;
7272 SettingManager.Local.ColorSelf = _clSelf;
7273 SettingManager.Local.ColorAtSelf = _clAtSelf;
7274 SettingManager.Local.ColorTarget = _clTarget;
7275 SettingManager.Local.ColorAtTarget = _clAtTarget;
7276 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7277 SettingManager.Local.ColorAtTo = _clAtTo;
7278 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7279 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7280 SettingManager.Local.ColorInputFont = _clInputFont;
7281 SettingManager.Local.FontInputFont = _fntInputFont;
7283 if (_ignoreConfigSave) return;
7284 SettingManager.SaveLocal();
7288 private void SaveConfigsTabs()
7290 var tabSettingList = new List<SettingTabs.SettingTabItem>();
7292 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7293 .Select(x => this._statuses.Tabs[x.Text])
7294 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7296 foreach (var tab in tabs)
7298 if (!tab.IsPermanentTabType)
7301 var tabSetting = new SettingTabs.SettingTabItem
7303 TabName = tab.TabName,
7304 TabType = tab.TabType,
7305 UnreadManage = tab.UnreadManage,
7306 Protected = tab.Protected,
7307 Notify = tab.Notify,
7308 SoundFile = tab.SoundFile,
7313 case FilterTabModel filterTab:
7314 tabSetting.FilterArray = filterTab.FilterArray;
7316 case UserTimelineTabModel userTab:
7317 tabSetting.User = userTab.ScreenName;
7319 case PublicSearchTabModel searchTab:
7320 tabSetting.SearchWords = searchTab.SearchWords;
7321 tabSetting.SearchLang = searchTab.SearchLang;
7323 case ListTimelineTabModel listTab:
7324 tabSetting.ListInfo = listTab.ListInfo;
7328 tabSettingList.Add(tabSetting);
7331 SettingManager.Tabs.Tabs = tabSettingList;
7332 SettingManager.SaveTabs();
7335 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7337 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
7338 if (ret != DialogResult.OK)
7341 var match = Twitter.StatusUrlRegex.Match(inputText);
7344 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7345 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7351 var statusId = long.Parse(match.Groups["StatusId"].Value);
7352 await this.OpenRelatedTab(statusId);
7354 catch (TabException ex)
7356 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7360 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7362 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7363 Properties.Resources.SaveLogMenuItem_ClickText2,
7364 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7365 if (rslt == DialogResult.Cancel) return;
7367 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7368 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7369 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7370 SaveFileDialog1.FilterIndex = 0;
7371 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7372 SaveFileDialog1.RestoreDirectory = true;
7374 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7376 if (!SaveFileDialog1.ValidateNames) return;
7377 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7379 if (rslt == DialogResult.Yes)
7382 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7384 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7385 string protect = "";
7386 if (post.IsProtect) protect = "Protect";
7387 sw.WriteLine(post.Nickname + "\t" +
7388 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7389 post.CreatedAt + "\t" +
7390 post.ScreenName + "\t" +
7391 post.StatusId + "\t" +
7392 post.ImageUrl + "\t" +
7393 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7399 foreach (int idx in _curList.SelectedIndices)
7401 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7402 string protect = "";
7403 if (post.IsProtect) protect = "Protect";
7404 sw.WriteLine(post.Nickname + "\t" +
7405 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7406 post.CreatedAt + "\t" +
7407 post.ScreenName + "\t" +
7408 post.StatusId + "\t" +
7409 post.ImageUrl + "\t" +
7410 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7416 this.TopMost = SettingManager.Common.AlwaysTop;
7419 public bool TabRename(string origTabName, out string newTabName)
7423 using (InputTabName inputName = new InputTabName())
7425 inputName.TabName = origTabName;
7426 inputName.ShowDialog();
7427 if (inputName.DialogResult == DialogResult.Cancel) return false;
7428 newTabName = inputName.TabName;
7430 this.TopMost = SettingManager.Common.AlwaysTop;
7431 if (!string.IsNullOrEmpty(newTabName))
7434 for (int i = 0; i < ListTab.TabCount; i++)
7436 if (ListTab.TabPages[i].Text == newTabName)
7438 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7439 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7444 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
7445 .FirstOrDefault(x => x.Text == origTabName);
7448 if (tabPage != null)
7449 tabPage.Text = newTabName;
7451 _statuses.RenameTab(origTabName, newTabName);
7453 SaveConfigsCommon();
7455 _rclickTabName = newTabName;
7464 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7466 if (e.Button == MouseButtons.Middle)
7468 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7470 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7472 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7473 this.SaveConfigsTabs();
7480 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7482 TabRename(this.ListTab.SelectedTab.Text, out var _);
7485 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7487 if (SettingManager.Common.TabMouseLock) return;
7488 if (e.Button == MouseButtons.Left)
7490 for (int i = 0; i < ListTab.TabPages.Count; i++)
7492 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7495 _tabMouseDownPoint = e.Location;
7506 private void ListTab_DragEnter(object sender, DragEventArgs e)
7508 if (e.Data.GetDataPresent(typeof(TabPage)))
7509 e.Effect = DragDropEffects.Move;
7511 e.Effect = DragDropEffects.None;
7514 private void ListTab_DragDrop(object sender, DragEventArgs e)
7516 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7521 Point cpos = new Point(e.X, e.Y);
7522 Point spos = ListTab.PointToClient(cpos);
7524 for (i = 0; i < ListTab.TabPages.Count; i++)
7526 Rectangle rect = ListTab.GetTabRect(i);
7527 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7528 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7530 tn = ListTab.TabPages[i].Text;
7531 if (spos.X <= (rect.Left + rect.Right) / 2)
7540 //タブのないところにドロップ->最後尾へ移動
7541 if (string.IsNullOrEmpty(tn))
7543 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7545 i = ListTab.TabPages.Count - 1;
7548 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7549 if (tp.Text == tn) return;
7551 ReOrderTab(tp.Text, tn, bef);
7554 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7556 var baseIndex = this.GetTabPageIndex(baseTabText);
7557 if (baseIndex == -1)
7560 var targetIndex = this.GetTabPageIndex(targetTabText);
7561 if (targetIndex == -1)
7564 using (ControlTransaction.Layout(this.ListTab))
7566 var mTp = this.ListTab.TabPages[targetIndex];
7567 this.ListTab.TabPages.Remove(mTp);
7569 if (targetIndex < baseIndex)
7572 if (isBeforeBaseTab)
7573 ListTab.TabPages.Insert(baseIndex, mTp);
7575 ListTab.TabPages.Insert(baseIndex + 1, mTp);
7581 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7583 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7584 //isReply:true=@,false=DM
7585 if (!StatusText.Enabled) return;
7586 if (_curList == null) return;
7587 if (_curTab == null) return;
7588 if (!this.ExistCurrentPost) return;
7590 // 複数あてリプライはReplyではなく通常ポスト
7591 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7592 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7593 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7595 if (_curList.SelectedIndices.Count > 0)
7598 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7601 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7604 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7605 StatusText.SelectionStart = StatusText.Text.Length;
7607 this.inReplyTo = null;
7610 if (string.IsNullOrEmpty(StatusText.Text))
7614 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7615 StatusText.Text = "@" + _curPost.ScreenName + " ";
7617 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7618 var inReplyToScreenName = this._curPost.ScreenName;
7619 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7627 //1件選んでEnter or DoubleClick
7628 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7630 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7633 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7634 var inReplyToScreenName = this._curPost.ScreenName;
7635 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7639 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7642 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7645 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7646 this.inReplyTo = null;
7651 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7652 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7653 var inReplyToScreenName = this._curPost.ScreenName;
7654 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7661 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7662 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7663 this.inReplyTo = null;
7668 //1件選んでCtrl-Rの場合(返信先操作せず)
7669 int sidx = StatusText.SelectionStart;
7670 string id = "@" + _curPost.ScreenName + " ";
7673 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7678 StatusText.Text = StatusText.Text.Insert(sidx, id);
7680 //if (StatusText.Text.StartsWith("@"))
7683 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7684 // sidx += 5 + _curPost.ScreenName.Length;
7689 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7690 // sidx += 3 + _curPost.ScreenName.Length;
7692 StatusText.SelectionStart = sidx;
7695 //_reply_to_name = null;
7703 if (!isAuto && !isReply) return;
7705 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7709 //Enter or DoubleClick
7711 string sTxt = StatusText.Text;
7712 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7715 this.inReplyTo = null;
7717 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7719 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7720 if (!sTxt.Contains("@" + post.ScreenName + " "))
7722 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7723 //sTxt = "@" + post.ScreenName + " " + sTxt;
7726 StatusText.Text = sTxt;
7731 if (_curList.SelectedIndices.Count > 1)
7736 int sidx = StatusText.SelectionStart;
7737 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7739 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7740 if (!ids.Contains("@" + post.ScreenName + " ") &&
7741 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7743 ids += "@" + post.ScreenName + " ";
7747 foreach (string nm in post.ReplyToList)
7749 if (!ids.Contains("@" + nm + " ") &&
7750 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7752 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7754 ids += "@" + m.Result("${id}") + " ";
7756 ids += "@" + nm + " ";
7761 if (ids.Length == 0) return;
7762 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7764 StatusText.Text = ". " + StatusText.Text;
7766 this.inReplyTo = null;
7770 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7775 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7777 //if (StatusText.Text.StartsWith("@"))
7779 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7780 // sidx += 2 + ids.Length;
7784 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7785 // sidx += 1 + ids.Length;
7787 StatusText.SelectionStart = sidx;
7793 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7796 int sidx = StatusText.SelectionStart;
7797 PostClass post = _curPost;
7798 if (!ids.Contains("@" + post.ScreenName + " ") &&
7799 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7801 ids += "@" + post.ScreenName + " ";
7803 foreach (string nm in post.ReplyToList)
7805 if (!ids.Contains("@" + nm + " ") &&
7806 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7808 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7810 ids += "@" + m.Result("${id}") + " ";
7812 ids += "@" + nm + " ";
7815 if (!string.IsNullOrEmpty(post.RetweetedBy))
7817 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
7818 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7820 ids += "@" + post.RetweetedBy + " ";
7823 if (ids.Length == 0) return;
7824 if (string.IsNullOrEmpty(StatusText.Text))
7827 StatusText.Text = ids;
7828 StatusText.SelectionStart = ids.Length;
7831 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7832 var inReplyToScreenName = this._curPost.ScreenName;
7833 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7839 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7844 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7846 StatusText.SelectionStart = sidx;
7852 StatusText.SelectionStart = StatusText.Text.Length;
7857 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7862 private static int iconCnt = 0;
7863 private static int blinkCnt = 0;
7864 private static bool blink = false;
7865 private static bool idle = false;
7867 private async Task RefreshTasktrayIcon()
7870 await this.Colorize();
7872 if (!TimerRefreshIcon.Enabled) return;
7873 //Static usCheckCnt As int = 0
7875 //Static iconDlListTopItem As ListViewItem = null
7877 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7878 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7880 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7882 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7888 //if (usCheckCnt > 300) //1min
7891 // if (!this.IsReceivedUserStream)
7893 // TraceOut("ReconnectUserStream");
7894 // tw.ReconnectUserStream();
7898 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7900 if (iconCnt >= this.NIconRefresh.Length)
7908 SaveConfigsAll(true);
7913 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7915 _myStatusError = false;
7919 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
7920 if (SettingManager.Common.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
7922 if (blinkCnt > 0) return;
7924 if (blink || SettingManager.Common.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
7926 NotifyIcon1.Icon = ReplyIcon;
7930 NotifyIcon1.Icon = ReplyIconBlink;
7938 //優先度:エラー→オフライン→アイドル
7942 NotifyIcon1.Icon = NIconAtRed;
7945 if (_myStatusOnline)
7947 NotifyIcon1.Icon = NIconAt;
7951 NotifyIcon1.Icon = NIconAtSmoke;
7955 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
7958 await this.RefreshTasktrayIcon();
7961 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7963 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7964 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7966 if (ListTab != null && ListTab.SelectedTab != null)
7967 _rclickTabName = ListTab.SelectedTab.Text;
7972 if (_statuses == null) return;
7973 if (_statuses.Tabs == null) return;
7975 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out var tb))
7978 NotifyDispMenuItem.Checked = tb.Notify;
7979 this.NotifyTbMenuItem.Checked = tb.Notify;
7981 soundfileListup = true;
7982 SoundFileComboBox.Items.Clear();
7983 this.SoundFileTbComboBox.Items.Clear();
7984 SoundFileComboBox.Items.Add("");
7985 this.SoundFileTbComboBox.Items.Add("");
7986 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
7987 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
7989 oDir = oDir.GetDirectories("Sounds")[0];
7991 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
7993 SoundFileComboBox.Items.Add(oFile.Name);
7994 this.SoundFileTbComboBox.Items.Add(oFile.Name);
7996 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
7997 if (idx == -1) idx = 0;
7998 SoundFileComboBox.SelectedIndex = idx;
7999 this.SoundFileTbComboBox.SelectedIndex = idx;
8000 soundfileListup = false;
8001 UreadManageMenuItem.Checked = tb.UnreadManage;
8002 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8004 TabMenuControl(_rclickTabName);
8007 private void TabMenuControl(string tabName)
8009 var tabInfo = _statuses.GetTabByName(tabName);
8011 this.FilterEditMenuItem.Enabled = true;
8012 this.EditRuleTbMenuItem.Enabled = true;
8014 if (tabInfo.IsDefaultTabType)
8016 this.ProtectTabMenuItem.Enabled = false;
8017 this.ProtectTbMenuItem.Enabled = false;
8021 this.ProtectTabMenuItem.Enabled = true;
8022 this.ProtectTbMenuItem.Enabled = true;
8025 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8027 this.ProtectTabMenuItem.Checked = true;
8028 this.ProtectTbMenuItem.Checked = true;
8029 this.DeleteTabMenuItem.Enabled = false;
8030 this.DeleteTbMenuItem.Enabled = false;
8034 this.ProtectTabMenuItem.Checked = false;
8035 this.ProtectTbMenuItem.Checked = false;
8036 this.DeleteTabMenuItem.Enabled = true;
8037 this.DeleteTbMenuItem.Enabled = true;
8041 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8043 var checkState = ((ToolStripMenuItem)sender).Checked;
8046 this.ProtectTbMenuItem.Checked = checkState;
8047 this.ProtectTabMenuItem.Checked = checkState;
8050 this.DeleteTabMenuItem.Enabled = !checkState;
8051 this.DeleteTbMenuItem.Enabled = !checkState;
8053 if (string.IsNullOrEmpty(_rclickTabName)) return;
8054 _statuses.Tabs[_rclickTabName].Protected = checkState;
8059 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8061 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8062 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8064 if (string.IsNullOrEmpty(_rclickTabName)) return;
8065 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8070 public void ChangeTabUnreadManage(string tabName, bool isManage)
8072 var idx = this.GetTabPageIndex(tabName);
8076 _statuses.Tabs[tabName].UnreadManage = isManage;
8077 if (SettingManager.Common.TabIconDisp)
8079 if (_statuses.Tabs[tabName].UnreadCount > 0)
8080 ListTab.TabPages[idx].ImageIndex = 0;
8082 ListTab.TabPages[idx].ImageIndex = -1;
8085 if (_curTab.Text == tabName)
8087 this.PurgeListViewItemCache();
8091 SetMainWindowTitle();
8092 SetStatusLabelUrl();
8093 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8096 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8098 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8099 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8101 if (string.IsNullOrEmpty(_rclickTabName)) return;
8103 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8108 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8110 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8112 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8117 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8119 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8121 RemoveSpecifiedTab(_rclickTabName, true);
8125 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8127 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8129 using (var fltDialog = new FilterDialog())
8131 fltDialog.Owner = this;
8132 fltDialog.SetCurrent(_rclickTabName);
8133 fltDialog.ShowDialog(this);
8135 this.TopMost = SettingManager.Common.AlwaysTop;
8137 this.ApplyPostFilters();
8141 private void AddTabMenuItem_Click(object sender, EventArgs e)
8143 string tabName = null;
8144 MyCommon.TabUsageType tabUsage;
8145 using (InputTabName inputName = new InputTabName())
8147 inputName.TabName = _statuses.MakeTabName("MyTab");
8148 inputName.IsShowUsage = true;
8149 inputName.ShowDialog();
8150 if (inputName.DialogResult == DialogResult.Cancel) return;
8151 tabName = inputName.TabName;
8152 tabUsage = inputName.Usage;
8154 this.TopMost = SettingManager.Common.AlwaysTop;
8155 if (!string.IsNullOrEmpty(tabName))
8158 ListElement list = null;
8159 if (tabUsage == MyCommon.TabUsageType.Lists)
8161 using (ListAvailable listAvail = new ListAvailable())
8163 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8164 if (listAvail.SelectedList == null) return;
8165 list = listAvail.SelectedList;
8172 case MyCommon.TabUsageType.UserDefined:
8173 tab = new FilterTabModel(tabName);
8175 case MyCommon.TabUsageType.PublicSearch:
8176 tab = new PublicSearchTabModel(tabName);
8178 case MyCommon.TabUsageType.Lists:
8179 tab = new ListTimelineTabModel(tabName, list);
8185 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8187 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8188 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8194 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8196 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8197 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8199 if (tabUsage == MyCommon.TabUsageType.Lists)
8201 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8202 var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8203 this.GetListTimelineAsync(listTab);
8209 private void TabMenuItem_Click(object sender, EventArgs e)
8211 using (var fltDialog = new FilterDialog())
8213 fltDialog.Owner = this;
8216 foreach (int idx in _curList.SelectedIndices)
8219 if (!SelectTab(out var tabName)) return;
8221 fltDialog.SetCurrent(tabName);
8222 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8224 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8228 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8230 fltDialog.ShowDialog(this);
8231 this.TopMost = SettingManager.Common.AlwaysTop;
8235 this.ApplyPostFilters();
8237 if (this.ListTab.SelectedTab != null &&
8238 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8240 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8244 protected override bool ProcessDialogKey(Keys keyData)
8246 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8247 if ((keyData & Keys.KeyCode) == Keys.Enter)
8249 if (StatusText.Focused)
8251 bool _NewLine = false;
8254 if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8256 if (StatusText.Multiline)
8258 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8260 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8264 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8268 else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8270 if (StatusText.Multiline)
8272 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8274 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8278 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8284 if (StatusText.Multiline)
8286 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8288 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8289 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8293 if (((keyData & Keys.Shift) == Keys.Shift) ||
8294 (((keyData & Keys.Control) != Keys.Control) &&
8295 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8301 int pos1 = StatusText.SelectionStart;
8302 if (StatusText.SelectionLength > 0)
8304 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8306 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8307 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8312 PostButton_Click(null, null);
8316 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8317 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8318 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8320 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8325 return base.ProcessDialogKey(keyData);
8328 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8330 MakeReplyOrDirectStatus(false, true, true);
8333 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8336 if (_curList.SelectedIndices.Count == 0) return;
8338 var tab = this._statuses.Tabs[this._curTab.Text];
8339 var screenNameArray = this._curList.SelectedIndices.Cast<int>()
8340 .Select(x => tab[x])
8341 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8344 this.AddFilterRuleByScreenName(screenNameArray);
8346 if (screenNameArray.Length != 0)
8348 List<string> atids = new List<string>();
8349 foreach (var screenName in screenNameArray)
8351 atids.Add("@" + screenName);
8353 int cnt = AtIdSupl.ItemCount;
8354 AtIdSupl.AddRangeItem(atids.ToArray());
8355 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8359 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8361 if (this._curList.SelectedIndices.Count == 0)
8364 var tab = this._statuses.Tabs[this._curTab.Text];
8365 var sourceArray = this._curList.SelectedIndices.Cast<int>()
8366 .Select(x => tab[x].Source).ToArray();
8368 this.AddFilterRuleBySource(sourceArray);
8371 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8374 if (!SelectTab(out var tabName)) return;
8376 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8380 if (tab.TabType != MyCommon.TabUsageType.Mute)
8382 this.MoveOrCopy(out mv, out mk);
8386 // ミュートタブでは常に MoveMatches を true にする
8391 foreach (var screenName in screenNameArray)
8393 tab.AddFilter(new PostFilterRule
8395 FilterName = screenName,
8396 UseNameField = true,
8400 FilterByUrl = false,
8404 this.ApplyPostFilters();
8408 public void AddFilterRuleBySource(params string[] sourceArray)
8410 // タブ選択ダイアログを表示(or追加)
8411 if (!this.SelectTab(out var tabName))
8414 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8418 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8420 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8421 this.MoveOrCopy(out mv, out mk);
8425 // ミュートタブでは常に MoveMatches を true にする
8430 // 振り分けルールに追加するSource
8431 foreach (var source in sourceArray)
8433 filterTab.AddFilter(new PostFilterRule
8435 FilterSource = source,
8439 FilterByUrl = false,
8443 this.ApplyPostFilters();
8444 this.SaveConfigsTabs();
8447 private bool SelectTab(out string tabName)
8454 using (var dialog = new TabsDialog(_statuses))
8456 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8458 var selectedTab = dialog.SelectedTab;
8459 tabName = selectedTab == null ? null : selectedTab.TabName;
8462 ListTab.SelectedTab.Focus();
8464 if (tabName == null)
8466 using (InputTabName inputName = new InputTabName())
8468 inputName.TabName = _statuses.MakeTabName("MyTab");
8469 inputName.ShowDialog();
8470 if (inputName.DialogResult == DialogResult.Cancel) return false;
8471 tabName = inputName.TabName;
8473 this.TopMost = SettingManager.Common.AlwaysTop;
8474 if (!string.IsNullOrEmpty(tabName))
8476 var tab = new FilterTabModel(tabName);
8477 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8479 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8480 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8498 private void MoveOrCopy(out bool move, out bool mark)
8502 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8503 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8511 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8512 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8522 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8527 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8532 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8534 if (StatusText.Focused)
8537 StatusText.SelectAll();
8541 // ListView上でのCtrl+A
8542 NativeMethods.SelectAllItems(this._curList);
8546 private void MoveMiddle()
8552 if (_curList.SelectedIndices.Count == 0) return;
8554 int idx = _curList.SelectedIndices[0];
8556 _item = _curList.GetItemAt(0, 25);
8562 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8564 idx2 = _curList.VirtualListSize - 1;
8568 idx -= Math.Abs(idx1 - idx2) / 2;
8569 if (idx < 0) idx = 0;
8571 _curList.EnsureVisible(_curList.VirtualListSize - 1);
8572 _curList.EnsureVisible(idx);
8575 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8577 var linkElements = this.tweetDetailsView.GetLinkElements();
8579 if (linkElements.Length > 0)
8581 UrlDialog.ClearUrl();
8583 string openUrlStr = "";
8585 if (linkElements.Length == 1)
8587 // ツイートに含まれる URL が 1 つのみの場合
8588 // => OpenURL ダイアログを表示せずにリンクを開く
8593 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8595 catch (ArgumentException)
8604 if (string.IsNullOrEmpty(urlStr)) return;
8605 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8607 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8608 await this.OpenUriAsync(new Uri(openUrlStr));
8612 // ツイートに含まれる URL が複数ある場合
8613 // => OpenURL を表示しユーザーが選択したリンクを開く
8615 foreach (var linkElm in linkElements)
8618 string linkText = "";
8622 urlStr = linkElm.GetAttribute("title");
8623 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8624 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8625 linkText = linkElm.InnerText;
8627 catch (ArgumentException)
8636 if (string.IsNullOrEmpty(urlStr)) continue;
8637 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8641 if (UrlDialog.ShowDialog() == DialogResult.OK)
8643 openUrlStr = UrlDialog.SelectedUrl;
8645 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8646 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8653 this.TopMost = SettingManager.Common.AlwaysTop;
8658 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8660 if (string.IsNullOrEmpty(_rclickTabName)) return;
8661 ClearTab(_rclickTabName, true);
8664 private void ClearTab(string tabName, bool showWarning)
8668 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8669 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8675 _statuses.ClearTabIds(tabName);
8676 if (ListTab.SelectedTab.Text == tabName)
8679 _anchorFlag = false;
8680 this.PurgeListViewItemCache();
8684 foreach (TabPage tb in ListTab.TabPages)
8686 if (tb.Text == tabName)
8688 ((DetailsListView)tb.Tag).VirtualListSize = 0;
8693 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8695 SetMainWindowTitle();
8696 SetStatusLabelUrl();
8699 private static long followers = 0;
8701 private void SetMainWindowTitle()
8704 StringBuilder ttl = new StringBuilder(256);
8707 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8708 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8709 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8710 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8712 foreach (var tab in _statuses.Tabs.Values)
8714 ur += tab.UnreadCount;
8719 if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8720 ttl.Append(Application.ProductName);
8722 switch (SettingManager.Common.DispLatestPost)
8724 case MyCommon.DispTitleEnum.Ver:
8725 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8727 case MyCommon.DispTitleEnum.Post:
8728 if (_history != null && _history.Count > 1)
8729 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8731 case MyCommon.DispTitleEnum.UnreadRepCount:
8732 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8734 case MyCommon.DispTitleEnum.UnreadAllCount:
8735 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8737 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8738 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8740 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8741 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8743 case MyCommon.DispTitleEnum.OwnStatus:
8744 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8745 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8751 this.Text = ttl.ToString();
8753 catch (AccessViolationException)
8755 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8759 private string GetStatusLabelText()
8762 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8763 if (_statuses == null) return "";
8764 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8765 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8766 if (tbRep == null || tbDm == null) return "";
8767 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8772 StringBuilder slbl = new StringBuilder(256);
8775 foreach (var tab in _statuses.Tabs.Values)
8777 ur += tab.UnreadCount;
8779 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
8781 tur = tab.UnreadCount;
8792 UnreadAtCounter = urat;
8794 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8796 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8797 if (SettingManager.Common.TimelinePeriod == 0)
8799 slbl.Append(Properties.Resources.SetStatusLabelText2);
8803 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8805 return slbl.ToString();
8808 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8812 if (this.InvokeRequired && !this.IsDisposed)
8814 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8818 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8819 SetApiStatusLabel(endpointName);
8822 catch (ObjectDisposedException)
8826 catch (InvalidOperationException)
8832 private void SetApiStatusLabel(string endpointName = null)
8834 if (_curTab == null)
8836 this.toolStripApiGauge.ApiEndpoint = null;
8840 var tabType = _statuses.Tabs[_curTab.Text].TabType;
8842 if (endpointName == null)
8847 case MyCommon.TabUsageType.Home:
8848 case MyCommon.TabUsageType.UserDefined:
8849 endpointName = "/statuses/home_timeline";
8852 case MyCommon.TabUsageType.Mentions:
8853 endpointName = "/statuses/mentions_timeline";
8856 case MyCommon.TabUsageType.Favorites:
8857 endpointName = "/favorites/list";
8860 case MyCommon.TabUsageType.DirectMessage:
8861 endpointName = "/direct_messages";
8864 case MyCommon.TabUsageType.UserTimeline:
8865 endpointName = "/statuses/user_timeline";
8868 case MyCommon.TabUsageType.Lists:
8869 endpointName = "/lists/statuses";
8872 case MyCommon.TabUsageType.PublicSearch:
8873 endpointName = "/search/tweets";
8876 case MyCommon.TabUsageType.Related:
8877 endpointName = "/statuses/show/:id";
8884 this.toolStripApiGauge.ApiEndpoint = endpointName;
8888 // 表示中のタブに関連する endpoint であれば更新
8891 switch (endpointName)
8893 case "/statuses/home_timeline":
8894 update = tabType == MyCommon.TabUsageType.Home ||
8895 tabType == MyCommon.TabUsageType.UserDefined;
8898 case "/statuses/mentions_timeline":
8899 update = tabType == MyCommon.TabUsageType.Mentions;
8902 case "/favorites/list":
8903 update = tabType == MyCommon.TabUsageType.Favorites;
8906 case "/direct_messages:":
8907 update = tabType == MyCommon.TabUsageType.DirectMessage;
8910 case "/statuses/user_timeline":
8911 update = tabType == MyCommon.TabUsageType.UserTimeline;
8914 case "/lists/statuses":
8915 update = tabType == MyCommon.TabUsageType.Lists;
8918 case "/search/tweets":
8919 update = tabType == MyCommon.TabUsageType.PublicSearch;
8922 case "/statuses/show/:id":
8923 update = tabType == MyCommon.TabUsageType.Related;
8932 this.toolStripApiGauge.ApiEndpoint = endpointName;
8938 private void SetStatusLabelUrl()
8940 StatusLabelUrl.Text = GetStatusLabelText();
8943 public void SetStatusLabel(string text)
8945 StatusLabel.Text = text;
8948 private void SetNotifyIconText()
8950 var ur = new StringBuilder(64);
8952 // タスクトレイアイコンのツールチップテキスト書き換え
8954 ur.Remove(0, ur.Length);
8955 if (SettingManager.Common.DispUsername)
8957 ur.Append(tw.Username);
8960 ur.Append(Application.ProductName);
8962 ur.Append("(Debug Build)");
8964 if (UnreadCounter != -1 && UnreadAtCounter != -1)
8967 ur.Append(UnreadCounter);
8969 ur.Append(UnreadAtCounter);
8972 NotifyIcon1.Text = ur.ToString();
8975 internal void CheckReplyTo(string StatusText)
8979 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
8981 foreach (Match hm in m)
8983 if (!hstr.Contains("#" + hm.Result("$3") + " "))
8985 hstr += "#" + hm.Result("$3") + " ";
8986 HashSupl.AddItem("#" + hm.Result("$3"));
8989 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
8991 hstr += HashMgr.UseHash;
8993 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
8995 // 本当にリプライ先指定すべきかどうかの判定
8996 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
8998 if (SettingManager.Common.UseAtIdSupplement)
9000 int bCnt = AtIdSupl.ItemCount;
9001 foreach (Match mid in m)
9003 AtIdSupl.AddItem(mid.Result("${id}"));
9005 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9008 // リプライ先ステータスIDの指定がない場合は指定しない
9009 if (this.inReplyTo == null)
9013 // 次の条件を満たす場合に in_reply_to_status_id 指定
9014 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9015 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9016 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9020 var inReplyToScreenName = this.inReplyTo.Item2;
9021 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9023 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9027 foreach (Match mid in m)
9029 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9034 this.inReplyTo = null;
9037 private void TweenMain_Resize(object sender, EventArgs e)
9039 if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
9041 this.Visible = false;
9043 if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
9045 // 現在の DPI と設定保存時の DPI との比を取得する
9046 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9048 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
9051 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
9052 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9053 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9055 this.SplitContainer1.SplitterDistance = splitterDistance;
9059 StatusText.Multiline = SettingManager.Local.StatusMultiline;
9060 if (StatusText.Multiline)
9062 var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
9063 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9064 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9066 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9068 StatusText.Height = statusTextHeight;
9072 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9074 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9078 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
9079 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9081 this.SplitContainer3.SplitterDistance = previewDistance;
9084 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9085 this.SplitContainer3.Panel2Collapsed = true;
9087 _initialLayout = false;
9089 if (this.WindowState != FormWindowState.Minimized)
9091 _formWindowState = this.WindowState;
9095 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9097 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9098 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9099 if (PlaySoundMenuItem.Checked)
9101 SettingManager.Common.PlaySound = true;
9105 SettingManager.Common.PlaySound = false;
9107 ModifySettingCommon = true;
9110 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9112 if (this._initialLayout)
9115 int splitterDistance;
9116 switch (this.WindowState)
9118 case FormWindowState.Normal:
9119 splitterDistance = this.SplitContainer1.SplitterDistance;
9121 case FormWindowState.Maximized:
9122 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9123 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9124 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9125 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9131 this._mySpDis = splitterDistance;
9132 this.ModifySettingLocal = true;
9135 private async Task doRepliedStatusOpen()
9137 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9139 if (MyCommon.IsKeyDown(Keys.Shift))
9141 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9144 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9146 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9147 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9151 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9153 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9154 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9155 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9158 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9163 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9165 await this.doRepliedStatusOpen();
9168 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9170 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9171 if (multiline != this.StatusText.Multiline)
9173 this.StatusText.Multiline = multiline;
9174 SettingManager.Local.StatusMultiline = multiline;
9175 ModifySettingLocal = true;
9179 private void StatusText_MultilineChanged(object sender, EventArgs e)
9181 if (this.StatusText.Multiline)
9182 this.StatusText.ScrollBars = ScrollBars.Vertical;
9184 this.StatusText.ScrollBars = ScrollBars.None;
9186 ModifySettingLocal = true;
9189 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9192 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
9193 StatusText.Multiline = menuItemChecked;
9194 SettingManager.Local.StatusMultiline = menuItemChecked;
9195 if (menuItemChecked)
9197 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9198 SplitContainer2.SplitterDistance = 0;
9200 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9204 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9206 ModifySettingLocal = true;
9209 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9211 if (Converter_Type == MyCommon.UrlConverter.Bitly || Converter_Type == MyCommon.UrlConverter.Jmp)
9213 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
9214 if (string.IsNullOrEmpty(SettingManager.Common.BitlyAccessToken) &&
9215 (string.IsNullOrEmpty(SettingManager.Common.BilyUser) || string.IsNullOrEmpty(SettingManager.Common.BitlyPwd)))
9217 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
9222 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9223 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9225 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9226 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9227 //Appendix A. Collected ABNF for URI
9228 //http://www.ietf.org/rfc/rfc3986.txt
9232 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9234 if (StatusText.SelectionLength > 0)
9236 string tmp = StatusText.SelectedText;
9237 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9238 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9240 // 文字列が選択されている場合はその文字列について処理
9242 //nico.ms使用、nicovideoにマッチしたら変換
9243 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9245 result = nicoms.Shorten(tmp);
9247 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9249 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9252 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9253 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9254 result = resultUri.AbsoluteUri;
9256 catch (WebApiException e)
9258 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9261 catch (UriFormatException e)
9263 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9272 if (!string.IsNullOrEmpty(result))
9274 urlUndo undotmp = new urlUndo();
9276 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9277 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9278 if (origUrlIndex == -1)
9281 StatusText.Select(origUrlIndex, tmp.Length);
9282 StatusText.SelectedText = result;
9285 undotmp.Before = tmp;
9286 undotmp.After = result;
9288 if (urlUndoBuffer == null)
9290 urlUndoBuffer = new List<urlUndo>();
9291 UrlUndoToolStripMenuItem.Enabled = true;
9294 urlUndoBuffer.Add(undotmp);
9300 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9301 @"(?<url>(?<protocol>https?://)" +
9302 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9303 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9304 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9305 // 正規表現にマッチしたURL文字列をtinyurl化
9306 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9308 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9309 string tmp = mt.Result("${url}");
9310 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9311 urlUndo undotmp = new urlUndo();
9314 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9316 //nico.ms使用、nicovideoにマッチしたら変換
9317 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9319 result = nicoms.Shorten(tmp);
9321 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9323 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9326 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9327 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9328 result = resultUri.AbsoluteUri;
9330 catch (HttpRequestException e)
9332 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9333 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9334 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9336 this.StatusLabel.Text = Converter_Type + ":" + message;
9339 catch (WebApiException e)
9341 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9344 catch (UriFormatException e)
9346 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9355 if (!string.IsNullOrEmpty(result))
9357 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9358 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9359 if (origUrlIndex == -1)
9362 StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9363 StatusText.SelectedText = result;
9365 undotmp.Before = mt.Result("${url}");
9366 undotmp.After = result;
9368 if (urlUndoBuffer == null)
9370 urlUndoBuffer = new List<urlUndo>();
9371 UrlUndoToolStripMenuItem.Enabled = true;
9374 urlUndoBuffer.Add(undotmp);
9382 private void doUrlUndo()
9384 if (urlUndoBuffer != null)
9386 string tmp = StatusText.Text;
9387 foreach (urlUndo data in urlUndoBuffer)
9389 tmp = tmp.Replace(data.After, data.Before);
9391 StatusText.Text = tmp;
9392 urlUndoBuffer = null;
9393 UrlUndoToolStripMenuItem.Enabled = false;
9394 StatusText.SelectionStart = 0;
9395 StatusText.SelectionLength = 0;
9399 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9401 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9404 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9406 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9409 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9411 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9414 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9416 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9419 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9421 if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9423 MyCommon.UrlConverter svc = SettingManager.Common.AutoShortUrlFirst;
9424 Random rnd = new Random();
9425 // 前回使用した短縮URLサービス以外を選択する
9428 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9430 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9431 await UrlConvertAsync(svc);
9435 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9440 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9442 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9443 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9444 SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9445 ModifySettingCommon = true;
9448 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9450 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9451 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9452 SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9453 ModifySettingCommon = true;
9456 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9458 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9459 MenuStrip1.Tag = new Object();
9460 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9463 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9465 if (this.Tag != null) // 設定された戻り先へ遷移
9467 if (this.Tag == this.ListTab.SelectedTab)
9468 ((Control)this.ListTab.SelectedTab.Tag).Select();
9470 ((Control)this.Tag).Select();
9472 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9474 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9476 this.Tag = ListTab.SelectedTab.Tag;
9477 ((Control)this.Tag).Select();
9480 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9481 MenuStrip1.Tag = null;
9484 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9486 DetailsListView lst = (DetailsListView)sender;
9487 if (SettingManager.Local == null) return;
9491 SettingManager.Local.Width1 = lst.Columns[0].Width;
9492 SettingManager.Local.Width3 = lst.Columns[1].Width;
9496 int[] darr = new int[lst.Columns.Count];
9497 for (int i = 0; i < lst.Columns.Count; i++)
9499 darr[lst.Columns[i].DisplayIndex] = i;
9501 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9503 for (int i = 0; i < lst.Columns.Count; i++)
9508 SettingManager.Local.DisplayIndex1 = i;
9511 SettingManager.Local.DisplayIndex2 = i;
9514 SettingManager.Local.DisplayIndex3 = i;
9517 SettingManager.Local.DisplayIndex4 = i;
9520 SettingManager.Local.DisplayIndex5 = i;
9523 SettingManager.Local.DisplayIndex6 = i;
9526 SettingManager.Local.DisplayIndex7 = i;
9529 SettingManager.Local.DisplayIndex8 = i;
9533 SettingManager.Local.Width1 = lst.Columns[0].Width;
9534 SettingManager.Local.Width2 = lst.Columns[1].Width;
9535 SettingManager.Local.Width3 = lst.Columns[2].Width;
9536 SettingManager.Local.Width4 = lst.Columns[3].Width;
9537 SettingManager.Local.Width5 = lst.Columns[4].Width;
9538 SettingManager.Local.Width6 = lst.Columns[5].Width;
9539 SettingManager.Local.Width7 = lst.Columns[6].Width;
9540 SettingManager.Local.Width8 = lst.Columns[7].Width;
9542 ModifySettingLocal = true;
9543 _isColumnChanged = true;
9546 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9548 DetailsListView lst = (DetailsListView)sender;
9549 if (SettingManager.Local == null) return;
9552 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9554 SettingManager.Local.Width1 = lst.Columns[0].Width;
9555 ModifySettingLocal = true;
9556 _isColumnChanged = true;
9558 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9560 SettingManager.Local.Width3 = lst.Columns[1].Width;
9561 ModifySettingLocal = true;
9562 _isColumnChanged = true;
9567 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9569 SettingManager.Local.Width1 = lst.Columns[0].Width;
9570 ModifySettingLocal = true;
9571 _isColumnChanged = true;
9573 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9575 SettingManager.Local.Width2 = lst.Columns[1].Width;
9576 ModifySettingLocal = true;
9577 _isColumnChanged = true;
9579 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9581 SettingManager.Local.Width3 = lst.Columns[2].Width;
9582 ModifySettingLocal = true;
9583 _isColumnChanged = true;
9585 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9587 SettingManager.Local.Width4 = lst.Columns[3].Width;
9588 ModifySettingLocal = true;
9589 _isColumnChanged = true;
9591 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9593 SettingManager.Local.Width5 = lst.Columns[4].Width;
9594 ModifySettingLocal = true;
9595 _isColumnChanged = true;
9597 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9599 SettingManager.Local.Width6 = lst.Columns[5].Width;
9600 ModifySettingLocal = true;
9601 _isColumnChanged = true;
9603 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9605 SettingManager.Local.Width7 = lst.Columns[6].Width;
9606 ModifySettingLocal = true;
9607 _isColumnChanged = true;
9609 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9611 SettingManager.Local.Width8 = lst.Columns[7].Width;
9612 ModifySettingLocal = true;
9613 _isColumnChanged = true;
9616 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9619 // SaveConfigsLocal();
9623 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9625 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9626 ModifySettingLocal = true;
9629 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9631 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9633 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9635 SelectMedia_DragDrop(e);
9638 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9640 var (url, title) = GetUrlFromDataObject(e.Data);
9646 appendText = title + " " + url;
9648 if (this.StatusText.TextLength == 0)
9649 this.StatusText.Text = appendText;
9651 this.StatusText.Text += " " + appendText;
9653 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9655 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9657 this.StatusText.Text += text;
9659 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9661 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9662 if (data != null) StatusText.Text += data;
9667 /// IDataObject から URL とタイトルの対を取得します
9670 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9672 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9673 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9674 internal static (string Url, string Title) GetUrlFromDataObject(IDataObject data)
9676 if (data.GetDataPresent("text/x-moz-url"))
9678 // Firefox, Google Chrome で利用可能
9679 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9681 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9683 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9684 if (lines.Length < 2)
9685 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9687 return (lines[0], lines[1]);
9690 else if (data.GetDataPresent("IESiteModeToUrl"))
9692 // Internet Exproler 用
9693 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9695 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9697 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9698 if (lines.Length < 2)
9699 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9701 return (lines[0], lines[1]);
9704 else if (data.GetDataPresent("UniformResourceLocatorW"))
9708 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9710 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9715 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9718 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9720 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9722 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9724 SelectMedia_DragEnter(e);
9728 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9730 e.Effect = DragDropEffects.Copy;
9733 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9735 e.Effect = DragDropEffects.Copy;
9738 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9740 e.Effect = DragDropEffects.Copy;
9744 e.Effect = DragDropEffects.None;
9747 private void TweenMain_DragOver(object sender, DragEventArgs e)
9751 public bool IsNetworkAvailable()
9754 nw = MyCommon.IsNetworkAvailable();
9755 _myStatusOnline = nw;
9759 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9761 var uriStr = uri.AbsoluteUri;
9763 // OpenTween 内部で使用する URL
9764 if (uri.Authority == "opentween")
9766 await this.OpenInternalUriAsync(uri);
9770 // ハッシュタグを含む Twitter 検索
9771 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9774 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9775 var pos = unescapedQuery.IndexOf('#');
9776 if (pos == -1) return;
9778 var hash = unescapedQuery.Substring(pos);
9779 this.HashSupl.AddItem(hash);
9780 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9781 this.AddNewTabForSearch(hash);
9786 // フラグが立っている場合は設定と逆の動作をする
9787 if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9788 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9790 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9791 if (userUriMatch.Success)
9793 var screenName = userUriMatch.Groups["ScreenName"].Value;
9794 if (this.IsTwitterId(screenName))
9796 this.AddNewTabForUserTimeline(screenName);
9803 await this.OpenUriInBrowserAsync(uriStr);
9807 /// OpenTween 内部の機能を呼び出すための URL を開きます
9809 private async Task OpenInternalUriAsync(Uri uri)
9811 // ツイートを開く (//opentween/status/:status_id)
9812 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9815 var statusId = long.Parse(match.Groups[1].Value);
9816 await this.OpenRelatedTab(statusId);
9821 public Task OpenUriInBrowserAsync(string UriString)
9823 return Task.Run(() =>
9825 string myPath = UriString;
9829 var configBrowserPath = SettingManager.Local.BrowserPath;
9830 if (!string.IsNullOrEmpty(configBrowserPath))
9832 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9834 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9835 string browserPath = configBrowserPath.Substring(1, sep - 1);
9837 if (sep < configBrowserPath.Length - 1)
9839 arg = configBrowserPath.Substring(sep + 1);
9841 myPath = arg + " " + myPath;
9842 System.Diagnostics.Process.Start(browserPath, myPath);
9846 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9851 System.Diagnostics.Process.Start(myPath);
9856 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9861 private void ListTabSelect(TabPage _tab)
9865 this.PurgeListViewItemCache();
9868 _curList = (DetailsListView)_tab.Tag;
9870 if (_curList.SelectedIndices.Count > 0)
9872 _curItemIndex = _curList.SelectedIndices[0];
9873 _curPost = GetCurTabPost(_curItemIndex);
9882 _anchorFlag = false;
9886 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
9890 for (int i = 0; i < _curList.Columns.Count; i++)
9892 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
9897 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9899 ListTabSelect(e.TabPage);
9902 private void SelectListItem(DetailsListView LView, int Index)
9905 Rectangle bnd = new Rectangle();
9907 var item = LView.FocusedItem;
9916 LView.SelectedIndices.Clear();
9918 while (LView.SelectedIndices.Count > 0);
9919 item = LView.Items[Index];
9920 item.Selected = true;
9921 item.Focused = true;
9923 if (flg) LView.Invalidate(bnd);
9926 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9929 Rectangle bnd = new Rectangle();
9931 var item = LView.FocusedItem;
9942 LView.SelectedIndices.Clear();
9944 while (LView.SelectedIndices.Count > 0);
9945 LView.SelectItems(Index);
9947 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9949 LView.SelectionMark = selectionMarkIndex;
9951 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9953 LView.Items[focusedIndex].Focused = true;
9955 else if (Index != null && Index.Length != 0)
9957 LView.Items[Index.Last()].Focused = true;
9960 if (flg) LView.Invalidate(bnd);
9963 private void StartUserStream()
9965 tw.NewPostFromStream += tw_NewPostFromStream;
9966 tw.UserStreamStarted += tw_UserStreamStarted;
9967 tw.UserStreamStopped += tw_UserStreamStopped;
9968 tw.PostDeleted += tw_PostDeleted;
9969 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9971 this.RefreshUserStreamsMenu();
9973 if (SettingManager.Common.UserstreamStartup)
9974 tw.StartUserStream();
9977 private async void TweenMain_Shown(object sender, EventArgs e)
9979 NotifyIcon1.Visible = true;
9981 if (this.IsNetworkAvailable())
9985 var loadTasks = new List<Task>
9987 this.RefreshMuteUserIdsAsync(),
9988 this.RefreshBlockIdsAsync(),
9989 this.RefreshNoRetweetIdsAsync(),
9990 this.RefreshTwitterConfigurationAsync(),
9991 this.GetHomeTimelineAsync(),
9992 this.GetReplyAsync(),
9993 this.GetDirectMessagesAsync(),
9994 this.GetPublicSearchAllAsync(),
9995 this.GetUserTimelineAllAsync(),
9996 this.GetListTimelineAllAsync(),
9999 if (SettingManager.Common.StartupFollowers)
10000 loadTasks.Add(this.RefreshFollowerIdsAsync());
10002 if (SettingManager.Common.GetFav)
10003 loadTasks.Add(this.GetFavoritesAsync());
10005 var allTasks = Task.WhenAll(loadTasks);
10010 var timeout = Task.Delay(5000);
10011 if (await Task.WhenAny(allTasks, timeout) != timeout)
10015 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10017 if (MyCommon._endingFlag)
10021 if (MyCommon._endingFlag) return;
10023 if (ApplicationSettings.VersionInfoUrl != null)
10025 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10026 if (SettingManager.Common.StartupVersion)
10027 await this.CheckNewVersion(true);
10031 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10032 this.VerUpMenuItem.Enabled = false;
10033 this.VerUpMenuItem.Available = false;
10034 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10037 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10038 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10040 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10041 SettingStripMenuItem_Click(null, null);
10045 var reloadTasks = new List<Task>();
10047 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
10048 reloadTasks.Add(this.RefreshFollowerIdsAsync());
10050 if (!tw.GetNoRetweetSuccess)
10051 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10053 if (this.tw.Configuration.PhotoSizeLimit == 0)
10054 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10056 await Task.WhenAll(reloadTasks);
10061 TimerTimeline.Enabled = true;
10064 private async Task doGetFollowersMenu()
10066 await this.RefreshFollowerIdsAsync();
10067 await this.DispSelectedPost(true);
10070 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10072 await this.doGetFollowersMenu();
10075 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10077 doReTweetUnofficial();
10080 private async Task doReTweetOfficial(bool isConfirm)
10083 if (this.ExistCurrentPost)
10085 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10087 if (this._curPost.IsProtect)
10088 MessageBox.Show("Protected.");
10090 _DoFavRetweetFlags = false;
10093 if (_curList.SelectedIndices.Count > 15)
10095 MessageBox.Show(Properties.Resources.RetweetLimitText);
10096 _DoFavRetweetFlags = false;
10099 else if (_curList.SelectedIndices.Count > 1)
10101 string QuestionText = Properties.Resources.RetweetQuestion2;
10102 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10103 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10105 case DialogResult.Cancel:
10106 case DialogResult.No:
10107 _DoFavRetweetFlags = false;
10113 if (!SettingManager.Common.RetweetNoConfirm)
10115 string Questiontext = Properties.Resources.RetweetQuestion1;
10116 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10117 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10119 _DoFavRetweetFlags = false;
10125 var statusIds = new List<long>();
10126 foreach (int idx in _curList.SelectedIndices)
10128 PostClass post = GetCurTabPost(idx);
10129 if (post.CanRetweetBy(this.twitterApi.CurrentUserId))
10130 statusIds.Add(post.StatusId);
10133 await this.RetweetAsync(statusIds);
10137 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10139 await this.doReTweetOfficial(true);
10142 private async Task FavoritesRetweetOfficial()
10144 if (!this.ExistCurrentPost) return;
10145 _DoFavRetweetFlags = true;
10146 var retweetTask = this.doReTweetOfficial(true);
10147 if (_DoFavRetweetFlags)
10149 _DoFavRetweetFlags = false;
10150 var favoriteTask = this.FavoriteChange(true, false);
10152 await Task.WhenAll(retweetTask, favoriteTask);
10160 private async Task FavoritesRetweetUnofficial()
10162 if (this.ExistCurrentPost && !_curPost.IsDm)
10164 _DoFavRetweetFlags = true;
10165 var favoriteTask = this.FavoriteChange(true);
10166 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10168 _DoFavRetweetFlags = false;
10169 doReTweetUnofficial();
10172 await favoriteTask;
10177 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10179 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10180 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10181 /// <returns>復元されたツイート本文</returns>
10182 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10184 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10187 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10189 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10191 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10195 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10197 statusHtml = statusHtml.Replace("<br>", " ");
10199 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10200 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10201 statusHtml = statusHtml.Replace(" ", " ");
10203 return WebUtility.HtmlDecode(statusHtml);
10206 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10208 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10210 if (_curPost != null)
10211 await this.DispSelectedPost(true);
10214 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10216 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10217 DebugModeToolStripMenuItem.Visible = true;
10219 DebugModeToolStripMenuItem.Visible = false;
10222 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
10224 this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
10227 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
10229 this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
10232 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
10234 SettingManager.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
10237 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
10239 SettingManager.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
10240 ModifySettingCommon = true;
10243 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10245 SettingManager.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
10246 ModifySettingCommon = true;
10249 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
10251 UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
10252 PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
10253 UrlAutoShortenMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10254 IdeographicSpaceToSpaceMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10255 MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
10256 FocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10259 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10261 UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
10262 PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
10263 UrlAutoShortenPullDownMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10264 IdeographicSpaceToSpacePullDownMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10265 MultiLinePullDownMenuItem.Checked = SettingManager.Local.StatusMultiline;
10266 FocusLockPullDownMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10269 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10271 if (TraceOutToolStripMenuItem.Checked)
10272 MyCommon.TraceFlag = true;
10274 MyCommon.TraceFlag = false;
10277 private void TweenMain_Deactivate(object sender, EventArgs e)
10279 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10280 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10283 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10285 if (string.IsNullOrEmpty(_rclickTabName)) return;
10287 TabRename(_rclickTabName, out var _);
10290 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10292 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10295 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10297 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10300 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10302 TwitterApiStatus apiStatus;
10304 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10306 var cancellationToken = dialog.EnableCancellation();
10310 var task = this.tw.GetInfoApi();
10311 apiStatus = await dialog.WaitForAsync(this, task);
10313 catch (WebApiException)
10318 if (cancellationToken.IsCancellationRequested)
10321 if (apiStatus == null)
10323 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10328 using (var apiDlg = new ApiInfoDialog())
10330 apiDlg.ShowDialog(this);
10334 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10336 var id = _curPost?.ScreenName ?? "";
10338 await this.FollowCommand(id);
10341 internal async Task FollowCommand(string id)
10343 using (var inputName = new InputTabName())
10345 inputName.FormTitle = "Follow";
10346 inputName.FormDescription = Properties.Resources.FRMessage1;
10347 inputName.TabName = id;
10349 if (inputName.ShowDialog(this) != DialogResult.OK)
10351 if (string.IsNullOrWhiteSpace(inputName.TabName))
10354 id = inputName.TabName.Trim();
10357 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10361 var task = this.twitterApi.FriendshipsCreate(id).IgnoreResponse();
10362 await dialog.WaitForAsync(this, task);
10364 catch (WebApiException ex)
10366 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10371 MessageBox.Show(Properties.Resources.FRMessage3);
10374 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10376 var id = _curPost?.ScreenName ?? "";
10378 await this.RemoveCommand(id, false);
10381 internal async Task RemoveCommand(string id, bool skipInput)
10385 using (var inputName = new InputTabName())
10387 inputName.FormTitle = "Unfollow";
10388 inputName.FormDescription = Properties.Resources.FRMessage1;
10389 inputName.TabName = id;
10391 if (inputName.ShowDialog(this) != DialogResult.OK)
10393 if (string.IsNullOrWhiteSpace(inputName.TabName))
10396 id = inputName.TabName.Trim();
10400 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10404 var task = this.twitterApi.FriendshipsDestroy(id).IgnoreResponse();
10405 await dialog.WaitForAsync(this, task);
10407 catch (WebApiException ex)
10409 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10414 MessageBox.Show(Properties.Resources.FRMessage3);
10417 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10419 var id = _curPost?.ScreenName ?? "";
10421 await this.ShowFriendship(id);
10424 internal async Task ShowFriendship(string id)
10426 using (var inputName = new InputTabName())
10428 inputName.FormTitle = "Show Friendships";
10429 inputName.FormDescription = Properties.Resources.FRMessage1;
10430 inputName.TabName = id;
10432 if (inputName.ShowDialog(this) != DialogResult.OK)
10434 if (string.IsNullOrWhiteSpace(inputName.TabName))
10437 id = inputName.TabName.Trim();
10440 bool isFollowing, isFollowed;
10442 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10444 var cancellationToken = dialog.EnableCancellation();
10448 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10449 var friendship = await dialog.WaitForAsync(this, task);
10451 isFollowing = friendship.Relationship.Source.Following;
10452 isFollowed = friendship.Relationship.Source.FollowedBy;
10454 catch (WebApiException ex)
10456 if (!cancellationToken.IsCancellationRequested)
10457 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10461 if (cancellationToken.IsCancellationRequested)
10465 string result = "";
10468 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10472 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10476 result += Properties.Resources.GetFriendshipInfo3;
10480 result += Properties.Resources.GetFriendshipInfo4;
10482 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10483 MessageBox.Show(result);
10486 internal async Task ShowFriendship(string[] ids)
10488 foreach (string id in ids)
10490 bool isFollowing, isFollowed;
10492 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10494 var cancellationToken = dialog.EnableCancellation();
10498 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10499 var friendship = await dialog.WaitForAsync(this, task);
10501 isFollowing = friendship.Relationship.Source.Following;
10502 isFollowed = friendship.Relationship.Source.FollowedBy;
10504 catch (WebApiException ex)
10506 if (!cancellationToken.IsCancellationRequested)
10507 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10511 if (cancellationToken.IsCancellationRequested)
10515 string result = "";
10521 ff += Properties.Resources.GetFriendshipInfo1;
10525 ff += Properties.Resources.GetFriendshipInfo2;
10528 ff += System.Environment.NewLine + " ";
10531 ff += Properties.Resources.GetFriendshipInfo3;
10535 ff += Properties.Resources.GetFriendshipInfo4;
10537 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10540 if (MessageBox.Show(
10541 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10542 MessageBoxButtons.YesNo,
10543 MessageBoxIcon.Question,
10544 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10546 await this.RemoveCommand(id, true);
10551 MessageBox.Show(result);
10556 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10558 await this.doShowUserStatus(tw.Username, false);
10559 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
10561 // doShowUserStatus(tw.Username, false);
10565 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
10570 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10571 // URLから切り出した文字列を渡す
10573 public bool IsTwitterId(string name)
10575 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10576 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10578 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
10581 private void doQuoteOfficial()
10583 if (this.ExistCurrentPost)
10585 if (_curPost.IsDm ||
10586 !StatusText.Enabled) return;
10588 if (_curPost.IsProtect)
10590 MessageBox.Show("Protected.");
10594 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10596 StatusText.Text += " " + MyCommon.GetStatusUrl(_curPost);
10598 this.inReplyTo = null;
10600 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10601 StatusText.Focus();
10605 private void doReTweetUnofficial()
10608 if (this.ExistCurrentPost)
10610 if (_curPost.IsDm || !StatusText.Enabled)
10613 if (_curPost.IsProtect)
10615 MessageBox.Show("Protected.");
10618 string rtdata = _curPost.Text;
10619 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10621 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10623 StatusText.Text += " RT @" + _curPost.ScreenName + ": " + rtdata;
10625 // 投稿時に in_reply_to_status_id を付加する
10626 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
10627 var inReplyToScreenName = this._curPost.ScreenName;
10628 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
10630 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10631 StatusText.Focus();
10635 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
10640 private void SearchButton_Click(object sender, EventArgs e)
10643 Control pnl = ((Control)sender).Parent;
10644 if (pnl == null) return;
10645 string tbName = pnl.Parent.Text;
10646 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10647 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10648 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10649 cmb.Text = cmb.Text.Trim();
10650 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10651 bool Quote = false;
10652 StringBuilder buf = new StringBuilder();
10653 char[] c = cmb.Text.ToCharArray();
10654 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10656 if (cnt > cmb.Text.Length - 4)
10658 buf.Append(cmb.Text.Substring(cnt));
10667 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10669 buf.Append(" OR ");
10674 buf.Append(c[cnt]);
10676 cmb.Text = buf.ToString();
10678 var listView = (DetailsListView)pnl.Parent.Tag;
10680 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10682 tb.SearchWords = cmb.Text;
10683 tb.SearchLang = cmbLang.Text;
10684 if (string.IsNullOrEmpty(cmb.Text))
10692 int idx = cmb.Items.IndexOf(tb.SearchWords);
10693 if (idx > -1) cmb.Items.RemoveAt(idx);
10694 cmb.Items.Insert(0, tb.SearchWords);
10695 cmb.Text = tb.SearchWords;
10697 this.PurgeListViewItemCache();
10698 listView.VirtualListSize = 0;
10699 _statuses.ClearTabIds(tbName);
10700 SaveConfigsTabs(); //検索条件の保存
10703 this.GetPublicSearchAsync(tb);
10707 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10710 await this.DoRefreshMore();
10714 /// 指定されたタブのListTabにおける位置を返します
10717 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10719 public int GetTabPageIndex(string tabName)
10722 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
10724 if (tabPage.Text == tabName)
10733 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10735 if (_statuses.RemovedTab.Count == 0)
10737 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10742 DetailsListView listView = null;
10744 TabModel tb = _statuses.RemovedTab.Pop();
10745 if (tb.TabType == MyCommon.TabUsageType.Related)
10747 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10748 if (relatedTab != null)
10750 // 関連発言なら既存のタブを置き換える
10751 tb.TabName = relatedTab.TabName;
10752 this.ClearTab(tb.TabName, false);
10753 _statuses.Tabs[tb.TabName] = tb;
10755 for (int i = 0; i < ListTab.TabPages.Count; i++)
10757 var tabPage = ListTab.TabPages[i];
10758 if (tb.TabName == tabPage.Text)
10760 listView = (DetailsListView)tabPage.Tag;
10761 ListTab.SelectedIndex = i;
10768 const string TabName = "Related Tweets";
10769 string renamed = TabName;
10770 for (int i = 2; i <= 100; i++)
10772 if (!_statuses.ContainsTab(renamed)) break;
10773 renamed = TabName + i;
10775 tb.TabName = renamed;
10777 _statuses.AddTab(tb);
10778 AddNewTab(tb, startup: false);
10780 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10781 listView = (DetailsListView)tabPage.Tag;
10782 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10787 string renamed = tb.TabName;
10788 for (int i = 1; i < int.MaxValue; i++)
10790 if (!_statuses.ContainsTab(renamed)) break;
10791 renamed = tb.TabName + "(" + i + ")";
10793 tb.TabName = renamed;
10795 _statuses.AddTab(tb);
10796 AddNewTab(tb, startup: false);
10798 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10799 listView = (DetailsListView)tabPage.Tag;
10800 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10804 if (listView != null)
10806 using (ControlTransaction.Update(listView))
10808 listView.VirtualListSize = tb.AllCount;
10814 private async Task doMoveToRTHome()
10816 if (_curList.SelectedIndices.Count > 0)
10818 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
10819 if (post.RetweetedId != null)
10821 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
10826 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10828 await this.doMoveToRTHome();
10831 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10833 var screenName = this._curPost?.ScreenName;
10834 if (screenName != null)
10835 this.ListManageUserContext(screenName);
10838 public void ListManageUserContext(string screenName)
10840 using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10842 listSelectForm.ShowDialog(this);
10846 private void SearchControls_Enter(object sender, EventArgs e)
10848 Control pnl = (Control)sender;
10849 foreach (Control ctl in pnl.Controls)
10851 ctl.TabStop = true;
10855 private void SearchControls_Leave(object sender, EventArgs e)
10857 Control pnl = (Control)sender;
10858 foreach (Control ctl in pnl.Controls)
10860 ctl.TabStop = false;
10864 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10866 if (ListTab.SelectedTab != null)
10868 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
10869 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
10873 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10875 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10878 private void HashManageMenuItem_Click(object sender, EventArgs e)
10880 DialogResult rslt = DialogResult.Cancel;
10883 rslt = HashMgr.ShowDialog();
10889 this.TopMost = SettingManager.Common.AlwaysTop;
10890 if (rslt == DialogResult.Cancel) return;
10891 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10893 HashStripSplitButton.Text = HashMgr.UseHash;
10894 HashTogglePullDownMenuItem.Checked = true;
10895 HashToggleMenuItem.Checked = true;
10899 HashStripSplitButton.Text = "#[-]";
10900 HashTogglePullDownMenuItem.Checked = false;
10901 HashToggleMenuItem.Checked = false;
10903 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10905 // int sidx = StatusText.SelectionStart;
10906 // string hash = HashMgr.UseHash + " ";
10909 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10910 // hash = " " + hash;
10912 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
10913 // sidx += hash.Length;
10914 // StatusText.SelectionStart = sidx;
10915 // StatusText.Focus();
10917 ModifySettingCommon = true;
10918 this.StatusText_TextChanged(null, null);
10921 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10923 HashMgr.ToggleHash();
10924 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10926 HashStripSplitButton.Text = HashMgr.UseHash;
10927 HashToggleMenuItem.Checked = true;
10928 HashTogglePullDownMenuItem.Checked = true;
10932 HashStripSplitButton.Text = "#[-]";
10933 HashToggleMenuItem.Checked = false;
10934 HashTogglePullDownMenuItem.Checked = false;
10936 ModifySettingCommon = true;
10937 this.StatusText_TextChanged(null, null);
10940 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10942 HashToggleMenuItem_Click(null, null);
10945 public void SetPermanentHashtag(string hashtag)
10947 HashMgr.SetPermanentHash("#" + hashtag);
10948 HashStripSplitButton.Text = HashMgr.UseHash;
10949 HashTogglePullDownMenuItem.Checked = true;
10950 HashToggleMenuItem.Checked = true;
10952 ModifySettingCommon = true;
10955 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10957 if (ListTab.SelectedTab == null) return;
10958 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
10959 if (!this.ExistCurrentPost)
10961 this.ReplyOpMenuItem.Enabled = false;
10962 this.ReplyAllOpMenuItem.Enabled = false;
10963 this.DmOpMenuItem.Enabled = false;
10964 this.ShowProfMenuItem.Enabled = false;
10965 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10966 this.ListManageMenuItem.Enabled = false;
10967 this.OpenFavOpMenuItem.Enabled = false;
10968 this.CreateTabRuleOpMenuItem.Enabled = false;
10969 this.CreateIdRuleOpMenuItem.Enabled = false;
10970 this.CreateSourceRuleOpMenuItem.Enabled = false;
10971 this.ReadOpMenuItem.Enabled = false;
10972 this.UnreadOpMenuItem.Enabled = false;
10976 this.ReplyOpMenuItem.Enabled = true;
10977 this.ReplyAllOpMenuItem.Enabled = true;
10978 this.DmOpMenuItem.Enabled = true;
10979 this.ShowProfMenuItem.Enabled = true;
10980 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10981 this.ListManageMenuItem.Enabled = true;
10982 this.OpenFavOpMenuItem.Enabled = true;
10983 this.CreateTabRuleOpMenuItem.Enabled = true;
10984 this.CreateIdRuleOpMenuItem.Enabled = true;
10985 this.CreateSourceRuleOpMenuItem.Enabled = true;
10986 this.ReadOpMenuItem.Enabled = true;
10987 this.UnreadOpMenuItem.Enabled = true;
10990 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
10992 this.FavOpMenuItem.Enabled = false;
10993 this.UnFavOpMenuItem.Enabled = false;
10994 this.OpenStatusOpMenuItem.Enabled = false;
10995 this.OpenFavotterOpMenuItem.Enabled = false;
10996 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10997 this.RtOpMenuItem.Enabled = false;
10998 this.RtUnOpMenuItem.Enabled = false;
10999 this.QtOpMenuItem.Enabled = false;
11000 this.FavoriteRetweetMenuItem.Enabled = false;
11001 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11005 this.FavOpMenuItem.Enabled = true;
11006 this.UnFavOpMenuItem.Enabled = true;
11007 this.OpenStatusOpMenuItem.Enabled = true;
11008 this.OpenFavotterOpMenuItem.Enabled = true;
11009 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
11011 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
11013 this.RtOpMenuItem.Enabled = false;
11014 this.RtUnOpMenuItem.Enabled = false;
11015 this.QtOpMenuItem.Enabled = false;
11016 this.FavoriteRetweetMenuItem.Enabled = false;
11017 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11021 this.RtOpMenuItem.Enabled = true;
11022 this.RtUnOpMenuItem.Enabled = true;
11023 this.QtOpMenuItem.Enabled = true;
11024 this.FavoriteRetweetMenuItem.Enabled = true;
11025 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11029 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11031 this.RefreshPrevOpMenuItem.Enabled = true;
11035 this.RefreshPrevOpMenuItem.Enabled = false;
11037 if (!this.ExistCurrentPost
11038 || _curPost.InReplyToStatusId == null)
11040 OpenRepSourceOpMenuItem.Enabled = false;
11044 OpenRepSourceOpMenuItem.Enabled = true;
11046 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11048 OpenRterHomeMenuItem.Enabled = false;
11052 OpenRterHomeMenuItem.Enabled = true;
11055 if (this.ExistCurrentPost)
11057 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11061 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11063 ContextMenuTabProperty_Opening(sender, null);
11066 public Twitter TwitterInstance
11071 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11073 if (this._initialLayout)
11076 int splitterDistance;
11077 switch (this.WindowState)
11079 case FormWindowState.Normal:
11080 splitterDistance = this.SplitContainer3.SplitterDistance;
11082 case FormWindowState.Maximized:
11083 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11084 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11085 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11086 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11092 this._mySpDis3 = splitterDistance;
11093 this.ModifySettingLocal = true;
11096 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11098 if (_statuses.RemovedTab.Count == 0)
11100 UndoRemoveTabMenuItem.Enabled = false;
11104 UndoRemoveTabMenuItem.Enabled = true;
11106 if (ListTab.SelectedTab != null)
11108 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11109 PublicSearchQueryMenuItem.Enabled = true;
11111 PublicSearchQueryMenuItem.Enabled = false;
11115 PublicSearchQueryMenuItem.Enabled = false;
11117 if (!this.ExistCurrentPost)
11119 this.CopySTOTMenuItem.Enabled = false;
11120 this.CopyURLMenuItem.Enabled = false;
11121 this.CopyUserIdStripMenuItem.Enabled = false;
11125 this.CopySTOTMenuItem.Enabled = true;
11126 this.CopyURLMenuItem.Enabled = true;
11127 this.CopyUserIdStripMenuItem.Enabled = true;
11128 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11129 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11133 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11135 SetNotifyIconText();
11138 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11140 var id = _curPost?.ScreenName ?? "";
11142 await this.ShowUserStatus(id);
11145 private async Task doShowUserStatus(string id, bool ShowInputDialog)
11147 TwitterUser user = null;
11149 if (ShowInputDialog)
11151 using (var inputName = new InputTabName())
11153 inputName.FormTitle = "Show UserStatus";
11154 inputName.FormDescription = Properties.Resources.FRMessage1;
11155 inputName.TabName = id;
11157 if (inputName.ShowDialog(this) != DialogResult.OK)
11159 if (string.IsNullOrWhiteSpace(inputName.TabName))
11162 id = inputName.TabName.Trim();
11166 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11168 var cancellationToken = dialog.EnableCancellation();
11172 var task = this.twitterApi.UsersShow(id);
11173 user = await dialog.WaitForAsync(this, task);
11175 catch (WebApiException ex)
11177 if (!cancellationToken.IsCancellationRequested)
11178 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11182 if (cancellationToken.IsCancellationRequested)
11186 await this.doShowUserStatus(user);
11189 private async Task doShowUserStatus(TwitterUser user)
11191 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
11193 var showUserTask = userDialog.ShowUserAsync(user);
11194 userDialog.ShowDialog(this);
11197 this.BringToFront();
11199 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11200 await showUserTask;
11204 internal Task ShowUserStatus(string id, bool ShowInputDialog)
11206 return this.doShowUserStatus(id, ShowInputDialog);
11209 internal Task ShowUserStatus(string id)
11211 return this.doShowUserStatus(id, true);
11214 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
11216 if (_curPost != null)
11218 await this.ShowUserStatus(_curPost.ScreenName, false);
11222 private async void RtCountMenuItem_Click(object sender, EventArgs e)
11224 if (!this.ExistCurrentPost)
11227 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11228 TwitterStatus status;
11230 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11232 var cancellationToken = dialog.EnableCancellation();
11236 var task = this.twitterApi.StatusesShow(statusId);
11237 status = await dialog.WaitForAsync(this, task);
11239 catch (WebApiException ex)
11241 if (!cancellationToken.IsCancellationRequested)
11242 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11246 if (cancellationToken.IsCancellationRequested)
11250 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11253 private HookGlobalHotkey _hookGlobalHotkey;
11256 _hookGlobalHotkey = new HookGlobalHotkey(this);
11258 // この呼び出しは、Windows フォーム デザイナで必要です。
11259 InitializeComponent();
11261 // InitializeComponent() 呼び出しの後で初期化を追加します。
11263 if (!this.DesignMode)
11265 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11266 this.StatusText.Dock = DockStyle.Fill;
11269 this.tweetDetailsView.Owner = this;
11271 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11272 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11273 this.gh.NotifyClicked += GrowlHelper_Callback;
11275 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11276 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11278 this.ImageSelector.Visible = false;
11279 this.ImageSelector.Enabled = false;
11280 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11282 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11284 this.ReplaceAppName();
11285 this.InitializeShortcuts();
11288 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11290 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11293 this.Visible = false;
11295 else if (Form.ActiveForm == null)
11297 this.Visible = true;
11298 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11300 this.BringToFront();
11301 this.StatusText.Focus();
11305 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11307 this.MultiLinePullDownMenuItem.PerformClick();
11310 public PostClass CurPost
11312 get { return _curPost; }
11316 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11318 if (ImageSelector.Visible)
11319 ImageSelector.EndSelection();
11321 ImageSelector.BeginSelection();
11324 private void SelectMedia_DragEnter(DragEventArgs e)
11326 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11328 e.Effect = DragDropEffects.Copy;
11331 e.Effect = DragDropEffects.None;
11334 private void SelectMedia_DragDrop(DragEventArgs e)
11337 this.BringToFront();
11338 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11339 StatusText.Focus();
11342 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11344 TimelinePanel.Visible = false;
11345 TimelinePanel.Enabled = false;
11348 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11350 TimelinePanel.Visible = true;
11351 TimelinePanel.Enabled = true;
11352 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11355 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11357 this.AllowDrop = false;
11360 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11362 this.AllowDrop = true;
11365 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11367 if (ImageSelector.Visible)
11369 ModifySettingCommon = true;
11370 SaveConfigsAll(true);
11372 this.StatusText_TextChanged(null, null);
11376 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11378 this.StatusText_TextChanged(null, null);
11382 /// StatusTextでCtrl+Vが押下された時の処理
11384 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11388 if (Clipboard.ContainsText())
11390 // clipboardにテキストがある場合は貼り付け処理
11391 this.StatusText.Paste(Clipboard.GetText());
11393 else if (Clipboard.ContainsImage())
11396 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11397 Properties.Resources.PostPictureWarn4,
11398 MessageBoxButtons.OKCancel,
11399 MessageBoxIcon.Question,
11400 MessageBoxDefaultButton.Button2)
11401 == DialogResult.OK)
11403 // clipboardから画像を取得
11404 using (var image = Clipboard.GetImage())
11406 this.ImageSelector.BeginSelection(image);
11411 catch (ExternalException ex)
11413 MessageBox.Show(ex.Message);
11418 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11420 using (ListManage form = new ListManage(tw))
11422 form.ShowDialog(this);
11426 public bool ModifySettingCommon { get; set; }
11427 public bool ModifySettingLocal { get; set; }
11428 public bool ModifySettingAtId { get; set; }
11430 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11432 if (this.ExistCurrentPost && !_curPost.IsDm)
11433 RtCountMenuItem.Enabled = true;
11435 RtCountMenuItem.Enabled = false;
11437 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11438 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11440 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11443 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11448 private void CopyUserId()
11450 if (_curPost == null) return;
11451 string clstr = _curPost.ScreenName;
11454 Clipboard.SetDataObject(clstr, false, 5, 100);
11456 catch (Exception ex)
11458 MessageBox.Show(ex.Message);
11462 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11464 if (this.ExistCurrentPost && !_curPost.IsDm)
11468 await this.OpenRelatedTab(this._curPost);
11470 catch (TabException ex)
11472 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11478 /// 指定されたツイートに対する関連発言タブを開きます
11480 /// <param name="statusId">表示するツイートのID</param>
11481 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11482 public async Task OpenRelatedTab(long statusId)
11484 var post = this._statuses[statusId];
11489 post = await this.tw.GetStatusApi(false, statusId);
11491 catch (WebApiException ex)
11493 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11498 await this.OpenRelatedTab(post);
11502 /// 指定されたツイートに対する関連発言タブを開きます
11504 /// <param name="post">表示する対象となるツイート</param>
11505 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11506 private async Task OpenRelatedTab(PostClass post)
11508 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11509 if (tabRelated != null)
11511 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11514 var tabName = this._statuses.MakeTabName("Related Tweets");
11516 tabRelated = new RelatedPostsTabModel(tabName, post);
11517 tabRelated.UnreadManage = false;
11518 tabRelated.Notify = false;
11520 this._statuses.AddTab(tabRelated);
11521 this.AddNewTab(tabRelated, startup: false);
11524 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
11526 tabPage = this.ListTab.TabPages[i];
11527 if (tabName == tabPage.Text)
11529 this.ListTab.SelectedIndex = i;
11534 await this.GetRelatedTweetsAsync(tabRelated);
11536 tabPage = this.ListTab.TabPages.Cast<TabPage>()
11537 .FirstOrDefault(x => x.Text == tabRelated.TabName);
11539 if (tabPage != null)
11541 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11543 var listView = (DetailsListView)tabPage.Tag;
11544 var targetPost = tabRelated.TargetPost;
11545 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11547 if (index != -1 && index < listView.Items.Count)
11549 listView.SelectedIndices.Add(index);
11550 listView.Items[index].Focused = true;
11555 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11557 StringBuilder buf = new StringBuilder();
11558 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11559 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11560 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11561 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11562 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11565 private void tw_UserIdChanged()
11567 this.ModifySettingCommon = true;
11570 #region "Userstream"
11571 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11575 if (InvokeRequired && !IsDisposed)
11577 await this.InvokeAsync(async () =>
11579 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11580 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
11582 this.PurgeListViewItemCache();
11583 ((DetailsListView)_curTab.Tag).Update();
11584 if (_curPost != null && _curPost.StatusId == e.StatusId)
11585 await this.DispSelectedPost(true);
11591 catch (ObjectDisposedException)
11595 catch (InvalidOperationException)
11601 private int userStreamsRefreshing = 0;
11603 private async void tw_NewPostFromStream(object sender, EventArgs e)
11605 if (SettingManager.Common.ReadOldPosts)
11607 _statuses.SetReadHomeTab(); //新着時未読クリア
11610 this._statuses.DistributePosts();
11612 if (SettingManager.Common.UserstreamPeriod > 0) return;
11614 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
11615 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
11619 await this.InvokeAsync(() => this.RefreshTimeline())
11620 .ConfigureAwait(false);
11624 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
11629 private async void tw_UserStreamStarted(object sender, EventArgs e)
11633 if (InvokeRequired && !IsDisposed)
11635 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11639 catch (ObjectDisposedException)
11643 catch (InvalidOperationException)
11648 this.RefreshUserStreamsMenu();
11649 this.MenuItemUserStream.Enabled = true;
11651 StatusLabel.Text = "UserStream Started.";
11654 private async void tw_UserStreamStopped(object sender, EventArgs e)
11658 if (InvokeRequired && !IsDisposed)
11660 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11664 catch (ObjectDisposedException)
11668 catch (InvalidOperationException)
11673 this.RefreshUserStreamsMenu();
11674 this.MenuItemUserStream.Enabled = true;
11676 StatusLabel.Text = "UserStream Stopped.";
11679 private void RefreshUserStreamsMenu()
11681 if (this.tw.UserStreamActive)
11683 this.MenuItemUserStream.Text = "&UserStream ▶";
11684 this.StopToolStripMenuItem.Text = "&Stop";
11688 this.MenuItemUserStream.Text = "&UserStream ■";
11689 this.StopToolStripMenuItem.Text = "&Start";
11693 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11697 if (InvokeRequired && !IsDisposed)
11699 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11703 catch (ObjectDisposedException)
11707 catch (InvalidOperationException)
11711 var ev = e.EventData;
11712 StatusLabel.Text = "Event: " + ev.Event;
11713 //if (ev.Event == "favorite")
11715 // NotifyFavorite(ev);
11718 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11720 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
11722 this.PurgeListViewItemCache();
11723 ((DetailsListView)_curTab.Tag).Update();
11725 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
11727 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11728 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11733 private void NotifyEvent(Twitter.FormattedEvent ev)
11736 if (BalloonRequired(ev))
11738 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11739 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11740 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11741 StringBuilder title = new StringBuilder();
11742 if (SettingManager.Common.DispUsername)
11744 title.Append(tw.Username);
11745 title.Append(" - ");
11751 title.Append(Application.ProductName);
11752 title.Append(" [");
11753 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11754 title.Append("] by ");
11755 if (!string.IsNullOrEmpty(ev.Username))
11757 title.Append(ev.Username);
11761 //title.Append("");
11764 if (!string.IsNullOrEmpty(ev.Target))
11766 //NotifyIcon1.BalloonTipText = ev.Target;
11771 //NotifyIcon1.BalloonTipText = " ";
11774 //NotifyIcon1.ShowBalloonTip(500);
11775 if (SettingManager.Common.IsUseNotifyGrowl)
11777 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11778 ev.Id.ToString(), title.ToString(), text);
11782 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11783 NotifyIcon1.BalloonTipTitle = title.ToString();
11784 NotifyIcon1.BalloonTipText = text;
11785 NotifyIcon1.ShowBalloonTip(500);
11790 string snd = SettingManager.Common.EventSoundFile;
11791 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11793 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11797 string dir = Application.StartupPath;
11798 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11800 dir = Path.Combine(dir, "Sounds");
11802 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11814 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11816 MenuItemUserStream.Enabled = false;
11817 if (StopRefreshAllMenuItem.Checked)
11819 StopRefreshAllMenuItem.Checked = false;
11822 if (this.tw.UserStreamActive)
11824 tw.StopUserStream();
11828 tw.StartUserStream();
11832 private static string inputTrack = "";
11834 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11836 if (TrackToolStripMenuItem.Checked)
11838 using (InputTabName inputForm = new InputTabName())
11840 inputForm.TabName = inputTrack;
11841 inputForm.FormTitle = "Input track word";
11842 inputForm.FormDescription = "Track word";
11843 if (inputForm.ShowDialog() != DialogResult.OK)
11845 TrackToolStripMenuItem.Checked = false;
11848 inputTrack = inputForm.TabName.Trim();
11850 if (!inputTrack.Equals(tw.TrackWord))
11852 tw.TrackWord = inputTrack;
11853 this.ModifySettingCommon = true;
11854 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11855 tw.ReconnectUserStream();
11861 tw.ReconnectUserStream();
11863 this.ModifySettingCommon = true;
11866 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11868 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11869 this.ModifySettingCommon = true;
11870 tw.ReconnectUserStream();
11873 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11875 if (evtDialog == null || evtDialog.IsDisposed)
11878 evtDialog = new EventViewerDialog();
11879 evtDialog.Owner = this;
11881 Point pos = evtDialog.Location;
11882 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
11883 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
11884 evtDialog.Location = pos;
11886 evtDialog.EventSource = tw.StoredEvent;
11887 if (!evtDialog.Visible)
11889 evtDialog.Show(this);
11893 evtDialog.Activate();
11895 this.TopMost = SettingManager.Common.AlwaysTop;
11899 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11901 MyCommon._endingFlag = true;
11905 Application.Restart();
11909 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
11913 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
11915 if (!string.IsNullOrEmpty(tw.Username))
11916 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
11919 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11921 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11924 private bool ExistCurrentPost
11928 if (_curPost == null) return false;
11929 if (_curPost.IsDeleted) return false;
11934 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11936 ShowUserTimeline();
11939 private string GetUserIdFromCurPostOrInput(string caption)
11941 var id = _curPost?.ScreenName ?? "";
11943 using (InputTabName inputName = new InputTabName())
11945 inputName.FormTitle = caption;
11946 inputName.FormDescription = Properties.Resources.FRMessage1;
11947 inputName.TabName = id;
11948 if (inputName.ShowDialog() == DialogResult.OK &&
11949 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11951 id = inputName.TabName.Trim();
11961 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11963 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11964 if (!string.IsNullOrEmpty(id))
11966 AddNewTabForUserTimeline(id);
11970 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
11972 string id = GetUserIdFromCurPostOrInput("Show Favstar");
11973 if (!string.IsNullOrEmpty(id))
11975 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
11979 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11981 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
11984 private void TimelineRefreshEnableChange(bool isEnable)
11988 tw.StartUserStream();
11992 tw.StopUserStream();
11994 TimerTimeline.Enabled = isEnable;
11997 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11999 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
12002 private async Task OpenUserAppointUrl()
12004 if (SettingManager.Common.UserAppointUrl != null)
12006 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
12008 if (_curPost != null)
12010 string xUrl = SettingManager.Common.UserAppointUrl;
12011 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
12013 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
12014 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
12016 await this.OpenUriInBrowserAsync(xUrl);
12021 await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
12026 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12028 await this.OpenUserAppointUrl();
12031 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
12033 if (Form.ActiveForm == null)
12035 await this.InvokeAsync(() =>
12037 this.Visible = true;
12038 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12040 this.BringToFront();
12041 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
12043 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12047 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12053 private void ReplaceAppName()
12055 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12056 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12059 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12061 this.SplitContainer3.Panel2Collapsed = false;
12064 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12066 await this.OpenThumbnailPicture(e.Thumbnail);
12069 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
12071 await this.OpenUriInBrowserAsync(e.ImageUrl);
12074 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
12076 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
12078 await this.OpenUriInBrowserAsync(url);
12081 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
12083 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
12086 private void PostButton_KeyDown(object sender, KeyEventArgs e)
12088 if (e.KeyCode == Keys.Space)
12090 this.JumpUnreadMenuItem_Click(null, null);
12092 e.SuppressKeyPress = true;
12096 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
12098 this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
12099 this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
12100 this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
12101 this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
12102 this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
12104 this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
12107 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
12109 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
12112 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
12114 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
12117 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
12119 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
12122 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
12124 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
12127 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
12129 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
12132 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
12134 if (SettingManager.Common.IconSize == iconSize) return;
12136 var oldIconCol = _iconCol;
12138 SettingManager.Common.IconSize = iconSize;
12139 ApplyListViewIconSize(iconSize);
12141 if (_iconCol != oldIconCol)
12143 foreach (TabPage tp in ListTab.TabPages)
12145 ResetColumns((DetailsListView)tp.Tag);
12149 _curList?.Refresh();
12151 ModifySettingCommon = true;
12154 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
12156 var state = this.LockListSortOrderToolStripMenuItem.Checked;
12157 if (SettingManager.Common.SortOrderLock == state) return;
12159 SettingManager.Common.SortOrderLock = state;
12161 ModifySettingCommon = true;
12164 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
12166 if (!string.IsNullOrEmpty(e.StatusText))
12168 this.StatusLabelUrl.Text = e.StatusText;
12172 this.SetStatusLabelUrl();