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;
4760 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
4761 if (this.inReplyTo != null && this.inReplyTo.Item2 == this.tw.Username)
4763 var mentionSelf = $"@{this.tw.Username} ";
4764 if (statusText.Length > mentionSelf.Length && statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
4765 statusText = statusText.Substring(mentionSelf.Length);
4771 var hashtag = this.HashMgr.UseHash;
4772 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4775 header = HashMgr.UseHash + " ";
4777 footer = " " + HashMgr.UseHash;
4782 if (SettingManager.Local.UseRecommendStatus)
4785 footer += this.recommendedStatusFooter;
4787 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4789 // テキストボックスに入力されている文字列を使用する
4790 footer += " " + SettingManager.Local.StatusText.Trim();
4794 statusText = header + statusText + footer;
4796 if (this.preventSmsCommand)
4798 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4799 // 参照: https://support.twitter.com/articles/14020
4801 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4802 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4804 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4805 statusText = '\u200b' + statusText;
4813 /// 投稿欄に表示する入力可能な文字数を計算します
4815 private int GetRestStatusCount(string statusText)
4818 var remainCount = this.tw.GetTextLengthRemain(statusText);
4820 var uploadService = this.ImageSelector.SelectedService;
4821 if (this.ImageSelector.Visible && uploadService != null)
4823 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4824 remainCount -= uploadService.GetReservedTextLength(1);
4830 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4832 if (sender != this._curList)
4835 var listCache = this._listItemCache;
4836 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4838 // If the newly requested cache is a subset of the old cache,
4839 // no need to rebuild everything, so do nothing.
4843 // Now we need to rebuild the cache.
4844 this.CreateCache(e.StartIndex, e.EndIndex);
4847 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4849 var listCache = this._listItemCache;
4850 if (listCache?.TargetList == sender)
4852 if (listCache.TryGetValue(e.ItemIndex, out var item, out var cacheItemPost))
4859 // A cache miss, so create a new ListViewItem and pass it back.
4860 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4863 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4867 // 不正な要求に対する間に合わせの応答
4868 string[] sitem = {"", "", "", "", "", "", "", ""};
4869 e.Item = new ImageListViewItem(sitem);
4873 private void CreateCache(int startIndex, int endIndex)
4875 var tabInfo = this._statuses.Tabs[this._curTab.Text];
4877 if (tabInfo.AllCount == 0)
4880 // インデックスを 0...(tabInfo.AllCount - 1) の範囲内にする
4881 int FilterRange(int index)
4882 => Math.Max(Math.Min(index, tabInfo.AllCount - 1), 0);
4884 // キャッシュ要求(要求範囲±30を作成)
4885 startIndex = FilterRange(startIndex - 30);
4886 endIndex = FilterRange(endIndex + 30);
4888 var cacheLength = endIndex - startIndex + 1;
4890 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4891 var listItems = Enumerable.Range(0, cacheLength)
4892 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4895 var listCache = new ListViewItemCache
4897 TargetList = this._curList,
4898 StartIndex = startIndex,
4899 EndIndex = endIndex,
4901 ListItem = listItems,
4904 Interlocked.Exchange(ref this._listItemCache, listCache);
4908 /// DetailsListView のための ListViewItem のキャッシュを消去する
4910 private void PurgeListViewItemCache()
4912 Interlocked.Exchange(ref this._listItemCache, null);
4915 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
4917 StringBuilder mk = new StringBuilder();
4918 //if (Post.IsDeleted) mk.Append("×");
4919 //if (Post.IsMark) mk.Append("♪");
4920 //if (Post.IsProtect) mk.Append("Ю");
4921 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4922 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4923 ImageListViewItem itm;
4924 if (Post.RetweetedId == null)
4926 string[] sitem= {"",
4928 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4929 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4934 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4938 string[] sitem = {"",
4940 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4941 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4942 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4946 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4948 itm.StateIndex = Post.StateIndex;
4951 bool read = Post.IsRead;
4952 //未読管理していなかったら既読として扱う
4953 if (!_statuses.Tabs[Tab.Text].UnreadManage || !SettingManager.Common.UnreadManage) read = true;
4954 ChangeItemStyleRead(read, itm, Post, null);
4955 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
4960 /// 全てのタブの振り分けルールを反映し直します
4962 private void ApplyPostFilters()
4964 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4966 this.PurgeListViewItemCache();
4967 this._curPost = null;
4968 this._curItemIndex = -1;
4969 this._statuses.FilterAll();
4971 foreach (TabPage tabPage in this.ListTab.TabPages)
4973 var tab = this._statuses.Tabs[tabPage.Text];
4975 var listview = (DetailsListView)tabPage.Tag;
4976 using (ControlTransaction.Update(listview))
4978 listview.VirtualListSize = tab.AllCount;
4981 if (SettingManager.Common.TabIconDisp)
4983 if (tab.UnreadCount > 0)
4984 tabPage.ImageIndex = 0;
4986 tabPage.ImageIndex = -1;
4990 if (!SettingManager.Common.TabIconDisp)
4991 this.ListTab.Refresh();
4993 SetMainWindowTitle();
4994 SetStatusLabelUrl();
4998 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5000 e.DrawDefault = true;
5003 private void MyList_HScrolled(object sender, EventArgs e)
5005 DetailsListView listView = (DetailsListView)sender;
5009 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5011 if (e.State == 0) return;
5012 e.DrawDefault = false;
5014 SolidBrush brs2 = null;
5015 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5017 if (e.Item.BackColor == _clSelf)
5018 brs2 = _brsBackColorMine;
5019 else if (e.Item.BackColor == _clAtSelf)
5020 brs2 = _brsBackColorAt;
5021 else if (e.Item.BackColor == _clTarget)
5022 brs2 = _brsBackColorYou;
5023 else if (e.Item.BackColor == _clAtTarget)
5024 brs2 = _brsBackColorAtYou;
5025 else if (e.Item.BackColor == _clAtFromTarget)
5026 brs2 = _brsBackColorAtFromTarget;
5027 else if (e.Item.BackColor == _clAtTo)
5028 brs2 = _brsBackColorAtTo;
5030 brs2 = _brsBackColorNone;
5035 if (((Control)sender).Focused)
5036 brs2 = _brsHighLight;
5038 brs2 = _brsDeactiveSelection;
5040 e.Graphics.FillRectangle(brs2, e.Bounds);
5041 e.DrawFocusRectangle();
5042 this.DrawListViewItemIcon(e);
5045 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5047 if (e.ItemState == 0) return;
5049 if (e.ColumnIndex > 0)
5052 var post = (PostClass)e.Item.Tag;
5054 RectangleF rct = e.Bounds;
5055 rct.Width = e.Header.Width;
5056 int fontHeight = e.Item.Font.Height;
5059 rct.Y += fontHeight;
5060 rct.Height -= fontHeight;
5063 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out var heightDiff));
5065 //if (heightDiff > fontHeight * 0.7)
5067 // rct.Height += fontHeight;
5068 // drawLineCount += 1;
5071 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5072 if (!_iconCol && drawLineCount <= 1)
5074 //rct.Inflate(0, heightDiff / -2);
5075 //rct.Height += fontHeight / 2;
5077 else if (heightDiff < fontHeight * 0.7)
5079 //最終行が70%以上欠けていたら、最終行は表示しない
5080 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5081 rct.Height = (fontHeight * drawLineCount) - 1;
5088 //if (!_iconCol && drawLineCount > 1)
5090 // rct.Y += fontHeight * 0.2;
5091 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5096 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5097 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5102 Rectangle rctB = e.Bounds;
5103 rctB.Width = e.Header.Width;
5104 rctB.Height = fontHeight;
5106 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5108 TextRenderer.DrawText(e.Graphics,
5109 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5111 Rectangle.Round(rct),
5113 TextFormatFlags.WordBreak |
5114 TextFormatFlags.EndEllipsis |
5115 TextFormatFlags.GlyphOverhangPadding |
5116 TextFormatFlags.NoPrefix);
5117 TextRenderer.DrawText(e.Graphics,
5118 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 + "]",
5122 TextFormatFlags.SingleLine |
5123 TextFormatFlags.EndEllipsis |
5124 TextFormatFlags.GlyphOverhangPadding |
5125 TextFormatFlags.NoPrefix);
5131 if (e.ColumnIndex != 2)
5132 text = e.SubItem.Text;
5134 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5136 if (drawLineCount == 1)
5138 TextRenderer.DrawText(e.Graphics,
5141 Rectangle.Round(rct),
5143 TextFormatFlags.SingleLine |
5144 TextFormatFlags.EndEllipsis |
5145 TextFormatFlags.GlyphOverhangPadding |
5146 TextFormatFlags.NoPrefix |
5147 TextFormatFlags.VerticalCenter);
5151 TextRenderer.DrawText(e.Graphics,
5154 Rectangle.Round(rct),
5156 TextFormatFlags.WordBreak |
5157 TextFormatFlags.EndEllipsis |
5158 TextFormatFlags.GlyphOverhangPadding |
5159 TextFormatFlags.NoPrefix);
5162 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5167 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5169 if (_iconSz == 0) return;
5171 ImageListViewItem item = (ImageListViewItem)e.Item;
5173 //e.Bounds.Leftが常に0を指すから自前で計算
5174 Rectangle itemRect = item.Bounds;
5175 var col0 = e.Item.ListView.Columns[0];
5176 itemRect.Width = col0.Width;
5178 if (col0.DisplayIndex > 0)
5180 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5182 if (clm.DisplayIndex < col0.DisplayIndex)
5183 itemRect.X += clm.Width;
5187 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5188 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5189 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5192 var img = item.Image;
5195 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5196 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5198 if (iconRect.Width > 0)
5200 e.Graphics.FillRectangle(Brushes.White, iconRect);
5201 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5204 e.Graphics.DrawImage(img.Image, iconRect);
5206 catch (ArgumentException)
5208 item.RefreshImageAsync();
5214 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5215 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5217 item.GetImageAsync();
5220 if (item.StateIndex > -1)
5222 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5223 if (stateRect.Width > 0)
5225 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5226 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5227 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5232 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5234 base.ScaleControl(factor, specified);
5236 ScaleChildControl(this.TabImage, factor);
5238 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5239 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5241 foreach (var listview in listviews)
5243 ScaleChildControl(listview, factor);
5247 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5249 // ImageListViewItem item = (ImageListViewItem)e.Item;
5250 // if (item.StateImageIndex > -1)
5252 // ////e.Bounds.Leftが常に0を指すから自前で計算
5253 // //Rectangle itemRect = item.Bounds;
5254 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5256 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5258 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5260 // // itemRect.X += clm.Width;
5264 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5265 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5267 // if (rct.Width > 0)
5269 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5270 // //e.Graphics.FillRectangle(Brushes.White, rct);
5271 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5272 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5277 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5279 var tab = this._statuses.Tabs[this._curTab.Text];
5281 if (tab.AllCount == 0)
5283 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5287 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5292 case SEARCHTYPE.NextSearch: // 次を検索
5293 if (selectedIndex != -1)
5294 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5298 case SEARCHTYPE.PrevSearch: // 前を検索
5299 if (selectedIndex != -1)
5300 startIndex = Math.Max(selectedIndex - 1, 0);
5302 startIndex = tab.AllCount - 1;
5304 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5306 if (selectedIndex != -1)
5307 startIndex = selectedIndex;
5313 Func<string, bool> stringComparer;
5316 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5318 catch (ArgumentException)
5320 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5324 var reverse = searchType == SEARCHTYPE.PrevSearch;
5325 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5326 .DefaultIfEmpty(-1).First();
5328 if (foundIndex == -1)
5330 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5334 this.SelectListItem(this._curList, foundIndex);
5335 this._curList.EnsureVisible(foundIndex);
5338 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5341 this.ShowSearchDialog();
5344 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5346 var previousSearch = this.SearchDialog.ResultOptions;
5347 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5349 this.SearchDialog.Reset();
5350 this.ShowSearchDialog();
5356 previousSearch.Query,
5357 previousSearch.CaseSensitive,
5358 previousSearch.UseRegex,
5359 SEARCHTYPE.NextSearch);
5362 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5364 var previousSearch = this.SearchDialog.ResultOptions;
5365 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5367 this.SearchDialog.Reset();
5368 this.ShowSearchDialog();
5374 previousSearch.Query,
5375 previousSearch.CaseSensitive,
5376 previousSearch.UseRegex,
5377 SEARCHTYPE.PrevSearch);
5381 /// 検索ダイアログを表示し、検索を実行します
5383 private void ShowSearchDialog()
5385 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5387 this.TopMost = SettingManager.Common.AlwaysTop;
5390 this.TopMost = SettingManager.Common.AlwaysTop;
5392 var searchOptions = this.SearchDialog.ResultOptions;
5393 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5395 if (searchOptions.NewTab)
5397 var tabName = Properties.Resources.SearchResults_TabName;
5401 tabName = this._statuses.MakeTabName(tabName);
5403 catch (TabException ex)
5405 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5408 var resultTab = new LocalSearchTabModel(tabName);
5409 this.AddNewTab(resultTab, startup: false);
5410 this._statuses.AddTab(resultTab);
5412 var targetTab = this._statuses.Tabs[this._curTab.Text];
5414 Func<string, bool> stringComparer;
5417 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5419 catch (ArgumentException)
5421 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5425 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5426 if (foundIndices.Length == 0)
5428 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5432 var foundPosts = foundIndices.Select(x => targetTab[x]);
5433 foreach (var post in foundPosts)
5435 resultTab.AddPostQueue(post);
5438 this._statuses.DistributePosts();
5439 this.RefreshTimeline();
5441 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5442 .First(x => x.Text == tabName);
5444 this.ListTab.SelectedTab = tabPage;
5449 searchOptions.Query,
5450 searchOptions.CaseSensitive,
5451 searchOptions.UseRegex,
5452 SEARCHTYPE.DialogSearch);
5455 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5457 this.AddNewTabForSearch(searchOptions.Query);
5461 /// <summary>発言検索に使用するメソッドを生成します</summary>
5462 /// <exception cref="ArgumentException">
5463 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5465 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5469 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5470 var regex = new Regex(query, regexOption);
5472 return x => regex.IsMatch(x);
5476 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5478 return x => x.IndexOf(query, comparisonType) != -1;
5482 private void AboutMenuItem_Click(object sender, EventArgs e)
5484 using (TweenAboutBox about = new TweenAboutBox())
5486 about.ShowDialog(this);
5488 this.TopMost = SettingManager.Common.AlwaysTop;
5491 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5493 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5495 if (ImageSelector.Enabled)
5498 TabModel foundTab = null;
5501 DetailsListView lst = null;
5504 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5506 var tabPage = this.ListTab.TabPages[i];
5507 var tab = this._statuses.Tabs[tabPage.Text];
5508 var unreadIndex = tab.NextUnreadIndex;
5510 if (unreadIndex != -1)
5512 ListTab.SelectedIndex = i;
5514 foundIndex = unreadIndex;
5515 lst = (DetailsListView)tabPage.Tag;
5520 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5521 if (foundTab == null && bgnIdx > 0)
5523 for (int i = 0; i < bgnIdx; i++)
5525 var tabPage = this.ListTab.TabPages[i];
5526 var tab = this._statuses.Tabs[tabPage.Text];
5527 var unreadIndex = tab.NextUnreadIndex;
5529 if (unreadIndex != -1)
5531 ListTab.SelectedIndex = i;
5533 foundIndex = unreadIndex;
5534 lst = (DetailsListView)tabPage.Tag;
5540 if (foundTab == null)
5542 //全部調べたが未読見つからず→先頭タブの最新発言へ
5543 ListTab.SelectedIndex = 0;
5544 var tabPage = this.ListTab.TabPages[0];
5545 var tab = this._statuses.Tabs[tabPage.Text];
5547 if (tab.AllCount == 0)
5550 if (_statuses.SortOrder == SortOrder.Ascending)
5551 foundIndex = tab.AllCount - 1;
5555 lst = (DetailsListView)tabPage.Tag;
5558 SelectListItem(lst, foundIndex);
5560 if (_statuses.SortMode == ComparerMode.Id)
5562 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5563 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5569 lst.EnsureVisible(foundIndex);
5574 lst.EnsureVisible(foundIndex);
5580 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5582 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5584 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5585 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5589 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5591 if (_curList.SelectedIndices.Count > 0)
5593 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5594 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5598 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5600 await this.CheckNewVersion(false);
5603 private void RunTweenUp()
5605 ProcessStartInfo pinfo = new ProcessStartInfo();
5606 pinfo.UseShellExecute = true;
5607 pinfo.WorkingDirectory = MyCommon.settingPath;
5608 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5609 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5612 Process.Start(pinfo);
5616 MessageBox.Show("Failed to execute TweenUp3.exe.");
5620 public class VersionInfo
5622 public Version Version { get; set; }
5623 public Uri DownloadUri { get; set; }
5624 public string ReleaseNote { get; set; }
5628 /// OpenTween の最新バージョンの情報を取得します
5630 public async Task<VersionInfo> GetVersionInfoAsync()
5632 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5633 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5635 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5636 .ConfigureAwait(false);
5638 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5639 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5641 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5642 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5644 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5646 return new VersionInfo
5648 Version = Version.Parse(msgHeader[0]),
5649 DownloadUri = new Uri(msgHeader[1]),
5650 ReleaseNote = msgBody,
5654 private async Task CheckNewVersion(bool startup = false)
5656 if (ApplicationSettings.VersionInfoUrl == null)
5657 return; // 更新チェック無効化
5661 var versionInfo = await this.GetVersionInfoAsync();
5663 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5668 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5669 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5670 msgtext = MyCommon.ReplaceAppName(msgtext);
5672 MessageBox.Show(msgtext,
5673 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5674 MessageBoxButtons.OK, MessageBoxIcon.Information);
5679 using (var dialog = new UpdateDialog())
5681 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5682 MyCommon.GetReadableVersion(versionInfo.Version));
5683 dialog.DetailsText = versionInfo.ReleaseNote;
5685 if (dialog.ShowDialog(this) == DialogResult.Yes)
5687 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5693 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5696 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5697 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5698 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5703 private async Task Colorize()
5706 await this.DispSelectedPost();
5707 //件数関連の場合、タイトル即時書き換え
5708 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5709 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5710 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5711 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5713 SetMainWindowTitle();
5715 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5716 SetStatusLabelUrl();
5717 foreach (TabPage tb in ListTab.TabPages)
5719 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5721 if (SettingManager.Common.TabIconDisp)
5723 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5727 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
5730 public string createDetailHtml(string orgdata)
5732 if (SettingManager.Local.UseTwemoji)
5733 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5735 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5738 private Task DispSelectedPost()
5740 return this.DispSelectedPost(false);
5743 private PostClass displayPost = new PostClass();
5746 /// サムネイル表示に使用する CancellationToken の生成元
5748 private CancellationTokenSource thumbnailTokenSource = null;
5750 private async Task DispSelectedPost(bool forceupdate)
5752 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5755 var oldDisplayPost = this.displayPost;
5756 this.displayPost = this._curPost;
5758 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5761 var loadTasks = new List<Task>
5763 this.tweetDetailsView.ShowPostDetails(this._curPost),
5766 this.SplitContainer3.Panel2Collapsed = true;
5768 if (SettingManager.Common.PreviewEnable)
5770 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5771 oldTokenSource?.Cancel();
5773 var token = this.thumbnailTokenSource.Token;
5774 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5779 await Task.WhenAll(loadTasks);
5781 catch (OperationCanceledException) { }
5784 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5786 await this.OpenApplicationWebsite();
5789 private async Task OpenApplicationWebsite()
5791 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5794 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5796 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5799 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5801 if (ListTab.SelectedTab != null)
5803 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
5805 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
5806 if (pnl.Controls["comboSearch"].Focused ||
5807 pnl.Controls["comboLang"].Focused ||
5808 pnl.Controls["buttonSearch"].Focused) return;
5811 if (e.Control || e.Shift || e.Alt)
5812 this._anchorFlag = false;
5814 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
5817 e.SuppressKeyPress = true;
5820 if (asyncTask != null)
5825 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
5827 private void InitializeShortcuts()
5829 this.shortcutCommands = new[]
5831 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5832 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5833 .FocusedOn(FocusedControl.ListTab)
5834 .Do(() => SendKeys.Send("{DOWN}")),
5836 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5837 .FocusedOn(FocusedControl.ListTab)
5838 .Do(() => SendKeys.Send("{UP}")),
5840 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5841 .FocusedOn(FocusedControl.ListTab)
5842 .Do(() => SendKeys.Send("{PGDN}")),
5844 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5845 .FocusedOn(FocusedControl.ListTab)
5846 .Do(() => SendKeys.Send("{PGUP}")),
5848 ShortcutCommand.Create(Keys.F1)
5849 .Do(() => this.OpenApplicationWebsite()),
5851 ShortcutCommand.Create(Keys.F3)
5852 .Do(() => this.MenuItemSearchNext_Click(null, null)),
5854 ShortcutCommand.Create(Keys.F5)
5855 .Do(() => this.DoRefresh()),
5857 ShortcutCommand.Create(Keys.F6)
5858 .Do(() => this.GetReplyAsync()),
5860 ShortcutCommand.Create(Keys.F7)
5861 .Do(() => this.GetDirectMessagesAsync()),
5863 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5864 .NotFocusedOn(FocusedControl.StatusText)
5865 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5867 ShortcutCommand.Create(Keys.G)
5868 .NotFocusedOn(FocusedControl.StatusText)
5869 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5871 ShortcutCommand.Create(Keys.Right, Keys.N)
5872 .FocusedOn(FocusedControl.ListTab)
5873 .Do(() => this.GoRelPost(forward: true)),
5875 ShortcutCommand.Create(Keys.Left, Keys.P)
5876 .FocusedOn(FocusedControl.ListTab)
5877 .Do(() => this.GoRelPost(forward: false)),
5879 ShortcutCommand.Create(Keys.OemPeriod)
5880 .FocusedOn(FocusedControl.ListTab)
5881 .Do(() => this.GoAnchor()),
5883 ShortcutCommand.Create(Keys.I)
5884 .FocusedOn(FocusedControl.ListTab)
5885 .OnlyWhen(() => this.StatusText.Enabled)
5886 .Do(() => this.StatusText.Focus()),
5888 ShortcutCommand.Create(Keys.Enter)
5889 .FocusedOn(FocusedControl.ListTab)
5890 .Do(() => this.MakeReplyOrDirectStatus()),
5892 ShortcutCommand.Create(Keys.R)
5893 .FocusedOn(FocusedControl.ListTab)
5894 .Do(() => this.DoRefresh()),
5896 ShortcutCommand.Create(Keys.L)
5897 .FocusedOn(FocusedControl.ListTab)
5898 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5900 ShortcutCommand.Create(Keys.H)
5901 .FocusedOn(FocusedControl.ListTab)
5902 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5904 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5905 .FocusedOn(FocusedControl.ListTab)
5906 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5908 ShortcutCommand.Create(Keys.S)
5909 .FocusedOn(FocusedControl.ListTab)
5910 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5912 ShortcutCommand.Create(Keys.A)
5913 .FocusedOn(FocusedControl.ListTab)
5914 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5916 // ] in_reply_to参照元へ戻る
5917 ShortcutCommand.Create(Keys.Oem4)
5918 .FocusedOn(FocusedControl.ListTab)
5919 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5921 // [ in_reply_toへジャンプ
5922 ShortcutCommand.Create(Keys.Oem6)
5923 .FocusedOn(FocusedControl.ListTab)
5924 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5926 ShortcutCommand.Create(Keys.Escape)
5927 .FocusedOn(FocusedControl.ListTab)
5929 this._anchorFlag = false;
5930 if (ListTab.SelectedTab != null)
5932 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
5933 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5935 var relTp = ListTab.SelectedTab;
5936 RemoveSpecifiedTab(relTp.Text, false);
5942 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5943 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5944 .FocusedOn(FocusedControl.ListTab)
5945 .Do(() => this._anchorFlag = false, preventDefault: false),
5947 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5948 ShortcutCommand.Create(Keys.Up, Keys.Down)
5949 .FocusedOn(FocusedControl.PostBrowser)
5952 ShortcutCommand.Create(Keys.Control | Keys.R)
5953 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5955 ShortcutCommand.Create(Keys.Control | Keys.D)
5956 .Do(() => this.doStatusDelete()),
5958 ShortcutCommand.Create(Keys.Control | Keys.M)
5959 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5961 ShortcutCommand.Create(Keys.Control | Keys.S)
5962 .Do(() => this.FavoriteChange(FavAdd: true)),
5964 ShortcutCommand.Create(Keys.Control | Keys.I)
5965 .Do(() => this.doRepliedStatusOpen()),
5967 ShortcutCommand.Create(Keys.Control | Keys.Q)
5968 .Do(() => this.doQuoteOfficial()),
5970 ShortcutCommand.Create(Keys.Control | Keys.B)
5971 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5973 ShortcutCommand.Create(Keys.Control | Keys.T)
5974 .Do(() => this.HashManageMenuItem_Click(null, null)),
5976 ShortcutCommand.Create(Keys.Control | Keys.L)
5977 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5979 ShortcutCommand.Create(Keys.Control | Keys.Y)
5980 .NotFocusedOn(FocusedControl.PostBrowser)
5981 .Do(() => this.MultiLineMenuItem_Click(null, null)),
5983 ShortcutCommand.Create(Keys.Control | Keys.F)
5984 .Do(() => this.MenuItemSubSearch_Click(null, null)),
5986 ShortcutCommand.Create(Keys.Control | Keys.U)
5987 .Do(() => this.ShowUserTimeline()),
5989 ShortcutCommand.Create(Keys.Control | Keys.H)
5990 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5992 ShortcutCommand.Create(Keys.Control | Keys.G)
5993 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
5995 ShortcutCommand.Create(Keys.Control | Keys.O)
5996 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
5998 ShortcutCommand.Create(Keys.Control | Keys.E)
5999 .Do(() => this.OpenURLMenuItem_Click(null, null)),
6001 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6002 .FocusedOn(FocusedControl.ListTab)
6003 .Do(() => this._colorize = true, preventDefault: false),
6005 ShortcutCommand.Create(Keys.Control | Keys.N)
6006 .FocusedOn(FocusedControl.ListTab)
6007 .Do(() => this.GoNextTab(forward: true)),
6009 ShortcutCommand.Create(Keys.Control | Keys.P)
6010 .FocusedOn(FocusedControl.ListTab)
6011 .Do(() => this.GoNextTab(forward: false)),
6013 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6014 .FocusedOn(FocusedControl.ListTab)
6015 .Do(() => this.CopyStot()),
6017 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6018 ShortcutCommand.Create(Keys.Control | Keys.D1)
6019 .FocusedOn(FocusedControl.ListTab)
6020 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6021 .Do(() => this.ListTab.SelectedIndex = 0),
6023 ShortcutCommand.Create(Keys.Control | Keys.D2)
6024 .FocusedOn(FocusedControl.ListTab)
6025 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6026 .Do(() => this.ListTab.SelectedIndex = 1),
6028 ShortcutCommand.Create(Keys.Control | Keys.D3)
6029 .FocusedOn(FocusedControl.ListTab)
6030 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6031 .Do(() => this.ListTab.SelectedIndex = 2),
6033 ShortcutCommand.Create(Keys.Control | Keys.D4)
6034 .FocusedOn(FocusedControl.ListTab)
6035 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6036 .Do(() => this.ListTab.SelectedIndex = 3),
6038 ShortcutCommand.Create(Keys.Control | Keys.D5)
6039 .FocusedOn(FocusedControl.ListTab)
6040 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6041 .Do(() => this.ListTab.SelectedIndex = 4),
6043 ShortcutCommand.Create(Keys.Control | Keys.D6)
6044 .FocusedOn(FocusedControl.ListTab)
6045 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6046 .Do(() => this.ListTab.SelectedIndex = 5),
6048 ShortcutCommand.Create(Keys.Control | Keys.D7)
6049 .FocusedOn(FocusedControl.ListTab)
6050 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6051 .Do(() => this.ListTab.SelectedIndex = 6),
6053 ShortcutCommand.Create(Keys.Control | Keys.D8)
6054 .FocusedOn(FocusedControl.ListTab)
6055 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6056 .Do(() => this.ListTab.SelectedIndex = 7),
6058 ShortcutCommand.Create(Keys.Control | Keys.D9)
6059 .FocusedOn(FocusedControl.ListTab)
6060 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6062 ShortcutCommand.Create(Keys.Control | Keys.A)
6063 .FocusedOn(FocusedControl.StatusText)
6064 .Do(() => this.StatusText.SelectAll()),
6066 ShortcutCommand.Create(Keys.Control | Keys.V)
6067 .FocusedOn(FocusedControl.StatusText)
6068 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6070 ShortcutCommand.Create(Keys.Control | Keys.Up)
6071 .FocusedOn(FocusedControl.StatusText)
6073 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6075 var inReplyToStatusId = this.inReplyTo?.Item1;
6076 var inReplyToScreenName = this.inReplyTo?.Item2;
6077 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6080 if (_hisIdx < 0) _hisIdx = 0;
6082 var historyItem = this._history[this._hisIdx];
6083 StatusText.Text = historyItem.status;
6084 StatusText.SelectionStart = StatusText.Text.Length;
6085 if (historyItem.inReplyToId != null)
6086 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6088 this.inReplyTo = null;
6091 ShortcutCommand.Create(Keys.Control | Keys.Down)
6092 .FocusedOn(FocusedControl.StatusText)
6094 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6096 var inReplyToStatusId = this.inReplyTo?.Item1;
6097 var inReplyToScreenName = this.inReplyTo?.Item2;
6098 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6101 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6103 var historyItem = this._history[this._hisIdx];
6104 StatusText.Text = historyItem.status;
6105 StatusText.SelectionStart = StatusText.Text.Length;
6106 if (historyItem.inReplyToId != null)
6107 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6109 this.inReplyTo = null;
6112 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6113 .FocusedOn(FocusedControl.StatusText)
6115 if (ListTab.SelectedIndex == 0)
6117 ListTab.SelectedIndex = ListTab.TabCount - 1;
6121 ListTab.SelectedIndex -= 1;
6126 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6127 .FocusedOn(FocusedControl.StatusText)
6129 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6131 ListTab.SelectedIndex = 0;
6135 ListTab.SelectedIndex += 1;
6140 ShortcutCommand.Create(Keys.Control | Keys.Y)
6141 .FocusedOn(FocusedControl.PostBrowser)
6143 var multiline = !SettingManager.Local.StatusMultiline;
6144 SettingManager.Local.StatusMultiline = multiline;
6145 MultiLineMenuItem.Checked = multiline;
6146 MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
6149 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6150 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6152 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6153 .Do(() => this.DoRefreshMore()),
6155 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6156 .Do(() => this.GetReplyAsync(loadMore: true)),
6158 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6159 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6161 ShortcutCommand.Create(Keys.Shift | Keys.R)
6162 .NotFocusedOn(FocusedControl.StatusText)
6163 .Do(() => this.DoRefreshMore()),
6165 ShortcutCommand.Create(Keys.Shift | Keys.H)
6166 .FocusedOn(FocusedControl.ListTab)
6167 .Do(() => this.GoTopEnd(GoTop: true)),
6169 ShortcutCommand.Create(Keys.Shift | Keys.L)
6170 .FocusedOn(FocusedControl.ListTab)
6171 .Do(() => this.GoTopEnd(GoTop: false)),
6173 ShortcutCommand.Create(Keys.Shift | Keys.M)
6174 .FocusedOn(FocusedControl.ListTab)
6175 .Do(() => this.GoMiddle()),
6177 ShortcutCommand.Create(Keys.Shift | Keys.G)
6178 .FocusedOn(FocusedControl.ListTab)
6179 .Do(() => this.GoLast()),
6181 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6182 .FocusedOn(FocusedControl.ListTab)
6183 .Do(() => this.MoveMiddle()),
6185 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6186 .FocusedOn(FocusedControl.ListTab)
6187 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6189 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6190 .FocusedOn(FocusedControl.ListTab)
6191 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6193 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6194 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6195 .FocusedOn(FocusedControl.ListTab)
6196 .Do(() => this.GoFav(forward: true)),
6198 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6199 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6200 .FocusedOn(FocusedControl.ListTab)
6201 .Do(() => this.GoFav(forward: false)),
6203 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6204 .FocusedOn(FocusedControl.ListTab)
6205 .Do(() => this.GoBackSelectPostChain()),
6207 ShortcutCommand.Create(Keys.Alt | Keys.R)
6208 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6210 ShortcutCommand.Create(Keys.Alt | Keys.P)
6211 .OnlyWhen(() => this._curPost != null)
6212 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6214 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6215 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6217 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6218 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6220 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6221 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6223 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6224 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6226 // 別タブの同じ書き込みへ(ALT+←/→)
6227 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6228 .FocusedOn(FocusedControl.ListTab)
6229 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6231 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6232 .FocusedOn(FocusedControl.ListTab)
6233 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6235 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6236 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6238 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6239 .Do(() => this.CopyIdUri()),
6241 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6242 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6243 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6244 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6246 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6247 .Do(() => this.FavoriteChange(FavAdd: false)),
6249 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6250 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6252 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6253 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6255 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6256 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6258 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6259 .Do(() => this.doMoveToRTHome()),
6261 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6262 .Do(() => this.FavorareMenuItem_Click(null, null)),
6264 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6265 .FocusedOn(FocusedControl.StatusText)
6267 if (_curList != null && _curList.VirtualListSize != 0 &&
6268 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6270 var idx = _curList.SelectedIndices[0] - 1;
6271 SelectListItem(_curList, idx);
6272 _curList.EnsureVisible(idx);
6276 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6277 .FocusedOn(FocusedControl.StatusText)
6279 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6280 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6282 var idx = _curList.SelectedIndices[0] + 1;
6283 SelectListItem(_curList, idx);
6284 _curList.EnsureVisible(idx);
6288 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6289 .FocusedOn(FocusedControl.StatusText)
6291 if (StatusText.SelectionStart > 0)
6293 int endidx = StatusText.SelectionStart - 1;
6294 string startstr = "";
6295 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6297 char c = StatusText.Text[i];
6298 if (Char.IsLetterOrDigit(c) || c == '_')
6304 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6305 int cnt = AtIdSupl.ItemCount;
6306 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6307 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6311 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6312 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6322 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6323 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6324 .FocusedOn(FocusedControl.ListTab)
6325 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6327 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6328 .FocusedOn(FocusedControl.ListTab)
6329 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6331 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6332 .FocusedOn(FocusedControl.ListTab)
6333 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6335 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6336 .FocusedOn(FocusedControl.ListTab)
6337 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6339 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6340 .FocusedOn(FocusedControl.ListTab)
6341 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6343 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6344 .FocusedOn(FocusedControl.ListTab)
6345 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6347 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6348 .FocusedOn(FocusedControl.ListTab)
6349 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6351 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6352 .FocusedOn(FocusedControl.ListTab)
6353 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6355 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6356 .FocusedOn(FocusedControl.ListTab)
6357 .Do(() => this.SetSortLastColumn()),
6359 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6360 .Do(() => this.FavoritesRetweetOfficial()),
6362 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6363 .Do(() => this.FavoritesRetweetUnofficial()),
6365 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6366 .Do(() => this.OpenUserAppointUrl()),
6368 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6369 .FocusedOn(FocusedControl.PostBrowser)
6370 .Do(() => this.doReTweetUnofficial()),
6372 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6373 .OnlyWhen(() => this.ExistCurrentPost)
6374 .Do(() => this.tweetDetailsView.DoTranslation()),
6376 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6377 .Do(() => this.doReTweetUnofficial()),
6379 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6380 .Do(() => this.CopyUserId()),
6382 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6383 .Do(() => this.tweetThumbnail1.ScrollUp()),
6385 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6386 .Do(() => this.tweetThumbnail1.ScrollDown()),
6388 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6389 .FocusedOn(FocusedControl.ListTab)
6390 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6391 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6395 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6397 // Task を返す非同期処理があれば asyncTask に代入する
6400 // ShortcutCommand に対応しているコマンドはここで処理される
6401 foreach (var command in this.shortcutCommands)
6403 if (command.IsMatch(keyData, focusedOn))
6405 asyncTask = command.RunCommand();
6406 return command.PreventDefault;
6413 private void GoNextTab(bool forward)
6415 int idx = ListTab.SelectedIndex;
6419 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6424 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6426 ListTab.SelectedIndex = idx;
6429 private void CopyStot()
6432 StringBuilder sb = new StringBuilder();
6433 bool IsProtected = false;
6435 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6436 foreach (int idx in _curList.SelectedIndices)
6438 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6439 if (post.IsDeleted) continue;
6442 if (post.RetweetedId != null)
6443 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6445 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6449 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6454 MessageBox.Show(Properties.Resources.CopyStotText1);
6458 clstr = sb.ToString();
6461 Clipboard.SetDataObject(clstr, false, 5, 100);
6463 catch (Exception ex)
6465 MessageBox.Show(ex.Message);
6470 private void CopyIdUri()
6472 if (this._curTab == null)
6475 var tab = this._statuses.GetTabByName(this._curTab.Text);
6476 if (tab == null || tab is DirectMessagesTabModel)
6479 var copyUrls = new List<string>();
6480 foreach (int idx in _curList.SelectedIndices)
6482 var post = tab[idx];
6483 copyUrls.Add(MyCommon.GetStatusUrl(post));
6486 if (copyUrls.Count == 0)
6491 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6493 catch (ExternalException ex)
6495 MessageBox.Show(ex.Message);
6499 private void GoFav(bool forward)
6501 if (_curList.VirtualListSize == 0) return;
6508 if (_curList.SelectedIndices.Count == 0)
6514 fIdx = _curList.SelectedIndices[0] + 1;
6515 if (fIdx > _curList.VirtualListSize - 1) return;
6517 toIdx = _curList.VirtualListSize;
6522 if (_curList.SelectedIndices.Count == 0)
6524 fIdx = _curList.VirtualListSize - 1;
6528 fIdx = _curList.SelectedIndices[0] - 1;
6529 if (fIdx < 0) return;
6535 for (int idx = fIdx; idx != toIdx; idx += stp)
6537 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6539 SelectListItem(_curList, idx);
6540 _curList.EnsureVisible(idx);
6546 private void GoSamePostToAnotherTab(bool left)
6548 if (this._curList.SelectedIndices.Count == 0)
6551 var tab = this._statuses.Tabs[this._curTab.Text];
6553 // Directタブは対象外(見つかるはずがない)
6554 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6557 var selectedIndex = this._curList.SelectedIndices[0];
6558 var selectedStatusId = tab.GetStatusIdAt(selectedIndex);
6560 int fIdx, toIdx, stp;
6565 if (ListTab.SelectedIndex == 0)
6571 fIdx = ListTab.SelectedIndex - 1;
6579 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6585 fIdx = ListTab.SelectedIndex + 1;
6587 toIdx = ListTab.TabCount;
6591 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6593 var targetTab = this._statuses.Tabs[this.ListTab.TabPages[tabidx].Text];
6596 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6599 var foundIndex = targetTab.IndexOf(selectedStatusId);
6600 if (foundIndex != -1)
6602 ListTab.SelectedIndex = tabidx;
6603 SelectListItem(_curList, foundIndex);
6604 _curList.EnsureVisible(foundIndex);
6610 private void GoPost(bool forward)
6612 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6615 var tab = this._statuses.Tabs[this._curTab.Text];
6616 var selectedIndex = this._curList.SelectedIndices[0];
6618 int fIdx, toIdx, stp;
6622 fIdx = selectedIndex + 1;
6623 if (fIdx > tab.AllCount - 1) return;
6624 toIdx = tab.AllCount;
6629 fIdx = selectedIndex - 1;
6630 if (fIdx < 0) return;
6636 if (_curPost.RetweetedId == null)
6638 name = _curPost.ScreenName;
6642 name = _curPost.RetweetedBy;
6644 for (int idx = fIdx; idx != toIdx; idx += stp)
6646 var post = tab[idx];
6647 if (post.RetweetedId == null)
6649 if (post.ScreenName == name)
6651 SelectListItem(_curList, idx);
6652 _curList.EnsureVisible(idx);
6658 if (post.RetweetedBy == name)
6660 SelectListItem(_curList, idx);
6661 _curList.EnsureVisible(idx);
6668 private void GoRelPost(bool forward)
6670 if (this._curList.SelectedIndices.Count == 0)
6673 var tab = this._statuses.Tabs[this._curTab.Text];
6674 var selectedIndex = this._curList.SelectedIndices[0];
6676 int fIdx, toIdx, stp;
6680 fIdx = selectedIndex + 1;
6681 if (fIdx > tab.AllCount - 1) return;
6682 toIdx = tab.AllCount;
6687 fIdx = selectedIndex - 1;
6688 if (fIdx < 0) return;
6695 if (_curPost == null) return;
6696 _anchorPost = _curPost;
6701 if (_anchorPost == null) return;
6704 for (int idx = fIdx; idx != toIdx; idx += stp)
6706 var post = tab[idx];
6707 if (post.ScreenName == _anchorPost.ScreenName ||
6708 post.RetweetedBy == _anchorPost.ScreenName ||
6709 post.ScreenName == _anchorPost.RetweetedBy ||
6710 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6711 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
6712 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
6713 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
6714 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
6716 SelectListItem(_curList, idx);
6717 _curList.EnsureVisible(idx);
6723 private void GoAnchor()
6725 if (_anchorPost == null) return;
6726 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6727 if (idx == -1) return;
6729 SelectListItem(_curList, idx);
6730 _curList.EnsureVisible(idx);
6733 private void GoTopEnd(bool GoTop)
6735 if (_curList.VirtualListSize == 0)
6743 _item = _curList.GetItemAt(0, 25);
6751 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6753 idx = _curList.VirtualListSize - 1;
6757 SelectListItem(_curList, idx);
6760 private void GoMiddle()
6762 if (_curList.VirtualListSize == 0)
6770 _item = _curList.GetItemAt(0, 0);
6780 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6783 idx2 = _curList.VirtualListSize - 1;
6789 idx3 = (idx1 + idx2) / 2;
6791 SelectListItem(_curList, idx3);
6794 private void GoLast()
6796 if (_curList.VirtualListSize == 0) return;
6798 if (_statuses.SortOrder == SortOrder.Ascending)
6800 SelectListItem(_curList, _curList.VirtualListSize - 1);
6801 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6805 SelectListItem(_curList, 0);
6806 _curList.EnsureVisible(0);
6810 private void MoveTop()
6812 if (_curList.SelectedIndices.Count == 0) return;
6813 int idx = _curList.SelectedIndices[0];
6814 if (_statuses.SortOrder == SortOrder.Ascending)
6816 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6820 _curList.EnsureVisible(0);
6822 _curList.EnsureVisible(idx);
6825 private async Task GoInReplyToPostTree()
6827 if (_curPost == null) return;
6829 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6831 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
6835 var post = await tw.GetStatusApi(false, _curPost.StatusId);
6837 _curPost.InReplyToStatusId = post.InReplyToStatusId;
6838 _curPost.InReplyToUser = post.InReplyToUser;
6839 _curPost.IsReply = post.IsReply;
6840 this.PurgeListViewItemCache();
6841 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
6843 catch (WebApiException ex)
6845 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6849 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
6851 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
6853 replyChains = new Stack<ReplyChain>();
6855 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
6858 string inReplyToTabName;
6859 long inReplyToId = _curPost.InReplyToStatusId.Value;
6860 string inReplyToUser = _curPost.InReplyToUser;
6861 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6863 var inReplyToPosts = from tab in _statuses.Tabs.Values
6864 orderby tab != curTabClass
6865 from post in tab.Posts.Values
6866 where post.StatusId == inReplyToId
6867 let index = tab.IndexOf(post.StatusId)
6869 select new {Tab = tab, Index = index};
6871 var inReplyPost = inReplyToPosts.FirstOrDefault();
6872 if (inReplyPost == null)
6876 await Task.Run(async () =>
6878 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
6879 .ConfigureAwait(false);
6882 _statuses.AddPost(post);
6883 _statuses.DistributePosts();
6886 catch (WebApiException ex)
6888 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6889 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6893 this.RefreshTimeline();
6895 inReplyPost = inReplyToPosts.FirstOrDefault();
6896 if (inReplyPost == null)
6898 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6902 inReplyToTabName = inReplyPost.Tab.TabName;
6903 inReplyToIndex = inReplyPost.Index;
6905 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
6906 DetailsListView listView = (DetailsListView)tabPage.Tag;
6908 if (_curTab != tabPage)
6910 this.ListTab.SelectTab(tabPage);
6913 this.SelectListItem(listView, inReplyToIndex);
6914 listView.EnsureVisible(inReplyToIndex);
6917 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6919 if (_curPost == null) return;
6921 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6922 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6926 if (_curPost.InReplyToStatusId != null)
6928 var posts = from t in _statuses.Tabs
6929 from p in t.Value.Posts
6930 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
6931 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6933 orderby isForward ? indexOf : indexOf * -1
6934 orderby t.Value != curTabClass
6935 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
6938 var postList = posts.ToList();
6939 for (int i = postList.Count - 1; i >= 0; i--)
6942 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
6944 postList.RemoveAt(index);
6947 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
6948 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
6949 if (post == null) post = postList.First();
6950 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6951 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6952 SelectListItem(listView, post.Index);
6953 listView.EnsureVisible(post.Index);
6955 catch (InvalidOperationException)
6963 if (replyChains == null || replyChains.Count < 1)
6965 var posts = from t in _statuses.Tabs
6966 from p in t.Value.Posts
6967 where p.Value.InReplyToStatusId == _curPost.StatusId
6968 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6971 orderby t.Value != curTabClass
6972 select new {Tab = t.Value, Index = indexOf};
6975 var post = posts.First();
6976 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6977 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6978 SelectListItem(listView, post.Index);
6979 listView.EnsureVisible(post.Index);
6981 catch (InvalidOperationException)
6988 ReplyChain chainHead = replyChains.Pop();
6989 if (chainHead.InReplyToId == _curPost.StatusId)
6991 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7000 ListTab.SelectTab(chainHead.OriginalTab);
7006 SelectListItem(_curList, idx);
7007 _curList.EnsureVisible(idx);
7013 this.GoBackInReplyToPostTree(parallel);
7019 private void GoBackSelectPostChain()
7021 if (this.selectPostChains.Count > 1)
7030 this.selectPostChains.Pop();
7031 var (tabPage, post) = this.selectPostChains.Peek();
7033 if (!this.ListTab.TabPages.Contains(tabPage)) continue; //該当タブが存在しないので無視
7037 idx = this._statuses.Tabs[tabPage.Text].IndexOf(post.StatusId);
7038 if (idx == -1) continue; //該当ポストが存在しないので無視
7043 this.selectPostChains.Pop();
7045 catch (InvalidOperationException)
7051 while (this.selectPostChains.Count > 1);
7056 //履歴が残り1つであればクリアしておく
7057 if (this.selectPostChains.Count == 1)
7058 this.selectPostChains.Clear();
7062 DetailsListView lst = (DetailsListView)tp.Tag;
7063 this.ListTab.SelectedTab = tp;
7066 SelectListItem(lst, idx);
7067 lst.EnsureVisible(idx);
7073 private void PushSelectPostChain()
7075 int count = this.selectPostChains.Count;
7078 var (tabPage, post) = this.selectPostChains.Peek();
7079 if (tabPage == this._curTab)
7081 if (post == this._curPost) return; //最新の履歴と同一
7082 if (post == null) this.selectPostChains.Pop(); //置き換えるため削除
7085 if (count >= 2500) TrimPostChain();
7086 this.selectPostChains.Push((this._curTab, this._curPost));
7089 private void TrimPostChain()
7091 if (this.selectPostChains.Count <= 2000) return;
7092 var p = new Stack<ValueTuple<TabPage, PostClass>>(2000);
7093 for (int i = 0; i < 2000; i++)
7095 p.Push(this.selectPostChains.Pop());
7097 this.selectPostChains.Clear();
7098 for (int i = 0; i < 2000; i++)
7100 this.selectPostChains.Push(p.Pop());
7104 private bool GoStatus(long statusId)
7106 if (statusId == 0) return false;
7107 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7109 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7111 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7112 ListTab.SelectedIndex = tabidx;
7113 SelectListItem(_curList, idx);
7114 _curList.EnsureVisible(idx);
7121 private bool GoDirectMessage(long statusId)
7123 if (statusId == 0) return false;
7124 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7126 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7128 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7129 ListTab.SelectedIndex = tabidx;
7130 SelectListItem(_curList, idx);
7131 _curList.EnsureVisible(idx);
7138 private void MyList_MouseClick(object sender, MouseEventArgs e)
7140 _anchorFlag = false;
7143 private void StatusText_Enter(object sender, EventArgs e)
7145 // フォーカスの戻り先を StatusText に設定
7146 this.Tag = StatusText;
7147 StatusText.BackColor = _clInputBackcolor;
7150 public Color InputBackColor
7152 get => _clInputBackcolor;
7153 set => _clInputBackcolor = value;
7156 private void StatusText_Leave(object sender, EventArgs e)
7158 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7159 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7160 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7163 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7165 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
7168 e.SuppressKeyPress = true;
7171 this.StatusText_TextChanged(null, null);
7173 if (asyncTask != null)
7177 private void SaveConfigsAll(bool ifModified)
7181 SaveConfigsCommon();
7188 if (ModifySettingCommon) SaveConfigsCommon();
7189 if (ModifySettingLocal) SaveConfigsLocal();
7190 if (ModifySettingAtId) SaveConfigsAtId();
7194 private void SaveConfigsAtId()
7196 if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7198 ModifySettingAtId = false;
7199 SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7200 SettingManager.SaveAtIdList();
7203 private void SaveConfigsCommon()
7205 if (_ignoreConfigSave) return;
7207 ModifySettingCommon = false;
7210 SettingManager.Common.UserName = tw.Username;
7211 SettingManager.Common.UserId = tw.UserId;
7212 SettingManager.Common.Token = tw.AccessToken;
7213 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7214 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7215 switch (_statuses.SortMode)
7217 case ComparerMode.Nickname: //ニックネーム
7218 SettingManager.Common.SortColumn = 1;
7220 case ComparerMode.Data: //本文
7221 SettingManager.Common.SortColumn = 2;
7223 case ComparerMode.Id: //時刻=発言Id
7224 SettingManager.Common.SortColumn = 3;
7226 case ComparerMode.Name: //名前
7227 SettingManager.Common.SortColumn = 4;
7229 case ComparerMode.Source: //Source
7230 SettingManager.Common.SortColumn = 7;
7234 SettingManager.Common.HashTags = HashMgr.HashHistories;
7235 if (HashMgr.IsPermanent)
7237 SettingManager.Common.HashSelected = HashMgr.UseHash;
7241 SettingManager.Common.HashSelected = "";
7243 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7244 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7245 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7246 SettingManager.Common.TrackWord = tw.TrackWord;
7247 SettingManager.Common.AllAtReply = tw.AllAtReply;
7248 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7249 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7251 SettingManager.SaveCommon();
7255 private void SaveConfigsLocal()
7257 if (_ignoreConfigSave) return;
7260 ModifySettingLocal = false;
7261 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7262 SettingManager.Local.FormSize = _mySize;
7263 SettingManager.Local.FormLocation = _myLoc;
7264 SettingManager.Local.SplitterDistance = _mySpDis;
7265 SettingManager.Local.PreviewDistance = _mySpDis3;
7266 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7267 SettingManager.Local.StatusTextHeight = _mySpDis2;
7269 SettingManager.Local.FontUnread = _fntUnread;
7270 SettingManager.Local.ColorUnread = _clUnread;
7271 SettingManager.Local.FontRead = _fntReaded;
7272 SettingManager.Local.ColorRead = _clReaded;
7273 SettingManager.Local.FontDetail = _fntDetail;
7274 SettingManager.Local.ColorDetail = _clDetail;
7275 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7276 SettingManager.Local.ColorDetailLink = _clDetailLink;
7277 SettingManager.Local.ColorFav = _clFav;
7278 SettingManager.Local.ColorOWL = _clOWL;
7279 SettingManager.Local.ColorRetweet = _clRetweet;
7280 SettingManager.Local.ColorSelf = _clSelf;
7281 SettingManager.Local.ColorAtSelf = _clAtSelf;
7282 SettingManager.Local.ColorTarget = _clTarget;
7283 SettingManager.Local.ColorAtTarget = _clAtTarget;
7284 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7285 SettingManager.Local.ColorAtTo = _clAtTo;
7286 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7287 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7288 SettingManager.Local.ColorInputFont = _clInputFont;
7289 SettingManager.Local.FontInputFont = _fntInputFont;
7291 if (_ignoreConfigSave) return;
7292 SettingManager.SaveLocal();
7296 private void SaveConfigsTabs()
7298 var tabSettingList = new List<SettingTabs.SettingTabItem>();
7300 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7301 .Select(x => this._statuses.Tabs[x.Text])
7302 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7304 foreach (var tab in tabs)
7306 if (!tab.IsPermanentTabType)
7309 var tabSetting = new SettingTabs.SettingTabItem
7311 TabName = tab.TabName,
7312 TabType = tab.TabType,
7313 UnreadManage = tab.UnreadManage,
7314 Protected = tab.Protected,
7315 Notify = tab.Notify,
7316 SoundFile = tab.SoundFile,
7321 case FilterTabModel filterTab:
7322 tabSetting.FilterArray = filterTab.FilterArray;
7324 case UserTimelineTabModel userTab:
7325 tabSetting.User = userTab.ScreenName;
7327 case PublicSearchTabModel searchTab:
7328 tabSetting.SearchWords = searchTab.SearchWords;
7329 tabSetting.SearchLang = searchTab.SearchLang;
7331 case ListTimelineTabModel listTab:
7332 tabSetting.ListInfo = listTab.ListInfo;
7336 tabSettingList.Add(tabSetting);
7339 SettingManager.Tabs.Tabs = tabSettingList;
7340 SettingManager.SaveTabs();
7343 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7345 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
7346 if (ret != DialogResult.OK)
7349 var match = Twitter.StatusUrlRegex.Match(inputText);
7352 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7353 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7359 var statusId = long.Parse(match.Groups["StatusId"].Value);
7360 await this.OpenRelatedTab(statusId);
7362 catch (TabException ex)
7364 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7368 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7370 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7371 Properties.Resources.SaveLogMenuItem_ClickText2,
7372 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7373 if (rslt == DialogResult.Cancel) return;
7375 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7376 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7377 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7378 SaveFileDialog1.FilterIndex = 0;
7379 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7380 SaveFileDialog1.RestoreDirectory = true;
7382 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7384 if (!SaveFileDialog1.ValidateNames) return;
7385 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7387 if (rslt == DialogResult.Yes)
7390 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7392 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7393 string protect = "";
7394 if (post.IsProtect) protect = "Protect";
7395 sw.WriteLine(post.Nickname + "\t" +
7396 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7397 post.CreatedAt + "\t" +
7398 post.ScreenName + "\t" +
7399 post.StatusId + "\t" +
7400 post.ImageUrl + "\t" +
7401 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7407 foreach (int idx in _curList.SelectedIndices)
7409 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7410 string protect = "";
7411 if (post.IsProtect) protect = "Protect";
7412 sw.WriteLine(post.Nickname + "\t" +
7413 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7414 post.CreatedAt + "\t" +
7415 post.ScreenName + "\t" +
7416 post.StatusId + "\t" +
7417 post.ImageUrl + "\t" +
7418 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7424 this.TopMost = SettingManager.Common.AlwaysTop;
7427 public bool TabRename(string origTabName, out string newTabName)
7431 using (InputTabName inputName = new InputTabName())
7433 inputName.TabName = origTabName;
7434 inputName.ShowDialog();
7435 if (inputName.DialogResult == DialogResult.Cancel) return false;
7436 newTabName = inputName.TabName;
7438 this.TopMost = SettingManager.Common.AlwaysTop;
7439 if (!string.IsNullOrEmpty(newTabName))
7442 for (int i = 0; i < ListTab.TabCount; i++)
7444 if (ListTab.TabPages[i].Text == newTabName)
7446 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7447 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7452 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
7453 .FirstOrDefault(x => x.Text == origTabName);
7456 if (tabPage != null)
7457 tabPage.Text = newTabName;
7459 _statuses.RenameTab(origTabName, newTabName);
7461 SaveConfigsCommon();
7463 _rclickTabName = newTabName;
7472 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7474 if (e.Button == MouseButtons.Middle)
7476 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7478 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7480 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7481 this.SaveConfigsTabs();
7488 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7490 TabRename(this.ListTab.SelectedTab.Text, out var _);
7493 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7495 if (SettingManager.Common.TabMouseLock) return;
7496 if (e.Button == MouseButtons.Left)
7498 for (int i = 0; i < ListTab.TabPages.Count; i++)
7500 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7503 _tabMouseDownPoint = e.Location;
7514 private void ListTab_DragEnter(object sender, DragEventArgs e)
7516 if (e.Data.GetDataPresent(typeof(TabPage)))
7517 e.Effect = DragDropEffects.Move;
7519 e.Effect = DragDropEffects.None;
7522 private void ListTab_DragDrop(object sender, DragEventArgs e)
7524 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7529 Point cpos = new Point(e.X, e.Y);
7530 Point spos = ListTab.PointToClient(cpos);
7532 for (i = 0; i < ListTab.TabPages.Count; i++)
7534 Rectangle rect = ListTab.GetTabRect(i);
7535 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7536 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7538 tn = ListTab.TabPages[i].Text;
7539 if (spos.X <= (rect.Left + rect.Right) / 2)
7548 //タブのないところにドロップ->最後尾へ移動
7549 if (string.IsNullOrEmpty(tn))
7551 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7553 i = ListTab.TabPages.Count - 1;
7556 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7557 if (tp.Text == tn) return;
7559 ReOrderTab(tp.Text, tn, bef);
7562 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7564 var baseIndex = this.GetTabPageIndex(baseTabText);
7565 if (baseIndex == -1)
7568 var targetIndex = this.GetTabPageIndex(targetTabText);
7569 if (targetIndex == -1)
7572 using (ControlTransaction.Layout(this.ListTab))
7574 var mTp = this.ListTab.TabPages[targetIndex];
7575 this.ListTab.TabPages.Remove(mTp);
7577 if (targetIndex < baseIndex)
7580 if (isBeforeBaseTab)
7581 ListTab.TabPages.Insert(baseIndex, mTp);
7583 ListTab.TabPages.Insert(baseIndex + 1, mTp);
7589 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7591 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7592 //isReply:true=@,false=DM
7593 if (!StatusText.Enabled) return;
7594 if (_curList == null) return;
7595 if (_curTab == null) return;
7596 if (!this.ExistCurrentPost) return;
7598 // 複数あてリプライはReplyではなく通常ポスト
7599 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7600 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7601 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7603 if (_curList.SelectedIndices.Count > 0)
7606 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7609 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7612 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7613 StatusText.SelectionStart = StatusText.Text.Length;
7615 this.inReplyTo = null;
7618 if (string.IsNullOrEmpty(StatusText.Text))
7622 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7623 StatusText.Text = "@" + _curPost.ScreenName + " ";
7625 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7626 var inReplyToScreenName = this._curPost.ScreenName;
7627 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7635 //1件選んでEnter or DoubleClick
7636 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7638 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7641 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7642 var inReplyToScreenName = this._curPost.ScreenName;
7643 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7647 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7650 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7653 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7654 this.inReplyTo = null;
7659 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7660 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7661 var inReplyToScreenName = this._curPost.ScreenName;
7662 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7669 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7670 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7671 this.inReplyTo = null;
7676 //1件選んでCtrl-Rの場合(返信先操作せず)
7677 int sidx = StatusText.SelectionStart;
7678 string id = "@" + _curPost.ScreenName + " ";
7681 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7686 StatusText.Text = StatusText.Text.Insert(sidx, id);
7688 //if (StatusText.Text.StartsWith("@"))
7691 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7692 // sidx += 5 + _curPost.ScreenName.Length;
7697 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7698 // sidx += 3 + _curPost.ScreenName.Length;
7700 StatusText.SelectionStart = sidx;
7703 //_reply_to_name = null;
7711 if (!isAuto && !isReply) return;
7713 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7717 //Enter or DoubleClick
7719 string sTxt = StatusText.Text;
7720 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7723 this.inReplyTo = null;
7725 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7727 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7728 if (!sTxt.Contains("@" + post.ScreenName + " "))
7730 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7731 //sTxt = "@" + post.ScreenName + " " + sTxt;
7734 StatusText.Text = sTxt;
7739 if (_curList.SelectedIndices.Count > 1)
7744 int sidx = StatusText.SelectionStart;
7745 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7747 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7748 if (!ids.Contains("@" + post.ScreenName + " ") &&
7749 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7751 ids += "@" + post.ScreenName + " ";
7755 foreach (string nm in post.ReplyToList)
7757 if (!ids.Contains("@" + nm + " ") &&
7758 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7760 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7762 ids += "@" + m.Result("${id}") + " ";
7764 ids += "@" + nm + " ";
7769 if (ids.Length == 0) return;
7770 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7772 StatusText.Text = ". " + StatusText.Text;
7774 this.inReplyTo = null;
7778 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7783 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7785 //if (StatusText.Text.StartsWith("@"))
7787 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7788 // sidx += 2 + ids.Length;
7792 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7793 // sidx += 1 + ids.Length;
7795 StatusText.SelectionStart = sidx;
7801 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7804 int sidx = StatusText.SelectionStart;
7805 PostClass post = _curPost;
7806 if (!ids.Contains("@" + post.ScreenName + " ") &&
7807 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7809 ids += "@" + post.ScreenName + " ";
7811 foreach (string nm in post.ReplyToList)
7813 if (!ids.Contains("@" + nm + " ") &&
7814 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7816 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7818 ids += "@" + m.Result("${id}") + " ";
7820 ids += "@" + nm + " ";
7823 if (!string.IsNullOrEmpty(post.RetweetedBy))
7825 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
7826 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7828 ids += "@" + post.RetweetedBy + " ";
7831 if (ids.Length == 0) return;
7832 if (string.IsNullOrEmpty(StatusText.Text))
7835 StatusText.Text = ids;
7836 StatusText.SelectionStart = ids.Length;
7839 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7840 var inReplyToScreenName = this._curPost.ScreenName;
7841 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7847 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7852 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7854 StatusText.SelectionStart = sidx;
7860 StatusText.SelectionStart = StatusText.Text.Length;
7865 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7870 private static int iconCnt = 0;
7871 private static int blinkCnt = 0;
7872 private static bool blink = false;
7873 private static bool idle = false;
7875 private async Task RefreshTasktrayIcon()
7878 await this.Colorize();
7880 if (!TimerRefreshIcon.Enabled) return;
7881 //Static usCheckCnt As int = 0
7883 //Static iconDlListTopItem As ListViewItem = null
7885 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7886 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7888 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7890 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7896 //if (usCheckCnt > 300) //1min
7899 // if (!this.IsReceivedUserStream)
7901 // TraceOut("ReconnectUserStream");
7902 // tw.ReconnectUserStream();
7906 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7908 if (iconCnt >= this.NIconRefresh.Length)
7916 SaveConfigsAll(true);
7921 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7923 _myStatusError = false;
7927 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
7928 if (SettingManager.Common.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
7930 if (blinkCnt > 0) return;
7932 if (blink || SettingManager.Common.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
7934 NotifyIcon1.Icon = ReplyIcon;
7938 NotifyIcon1.Icon = ReplyIconBlink;
7946 //優先度:エラー→オフライン→アイドル
7950 NotifyIcon1.Icon = NIconAtRed;
7953 if (_myStatusOnline)
7955 NotifyIcon1.Icon = NIconAt;
7959 NotifyIcon1.Icon = NIconAtSmoke;
7963 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
7966 await this.RefreshTasktrayIcon();
7969 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7971 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7972 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7974 if (ListTab != null && ListTab.SelectedTab != null)
7975 _rclickTabName = ListTab.SelectedTab.Text;
7980 if (_statuses == null) return;
7981 if (_statuses.Tabs == null) return;
7983 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out var tb))
7986 NotifyDispMenuItem.Checked = tb.Notify;
7987 this.NotifyTbMenuItem.Checked = tb.Notify;
7989 soundfileListup = true;
7990 SoundFileComboBox.Items.Clear();
7991 this.SoundFileTbComboBox.Items.Clear();
7992 SoundFileComboBox.Items.Add("");
7993 this.SoundFileTbComboBox.Items.Add("");
7994 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
7995 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
7997 oDir = oDir.GetDirectories("Sounds")[0];
7999 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8001 SoundFileComboBox.Items.Add(oFile.Name);
8002 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8004 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8005 if (idx == -1) idx = 0;
8006 SoundFileComboBox.SelectedIndex = idx;
8007 this.SoundFileTbComboBox.SelectedIndex = idx;
8008 soundfileListup = false;
8009 UreadManageMenuItem.Checked = tb.UnreadManage;
8010 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8012 TabMenuControl(_rclickTabName);
8015 private void TabMenuControl(string tabName)
8017 var tabInfo = _statuses.GetTabByName(tabName);
8019 this.FilterEditMenuItem.Enabled = true;
8020 this.EditRuleTbMenuItem.Enabled = true;
8022 if (tabInfo.IsDefaultTabType)
8024 this.ProtectTabMenuItem.Enabled = false;
8025 this.ProtectTbMenuItem.Enabled = false;
8029 this.ProtectTabMenuItem.Enabled = true;
8030 this.ProtectTbMenuItem.Enabled = true;
8033 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8035 this.ProtectTabMenuItem.Checked = true;
8036 this.ProtectTbMenuItem.Checked = true;
8037 this.DeleteTabMenuItem.Enabled = false;
8038 this.DeleteTbMenuItem.Enabled = false;
8042 this.ProtectTabMenuItem.Checked = false;
8043 this.ProtectTbMenuItem.Checked = false;
8044 this.DeleteTabMenuItem.Enabled = true;
8045 this.DeleteTbMenuItem.Enabled = true;
8049 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8051 var checkState = ((ToolStripMenuItem)sender).Checked;
8054 this.ProtectTbMenuItem.Checked = checkState;
8055 this.ProtectTabMenuItem.Checked = checkState;
8058 this.DeleteTabMenuItem.Enabled = !checkState;
8059 this.DeleteTbMenuItem.Enabled = !checkState;
8061 if (string.IsNullOrEmpty(_rclickTabName)) return;
8062 _statuses.Tabs[_rclickTabName].Protected = checkState;
8067 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8069 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8070 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8072 if (string.IsNullOrEmpty(_rclickTabName)) return;
8073 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8078 public void ChangeTabUnreadManage(string tabName, bool isManage)
8080 var idx = this.GetTabPageIndex(tabName);
8084 _statuses.Tabs[tabName].UnreadManage = isManage;
8085 if (SettingManager.Common.TabIconDisp)
8087 if (_statuses.Tabs[tabName].UnreadCount > 0)
8088 ListTab.TabPages[idx].ImageIndex = 0;
8090 ListTab.TabPages[idx].ImageIndex = -1;
8093 if (_curTab.Text == tabName)
8095 this.PurgeListViewItemCache();
8099 SetMainWindowTitle();
8100 SetStatusLabelUrl();
8101 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8104 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8106 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8107 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8109 if (string.IsNullOrEmpty(_rclickTabName)) return;
8111 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8116 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8118 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8120 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8125 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8127 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8129 RemoveSpecifiedTab(_rclickTabName, true);
8133 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8135 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8137 using (var fltDialog = new FilterDialog())
8139 fltDialog.Owner = this;
8140 fltDialog.SetCurrent(_rclickTabName);
8141 fltDialog.ShowDialog(this);
8143 this.TopMost = SettingManager.Common.AlwaysTop;
8145 this.ApplyPostFilters();
8149 private void AddTabMenuItem_Click(object sender, EventArgs e)
8151 string tabName = null;
8152 MyCommon.TabUsageType tabUsage;
8153 using (InputTabName inputName = new InputTabName())
8155 inputName.TabName = _statuses.MakeTabName("MyTab");
8156 inputName.IsShowUsage = true;
8157 inputName.ShowDialog();
8158 if (inputName.DialogResult == DialogResult.Cancel) return;
8159 tabName = inputName.TabName;
8160 tabUsage = inputName.Usage;
8162 this.TopMost = SettingManager.Common.AlwaysTop;
8163 if (!string.IsNullOrEmpty(tabName))
8166 ListElement list = null;
8167 if (tabUsage == MyCommon.TabUsageType.Lists)
8169 using (ListAvailable listAvail = new ListAvailable())
8171 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8172 if (listAvail.SelectedList == null) return;
8173 list = listAvail.SelectedList;
8180 case MyCommon.TabUsageType.UserDefined:
8181 tab = new FilterTabModel(tabName);
8183 case MyCommon.TabUsageType.PublicSearch:
8184 tab = new PublicSearchTabModel(tabName);
8186 case MyCommon.TabUsageType.Lists:
8187 tab = new ListTimelineTabModel(tabName, list);
8193 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8195 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8196 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8202 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8204 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8205 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8207 if (tabUsage == MyCommon.TabUsageType.Lists)
8209 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8210 var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8211 this.GetListTimelineAsync(listTab);
8217 private void TabMenuItem_Click(object sender, EventArgs e)
8219 using (var fltDialog = new FilterDialog())
8221 fltDialog.Owner = this;
8224 foreach (int idx in _curList.SelectedIndices)
8227 if (!SelectTab(out var tabName)) return;
8229 fltDialog.SetCurrent(tabName);
8230 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8232 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8236 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8238 fltDialog.ShowDialog(this);
8239 this.TopMost = SettingManager.Common.AlwaysTop;
8243 this.ApplyPostFilters();
8245 if (this.ListTab.SelectedTab != null &&
8246 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8248 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8252 protected override bool ProcessDialogKey(Keys keyData)
8254 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8255 if ((keyData & Keys.KeyCode) == Keys.Enter)
8257 if (StatusText.Focused)
8259 bool _NewLine = false;
8262 if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8264 if (StatusText.Multiline)
8266 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8268 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8272 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8276 else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8278 if (StatusText.Multiline)
8280 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8282 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8286 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8292 if (StatusText.Multiline)
8294 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8296 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8297 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8301 if (((keyData & Keys.Shift) == Keys.Shift) ||
8302 (((keyData & Keys.Control) != Keys.Control) &&
8303 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8309 int pos1 = StatusText.SelectionStart;
8310 if (StatusText.SelectionLength > 0)
8312 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8314 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8315 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8320 PostButton_Click(null, null);
8324 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8325 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8326 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8328 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8333 return base.ProcessDialogKey(keyData);
8336 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8338 MakeReplyOrDirectStatus(false, true, true);
8341 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8344 if (_curList.SelectedIndices.Count == 0) return;
8346 var tab = this._statuses.Tabs[this._curTab.Text];
8347 var screenNameArray = this._curList.SelectedIndices.Cast<int>()
8348 .Select(x => tab[x])
8349 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8352 this.AddFilterRuleByScreenName(screenNameArray);
8354 if (screenNameArray.Length != 0)
8356 List<string> atids = new List<string>();
8357 foreach (var screenName in screenNameArray)
8359 atids.Add("@" + screenName);
8361 int cnt = AtIdSupl.ItemCount;
8362 AtIdSupl.AddRangeItem(atids.ToArray());
8363 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8367 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8369 if (this._curList.SelectedIndices.Count == 0)
8372 var tab = this._statuses.Tabs[this._curTab.Text];
8373 var sourceArray = this._curList.SelectedIndices.Cast<int>()
8374 .Select(x => tab[x].Source).ToArray();
8376 this.AddFilterRuleBySource(sourceArray);
8379 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8382 if (!SelectTab(out var tabName)) return;
8384 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8388 if (tab.TabType != MyCommon.TabUsageType.Mute)
8390 this.MoveOrCopy(out mv, out mk);
8394 // ミュートタブでは常に MoveMatches を true にする
8399 foreach (var screenName in screenNameArray)
8401 tab.AddFilter(new PostFilterRule
8403 FilterName = screenName,
8404 UseNameField = true,
8408 FilterByUrl = false,
8412 this.ApplyPostFilters();
8416 public void AddFilterRuleBySource(params string[] sourceArray)
8418 // タブ選択ダイアログを表示(or追加)
8419 if (!this.SelectTab(out var tabName))
8422 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8426 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8428 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8429 this.MoveOrCopy(out mv, out mk);
8433 // ミュートタブでは常に MoveMatches を true にする
8438 // 振り分けルールに追加するSource
8439 foreach (var source in sourceArray)
8441 filterTab.AddFilter(new PostFilterRule
8443 FilterSource = source,
8447 FilterByUrl = false,
8451 this.ApplyPostFilters();
8452 this.SaveConfigsTabs();
8455 private bool SelectTab(out string tabName)
8462 using (var dialog = new TabsDialog(_statuses))
8464 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8466 var selectedTab = dialog.SelectedTab;
8467 tabName = selectedTab == null ? null : selectedTab.TabName;
8470 ListTab.SelectedTab.Focus();
8472 if (tabName == null)
8474 using (InputTabName inputName = new InputTabName())
8476 inputName.TabName = _statuses.MakeTabName("MyTab");
8477 inputName.ShowDialog();
8478 if (inputName.DialogResult == DialogResult.Cancel) return false;
8479 tabName = inputName.TabName;
8481 this.TopMost = SettingManager.Common.AlwaysTop;
8482 if (!string.IsNullOrEmpty(tabName))
8484 var tab = new FilterTabModel(tabName);
8485 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8487 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8488 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8506 private void MoveOrCopy(out bool move, out bool mark)
8510 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8511 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8519 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8520 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8530 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8535 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8540 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8542 if (StatusText.Focused)
8545 StatusText.SelectAll();
8549 // ListView上でのCtrl+A
8550 NativeMethods.SelectAllItems(this._curList);
8554 private void MoveMiddle()
8560 if (_curList.SelectedIndices.Count == 0) return;
8562 int idx = _curList.SelectedIndices[0];
8564 _item = _curList.GetItemAt(0, 25);
8570 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8572 idx2 = _curList.VirtualListSize - 1;
8576 idx -= Math.Abs(idx1 - idx2) / 2;
8577 if (idx < 0) idx = 0;
8579 _curList.EnsureVisible(_curList.VirtualListSize - 1);
8580 _curList.EnsureVisible(idx);
8583 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8585 var linkElements = this.tweetDetailsView.GetLinkElements();
8587 if (linkElements.Length > 0)
8589 UrlDialog.ClearUrl();
8591 string openUrlStr = "";
8593 if (linkElements.Length == 1)
8595 // ツイートに含まれる URL が 1 つのみの場合
8596 // => OpenURL ダイアログを表示せずにリンクを開く
8601 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8603 catch (ArgumentException)
8612 if (string.IsNullOrEmpty(urlStr)) return;
8613 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8615 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8616 await this.OpenUriAsync(new Uri(openUrlStr));
8620 // ツイートに含まれる URL が複数ある場合
8621 // => OpenURL を表示しユーザーが選択したリンクを開く
8623 foreach (var linkElm in linkElements)
8626 string linkText = "";
8630 urlStr = linkElm.GetAttribute("title");
8631 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8632 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8633 linkText = linkElm.InnerText;
8635 catch (ArgumentException)
8644 if (string.IsNullOrEmpty(urlStr)) continue;
8645 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8649 if (UrlDialog.ShowDialog() == DialogResult.OK)
8651 openUrlStr = UrlDialog.SelectedUrl;
8653 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8654 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8661 this.TopMost = SettingManager.Common.AlwaysTop;
8666 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8668 if (string.IsNullOrEmpty(_rclickTabName)) return;
8669 ClearTab(_rclickTabName, true);
8672 private void ClearTab(string tabName, bool showWarning)
8676 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8677 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8683 _statuses.ClearTabIds(tabName);
8684 if (ListTab.SelectedTab.Text == tabName)
8687 _anchorFlag = false;
8688 this.PurgeListViewItemCache();
8692 foreach (TabPage tb in ListTab.TabPages)
8694 if (tb.Text == tabName)
8696 ((DetailsListView)tb.Tag).VirtualListSize = 0;
8701 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8703 SetMainWindowTitle();
8704 SetStatusLabelUrl();
8707 private static long followers = 0;
8709 private void SetMainWindowTitle()
8712 StringBuilder ttl = new StringBuilder(256);
8715 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8716 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8717 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8718 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8720 foreach (var tab in _statuses.Tabs.Values)
8722 ur += tab.UnreadCount;
8727 if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8728 ttl.Append(Application.ProductName);
8730 switch (SettingManager.Common.DispLatestPost)
8732 case MyCommon.DispTitleEnum.Ver:
8733 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8735 case MyCommon.DispTitleEnum.Post:
8736 if (_history != null && _history.Count > 1)
8737 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8739 case MyCommon.DispTitleEnum.UnreadRepCount:
8740 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8742 case MyCommon.DispTitleEnum.UnreadAllCount:
8743 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8745 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8746 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8748 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8749 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8751 case MyCommon.DispTitleEnum.OwnStatus:
8752 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8753 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8759 this.Text = ttl.ToString();
8761 catch (AccessViolationException)
8763 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8767 private string GetStatusLabelText()
8770 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8771 if (_statuses == null) return "";
8772 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8773 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8774 if (tbRep == null || tbDm == null) return "";
8775 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8780 StringBuilder slbl = new StringBuilder(256);
8783 foreach (var tab in _statuses.Tabs.Values)
8785 ur += tab.UnreadCount;
8787 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
8789 tur = tab.UnreadCount;
8800 UnreadAtCounter = urat;
8802 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8804 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8805 if (SettingManager.Common.TimelinePeriod == 0)
8807 slbl.Append(Properties.Resources.SetStatusLabelText2);
8811 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8813 return slbl.ToString();
8816 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8820 if (this.InvokeRequired && !this.IsDisposed)
8822 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8826 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8827 SetApiStatusLabel(endpointName);
8830 catch (ObjectDisposedException)
8834 catch (InvalidOperationException)
8840 private void SetApiStatusLabel(string endpointName = null)
8842 if (_curTab == null)
8844 this.toolStripApiGauge.ApiEndpoint = null;
8848 var tabType = _statuses.Tabs[_curTab.Text].TabType;
8850 if (endpointName == null)
8855 case MyCommon.TabUsageType.Home:
8856 case MyCommon.TabUsageType.UserDefined:
8857 endpointName = "/statuses/home_timeline";
8860 case MyCommon.TabUsageType.Mentions:
8861 endpointName = "/statuses/mentions_timeline";
8864 case MyCommon.TabUsageType.Favorites:
8865 endpointName = "/favorites/list";
8868 case MyCommon.TabUsageType.DirectMessage:
8869 endpointName = "/direct_messages";
8872 case MyCommon.TabUsageType.UserTimeline:
8873 endpointName = "/statuses/user_timeline";
8876 case MyCommon.TabUsageType.Lists:
8877 endpointName = "/lists/statuses";
8880 case MyCommon.TabUsageType.PublicSearch:
8881 endpointName = "/search/tweets";
8884 case MyCommon.TabUsageType.Related:
8885 endpointName = "/statuses/show/:id";
8892 this.toolStripApiGauge.ApiEndpoint = endpointName;
8896 // 表示中のタブに関連する endpoint であれば更新
8899 switch (endpointName)
8901 case "/statuses/home_timeline":
8902 update = tabType == MyCommon.TabUsageType.Home ||
8903 tabType == MyCommon.TabUsageType.UserDefined;
8906 case "/statuses/mentions_timeline":
8907 update = tabType == MyCommon.TabUsageType.Mentions;
8910 case "/favorites/list":
8911 update = tabType == MyCommon.TabUsageType.Favorites;
8914 case "/direct_messages:":
8915 update = tabType == MyCommon.TabUsageType.DirectMessage;
8918 case "/statuses/user_timeline":
8919 update = tabType == MyCommon.TabUsageType.UserTimeline;
8922 case "/lists/statuses":
8923 update = tabType == MyCommon.TabUsageType.Lists;
8926 case "/search/tweets":
8927 update = tabType == MyCommon.TabUsageType.PublicSearch;
8930 case "/statuses/show/:id":
8931 update = tabType == MyCommon.TabUsageType.Related;
8940 this.toolStripApiGauge.ApiEndpoint = endpointName;
8946 private void SetStatusLabelUrl()
8948 StatusLabelUrl.Text = GetStatusLabelText();
8951 public void SetStatusLabel(string text)
8953 StatusLabel.Text = text;
8956 private void SetNotifyIconText()
8958 var ur = new StringBuilder(64);
8960 // タスクトレイアイコンのツールチップテキスト書き換え
8962 ur.Remove(0, ur.Length);
8963 if (SettingManager.Common.DispUsername)
8965 ur.Append(tw.Username);
8968 ur.Append(Application.ProductName);
8970 ur.Append("(Debug Build)");
8972 if (UnreadCounter != -1 && UnreadAtCounter != -1)
8975 ur.Append(UnreadCounter);
8977 ur.Append(UnreadAtCounter);
8980 NotifyIcon1.Text = ur.ToString();
8983 internal void CheckReplyTo(string StatusText)
8987 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
8989 foreach (Match hm in m)
8991 if (!hstr.Contains("#" + hm.Result("$3") + " "))
8993 hstr += "#" + hm.Result("$3") + " ";
8994 HashSupl.AddItem("#" + hm.Result("$3"));
8997 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
8999 hstr += HashMgr.UseHash;
9001 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9003 // 本当にリプライ先指定すべきかどうかの判定
9004 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9006 if (SettingManager.Common.UseAtIdSupplement)
9008 int bCnt = AtIdSupl.ItemCount;
9009 foreach (Match mid in m)
9011 AtIdSupl.AddItem(mid.Result("${id}"));
9013 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9016 // リプライ先ステータスIDの指定がない場合は指定しない
9017 if (this.inReplyTo == null)
9021 // 次の条件を満たす場合に in_reply_to_status_id 指定
9022 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9023 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9024 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9028 var inReplyToScreenName = this.inReplyTo.Item2;
9029 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9031 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9035 foreach (Match mid in m)
9037 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9042 this.inReplyTo = null;
9045 private void TweenMain_Resize(object sender, EventArgs e)
9047 if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
9049 this.Visible = false;
9051 if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
9053 // 現在の DPI と設定保存時の DPI との比を取得する
9054 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9056 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
9059 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
9060 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9061 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9063 this.SplitContainer1.SplitterDistance = splitterDistance;
9067 StatusText.Multiline = SettingManager.Local.StatusMultiline;
9068 if (StatusText.Multiline)
9070 var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
9071 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9072 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9074 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9076 StatusText.Height = statusTextHeight;
9080 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9082 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9086 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
9087 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9089 this.SplitContainer3.SplitterDistance = previewDistance;
9092 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9093 this.SplitContainer3.Panel2Collapsed = true;
9095 _initialLayout = false;
9097 if (this.WindowState != FormWindowState.Minimized)
9099 _formWindowState = this.WindowState;
9103 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9105 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9106 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9107 if (PlaySoundMenuItem.Checked)
9109 SettingManager.Common.PlaySound = true;
9113 SettingManager.Common.PlaySound = false;
9115 ModifySettingCommon = true;
9118 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9120 if (this._initialLayout)
9123 int splitterDistance;
9124 switch (this.WindowState)
9126 case FormWindowState.Normal:
9127 splitterDistance = this.SplitContainer1.SplitterDistance;
9129 case FormWindowState.Maximized:
9130 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9131 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9132 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9133 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9139 this._mySpDis = splitterDistance;
9140 this.ModifySettingLocal = true;
9143 private async Task doRepliedStatusOpen()
9145 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9147 if (MyCommon.IsKeyDown(Keys.Shift))
9149 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9152 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9154 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9155 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9159 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9161 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9162 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9163 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9166 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9171 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9173 await this.doRepliedStatusOpen();
9176 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9178 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9179 if (multiline != this.StatusText.Multiline)
9181 this.StatusText.Multiline = multiline;
9182 SettingManager.Local.StatusMultiline = multiline;
9183 ModifySettingLocal = true;
9187 private void StatusText_MultilineChanged(object sender, EventArgs e)
9189 if (this.StatusText.Multiline)
9190 this.StatusText.ScrollBars = ScrollBars.Vertical;
9192 this.StatusText.ScrollBars = ScrollBars.None;
9194 ModifySettingLocal = true;
9197 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9200 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
9201 StatusText.Multiline = menuItemChecked;
9202 SettingManager.Local.StatusMultiline = menuItemChecked;
9203 if (menuItemChecked)
9205 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9206 SplitContainer2.SplitterDistance = 0;
9208 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9212 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9214 ModifySettingLocal = true;
9217 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9219 if (Converter_Type == MyCommon.UrlConverter.Bitly || Converter_Type == MyCommon.UrlConverter.Jmp)
9221 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
9222 if (string.IsNullOrEmpty(SettingManager.Common.BitlyAccessToken) &&
9223 (string.IsNullOrEmpty(SettingManager.Common.BilyUser) || string.IsNullOrEmpty(SettingManager.Common.BitlyPwd)))
9225 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
9230 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9231 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9233 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9234 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9235 //Appendix A. Collected ABNF for URI
9236 //http://www.ietf.org/rfc/rfc3986.txt
9240 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9242 if (StatusText.SelectionLength > 0)
9244 string tmp = StatusText.SelectedText;
9245 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9246 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9248 // 文字列が選択されている場合はその文字列について処理
9250 //nico.ms使用、nicovideoにマッチしたら変換
9251 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9253 result = nicoms.Shorten(tmp);
9255 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9257 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9260 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9261 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9262 result = resultUri.AbsoluteUri;
9264 catch (WebApiException e)
9266 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9269 catch (UriFormatException e)
9271 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9280 if (!string.IsNullOrEmpty(result))
9282 urlUndo undotmp = new urlUndo();
9284 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9285 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9286 if (origUrlIndex == -1)
9289 StatusText.Select(origUrlIndex, tmp.Length);
9290 StatusText.SelectedText = result;
9293 undotmp.Before = tmp;
9294 undotmp.After = result;
9296 if (urlUndoBuffer == null)
9298 urlUndoBuffer = new List<urlUndo>();
9299 UrlUndoToolStripMenuItem.Enabled = true;
9302 urlUndoBuffer.Add(undotmp);
9308 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9309 @"(?<url>(?<protocol>https?://)" +
9310 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9311 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9312 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9313 // 正規表現にマッチしたURL文字列をtinyurl化
9314 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9316 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9317 string tmp = mt.Result("${url}");
9318 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9319 urlUndo undotmp = new urlUndo();
9322 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9324 //nico.ms使用、nicovideoにマッチしたら変換
9325 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9327 result = nicoms.Shorten(tmp);
9329 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9331 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9334 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9335 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9336 result = resultUri.AbsoluteUri;
9338 catch (HttpRequestException e)
9340 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9341 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9342 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9344 this.StatusLabel.Text = Converter_Type + ":" + message;
9347 catch (WebApiException e)
9349 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9352 catch (UriFormatException e)
9354 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9363 if (!string.IsNullOrEmpty(result))
9365 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9366 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9367 if (origUrlIndex == -1)
9370 StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9371 StatusText.SelectedText = result;
9373 undotmp.Before = mt.Result("${url}");
9374 undotmp.After = result;
9376 if (urlUndoBuffer == null)
9378 urlUndoBuffer = new List<urlUndo>();
9379 UrlUndoToolStripMenuItem.Enabled = true;
9382 urlUndoBuffer.Add(undotmp);
9390 private void doUrlUndo()
9392 if (urlUndoBuffer != null)
9394 string tmp = StatusText.Text;
9395 foreach (urlUndo data in urlUndoBuffer)
9397 tmp = tmp.Replace(data.After, data.Before);
9399 StatusText.Text = tmp;
9400 urlUndoBuffer = null;
9401 UrlUndoToolStripMenuItem.Enabled = false;
9402 StatusText.SelectionStart = 0;
9403 StatusText.SelectionLength = 0;
9407 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9409 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9412 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9414 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9417 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9419 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9422 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9424 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9427 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9429 if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9431 MyCommon.UrlConverter svc = SettingManager.Common.AutoShortUrlFirst;
9432 Random rnd = new Random();
9433 // 前回使用した短縮URLサービス以外を選択する
9436 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9438 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9439 await UrlConvertAsync(svc);
9443 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9448 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9450 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9451 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9452 SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9453 ModifySettingCommon = true;
9456 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9458 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9459 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9460 SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9461 ModifySettingCommon = true;
9464 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9466 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9467 MenuStrip1.Tag = new Object();
9468 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9471 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9473 if (this.Tag != null) // 設定された戻り先へ遷移
9475 if (this.Tag == this.ListTab.SelectedTab)
9476 ((Control)this.ListTab.SelectedTab.Tag).Select();
9478 ((Control)this.Tag).Select();
9480 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9482 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9484 this.Tag = ListTab.SelectedTab.Tag;
9485 ((Control)this.Tag).Select();
9488 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9489 MenuStrip1.Tag = null;
9492 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9494 DetailsListView lst = (DetailsListView)sender;
9495 if (SettingManager.Local == null) return;
9499 SettingManager.Local.Width1 = lst.Columns[0].Width;
9500 SettingManager.Local.Width3 = lst.Columns[1].Width;
9504 int[] darr = new int[lst.Columns.Count];
9505 for (int i = 0; i < lst.Columns.Count; i++)
9507 darr[lst.Columns[i].DisplayIndex] = i;
9509 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9511 for (int i = 0; i < lst.Columns.Count; i++)
9516 SettingManager.Local.DisplayIndex1 = i;
9519 SettingManager.Local.DisplayIndex2 = i;
9522 SettingManager.Local.DisplayIndex3 = i;
9525 SettingManager.Local.DisplayIndex4 = i;
9528 SettingManager.Local.DisplayIndex5 = i;
9531 SettingManager.Local.DisplayIndex6 = i;
9534 SettingManager.Local.DisplayIndex7 = i;
9537 SettingManager.Local.DisplayIndex8 = i;
9541 SettingManager.Local.Width1 = lst.Columns[0].Width;
9542 SettingManager.Local.Width2 = lst.Columns[1].Width;
9543 SettingManager.Local.Width3 = lst.Columns[2].Width;
9544 SettingManager.Local.Width4 = lst.Columns[3].Width;
9545 SettingManager.Local.Width5 = lst.Columns[4].Width;
9546 SettingManager.Local.Width6 = lst.Columns[5].Width;
9547 SettingManager.Local.Width7 = lst.Columns[6].Width;
9548 SettingManager.Local.Width8 = lst.Columns[7].Width;
9550 ModifySettingLocal = true;
9551 _isColumnChanged = true;
9554 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9556 DetailsListView lst = (DetailsListView)sender;
9557 if (SettingManager.Local == null) return;
9560 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9562 SettingManager.Local.Width1 = lst.Columns[0].Width;
9563 ModifySettingLocal = true;
9564 _isColumnChanged = true;
9566 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9568 SettingManager.Local.Width3 = lst.Columns[1].Width;
9569 ModifySettingLocal = true;
9570 _isColumnChanged = true;
9575 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9577 SettingManager.Local.Width1 = lst.Columns[0].Width;
9578 ModifySettingLocal = true;
9579 _isColumnChanged = true;
9581 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9583 SettingManager.Local.Width2 = lst.Columns[1].Width;
9584 ModifySettingLocal = true;
9585 _isColumnChanged = true;
9587 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9589 SettingManager.Local.Width3 = lst.Columns[2].Width;
9590 ModifySettingLocal = true;
9591 _isColumnChanged = true;
9593 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9595 SettingManager.Local.Width4 = lst.Columns[3].Width;
9596 ModifySettingLocal = true;
9597 _isColumnChanged = true;
9599 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9601 SettingManager.Local.Width5 = lst.Columns[4].Width;
9602 ModifySettingLocal = true;
9603 _isColumnChanged = true;
9605 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9607 SettingManager.Local.Width6 = lst.Columns[5].Width;
9608 ModifySettingLocal = true;
9609 _isColumnChanged = true;
9611 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9613 SettingManager.Local.Width7 = lst.Columns[6].Width;
9614 ModifySettingLocal = true;
9615 _isColumnChanged = true;
9617 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9619 SettingManager.Local.Width8 = lst.Columns[7].Width;
9620 ModifySettingLocal = true;
9621 _isColumnChanged = true;
9624 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9627 // SaveConfigsLocal();
9631 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9633 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9634 ModifySettingLocal = true;
9637 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9639 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9641 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9643 SelectMedia_DragDrop(e);
9646 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9648 var (url, title) = GetUrlFromDataObject(e.Data);
9654 appendText = title + " " + url;
9656 if (this.StatusText.TextLength == 0)
9657 this.StatusText.Text = appendText;
9659 this.StatusText.Text += " " + appendText;
9661 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9663 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9665 this.StatusText.Text += text;
9667 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9669 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9670 if (data != null) StatusText.Text += data;
9675 /// IDataObject から URL とタイトルの対を取得します
9678 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9680 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9681 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9682 internal static (string Url, string Title) GetUrlFromDataObject(IDataObject data)
9684 if (data.GetDataPresent("text/x-moz-url"))
9686 // Firefox, Google Chrome で利用可能
9687 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9689 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9691 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9692 if (lines.Length < 2)
9693 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9695 return (lines[0], lines[1]);
9698 else if (data.GetDataPresent("IESiteModeToUrl"))
9700 // Internet Exproler 用
9701 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9703 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9705 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9706 if (lines.Length < 2)
9707 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9709 return (lines[0], lines[1]);
9712 else if (data.GetDataPresent("UniformResourceLocatorW"))
9716 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9718 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9723 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9726 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9728 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9730 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9732 SelectMedia_DragEnter(e);
9736 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9738 e.Effect = DragDropEffects.Copy;
9741 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9743 e.Effect = DragDropEffects.Copy;
9746 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9748 e.Effect = DragDropEffects.Copy;
9752 e.Effect = DragDropEffects.None;
9755 private void TweenMain_DragOver(object sender, DragEventArgs e)
9759 public bool IsNetworkAvailable()
9762 nw = MyCommon.IsNetworkAvailable();
9763 _myStatusOnline = nw;
9767 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9769 var uriStr = uri.AbsoluteUri;
9771 // OpenTween 内部で使用する URL
9772 if (uri.Authority == "opentween")
9774 await this.OpenInternalUriAsync(uri);
9778 // ハッシュタグを含む Twitter 検索
9779 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9782 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9783 var pos = unescapedQuery.IndexOf('#');
9784 if (pos == -1) return;
9786 var hash = unescapedQuery.Substring(pos);
9787 this.HashSupl.AddItem(hash);
9788 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9789 this.AddNewTabForSearch(hash);
9794 // フラグが立っている場合は設定と逆の動作をする
9795 if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9796 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9798 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9799 if (userUriMatch.Success)
9801 var screenName = userUriMatch.Groups["ScreenName"].Value;
9802 if (this.IsTwitterId(screenName))
9804 this.AddNewTabForUserTimeline(screenName);
9811 await this.OpenUriInBrowserAsync(uriStr);
9815 /// OpenTween 内部の機能を呼び出すための URL を開きます
9817 private async Task OpenInternalUriAsync(Uri uri)
9819 // ツイートを開く (//opentween/status/:status_id)
9820 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9823 var statusId = long.Parse(match.Groups[1].Value);
9824 await this.OpenRelatedTab(statusId);
9829 public Task OpenUriInBrowserAsync(string UriString)
9831 return Task.Run(() =>
9833 string myPath = UriString;
9837 var configBrowserPath = SettingManager.Local.BrowserPath;
9838 if (!string.IsNullOrEmpty(configBrowserPath))
9840 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9842 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9843 string browserPath = configBrowserPath.Substring(1, sep - 1);
9845 if (sep < configBrowserPath.Length - 1)
9847 arg = configBrowserPath.Substring(sep + 1);
9849 myPath = arg + " " + myPath;
9850 System.Diagnostics.Process.Start(browserPath, myPath);
9854 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9859 System.Diagnostics.Process.Start(myPath);
9864 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9869 private void ListTabSelect(TabPage _tab)
9873 this.PurgeListViewItemCache();
9876 _curList = (DetailsListView)_tab.Tag;
9878 if (_curList.SelectedIndices.Count > 0)
9880 _curItemIndex = _curList.SelectedIndices[0];
9881 _curPost = GetCurTabPost(_curItemIndex);
9890 _anchorFlag = false;
9894 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
9898 for (int i = 0; i < _curList.Columns.Count; i++)
9900 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
9905 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9907 ListTabSelect(e.TabPage);
9910 private void SelectListItem(DetailsListView LView, int Index)
9913 Rectangle bnd = new Rectangle();
9915 var item = LView.FocusedItem;
9924 LView.SelectedIndices.Clear();
9926 while (LView.SelectedIndices.Count > 0);
9927 item = LView.Items[Index];
9928 item.Selected = true;
9929 item.Focused = true;
9931 if (flg) LView.Invalidate(bnd);
9934 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9937 Rectangle bnd = new Rectangle();
9939 var item = LView.FocusedItem;
9950 LView.SelectedIndices.Clear();
9952 while (LView.SelectedIndices.Count > 0);
9953 LView.SelectItems(Index);
9955 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9957 LView.SelectionMark = selectionMarkIndex;
9959 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9961 LView.Items[focusedIndex].Focused = true;
9963 else if (Index != null && Index.Length != 0)
9965 LView.Items[Index.Last()].Focused = true;
9968 if (flg) LView.Invalidate(bnd);
9971 private void StartUserStream()
9973 tw.NewPostFromStream += tw_NewPostFromStream;
9974 tw.UserStreamStarted += tw_UserStreamStarted;
9975 tw.UserStreamStopped += tw_UserStreamStopped;
9976 tw.PostDeleted += tw_PostDeleted;
9977 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9979 this.RefreshUserStreamsMenu();
9981 if (SettingManager.Common.UserstreamStartup)
9982 tw.StartUserStream();
9985 private async void TweenMain_Shown(object sender, EventArgs e)
9987 NotifyIcon1.Visible = true;
9989 if (this.IsNetworkAvailable())
9993 var loadTasks = new List<Task>
9995 this.RefreshMuteUserIdsAsync(),
9996 this.RefreshBlockIdsAsync(),
9997 this.RefreshNoRetweetIdsAsync(),
9998 this.RefreshTwitterConfigurationAsync(),
9999 this.GetHomeTimelineAsync(),
10000 this.GetReplyAsync(),
10001 this.GetDirectMessagesAsync(),
10002 this.GetPublicSearchAllAsync(),
10003 this.GetUserTimelineAllAsync(),
10004 this.GetListTimelineAllAsync(),
10007 if (SettingManager.Common.StartupFollowers)
10008 loadTasks.Add(this.RefreshFollowerIdsAsync());
10010 if (SettingManager.Common.GetFav)
10011 loadTasks.Add(this.GetFavoritesAsync());
10013 var allTasks = Task.WhenAll(loadTasks);
10018 var timeout = Task.Delay(5000);
10019 if (await Task.WhenAny(allTasks, timeout) != timeout)
10023 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10025 if (MyCommon._endingFlag)
10029 if (MyCommon._endingFlag) return;
10031 if (ApplicationSettings.VersionInfoUrl != null)
10033 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10034 if (SettingManager.Common.StartupVersion)
10035 await this.CheckNewVersion(true);
10039 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10040 this.VerUpMenuItem.Enabled = false;
10041 this.VerUpMenuItem.Available = false;
10042 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10045 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10046 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10048 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10049 SettingStripMenuItem_Click(null, null);
10053 var reloadTasks = new List<Task>();
10055 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
10056 reloadTasks.Add(this.RefreshFollowerIdsAsync());
10058 if (!tw.GetNoRetweetSuccess)
10059 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10061 if (this.tw.Configuration.PhotoSizeLimit == 0)
10062 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10064 await Task.WhenAll(reloadTasks);
10069 TimerTimeline.Enabled = true;
10072 private async Task doGetFollowersMenu()
10074 await this.RefreshFollowerIdsAsync();
10075 await this.DispSelectedPost(true);
10078 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10080 await this.doGetFollowersMenu();
10083 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10085 doReTweetUnofficial();
10088 private async Task doReTweetOfficial(bool isConfirm)
10091 if (this.ExistCurrentPost)
10093 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10095 if (this._curPost.IsProtect)
10096 MessageBox.Show("Protected.");
10098 _DoFavRetweetFlags = false;
10101 if (_curList.SelectedIndices.Count > 15)
10103 MessageBox.Show(Properties.Resources.RetweetLimitText);
10104 _DoFavRetweetFlags = false;
10107 else if (_curList.SelectedIndices.Count > 1)
10109 string QuestionText = Properties.Resources.RetweetQuestion2;
10110 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10111 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10113 case DialogResult.Cancel:
10114 case DialogResult.No:
10115 _DoFavRetweetFlags = false;
10121 if (!SettingManager.Common.RetweetNoConfirm)
10123 string Questiontext = Properties.Resources.RetweetQuestion1;
10124 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10125 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10127 _DoFavRetweetFlags = false;
10133 var statusIds = new List<long>();
10134 foreach (int idx in _curList.SelectedIndices)
10136 PostClass post = GetCurTabPost(idx);
10137 if (post.CanRetweetBy(this.twitterApi.CurrentUserId))
10138 statusIds.Add(post.StatusId);
10141 await this.RetweetAsync(statusIds);
10145 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10147 await this.doReTweetOfficial(true);
10150 private async Task FavoritesRetweetOfficial()
10152 if (!this.ExistCurrentPost) return;
10153 _DoFavRetweetFlags = true;
10154 var retweetTask = this.doReTweetOfficial(true);
10155 if (_DoFavRetweetFlags)
10157 _DoFavRetweetFlags = false;
10158 var favoriteTask = this.FavoriteChange(true, false);
10160 await Task.WhenAll(retweetTask, favoriteTask);
10168 private async Task FavoritesRetweetUnofficial()
10170 if (this.ExistCurrentPost && !_curPost.IsDm)
10172 _DoFavRetweetFlags = true;
10173 var favoriteTask = this.FavoriteChange(true);
10174 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10176 _DoFavRetweetFlags = false;
10177 doReTweetUnofficial();
10180 await favoriteTask;
10185 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10187 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10188 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10189 /// <returns>復元されたツイート本文</returns>
10190 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10192 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10195 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10197 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10199 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10203 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10205 statusHtml = statusHtml.Replace("<br>", " ");
10207 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10208 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10209 statusHtml = statusHtml.Replace(" ", " ");
10211 return WebUtility.HtmlDecode(statusHtml);
10214 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10216 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10218 if (_curPost != null)
10219 await this.DispSelectedPost(true);
10222 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10224 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10225 DebugModeToolStripMenuItem.Visible = true;
10227 DebugModeToolStripMenuItem.Visible = false;
10230 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
10232 this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
10235 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
10237 this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
10240 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
10242 SettingManager.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
10245 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
10247 SettingManager.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
10248 ModifySettingCommon = true;
10251 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10253 SettingManager.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
10254 ModifySettingCommon = true;
10257 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
10259 UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
10260 PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
10261 UrlAutoShortenMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10262 IdeographicSpaceToSpaceMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10263 MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
10264 FocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10267 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10269 UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
10270 PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
10271 UrlAutoShortenPullDownMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10272 IdeographicSpaceToSpacePullDownMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10273 MultiLinePullDownMenuItem.Checked = SettingManager.Local.StatusMultiline;
10274 FocusLockPullDownMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10277 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10279 if (TraceOutToolStripMenuItem.Checked)
10280 MyCommon.TraceFlag = true;
10282 MyCommon.TraceFlag = false;
10285 private void TweenMain_Deactivate(object sender, EventArgs e)
10287 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10288 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10291 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10293 if (string.IsNullOrEmpty(_rclickTabName)) return;
10295 TabRename(_rclickTabName, out var _);
10298 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10300 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10303 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10305 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10308 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10310 TwitterApiStatus apiStatus;
10312 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10314 var cancellationToken = dialog.EnableCancellation();
10318 var task = this.tw.GetInfoApi();
10319 apiStatus = await dialog.WaitForAsync(this, task);
10321 catch (WebApiException)
10326 if (cancellationToken.IsCancellationRequested)
10329 if (apiStatus == null)
10331 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10336 using (var apiDlg = new ApiInfoDialog())
10338 apiDlg.ShowDialog(this);
10342 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10344 var id = _curPost?.ScreenName ?? "";
10346 await this.FollowCommand(id);
10349 internal async Task FollowCommand(string id)
10351 using (var inputName = new InputTabName())
10353 inputName.FormTitle = "Follow";
10354 inputName.FormDescription = Properties.Resources.FRMessage1;
10355 inputName.TabName = id;
10357 if (inputName.ShowDialog(this) != DialogResult.OK)
10359 if (string.IsNullOrWhiteSpace(inputName.TabName))
10362 id = inputName.TabName.Trim();
10365 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10369 var task = this.twitterApi.FriendshipsCreate(id).IgnoreResponse();
10370 await dialog.WaitForAsync(this, task);
10372 catch (WebApiException ex)
10374 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10379 MessageBox.Show(Properties.Resources.FRMessage3);
10382 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10384 var id = _curPost?.ScreenName ?? "";
10386 await this.RemoveCommand(id, false);
10389 internal async Task RemoveCommand(string id, bool skipInput)
10393 using (var inputName = new InputTabName())
10395 inputName.FormTitle = "Unfollow";
10396 inputName.FormDescription = Properties.Resources.FRMessage1;
10397 inputName.TabName = id;
10399 if (inputName.ShowDialog(this) != DialogResult.OK)
10401 if (string.IsNullOrWhiteSpace(inputName.TabName))
10404 id = inputName.TabName.Trim();
10408 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10412 var task = this.twitterApi.FriendshipsDestroy(id).IgnoreResponse();
10413 await dialog.WaitForAsync(this, task);
10415 catch (WebApiException ex)
10417 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10422 MessageBox.Show(Properties.Resources.FRMessage3);
10425 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10427 var id = _curPost?.ScreenName ?? "";
10429 await this.ShowFriendship(id);
10432 internal async Task ShowFriendship(string id)
10434 using (var inputName = new InputTabName())
10436 inputName.FormTitle = "Show Friendships";
10437 inputName.FormDescription = Properties.Resources.FRMessage1;
10438 inputName.TabName = id;
10440 if (inputName.ShowDialog(this) != DialogResult.OK)
10442 if (string.IsNullOrWhiteSpace(inputName.TabName))
10445 id = inputName.TabName.Trim();
10448 bool isFollowing, isFollowed;
10450 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10452 var cancellationToken = dialog.EnableCancellation();
10456 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10457 var friendship = await dialog.WaitForAsync(this, task);
10459 isFollowing = friendship.Relationship.Source.Following;
10460 isFollowed = friendship.Relationship.Source.FollowedBy;
10462 catch (WebApiException ex)
10464 if (!cancellationToken.IsCancellationRequested)
10465 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10469 if (cancellationToken.IsCancellationRequested)
10473 string result = "";
10476 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10480 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10484 result += Properties.Resources.GetFriendshipInfo3;
10488 result += Properties.Resources.GetFriendshipInfo4;
10490 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10491 MessageBox.Show(result);
10494 internal async Task ShowFriendship(string[] ids)
10496 foreach (string id in ids)
10498 bool isFollowing, isFollowed;
10500 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10502 var cancellationToken = dialog.EnableCancellation();
10506 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10507 var friendship = await dialog.WaitForAsync(this, task);
10509 isFollowing = friendship.Relationship.Source.Following;
10510 isFollowed = friendship.Relationship.Source.FollowedBy;
10512 catch (WebApiException ex)
10514 if (!cancellationToken.IsCancellationRequested)
10515 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10519 if (cancellationToken.IsCancellationRequested)
10523 string result = "";
10529 ff += Properties.Resources.GetFriendshipInfo1;
10533 ff += Properties.Resources.GetFriendshipInfo2;
10536 ff += System.Environment.NewLine + " ";
10539 ff += Properties.Resources.GetFriendshipInfo3;
10543 ff += Properties.Resources.GetFriendshipInfo4;
10545 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10548 if (MessageBox.Show(
10549 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10550 MessageBoxButtons.YesNo,
10551 MessageBoxIcon.Question,
10552 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10554 await this.RemoveCommand(id, true);
10559 MessageBox.Show(result);
10564 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10566 await this.doShowUserStatus(tw.Username, false);
10567 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
10569 // doShowUserStatus(tw.Username, false);
10573 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
10578 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10579 // URLから切り出した文字列を渡す
10581 public bool IsTwitterId(string name)
10583 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10584 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10586 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
10589 private void doQuoteOfficial()
10591 if (this.ExistCurrentPost)
10593 if (_curPost.IsDm ||
10594 !StatusText.Enabled) return;
10596 if (_curPost.IsProtect)
10598 MessageBox.Show("Protected.");
10602 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10604 StatusText.Text += " " + MyCommon.GetStatusUrl(_curPost);
10606 this.inReplyTo = null;
10608 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10609 StatusText.Focus();
10613 private void doReTweetUnofficial()
10616 if (this.ExistCurrentPost)
10618 if (_curPost.IsDm || !StatusText.Enabled)
10621 if (_curPost.IsProtect)
10623 MessageBox.Show("Protected.");
10626 string rtdata = _curPost.Text;
10627 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10629 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10631 StatusText.Text += " RT @" + _curPost.ScreenName + ": " + rtdata;
10633 // 投稿時に in_reply_to_status_id を付加する
10634 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
10635 var inReplyToScreenName = this._curPost.ScreenName;
10636 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
10638 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10639 StatusText.Focus();
10643 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
10648 private void SearchButton_Click(object sender, EventArgs e)
10651 Control pnl = ((Control)sender).Parent;
10652 if (pnl == null) return;
10653 string tbName = pnl.Parent.Text;
10654 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10655 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10656 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10657 cmb.Text = cmb.Text.Trim();
10658 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10659 bool Quote = false;
10660 StringBuilder buf = new StringBuilder();
10661 char[] c = cmb.Text.ToCharArray();
10662 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10664 if (cnt > cmb.Text.Length - 4)
10666 buf.Append(cmb.Text.Substring(cnt));
10675 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10677 buf.Append(" OR ");
10682 buf.Append(c[cnt]);
10684 cmb.Text = buf.ToString();
10686 var listView = (DetailsListView)pnl.Parent.Tag;
10688 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10690 tb.SearchWords = cmb.Text;
10691 tb.SearchLang = cmbLang.Text;
10692 if (string.IsNullOrEmpty(cmb.Text))
10700 int idx = cmb.Items.IndexOf(tb.SearchWords);
10701 if (idx > -1) cmb.Items.RemoveAt(idx);
10702 cmb.Items.Insert(0, tb.SearchWords);
10703 cmb.Text = tb.SearchWords;
10705 this.PurgeListViewItemCache();
10706 listView.VirtualListSize = 0;
10707 _statuses.ClearTabIds(tbName);
10708 SaveConfigsTabs(); //検索条件の保存
10711 this.GetPublicSearchAsync(tb);
10715 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10718 await this.DoRefreshMore();
10722 /// 指定されたタブのListTabにおける位置を返します
10725 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10727 public int GetTabPageIndex(string tabName)
10730 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
10732 if (tabPage.Text == tabName)
10741 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10743 if (_statuses.RemovedTab.Count == 0)
10745 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10750 DetailsListView listView = null;
10752 TabModel tb = _statuses.RemovedTab.Pop();
10753 if (tb.TabType == MyCommon.TabUsageType.Related)
10755 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10756 if (relatedTab != null)
10758 // 関連発言なら既存のタブを置き換える
10759 tb.TabName = relatedTab.TabName;
10760 this.ClearTab(tb.TabName, false);
10761 _statuses.Tabs[tb.TabName] = tb;
10763 for (int i = 0; i < ListTab.TabPages.Count; i++)
10765 var tabPage = ListTab.TabPages[i];
10766 if (tb.TabName == tabPage.Text)
10768 listView = (DetailsListView)tabPage.Tag;
10769 ListTab.SelectedIndex = i;
10776 const string TabName = "Related Tweets";
10777 string renamed = TabName;
10778 for (int i = 2; i <= 100; i++)
10780 if (!_statuses.ContainsTab(renamed)) break;
10781 renamed = TabName + i;
10783 tb.TabName = renamed;
10785 _statuses.AddTab(tb);
10786 AddNewTab(tb, startup: false);
10788 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10789 listView = (DetailsListView)tabPage.Tag;
10790 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10795 string renamed = tb.TabName;
10796 for (int i = 1; i < int.MaxValue; i++)
10798 if (!_statuses.ContainsTab(renamed)) break;
10799 renamed = tb.TabName + "(" + i + ")";
10801 tb.TabName = renamed;
10803 _statuses.AddTab(tb);
10804 AddNewTab(tb, startup: false);
10806 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10807 listView = (DetailsListView)tabPage.Tag;
10808 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10812 if (listView != null)
10814 using (ControlTransaction.Update(listView))
10816 listView.VirtualListSize = tb.AllCount;
10822 private async Task doMoveToRTHome()
10824 if (_curList.SelectedIndices.Count > 0)
10826 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
10827 if (post.RetweetedId != null)
10829 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
10834 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10836 await this.doMoveToRTHome();
10839 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10841 var screenName = this._curPost?.ScreenName;
10842 if (screenName != null)
10843 this.ListManageUserContext(screenName);
10846 public void ListManageUserContext(string screenName)
10848 using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10850 listSelectForm.ShowDialog(this);
10854 private void SearchControls_Enter(object sender, EventArgs e)
10856 Control pnl = (Control)sender;
10857 foreach (Control ctl in pnl.Controls)
10859 ctl.TabStop = true;
10863 private void SearchControls_Leave(object sender, EventArgs e)
10865 Control pnl = (Control)sender;
10866 foreach (Control ctl in pnl.Controls)
10868 ctl.TabStop = false;
10872 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10874 if (ListTab.SelectedTab != null)
10876 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
10877 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
10881 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10883 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10886 private void HashManageMenuItem_Click(object sender, EventArgs e)
10888 DialogResult rslt = DialogResult.Cancel;
10891 rslt = HashMgr.ShowDialog();
10897 this.TopMost = SettingManager.Common.AlwaysTop;
10898 if (rslt == DialogResult.Cancel) return;
10899 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10901 HashStripSplitButton.Text = HashMgr.UseHash;
10902 HashTogglePullDownMenuItem.Checked = true;
10903 HashToggleMenuItem.Checked = true;
10907 HashStripSplitButton.Text = "#[-]";
10908 HashTogglePullDownMenuItem.Checked = false;
10909 HashToggleMenuItem.Checked = false;
10911 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10913 // int sidx = StatusText.SelectionStart;
10914 // string hash = HashMgr.UseHash + " ";
10917 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10918 // hash = " " + hash;
10920 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
10921 // sidx += hash.Length;
10922 // StatusText.SelectionStart = sidx;
10923 // StatusText.Focus();
10925 ModifySettingCommon = true;
10926 this.StatusText_TextChanged(null, null);
10929 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10931 HashMgr.ToggleHash();
10932 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10934 HashStripSplitButton.Text = HashMgr.UseHash;
10935 HashToggleMenuItem.Checked = true;
10936 HashTogglePullDownMenuItem.Checked = true;
10940 HashStripSplitButton.Text = "#[-]";
10941 HashToggleMenuItem.Checked = false;
10942 HashTogglePullDownMenuItem.Checked = false;
10944 ModifySettingCommon = true;
10945 this.StatusText_TextChanged(null, null);
10948 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10950 HashToggleMenuItem_Click(null, null);
10953 public void SetPermanentHashtag(string hashtag)
10955 HashMgr.SetPermanentHash("#" + hashtag);
10956 HashStripSplitButton.Text = HashMgr.UseHash;
10957 HashTogglePullDownMenuItem.Checked = true;
10958 HashToggleMenuItem.Checked = true;
10960 ModifySettingCommon = true;
10963 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10965 if (ListTab.SelectedTab == null) return;
10966 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
10967 if (!this.ExistCurrentPost)
10969 this.ReplyOpMenuItem.Enabled = false;
10970 this.ReplyAllOpMenuItem.Enabled = false;
10971 this.DmOpMenuItem.Enabled = false;
10972 this.ShowProfMenuItem.Enabled = false;
10973 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10974 this.ListManageMenuItem.Enabled = false;
10975 this.OpenFavOpMenuItem.Enabled = false;
10976 this.CreateTabRuleOpMenuItem.Enabled = false;
10977 this.CreateIdRuleOpMenuItem.Enabled = false;
10978 this.CreateSourceRuleOpMenuItem.Enabled = false;
10979 this.ReadOpMenuItem.Enabled = false;
10980 this.UnreadOpMenuItem.Enabled = false;
10984 this.ReplyOpMenuItem.Enabled = true;
10985 this.ReplyAllOpMenuItem.Enabled = true;
10986 this.DmOpMenuItem.Enabled = true;
10987 this.ShowProfMenuItem.Enabled = true;
10988 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10989 this.ListManageMenuItem.Enabled = true;
10990 this.OpenFavOpMenuItem.Enabled = true;
10991 this.CreateTabRuleOpMenuItem.Enabled = true;
10992 this.CreateIdRuleOpMenuItem.Enabled = true;
10993 this.CreateSourceRuleOpMenuItem.Enabled = true;
10994 this.ReadOpMenuItem.Enabled = true;
10995 this.UnreadOpMenuItem.Enabled = true;
10998 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
11000 this.FavOpMenuItem.Enabled = false;
11001 this.UnFavOpMenuItem.Enabled = false;
11002 this.OpenStatusOpMenuItem.Enabled = false;
11003 this.OpenFavotterOpMenuItem.Enabled = false;
11004 this.ShowRelatedStatusesMenuItem2.Enabled = false;
11005 this.RtOpMenuItem.Enabled = false;
11006 this.RtUnOpMenuItem.Enabled = false;
11007 this.QtOpMenuItem.Enabled = false;
11008 this.FavoriteRetweetMenuItem.Enabled = false;
11009 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11013 this.FavOpMenuItem.Enabled = true;
11014 this.UnFavOpMenuItem.Enabled = true;
11015 this.OpenStatusOpMenuItem.Enabled = true;
11016 this.OpenFavotterOpMenuItem.Enabled = true;
11017 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
11019 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
11021 this.RtOpMenuItem.Enabled = false;
11022 this.RtUnOpMenuItem.Enabled = false;
11023 this.QtOpMenuItem.Enabled = false;
11024 this.FavoriteRetweetMenuItem.Enabled = false;
11025 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11029 this.RtOpMenuItem.Enabled = true;
11030 this.RtUnOpMenuItem.Enabled = true;
11031 this.QtOpMenuItem.Enabled = true;
11032 this.FavoriteRetweetMenuItem.Enabled = true;
11033 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11037 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11039 this.RefreshPrevOpMenuItem.Enabled = true;
11043 this.RefreshPrevOpMenuItem.Enabled = false;
11045 if (!this.ExistCurrentPost
11046 || _curPost.InReplyToStatusId == null)
11048 OpenRepSourceOpMenuItem.Enabled = false;
11052 OpenRepSourceOpMenuItem.Enabled = true;
11054 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11056 OpenRterHomeMenuItem.Enabled = false;
11060 OpenRterHomeMenuItem.Enabled = true;
11063 if (this.ExistCurrentPost)
11065 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11069 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11071 ContextMenuTabProperty_Opening(sender, null);
11074 public Twitter TwitterInstance
11079 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11081 if (this._initialLayout)
11084 int splitterDistance;
11085 switch (this.WindowState)
11087 case FormWindowState.Normal:
11088 splitterDistance = this.SplitContainer3.SplitterDistance;
11090 case FormWindowState.Maximized:
11091 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11092 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11093 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11094 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11100 this._mySpDis3 = splitterDistance;
11101 this.ModifySettingLocal = true;
11104 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11106 if (_statuses.RemovedTab.Count == 0)
11108 UndoRemoveTabMenuItem.Enabled = false;
11112 UndoRemoveTabMenuItem.Enabled = true;
11114 if (ListTab.SelectedTab != null)
11116 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11117 PublicSearchQueryMenuItem.Enabled = true;
11119 PublicSearchQueryMenuItem.Enabled = false;
11123 PublicSearchQueryMenuItem.Enabled = false;
11125 if (!this.ExistCurrentPost)
11127 this.CopySTOTMenuItem.Enabled = false;
11128 this.CopyURLMenuItem.Enabled = false;
11129 this.CopyUserIdStripMenuItem.Enabled = false;
11133 this.CopySTOTMenuItem.Enabled = true;
11134 this.CopyURLMenuItem.Enabled = true;
11135 this.CopyUserIdStripMenuItem.Enabled = true;
11136 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11137 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11141 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11143 SetNotifyIconText();
11146 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11148 var id = _curPost?.ScreenName ?? "";
11150 await this.ShowUserStatus(id);
11153 private async Task doShowUserStatus(string id, bool ShowInputDialog)
11155 TwitterUser user = null;
11157 if (ShowInputDialog)
11159 using (var inputName = new InputTabName())
11161 inputName.FormTitle = "Show UserStatus";
11162 inputName.FormDescription = Properties.Resources.FRMessage1;
11163 inputName.TabName = id;
11165 if (inputName.ShowDialog(this) != DialogResult.OK)
11167 if (string.IsNullOrWhiteSpace(inputName.TabName))
11170 id = inputName.TabName.Trim();
11174 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11176 var cancellationToken = dialog.EnableCancellation();
11180 var task = this.twitterApi.UsersShow(id);
11181 user = await dialog.WaitForAsync(this, task);
11183 catch (WebApiException ex)
11185 if (!cancellationToken.IsCancellationRequested)
11186 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11190 if (cancellationToken.IsCancellationRequested)
11194 await this.doShowUserStatus(user);
11197 private async Task doShowUserStatus(TwitterUser user)
11199 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
11201 var showUserTask = userDialog.ShowUserAsync(user);
11202 userDialog.ShowDialog(this);
11205 this.BringToFront();
11207 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11208 await showUserTask;
11212 internal Task ShowUserStatus(string id, bool ShowInputDialog)
11214 return this.doShowUserStatus(id, ShowInputDialog);
11217 internal Task ShowUserStatus(string id)
11219 return this.doShowUserStatus(id, true);
11222 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
11224 if (_curPost != null)
11226 await this.ShowUserStatus(_curPost.ScreenName, false);
11230 private async void RtCountMenuItem_Click(object sender, EventArgs e)
11232 if (!this.ExistCurrentPost)
11235 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11236 TwitterStatus status;
11238 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11240 var cancellationToken = dialog.EnableCancellation();
11244 var task = this.twitterApi.StatusesShow(statusId);
11245 status = await dialog.WaitForAsync(this, task);
11247 catch (WebApiException ex)
11249 if (!cancellationToken.IsCancellationRequested)
11250 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11254 if (cancellationToken.IsCancellationRequested)
11258 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11261 private HookGlobalHotkey _hookGlobalHotkey;
11264 _hookGlobalHotkey = new HookGlobalHotkey(this);
11266 // この呼び出しは、Windows フォーム デザイナで必要です。
11267 InitializeComponent();
11269 // InitializeComponent() 呼び出しの後で初期化を追加します。
11271 if (!this.DesignMode)
11273 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11274 this.StatusText.Dock = DockStyle.Fill;
11277 this.tweetDetailsView.Owner = this;
11279 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11280 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11281 this.gh.NotifyClicked += GrowlHelper_Callback;
11283 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11284 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11286 this.ImageSelector.Visible = false;
11287 this.ImageSelector.Enabled = false;
11288 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11290 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11292 this.ReplaceAppName();
11293 this.InitializeShortcuts();
11296 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11298 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11301 this.Visible = false;
11303 else if (Form.ActiveForm == null)
11305 this.Visible = true;
11306 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11308 this.BringToFront();
11309 this.StatusText.Focus();
11313 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11315 this.MultiLinePullDownMenuItem.PerformClick();
11318 public PostClass CurPost
11320 get { return _curPost; }
11324 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11326 if (ImageSelector.Visible)
11327 ImageSelector.EndSelection();
11329 ImageSelector.BeginSelection();
11332 private void SelectMedia_DragEnter(DragEventArgs e)
11334 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11336 e.Effect = DragDropEffects.Copy;
11339 e.Effect = DragDropEffects.None;
11342 private void SelectMedia_DragDrop(DragEventArgs e)
11345 this.BringToFront();
11346 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11347 StatusText.Focus();
11350 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11352 TimelinePanel.Visible = false;
11353 TimelinePanel.Enabled = false;
11356 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11358 TimelinePanel.Visible = true;
11359 TimelinePanel.Enabled = true;
11360 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11363 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11365 this.AllowDrop = false;
11368 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11370 this.AllowDrop = true;
11373 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11375 if (ImageSelector.Visible)
11377 ModifySettingCommon = true;
11378 SaveConfigsAll(true);
11380 this.StatusText_TextChanged(null, null);
11384 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11386 this.StatusText_TextChanged(null, null);
11390 /// StatusTextでCtrl+Vが押下された時の処理
11392 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11396 if (Clipboard.ContainsText())
11398 // clipboardにテキストがある場合は貼り付け処理
11399 this.StatusText.Paste(Clipboard.GetText());
11401 else if (Clipboard.ContainsImage())
11404 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11405 Properties.Resources.PostPictureWarn4,
11406 MessageBoxButtons.OKCancel,
11407 MessageBoxIcon.Question,
11408 MessageBoxDefaultButton.Button2)
11409 == DialogResult.OK)
11411 // clipboardから画像を取得
11412 using (var image = Clipboard.GetImage())
11414 this.ImageSelector.BeginSelection(image);
11419 catch (ExternalException ex)
11421 MessageBox.Show(ex.Message);
11426 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11428 using (ListManage form = new ListManage(tw))
11430 form.ShowDialog(this);
11434 public bool ModifySettingCommon { get; set; }
11435 public bool ModifySettingLocal { get; set; }
11436 public bool ModifySettingAtId { get; set; }
11438 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11440 if (this.ExistCurrentPost && !_curPost.IsDm)
11441 RtCountMenuItem.Enabled = true;
11443 RtCountMenuItem.Enabled = false;
11445 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11446 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11448 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11451 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11456 private void CopyUserId()
11458 if (_curPost == null) return;
11459 string clstr = _curPost.ScreenName;
11462 Clipboard.SetDataObject(clstr, false, 5, 100);
11464 catch (Exception ex)
11466 MessageBox.Show(ex.Message);
11470 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11472 if (this.ExistCurrentPost && !_curPost.IsDm)
11476 await this.OpenRelatedTab(this._curPost);
11478 catch (TabException ex)
11480 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11486 /// 指定されたツイートに対する関連発言タブを開きます
11488 /// <param name="statusId">表示するツイートのID</param>
11489 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11490 public async Task OpenRelatedTab(long statusId)
11492 var post = this._statuses[statusId];
11497 post = await this.tw.GetStatusApi(false, statusId);
11499 catch (WebApiException ex)
11501 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11506 await this.OpenRelatedTab(post);
11510 /// 指定されたツイートに対する関連発言タブを開きます
11512 /// <param name="post">表示する対象となるツイート</param>
11513 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11514 private async Task OpenRelatedTab(PostClass post)
11516 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11517 if (tabRelated != null)
11519 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11522 var tabName = this._statuses.MakeTabName("Related Tweets");
11524 tabRelated = new RelatedPostsTabModel(tabName, post);
11525 tabRelated.UnreadManage = false;
11526 tabRelated.Notify = false;
11528 this._statuses.AddTab(tabRelated);
11529 this.AddNewTab(tabRelated, startup: false);
11532 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
11534 tabPage = this.ListTab.TabPages[i];
11535 if (tabName == tabPage.Text)
11537 this.ListTab.SelectedIndex = i;
11542 await this.GetRelatedTweetsAsync(tabRelated);
11544 tabPage = this.ListTab.TabPages.Cast<TabPage>()
11545 .FirstOrDefault(x => x.Text == tabRelated.TabName);
11547 if (tabPage != null)
11549 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11551 var listView = (DetailsListView)tabPage.Tag;
11552 var targetPost = tabRelated.TargetPost;
11553 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11555 if (index != -1 && index < listView.Items.Count)
11557 listView.SelectedIndices.Add(index);
11558 listView.Items[index].Focused = true;
11563 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11565 StringBuilder buf = new StringBuilder();
11566 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11567 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11568 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11569 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11570 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11573 private void tw_UserIdChanged()
11575 this.ModifySettingCommon = true;
11578 #region "Userstream"
11579 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11583 if (InvokeRequired && !IsDisposed)
11585 await this.InvokeAsync(async () =>
11587 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11588 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
11590 this.PurgeListViewItemCache();
11591 ((DetailsListView)_curTab.Tag).Update();
11592 if (_curPost != null && _curPost.StatusId == e.StatusId)
11593 await this.DispSelectedPost(true);
11599 catch (ObjectDisposedException)
11603 catch (InvalidOperationException)
11609 private int userStreamsRefreshing = 0;
11611 private async void tw_NewPostFromStream(object sender, EventArgs e)
11613 if (SettingManager.Common.ReadOldPosts)
11615 _statuses.SetReadHomeTab(); //新着時未読クリア
11618 this._statuses.DistributePosts();
11620 if (SettingManager.Common.UserstreamPeriod > 0) return;
11622 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
11623 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
11627 await this.InvokeAsync(() => this.RefreshTimeline())
11628 .ConfigureAwait(false);
11632 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
11637 private async void tw_UserStreamStarted(object sender, EventArgs e)
11641 if (InvokeRequired && !IsDisposed)
11643 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11647 catch (ObjectDisposedException)
11651 catch (InvalidOperationException)
11656 this.RefreshUserStreamsMenu();
11657 this.MenuItemUserStream.Enabled = true;
11659 StatusLabel.Text = "UserStream Started.";
11662 private async void tw_UserStreamStopped(object sender, EventArgs e)
11666 if (InvokeRequired && !IsDisposed)
11668 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11672 catch (ObjectDisposedException)
11676 catch (InvalidOperationException)
11681 this.RefreshUserStreamsMenu();
11682 this.MenuItemUserStream.Enabled = true;
11684 StatusLabel.Text = "UserStream Stopped.";
11687 private void RefreshUserStreamsMenu()
11689 if (this.tw.UserStreamActive)
11691 this.MenuItemUserStream.Text = "&UserStream ▶";
11692 this.StopToolStripMenuItem.Text = "&Stop";
11696 this.MenuItemUserStream.Text = "&UserStream ■";
11697 this.StopToolStripMenuItem.Text = "&Start";
11701 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11705 if (InvokeRequired && !IsDisposed)
11707 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11711 catch (ObjectDisposedException)
11715 catch (InvalidOperationException)
11719 var ev = e.EventData;
11720 StatusLabel.Text = "Event: " + ev.Event;
11721 //if (ev.Event == "favorite")
11723 // NotifyFavorite(ev);
11726 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11728 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
11730 this.PurgeListViewItemCache();
11731 ((DetailsListView)_curTab.Tag).Update();
11733 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
11735 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11736 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11741 private void NotifyEvent(Twitter.FormattedEvent ev)
11744 if (BalloonRequired(ev))
11746 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11747 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11748 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11749 StringBuilder title = new StringBuilder();
11750 if (SettingManager.Common.DispUsername)
11752 title.Append(tw.Username);
11753 title.Append(" - ");
11759 title.Append(Application.ProductName);
11760 title.Append(" [");
11761 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11762 title.Append("] by ");
11763 if (!string.IsNullOrEmpty(ev.Username))
11765 title.Append(ev.Username);
11769 //title.Append("");
11772 if (!string.IsNullOrEmpty(ev.Target))
11774 //NotifyIcon1.BalloonTipText = ev.Target;
11779 //NotifyIcon1.BalloonTipText = " ";
11782 //NotifyIcon1.ShowBalloonTip(500);
11783 if (SettingManager.Common.IsUseNotifyGrowl)
11785 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11786 ev.Id.ToString(), title.ToString(), text);
11790 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11791 NotifyIcon1.BalloonTipTitle = title.ToString();
11792 NotifyIcon1.BalloonTipText = text;
11793 NotifyIcon1.ShowBalloonTip(500);
11798 string snd = SettingManager.Common.EventSoundFile;
11799 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11801 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11805 string dir = Application.StartupPath;
11806 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11808 dir = Path.Combine(dir, "Sounds");
11810 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11822 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11824 MenuItemUserStream.Enabled = false;
11825 if (StopRefreshAllMenuItem.Checked)
11827 StopRefreshAllMenuItem.Checked = false;
11830 if (this.tw.UserStreamActive)
11832 tw.StopUserStream();
11836 tw.StartUserStream();
11840 private static string inputTrack = "";
11842 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11844 if (TrackToolStripMenuItem.Checked)
11846 using (InputTabName inputForm = new InputTabName())
11848 inputForm.TabName = inputTrack;
11849 inputForm.FormTitle = "Input track word";
11850 inputForm.FormDescription = "Track word";
11851 if (inputForm.ShowDialog() != DialogResult.OK)
11853 TrackToolStripMenuItem.Checked = false;
11856 inputTrack = inputForm.TabName.Trim();
11858 if (!inputTrack.Equals(tw.TrackWord))
11860 tw.TrackWord = inputTrack;
11861 this.ModifySettingCommon = true;
11862 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11863 tw.ReconnectUserStream();
11869 tw.ReconnectUserStream();
11871 this.ModifySettingCommon = true;
11874 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11876 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11877 this.ModifySettingCommon = true;
11878 tw.ReconnectUserStream();
11881 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11883 if (evtDialog == null || evtDialog.IsDisposed)
11886 evtDialog = new EventViewerDialog();
11887 evtDialog.Owner = this;
11889 Point pos = evtDialog.Location;
11890 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
11891 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
11892 evtDialog.Location = pos;
11894 evtDialog.EventSource = tw.StoredEvent;
11895 if (!evtDialog.Visible)
11897 evtDialog.Show(this);
11901 evtDialog.Activate();
11903 this.TopMost = SettingManager.Common.AlwaysTop;
11907 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11909 MyCommon._endingFlag = true;
11913 Application.Restart();
11917 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
11921 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
11923 if (!string.IsNullOrEmpty(tw.Username))
11924 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
11927 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11929 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11932 private bool ExistCurrentPost
11936 if (_curPost == null) return false;
11937 if (_curPost.IsDeleted) return false;
11942 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11944 ShowUserTimeline();
11947 private string GetUserIdFromCurPostOrInput(string caption)
11949 var id = _curPost?.ScreenName ?? "";
11951 using (InputTabName inputName = new InputTabName())
11953 inputName.FormTitle = caption;
11954 inputName.FormDescription = Properties.Resources.FRMessage1;
11955 inputName.TabName = id;
11956 if (inputName.ShowDialog() == DialogResult.OK &&
11957 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11959 id = inputName.TabName.Trim();
11969 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11971 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11972 if (!string.IsNullOrEmpty(id))
11974 AddNewTabForUserTimeline(id);
11978 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
11980 string id = GetUserIdFromCurPostOrInput("Show Favstar");
11981 if (!string.IsNullOrEmpty(id))
11983 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
11987 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11989 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
11992 private void TimelineRefreshEnableChange(bool isEnable)
11996 tw.StartUserStream();
12000 tw.StopUserStream();
12002 TimerTimeline.Enabled = isEnable;
12005 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
12007 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
12010 private async Task OpenUserAppointUrl()
12012 if (SettingManager.Common.UserAppointUrl != null)
12014 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
12016 if (_curPost != null)
12018 string xUrl = SettingManager.Common.UserAppointUrl;
12019 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
12021 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
12022 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
12024 await this.OpenUriInBrowserAsync(xUrl);
12029 await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
12034 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12036 await this.OpenUserAppointUrl();
12039 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
12041 if (Form.ActiveForm == null)
12043 await this.InvokeAsync(() =>
12045 this.Visible = true;
12046 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12048 this.BringToFront();
12049 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
12051 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12055 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12061 private void ReplaceAppName()
12063 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12064 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12067 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12069 this.SplitContainer3.Panel2Collapsed = false;
12072 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12074 await this.OpenThumbnailPicture(e.Thumbnail);
12077 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
12079 await this.OpenUriInBrowserAsync(e.ImageUrl);
12082 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
12084 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
12086 await this.OpenUriInBrowserAsync(url);
12089 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
12091 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
12094 private void PostButton_KeyDown(object sender, KeyEventArgs e)
12096 if (e.KeyCode == Keys.Space)
12098 this.JumpUnreadMenuItem_Click(null, null);
12100 e.SuppressKeyPress = true;
12104 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
12106 this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
12107 this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
12108 this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
12109 this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
12110 this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
12112 this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
12115 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
12117 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
12120 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
12122 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
12125 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
12127 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
12130 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
12132 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
12135 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
12137 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
12140 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
12142 if (SettingManager.Common.IconSize == iconSize) return;
12144 var oldIconCol = _iconCol;
12146 SettingManager.Common.IconSize = iconSize;
12147 ApplyListViewIconSize(iconSize);
12149 if (_iconCol != oldIconCol)
12151 foreach (TabPage tp in ListTab.TabPages)
12153 ResetColumns((DetailsListView)tp.Tag);
12157 _curList?.Refresh();
12159 ModifySettingCommon = true;
12162 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
12164 var state = this.LockListSortOrderToolStripMenuItem.Checked;
12165 if (SettingManager.Common.SortOrderLock == state) return;
12167 SettingManager.Common.SortOrderLock = state;
12169 ModifySettingCommon = true;
12172 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
12174 if (!string.IsNullOrEmpty(e.StatusText))
12176 this.StatusLabelUrl.Text = e.StatusText;
12180 this.SetStatusLabelUrl();