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 long[] excludeReplyUserIds = null;
322 public string imageService = ""; //画像投稿サービス名
323 public IMediaItem[] mediaItems = null;
324 public PostingStatus()
327 public PostingStatus(string status, long? replyToId, string replyToName)
329 this.status = status;
330 this.inReplyToId = replyToId;
331 this.inReplyToName = replyToName;
335 private void TweenMain_Activated(object sender, EventArgs e)
337 //画面がアクティブになったら、発言欄の背景色戻す
338 if (StatusText.Focused)
340 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
344 private bool disposed = false;
347 /// 使用中のリソースをすべてクリーンアップします。
349 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
350 protected override void Dispose(bool disposing)
352 base.Dispose(disposing);
359 this.components?.Dispose();
362 SearchDialog.Dispose();
365 NIconAtRed?.Dispose();
366 NIconAtSmoke?.Dispose();
367 foreach (var iconRefresh in this.NIconRefresh)
369 iconRefresh?.Dispose();
373 ReplyIcon?.Dispose();
374 ReplyIconBlink?.Dispose();
375 _listViewImageList.Dispose();
376 _brsHighLight.Dispose();
377 _brsBackColorMine?.Dispose();
378 _brsBackColorAt?.Dispose();
379 _brsBackColorYou?.Dispose();
380 _brsBackColorAtYou?.Dispose();
381 _brsBackColorAtFromTarget?.Dispose();
382 _brsBackColorAtTo?.Dispose();
383 _brsBackColorNone?.Dispose();
384 _brsDeactiveSelection?.Dispose();
388 this.workerCts.Cancel();
390 if (IconCache != null)
392 this.IconCache.CancelAsync();
393 this.IconCache.Dispose();
396 this.thumbnailTokenSource?.Dispose();
399 this.twitterApi.Dispose();
400 this._hookGlobalHotkey.Dispose();
403 // 終了時にRemoveHandlerしておかないとメモリリークする
404 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
405 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
407 this.disposed = true;
410 private void LoadIcons()
412 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
413 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
416 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
419 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
422 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
425 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
427 // タスクトレイ: オフライン時アイコン
428 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
430 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
431 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
432 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
434 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
435 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
436 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
437 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
438 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
440 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
442 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
443 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
444 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
445 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
446 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
448 if (iconReply != null && iconReplyBlink != null)
450 this.ReplyIcon = iconReply;
451 this.ReplyIconBlink = iconReplyBlink;
455 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
456 this.ReplyIconBlink = this.NIconAt;
459 if (iconRefresh1 == null)
461 this.NIconRefresh = new[] {
462 Properties.Resources.Refresh, Properties.Resources.Refresh2,
463 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
466 else if (iconRefresh2 == null)
468 this.NIconRefresh = new[] { iconRefresh1 };
470 else if (iconRefresh3 == null)
472 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
474 else if (iconRefresh4 == null)
476 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
478 else // iconRefresh1 から iconRefresh4 まで全て揃っている
480 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
484 private Icon LoadIcon(string filePath)
486 if (!File.Exists(filePath))
491 return new Icon(filePath);
499 private void InitColumns(ListView list, bool startup)
501 this.InitColumnText();
503 ColumnHeader[] columns = null;
510 new ColumnHeader(), // アイコン
511 new ColumnHeader(), // 本文
514 columns[0].Text = this.ColumnText[0];
515 columns[1].Text = this.ColumnText[2];
519 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
521 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
522 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
523 columns[0].DisplayIndex = 0;
524 columns[1].DisplayIndex = 1;
529 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
531 columns[idx].Width = curListColumn.Width;
532 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
541 new ColumnHeader(), // アイコン
542 new ColumnHeader(), // ニックネーム
543 new ColumnHeader(), // 本文
544 new ColumnHeader(), // 日付
545 new ColumnHeader(), // ユーザID
546 new ColumnHeader(), // 未読
547 new ColumnHeader(), // マーク&プロテクト
548 new ColumnHeader(), // ソース
551 foreach (var i in Enumerable.Range(0, columns.Length))
552 columns[i].Text = this.ColumnText[i];
556 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
558 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
559 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width2);
560 columns[2].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
561 columns[3].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width4);
562 columns[4].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width5);
563 columns[5].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width6);
564 columns[6].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width7);
565 columns[7].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width8);
567 var displayIndex = new[] {
568 SettingManager.Local.DisplayIndex1, SettingManager.Local.DisplayIndex2,
569 SettingManager.Local.DisplayIndex3, SettingManager.Local.DisplayIndex4,
570 SettingManager.Local.DisplayIndex5, SettingManager.Local.DisplayIndex6,
571 SettingManager.Local.DisplayIndex7, SettingManager.Local.DisplayIndex8
574 foreach (var i in Enumerable.Range(0, displayIndex.Length))
576 columns[i].DisplayIndex = displayIndex[i];
582 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
584 columns[idx].Width = curListColumn.Width;
585 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
591 list.Columns.AddRange(columns);
599 foreach (var column in columns)
605 private void InitColumnText()
608 ColumnText[1] = Properties.Resources.AddNewTabText2;
609 ColumnText[2] = Properties.Resources.AddNewTabText3;
610 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
611 ColumnText[4] = Properties.Resources.AddNewTabText5;
614 ColumnText[7] = "Source";
616 ColumnOrgText[0] = "";
617 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
618 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
619 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
620 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
621 ColumnOrgText[5] = "";
622 ColumnOrgText[6] = "";
623 ColumnOrgText[7] = "Source";
626 switch (_statuses.SortMode)
628 case ComparerMode.Nickname: //ニックネーム
631 case ComparerMode.Data: //本文
634 case ComparerMode.Id: //時刻=発言Id
637 case ComparerMode.Name: //名前
640 case ComparerMode.Source: //Source
647 if (_statuses.SortOrder == SortOrder.Descending)
649 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
650 ColumnText[2] = ColumnOrgText[2] + "▾";
654 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
655 ColumnText[2] = ColumnOrgText[2] + "▴";
660 if (_statuses.SortOrder == SortOrder.Descending)
662 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
663 ColumnText[c] = ColumnOrgText[c] + "▾";
667 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
668 ColumnText[c] = ColumnOrgText[c] + "▴";
673 private void InitializeTraceFrag()
676 TraceOutToolStripMenuItem.Checked = true;
677 MyCommon.TraceFlag = true;
679 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
681 TraceOutToolStripMenuItem.Checked = true;
682 MyCommon.TraceFlag = true;
686 private void TweenMain_Load(object sender, EventArgs e)
688 _ignoreConfigSave = true;
689 this.Visible = false;
691 if (MyApplication.StartupOptions.ContainsKey("d"))
692 MyCommon.TraceFlag = true;
694 InitializeTraceFrag();
696 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
698 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
699 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
701 Regex.CacheSize = 100;
704 _statuses = TabInformations.GetInstance();
708 this.Icon = MainIcon; //メインフォーム(TweenMain)
709 NotifyIcon1.Icon = NIconAt; //タスクトレイ
710 TabImage.Images.Add(TabIcon); //タブ見出し
712 //<<<<<<<<<設定関連>>>>>>>>>
716 // 現在の DPI と設定保存時の DPI との比を取得する
717 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
720 var fontUIGlobal = SettingManager.Local.FontUIGlobal;
721 if (fontUIGlobal != null)
723 OTBaseForm.GlobalFont = fontUIGlobal;
724 this.Font = fontUIGlobal;
728 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
730 if (SettingManager.Common.TimelinePeriod < 15 && SettingManager.Common.TimelinePeriod > 0)
731 SettingManager.Common.TimelinePeriod = 15;
733 if (SettingManager.Common.ReplyPeriod < 15 && SettingManager.Common.ReplyPeriod > 0)
734 SettingManager.Common.ReplyPeriod = 15;
736 if (SettingManager.Common.DMPeriod < 15 && SettingManager.Common.DMPeriod > 0)
737 SettingManager.Common.DMPeriod = 15;
739 if (SettingManager.Common.PubSearchPeriod < 30 && SettingManager.Common.PubSearchPeriod > 0)
740 SettingManager.Common.PubSearchPeriod = 30;
742 if (SettingManager.Common.UserTimelinePeriod < 15 && SettingManager.Common.UserTimelinePeriod > 0)
743 SettingManager.Common.UserTimelinePeriod = 15;
745 if (SettingManager.Common.ListsPeriod < 15 && SettingManager.Common.ListsPeriod > 0)
746 SettingManager.Common.ListsPeriod = 15;
749 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, SettingManager.Common.CountApi))
750 SettingManager.Common.CountApi = 60;
751 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, SettingManager.Common.CountApiReply))
752 SettingManager.Common.CountApiReply = 40;
754 if (SettingManager.Common.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(SettingManager.Common.MoreCountApi))
755 SettingManager.Common.MoreCountApi = 200;
756 if (SettingManager.Common.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(SettingManager.Common.FirstCountApi))
757 SettingManager.Common.FirstCountApi = 100;
759 if (SettingManager.Common.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, SettingManager.Common.FavoritesCountApi))
760 SettingManager.Common.FavoritesCountApi = 40;
761 if (SettingManager.Common.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, SettingManager.Common.ListCountApi))
762 SettingManager.Common.ListCountApi = 100;
763 if (SettingManager.Common.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, SettingManager.Common.SearchCountApi))
764 SettingManager.Common.SearchCountApi = 100;
765 if (SettingManager.Common.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, SettingManager.Common.UserTimelineCountApi))
766 SettingManager.Common.UserTimelineCountApi = 20;
768 //廃止サービスが選択されていた場合ux.nuへ読み替え
769 if (SettingManager.Common.AutoShortUrlFirst < 0)
770 SettingManager.Common.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
772 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
773 this.tw = new Twitter(this.twitterApi);
776 if (string.IsNullOrEmpty(SettingManager.Common.Token)) SettingManager.Common.UserName = "";
777 tw.Initialize(SettingManager.Common.Token, SettingManager.Common.TokenSecret, SettingManager.Common.UserName, SettingManager.Common.UserId);
781 Networking.Initialize();
783 bool saveRequired = false;
784 bool firstRun = false;
786 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
787 if (string.IsNullOrEmpty(tw.Username))
792 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
793 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
794 string.IsNullOrEmpty(tw.Username))
796 Application.Exit(); //強制終了
802 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
803 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
804 Networking.SetWebProxy(SettingManager.Local.ProxyType,
805 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
806 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
807 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
809 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
810 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
811 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
812 tw.TrackWord = SettingManager.Common.TrackWord;
813 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
814 tw.AllAtReply = SettingManager.Common.AllAtReply;
815 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
816 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
817 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
818 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
819 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
821 // アクセストークンが有効であるか確認する
822 // ここが Twitter API への最初のアクセスになるようにすること
825 this.tw.VerifyCredentials();
827 catch (WebApiException ex)
829 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
830 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
834 //プロキシ設定等の通信まわりの初期化が済んでから処理する
835 ThumbnailGenerator.InitializeGenerator();
837 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
838 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
839 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
841 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
844 ImageSelector.Initialize(tw, this.tw.Configuration, SettingManager.Common.UseImageServiceName, SettingManager.Common.UseImageService);
847 AtIdSupl = new AtIdSupplement(SettingManager.AtIdList.AtIdList, "@");
848 HashSupl = new AtIdSupplement(SettingManager.Common.HashTags, "#");
849 HashMgr = new HashtagManage(HashSupl,
850 SettingManager.Common.HashTags.ToArray(),
851 SettingManager.Common.HashSelected,
852 SettingManager.Common.HashIsPermanent,
853 SettingManager.Common.HashIsHead,
854 SettingManager.Common.HashIsNotAddToAtReply);
855 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
858 this.IconCache = new ImageCache();
859 this.tweetDetailsView.IconCache = this.IconCache;
862 _fntUnread = SettingManager.Local.FontUnread;
863 _clUnread = SettingManager.Local.ColorUnread;
864 _fntReaded = SettingManager.Local.FontRead;
865 _clReaded = SettingManager.Local.ColorRead;
866 _clFav = SettingManager.Local.ColorFav;
867 _clOWL = SettingManager.Local.ColorOWL;
868 _clRetweet = SettingManager.Local.ColorRetweet;
869 _fntDetail = SettingManager.Local.FontDetail;
870 _clDetail = SettingManager.Local.ColorDetail;
871 _clDetailLink = SettingManager.Local.ColorDetailLink;
872 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
873 _clSelf = SettingManager.Local.ColorSelf;
874 _clAtSelf = SettingManager.Local.ColorAtSelf;
875 _clTarget = SettingManager.Local.ColorTarget;
876 _clAtTarget = SettingManager.Local.ColorAtTarget;
877 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
878 _clAtTo = SettingManager.Local.ColorAtTo;
879 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
880 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
881 _clInputFont = SettingManager.Local.ColorInputFont;
882 _fntInputFont = SettingManager.Local.FontInputFont;
884 _brsBackColorMine = new SolidBrush(_clSelf);
885 _brsBackColorAt = new SolidBrush(_clAtSelf);
886 _brsBackColorYou = new SolidBrush(_clTarget);
887 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
888 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
889 _brsBackColorAtTo = new SolidBrush(_clAtTo);
890 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
891 _brsBackColorNone = new SolidBrush(_clListBackcolor);
893 // StringFormatオブジェクトへの事前設定
894 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
895 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
896 //sf.FormatFlags = StringFormatFlags.LineLimit; //
897 sfTab.Alignment = StringAlignment.Center;
898 sfTab.LineAlignment = StringAlignment.Center;
900 InitDetailHtmlFormat();
902 //Regex statregex = new Regex("^0*");
903 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
905 _history.Add(new PostingStatus());
907 this.inReplyTo = null;
910 SearchDialog.Owner = this;
911 UrlDialog.Owner = this;
914 NewPostPopMenuItem.Checked = SettingManager.Common.NewAllPop;
915 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
917 //新着取得時のリストスクロールをするか。trueならスクロールしない
918 ListLockMenuItem.Checked = SettingManager.Common.ListLock;
919 this.LockListFileMenuItem.Checked = SettingManager.Common.ListLock;
921 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
922 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
925 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
926 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
927 _myLoc = SettingManager.Local.FormLocation;
929 if (this.WindowState != FormWindowState.Minimized)
931 Rectangle tbarRect = new Rectangle(this._myLoc, new Size(_mySize.Width, SystemInformation.CaptionHeight));
932 bool outOfScreen = true;
933 if (Screen.AllScreens.Length == 1) //ハングするとの報告
935 foreach (Screen scr in Screen.AllScreens)
937 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
945 this._myLoc = new Point(0, 0);
947 this.DesktopLocation = this._myLoc;
949 this.TopMost = SettingManager.Common.AlwaysTop;
950 _mySpDis = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
951 _mySpDis2 = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
952 if (SettingManager.Local.PreviewDistance == -1)
954 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
955 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
956 SettingManager.Local.PreviewDistance = _mySpDis3;
960 _mySpDis3 = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
962 //this.Tween_ClientSizeChanged(this, null);
963 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
964 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
966 StatusText.Font = _fntInputFont;
967 StatusText.ForeColor = _clInputFont;
969 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
970 this.StatusText.Multiline = false; // SettingManager.Local.StatusMultiline の設定は後で反映される
971 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
973 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
974 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
976 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
977 if (SettingManager.Common.UnreadManage == false)
979 ReadedStripMenuItem.Enabled = false;
980 UnreadStripMenuItem.Enabled = false;
983 //リンク先URL表示部の初期化(画面左下)
984 StatusLabelUrl.Text = "";
986 StatusLabel.Text = "";
987 StatusLabel.AutoToolTip = false;
988 StatusLabel.ToolTipText = "";
990 lblLen.Text = this.GetRestStatusCount("").ToString();
992 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
993 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
994 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
995 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
997 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
998 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
999 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1000 this.SplitContainer2.Panel2.AccessibleName = "";
1002 ////////////////////////////////////////////////////////////////////////////////
1003 var sortOrder = (SortOrder)SettingManager.Common.SortOrder;
1004 var mode = ComparerMode.Id;
1005 switch (SettingManager.Common.SortColumn)
1007 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1011 mode = ComparerMode.Id; //Idソートに読み替え
1014 mode = ComparerMode.Nickname;
1017 mode = ComparerMode.Data;
1020 mode = ComparerMode.Id;
1023 mode = ComparerMode.Name;
1026 mode = ComparerMode.Source;
1029 _statuses.SetSortMode(mode, sortOrder);
1030 ////////////////////////////////////////////////////////////////////////////////
1032 ApplyListViewIconSize(SettingManager.Common.IconSize);
1034 //<<<<<<<<タブ関連>>>>>>>
1038 //デフォルトタブの存在チェック、ない場合には追加
1039 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1040 this._statuses.AddTab(new HomeTabModel());
1042 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1043 this._statuses.AddTab(new MentionsTabModel());
1045 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1046 this._statuses.AddTab(new DirectMessagesTabModel());
1048 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1049 this._statuses.AddTab(new FavoritesTabModel());
1051 if (this._statuses.GetTabByType<MuteTabModel>() == null)
1052 this._statuses.AddTab(new MuteTabModel());
1054 foreach (var tab in _statuses.Tabs.Values)
1057 if (tab.TabType == MyCommon.TabUsageType.Mute)
1060 if (!AddNewTab(tab, startup: true))
1061 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1064 _curTab = ListTab.SelectedTab;
1066 _curList = (DetailsListView)_curTab.Tag;
1068 if (SettingManager.Common.TabIconDisp)
1070 ListTab.DrawMode = TabDrawMode.Normal;
1074 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1075 ListTab.DrawItem += ListTab_DrawItem;
1076 ListTab.ImageList = null;
1079 if (SettingManager.Common.HotkeyEnabled)
1082 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1083 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
1084 modKey |= HookGlobalHotkey.ModKeys.Alt;
1085 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
1086 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1087 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
1088 modKey |= HookGlobalHotkey.ModKeys.Shift;
1089 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
1090 modKey |= HookGlobalHotkey.ModKeys.Win;
1092 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
1095 if (SettingManager.Common.IsUseNotifyGrowl)
1098 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1100 SetMainWindowTitle();
1101 SetNotifyIconText();
1103 if (!SettingManager.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1105 this.Visible = true;
1109 TimerTimeline.AutoReset = true;
1110 TimerTimeline.SynchronizingObject = this;
1112 TimerTimeline.Interval = 1000;
1113 TimerTimeline.Enabled = true;
1115 TimerRefreshIcon.Interval = 200;
1116 TimerRefreshIcon.Enabled = true;
1118 _ignoreConfigSave = false;
1119 this.TweenMain_Resize(null, null);
1120 if (saveRequired) SaveConfigsAll(false);
1122 foreach (var ua in SettingManager.Common.UserAccounts)
1124 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1126 ua.UserId = tw.UserId;
1133 // 初回起動時だけ右下のメニューを目立たせる
1134 HashStripSplitButton.ShowDropDown();
1138 private void InitDetailHtmlFormat()
1140 if (SettingManager.Common.IsMonospace)
1142 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1143 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1147 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1148 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1151 detailHtmlFormatHeader = detailHtmlFormatHeader
1152 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1153 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1154 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1155 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1156 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1157 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1160 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1165 txt = ListTab.TabPages[e.Index].Text;
1172 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1173 if (e.State == DrawItemState.Selected)
1175 e.DrawFocusRectangle();
1180 if (_statuses.Tabs[txt].UnreadCount > 0)
1183 fore = System.Drawing.SystemBrushes.ControlText;
1187 fore = System.Drawing.SystemBrushes.ControlText;
1189 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1192 private void LoadConfig()
1194 SettingManager.Local = SettingManager.Local;
1196 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1197 if (SettingManager.Local.ScaleDimension.IsEmpty)
1198 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
1200 var tabSettings = SettingManager.Tabs;
1201 foreach (var tabSetting in tabSettings.Tabs)
1204 switch (tabSetting.TabType)
1206 case MyCommon.TabUsageType.Home:
1207 tab = new HomeTabModel(tabSetting.TabName);
1209 case MyCommon.TabUsageType.Mentions:
1210 tab = new MentionsTabModel(tabSetting.TabName);
1212 case MyCommon.TabUsageType.DirectMessage:
1213 tab = new DirectMessagesTabModel(tabSetting.TabName);
1215 case MyCommon.TabUsageType.Favorites:
1216 tab = new FavoritesTabModel(tabSetting.TabName);
1218 case MyCommon.TabUsageType.UserDefined:
1219 tab = new FilterTabModel(tabSetting.TabName);
1221 case MyCommon.TabUsageType.UserTimeline:
1222 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1224 case MyCommon.TabUsageType.PublicSearch:
1225 tab = new PublicSearchTabModel(tabSetting.TabName)
1227 SearchWords = tabSetting.SearchWords,
1228 SearchLang = tabSetting.SearchLang,
1231 case MyCommon.TabUsageType.Lists:
1232 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1234 case MyCommon.TabUsageType.Mute:
1235 tab = new MuteTabModel(tabSetting.TabName);
1241 tab.UnreadManage = tabSetting.UnreadManage;
1242 tab.Protected = tabSetting.Protected;
1243 tab.Notify = tabSetting.Notify;
1244 tab.SoundFile = tabSetting.SoundFile;
1246 if (tab.IsDistributableTabType)
1248 var filterTab = (FilterTabModel)tab;
1249 filterTab.FilterArray = tabSetting.FilterArray;
1250 filterTab.FilterModified = false;
1253 if (this._statuses.ContainsTab(tab.TabName))
1254 tab.TabName = this._statuses.MakeTabName("MyTab");
1256 this._statuses.AddTab(tab);
1258 if (_statuses.Tabs.Count == 0)
1260 _statuses.AddTab(new HomeTabModel());
1261 _statuses.AddTab(new MentionsTabModel());
1262 _statuses.AddTab(new DirectMessagesTabModel());
1263 _statuses.AddTab(new FavoritesTabModel());
1267 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1269 if (!TimerTimeline.Enabled) return;
1273 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1275 private static int homeCounter = 0;
1276 private static int mentionCounter = 0;
1277 private static int dmCounter = 0;
1278 private static int pubSearchCounter = 0;
1279 private static int userTimelineCounter = 0;
1280 private static int listsCounter = 0;
1281 private static int usCounter = 0;
1282 private static int ResumeWait = 0;
1283 private static int refreshFollowers = 0;
1285 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1287 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1288 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1289 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1290 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1291 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1292 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1293 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1294 Interlocked.Increment(ref refreshFollowers);
1296 var refreshTasks = new List<Task>();
1299 if (ResetTimers.Timeline || homeCounter <= 0 && SettingManager.Common.TimelinePeriod > 0)
1301 Interlocked.Exchange(ref homeCounter, SettingManager.Common.TimelinePeriod);
1302 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1303 refreshTasks.Add(this.GetHomeTimelineAsync());
1304 ResetTimers.Timeline = false;
1306 if (ResetTimers.Reply || mentionCounter <= 0 && SettingManager.Common.ReplyPeriod > 0)
1308 Interlocked.Exchange(ref mentionCounter, SettingManager.Common.ReplyPeriod);
1309 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1310 refreshTasks.Add(this.GetReplyAsync());
1311 ResetTimers.Reply = false;
1313 if (ResetTimers.DirectMessage || dmCounter <= 0 && SettingManager.Common.DMPeriod > 0)
1315 Interlocked.Exchange(ref dmCounter, SettingManager.Common.DMPeriod);
1316 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1317 refreshTasks.Add(this.GetDirectMessagesAsync());
1318 ResetTimers.DirectMessage = false;
1320 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && SettingManager.Common.PubSearchPeriod > 0)
1322 Interlocked.Exchange(ref pubSearchCounter, SettingManager.Common.PubSearchPeriod);
1323 if (!ResetTimers.PublicSearch)
1324 refreshTasks.Add(this.GetPublicSearchAllAsync());
1325 ResetTimers.PublicSearch = false;
1327 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && SettingManager.Common.UserTimelinePeriod > 0)
1329 Interlocked.Exchange(ref userTimelineCounter, SettingManager.Common.UserTimelinePeriod);
1330 if (!ResetTimers.UserTimeline)
1331 refreshTasks.Add(this.GetUserTimelineAllAsync());
1332 ResetTimers.UserTimeline = false;
1334 if (ResetTimers.Lists || listsCounter <= 0 && SettingManager.Common.ListsPeriod > 0)
1336 Interlocked.Exchange(ref listsCounter, SettingManager.Common.ListsPeriod);
1337 if (!ResetTimers.Lists)
1338 refreshTasks.Add(this.GetListTimelineAllAsync());
1339 ResetTimers.Lists = false;
1341 if (ResetTimers.UserStream || usCounter <= 0 && SettingManager.Common.UserstreamPeriod > 0)
1343 Interlocked.Exchange(ref usCounter, SettingManager.Common.UserstreamPeriod);
1344 if (this.tw.UserStreamActive)
1345 this.RefreshTimeline();
1346 ResetTimers.UserStream = false;
1348 if (refreshFollowers > 6 * 3600)
1350 Interlocked.Exchange(ref refreshFollowers, 0);
1351 refreshTasks.AddRange(new[]
1353 this.doGetFollowersMenu(),
1354 this.RefreshNoRetweetIdsAsync(),
1355 this.RefreshTwitterConfigurationAsync(),
1360 Interlocked.Increment(ref ResumeWait);
1361 if (ResumeWait > 30)
1364 Interlocked.Exchange(ref ResumeWait, 0);
1365 refreshTasks.AddRange(new[]
1367 this.GetHomeTimelineAsync(),
1368 this.GetReplyAsync(),
1369 this.GetDirectMessagesAsync(),
1370 this.GetPublicSearchAllAsync(),
1371 this.GetUserTimelineAllAsync(),
1372 this.GetListTimelineAllAsync(),
1373 this.doGetFollowersMenu(),
1374 this.RefreshTwitterConfigurationAsync(),
1379 await Task.WhenAll(refreshTasks);
1382 private void RefreshTimeline()
1384 var curTabModel = this._statuses.Tabs[this._curTab.Text];
1386 // 現在表示中のタブのスクロール位置を退避
1387 var curListScroll = this.SaveListViewScroll(this._curList, curTabModel);
1389 // 各タブのリスト上の選択位置などを退避
1390 var listSelections = this.SaveListViewSelection();
1394 addCount = _statuses.SubmitUpdate(out var soundFile, out var notifyPosts,
1395 out var newMentionOrDm, out var isDelete);
1397 if (MyCommon._endingFlag) return;
1400 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1402 var listView = (DetailsListView)tabPage.Tag;
1403 var tabModel = this._statuses.Tabs[tabPage.Text];
1405 if (listView.VirtualListSize != tabModel.AllCount || isDelete)
1407 using (ControlTransaction.Update(listView))
1409 if (listView == this._curList)
1410 this.PurgeListViewItemCache();
1415 listView.VirtualListSize = tabModel.AllCount;
1417 catch (NullReferenceException ex)
1419 // WinForms 内部で ListView.set_TopItem が発生させている例外
1420 // https://ja.osdn.net/ticket/browse.php?group_id=6526&tid=36588
1421 MyCommon.TraceOut(ex, $"TabType: {tabModel.TabType}, Count: {tabModel.AllCount}, ListSize: {listView.VirtualListSize}");
1425 this.RestoreListViewSelection(listView, tabModel, listSelections[tabModel.TabName]);
1432 if (SettingManager.Common.TabIconDisp)
1434 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1436 var tabModel = this._statuses.Tabs[tabPage.Text];
1437 if (tabModel.UnreadCount > 0 && tabPage.ImageIndex != 0)
1438 tabPage.ImageIndex = 0; // 未読アイコン
1443 this.ListTab.Refresh();
1448 this.RestoreListViewScroll(this._curList, curTabModel, curListScroll);
1451 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1453 SetMainWindowTitle();
1454 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1456 HashSupl.AddRangeItem(tw.GetHashList());
1460 internal struct ListViewScroll
1462 public ScrollLockMode ScrollLockMode { get; set; }
1463 public long? TopItemStatusId { get; set; }
1466 internal enum ScrollLockMode
1468 /// <summary>固定しない</summary>
1471 /// <summary>最上部に固定する</summary>
1474 /// <summary>最下部に固定する</summary>
1477 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1482 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1484 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1486 var listScroll = new ListViewScroll
1488 ScrollLockMode = this.GetScrollLockMode(listView),
1491 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1493 var topItemIndex = listView.TopItem?.Index ?? -1;
1494 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
1495 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItemIndex);
1501 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1503 if (this._statuses.SortMode == ComparerMode.Id)
1505 if (this._statuses.SortOrder == SortOrder.Ascending)
1508 if (this.ListLockMenuItem.Checked)
1509 return ScrollLockMode.None;
1511 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1514 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1515 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1516 return ScrollLockMode.FixedToBottom;
1518 return ScrollLockMode.None;
1523 if (this.ListLockMenuItem.Checked)
1524 return ScrollLockMode.FixedToItem;
1526 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1527 var topItem = listView.TopItem;
1528 if (topItem == null || topItem.Index == 0)
1529 return ScrollLockMode.FixedToTop;
1531 return ScrollLockMode.FixedToItem;
1536 return ScrollLockMode.FixedToItem;
1540 internal struct ListViewSelection
1542 public long[] SelectedStatusIds { get; set; }
1543 public long? SelectionMarkStatusId { get; set; }
1544 public long? FocusedStatusId { get; set; }
1548 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1550 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1552 var listsDict = new Dictionary<string, ListViewSelection>();
1554 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1556 var listView = (DetailsListView)tabPage.Tag;
1557 var tab = _statuses.Tabs[tabPage.Text];
1559 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1566 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1568 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1570 if (listView.VirtualListSize == 0)
1572 return new ListViewSelection
1574 SelectedStatusIds = new long[0],
1575 SelectionMarkStatusId = null,
1576 FocusedStatusId = null,
1580 return new ListViewSelection
1582 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1583 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1584 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1588 private long[] GetSelectedStatusIds(DetailsListView listView, TabModel tab)
1590 var selectedIndices = listView.SelectedIndices;
1591 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1592 return tab.GetStatusIdAt(selectedIndices.Cast<int>());
1597 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1599 var index = listView.FocusedItem?.Index ?? -1;
1601 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1604 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1606 var index = listView.SelectionMark;
1608 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1612 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1614 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1616 if (listView.VirtualListSize == 0)
1619 switch (listScroll.ScrollLockMode)
1621 case ScrollLockMode.FixedToTop:
1622 listView.EnsureVisible(0);
1624 case ScrollLockMode.FixedToBottom:
1625 listView.EnsureVisible(listView.VirtualListSize - 1);
1627 case ScrollLockMode.FixedToItem:
1628 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1631 var topItem = listView.Items[topIndex];
1634 listView.TopItem = topItem;
1636 catch (NullReferenceException)
1638 listView.EnsureVisible(listView.VirtualListSize - 1);
1639 listView.EnsureVisible(topIndex);
1643 case ScrollLockMode.None:
1650 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1652 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1654 // status_id から ListView 上のインデックスに変換
1655 int[] selectedIndices = null;
1656 if (listSelection.SelectedStatusIds != null)
1657 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1659 var focusedIndex = -1;
1660 if (listSelection.FocusedStatusId != null)
1661 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1663 var selectionMarkIndex = -1;
1664 if (listSelection.SelectionMarkStatusId != null)
1665 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1667 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1670 private bool BalloonRequired()
1672 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1673 ev.Eventtype = MyCommon.EVENTTYPE.None;
1675 return BalloonRequired(ev);
1678 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1680 if (type == MyCommon.EVENTTYPE.None)
1683 if (!SettingManager.Common.EventNotifyEnabled)
1686 return SettingManager.Common.EventNotifyFlag.HasFlag(type);
1689 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1694 return SettingManager.Common.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1697 private bool BalloonRequired(Twitter.FormattedEvent ev)
1702 if (NativeMethods.IsScreenSaverRunning())
1706 if (!this.NewPostPopMenuItem.Checked)
1708 // 「新着通知が無効でもイベントを通知する」にも該当しない
1709 if (!SettingManager.Common.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1713 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1714 if (SettingManager.Common.LimitBalloon)
1716 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1720 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1723 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1725 if (SettingManager.Common.ReadOwnPost)
1727 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1732 if (BalloonRequired())
1734 if (notifyPosts != null && notifyPosts.Length > 0)
1736 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1737 if (SettingManager.Common.IsUseNotifyGrowl)
1739 StringBuilder sb = new StringBuilder();
1743 foreach (PostClass post in notifyPosts)
1745 if (!(notifyPosts.Length > 3))
1751 if (post.IsReply && !post.IsExcludeReply) reply = true;
1752 if (post.IsDm) dm = true;
1753 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1754 switch (SettingManager.Common.NameBalloon)
1756 case MyCommon.NameBalloonEnum.UserID:
1757 sb.Append(post.ScreenName).Append(" : ");
1759 case MyCommon.NameBalloonEnum.NickName:
1760 sb.Append(post.Nickname).Append(" : ");
1763 sb.Append(post.TextFromApi);
1764 if (notifyPosts.Length > 3)
1766 if (notifyPosts.Last() != post) continue;
1769 StringBuilder title = new StringBuilder();
1770 GrowlHelper.NotifyType nt;
1771 if (SettingManager.Common.DispUsername)
1773 title.Append(tw.Username);
1774 title.Append(" - ");
1782 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1783 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1784 title.Append(Application.ProductName);
1785 title.Append(" [DM] ");
1786 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1787 nt = GrowlHelper.NotifyType.DirectMessage;
1791 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1792 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1793 title.Append(Application.ProductName);
1794 title.Append(" [Reply!] ");
1795 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1796 nt = GrowlHelper.NotifyType.Reply;
1800 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1801 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1802 title.Append(Application.ProductName);
1804 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1805 nt = GrowlHelper.NotifyType.Notify;
1807 string bText = sb.ToString();
1808 if (string.IsNullOrEmpty(bText)) return;
1810 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1811 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1816 StringBuilder sb = new StringBuilder();
1819 foreach (PostClass post in notifyPosts)
1821 if (post.IsReply && !post.IsExcludeReply) reply = true;
1822 if (post.IsDm) dm = true;
1823 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1824 switch (SettingManager.Common.NameBalloon)
1826 case MyCommon.NameBalloonEnum.UserID:
1827 sb.Append(post.ScreenName).Append(" : ");
1829 case MyCommon.NameBalloonEnum.NickName:
1830 sb.Append(post.Nickname).Append(" : ");
1833 sb.Append(post.TextFromApi);
1836 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1837 StringBuilder title = new StringBuilder();
1839 if (SettingManager.Common.DispUsername)
1841 title.Append(tw.Username);
1842 title.Append(" - ");
1850 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1851 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1852 ntIcon = ToolTipIcon.Warning;
1853 title.Append(Application.ProductName);
1854 title.Append(" [DM] ");
1855 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1859 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1860 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1861 ntIcon = ToolTipIcon.Warning;
1862 title.Append(Application.ProductName);
1863 title.Append(" [Reply!] ");
1864 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1868 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1869 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1870 ntIcon = ToolTipIcon.Info;
1871 title.Append(Application.ProductName);
1873 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1875 string bText = sb.ToString();
1876 if (string.IsNullOrEmpty(bText)) return;
1877 //NotifyIcon1.BalloonTipText = sb.ToString();
1878 //NotifyIcon1.ShowBalloonTip(500);
1879 NotifyIcon1.BalloonTipTitle = title.ToString();
1880 NotifyIcon1.BalloonTipText = bText;
1881 NotifyIcon1.BalloonTipIcon = ntIcon;
1882 NotifyIcon1.ShowBalloonTip(500);
1888 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(soundFile))
1892 string dir = Application.StartupPath;
1893 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1895 dir = Path.Combine(dir, "Sounds");
1897 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1907 //mentions新着時に画面ブリンク
1908 if (!_initial && SettingManager.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1910 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1914 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1916 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1918 _curItemIndex = _curList.SelectedIndices[0];
1919 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1923 this._curPost = GetCurTabPost(_curItemIndex);
1925 catch (ArgumentException)
1930 this.PushSelectPostChain();
1932 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1934 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1940 private void ChangeCacheStyleRead(bool Read, int Index)
1942 var tabInfo = _statuses.Tabs[_curTab.Text];
1943 //Read:true=既読 false=未読
1944 //未読管理していなかったら既読として扱う
1945 if (!tabInfo.UnreadManage ||
1946 !SettingManager.Common.UnreadManage) Read = true;
1948 var listCache = this._listItemCache;
1949 if (listCache == null)
1952 // キャッシュに含まれていないアイテムは対象外
1953 if (!listCache.TryGetValue(Index, out var itm, out var post))
1956 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1959 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1966 Item.SubItems[5].Text = "";
1971 Item.SubItems[5].Text = "★";
1977 else if (Post.RetweetedId != null)
1979 else if (Post.IsOwl && (Post.IsDm || SettingManager.Common.OneWayLove))
1981 else if (Read || !SettingManager.Common.UseUnreadStyle)
1986 if (DList == null || Item.Index == -1)
1988 Item.ForeColor = cl;
1989 if (SettingManager.Common.UseUnreadStyle)
1995 if (SettingManager.Common.UseUnreadStyle)
1996 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1998 DList.ChangeItemForeColor(Item.Index, cl);
1999 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2003 private void ColorizeList()
2005 //Index:更新対象のListviewItem.Index。Colorを返す。
2006 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2009 _post = _anchorPost;
2013 if (_post == null) return;
2015 var listCache = this._listItemCache;
2016 if (listCache == null)
2019 var index = listCache.StartIndex;
2020 foreach (var cachedPost in listCache.Post)
2022 var backColor = this.JudgeColor(_post, cachedPost);
2023 this._curList.ChangeItemBackColor(index++, backColor);
2027 private void ColorizeList(ListViewItem Item, int Index)
2029 //Index:更新対象のListviewItem.Index。Colorを返す。
2030 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2033 _post = _anchorPost;
2037 PostClass tPost = GetCurTabPost(Index);
2039 if (_post == null) return;
2041 if (Item.Index == -1)
2042 Item.BackColor = JudgeColor(_post, tPost);
2044 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2047 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2050 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2053 else if (TargetPost.IsMe)
2056 else if (TargetPost.IsReply)
2059 else if (BasePost.ReplyToList.Any(x => x.Item1 == TargetPost.UserId))
2061 cl = _clAtFromTarget;
2062 else if (TargetPost.ReplyToList.Any(x => x.Item1 == BasePost.UserId))
2065 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2070 cl = _clListBackcolor;
2075 private async void PostButton_Click(object sender, EventArgs e)
2077 if (StatusText.Text.Trim().Length == 0)
2079 if (!ImageSelector.Enabled)
2081 await this.DoRefresh();
2086 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2088 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2090 MessageBoxButtons.YesNoCancel,
2091 MessageBoxIcon.Question);
2094 case DialogResult.Yes:
2095 StatusText.Text = "";
2096 await this.doReTweetOfficial(false);
2098 case DialogResult.Cancel:
2103 var inReplyToStatusId = this.inReplyTo?.Item1;
2104 var inReplyToScreenName = this.inReplyTo?.Item2;
2105 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2107 if (SettingManager.Common.Nicoms)
2109 StatusText.SelectionStart = StatusText.Text.Length;
2110 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2112 //if (SettingDialog.UrlConvertAuto)
2114 // StatusText.SelectionStart = StatusText.Text.Length;
2115 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2117 //else if (SettingDialog.Nicoms)
2119 // StatusText.SelectionStart = StatusText.Text.Length;
2120 // UrlConvert(UrlConverter.Nicoms);
2122 StatusText.SelectionStart = StatusText.Text.Length;
2123 CheckReplyTo(StatusText.Text);
2125 long[] autoPopulatedUserIds;
2127 var statusText = this.RemoveAutoPopuratedMentions(this.StatusText.Text, out autoPopulatedUserIds);
2128 statusText = this.FormatStatusText(statusText);
2130 if (this.GetRestStatusCount(statusText) < 0)
2132 // 文字数制限を超えているが強制的に投稿するか
2133 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2134 if (ret != DialogResult.OK)
2138 var status = new PostingStatus();
2139 status.status = statusText;
2141 status.inReplyToId = this.inReplyTo?.Item1;
2142 status.inReplyToName = this.inReplyTo?.Item2;
2144 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Item1] : null;
2145 if (replyToPost != null)
2147 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
2148 status.excludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.Item1).Except(autoPopulatedUserIds)
2152 if (ImageSelector.Visible)
2155 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2159 this.inReplyTo = null;
2160 StatusText.Text = "";
2161 _history.Add(new PostingStatus());
2162 _hisIdx = _history.Count - 1;
2163 if (!SettingManager.Common.FocusLockToStatusText)
2164 ((Control)ListTab.SelectedTab.Tag).Focus();
2165 urlUndoBuffer = null;
2166 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2169 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2171 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2172 await this.OpenUriInBrowserAsync(tmp);
2175 await this.PostMessageAsync(status);
2178 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2180 MyCommon._endingFlag = true;
2184 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2186 if (!SettingManager.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2188 //_endingFlag=false:フォームの×ボタン
2190 this.Visible = false;
2194 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2195 _ignoreConfigSave = true;
2196 MyCommon._endingFlag = true;
2197 TimerTimeline.Enabled = false;
2198 TimerRefreshIcon.Enabled = false;
2202 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2204 this.Visible = true;
2205 if (this.WindowState == FormWindowState.Minimized)
2207 this.WindowState = FormWindowState.Normal;
2210 this.BringToFront();
2213 private static int errorCount = 0;
2215 private static bool CheckAccountValid()
2217 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2223 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2232 private Task GetHomeTimelineAsync()
2234 return this.GetHomeTimelineAsync(loadMore: false);
2237 private async Task GetHomeTimelineAsync(bool loadMore)
2239 await this.workerSemaphore.WaitAsync();
2243 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
2244 await homeTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2246 this.RefreshTimeline();
2248 catch (WebApiException ex)
2250 this._myStatusError = true;
2251 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2255 this.workerSemaphore.Release();
2259 private Task GetReplyAsync()
2261 return this.GetReplyAsync(loadMore: false);
2264 private async Task GetReplyAsync(bool loadMore)
2266 await this.workerSemaphore.WaitAsync();
2270 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
2271 await replyTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2273 this.RefreshTimeline();
2275 catch (WebApiException ex)
2277 this._myStatusError = true;
2278 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2282 this.workerSemaphore.Release();
2286 private Task GetDirectMessagesAsync()
2288 return this.GetDirectMessagesAsync(loadMore: false);
2291 private async Task GetDirectMessagesAsync(bool loadMore)
2293 await this.workerSemaphore.WaitAsync();
2297 var dmTab = this._statuses.GetTabByType<DirectMessagesTabModel>();
2298 await dmTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2300 this.RefreshTimeline();
2302 catch (WebApiException ex)
2304 this._myStatusError = true;
2305 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2309 this.workerSemaphore.Release();
2313 private Task GetFavoritesAsync()
2315 return this.GetFavoritesAsync(loadMore: false);
2318 private async Task GetFavoritesAsync(bool loadMore)
2320 await this.workerSemaphore.WaitAsync();
2324 var favTab = this._statuses.GetTabByType<FavoritesTabModel>();
2325 await favTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2327 this.RefreshTimeline();
2329 catch (WebApiException ex)
2331 this._myStatusError = true;
2332 this.StatusLabel.Text = ex.Message;
2336 this.workerSemaphore.Release();
2340 private Task GetPublicSearchAllAsync()
2342 var tabs = this._statuses.GetTabsByType<PublicSearchTabModel>();
2344 return this.GetPublicSearchAsync(tabs, loadMore: false);
2347 private Task GetPublicSearchAsync(PublicSearchTabModel tab)
2349 return this.GetPublicSearchAsync(tab, loadMore: false);
2352 private Task GetPublicSearchAsync(PublicSearchTabModel tab, bool loadMore)
2354 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2357 private async Task GetPublicSearchAsync(IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2359 await this.workerSemaphore.WaitAsync();
2363 foreach (var tab in tabs)
2367 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2369 catch (WebApiException ex)
2371 this._myStatusError = true;
2372 this.StatusLabel.Text = $"Err:{ex.Message}(GetSearch)";
2376 this.RefreshTimeline();
2380 this.workerSemaphore.Release();
2384 private Task GetUserTimelineAllAsync()
2386 var tabs = this._statuses.GetTabsByType<UserTimelineTabModel>();
2388 return this.GetUserTimelineAsync(tabs, loadMore: false);
2391 private Task GetUserTimelineAsync(UserTimelineTabModel tab)
2393 return this.GetUserTimelineAsync(tab, loadMore: false);
2396 private Task GetUserTimelineAsync(UserTimelineTabModel tab, bool loadMore)
2398 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2401 private async Task GetUserTimelineAsync(IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2403 await this.workerSemaphore.WaitAsync();
2407 foreach (var tab in tabs)
2411 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2413 catch (WebApiException ex)
2415 this._myStatusError = true;
2416 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2420 this.RefreshTimeline();
2424 this.workerSemaphore.Release();
2428 private Task GetListTimelineAllAsync()
2430 var tabs = this._statuses.GetTabsByType<ListTimelineTabModel>();
2432 return this.GetListTimelineAsync(tabs, loadMore: false);
2435 private Task GetListTimelineAsync(ListTimelineTabModel tab)
2437 return this.GetListTimelineAsync(tab, loadMore: false);
2440 private Task GetListTimelineAsync(ListTimelineTabModel tab, bool loadMore)
2442 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2445 private async Task GetListTimelineAsync(IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2447 await this.workerSemaphore.WaitAsync();
2451 foreach (var tab in tabs)
2455 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2457 catch (WebApiException ex)
2459 this._myStatusError = true;
2460 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2464 this.RefreshTimeline();
2468 this.workerSemaphore.Release();
2472 private async Task GetRelatedTweetsAsync(RelatedPostsTabModel tab)
2474 await this.workerSemaphore.WaitAsync();
2478 await tab.RefreshAsync(this.tw, this._initial, this.workerProgress);
2480 this.RefreshTimeline();
2482 catch (WebApiException ex)
2484 this._myStatusError = true;
2485 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2489 this.workerSemaphore.Release();
2493 private async Task FavAddAsync(long statusId, TabModel tab)
2495 await this.workerSemaphore.WaitAsync();
2499 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2501 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2503 catch (WebApiException ex)
2505 this._myStatusError = true;
2506 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2510 this.workerSemaphore.Release();
2514 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2516 if (ct.IsCancellationRequested)
2519 if (!CheckAccountValid())
2520 throw new WebApiException("Auth error. Check your account");
2522 if (!tab.Posts.TryGetValue(statusId, out var post))
2528 await Task.Run(async () =>
2530 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2536 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2538 .ConfigureAwait(false);
2540 catch (TwitterApiException ex)
2541 when (ex.ErrorResponse.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
2543 // エラーコード 139 のみの場合は成功と見なす
2546 if (SettingManager.Common.RestrictFavCheck)
2548 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2549 .ConfigureAwait(false);
2551 if (status.Favorited != true)
2552 throw new WebApiException("NG(Restricted?)");
2555 this._favTimestamps.Add(DateTime.Now);
2558 if (this._statuses.ContainsKey(statusId))
2560 var postTl = this._statuses[statusId];
2561 postTl.IsFav = true;
2563 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2564 favTab.AddPostQueue(postTl);
2567 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2568 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2570 if (tb.Contains(statusId))
2571 tb.Posts[statusId].IsFav = true;
2574 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2576 catch (WebApiException)
2578 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2583 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2584 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2586 if (this._favTimestamps[i] < oneHour)
2587 this._favTimestamps.RemoveAt(i);
2590 this._statuses.DistributePosts();
2593 if (ct.IsCancellationRequested)
2596 this.RefreshTimeline();
2598 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2600 using (ControlTransaction.Update(this._curList))
2602 var idx = tab.IndexOf(statusId);
2604 this.ChangeCacheStyleRead(post.IsRead, idx);
2607 if (statusId == this._curPost.StatusId)
2608 await this.DispSelectedPost(true); // 選択アイテム再表示
2612 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2614 await this.workerSemaphore.WaitAsync();
2618 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2620 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2622 catch (WebApiException ex)
2624 this._myStatusError = true;
2625 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2629 this.workerSemaphore.Release();
2633 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2635 if (ct.IsCancellationRequested)
2638 if (!CheckAccountValid())
2639 throw new WebApiException("Auth error. Check your account");
2641 var successIds = new List<long>();
2643 await Task.Run(async () =>
2647 var failedCount = 0;
2648 foreach (var statusId in statusIds)
2652 var post = tab.Posts[statusId];
2654 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2661 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2663 .ConfigureAwait(false);
2665 catch (WebApiException)
2671 successIds.Add(statusId);
2672 post.IsFav = false; // リスト再描画必要
2674 if (this._statuses.ContainsKey(statusId))
2676 this._statuses[statusId].IsFav = false;
2679 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2680 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2682 if (tb.Contains(statusId))
2683 tb.Posts[statusId].IsFav = false;
2688 if (ct.IsCancellationRequested)
2691 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2692 foreach (var statusId in successIds)
2694 // ツイートが削除された訳ではないので IsDeleted はセットしない
2695 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2698 this.RefreshTimeline();
2700 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2702 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2708 using (ControlTransaction.Update(this._curList))
2710 foreach (var statusId in successIds)
2712 var idx = tab.IndexOf(statusId);
2716 var post = tab.Posts[statusId];
2717 this.ChangeCacheStyleRead(post.IsRead, idx);
2721 if (successIds.Contains(this._curPost.StatusId))
2722 await this.DispSelectedPost(true); // 選択アイテム再表示
2727 private async Task PostMessageAsync(PostingStatus status)
2729 await this.workerSemaphore.WaitAsync();
2733 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2735 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
2737 catch (WebApiException ex)
2739 this._myStatusError = true;
2740 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2744 this.workerSemaphore.Release();
2748 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
2750 if (ct.IsCancellationRequested)
2753 if (!CheckAccountValid())
2754 throw new WebApiException("Auth error. Check your account");
2756 p.Report("Posting...");
2762 await Task.Run(async () =>
2764 if (status.mediaItems == null || status.mediaItems.Length == 0)
2766 await this.tw.PostStatus(status.status, status.inReplyToId, excludeReplyUserIds: status.excludeReplyUserIds)
2767 .ConfigureAwait(false);
2771 var service = ImageSelector.GetService(status.imageService);
2772 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems, status.excludeReplyUserIds)
2773 .ConfigureAwait(false);
2777 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2779 catch (WebApiException ex)
2781 // 処理は中断せずエラーの表示のみ行う
2782 errMsg = $"Err:{ex.Message}(PostMessage)";
2784 this._myStatusError = true;
2786 catch (UnauthorizedAccessException ex)
2788 // アップロード対象のファイルが開けなかった場合など
2789 errMsg = $"Err:{ex.Message}(PostMessage)";
2791 this._myStatusError = true;
2795 // 使い終わった MediaItem は破棄する
2796 if (status.mediaItems != null)
2798 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
2800 disposableItem.Dispose();
2805 if (ct.IsCancellationRequested)
2808 if (!string.IsNullOrEmpty(errMsg) &&
2809 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2810 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2812 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, status.status);
2814 var ret = MessageBox.Show(
2816 "Failed to update status",
2817 MessageBoxButtons.RetryCancel,
2818 MessageBoxIcon.Question);
2820 if (ret == DialogResult.Retry)
2822 await this.PostMessageAsync(status);
2826 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2827 if (SettingManager.Common.FocusLockToStatusText)
2828 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2833 this._postTimestamps.Add(DateTime.Now);
2835 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2836 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2838 if (this._postTimestamps[i] < oneHour)
2839 this._postTimestamps.RemoveAt(i);
2842 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2844 this.HashMgr.ClearHashtag();
2845 this.HashStripSplitButton.Text = "#[-]";
2846 this.HashTogglePullDownMenuItem.Checked = false;
2847 this.HashToggleMenuItem.Checked = false;
2850 this.SetMainWindowTitle();
2852 if (SettingManager.Common.PostAndGet)
2854 if (this.tw.UserStreamActive)
2855 this.RefreshTimeline();
2857 await this.GetHomeTimelineAsync();
2861 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2863 await this.workerSemaphore.WaitAsync();
2867 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2869 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2871 if (SettingManager.Common.PostAndGet && !this.tw.UserStreamActive)
2872 await this.GetHomeTimelineAsync();
2874 catch (WebApiException ex)
2876 this._myStatusError = true;
2877 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2881 this.workerSemaphore.Release();
2885 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2887 if (ct.IsCancellationRequested)
2890 if (!CheckAccountValid())
2891 throw new WebApiException("Auth error. Check your account");
2894 if (!SettingManager.Common.UnreadManage)
2897 read = this._initial && SettingManager.Common.Read;
2899 p.Report("Posting...");
2901 foreach (var statusId in statusIds)
2903 await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2906 if (ct.IsCancellationRequested)
2909 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2911 this._postTimestamps.Add(DateTime.Now);
2913 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2914 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2916 if (this._postTimestamps[i] < oneHour)
2917 this._postTimestamps.RemoveAt(i);
2921 private async Task RefreshFollowerIdsAsync()
2923 await this.workerSemaphore.WaitAsync();
2926 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2928 await this.tw.RefreshFollowerIds();
2930 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2932 this.RefreshTimeline();
2933 this.PurgeListViewItemCache();
2934 this._curList?.Refresh();
2936 catch (WebApiException ex)
2938 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2942 this.workerSemaphore.Release();
2946 private async Task RefreshNoRetweetIdsAsync()
2948 await this.workerSemaphore.WaitAsync();
2951 await this.tw.RefreshNoRetweetIds();
2953 this.StatusLabel.Text = "NoRetweetIds refreshed";
2955 catch (WebApiException ex)
2957 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2961 this.workerSemaphore.Release();
2965 private async Task RefreshBlockIdsAsync()
2967 await this.workerSemaphore.WaitAsync();
2970 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2972 await this.tw.RefreshBlockIds();
2974 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2976 catch (WebApiException ex)
2978 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2982 this.workerSemaphore.Release();
2986 private async Task RefreshTwitterConfigurationAsync()
2988 await this.workerSemaphore.WaitAsync();
2991 await this.tw.RefreshConfiguration();
2993 if (this.tw.Configuration.PhotoSizeLimit != 0)
2995 foreach (var service in this.ImageSelector.GetServices())
2997 service.UpdateTwitterConfiguration(this.tw.Configuration);
3001 this.PurgeListViewItemCache();
3003 this._curList?.Refresh();
3005 catch (WebApiException ex)
3007 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
3011 this.workerSemaphore.Release();
3015 private async Task RefreshMuteUserIdsAsync()
3017 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3021 await tw.RefreshMuteUserIdsAsync();
3023 catch (WebApiException ex)
3025 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3029 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3032 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3034 if (e.Button == MouseButtons.Left)
3036 this.Visible = true;
3037 if (this.WindowState == FormWindowState.Minimized)
3039 this.WindowState = _formWindowState;
3042 this.BringToFront();
3046 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3048 switch (SettingManager.Common.ListDoubleClickAction)
3051 MakeReplyOrDirectStatus();
3054 await this.FavoriteChange(true);
3057 if (_curPost != null)
3058 await this.ShowUserStatus(_curPost.ScreenName, false);
3064 ShowRelatedStatusesMenuItem_Click(null, null);
3067 MoveToHomeToolStripMenuItem_Click(null, null);
3070 StatusOpenMenuItem_Click(null, null);
3078 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3080 await this.FavoriteChange(true);
3083 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3085 await this.FavoriteChange(false);
3089 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3091 await this.FavoritesRetweetOfficial();
3094 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3096 await this.FavoritesRetweetUnofficial();
3099 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3101 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3104 //trueでFavAdd,falseでFavRemove
3105 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3106 || !this.ExistCurrentPost) return;
3108 if (this._curList.SelectedIndices.Count > 1)
3113 // https://support.twitter.com/articles/76915#favoriting
3114 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3115 _DoFavRetweetFlags = false;
3120 if (multiFavoriteChangeDialogEnable)
3122 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3123 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3124 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3126 if (confirm == DialogResult.Cancel)
3134 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3135 if (selectedPost.IsFav)
3137 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3141 await this.FavAddAsync(selectedPost.StatusId, tab);
3145 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3146 .Select(x => this.GetCurTabPost(x))
3147 .Where(x => x.IsFav);
3149 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3150 if (statusIds.Length == 0)
3152 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3156 await this.FavRemoveAsync(statusIds, tab);
3160 private PostClass GetCurTabPost(int Index)
3162 var listCache = this._listItemCache;
3163 if (listCache != null)
3165 if (listCache.TryGetValue(Index, out var item, out var post))
3169 return _statuses.Tabs[_curTab.Text][Index];
3172 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3174 if (_curList.SelectedIndices.Count > 0)
3175 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3176 else if (_curList.SelectedIndices.Count == 0)
3177 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3180 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3182 if (_curList.SelectedIndices.Count > 0)
3183 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3186 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3188 if ((!_initialLayout) && this.Visible)
3190 if (this.WindowState == FormWindowState.Normal)
3192 _mySize = this.ClientSize;
3193 _mySpDis = this.SplitContainer1.SplitterDistance;
3194 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3195 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3196 ModifySettingLocal = true;
3201 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3203 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3204 if (comparerMode == null)
3207 this.SetSortColumn(comparerMode.Value);
3211 /// 列インデックスからソートを行う ComparerMode を求める
3213 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3214 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3215 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3218 return ComparerMode.Id;
3220 switch (columnIndex)
3223 return ComparerMode.Nickname;
3225 return ComparerMode.Data;
3227 return ComparerMode.Id;
3229 return ComparerMode.Name;
3231 return ComparerMode.Source;
3233 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3239 /// 発言一覧の指定した位置の列でソートする
3241 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3242 private void SetSortColumnByDisplayIndex(int columnIndex)
3244 // 表示上の列の位置から ColumnHeader を求める
3245 var col = this._curList.Columns.Cast<ColumnHeader>()
3246 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3251 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3252 if (comparerMode == null)
3255 this.SetSortColumn(comparerMode.Value);
3259 /// 発言一覧の最後列の項目でソートする
3261 private void SetSortLastColumn()
3263 // 表示上の最後列にある ColumnHeader を求める
3264 var col = this._curList.Columns.Cast<ColumnHeader>()
3265 .OrderByDescending(x => x.DisplayIndex)
3268 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3269 if (comparerMode == null)
3272 this.SetSortColumn(comparerMode.Value);
3276 /// 発言一覧を指定された ComparerMode に基づいてソートする
3278 private void SetSortColumn(ComparerMode sortColumn)
3280 if (SettingManager.Common.SortOrderLock)
3283 this._statuses.ToggleSortOrder(sortColumn);
3284 this.InitColumnText();
3286 var list = this._curList;
3289 list.Columns[0].Text = this.ColumnText[0];
3290 list.Columns[1].Text = this.ColumnText[2];
3294 for (var i = 0; i <= 7; i++)
3296 list.Columns[i].Text = this.ColumnText[i];
3300 this.PurgeListViewItemCache();
3302 var tab = this._statuses.Tabs[this._curTab.Text];
3303 if (tab.AllCount > 0 && this._curPost != null)
3305 var idx = tab.IndexOf(this._curPost.StatusId);
3308 this.SelectListItem(list, idx);
3309 list.EnsureVisible(idx);
3314 this.ModifySettingCommon = true;
3317 private void TweenMain_LocationChanged(object sender, EventArgs e)
3319 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3321 _myLoc = this.DesktopLocation;
3322 ModifySettingLocal = true;
3326 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3328 if (ListTab.SelectedTab == null) return;
3329 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3330 if (!this.ExistCurrentPost)
3332 ReplyStripMenuItem.Enabled = false;
3333 ReplyAllStripMenuItem.Enabled = false;
3334 DMStripMenuItem.Enabled = false;
3335 ShowProfileMenuItem.Enabled = false;
3336 ShowUserTimelineContextMenuItem.Enabled = false;
3337 ListManageUserContextToolStripMenuItem2.Enabled = false;
3338 MoveToFavToolStripMenuItem.Enabled = false;
3339 TabMenuItem.Enabled = false;
3340 IDRuleMenuItem.Enabled = false;
3341 SourceRuleMenuItem.Enabled = false;
3342 ReadedStripMenuItem.Enabled = false;
3343 UnreadStripMenuItem.Enabled = false;
3347 ShowProfileMenuItem.Enabled = true;
3348 ListManageUserContextToolStripMenuItem2.Enabled = true;
3349 ReplyStripMenuItem.Enabled = true;
3350 ReplyAllStripMenuItem.Enabled = true;
3351 DMStripMenuItem.Enabled = true;
3352 ShowUserTimelineContextMenuItem.Enabled = true;
3353 MoveToFavToolStripMenuItem.Enabled = true;
3354 TabMenuItem.Enabled = true;
3355 IDRuleMenuItem.Enabled = true;
3356 SourceRuleMenuItem.Enabled = true;
3357 ReadedStripMenuItem.Enabled = true;
3358 UnreadStripMenuItem.Enabled = true;
3360 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3362 FavAddToolStripMenuItem.Enabled = false;
3363 FavRemoveToolStripMenuItem.Enabled = false;
3364 StatusOpenMenuItem.Enabled = false;
3365 FavorareMenuItem.Enabled = false;
3366 ShowRelatedStatusesMenuItem.Enabled = false;
3368 ReTweetStripMenuItem.Enabled = false;
3369 ReTweetUnofficialStripMenuItem.Enabled = false;
3370 QuoteStripMenuItem.Enabled = false;
3371 FavoriteRetweetContextMenu.Enabled = false;
3372 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3376 FavAddToolStripMenuItem.Enabled = true;
3377 FavRemoveToolStripMenuItem.Enabled = true;
3378 StatusOpenMenuItem.Enabled = true;
3379 FavorareMenuItem.Enabled = true;
3380 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3382 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
3384 ReTweetStripMenuItem.Enabled = false;
3385 ReTweetUnofficialStripMenuItem.Enabled = false;
3386 QuoteStripMenuItem.Enabled = false;
3387 FavoriteRetweetContextMenu.Enabled = false;
3388 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3392 ReTweetStripMenuItem.Enabled = true;
3393 ReTweetUnofficialStripMenuItem.Enabled = true;
3394 QuoteStripMenuItem.Enabled = true;
3395 FavoriteRetweetContextMenu.Enabled = true;
3396 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3399 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3401 // RefreshMoreStripMenuItem.Enabled = true;
3405 // RefreshMoreStripMenuItem.Enabled = false;
3407 if (!this.ExistCurrentPost
3408 || _curPost.InReplyToStatusId == null)
3410 RepliedStatusOpenMenuItem.Enabled = false;
3414 RepliedStatusOpenMenuItem.Enabled = true;
3416 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3418 MoveToRTHomeMenuItem.Enabled = false;
3422 MoveToRTHomeMenuItem.Enabled = true;
3425 if (this.ExistCurrentPost)
3427 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3428 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3429 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3431 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3435 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3437 MakeReplyOrDirectStatus(false, true);
3440 private void DMStripMenuItem_Click(object sender, EventArgs e)
3442 MakeReplyOrDirectStatus(false, false);
3445 private async Task doStatusDelete()
3447 if (this._curTab == null || this._curList == null)
3450 if (this._curList.SelectedIndices.Count == 0)
3453 var posts = this._curList.SelectedIndices.Cast<int>()
3454 .Select(x => this.GetCurTabPost(x))
3457 // 選択されたツイートの中に削除可能なものが一つでもあるか
3458 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3461 var ret = MessageBox.Show(this,
3462 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3463 Properties.Resources.DeleteStripMenuItem_ClickText2,
3464 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3466 if (ret != DialogResult.OK)
3469 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3471 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3473 Exception lastException = null;
3474 foreach (var post in posts)
3476 if (!post.CanDeleteBy(this.tw.UserId))
3483 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3488 if (post.RetweetedByUserId == this.tw.UserId)
3490 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3492 await this.twitterApi.StatusesDestroy(post.StatusId)
3497 if (post.UserId == this.tw.UserId)
3499 if (post.RetweetedId != null)
3500 // 他人に RT された自分のツイート
3501 // => RT 元の自分のツイートを削除
3502 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3507 await this.twitterApi.StatusesDestroy(post.StatusId)
3513 catch (WebApiException ex)
3519 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3522 if (lastException == null)
3523 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3525 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3527 this.PurgeListViewItemCache();
3528 this._curPost = null;
3529 this._curItemIndex = -1;
3531 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3533 var listView = (DetailsListView)tabPage.Tag;
3534 var tab = this._statuses.Tabs[tabPage.Text];
3536 using (ControlTransaction.Update(listView))
3538 listView.VirtualListSize = tab.AllCount;
3540 if (tabPage == this._curTab)
3542 listView.SelectedIndices.Clear();
3544 if (tab.AllCount != 0)
3547 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3548 selectedIndex = focusedIndex;
3550 selectedIndex = tab.AllCount - 1;
3552 listView.SelectedIndices.Add(selectedIndex);
3553 listView.EnsureVisible(selectedIndex);
3554 listView.FocusedItem = listView.Items[selectedIndex];
3559 if (SettingManager.Common.TabIconDisp && tab.UnreadCount == 0)
3561 if (tabPage.ImageIndex == 0)
3562 tabPage.ImageIndex = -1; // タブアイコン
3566 if (!SettingManager.Common.TabIconDisp)
3567 this.ListTab.Refresh();
3571 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3573 await this.doStatusDelete();
3576 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3578 using (ControlTransaction.Update(this._curList))
3580 foreach (int idx in _curList.SelectedIndices)
3582 var post = this._statuses.Tabs[this._curTab.Text][idx];
3583 this._statuses.SetReadAllTab(post.StatusId, read: true);
3584 ChangeCacheStyleRead(true, idx);
3588 foreach (TabPage tb in ListTab.TabPages)
3590 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3592 if (SettingManager.Common.TabIconDisp)
3594 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3598 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3601 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3603 using (ControlTransaction.Update(this._curList))
3605 foreach (int idx in _curList.SelectedIndices)
3607 var post = this._statuses.Tabs[this._curTab.Text][idx];
3608 this._statuses.SetReadAllTab(post.StatusId, read: false);
3609 ChangeCacheStyleRead(false, idx);
3613 foreach (TabPage tb in ListTab.TabPages)
3615 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3617 if (SettingManager.Common.TabIconDisp)
3619 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3623 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3626 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3628 await this.DoRefresh();
3631 private async Task DoRefresh()
3633 if (_curTab != null)
3635 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3640 case MentionsTabModel replyTab:
3641 await this.GetReplyAsync();
3643 case DirectMessagesTabModel dmTab:
3644 await this.GetDirectMessagesAsync();
3646 case FavoritesTabModel favTab:
3647 await this.GetFavoritesAsync();
3649 case PublicSearchTabModel searchTab:
3650 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3651 await this.GetPublicSearchAsync(searchTab);
3653 case UserTimelineTabModel userTab:
3654 await this.GetUserTimelineAsync(userTab);
3656 case ListTimelineTabModel listTab:
3657 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3658 await this.GetListTimelineAsync(listTab);
3661 await this.GetHomeTimelineAsync();
3667 await this.GetHomeTimelineAsync();
3671 private async Task DoRefreshMore()
3674 if (_curTab != null)
3676 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3681 case MentionsTabModel replyTab:
3682 await this.GetReplyAsync(loadMore: true);
3684 case DirectMessagesTabModel dmTab:
3685 await this.GetDirectMessagesAsync(loadMore: true);
3687 case FavoritesTabModel favTab:
3688 await this.GetFavoritesAsync(loadMore: true);
3690 case PublicSearchTabModel searchTab:
3691 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3692 await this.GetPublicSearchAsync(searchTab, loadMore: true);
3694 case UserTimelineTabModel userTab:
3695 await this.GetUserTimelineAsync(userTab, loadMore: true);
3697 case ListTimelineTabModel listTab:
3698 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3699 await this.GetListTimelineAsync(listTab, loadMore: true);
3702 await this.GetHomeTimelineAsync(loadMore: true);
3708 await this.GetHomeTimelineAsync(loadMore: true);
3712 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3714 DialogResult result = DialogResult.Abort;
3716 using (var settingDialog = new AppendSettingDialog())
3718 settingDialog.Icon = this.MainIcon;
3719 settingDialog.Owner = this;
3720 settingDialog.ShowInTaskbar = showTaskbarIcon;
3721 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3723 settingDialog.tw = this.tw;
3724 settingDialog.twitterApi = this.twitterApi;
3726 settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
3730 result = settingDialog.ShowDialog(this);
3734 return DialogResult.Abort;
3737 if (result == DialogResult.OK)
3741 settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
3749 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3752 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3754 var oldIconSz = SettingManager.Common.IconSize;
3756 if (ShowSettingDialog() == DialogResult.OK)
3760 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
3761 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
3762 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
3763 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
3764 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
3765 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
3766 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
3768 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
3769 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
3770 Networking.SetWebProxy(SettingManager.Local.ProxyType,
3771 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
3772 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
3773 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
3775 ImageSelector.Reset(tw, this.tw.Configuration);
3779 if (SettingManager.Common.TabIconDisp)
3781 ListTab.DrawItem -= ListTab_DrawItem;
3782 ListTab.DrawMode = TabDrawMode.Normal;
3783 ListTab.ImageList = this.TabImage;
3787 ListTab.DrawItem -= ListTab_DrawItem;
3788 ListTab.DrawItem += ListTab_DrawItem;
3789 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3790 ListTab.ImageList = null;
3793 catch (Exception ex)
3795 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3796 ex.Data["IsTerminatePermission"] = false;
3802 if (!SettingManager.Common.UnreadManage)
3804 ReadedStripMenuItem.Enabled = false;
3805 UnreadStripMenuItem.Enabled = false;
3806 if (SettingManager.Common.TabIconDisp)
3808 foreach (TabPage myTab in ListTab.TabPages)
3810 myTab.ImageIndex = -1;
3816 ReadedStripMenuItem.Enabled = true;
3817 UnreadStripMenuItem.Enabled = true;
3820 catch (Exception ex)
3822 ex.Data["Instance"] = "ListTab(UnreadManage)";
3823 ex.Data["IsTerminatePermission"] = false;
3830 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
3832 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3833 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
3834 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
3836 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
3837 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
3838 _fntUnread = SettingManager.Local.FontUnread;
3839 _clUnread = SettingManager.Local.ColorUnread;
3840 _fntReaded = SettingManager.Local.FontRead;
3841 _clReaded = SettingManager.Local.ColorRead;
3842 _clFav = SettingManager.Local.ColorFav;
3843 _clOWL = SettingManager.Local.ColorOWL;
3844 _clRetweet = SettingManager.Local.ColorRetweet;
3845 _fntDetail = SettingManager.Local.FontDetail;
3846 _clDetail = SettingManager.Local.ColorDetail;
3847 _clDetailLink = SettingManager.Local.ColorDetailLink;
3848 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
3849 _clSelf = SettingManager.Local.ColorSelf;
3850 _clAtSelf = SettingManager.Local.ColorAtSelf;
3851 _clTarget = SettingManager.Local.ColorTarget;
3852 _clAtTarget = SettingManager.Local.ColorAtTarget;
3853 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
3854 _clAtTo = SettingManager.Local.ColorAtTo;
3855 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
3856 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
3857 _clInputFont = SettingManager.Local.ColorInputFont;
3858 _fntInputFont = SettingManager.Local.FontInputFont;
3859 _brsBackColorMine.Dispose();
3860 _brsBackColorAt.Dispose();
3861 _brsBackColorYou.Dispose();
3862 _brsBackColorAtYou.Dispose();
3863 _brsBackColorAtFromTarget.Dispose();
3864 _brsBackColorAtTo.Dispose();
3865 _brsBackColorNone.Dispose();
3866 _brsBackColorMine = new SolidBrush(_clSelf);
3867 _brsBackColorAt = new SolidBrush(_clAtSelf);
3868 _brsBackColorYou = new SolidBrush(_clTarget);
3869 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3870 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3871 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3872 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3876 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3877 StatusText.Font = _fntInputFont;
3878 StatusText.ForeColor = _clInputFont;
3880 catch (Exception ex)
3882 MessageBox.Show(ex.Message);
3887 InitDetailHtmlFormat();
3889 catch (Exception ex)
3891 ex.Data["Instance"] = "Font";
3892 ex.Data["IsTerminatePermission"] = false;
3898 foreach (TabPage tb in ListTab.TabPages)
3900 if (SettingManager.Common.TabIconDisp)
3902 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3909 catch (Exception ex)
3911 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3912 ex.Data["IsTerminatePermission"] = false;
3918 var oldIconCol = _iconCol;
3920 if (SettingManager.Common.IconSize != oldIconSz)
3921 ApplyListViewIconSize(SettingManager.Common.IconSize);
3923 foreach (TabPage tp in ListTab.TabPages)
3925 DetailsListView lst = (DetailsListView)tp.Tag;
3927 using (ControlTransaction.Update(lst))
3929 lst.GridLines = SettingManager.Common.ShowGrid;
3930 lst.Font = _fntReaded;
3931 lst.BackColor = _clListBackcolor;
3933 if (_iconCol != oldIconCol)
3938 catch (Exception ex)
3940 ex.Data["Instance"] = "ListView(IconSize)";
3941 ex.Data["IsTerminatePermission"] = false;
3945 SetMainWindowTitle();
3946 SetNotifyIconText();
3948 this.PurgeListViewItemCache();
3949 _curList?.Refresh();
3952 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3953 if (SettingManager.Common.HotkeyEnabled)
3955 ///グローバルホットキーの登録。設定で変更可能にするかも
3956 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
3957 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
3958 modKey |= HookGlobalHotkey.ModKeys.Alt;
3959 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
3960 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3961 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
3962 modKey |= HookGlobalHotkey.ModKeys.Shift;
3963 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
3964 modKey |= HookGlobalHotkey.ModKeys.Win;
3966 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
3969 if (SettingManager.Common.IsUseNotifyGrowl) gh.RegisterGrowl();
3972 StatusText_TextChanged(null, null);
3981 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3982 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3985 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3987 this.TopMost = SettingManager.Common.AlwaysTop;
3988 SaveConfigsAll(false);
3990 if (tw.Username != oldUser.Username)
3991 await this.doGetFollowersMenu();
3997 private void SetTabAlignment()
3999 var newAlignment = SettingManager.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4000 if (ListTab.Alignment == newAlignment) return;
4002 // 各タブのリスト上の選択位置などを退避
4003 var listSelections = this.SaveListViewSelection();
4005 ListTab.Alignment = newAlignment;
4007 foreach (TabPage tab in ListTab.TabPages)
4009 DetailsListView lst = (DetailsListView)tab.Tag;
4010 TabModel tabInfo = _statuses.Tabs[tab.Text];
4011 using (ControlTransaction.Update(lst))
4014 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4019 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4025 case MyCommon.IconSizes.IconNone:
4028 case MyCommon.IconSizes.Icon16:
4031 case MyCommon.IconSizes.Icon24:
4034 case MyCommon.IconSizes.Icon48:
4037 case MyCommon.IconSizes.Icon48_2:
4045 // ディスプレイの DPI 設定を考慮したサイズを設定する
4046 _listViewImageList.ImageSize = new Size(
4048 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4052 _listViewImageList.ImageSize = new Size(1, 1);
4056 private void ResetColumns(DetailsListView list)
4058 using (ControlTransaction.Update(list))
4059 using (ControlTransaction.Layout(list, false))
4062 list.ColumnClick -= MyList_ColumnClick;
4063 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4064 list.ColumnReordered -= MyList_ColumnReordered;
4065 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4067 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4068 list.Columns.Clear();
4069 cols.ForEach(col => col.Dispose());
4072 InitColumns(list, true);
4074 list.ColumnClick += MyList_ColumnClick;
4075 list.DrawColumnHeader += MyList_DrawColumnHeader;
4076 list.ColumnReordered += MyList_ColumnReordered;
4077 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4081 public void AddNewTabForSearch(string searchWord)
4083 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4084 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4086 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4088 foreach (TabPage tp in ListTab.TabPages)
4090 if (tb.TabName == tp.Text)
4092 ListTab.SelectedTab = tp;
4099 string tabName = searchWord;
4100 for (int i = 0; i <= 100; i++)
4102 if (_statuses.ContainsTab(tabName))
4108 var tab = new PublicSearchTabModel(tabName);
4109 _statuses.AddTab(tab);
4110 AddNewTab(tab, startup: false);
4112 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4114 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4115 cmb.Items.Add(searchWord);
4116 cmb.Text = searchWord;
4119 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4122 private void ShowUserTimeline()
4124 if (!this.ExistCurrentPost) return;
4125 AddNewTabForUserTimeline(_curPost.ScreenName);
4128 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4130 if (e.KeyCode == Keys.Escape)
4132 TabPage relTp = ListTab.SelectedTab;
4133 RemoveSpecifiedTab(relTp.Text, false);
4135 e.SuppressKeyPress = true;
4139 public void AddNewTabForUserTimeline(string user)
4141 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4142 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4144 if (tb.ScreenName == user)
4146 foreach (TabPage tp in ListTab.TabPages)
4148 if (tb.TabName == tp.Text)
4150 ListTab.SelectedTab = tp;
4157 string tabName = "user:" + user;
4158 while (_statuses.ContainsTab(tabName))
4163 var tab = new UserTimelineTabModel(tabName, user);
4164 this._statuses.AddTab(tab);
4165 this.AddNewTab(tab, startup: false);
4167 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4170 this.GetUserTimelineAsync(tab);
4173 public bool AddNewTab(TabModel tab, bool startup)
4176 foreach (TabPage tb in ListTab.TabPages)
4178 if (tb.Text == tab.TabName) return false;
4182 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4184 var _tabPage = new TabPage();
4185 var _listCustom = new DetailsListView();
4187 int cnt = ListTab.TabPages.Count;
4189 ///ToDo:Create and set controls follow tabtypes
4191 using (ControlTransaction.Update(_listCustom))
4192 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4193 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4194 using (ControlTransaction.Layout(this.SplitContainer1, false))
4195 using (ControlTransaction.Layout(this.ListTab, false))
4196 using (ControlTransaction.Layout(this))
4197 using (ControlTransaction.Layout(_tabPage, false))
4199 _tabPage.Controls.Add(_listCustom);
4202 var userTab = tab as UserTimelineTabModel;
4203 var listTab = tab as ListTimelineTabModel;
4204 var searchTab = tab as PublicSearchTabModel;
4206 if (userTab != null || listTab != null)
4208 var label = new Label();
4209 label.Dock = DockStyle.Top;
4210 label.Name = "labelUser";
4213 if (listTab != null)
4215 label.Text = listTab.ListInfo.ToString();
4217 else if (userTab != null)
4219 label.Text = userTab.ScreenName + "'s Timeline";
4221 label.TextAlign = ContentAlignment.MiddleLeft;
4222 using (ComboBox tmpComboBox = new ComboBox())
4224 label.Height = tmpComboBox.Height;
4226 _tabPage.Controls.Add(label);
4229 else if (searchTab != null)
4231 var pnl = new Panel();
4233 var lbl = new Label();
4234 var cmb = new ComboBox();
4235 var btn = new Button();
4236 var cmbLang = new ComboBox();
4238 using (ControlTransaction.Layout(pnl, false))
4240 pnl.Controls.Add(cmb);
4241 pnl.Controls.Add(cmbLang);
4242 pnl.Controls.Add(btn);
4243 pnl.Controls.Add(lbl);
4244 pnl.Name = "panelSearch";
4246 pnl.Dock = DockStyle.Top;
4247 pnl.Height = cmb.Height;
4248 pnl.Enter += SearchControls_Enter;
4249 pnl.Leave += SearchControls_Leave;
4252 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4253 cmb.Dock = DockStyle.Fill;
4254 cmb.Name = "comboSearch";
4255 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4256 cmb.ImeMode = ImeMode.NoControl;
4257 cmb.TabStop = false;
4259 cmb.AutoCompleteMode = AutoCompleteMode.None;
4260 cmb.KeyDown += SearchComboBox_KeyDown;
4263 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4264 cmbLang.Dock = DockStyle.Right;
4266 cmbLang.Name = "comboLang";
4267 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4268 cmbLang.TabStop = false;
4269 cmbLang.TabIndex = 2;
4270 cmbLang.Items.Add("");
4271 cmbLang.Items.Add("ja");
4272 cmbLang.Items.Add("en");
4273 cmbLang.Items.Add("ar");
4274 cmbLang.Items.Add("da");
4275 cmbLang.Items.Add("nl");
4276 cmbLang.Items.Add("fa");
4277 cmbLang.Items.Add("fi");
4278 cmbLang.Items.Add("fr");
4279 cmbLang.Items.Add("de");
4280 cmbLang.Items.Add("hu");
4281 cmbLang.Items.Add("is");
4282 cmbLang.Items.Add("it");
4283 cmbLang.Items.Add("no");
4284 cmbLang.Items.Add("pl");
4285 cmbLang.Items.Add("pt");
4286 cmbLang.Items.Add("ru");
4287 cmbLang.Items.Add("es");
4288 cmbLang.Items.Add("sv");
4289 cmbLang.Items.Add("th");
4291 lbl.Text = "Search(C-S-f)";
4292 lbl.Name = "label1";
4293 lbl.Dock = DockStyle.Left;
4295 lbl.Height = cmb.Height;
4296 lbl.TextAlign = ContentAlignment.MiddleLeft;
4299 btn.Text = "Search";
4300 btn.Name = "buttonSearch";
4301 btn.UseVisualStyleBackColor = true;
4302 btn.Dock = DockStyle.Right;
4303 btn.TabStop = false;
4305 btn.Click += SearchButton_Click;
4307 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4309 cmb.Items.Add(searchTab.SearchWords);
4310 cmb.Text = searchTab.SearchWords;
4313 cmbLang.Text = searchTab.SearchLang;
4315 _tabPage.Controls.Add(pnl);
4319 _tabPage.Tag = _listCustom;
4320 this.ListTab.Controls.Add(_tabPage);
4322 _tabPage.Location = new Point(4, 4);
4323 _tabPage.Name = "CTab" + cnt;
4324 _tabPage.Size = new Size(380, 260);
4325 _tabPage.TabIndex = 2 + cnt;
4326 _tabPage.Text = tab.TabName;
4327 _tabPage.UseVisualStyleBackColor = true;
4328 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4330 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4331 _listCustom.TabIndex = 1;
4332 _listCustom.AllowColumnReorder = true;
4333 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4334 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4335 _listCustom.Dock = DockStyle.Fill;
4336 _listCustom.FullRowSelect = true;
4337 _listCustom.HideSelection = false;
4338 _listCustom.Location = new Point(0, 0);
4339 _listCustom.Margin = new Padding(0);
4340 _listCustom.Name = "CList" + Environment.TickCount;
4341 _listCustom.ShowItemToolTips = true;
4342 _listCustom.Size = new Size(380, 260);
4343 _listCustom.UseCompatibleStateImageBehavior = false;
4344 _listCustom.View = View.Details;
4345 _listCustom.OwnerDraw = true;
4346 _listCustom.VirtualMode = true;
4347 _listCustom.Font = _fntReaded;
4348 _listCustom.BackColor = _clListBackcolor;
4350 _listCustom.GridLines = SettingManager.Common.ShowGrid;
4351 _listCustom.AllowDrop = true;
4353 _listCustom.SmallImageList = _listViewImageList;
4355 InitColumns(_listCustom, startup);
4357 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4358 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4359 _listCustom.ColumnClick += MyList_ColumnClick;
4360 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4361 _listCustom.DragDrop += TweenMain_DragDrop;
4362 _listCustom.DragEnter += TweenMain_DragEnter;
4363 _listCustom.DragOver += TweenMain_DragOver;
4364 _listCustom.DrawItem += MyList_DrawItem;
4365 _listCustom.MouseClick += MyList_MouseClick;
4366 _listCustom.ColumnReordered += MyList_ColumnReordered;
4367 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4368 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4369 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4370 _listCustom.DrawSubItem += MyList_DrawSubItem;
4371 _listCustom.HScrolled += MyList_HScrolled;
4377 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4379 var tabInfo = _statuses.GetTabByName(TabName);
4380 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4384 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4385 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4386 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4392 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4393 if (_tabPage == null) return false;
4395 SetListProperty(); //他のタブに列幅等を反映
4398 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4399 _tabPage.Tag = null;
4401 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4402 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4403 using (ControlTransaction.Layout(this.SplitContainer1, false))
4404 using (ControlTransaction.Layout(this.ListTab, false))
4405 using (ControlTransaction.Layout(this))
4406 using (ControlTransaction.Layout(_tabPage, false))
4408 if (this.ListTab.SelectedTab == _tabPage)
4410 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4411 this._beforeSelectedTab = null;
4413 this.ListTab.Controls.Remove(_tabPage);
4416 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4418 using (Control label = _tabPage.Controls["labelUser"])
4420 _tabPage.Controls.Remove(label);
4423 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4425 using (Control pnl = _tabPage.Controls["panelSearch"])
4427 pnl.Enter -= SearchControls_Enter;
4428 pnl.Leave -= SearchControls_Leave;
4429 _tabPage.Controls.Remove(pnl);
4431 foreach (Control ctrl in pnl.Controls)
4433 if (ctrl.Name == "buttonSearch")
4435 ctrl.Click -= SearchButton_Click;
4437 else if (ctrl.Name == "comboSearch")
4439 ctrl.KeyDown -= SearchComboBox_KeyDown;
4441 pnl.Controls.Remove(ctrl);
4447 _tabPage.Controls.Remove(_listCustom);
4449 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4450 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4451 _listCustom.ColumnClick -= MyList_ColumnClick;
4452 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4453 _listCustom.DragDrop -= TweenMain_DragDrop;
4454 _listCustom.DragEnter -= TweenMain_DragEnter;
4455 _listCustom.DragOver -= TweenMain_DragOver;
4456 _listCustom.DrawItem -= MyList_DrawItem;
4457 _listCustom.MouseClick -= MyList_MouseClick;
4458 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4459 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4460 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4461 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4462 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4463 _listCustom.HScrolled -= MyList_HScrolled;
4465 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4466 _listCustom.Columns.Clear();
4467 cols.ForEach(col => col.Dispose());
4470 _listCustom.ContextMenuStrip = null;
4471 _listCustom.ColumnHeaderContextMenuStrip = null;
4472 _listCustom.Font = null;
4474 _listCustom.SmallImageList = null;
4475 _listCustom.ListViewItemSorter = null;
4478 if (_curTab.Equals(_tabPage))
4485 this.PurgeListViewItemCache();
4489 _listCustom.Dispose();
4490 _statuses.RemoveTab(TabName);
4492 foreach (TabPage tp in ListTab.TabPages)
4494 DetailsListView lst = (DetailsListView)tp.Tag;
4495 var count = _statuses.Tabs[tp.Text].AllCount;
4496 lst.VirtualListSize = count;
4502 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4504 this.PurgeListViewItemCache();
4505 _beforeSelectedTab = e.TabPage;
4508 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4512 if (!SettingManager.Common.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4515 Rectangle dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4516 if (!dragEnableRectangle.Contains(e.Location))
4518 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4519 tn = ListTab.SelectedTab.Text;
4522 if (string.IsNullOrEmpty(tn)) return;
4524 foreach (TabPage tb in ListTab.TabPages)
4528 ListTab.DoDragDrop(tb, DragDropEffects.All);
4538 Point cpos = new Point(e.X, e.Y);
4539 for (int i = 0; i < ListTab.TabPages.Count; i++)
4541 Rectangle rect = ListTab.GetTabRect(i);
4542 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4543 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4545 _rclickTabName = ListTab.TabPages[i].Text;
4551 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4553 //_curList.Refresh();
4554 SetMainWindowTitle();
4555 SetStatusLabelUrl();
4556 SetApiStatusLabel();
4557 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4558 TabMenuControl(ListTab.SelectedTab.Text);
4559 this.PushSelectPostChain();
4560 await DispSelectedPost();
4563 private void SetListProperty()
4565 //削除などで見つからない場合は処理せず
4566 if (_curList == null) return;
4567 if (!_isColumnChanged) return;
4569 int[] dispOrder = new int[_curList.Columns.Count];
4570 for (int i = 0; i < _curList.Columns.Count; i++)
4572 for (int j = 0; j < _curList.Columns.Count; j++)
4574 if (_curList.Columns[j].DisplayIndex == i)
4583 foreach (TabPage tb in ListTab.TabPages)
4585 if (!tb.Equals(_curTab))
4587 if (tb.Tag != null && tb.Controls.Count > 0)
4589 DetailsListView lst = (DetailsListView)tb.Tag;
4590 for (int i = 0; i < lst.Columns.Count; i++)
4592 lst.Columns[dispOrder[i]].DisplayIndex = i;
4593 lst.Columns[i].Width = _curList.Columns[i].Width;
4599 _isColumnChanged = false;
4602 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4604 if (e.KeyChar == '@')
4606 if (!SettingManager.Common.UseAtIdSupplement) return;
4608 int cnt = AtIdSupl.ItemCount;
4609 ShowSuplDialog(StatusText, AtIdSupl);
4610 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
4613 else if (e.KeyChar == '#')
4615 if (!SettingManager.Common.UseHashSupplement) return;
4616 ShowSuplDialog(StatusText, HashSupl);
4621 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4623 ShowSuplDialog(owner, dialog, 0, "");
4626 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4628 ShowSuplDialog(owner, dialog, offset, "");
4631 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4633 dialog.StartsWith = startswith;
4640 dialog.ShowDialog();
4642 this.TopMost = SettingManager.Common.AlwaysTop;
4643 int selStart = owner.SelectionStart;
4646 if (dialog.DialogResult == DialogResult.OK)
4648 if (!string.IsNullOrEmpty(dialog.inputText))
4652 fHalf = owner.Text.Substring(0, selStart - offset);
4654 if (selStart < owner.Text.Length)
4656 eHalf = owner.Text.Substring(selStart);
4658 owner.Text = fHalf + dialog.inputText + eHalf;
4659 owner.SelectionStart = selStart + dialog.inputText.Length;
4666 fHalf = owner.Text.Substring(0, selStart);
4668 if (selStart < owner.Text.Length)
4670 eHalf = owner.Text.Substring(selStart);
4672 owner.Text = fHalf + eHalf;
4675 owner.SelectionStart = selStart;
4681 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4684 if (!e.Alt && !e.Control && !e.Shift)
4686 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4688 bool isSpace = false;
4689 foreach (char c in StatusText.Text)
4691 if (c == ' ' || c == ' ')
4704 StatusText.Text = "";
4705 JumpUnreadMenuItem_Click(null, null);
4709 this.StatusText_TextChanged(null, null);
4712 private void StatusText_TextChanged(object sender, EventArgs e)
4715 int pLen = this.GetRestStatusCount(this.StatusText.Text);
4716 lblLen.Text = pLen.ToString();
4719 StatusText.ForeColor = Color.Red;
4723 StatusText.ForeColor = _clInputFont;
4726 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4728 if (string.IsNullOrEmpty(StatusText.Text))
4730 this.inReplyTo = null;
4735 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
4737 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
4739 List<long> _autoPopulatedUserIds = new List<long>();
4741 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Item1] : null;
4742 if (replyToPost != null)
4744 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
4746 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
4748 foreach (var reply in replyToPost.ReplyToList)
4750 if (statusText.StartsWith($"@{reply.Item2} ", StringComparison.Ordinal))
4752 statusText = statusText.Substring(reply.Item2.Length + 2);
4753 _autoPopulatedUserIds.Add(reply.Item1);
4759 autoPopulatedUserIds = _autoPopulatedUserIds.ToArray();
4765 /// ツイート投稿前のフッター付与などの前処理を行います
4767 private string FormatStatusText(string statusText)
4769 statusText = statusText.Replace("\r\n", "\n");
4771 if (this.urlMultibyteSplit)
4774 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4777 if (SettingManager.Common.WideSpaceConvert)
4779 // 文中の全角スペースを半角スペース1個にする
4780 statusText = statusText.Replace(" ", " ");
4783 // DM の場合はこれ以降の処理を行わない
4784 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4788 if (SettingManager.Common.PostShiftEnter)
4790 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4794 if (this.StatusText.Multiline && !SettingManager.Common.PostCtrlEnter)
4795 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4797 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4800 if (statusText.Contains("RT @"))
4801 disableFooter = true;
4803 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
4804 if (this.inReplyTo != null && this.inReplyTo.Item2 == this.tw.Username)
4806 var mentionSelf = $"@{this.tw.Username} ";
4807 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
4809 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
4810 statusText = statusText.Substring(mentionSelf.Length);
4817 var hashtag = this.HashMgr.UseHash;
4818 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4821 header = HashMgr.UseHash + " ";
4823 footer = " " + HashMgr.UseHash;
4828 if (SettingManager.Local.UseRecommendStatus)
4831 footer += this.recommendedStatusFooter;
4833 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4835 // テキストボックスに入力されている文字列を使用する
4836 footer += " " + SettingManager.Local.StatusText.Trim();
4840 statusText = header + statusText + footer;
4842 if (this.preventSmsCommand)
4844 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4845 // 参照: https://support.twitter.com/articles/14020
4847 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4848 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4850 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4851 statusText = '\u200b' + statusText;
4859 /// 投稿欄に表示する入力可能な文字数を計算します
4861 private int GetRestStatusCount(string statusText)
4863 long[] autoPopulatedUserIds;
4864 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
4866 statusText = this.FormatStatusText(statusText);
4868 var remainCount = this.tw.GetTextLengthRemain(statusText);
4870 var uploadService = this.GetSelectedImageService();
4871 if (uploadService != null)
4873 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4874 remainCount -= uploadService.GetReservedTextLength(1);
4880 private IMediaUploadService GetSelectedImageService()
4881 => this.ImageSelector.Visible ? this.ImageSelector.SelectedService : null;
4883 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4885 if (sender != this._curList)
4888 var listCache = this._listItemCache;
4889 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4891 // If the newly requested cache is a subset of the old cache,
4892 // no need to rebuild everything, so do nothing.
4896 // Now we need to rebuild the cache.
4897 this.CreateCache(e.StartIndex, e.EndIndex);
4900 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4902 var listCache = this._listItemCache;
4903 if (listCache?.TargetList == sender)
4905 if (listCache.TryGetValue(e.ItemIndex, out var item, out var cacheItemPost))
4912 // A cache miss, so create a new ListViewItem and pass it back.
4913 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4916 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4920 // 不正な要求に対する間に合わせの応答
4921 string[] sitem = {"", "", "", "", "", "", "", ""};
4922 e.Item = new ImageListViewItem(sitem);
4926 private void CreateCache(int startIndex, int endIndex)
4928 var tabInfo = this._statuses.Tabs[this._curTab.Text];
4930 if (tabInfo.AllCount == 0)
4933 // インデックスを 0...(tabInfo.AllCount - 1) の範囲内にする
4934 int FilterRange(int index)
4935 => Math.Max(Math.Min(index, tabInfo.AllCount - 1), 0);
4937 // キャッシュ要求(要求範囲±30を作成)
4938 startIndex = FilterRange(startIndex - 30);
4939 endIndex = FilterRange(endIndex + 30);
4941 var cacheLength = endIndex - startIndex + 1;
4943 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4944 var listItems = Enumerable.Range(0, cacheLength)
4945 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4948 var listCache = new ListViewItemCache
4950 TargetList = this._curList,
4951 StartIndex = startIndex,
4952 EndIndex = endIndex,
4954 ListItem = listItems,
4957 Interlocked.Exchange(ref this._listItemCache, listCache);
4961 /// DetailsListView のための ListViewItem のキャッシュを消去する
4963 private void PurgeListViewItemCache()
4965 Interlocked.Exchange(ref this._listItemCache, null);
4968 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
4970 StringBuilder mk = new StringBuilder();
4971 //if (Post.IsDeleted) mk.Append("×");
4972 //if (Post.IsMark) mk.Append("♪");
4973 //if (Post.IsProtect) mk.Append("Ю");
4974 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4975 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4976 ImageListViewItem itm;
4977 if (Post.RetweetedId == null)
4979 string[] sitem= {"",
4981 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4982 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4987 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4991 string[] sitem = {"",
4993 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4994 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4995 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4999 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5001 itm.StateIndex = Post.StateIndex;
5004 bool read = Post.IsRead;
5005 //未読管理していなかったら既読として扱う
5006 if (!_statuses.Tabs[Tab.Text].UnreadManage || !SettingManager.Common.UnreadManage) read = true;
5007 ChangeItemStyleRead(read, itm, Post, null);
5008 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5013 /// 全てのタブの振り分けルールを反映し直します
5015 private void ApplyPostFilters()
5017 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5019 this.PurgeListViewItemCache();
5020 this._curPost = null;
5021 this._curItemIndex = -1;
5022 this._statuses.FilterAll();
5024 foreach (TabPage tabPage in this.ListTab.TabPages)
5026 var tab = this._statuses.Tabs[tabPage.Text];
5028 var listview = (DetailsListView)tabPage.Tag;
5029 using (ControlTransaction.Update(listview))
5031 listview.VirtualListSize = tab.AllCount;
5034 if (SettingManager.Common.TabIconDisp)
5036 if (tab.UnreadCount > 0)
5037 tabPage.ImageIndex = 0;
5039 tabPage.ImageIndex = -1;
5043 if (!SettingManager.Common.TabIconDisp)
5044 this.ListTab.Refresh();
5046 SetMainWindowTitle();
5047 SetStatusLabelUrl();
5051 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5053 e.DrawDefault = true;
5056 private void MyList_HScrolled(object sender, EventArgs e)
5058 DetailsListView listView = (DetailsListView)sender;
5062 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5064 if (e.State == 0) return;
5065 e.DrawDefault = false;
5067 SolidBrush brs2 = null;
5068 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5070 if (e.Item.BackColor == _clSelf)
5071 brs2 = _brsBackColorMine;
5072 else if (e.Item.BackColor == _clAtSelf)
5073 brs2 = _brsBackColorAt;
5074 else if (e.Item.BackColor == _clTarget)
5075 brs2 = _brsBackColorYou;
5076 else if (e.Item.BackColor == _clAtTarget)
5077 brs2 = _brsBackColorAtYou;
5078 else if (e.Item.BackColor == _clAtFromTarget)
5079 brs2 = _brsBackColorAtFromTarget;
5080 else if (e.Item.BackColor == _clAtTo)
5081 brs2 = _brsBackColorAtTo;
5083 brs2 = _brsBackColorNone;
5088 if (((Control)sender).Focused)
5089 brs2 = _brsHighLight;
5091 brs2 = _brsDeactiveSelection;
5093 e.Graphics.FillRectangle(brs2, e.Bounds);
5094 e.DrawFocusRectangle();
5095 this.DrawListViewItemIcon(e);
5098 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5100 if (e.ItemState == 0) return;
5102 if (e.ColumnIndex > 0)
5105 var post = (PostClass)e.Item.Tag;
5107 RectangleF rct = e.Bounds;
5108 rct.Width = e.Header.Width;
5109 int fontHeight = e.Item.Font.Height;
5112 rct.Y += fontHeight;
5113 rct.Height -= fontHeight;
5116 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out var heightDiff));
5118 //if (heightDiff > fontHeight * 0.7)
5120 // rct.Height += fontHeight;
5121 // drawLineCount += 1;
5124 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5125 if (!_iconCol && drawLineCount <= 1)
5127 //rct.Inflate(0, heightDiff / -2);
5128 //rct.Height += fontHeight / 2;
5130 else if (heightDiff < fontHeight * 0.7)
5132 //最終行が70%以上欠けていたら、最終行は表示しない
5133 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5134 rct.Height = (fontHeight * drawLineCount) - 1;
5141 //if (!_iconCol && drawLineCount > 1)
5143 // rct.Y += fontHeight * 0.2;
5144 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5149 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5150 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5155 Rectangle rctB = e.Bounds;
5156 rctB.Width = e.Header.Width;
5157 rctB.Height = fontHeight;
5159 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5161 TextRenderer.DrawText(e.Graphics,
5162 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5164 Rectangle.Round(rct),
5166 TextFormatFlags.WordBreak |
5167 TextFormatFlags.EndEllipsis |
5168 TextFormatFlags.GlyphOverhangPadding |
5169 TextFormatFlags.NoPrefix);
5170 TextRenderer.DrawText(e.Graphics,
5171 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 + "]",
5175 TextFormatFlags.SingleLine |
5176 TextFormatFlags.EndEllipsis |
5177 TextFormatFlags.GlyphOverhangPadding |
5178 TextFormatFlags.NoPrefix);
5184 if (e.ColumnIndex != 2)
5185 text = e.SubItem.Text;
5187 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5189 if (drawLineCount == 1)
5191 TextRenderer.DrawText(e.Graphics,
5194 Rectangle.Round(rct),
5196 TextFormatFlags.SingleLine |
5197 TextFormatFlags.EndEllipsis |
5198 TextFormatFlags.GlyphOverhangPadding |
5199 TextFormatFlags.NoPrefix |
5200 TextFormatFlags.VerticalCenter);
5204 TextRenderer.DrawText(e.Graphics,
5207 Rectangle.Round(rct),
5209 TextFormatFlags.WordBreak |
5210 TextFormatFlags.EndEllipsis |
5211 TextFormatFlags.GlyphOverhangPadding |
5212 TextFormatFlags.NoPrefix);
5215 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5220 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5222 if (_iconSz == 0) return;
5224 ImageListViewItem item = (ImageListViewItem)e.Item;
5226 //e.Bounds.Leftが常に0を指すから自前で計算
5227 Rectangle itemRect = item.Bounds;
5228 var col0 = e.Item.ListView.Columns[0];
5229 itemRect.Width = col0.Width;
5231 if (col0.DisplayIndex > 0)
5233 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5235 if (clm.DisplayIndex < col0.DisplayIndex)
5236 itemRect.X += clm.Width;
5240 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5241 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5242 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5245 var img = item.Image;
5248 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5249 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5251 if (iconRect.Width > 0)
5253 e.Graphics.FillRectangle(Brushes.White, iconRect);
5254 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5257 e.Graphics.DrawImage(img.Image, iconRect);
5259 catch (ArgumentException)
5261 item.RefreshImageAsync();
5267 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5268 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5270 item.GetImageAsync();
5273 if (item.StateIndex > -1)
5275 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5276 if (stateRect.Width > 0)
5278 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5279 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5280 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5285 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5287 base.ScaleControl(factor, specified);
5289 ScaleChildControl(this.TabImage, factor);
5291 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5292 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5294 foreach (var listview in listviews)
5296 ScaleChildControl(listview, factor);
5300 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5302 // ImageListViewItem item = (ImageListViewItem)e.Item;
5303 // if (item.StateImageIndex > -1)
5305 // ////e.Bounds.Leftが常に0を指すから自前で計算
5306 // //Rectangle itemRect = item.Bounds;
5307 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5309 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5311 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5313 // // itemRect.X += clm.Width;
5317 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5318 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5320 // if (rct.Width > 0)
5322 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5323 // //e.Graphics.FillRectangle(Brushes.White, rct);
5324 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5325 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5330 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5332 var tab = this._statuses.Tabs[this._curTab.Text];
5334 if (tab.AllCount == 0)
5336 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5340 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5345 case SEARCHTYPE.NextSearch: // 次を検索
5346 if (selectedIndex != -1)
5347 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5351 case SEARCHTYPE.PrevSearch: // 前を検索
5352 if (selectedIndex != -1)
5353 startIndex = Math.Max(selectedIndex - 1, 0);
5355 startIndex = tab.AllCount - 1;
5357 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5359 if (selectedIndex != -1)
5360 startIndex = selectedIndex;
5366 Func<string, bool> stringComparer;
5369 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5371 catch (ArgumentException)
5373 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5377 var reverse = searchType == SEARCHTYPE.PrevSearch;
5378 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5379 .DefaultIfEmpty(-1).First();
5381 if (foundIndex == -1)
5383 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5387 this.SelectListItem(this._curList, foundIndex);
5388 this._curList.EnsureVisible(foundIndex);
5391 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5394 this.ShowSearchDialog();
5397 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5399 var previousSearch = this.SearchDialog.ResultOptions;
5400 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5402 this.SearchDialog.Reset();
5403 this.ShowSearchDialog();
5409 previousSearch.Query,
5410 previousSearch.CaseSensitive,
5411 previousSearch.UseRegex,
5412 SEARCHTYPE.NextSearch);
5415 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5417 var previousSearch = this.SearchDialog.ResultOptions;
5418 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5420 this.SearchDialog.Reset();
5421 this.ShowSearchDialog();
5427 previousSearch.Query,
5428 previousSearch.CaseSensitive,
5429 previousSearch.UseRegex,
5430 SEARCHTYPE.PrevSearch);
5434 /// 検索ダイアログを表示し、検索を実行します
5436 private void ShowSearchDialog()
5438 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5440 this.TopMost = SettingManager.Common.AlwaysTop;
5443 this.TopMost = SettingManager.Common.AlwaysTop;
5445 var searchOptions = this.SearchDialog.ResultOptions;
5446 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5448 if (searchOptions.NewTab)
5450 var tabName = Properties.Resources.SearchResults_TabName;
5454 tabName = this._statuses.MakeTabName(tabName);
5456 catch (TabException ex)
5458 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5461 var resultTab = new LocalSearchTabModel(tabName);
5462 this.AddNewTab(resultTab, startup: false);
5463 this._statuses.AddTab(resultTab);
5465 var targetTab = this._statuses.Tabs[this._curTab.Text];
5467 Func<string, bool> stringComparer;
5470 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5472 catch (ArgumentException)
5474 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5478 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5479 if (foundIndices.Length == 0)
5481 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5485 var foundPosts = foundIndices.Select(x => targetTab[x]);
5486 foreach (var post in foundPosts)
5488 resultTab.AddPostQueue(post);
5491 this._statuses.DistributePosts();
5492 this.RefreshTimeline();
5494 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5495 .First(x => x.Text == tabName);
5497 this.ListTab.SelectedTab = tabPage;
5502 searchOptions.Query,
5503 searchOptions.CaseSensitive,
5504 searchOptions.UseRegex,
5505 SEARCHTYPE.DialogSearch);
5508 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5510 this.AddNewTabForSearch(searchOptions.Query);
5514 /// <summary>発言検索に使用するメソッドを生成します</summary>
5515 /// <exception cref="ArgumentException">
5516 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5518 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5522 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5523 var regex = new Regex(query, regexOption);
5525 return x => regex.IsMatch(x);
5529 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5531 return x => x.IndexOf(query, comparisonType) != -1;
5535 private void AboutMenuItem_Click(object sender, EventArgs e)
5537 using (TweenAboutBox about = new TweenAboutBox())
5539 about.ShowDialog(this);
5541 this.TopMost = SettingManager.Common.AlwaysTop;
5544 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5546 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5548 if (ImageSelector.Enabled)
5551 TabModel foundTab = null;
5554 DetailsListView lst = null;
5557 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5559 var tabPage = this.ListTab.TabPages[i];
5560 var tab = this._statuses.Tabs[tabPage.Text];
5561 var unreadIndex = tab.NextUnreadIndex;
5563 if (unreadIndex != -1)
5565 ListTab.SelectedIndex = i;
5567 foundIndex = unreadIndex;
5568 lst = (DetailsListView)tabPage.Tag;
5573 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5574 if (foundTab == null && bgnIdx > 0)
5576 for (int i = 0; i < bgnIdx; i++)
5578 var tabPage = this.ListTab.TabPages[i];
5579 var tab = this._statuses.Tabs[tabPage.Text];
5580 var unreadIndex = tab.NextUnreadIndex;
5582 if (unreadIndex != -1)
5584 ListTab.SelectedIndex = i;
5586 foundIndex = unreadIndex;
5587 lst = (DetailsListView)tabPage.Tag;
5593 if (foundTab == null)
5595 //全部調べたが未読見つからず→先頭タブの最新発言へ
5596 ListTab.SelectedIndex = 0;
5597 var tabPage = this.ListTab.TabPages[0];
5598 var tab = this._statuses.Tabs[tabPage.Text];
5600 if (tab.AllCount == 0)
5603 if (_statuses.SortOrder == SortOrder.Ascending)
5604 foundIndex = tab.AllCount - 1;
5608 lst = (DetailsListView)tabPage.Tag;
5611 SelectListItem(lst, foundIndex);
5613 if (_statuses.SortMode == ComparerMode.Id)
5615 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5616 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5622 lst.EnsureVisible(foundIndex);
5627 lst.EnsureVisible(foundIndex);
5633 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5635 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5637 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5638 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5642 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5644 if (_curList.SelectedIndices.Count > 0)
5646 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5647 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5651 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5653 await this.CheckNewVersion(false);
5656 private void RunTweenUp()
5658 ProcessStartInfo pinfo = new ProcessStartInfo();
5659 pinfo.UseShellExecute = true;
5660 pinfo.WorkingDirectory = MyCommon.settingPath;
5661 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5662 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5665 Process.Start(pinfo);
5669 MessageBox.Show("Failed to execute TweenUp3.exe.");
5673 public class VersionInfo
5675 public Version Version { get; set; }
5676 public Uri DownloadUri { get; set; }
5677 public string ReleaseNote { get; set; }
5681 /// OpenTween の最新バージョンの情報を取得します
5683 public async Task<VersionInfo> GetVersionInfoAsync()
5685 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5686 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5688 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5689 .ConfigureAwait(false);
5691 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5692 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5694 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5695 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5697 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5699 return new VersionInfo
5701 Version = Version.Parse(msgHeader[0]),
5702 DownloadUri = new Uri(msgHeader[1]),
5703 ReleaseNote = msgBody,
5707 private async Task CheckNewVersion(bool startup = false)
5709 if (ApplicationSettings.VersionInfoUrl == null)
5710 return; // 更新チェック無効化
5714 var versionInfo = await this.GetVersionInfoAsync();
5716 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5721 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5722 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5723 msgtext = MyCommon.ReplaceAppName(msgtext);
5725 MessageBox.Show(msgtext,
5726 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5727 MessageBoxButtons.OK, MessageBoxIcon.Information);
5732 using (var dialog = new UpdateDialog())
5734 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5735 MyCommon.GetReadableVersion(versionInfo.Version));
5736 dialog.DetailsText = versionInfo.ReleaseNote;
5738 if (dialog.ShowDialog(this) == DialogResult.Yes)
5740 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5746 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5749 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5750 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5751 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5756 private async Task Colorize()
5759 await this.DispSelectedPost();
5760 //件数関連の場合、タイトル即時書き換え
5761 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5762 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5763 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5764 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5766 SetMainWindowTitle();
5768 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5769 SetStatusLabelUrl();
5770 foreach (TabPage tb in ListTab.TabPages)
5772 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5774 if (SettingManager.Common.TabIconDisp)
5776 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5780 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
5783 public string createDetailHtml(string orgdata)
5785 if (SettingManager.Local.UseTwemoji)
5786 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5788 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5791 private Task DispSelectedPost()
5793 return this.DispSelectedPost(false);
5796 private PostClass displayPost = new PostClass();
5799 /// サムネイル表示に使用する CancellationToken の生成元
5801 private CancellationTokenSource thumbnailTokenSource = null;
5803 private async Task DispSelectedPost(bool forceupdate)
5805 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5808 var oldDisplayPost = this.displayPost;
5809 this.displayPost = this._curPost;
5811 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5814 var loadTasks = new List<Task>
5816 this.tweetDetailsView.ShowPostDetails(this._curPost),
5819 this.SplitContainer3.Panel2Collapsed = true;
5821 if (SettingManager.Common.PreviewEnable)
5823 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5824 oldTokenSource?.Cancel();
5826 var token = this.thumbnailTokenSource.Token;
5827 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5832 await Task.WhenAll(loadTasks);
5834 catch (OperationCanceledException) { }
5837 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5839 await this.OpenApplicationWebsite();
5842 private async Task OpenApplicationWebsite()
5844 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5847 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5849 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5852 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5854 if (ListTab.SelectedTab != null)
5856 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
5858 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
5859 if (pnl.Controls["comboSearch"].Focused ||
5860 pnl.Controls["comboLang"].Focused ||
5861 pnl.Controls["buttonSearch"].Focused) return;
5864 if (e.Control || e.Shift || e.Alt)
5865 this._anchorFlag = false;
5867 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
5870 e.SuppressKeyPress = true;
5873 if (asyncTask != null)
5878 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
5880 private void InitializeShortcuts()
5882 this.shortcutCommands = new[]
5884 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5885 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5886 .FocusedOn(FocusedControl.ListTab)
5887 .Do(() => SendKeys.Send("{DOWN}")),
5889 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5890 .FocusedOn(FocusedControl.ListTab)
5891 .Do(() => SendKeys.Send("{UP}")),
5893 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5894 .FocusedOn(FocusedControl.ListTab)
5895 .Do(() => SendKeys.Send("{PGDN}")),
5897 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5898 .FocusedOn(FocusedControl.ListTab)
5899 .Do(() => SendKeys.Send("{PGUP}")),
5901 ShortcutCommand.Create(Keys.F1)
5902 .Do(() => this.OpenApplicationWebsite()),
5904 ShortcutCommand.Create(Keys.F3)
5905 .Do(() => this.MenuItemSearchNext_Click(null, null)),
5907 ShortcutCommand.Create(Keys.F5)
5908 .Do(() => this.DoRefresh()),
5910 ShortcutCommand.Create(Keys.F6)
5911 .Do(() => this.GetReplyAsync()),
5913 ShortcutCommand.Create(Keys.F7)
5914 .Do(() => this.GetDirectMessagesAsync()),
5916 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5917 .NotFocusedOn(FocusedControl.StatusText)
5918 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5920 ShortcutCommand.Create(Keys.G)
5921 .NotFocusedOn(FocusedControl.StatusText)
5922 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5924 ShortcutCommand.Create(Keys.Right, Keys.N)
5925 .FocusedOn(FocusedControl.ListTab)
5926 .Do(() => this.GoRelPost(forward: true)),
5928 ShortcutCommand.Create(Keys.Left, Keys.P)
5929 .FocusedOn(FocusedControl.ListTab)
5930 .Do(() => this.GoRelPost(forward: false)),
5932 ShortcutCommand.Create(Keys.OemPeriod)
5933 .FocusedOn(FocusedControl.ListTab)
5934 .Do(() => this.GoAnchor()),
5936 ShortcutCommand.Create(Keys.I)
5937 .FocusedOn(FocusedControl.ListTab)
5938 .OnlyWhen(() => this.StatusText.Enabled)
5939 .Do(() => this.StatusText.Focus()),
5941 ShortcutCommand.Create(Keys.Enter)
5942 .FocusedOn(FocusedControl.ListTab)
5943 .Do(() => this.MakeReplyOrDirectStatus()),
5945 ShortcutCommand.Create(Keys.R)
5946 .FocusedOn(FocusedControl.ListTab)
5947 .Do(() => this.DoRefresh()),
5949 ShortcutCommand.Create(Keys.L)
5950 .FocusedOn(FocusedControl.ListTab)
5951 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5953 ShortcutCommand.Create(Keys.H)
5954 .FocusedOn(FocusedControl.ListTab)
5955 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5957 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5958 .FocusedOn(FocusedControl.ListTab)
5959 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5961 ShortcutCommand.Create(Keys.S)
5962 .FocusedOn(FocusedControl.ListTab)
5963 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5965 ShortcutCommand.Create(Keys.A)
5966 .FocusedOn(FocusedControl.ListTab)
5967 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5969 // ] in_reply_to参照元へ戻る
5970 ShortcutCommand.Create(Keys.Oem4)
5971 .FocusedOn(FocusedControl.ListTab)
5972 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5974 // [ in_reply_toへジャンプ
5975 ShortcutCommand.Create(Keys.Oem6)
5976 .FocusedOn(FocusedControl.ListTab)
5977 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5979 ShortcutCommand.Create(Keys.Escape)
5980 .FocusedOn(FocusedControl.ListTab)
5982 this._anchorFlag = false;
5983 if (ListTab.SelectedTab != null)
5985 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
5986 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5988 var relTp = ListTab.SelectedTab;
5989 RemoveSpecifiedTab(relTp.Text, false);
5995 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5996 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5997 .FocusedOn(FocusedControl.ListTab)
5998 .Do(() => this._anchorFlag = false, preventDefault: false),
6000 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6001 ShortcutCommand.Create(Keys.Up, Keys.Down)
6002 .FocusedOn(FocusedControl.PostBrowser)
6005 ShortcutCommand.Create(Keys.Control | Keys.R)
6006 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6008 ShortcutCommand.Create(Keys.Control | Keys.D)
6009 .Do(() => this.doStatusDelete()),
6011 ShortcutCommand.Create(Keys.Control | Keys.M)
6012 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6014 ShortcutCommand.Create(Keys.Control | Keys.S)
6015 .Do(() => this.FavoriteChange(FavAdd: true)),
6017 ShortcutCommand.Create(Keys.Control | Keys.I)
6018 .Do(() => this.doRepliedStatusOpen()),
6020 ShortcutCommand.Create(Keys.Control | Keys.Q)
6021 .Do(() => this.doQuoteOfficial()),
6023 ShortcutCommand.Create(Keys.Control | Keys.B)
6024 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6026 ShortcutCommand.Create(Keys.Control | Keys.T)
6027 .Do(() => this.HashManageMenuItem_Click(null, null)),
6029 ShortcutCommand.Create(Keys.Control | Keys.L)
6030 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6032 ShortcutCommand.Create(Keys.Control | Keys.Y)
6033 .NotFocusedOn(FocusedControl.PostBrowser)
6034 .Do(() => this.MultiLineMenuItem_Click(null, null)),
6036 ShortcutCommand.Create(Keys.Control | Keys.F)
6037 .Do(() => this.MenuItemSubSearch_Click(null, null)),
6039 ShortcutCommand.Create(Keys.Control | Keys.U)
6040 .Do(() => this.ShowUserTimeline()),
6042 ShortcutCommand.Create(Keys.Control | Keys.H)
6043 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6045 ShortcutCommand.Create(Keys.Control | Keys.G)
6046 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6048 ShortcutCommand.Create(Keys.Control | Keys.O)
6049 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6051 ShortcutCommand.Create(Keys.Control | Keys.E)
6052 .Do(() => this.OpenURLMenuItem_Click(null, null)),
6054 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6055 .FocusedOn(FocusedControl.ListTab)
6056 .Do(() => this._colorize = true, preventDefault: false),
6058 ShortcutCommand.Create(Keys.Control | Keys.N)
6059 .FocusedOn(FocusedControl.ListTab)
6060 .Do(() => this.GoNextTab(forward: true)),
6062 ShortcutCommand.Create(Keys.Control | Keys.P)
6063 .FocusedOn(FocusedControl.ListTab)
6064 .Do(() => this.GoNextTab(forward: false)),
6066 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6067 .FocusedOn(FocusedControl.ListTab)
6068 .Do(() => this.CopyStot()),
6070 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6071 ShortcutCommand.Create(Keys.Control | Keys.D1)
6072 .FocusedOn(FocusedControl.ListTab)
6073 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6074 .Do(() => this.ListTab.SelectedIndex = 0),
6076 ShortcutCommand.Create(Keys.Control | Keys.D2)
6077 .FocusedOn(FocusedControl.ListTab)
6078 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6079 .Do(() => this.ListTab.SelectedIndex = 1),
6081 ShortcutCommand.Create(Keys.Control | Keys.D3)
6082 .FocusedOn(FocusedControl.ListTab)
6083 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6084 .Do(() => this.ListTab.SelectedIndex = 2),
6086 ShortcutCommand.Create(Keys.Control | Keys.D4)
6087 .FocusedOn(FocusedControl.ListTab)
6088 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6089 .Do(() => this.ListTab.SelectedIndex = 3),
6091 ShortcutCommand.Create(Keys.Control | Keys.D5)
6092 .FocusedOn(FocusedControl.ListTab)
6093 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6094 .Do(() => this.ListTab.SelectedIndex = 4),
6096 ShortcutCommand.Create(Keys.Control | Keys.D6)
6097 .FocusedOn(FocusedControl.ListTab)
6098 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6099 .Do(() => this.ListTab.SelectedIndex = 5),
6101 ShortcutCommand.Create(Keys.Control | Keys.D7)
6102 .FocusedOn(FocusedControl.ListTab)
6103 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6104 .Do(() => this.ListTab.SelectedIndex = 6),
6106 ShortcutCommand.Create(Keys.Control | Keys.D8)
6107 .FocusedOn(FocusedControl.ListTab)
6108 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6109 .Do(() => this.ListTab.SelectedIndex = 7),
6111 ShortcutCommand.Create(Keys.Control | Keys.D9)
6112 .FocusedOn(FocusedControl.ListTab)
6113 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6115 ShortcutCommand.Create(Keys.Control | Keys.A)
6116 .FocusedOn(FocusedControl.StatusText)
6117 .Do(() => this.StatusText.SelectAll()),
6119 ShortcutCommand.Create(Keys.Control | Keys.V)
6120 .FocusedOn(FocusedControl.StatusText)
6121 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6123 ShortcutCommand.Create(Keys.Control | Keys.Up)
6124 .FocusedOn(FocusedControl.StatusText)
6126 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6128 var inReplyToStatusId = this.inReplyTo?.Item1;
6129 var inReplyToScreenName = this.inReplyTo?.Item2;
6130 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6133 if (_hisIdx < 0) _hisIdx = 0;
6135 var historyItem = this._history[this._hisIdx];
6136 StatusText.Text = historyItem.status;
6137 StatusText.SelectionStart = StatusText.Text.Length;
6138 if (historyItem.inReplyToId != null)
6139 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6141 this.inReplyTo = null;
6144 ShortcutCommand.Create(Keys.Control | Keys.Down)
6145 .FocusedOn(FocusedControl.StatusText)
6147 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6149 var inReplyToStatusId = this.inReplyTo?.Item1;
6150 var inReplyToScreenName = this.inReplyTo?.Item2;
6151 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6154 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6156 var historyItem = this._history[this._hisIdx];
6157 StatusText.Text = historyItem.status;
6158 StatusText.SelectionStart = StatusText.Text.Length;
6159 if (historyItem.inReplyToId != null)
6160 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6162 this.inReplyTo = null;
6165 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6166 .FocusedOn(FocusedControl.StatusText)
6168 if (ListTab.SelectedIndex == 0)
6170 ListTab.SelectedIndex = ListTab.TabCount - 1;
6174 ListTab.SelectedIndex -= 1;
6179 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6180 .FocusedOn(FocusedControl.StatusText)
6182 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6184 ListTab.SelectedIndex = 0;
6188 ListTab.SelectedIndex += 1;
6193 ShortcutCommand.Create(Keys.Control | Keys.Y)
6194 .FocusedOn(FocusedControl.PostBrowser)
6196 var multiline = !SettingManager.Local.StatusMultiline;
6197 SettingManager.Local.StatusMultiline = multiline;
6198 MultiLineMenuItem.Checked = multiline;
6199 MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
6202 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6203 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6205 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6206 .Do(() => this.DoRefreshMore()),
6208 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6209 .Do(() => this.GetReplyAsync(loadMore: true)),
6211 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6212 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6214 ShortcutCommand.Create(Keys.Shift | Keys.R)
6215 .NotFocusedOn(FocusedControl.StatusText)
6216 .Do(() => this.DoRefreshMore()),
6218 ShortcutCommand.Create(Keys.Shift | Keys.H)
6219 .FocusedOn(FocusedControl.ListTab)
6220 .Do(() => this.GoTopEnd(GoTop: true)),
6222 ShortcutCommand.Create(Keys.Shift | Keys.L)
6223 .FocusedOn(FocusedControl.ListTab)
6224 .Do(() => this.GoTopEnd(GoTop: false)),
6226 ShortcutCommand.Create(Keys.Shift | Keys.M)
6227 .FocusedOn(FocusedControl.ListTab)
6228 .Do(() => this.GoMiddle()),
6230 ShortcutCommand.Create(Keys.Shift | Keys.G)
6231 .FocusedOn(FocusedControl.ListTab)
6232 .Do(() => this.GoLast()),
6234 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6235 .FocusedOn(FocusedControl.ListTab)
6236 .Do(() => this.MoveMiddle()),
6238 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6239 .FocusedOn(FocusedControl.ListTab)
6240 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6242 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6243 .FocusedOn(FocusedControl.ListTab)
6244 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6246 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6247 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6248 .FocusedOn(FocusedControl.ListTab)
6249 .Do(() => this.GoFav(forward: true)),
6251 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6252 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6253 .FocusedOn(FocusedControl.ListTab)
6254 .Do(() => this.GoFav(forward: false)),
6256 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6257 .FocusedOn(FocusedControl.ListTab)
6258 .Do(() => this.GoBackSelectPostChain()),
6260 ShortcutCommand.Create(Keys.Alt | Keys.R)
6261 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6263 ShortcutCommand.Create(Keys.Alt | Keys.P)
6264 .OnlyWhen(() => this._curPost != null)
6265 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6267 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6268 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6270 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6271 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6273 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6274 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6276 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6277 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6279 // 別タブの同じ書き込みへ(ALT+←/→)
6280 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6281 .FocusedOn(FocusedControl.ListTab)
6282 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6284 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6285 .FocusedOn(FocusedControl.ListTab)
6286 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6288 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6289 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6291 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6292 .Do(() => this.CopyIdUri()),
6294 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6295 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6296 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6297 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6299 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6300 .Do(() => this.FavoriteChange(FavAdd: false)),
6302 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6303 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6305 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6306 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6308 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6309 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6311 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6312 .Do(() => this.doMoveToRTHome()),
6314 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6315 .Do(() => this.FavorareMenuItem_Click(null, null)),
6317 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6318 .FocusedOn(FocusedControl.StatusText)
6320 if (_curList != null && _curList.VirtualListSize != 0 &&
6321 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6323 var idx = _curList.SelectedIndices[0] - 1;
6324 SelectListItem(_curList, idx);
6325 _curList.EnsureVisible(idx);
6329 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6330 .FocusedOn(FocusedControl.StatusText)
6332 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6333 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6335 var idx = _curList.SelectedIndices[0] + 1;
6336 SelectListItem(_curList, idx);
6337 _curList.EnsureVisible(idx);
6341 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6342 .FocusedOn(FocusedControl.StatusText)
6344 if (StatusText.SelectionStart > 0)
6346 int endidx = StatusText.SelectionStart - 1;
6347 string startstr = "";
6348 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6350 char c = StatusText.Text[i];
6351 if (Char.IsLetterOrDigit(c) || c == '_')
6357 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6358 int cnt = AtIdSupl.ItemCount;
6359 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6360 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6364 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6365 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6375 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6376 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6377 .FocusedOn(FocusedControl.ListTab)
6378 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6380 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6381 .FocusedOn(FocusedControl.ListTab)
6382 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6384 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6385 .FocusedOn(FocusedControl.ListTab)
6386 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6388 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6389 .FocusedOn(FocusedControl.ListTab)
6390 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6392 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6393 .FocusedOn(FocusedControl.ListTab)
6394 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6396 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6397 .FocusedOn(FocusedControl.ListTab)
6398 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6400 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6401 .FocusedOn(FocusedControl.ListTab)
6402 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6404 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6405 .FocusedOn(FocusedControl.ListTab)
6406 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6408 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6409 .FocusedOn(FocusedControl.ListTab)
6410 .Do(() => this.SetSortLastColumn()),
6412 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6413 .Do(() => this.FavoritesRetweetOfficial()),
6415 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6416 .Do(() => this.FavoritesRetweetUnofficial()),
6418 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6419 .Do(() => this.OpenUserAppointUrl()),
6421 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6422 .FocusedOn(FocusedControl.PostBrowser)
6423 .Do(() => this.doReTweetUnofficial()),
6425 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6426 .OnlyWhen(() => this.ExistCurrentPost)
6427 .Do(() => this.tweetDetailsView.DoTranslation()),
6429 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6430 .Do(() => this.doReTweetUnofficial()),
6432 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6433 .Do(() => this.CopyUserId()),
6435 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6436 .Do(() => this.tweetThumbnail1.ScrollUp()),
6438 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6439 .Do(() => this.tweetThumbnail1.ScrollDown()),
6441 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6442 .FocusedOn(FocusedControl.ListTab)
6443 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6444 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6448 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6450 // Task を返す非同期処理があれば asyncTask に代入する
6453 // ShortcutCommand に対応しているコマンドはここで処理される
6454 foreach (var command in this.shortcutCommands)
6456 if (command.IsMatch(keyData, focusedOn))
6458 asyncTask = command.RunCommand();
6459 return command.PreventDefault;
6466 private void GoNextTab(bool forward)
6468 int idx = ListTab.SelectedIndex;
6472 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6477 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6479 ListTab.SelectedIndex = idx;
6482 private void CopyStot()
6485 StringBuilder sb = new StringBuilder();
6486 bool IsProtected = false;
6488 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6489 foreach (int idx in _curList.SelectedIndices)
6491 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6492 if (post.IsDeleted) continue;
6495 if (post.RetweetedId != null)
6496 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6498 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6502 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6507 MessageBox.Show(Properties.Resources.CopyStotText1);
6511 clstr = sb.ToString();
6514 Clipboard.SetDataObject(clstr, false, 5, 100);
6516 catch (Exception ex)
6518 MessageBox.Show(ex.Message);
6523 private void CopyIdUri()
6525 if (this._curTab == null)
6528 var tab = this._statuses.GetTabByName(this._curTab.Text);
6529 if (tab == null || tab is DirectMessagesTabModel)
6532 var copyUrls = new List<string>();
6533 foreach (int idx in _curList.SelectedIndices)
6535 var post = tab[idx];
6536 copyUrls.Add(MyCommon.GetStatusUrl(post));
6539 if (copyUrls.Count == 0)
6544 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6546 catch (ExternalException ex)
6548 MessageBox.Show(ex.Message);
6552 private void GoFav(bool forward)
6554 if (_curList.VirtualListSize == 0) return;
6561 if (_curList.SelectedIndices.Count == 0)
6567 fIdx = _curList.SelectedIndices[0] + 1;
6568 if (fIdx > _curList.VirtualListSize - 1) return;
6570 toIdx = _curList.VirtualListSize;
6575 if (_curList.SelectedIndices.Count == 0)
6577 fIdx = _curList.VirtualListSize - 1;
6581 fIdx = _curList.SelectedIndices[0] - 1;
6582 if (fIdx < 0) return;
6588 for (int idx = fIdx; idx != toIdx; idx += stp)
6590 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6592 SelectListItem(_curList, idx);
6593 _curList.EnsureVisible(idx);
6599 private void GoSamePostToAnotherTab(bool left)
6601 if (this._curList.SelectedIndices.Count == 0)
6604 var tab = this._statuses.Tabs[this._curTab.Text];
6606 // Directタブは対象外(見つかるはずがない)
6607 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6610 var selectedIndex = this._curList.SelectedIndices[0];
6611 var selectedStatusId = tab.GetStatusIdAt(selectedIndex);
6613 int fIdx, toIdx, stp;
6618 if (ListTab.SelectedIndex == 0)
6624 fIdx = ListTab.SelectedIndex - 1;
6632 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6638 fIdx = ListTab.SelectedIndex + 1;
6640 toIdx = ListTab.TabCount;
6644 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6646 var targetTab = this._statuses.Tabs[this.ListTab.TabPages[tabidx].Text];
6649 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6652 var foundIndex = targetTab.IndexOf(selectedStatusId);
6653 if (foundIndex != -1)
6655 ListTab.SelectedIndex = tabidx;
6656 SelectListItem(_curList, foundIndex);
6657 _curList.EnsureVisible(foundIndex);
6663 private void GoPost(bool forward)
6665 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6668 var tab = this._statuses.Tabs[this._curTab.Text];
6669 var selectedIndex = this._curList.SelectedIndices[0];
6671 int fIdx, toIdx, stp;
6675 fIdx = selectedIndex + 1;
6676 if (fIdx > tab.AllCount - 1) return;
6677 toIdx = tab.AllCount;
6682 fIdx = selectedIndex - 1;
6683 if (fIdx < 0) return;
6689 if (_curPost.RetweetedId == null)
6691 name = _curPost.ScreenName;
6695 name = _curPost.RetweetedBy;
6697 for (int idx = fIdx; idx != toIdx; idx += stp)
6699 var post = tab[idx];
6700 if (post.RetweetedId == null)
6702 if (post.ScreenName == name)
6704 SelectListItem(_curList, idx);
6705 _curList.EnsureVisible(idx);
6711 if (post.RetweetedBy == name)
6713 SelectListItem(_curList, idx);
6714 _curList.EnsureVisible(idx);
6721 private void GoRelPost(bool forward)
6723 if (this._curList.SelectedIndices.Count == 0)
6726 var tab = this._statuses.Tabs[this._curTab.Text];
6727 var selectedIndex = this._curList.SelectedIndices[0];
6729 int fIdx, toIdx, stp;
6733 fIdx = selectedIndex + 1;
6734 if (fIdx > tab.AllCount - 1) return;
6735 toIdx = tab.AllCount;
6740 fIdx = selectedIndex - 1;
6741 if (fIdx < 0) return;
6748 if (_curPost == null) return;
6749 _anchorPost = _curPost;
6754 if (_anchorPost == null) return;
6757 for (int idx = fIdx; idx != toIdx; idx += stp)
6759 var post = tab[idx];
6760 if (post.ScreenName == _anchorPost.ScreenName ||
6761 post.RetweetedBy == _anchorPost.ScreenName ||
6762 post.ScreenName == _anchorPost.RetweetedBy ||
6763 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6764 _anchorPost.ReplyToList.Any(x => x.Item1 == post.UserId) ||
6765 _anchorPost.ReplyToList.Any(x => x.Item1 == post.RetweetedByUserId) ||
6766 post.ReplyToList.Any(x => x.Item1 == _anchorPost.UserId) ||
6767 post.ReplyToList.Any(x => x.Item1 == _anchorPost.RetweetedByUserId))
6769 SelectListItem(_curList, idx);
6770 _curList.EnsureVisible(idx);
6776 private void GoAnchor()
6778 if (_anchorPost == null) return;
6779 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6780 if (idx == -1) return;
6782 SelectListItem(_curList, idx);
6783 _curList.EnsureVisible(idx);
6786 private void GoTopEnd(bool GoTop)
6788 if (_curList.VirtualListSize == 0)
6796 _item = _curList.GetItemAt(0, 25);
6804 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6806 idx = _curList.VirtualListSize - 1;
6810 SelectListItem(_curList, idx);
6813 private void GoMiddle()
6815 if (_curList.VirtualListSize == 0)
6823 _item = _curList.GetItemAt(0, 0);
6833 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6836 idx2 = _curList.VirtualListSize - 1;
6842 idx3 = (idx1 + idx2) / 2;
6844 SelectListItem(_curList, idx3);
6847 private void GoLast()
6849 if (_curList.VirtualListSize == 0) return;
6851 if (_statuses.SortOrder == SortOrder.Ascending)
6853 SelectListItem(_curList, _curList.VirtualListSize - 1);
6854 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6858 SelectListItem(_curList, 0);
6859 _curList.EnsureVisible(0);
6863 private void MoveTop()
6865 if (_curList.SelectedIndices.Count == 0) return;
6866 int idx = _curList.SelectedIndices[0];
6867 if (_statuses.SortOrder == SortOrder.Ascending)
6869 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6873 _curList.EnsureVisible(0);
6875 _curList.EnsureVisible(idx);
6878 private async Task GoInReplyToPostTree()
6880 if (_curPost == null) return;
6882 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6884 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
6888 var post = await tw.GetStatusApi(false, _curPost.StatusId);
6890 _curPost.InReplyToStatusId = post.InReplyToStatusId;
6891 _curPost.InReplyToUser = post.InReplyToUser;
6892 _curPost.IsReply = post.IsReply;
6893 this.PurgeListViewItemCache();
6894 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
6896 catch (WebApiException ex)
6898 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6902 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
6904 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
6906 replyChains = new Stack<ReplyChain>();
6908 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
6911 string inReplyToTabName;
6912 long inReplyToId = _curPost.InReplyToStatusId.Value;
6913 string inReplyToUser = _curPost.InReplyToUser;
6914 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6916 var inReplyToPosts = from tab in _statuses.Tabs.Values
6917 orderby tab != curTabClass
6918 from post in tab.Posts.Values
6919 where post.StatusId == inReplyToId
6920 let index = tab.IndexOf(post.StatusId)
6922 select new {Tab = tab, Index = index};
6924 var inReplyPost = inReplyToPosts.FirstOrDefault();
6925 if (inReplyPost == null)
6929 await Task.Run(async () =>
6931 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
6932 .ConfigureAwait(false);
6935 _statuses.AddPost(post);
6936 _statuses.DistributePosts();
6939 catch (WebApiException ex)
6941 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6942 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6946 this.RefreshTimeline();
6948 inReplyPost = inReplyToPosts.FirstOrDefault();
6949 if (inReplyPost == null)
6951 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6955 inReplyToTabName = inReplyPost.Tab.TabName;
6956 inReplyToIndex = inReplyPost.Index;
6958 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
6959 DetailsListView listView = (DetailsListView)tabPage.Tag;
6961 if (_curTab != tabPage)
6963 this.ListTab.SelectTab(tabPage);
6966 this.SelectListItem(listView, inReplyToIndex);
6967 listView.EnsureVisible(inReplyToIndex);
6970 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6972 if (_curPost == null) return;
6974 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6975 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6979 if (_curPost.InReplyToStatusId != null)
6981 var posts = from t in _statuses.Tabs
6982 from p in t.Value.Posts
6983 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
6984 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6986 orderby isForward ? indexOf : indexOf * -1
6987 orderby t.Value != curTabClass
6988 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
6991 var postList = posts.ToList();
6992 for (int i = postList.Count - 1; i >= 0; i--)
6995 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
6997 postList.RemoveAt(index);
7000 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7001 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7002 if (post == null) post = postList.First();
7003 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7004 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7005 SelectListItem(listView, post.Index);
7006 listView.EnsureVisible(post.Index);
7008 catch (InvalidOperationException)
7016 if (replyChains == null || replyChains.Count < 1)
7018 var posts = from t in _statuses.Tabs
7019 from p in t.Value.Posts
7020 where p.Value.InReplyToStatusId == _curPost.StatusId
7021 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7024 orderby t.Value != curTabClass
7025 select new {Tab = t.Value, Index = indexOf};
7028 var post = posts.First();
7029 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7030 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7031 SelectListItem(listView, post.Index);
7032 listView.EnsureVisible(post.Index);
7034 catch (InvalidOperationException)
7041 ReplyChain chainHead = replyChains.Pop();
7042 if (chainHead.InReplyToId == _curPost.StatusId)
7044 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7053 ListTab.SelectTab(chainHead.OriginalTab);
7059 SelectListItem(_curList, idx);
7060 _curList.EnsureVisible(idx);
7066 this.GoBackInReplyToPostTree(parallel);
7072 private void GoBackSelectPostChain()
7074 if (this.selectPostChains.Count > 1)
7083 this.selectPostChains.Pop();
7084 var (tabPage, post) = this.selectPostChains.Peek();
7086 if (!this.ListTab.TabPages.Contains(tabPage)) continue; //該当タブが存在しないので無視
7090 idx = this._statuses.Tabs[tabPage.Text].IndexOf(post.StatusId);
7091 if (idx == -1) continue; //該当ポストが存在しないので無視
7096 this.selectPostChains.Pop();
7098 catch (InvalidOperationException)
7104 while (this.selectPostChains.Count > 1);
7109 //履歴が残り1つであればクリアしておく
7110 if (this.selectPostChains.Count == 1)
7111 this.selectPostChains.Clear();
7115 DetailsListView lst = (DetailsListView)tp.Tag;
7116 this.ListTab.SelectedTab = tp;
7119 SelectListItem(lst, idx);
7120 lst.EnsureVisible(idx);
7126 private void PushSelectPostChain()
7128 int count = this.selectPostChains.Count;
7131 var (tabPage, post) = this.selectPostChains.Peek();
7132 if (tabPage == this._curTab)
7134 if (post == this._curPost) return; //最新の履歴と同一
7135 if (post == null) this.selectPostChains.Pop(); //置き換えるため削除
7138 if (count >= 2500) TrimPostChain();
7139 this.selectPostChains.Push((this._curTab, this._curPost));
7142 private void TrimPostChain()
7144 if (this.selectPostChains.Count <= 2000) return;
7145 var p = new Stack<ValueTuple<TabPage, PostClass>>(2000);
7146 for (int i = 0; i < 2000; i++)
7148 p.Push(this.selectPostChains.Pop());
7150 this.selectPostChains.Clear();
7151 for (int i = 0; i < 2000; i++)
7153 this.selectPostChains.Push(p.Pop());
7157 private bool GoStatus(long statusId)
7159 if (statusId == 0) return false;
7160 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7162 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7164 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7165 ListTab.SelectedIndex = tabidx;
7166 SelectListItem(_curList, idx);
7167 _curList.EnsureVisible(idx);
7174 private bool GoDirectMessage(long statusId)
7176 if (statusId == 0) return false;
7177 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7179 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7181 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7182 ListTab.SelectedIndex = tabidx;
7183 SelectListItem(_curList, idx);
7184 _curList.EnsureVisible(idx);
7191 private void MyList_MouseClick(object sender, MouseEventArgs e)
7193 _anchorFlag = false;
7196 private void StatusText_Enter(object sender, EventArgs e)
7198 // フォーカスの戻り先を StatusText に設定
7199 this.Tag = StatusText;
7200 StatusText.BackColor = _clInputBackcolor;
7203 public Color InputBackColor
7205 get => _clInputBackcolor;
7206 set => _clInputBackcolor = value;
7209 private void StatusText_Leave(object sender, EventArgs e)
7211 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7212 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7213 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7216 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7218 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
7221 e.SuppressKeyPress = true;
7224 this.StatusText_TextChanged(null, null);
7226 if (asyncTask != null)
7230 private void SaveConfigsAll(bool ifModified)
7234 SaveConfigsCommon();
7241 if (ModifySettingCommon) SaveConfigsCommon();
7242 if (ModifySettingLocal) SaveConfigsLocal();
7243 if (ModifySettingAtId) SaveConfigsAtId();
7247 private void SaveConfigsAtId()
7249 if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7251 ModifySettingAtId = false;
7252 SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7253 SettingManager.SaveAtIdList();
7256 private void SaveConfigsCommon()
7258 if (_ignoreConfigSave) return;
7260 ModifySettingCommon = false;
7263 SettingManager.Common.UserName = tw.Username;
7264 SettingManager.Common.UserId = tw.UserId;
7265 SettingManager.Common.Token = tw.AccessToken;
7266 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7267 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7268 switch (_statuses.SortMode)
7270 case ComparerMode.Nickname: //ニックネーム
7271 SettingManager.Common.SortColumn = 1;
7273 case ComparerMode.Data: //本文
7274 SettingManager.Common.SortColumn = 2;
7276 case ComparerMode.Id: //時刻=発言Id
7277 SettingManager.Common.SortColumn = 3;
7279 case ComparerMode.Name: //名前
7280 SettingManager.Common.SortColumn = 4;
7282 case ComparerMode.Source: //Source
7283 SettingManager.Common.SortColumn = 7;
7287 SettingManager.Common.HashTags = HashMgr.HashHistories;
7288 if (HashMgr.IsPermanent)
7290 SettingManager.Common.HashSelected = HashMgr.UseHash;
7294 SettingManager.Common.HashSelected = "";
7296 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7297 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7298 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7299 SettingManager.Common.TrackWord = tw.TrackWord;
7300 SettingManager.Common.AllAtReply = tw.AllAtReply;
7301 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7302 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7304 SettingManager.SaveCommon();
7308 private void SaveConfigsLocal()
7310 if (_ignoreConfigSave) return;
7313 ModifySettingLocal = false;
7314 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7315 SettingManager.Local.FormSize = _mySize;
7316 SettingManager.Local.FormLocation = _myLoc;
7317 SettingManager.Local.SplitterDistance = _mySpDis;
7318 SettingManager.Local.PreviewDistance = _mySpDis3;
7319 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7320 SettingManager.Local.StatusTextHeight = _mySpDis2;
7322 SettingManager.Local.FontUnread = _fntUnread;
7323 SettingManager.Local.ColorUnread = _clUnread;
7324 SettingManager.Local.FontRead = _fntReaded;
7325 SettingManager.Local.ColorRead = _clReaded;
7326 SettingManager.Local.FontDetail = _fntDetail;
7327 SettingManager.Local.ColorDetail = _clDetail;
7328 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7329 SettingManager.Local.ColorDetailLink = _clDetailLink;
7330 SettingManager.Local.ColorFav = _clFav;
7331 SettingManager.Local.ColorOWL = _clOWL;
7332 SettingManager.Local.ColorRetweet = _clRetweet;
7333 SettingManager.Local.ColorSelf = _clSelf;
7334 SettingManager.Local.ColorAtSelf = _clAtSelf;
7335 SettingManager.Local.ColorTarget = _clTarget;
7336 SettingManager.Local.ColorAtTarget = _clAtTarget;
7337 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7338 SettingManager.Local.ColorAtTo = _clAtTo;
7339 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7340 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7341 SettingManager.Local.ColorInputFont = _clInputFont;
7342 SettingManager.Local.FontInputFont = _fntInputFont;
7344 if (_ignoreConfigSave) return;
7345 SettingManager.SaveLocal();
7349 private void SaveConfigsTabs()
7351 var tabSettingList = new List<SettingTabs.SettingTabItem>();
7353 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7354 .Select(x => this._statuses.Tabs[x.Text])
7355 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7357 foreach (var tab in tabs)
7359 if (!tab.IsPermanentTabType)
7362 var tabSetting = new SettingTabs.SettingTabItem
7364 TabName = tab.TabName,
7365 TabType = tab.TabType,
7366 UnreadManage = tab.UnreadManage,
7367 Protected = tab.Protected,
7368 Notify = tab.Notify,
7369 SoundFile = tab.SoundFile,
7374 case FilterTabModel filterTab:
7375 tabSetting.FilterArray = filterTab.FilterArray;
7377 case UserTimelineTabModel userTab:
7378 tabSetting.User = userTab.ScreenName;
7380 case PublicSearchTabModel searchTab:
7381 tabSetting.SearchWords = searchTab.SearchWords;
7382 tabSetting.SearchLang = searchTab.SearchLang;
7384 case ListTimelineTabModel listTab:
7385 tabSetting.ListInfo = listTab.ListInfo;
7389 tabSettingList.Add(tabSetting);
7392 SettingManager.Tabs.Tabs = tabSettingList;
7393 SettingManager.SaveTabs();
7396 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7398 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
7399 if (ret != DialogResult.OK)
7402 var match = Twitter.StatusUrlRegex.Match(inputText);
7405 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7406 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7412 var statusId = long.Parse(match.Groups["StatusId"].Value);
7413 await this.OpenRelatedTab(statusId);
7415 catch (TabException ex)
7417 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7421 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7423 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7424 Properties.Resources.SaveLogMenuItem_ClickText2,
7425 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7426 if (rslt == DialogResult.Cancel) return;
7428 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7429 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7430 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7431 SaveFileDialog1.FilterIndex = 0;
7432 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7433 SaveFileDialog1.RestoreDirectory = true;
7435 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7437 if (!SaveFileDialog1.ValidateNames) return;
7438 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7440 if (rslt == DialogResult.Yes)
7443 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7445 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7446 string protect = "";
7447 if (post.IsProtect) protect = "Protect";
7448 sw.WriteLine(post.Nickname + "\t" +
7449 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7450 post.CreatedAt + "\t" +
7451 post.ScreenName + "\t" +
7452 post.StatusId + "\t" +
7453 post.ImageUrl + "\t" +
7454 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7460 foreach (int idx in _curList.SelectedIndices)
7462 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7463 string protect = "";
7464 if (post.IsProtect) protect = "Protect";
7465 sw.WriteLine(post.Nickname + "\t" +
7466 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7467 post.CreatedAt + "\t" +
7468 post.ScreenName + "\t" +
7469 post.StatusId + "\t" +
7470 post.ImageUrl + "\t" +
7471 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7477 this.TopMost = SettingManager.Common.AlwaysTop;
7480 public bool TabRename(string origTabName, out string newTabName)
7484 using (InputTabName inputName = new InputTabName())
7486 inputName.TabName = origTabName;
7487 inputName.ShowDialog();
7488 if (inputName.DialogResult == DialogResult.Cancel) return false;
7489 newTabName = inputName.TabName;
7491 this.TopMost = SettingManager.Common.AlwaysTop;
7492 if (!string.IsNullOrEmpty(newTabName))
7495 for (int i = 0; i < ListTab.TabCount; i++)
7497 if (ListTab.TabPages[i].Text == newTabName)
7499 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7500 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7505 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
7506 .FirstOrDefault(x => x.Text == origTabName);
7509 if (tabPage != null)
7510 tabPage.Text = newTabName;
7512 _statuses.RenameTab(origTabName, newTabName);
7514 SaveConfigsCommon();
7516 _rclickTabName = newTabName;
7525 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7527 if (e.Button == MouseButtons.Middle)
7529 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7531 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7533 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7534 this.SaveConfigsTabs();
7541 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7543 TabRename(this.ListTab.SelectedTab.Text, out var _);
7546 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7548 if (SettingManager.Common.TabMouseLock) return;
7549 if (e.Button == MouseButtons.Left)
7551 for (int i = 0; i < ListTab.TabPages.Count; i++)
7553 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7556 _tabMouseDownPoint = e.Location;
7567 private void ListTab_DragEnter(object sender, DragEventArgs e)
7569 if (e.Data.GetDataPresent(typeof(TabPage)))
7570 e.Effect = DragDropEffects.Move;
7572 e.Effect = DragDropEffects.None;
7575 private void ListTab_DragDrop(object sender, DragEventArgs e)
7577 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7582 Point cpos = new Point(e.X, e.Y);
7583 Point spos = ListTab.PointToClient(cpos);
7585 for (i = 0; i < ListTab.TabPages.Count; i++)
7587 Rectangle rect = ListTab.GetTabRect(i);
7588 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7589 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7591 tn = ListTab.TabPages[i].Text;
7592 if (spos.X <= (rect.Left + rect.Right) / 2)
7601 //タブのないところにドロップ->最後尾へ移動
7602 if (string.IsNullOrEmpty(tn))
7604 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7606 i = ListTab.TabPages.Count - 1;
7609 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7610 if (tp.Text == tn) return;
7612 ReOrderTab(tp.Text, tn, bef);
7615 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7617 var baseIndex = this.GetTabPageIndex(baseTabText);
7618 if (baseIndex == -1)
7621 var targetIndex = this.GetTabPageIndex(targetTabText);
7622 if (targetIndex == -1)
7625 using (ControlTransaction.Layout(this.ListTab))
7627 var mTp = this.ListTab.TabPages[targetIndex];
7628 this.ListTab.TabPages.Remove(mTp);
7630 if (targetIndex < baseIndex)
7633 if (isBeforeBaseTab)
7634 ListTab.TabPages.Insert(baseIndex, mTp);
7636 ListTab.TabPages.Insert(baseIndex + 1, mTp);
7642 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7644 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7645 //isReply:true=@,false=DM
7646 if (!StatusText.Enabled) return;
7647 if (_curList == null) return;
7648 if (_curTab == null) return;
7649 if (!this.ExistCurrentPost) return;
7651 // 複数あてリプライはReplyではなく通常ポスト
7652 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7653 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7654 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7656 if (_curList.SelectedIndices.Count > 0)
7659 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7662 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7665 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7666 StatusText.SelectionStart = StatusText.Text.Length;
7668 this.inReplyTo = null;
7671 if (string.IsNullOrEmpty(StatusText.Text))
7675 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7676 StatusText.Text = "@" + _curPost.ScreenName + " ";
7678 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7679 var inReplyToScreenName = this._curPost.ScreenName;
7680 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7688 //1件選んでEnter or DoubleClick
7689 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7691 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7694 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7695 var inReplyToScreenName = this._curPost.ScreenName;
7696 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7700 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7703 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7706 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7707 this.inReplyTo = null;
7712 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7713 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7714 var inReplyToScreenName = this._curPost.ScreenName;
7715 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7722 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7723 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7724 this.inReplyTo = null;
7729 //1件選んでCtrl-Rの場合(返信先操作せず)
7730 int sidx = StatusText.SelectionStart;
7731 string id = "@" + _curPost.ScreenName + " ";
7734 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7739 StatusText.Text = StatusText.Text.Insert(sidx, id);
7741 //if (StatusText.Text.StartsWith("@"))
7744 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7745 // sidx += 5 + _curPost.ScreenName.Length;
7750 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7751 // sidx += 3 + _curPost.ScreenName.Length;
7753 StatusText.SelectionStart = sidx;
7756 //_reply_to_name = null;
7764 if (!isAuto && !isReply) return;
7766 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7770 //Enter or DoubleClick
7772 string sTxt = StatusText.Text;
7773 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7776 this.inReplyTo = null;
7778 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7780 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7781 if (!sTxt.Contains("@" + post.ScreenName + " "))
7783 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7784 //sTxt = "@" + post.ScreenName + " " + sTxt;
7787 StatusText.Text = sTxt;
7792 if (_curList.SelectedIndices.Count > 1)
7797 int sidx = StatusText.SelectionStart;
7798 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7800 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7801 if (!ids.Contains("@" + post.ScreenName + " ") &&
7802 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7804 ids += "@" + post.ScreenName + " ";
7808 foreach (string nm in post.ReplyToList.Select(x => x.Item2))
7810 if (!ids.Contains("@" + nm + " ") &&
7811 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7813 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7815 ids += "@" + m.Result("${id}") + " ";
7817 ids += "@" + nm + " ";
7822 if (ids.Length == 0) return;
7823 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7825 StatusText.Text = ". " + StatusText.Text;
7827 this.inReplyTo = null;
7831 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7836 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7838 //if (StatusText.Text.StartsWith("@"))
7840 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7841 // sidx += 2 + ids.Length;
7845 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7846 // sidx += 1 + ids.Length;
7848 StatusText.SelectionStart = sidx;
7854 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7857 int sidx = StatusText.SelectionStart;
7858 PostClass post = _curPost;
7859 if (!ids.Contains("@" + post.ScreenName + " ") &&
7860 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7862 ids += "@" + post.ScreenName + " ";
7864 foreach (string nm in post.ReplyToList.Select(x => x.Item2))
7866 if (!ids.Contains("@" + nm + " ") &&
7867 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7869 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7871 ids += "@" + m.Result("${id}") + " ";
7873 ids += "@" + nm + " ";
7876 if (!string.IsNullOrEmpty(post.RetweetedBy))
7878 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
7879 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7881 ids += "@" + post.RetweetedBy + " ";
7884 if (ids.Length == 0) return;
7885 if (string.IsNullOrEmpty(StatusText.Text))
7888 StatusText.Text = ids;
7889 StatusText.SelectionStart = ids.Length;
7892 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7893 var inReplyToScreenName = this._curPost.ScreenName;
7894 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7900 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7905 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7907 StatusText.SelectionStart = sidx;
7913 StatusText.SelectionStart = StatusText.Text.Length;
7918 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7923 private static int iconCnt = 0;
7924 private static int blinkCnt = 0;
7925 private static bool blink = false;
7926 private static bool idle = false;
7928 private async Task RefreshTasktrayIcon()
7931 await this.Colorize();
7933 if (!TimerRefreshIcon.Enabled) return;
7934 //Static usCheckCnt As int = 0
7936 //Static iconDlListTopItem As ListViewItem = null
7938 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7939 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7941 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7943 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7949 //if (usCheckCnt > 300) //1min
7952 // if (!this.IsReceivedUserStream)
7954 // TraceOut("ReconnectUserStream");
7955 // tw.ReconnectUserStream();
7959 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7961 if (iconCnt >= this.NIconRefresh.Length)
7969 SaveConfigsAll(true);
7974 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7976 _myStatusError = false;
7980 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
7981 if (SettingManager.Common.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
7983 if (blinkCnt > 0) return;
7985 if (blink || SettingManager.Common.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
7987 NotifyIcon1.Icon = ReplyIcon;
7991 NotifyIcon1.Icon = ReplyIconBlink;
7999 //優先度:エラー→オフライン→アイドル
8003 NotifyIcon1.Icon = NIconAtRed;
8006 if (_myStatusOnline)
8008 NotifyIcon1.Icon = NIconAt;
8012 NotifyIcon1.Icon = NIconAtSmoke;
8016 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8019 await this.RefreshTasktrayIcon();
8022 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8024 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8025 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8027 if (ListTab != null && ListTab.SelectedTab != null)
8028 _rclickTabName = ListTab.SelectedTab.Text;
8033 if (_statuses == null) return;
8034 if (_statuses.Tabs == null) return;
8036 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out var tb))
8039 NotifyDispMenuItem.Checked = tb.Notify;
8040 this.NotifyTbMenuItem.Checked = tb.Notify;
8042 soundfileListup = true;
8043 SoundFileComboBox.Items.Clear();
8044 this.SoundFileTbComboBox.Items.Clear();
8045 SoundFileComboBox.Items.Add("");
8046 this.SoundFileTbComboBox.Items.Add("");
8047 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8048 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8050 oDir = oDir.GetDirectories("Sounds")[0];
8052 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8054 SoundFileComboBox.Items.Add(oFile.Name);
8055 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8057 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8058 if (idx == -1) idx = 0;
8059 SoundFileComboBox.SelectedIndex = idx;
8060 this.SoundFileTbComboBox.SelectedIndex = idx;
8061 soundfileListup = false;
8062 UreadManageMenuItem.Checked = tb.UnreadManage;
8063 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8065 TabMenuControl(_rclickTabName);
8068 private void TabMenuControl(string tabName)
8070 var tabInfo = _statuses.GetTabByName(tabName);
8072 this.FilterEditMenuItem.Enabled = true;
8073 this.EditRuleTbMenuItem.Enabled = true;
8075 if (tabInfo.IsDefaultTabType)
8077 this.ProtectTabMenuItem.Enabled = false;
8078 this.ProtectTbMenuItem.Enabled = false;
8082 this.ProtectTabMenuItem.Enabled = true;
8083 this.ProtectTbMenuItem.Enabled = true;
8086 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8088 this.ProtectTabMenuItem.Checked = true;
8089 this.ProtectTbMenuItem.Checked = true;
8090 this.DeleteTabMenuItem.Enabled = false;
8091 this.DeleteTbMenuItem.Enabled = false;
8095 this.ProtectTabMenuItem.Checked = false;
8096 this.ProtectTbMenuItem.Checked = false;
8097 this.DeleteTabMenuItem.Enabled = true;
8098 this.DeleteTbMenuItem.Enabled = true;
8102 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8104 var checkState = ((ToolStripMenuItem)sender).Checked;
8107 this.ProtectTbMenuItem.Checked = checkState;
8108 this.ProtectTabMenuItem.Checked = checkState;
8111 this.DeleteTabMenuItem.Enabled = !checkState;
8112 this.DeleteTbMenuItem.Enabled = !checkState;
8114 if (string.IsNullOrEmpty(_rclickTabName)) return;
8115 _statuses.Tabs[_rclickTabName].Protected = checkState;
8120 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8122 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8123 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8125 if (string.IsNullOrEmpty(_rclickTabName)) return;
8126 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8131 public void ChangeTabUnreadManage(string tabName, bool isManage)
8133 var idx = this.GetTabPageIndex(tabName);
8137 _statuses.Tabs[tabName].UnreadManage = isManage;
8138 if (SettingManager.Common.TabIconDisp)
8140 if (_statuses.Tabs[tabName].UnreadCount > 0)
8141 ListTab.TabPages[idx].ImageIndex = 0;
8143 ListTab.TabPages[idx].ImageIndex = -1;
8146 if (_curTab.Text == tabName)
8148 this.PurgeListViewItemCache();
8152 SetMainWindowTitle();
8153 SetStatusLabelUrl();
8154 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8157 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8159 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8160 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8162 if (string.IsNullOrEmpty(_rclickTabName)) return;
8164 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8169 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8171 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8173 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8178 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8180 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8182 RemoveSpecifiedTab(_rclickTabName, true);
8186 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8188 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8190 using (var fltDialog = new FilterDialog())
8192 fltDialog.Owner = this;
8193 fltDialog.SetCurrent(_rclickTabName);
8194 fltDialog.ShowDialog(this);
8196 this.TopMost = SettingManager.Common.AlwaysTop;
8198 this.ApplyPostFilters();
8202 private void AddTabMenuItem_Click(object sender, EventArgs e)
8204 string tabName = null;
8205 MyCommon.TabUsageType tabUsage;
8206 using (InputTabName inputName = new InputTabName())
8208 inputName.TabName = _statuses.MakeTabName("MyTab");
8209 inputName.IsShowUsage = true;
8210 inputName.ShowDialog();
8211 if (inputName.DialogResult == DialogResult.Cancel) return;
8212 tabName = inputName.TabName;
8213 tabUsage = inputName.Usage;
8215 this.TopMost = SettingManager.Common.AlwaysTop;
8216 if (!string.IsNullOrEmpty(tabName))
8219 ListElement list = null;
8220 if (tabUsage == MyCommon.TabUsageType.Lists)
8222 using (ListAvailable listAvail = new ListAvailable())
8224 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8225 if (listAvail.SelectedList == null) return;
8226 list = listAvail.SelectedList;
8233 case MyCommon.TabUsageType.UserDefined:
8234 tab = new FilterTabModel(tabName);
8236 case MyCommon.TabUsageType.PublicSearch:
8237 tab = new PublicSearchTabModel(tabName);
8239 case MyCommon.TabUsageType.Lists:
8240 tab = new ListTimelineTabModel(tabName, list);
8246 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8248 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8249 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8255 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8257 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8258 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8260 if (tabUsage == MyCommon.TabUsageType.Lists)
8262 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8263 var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8264 this.GetListTimelineAsync(listTab);
8270 private void TabMenuItem_Click(object sender, EventArgs e)
8272 using (var fltDialog = new FilterDialog())
8274 fltDialog.Owner = this;
8277 foreach (int idx in _curList.SelectedIndices)
8280 if (!SelectTab(out var tabName)) return;
8282 fltDialog.SetCurrent(tabName);
8283 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8285 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8289 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8291 fltDialog.ShowDialog(this);
8292 this.TopMost = SettingManager.Common.AlwaysTop;
8296 this.ApplyPostFilters();
8298 if (this.ListTab.SelectedTab != null &&
8299 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8301 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8305 protected override bool ProcessDialogKey(Keys keyData)
8307 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8308 if ((keyData & Keys.KeyCode) == Keys.Enter)
8310 if (StatusText.Focused)
8312 bool _NewLine = false;
8315 if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8317 if (StatusText.Multiline)
8319 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8321 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8325 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8329 else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8331 if (StatusText.Multiline)
8333 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8335 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8339 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8345 if (StatusText.Multiline)
8347 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8349 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8350 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8354 if (((keyData & Keys.Shift) == Keys.Shift) ||
8355 (((keyData & Keys.Control) != Keys.Control) &&
8356 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8362 int pos1 = StatusText.SelectionStart;
8363 if (StatusText.SelectionLength > 0)
8365 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8367 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8368 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8373 PostButton_Click(null, null);
8377 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8378 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8379 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8381 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8386 return base.ProcessDialogKey(keyData);
8389 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8391 MakeReplyOrDirectStatus(false, true, true);
8394 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8397 if (_curList.SelectedIndices.Count == 0) return;
8399 var tab = this._statuses.Tabs[this._curTab.Text];
8400 var screenNameArray = this._curList.SelectedIndices.Cast<int>()
8401 .Select(x => tab[x])
8402 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8405 this.AddFilterRuleByScreenName(screenNameArray);
8407 if (screenNameArray.Length != 0)
8409 List<string> atids = new List<string>();
8410 foreach (var screenName in screenNameArray)
8412 atids.Add("@" + screenName);
8414 int cnt = AtIdSupl.ItemCount;
8415 AtIdSupl.AddRangeItem(atids.ToArray());
8416 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8420 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8422 if (this._curList.SelectedIndices.Count == 0)
8425 var tab = this._statuses.Tabs[this._curTab.Text];
8426 var sourceArray = this._curList.SelectedIndices.Cast<int>()
8427 .Select(x => tab[x].Source).ToArray();
8429 this.AddFilterRuleBySource(sourceArray);
8432 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8435 if (!SelectTab(out var tabName)) return;
8437 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8441 if (tab.TabType != MyCommon.TabUsageType.Mute)
8443 this.MoveOrCopy(out mv, out mk);
8447 // ミュートタブでは常に MoveMatches を true にする
8452 foreach (var screenName in screenNameArray)
8454 tab.AddFilter(new PostFilterRule
8456 FilterName = screenName,
8457 UseNameField = true,
8461 FilterByUrl = false,
8465 this.ApplyPostFilters();
8469 public void AddFilterRuleBySource(params string[] sourceArray)
8471 // タブ選択ダイアログを表示(or追加)
8472 if (!this.SelectTab(out var tabName))
8475 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8479 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8481 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8482 this.MoveOrCopy(out mv, out mk);
8486 // ミュートタブでは常に MoveMatches を true にする
8491 // 振り分けルールに追加するSource
8492 foreach (var source in sourceArray)
8494 filterTab.AddFilter(new PostFilterRule
8496 FilterSource = source,
8500 FilterByUrl = false,
8504 this.ApplyPostFilters();
8505 this.SaveConfigsTabs();
8508 private bool SelectTab(out string tabName)
8515 using (var dialog = new TabsDialog(_statuses))
8517 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8519 var selectedTab = dialog.SelectedTab;
8520 tabName = selectedTab == null ? null : selectedTab.TabName;
8523 ListTab.SelectedTab.Focus();
8525 if (tabName == null)
8527 using (InputTabName inputName = new InputTabName())
8529 inputName.TabName = _statuses.MakeTabName("MyTab");
8530 inputName.ShowDialog();
8531 if (inputName.DialogResult == DialogResult.Cancel) return false;
8532 tabName = inputName.TabName;
8534 this.TopMost = SettingManager.Common.AlwaysTop;
8535 if (!string.IsNullOrEmpty(tabName))
8537 var tab = new FilterTabModel(tabName);
8538 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8540 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8541 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8559 private void MoveOrCopy(out bool move, out bool mark)
8563 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8564 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8572 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8573 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8583 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8588 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8593 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8595 if (StatusText.Focused)
8598 StatusText.SelectAll();
8602 // ListView上でのCtrl+A
8603 NativeMethods.SelectAllItems(this._curList);
8607 private void MoveMiddle()
8613 if (_curList.SelectedIndices.Count == 0) return;
8615 int idx = _curList.SelectedIndices[0];
8617 _item = _curList.GetItemAt(0, 25);
8623 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8625 idx2 = _curList.VirtualListSize - 1;
8629 idx -= Math.Abs(idx1 - idx2) / 2;
8630 if (idx < 0) idx = 0;
8632 _curList.EnsureVisible(_curList.VirtualListSize - 1);
8633 _curList.EnsureVisible(idx);
8636 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8638 var linkElements = this.tweetDetailsView.GetLinkElements();
8640 if (linkElements.Length > 0)
8642 UrlDialog.ClearUrl();
8644 string openUrlStr = "";
8646 if (linkElements.Length == 1)
8648 // ツイートに含まれる URL が 1 つのみの場合
8649 // => OpenURL ダイアログを表示せずにリンクを開く
8654 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8656 catch (ArgumentException)
8665 if (string.IsNullOrEmpty(urlStr)) return;
8666 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8668 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8669 await this.OpenUriAsync(new Uri(openUrlStr));
8673 // ツイートに含まれる URL が複数ある場合
8674 // => OpenURL を表示しユーザーが選択したリンクを開く
8676 foreach (var linkElm in linkElements)
8679 string linkText = "";
8683 urlStr = linkElm.GetAttribute("title");
8684 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8685 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8686 linkText = linkElm.InnerText;
8688 catch (ArgumentException)
8697 if (string.IsNullOrEmpty(urlStr)) continue;
8698 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8702 if (UrlDialog.ShowDialog() == DialogResult.OK)
8704 openUrlStr = UrlDialog.SelectedUrl;
8706 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8707 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8714 this.TopMost = SettingManager.Common.AlwaysTop;
8719 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8721 if (string.IsNullOrEmpty(_rclickTabName)) return;
8722 ClearTab(_rclickTabName, true);
8725 private void ClearTab(string tabName, bool showWarning)
8729 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8730 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8736 _statuses.ClearTabIds(tabName);
8737 if (ListTab.SelectedTab.Text == tabName)
8740 _anchorFlag = false;
8741 this.PurgeListViewItemCache();
8745 foreach (TabPage tb in ListTab.TabPages)
8747 if (tb.Text == tabName)
8749 ((DetailsListView)tb.Tag).VirtualListSize = 0;
8754 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8756 SetMainWindowTitle();
8757 SetStatusLabelUrl();
8760 private static long followers = 0;
8762 private void SetMainWindowTitle()
8765 StringBuilder ttl = new StringBuilder(256);
8768 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8769 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8770 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8771 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8773 foreach (var tab in _statuses.Tabs.Values)
8775 ur += tab.UnreadCount;
8780 if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8781 ttl.Append(Application.ProductName);
8783 switch (SettingManager.Common.DispLatestPost)
8785 case MyCommon.DispTitleEnum.Ver:
8786 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8788 case MyCommon.DispTitleEnum.Post:
8789 if (_history != null && _history.Count > 1)
8790 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8792 case MyCommon.DispTitleEnum.UnreadRepCount:
8793 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8795 case MyCommon.DispTitleEnum.UnreadAllCount:
8796 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8798 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8799 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8801 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8802 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8804 case MyCommon.DispTitleEnum.OwnStatus:
8805 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8806 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8812 this.Text = ttl.ToString();
8814 catch (AccessViolationException)
8816 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8820 private string GetStatusLabelText()
8823 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8824 if (_statuses == null) return "";
8825 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8826 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8827 if (tbRep == null || tbDm == null) return "";
8828 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8833 StringBuilder slbl = new StringBuilder(256);
8836 foreach (var tab in _statuses.Tabs.Values)
8838 ur += tab.UnreadCount;
8840 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
8842 tur = tab.UnreadCount;
8853 UnreadAtCounter = urat;
8855 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8857 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8858 if (SettingManager.Common.TimelinePeriod == 0)
8860 slbl.Append(Properties.Resources.SetStatusLabelText2);
8864 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8866 return slbl.ToString();
8869 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8873 if (this.InvokeRequired && !this.IsDisposed)
8875 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8879 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8880 SetApiStatusLabel(endpointName);
8883 catch (ObjectDisposedException)
8887 catch (InvalidOperationException)
8893 private void SetApiStatusLabel(string endpointName = null)
8895 if (_curTab == null)
8897 this.toolStripApiGauge.ApiEndpoint = null;
8901 var tabType = _statuses.Tabs[_curTab.Text].TabType;
8903 if (endpointName == null)
8908 case MyCommon.TabUsageType.Home:
8909 case MyCommon.TabUsageType.UserDefined:
8910 endpointName = "/statuses/home_timeline";
8913 case MyCommon.TabUsageType.Mentions:
8914 endpointName = "/statuses/mentions_timeline";
8917 case MyCommon.TabUsageType.Favorites:
8918 endpointName = "/favorites/list";
8921 case MyCommon.TabUsageType.DirectMessage:
8922 endpointName = "/direct_messages";
8925 case MyCommon.TabUsageType.UserTimeline:
8926 endpointName = "/statuses/user_timeline";
8929 case MyCommon.TabUsageType.Lists:
8930 endpointName = "/lists/statuses";
8933 case MyCommon.TabUsageType.PublicSearch:
8934 endpointName = "/search/tweets";
8937 case MyCommon.TabUsageType.Related:
8938 endpointName = "/statuses/show/:id";
8945 this.toolStripApiGauge.ApiEndpoint = endpointName;
8949 // 表示中のタブに関連する endpoint であれば更新
8952 switch (endpointName)
8954 case "/statuses/home_timeline":
8955 update = tabType == MyCommon.TabUsageType.Home ||
8956 tabType == MyCommon.TabUsageType.UserDefined;
8959 case "/statuses/mentions_timeline":
8960 update = tabType == MyCommon.TabUsageType.Mentions;
8963 case "/favorites/list":
8964 update = tabType == MyCommon.TabUsageType.Favorites;
8967 case "/direct_messages:":
8968 update = tabType == MyCommon.TabUsageType.DirectMessage;
8971 case "/statuses/user_timeline":
8972 update = tabType == MyCommon.TabUsageType.UserTimeline;
8975 case "/lists/statuses":
8976 update = tabType == MyCommon.TabUsageType.Lists;
8979 case "/search/tweets":
8980 update = tabType == MyCommon.TabUsageType.PublicSearch;
8983 case "/statuses/show/:id":
8984 update = tabType == MyCommon.TabUsageType.Related;
8993 this.toolStripApiGauge.ApiEndpoint = endpointName;
8999 private void SetStatusLabelUrl()
9001 StatusLabelUrl.Text = GetStatusLabelText();
9004 public void SetStatusLabel(string text)
9006 StatusLabel.Text = text;
9009 private void SetNotifyIconText()
9011 var ur = new StringBuilder(64);
9013 // タスクトレイアイコンのツールチップテキスト書き換え
9015 ur.Remove(0, ur.Length);
9016 if (SettingManager.Common.DispUsername)
9018 ur.Append(tw.Username);
9021 ur.Append(Application.ProductName);
9023 ur.Append("(Debug Build)");
9025 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9028 ur.Append(UnreadCounter);
9030 ur.Append(UnreadAtCounter);
9033 NotifyIcon1.Text = ur.ToString();
9036 internal void CheckReplyTo(string StatusText)
9040 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9042 foreach (Match hm in m)
9044 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9046 hstr += "#" + hm.Result("$3") + " ";
9047 HashSupl.AddItem("#" + hm.Result("$3"));
9050 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9052 hstr += HashMgr.UseHash;
9054 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9056 // 本当にリプライ先指定すべきかどうかの判定
9057 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9059 if (SettingManager.Common.UseAtIdSupplement)
9061 int bCnt = AtIdSupl.ItemCount;
9062 foreach (Match mid in m)
9064 AtIdSupl.AddItem(mid.Result("${id}"));
9066 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9069 // リプライ先ステータスIDの指定がない場合は指定しない
9070 if (this.inReplyTo == null)
9074 // 次の条件を満たす場合に in_reply_to_status_id 指定
9075 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9076 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9077 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9081 var inReplyToScreenName = this.inReplyTo.Item2;
9082 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9084 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9088 foreach (Match mid in m)
9090 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9095 this.inReplyTo = null;
9098 private void TweenMain_Resize(object sender, EventArgs e)
9100 if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
9102 this.Visible = false;
9104 if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
9106 // 現在の DPI と設定保存時の DPI との比を取得する
9107 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9109 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
9112 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
9113 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9114 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9116 this.SplitContainer1.SplitterDistance = splitterDistance;
9120 StatusText.Multiline = SettingManager.Local.StatusMultiline;
9121 if (StatusText.Multiline)
9123 var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
9124 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9125 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9127 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9129 StatusText.Height = statusTextHeight;
9133 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9135 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9139 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
9140 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9142 this.SplitContainer3.SplitterDistance = previewDistance;
9145 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9146 this.SplitContainer3.Panel2Collapsed = true;
9148 _initialLayout = false;
9150 if (this.WindowState != FormWindowState.Minimized)
9152 _formWindowState = this.WindowState;
9156 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9158 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9159 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9160 if (PlaySoundMenuItem.Checked)
9162 SettingManager.Common.PlaySound = true;
9166 SettingManager.Common.PlaySound = false;
9168 ModifySettingCommon = true;
9171 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9173 if (this._initialLayout)
9176 int splitterDistance;
9177 switch (this.WindowState)
9179 case FormWindowState.Normal:
9180 splitterDistance = this.SplitContainer1.SplitterDistance;
9182 case FormWindowState.Maximized:
9183 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9184 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9185 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9186 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9192 this._mySpDis = splitterDistance;
9193 this.ModifySettingLocal = true;
9196 private async Task doRepliedStatusOpen()
9198 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9200 if (MyCommon.IsKeyDown(Keys.Shift))
9202 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9205 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9207 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9208 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9212 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9214 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9215 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9216 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9219 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9224 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9226 await this.doRepliedStatusOpen();
9229 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9231 if (this._initialLayout)
9232 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
9234 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9235 if (multiline != this.StatusText.Multiline)
9237 this.StatusText.Multiline = multiline;
9238 SettingManager.Local.StatusMultiline = multiline;
9239 ModifySettingLocal = true;
9243 private void StatusText_MultilineChanged(object sender, EventArgs e)
9245 if (this.StatusText.Multiline)
9246 this.StatusText.ScrollBars = ScrollBars.Vertical;
9248 this.StatusText.ScrollBars = ScrollBars.None;
9250 ModifySettingLocal = true;
9253 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9256 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
9257 StatusText.Multiline = menuItemChecked;
9258 SettingManager.Local.StatusMultiline = menuItemChecked;
9259 if (menuItemChecked)
9261 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9262 SplitContainer2.SplitterDistance = 0;
9264 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9268 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9270 ModifySettingLocal = true;
9273 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9275 if (Converter_Type == MyCommon.UrlConverter.Bitly || Converter_Type == MyCommon.UrlConverter.Jmp)
9277 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
9278 if (string.IsNullOrEmpty(SettingManager.Common.BitlyAccessToken) &&
9279 (string.IsNullOrEmpty(SettingManager.Common.BilyUser) || string.IsNullOrEmpty(SettingManager.Common.BitlyPwd)))
9281 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
9286 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9287 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9289 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9290 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9291 //Appendix A. Collected ABNF for URI
9292 //http://www.ietf.org/rfc/rfc3986.txt
9296 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9298 if (StatusText.SelectionLength > 0)
9300 string tmp = StatusText.SelectedText;
9301 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9302 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9304 // 文字列が選択されている場合はその文字列について処理
9306 //nico.ms使用、nicovideoにマッチしたら変換
9307 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9309 result = nicoms.Shorten(tmp);
9311 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9313 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9316 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9317 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9318 result = resultUri.AbsoluteUri;
9320 catch (WebApiException e)
9322 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9325 catch (UriFormatException e)
9327 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9336 if (!string.IsNullOrEmpty(result))
9338 urlUndo undotmp = new urlUndo();
9340 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9341 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9342 if (origUrlIndex == -1)
9345 StatusText.Select(origUrlIndex, tmp.Length);
9346 StatusText.SelectedText = result;
9349 undotmp.Before = tmp;
9350 undotmp.After = result;
9352 if (urlUndoBuffer == null)
9354 urlUndoBuffer = new List<urlUndo>();
9355 UrlUndoToolStripMenuItem.Enabled = true;
9358 urlUndoBuffer.Add(undotmp);
9364 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9365 @"(?<url>(?<protocol>https?://)" +
9366 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9367 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9368 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9369 // 正規表現にマッチしたURL文字列をtinyurl化
9370 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9372 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9373 string tmp = mt.Result("${url}");
9374 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9375 urlUndo undotmp = new urlUndo();
9378 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9380 //nico.ms使用、nicovideoにマッチしたら変換
9381 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9383 result = nicoms.Shorten(tmp);
9385 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9387 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9390 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9391 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9392 result = resultUri.AbsoluteUri;
9394 catch (HttpRequestException e)
9396 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9397 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9398 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9400 this.StatusLabel.Text = Converter_Type + ":" + message;
9403 catch (WebApiException e)
9405 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9408 catch (UriFormatException e)
9410 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9419 if (!string.IsNullOrEmpty(result))
9421 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9422 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9423 if (origUrlIndex == -1)
9426 StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9427 StatusText.SelectedText = result;
9429 undotmp.Before = mt.Result("${url}");
9430 undotmp.After = result;
9432 if (urlUndoBuffer == null)
9434 urlUndoBuffer = new List<urlUndo>();
9435 UrlUndoToolStripMenuItem.Enabled = true;
9438 urlUndoBuffer.Add(undotmp);
9446 private void doUrlUndo()
9448 if (urlUndoBuffer != null)
9450 string tmp = StatusText.Text;
9451 foreach (urlUndo data in urlUndoBuffer)
9453 tmp = tmp.Replace(data.After, data.Before);
9455 StatusText.Text = tmp;
9456 urlUndoBuffer = null;
9457 UrlUndoToolStripMenuItem.Enabled = false;
9458 StatusText.SelectionStart = 0;
9459 StatusText.SelectionLength = 0;
9463 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9465 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9468 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9470 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9473 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9475 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9478 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9480 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9483 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9485 if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9487 MyCommon.UrlConverter svc = SettingManager.Common.AutoShortUrlFirst;
9488 Random rnd = new Random();
9489 // 前回使用した短縮URLサービス以外を選択する
9492 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9494 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9495 await UrlConvertAsync(svc);
9499 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9504 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9506 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9507 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9508 SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9509 ModifySettingCommon = true;
9512 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9514 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9515 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9516 SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9517 ModifySettingCommon = true;
9520 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9522 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9523 MenuStrip1.Tag = new Object();
9524 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9527 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9529 if (this.Tag != null) // 設定された戻り先へ遷移
9531 if (this.Tag == this.ListTab.SelectedTab)
9532 ((Control)this.ListTab.SelectedTab.Tag).Select();
9534 ((Control)this.Tag).Select();
9536 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9538 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9540 this.Tag = ListTab.SelectedTab.Tag;
9541 ((Control)this.Tag).Select();
9544 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9545 MenuStrip1.Tag = null;
9548 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9550 DetailsListView lst = (DetailsListView)sender;
9551 if (SettingManager.Local == null) return;
9555 SettingManager.Local.Width1 = lst.Columns[0].Width;
9556 SettingManager.Local.Width3 = lst.Columns[1].Width;
9560 int[] darr = new int[lst.Columns.Count];
9561 for (int i = 0; i < lst.Columns.Count; i++)
9563 darr[lst.Columns[i].DisplayIndex] = i;
9565 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9567 for (int i = 0; i < lst.Columns.Count; i++)
9572 SettingManager.Local.DisplayIndex1 = i;
9575 SettingManager.Local.DisplayIndex2 = i;
9578 SettingManager.Local.DisplayIndex3 = i;
9581 SettingManager.Local.DisplayIndex4 = i;
9584 SettingManager.Local.DisplayIndex5 = i;
9587 SettingManager.Local.DisplayIndex6 = i;
9590 SettingManager.Local.DisplayIndex7 = i;
9593 SettingManager.Local.DisplayIndex8 = i;
9597 SettingManager.Local.Width1 = lst.Columns[0].Width;
9598 SettingManager.Local.Width2 = lst.Columns[1].Width;
9599 SettingManager.Local.Width3 = lst.Columns[2].Width;
9600 SettingManager.Local.Width4 = lst.Columns[3].Width;
9601 SettingManager.Local.Width5 = lst.Columns[4].Width;
9602 SettingManager.Local.Width6 = lst.Columns[5].Width;
9603 SettingManager.Local.Width7 = lst.Columns[6].Width;
9604 SettingManager.Local.Width8 = lst.Columns[7].Width;
9606 ModifySettingLocal = true;
9607 _isColumnChanged = true;
9610 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9612 DetailsListView lst = (DetailsListView)sender;
9613 if (SettingManager.Local == null) return;
9616 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9618 SettingManager.Local.Width1 = lst.Columns[0].Width;
9619 ModifySettingLocal = true;
9620 _isColumnChanged = true;
9622 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9624 SettingManager.Local.Width3 = lst.Columns[1].Width;
9625 ModifySettingLocal = true;
9626 _isColumnChanged = true;
9631 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9633 SettingManager.Local.Width1 = lst.Columns[0].Width;
9634 ModifySettingLocal = true;
9635 _isColumnChanged = true;
9637 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9639 SettingManager.Local.Width2 = lst.Columns[1].Width;
9640 ModifySettingLocal = true;
9641 _isColumnChanged = true;
9643 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9645 SettingManager.Local.Width3 = lst.Columns[2].Width;
9646 ModifySettingLocal = true;
9647 _isColumnChanged = true;
9649 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9651 SettingManager.Local.Width4 = lst.Columns[3].Width;
9652 ModifySettingLocal = true;
9653 _isColumnChanged = true;
9655 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9657 SettingManager.Local.Width5 = lst.Columns[4].Width;
9658 ModifySettingLocal = true;
9659 _isColumnChanged = true;
9661 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9663 SettingManager.Local.Width6 = lst.Columns[5].Width;
9664 ModifySettingLocal = true;
9665 _isColumnChanged = true;
9667 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9669 SettingManager.Local.Width7 = lst.Columns[6].Width;
9670 ModifySettingLocal = true;
9671 _isColumnChanged = true;
9673 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9675 SettingManager.Local.Width8 = lst.Columns[7].Width;
9676 ModifySettingLocal = true;
9677 _isColumnChanged = true;
9680 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9683 // SaveConfigsLocal();
9687 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9689 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9690 ModifySettingLocal = true;
9693 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9695 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9697 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9699 SelectMedia_DragDrop(e);
9702 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9704 var (url, title) = GetUrlFromDataObject(e.Data);
9710 appendText = title + " " + url;
9712 if (this.StatusText.TextLength == 0)
9713 this.StatusText.Text = appendText;
9715 this.StatusText.Text += " " + appendText;
9717 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9719 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9721 this.StatusText.Text += text;
9723 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9725 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9726 if (data != null) StatusText.Text += data;
9731 /// IDataObject から URL とタイトルの対を取得します
9734 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9736 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9737 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9738 internal static (string Url, string Title) GetUrlFromDataObject(IDataObject data)
9740 if (data.GetDataPresent("text/x-moz-url"))
9742 // Firefox, Google Chrome で利用可能
9743 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9745 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9747 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9748 if (lines.Length < 2)
9749 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9751 return (lines[0], lines[1]);
9754 else if (data.GetDataPresent("IESiteModeToUrl"))
9756 // Internet Exproler 用
9757 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9759 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9761 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9762 if (lines.Length < 2)
9763 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9765 return (lines[0], lines[1]);
9768 else if (data.GetDataPresent("UniformResourceLocatorW"))
9772 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9774 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9779 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9782 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9784 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9786 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9788 SelectMedia_DragEnter(e);
9792 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9794 e.Effect = DragDropEffects.Copy;
9797 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9799 e.Effect = DragDropEffects.Copy;
9802 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9804 e.Effect = DragDropEffects.Copy;
9808 e.Effect = DragDropEffects.None;
9811 private void TweenMain_DragOver(object sender, DragEventArgs e)
9815 public bool IsNetworkAvailable()
9818 nw = MyCommon.IsNetworkAvailable();
9819 _myStatusOnline = nw;
9823 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9825 var uriStr = uri.AbsoluteUri;
9827 // OpenTween 内部で使用する URL
9828 if (uri.Authority == "opentween")
9830 await this.OpenInternalUriAsync(uri);
9834 // ハッシュタグを含む Twitter 検索
9835 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9838 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9839 var pos = unescapedQuery.IndexOf('#');
9840 if (pos == -1) return;
9842 var hash = unescapedQuery.Substring(pos);
9843 this.HashSupl.AddItem(hash);
9844 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9845 this.AddNewTabForSearch(hash);
9850 // フラグが立っている場合は設定と逆の動作をする
9851 if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9852 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9854 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9855 if (userUriMatch.Success)
9857 var screenName = userUriMatch.Groups["ScreenName"].Value;
9858 if (this.IsTwitterId(screenName))
9860 this.AddNewTabForUserTimeline(screenName);
9867 await this.OpenUriInBrowserAsync(uriStr);
9871 /// OpenTween 内部の機能を呼び出すための URL を開きます
9873 private async Task OpenInternalUriAsync(Uri uri)
9875 // ツイートを開く (//opentween/status/:status_id)
9876 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9879 var statusId = long.Parse(match.Groups[1].Value);
9880 await this.OpenRelatedTab(statusId);
9885 public Task OpenUriInBrowserAsync(string UriString)
9887 return Task.Run(() =>
9889 string myPath = UriString;
9893 var configBrowserPath = SettingManager.Local.BrowserPath;
9894 if (!string.IsNullOrEmpty(configBrowserPath))
9896 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9898 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9899 string browserPath = configBrowserPath.Substring(1, sep - 1);
9901 if (sep < configBrowserPath.Length - 1)
9903 arg = configBrowserPath.Substring(sep + 1);
9905 myPath = arg + " " + myPath;
9906 System.Diagnostics.Process.Start(browserPath, myPath);
9910 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9915 System.Diagnostics.Process.Start(myPath);
9920 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9925 private void ListTabSelect(TabPage _tab)
9929 this.PurgeListViewItemCache();
9932 _curList = (DetailsListView)_tab.Tag;
9934 if (_curList.SelectedIndices.Count > 0)
9936 _curItemIndex = _curList.SelectedIndices[0];
9937 _curPost = GetCurTabPost(_curItemIndex);
9946 _anchorFlag = false;
9950 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
9954 for (int i = 0; i < _curList.Columns.Count; i++)
9956 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
9961 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9963 ListTabSelect(e.TabPage);
9966 private void SelectListItem(DetailsListView LView, int Index)
9969 Rectangle bnd = new Rectangle();
9971 var item = LView.FocusedItem;
9980 LView.SelectedIndices.Clear();
9982 while (LView.SelectedIndices.Count > 0);
9983 item = LView.Items[Index];
9984 item.Selected = true;
9985 item.Focused = true;
9987 if (flg) LView.Invalidate(bnd);
9990 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9993 Rectangle bnd = new Rectangle();
9995 var item = LView.FocusedItem;
10006 LView.SelectedIndices.Clear();
10008 while (LView.SelectedIndices.Count > 0);
10009 LView.SelectItems(Index);
10011 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
10013 LView.SelectionMark = selectionMarkIndex;
10015 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
10017 LView.Items[focusedIndex].Focused = true;
10019 else if (Index != null && Index.Length != 0)
10021 LView.Items[Index.Last()].Focused = true;
10024 if (flg) LView.Invalidate(bnd);
10027 private void StartUserStream()
10029 tw.NewPostFromStream += tw_NewPostFromStream;
10030 tw.UserStreamStarted += tw_UserStreamStarted;
10031 tw.UserStreamStopped += tw_UserStreamStopped;
10032 tw.PostDeleted += tw_PostDeleted;
10033 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
10035 this.RefreshUserStreamsMenu();
10037 if (SettingManager.Common.UserstreamStartup)
10038 tw.StartUserStream();
10041 private async void TweenMain_Shown(object sender, EventArgs e)
10043 NotifyIcon1.Visible = true;
10045 if (this.IsNetworkAvailable())
10049 var loadTasks = new List<Task>
10051 this.RefreshMuteUserIdsAsync(),
10052 this.RefreshBlockIdsAsync(),
10053 this.RefreshNoRetweetIdsAsync(),
10054 this.RefreshTwitterConfigurationAsync(),
10055 this.GetHomeTimelineAsync(),
10056 this.GetReplyAsync(),
10057 this.GetDirectMessagesAsync(),
10058 this.GetPublicSearchAllAsync(),
10059 this.GetUserTimelineAllAsync(),
10060 this.GetListTimelineAllAsync(),
10063 if (SettingManager.Common.StartupFollowers)
10064 loadTasks.Add(this.RefreshFollowerIdsAsync());
10066 if (SettingManager.Common.GetFav)
10067 loadTasks.Add(this.GetFavoritesAsync());
10069 var allTasks = Task.WhenAll(loadTasks);
10074 var timeout = Task.Delay(5000);
10075 if (await Task.WhenAny(allTasks, timeout) != timeout)
10079 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10081 if (MyCommon._endingFlag)
10085 if (MyCommon._endingFlag) return;
10087 if (ApplicationSettings.VersionInfoUrl != null)
10089 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10090 if (SettingManager.Common.StartupVersion)
10091 await this.CheckNewVersion(true);
10095 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10096 this.VerUpMenuItem.Enabled = false;
10097 this.VerUpMenuItem.Available = false;
10098 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10101 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10102 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10104 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10105 SettingStripMenuItem_Click(null, null);
10109 var reloadTasks = new List<Task>();
10111 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
10112 reloadTasks.Add(this.RefreshFollowerIdsAsync());
10114 if (!tw.GetNoRetweetSuccess)
10115 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10117 if (this.tw.Configuration.PhotoSizeLimit == 0)
10118 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10120 await Task.WhenAll(reloadTasks);
10125 TimerTimeline.Enabled = true;
10128 private async Task doGetFollowersMenu()
10130 await this.RefreshFollowerIdsAsync();
10131 await this.DispSelectedPost(true);
10134 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10136 await this.doGetFollowersMenu();
10139 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10141 doReTweetUnofficial();
10144 private async Task doReTweetOfficial(bool isConfirm)
10147 if (this.ExistCurrentPost)
10149 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10151 if (this._curPost.IsProtect)
10152 MessageBox.Show("Protected.");
10154 _DoFavRetweetFlags = false;
10157 if (_curList.SelectedIndices.Count > 15)
10159 MessageBox.Show(Properties.Resources.RetweetLimitText);
10160 _DoFavRetweetFlags = false;
10163 else if (_curList.SelectedIndices.Count > 1)
10165 string QuestionText = Properties.Resources.RetweetQuestion2;
10166 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10167 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10169 case DialogResult.Cancel:
10170 case DialogResult.No:
10171 _DoFavRetweetFlags = false;
10177 if (!SettingManager.Common.RetweetNoConfirm)
10179 string Questiontext = Properties.Resources.RetweetQuestion1;
10180 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10181 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10183 _DoFavRetweetFlags = false;
10189 var statusIds = new List<long>();
10190 foreach (int idx in _curList.SelectedIndices)
10192 PostClass post = GetCurTabPost(idx);
10193 if (post.CanRetweetBy(this.twitterApi.CurrentUserId))
10194 statusIds.Add(post.StatusId);
10197 await this.RetweetAsync(statusIds);
10201 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10203 await this.doReTweetOfficial(true);
10206 private async Task FavoritesRetweetOfficial()
10208 if (!this.ExistCurrentPost) return;
10209 _DoFavRetweetFlags = true;
10210 var retweetTask = this.doReTweetOfficial(true);
10211 if (_DoFavRetweetFlags)
10213 _DoFavRetweetFlags = false;
10214 var favoriteTask = this.FavoriteChange(true, false);
10216 await Task.WhenAll(retweetTask, favoriteTask);
10224 private async Task FavoritesRetweetUnofficial()
10226 if (this.ExistCurrentPost && !_curPost.IsDm)
10228 _DoFavRetweetFlags = true;
10229 var favoriteTask = this.FavoriteChange(true);
10230 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10232 _DoFavRetweetFlags = false;
10233 doReTweetUnofficial();
10236 await favoriteTask;
10241 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10243 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10244 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10245 /// <returns>復元されたツイート本文</returns>
10246 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10248 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10251 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10253 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10255 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10259 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10261 statusHtml = statusHtml.Replace("<br>", " ");
10263 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10264 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10265 statusHtml = statusHtml.Replace(" ", " ");
10267 return WebUtility.HtmlDecode(statusHtml);
10270 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10272 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10274 if (_curPost != null)
10275 await this.DispSelectedPost(true);
10278 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10280 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10281 DebugModeToolStripMenuItem.Visible = true;
10283 DebugModeToolStripMenuItem.Visible = false;
10286 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
10288 this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
10291 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
10293 this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
10296 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
10298 SettingManager.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
10301 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
10303 SettingManager.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
10304 ModifySettingCommon = true;
10307 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10309 SettingManager.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
10310 ModifySettingCommon = true;
10313 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
10315 UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
10316 PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
10317 UrlAutoShortenMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10318 IdeographicSpaceToSpaceMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10319 MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
10320 FocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10323 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10325 UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
10326 PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
10327 UrlAutoShortenPullDownMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10328 IdeographicSpaceToSpacePullDownMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10329 MultiLinePullDownMenuItem.Checked = SettingManager.Local.StatusMultiline;
10330 FocusLockPullDownMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10333 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10335 if (TraceOutToolStripMenuItem.Checked)
10336 MyCommon.TraceFlag = true;
10338 MyCommon.TraceFlag = false;
10341 private void TweenMain_Deactivate(object sender, EventArgs e)
10343 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10344 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10347 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10349 if (string.IsNullOrEmpty(_rclickTabName)) return;
10351 TabRename(_rclickTabName, out var _);
10354 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10356 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10359 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10361 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10364 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10366 TwitterApiStatus apiStatus;
10368 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10370 var cancellationToken = dialog.EnableCancellation();
10374 var task = this.tw.GetInfoApi();
10375 apiStatus = await dialog.WaitForAsync(this, task);
10377 catch (WebApiException)
10382 if (cancellationToken.IsCancellationRequested)
10385 if (apiStatus == null)
10387 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10392 using (var apiDlg = new ApiInfoDialog())
10394 apiDlg.ShowDialog(this);
10398 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10400 var id = _curPost?.ScreenName ?? "";
10402 await this.FollowCommand(id);
10405 internal async Task FollowCommand(string id)
10407 using (var inputName = new InputTabName())
10409 inputName.FormTitle = "Follow";
10410 inputName.FormDescription = Properties.Resources.FRMessage1;
10411 inputName.TabName = id;
10413 if (inputName.ShowDialog(this) != DialogResult.OK)
10415 if (string.IsNullOrWhiteSpace(inputName.TabName))
10418 id = inputName.TabName.Trim();
10421 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10425 var task = this.twitterApi.FriendshipsCreate(id).IgnoreResponse();
10426 await dialog.WaitForAsync(this, task);
10428 catch (WebApiException ex)
10430 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10435 MessageBox.Show(Properties.Resources.FRMessage3);
10438 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10440 var id = _curPost?.ScreenName ?? "";
10442 await this.RemoveCommand(id, false);
10445 internal async Task RemoveCommand(string id, bool skipInput)
10449 using (var inputName = new InputTabName())
10451 inputName.FormTitle = "Unfollow";
10452 inputName.FormDescription = Properties.Resources.FRMessage1;
10453 inputName.TabName = id;
10455 if (inputName.ShowDialog(this) != DialogResult.OK)
10457 if (string.IsNullOrWhiteSpace(inputName.TabName))
10460 id = inputName.TabName.Trim();
10464 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10468 var task = this.twitterApi.FriendshipsDestroy(id).IgnoreResponse();
10469 await dialog.WaitForAsync(this, task);
10471 catch (WebApiException ex)
10473 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10478 MessageBox.Show(Properties.Resources.FRMessage3);
10481 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10483 var id = _curPost?.ScreenName ?? "";
10485 await this.ShowFriendship(id);
10488 internal async Task ShowFriendship(string id)
10490 using (var inputName = new InputTabName())
10492 inputName.FormTitle = "Show Friendships";
10493 inputName.FormDescription = Properties.Resources.FRMessage1;
10494 inputName.TabName = id;
10496 if (inputName.ShowDialog(this) != DialogResult.OK)
10498 if (string.IsNullOrWhiteSpace(inputName.TabName))
10501 id = inputName.TabName.Trim();
10504 bool isFollowing, isFollowed;
10506 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10508 var cancellationToken = dialog.EnableCancellation();
10512 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10513 var friendship = await dialog.WaitForAsync(this, task);
10515 isFollowing = friendship.Relationship.Source.Following;
10516 isFollowed = friendship.Relationship.Source.FollowedBy;
10518 catch (WebApiException ex)
10520 if (!cancellationToken.IsCancellationRequested)
10521 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10525 if (cancellationToken.IsCancellationRequested)
10529 string result = "";
10532 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10536 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10540 result += Properties.Resources.GetFriendshipInfo3;
10544 result += Properties.Resources.GetFriendshipInfo4;
10546 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10547 MessageBox.Show(result);
10550 internal async Task ShowFriendship(string[] ids)
10552 foreach (string id in ids)
10554 bool isFollowing, isFollowed;
10556 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10558 var cancellationToken = dialog.EnableCancellation();
10562 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10563 var friendship = await dialog.WaitForAsync(this, task);
10565 isFollowing = friendship.Relationship.Source.Following;
10566 isFollowed = friendship.Relationship.Source.FollowedBy;
10568 catch (WebApiException ex)
10570 if (!cancellationToken.IsCancellationRequested)
10571 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10575 if (cancellationToken.IsCancellationRequested)
10579 string result = "";
10585 ff += Properties.Resources.GetFriendshipInfo1;
10589 ff += Properties.Resources.GetFriendshipInfo2;
10592 ff += System.Environment.NewLine + " ";
10595 ff += Properties.Resources.GetFriendshipInfo3;
10599 ff += Properties.Resources.GetFriendshipInfo4;
10601 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10604 if (MessageBox.Show(
10605 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10606 MessageBoxButtons.YesNo,
10607 MessageBoxIcon.Question,
10608 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10610 await this.RemoveCommand(id, true);
10615 MessageBox.Show(result);
10620 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10622 await this.doShowUserStatus(tw.Username, false);
10623 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
10625 // doShowUserStatus(tw.Username, false);
10629 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
10634 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10635 // URLから切り出した文字列を渡す
10637 public bool IsTwitterId(string name)
10639 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10640 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10642 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
10645 private void doQuoteOfficial()
10647 if (this.ExistCurrentPost)
10649 if (_curPost.IsDm ||
10650 !StatusText.Enabled) return;
10652 if (_curPost.IsProtect)
10654 MessageBox.Show("Protected.");
10658 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10660 StatusText.Text += " " + MyCommon.GetStatusUrl(_curPost);
10662 this.inReplyTo = null;
10664 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10665 StatusText.Focus();
10669 private void doReTweetUnofficial()
10672 if (this.ExistCurrentPost)
10674 if (_curPost.IsDm || !StatusText.Enabled)
10677 if (_curPost.IsProtect)
10679 MessageBox.Show("Protected.");
10682 string rtdata = _curPost.Text;
10683 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10685 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10687 StatusText.Text += " RT @" + _curPost.ScreenName + ": " + rtdata;
10689 // 投稿時に in_reply_to_status_id を付加する
10690 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
10691 var inReplyToScreenName = this._curPost.ScreenName;
10692 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
10694 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10695 StatusText.Focus();
10699 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
10704 private void SearchButton_Click(object sender, EventArgs e)
10707 Control pnl = ((Control)sender).Parent;
10708 if (pnl == null) return;
10709 string tbName = pnl.Parent.Text;
10710 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10711 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10712 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10713 cmb.Text = cmb.Text.Trim();
10714 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10715 bool Quote = false;
10716 StringBuilder buf = new StringBuilder();
10717 char[] c = cmb.Text.ToCharArray();
10718 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10720 if (cnt > cmb.Text.Length - 4)
10722 buf.Append(cmb.Text.Substring(cnt));
10731 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10733 buf.Append(" OR ");
10738 buf.Append(c[cnt]);
10740 cmb.Text = buf.ToString();
10742 var listView = (DetailsListView)pnl.Parent.Tag;
10744 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10746 tb.SearchWords = cmb.Text;
10747 tb.SearchLang = cmbLang.Text;
10748 if (string.IsNullOrEmpty(cmb.Text))
10756 int idx = cmb.Items.IndexOf(tb.SearchWords);
10757 if (idx > -1) cmb.Items.RemoveAt(idx);
10758 cmb.Items.Insert(0, tb.SearchWords);
10759 cmb.Text = tb.SearchWords;
10761 this.PurgeListViewItemCache();
10762 listView.VirtualListSize = 0;
10763 _statuses.ClearTabIds(tbName);
10764 SaveConfigsTabs(); //検索条件の保存
10767 this.GetPublicSearchAsync(tb);
10771 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10774 await this.DoRefreshMore();
10778 /// 指定されたタブのListTabにおける位置を返します
10781 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10783 public int GetTabPageIndex(string tabName)
10786 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
10788 if (tabPage.Text == tabName)
10797 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10799 if (_statuses.RemovedTab.Count == 0)
10801 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10806 DetailsListView listView = null;
10808 TabModel tb = _statuses.RemovedTab.Pop();
10809 if (tb.TabType == MyCommon.TabUsageType.Related)
10811 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10812 if (relatedTab != null)
10814 // 関連発言なら既存のタブを置き換える
10815 tb.TabName = relatedTab.TabName;
10816 this.ClearTab(tb.TabName, false);
10817 _statuses.Tabs[tb.TabName] = tb;
10819 for (int i = 0; i < ListTab.TabPages.Count; i++)
10821 var tabPage = ListTab.TabPages[i];
10822 if (tb.TabName == tabPage.Text)
10824 listView = (DetailsListView)tabPage.Tag;
10825 ListTab.SelectedIndex = i;
10832 const string TabName = "Related Tweets";
10833 string renamed = TabName;
10834 for (int i = 2; i <= 100; i++)
10836 if (!_statuses.ContainsTab(renamed)) break;
10837 renamed = TabName + i;
10839 tb.TabName = renamed;
10841 _statuses.AddTab(tb);
10842 AddNewTab(tb, startup: false);
10844 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10845 listView = (DetailsListView)tabPage.Tag;
10846 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10851 string renamed = tb.TabName;
10852 for (int i = 1; i < int.MaxValue; i++)
10854 if (!_statuses.ContainsTab(renamed)) break;
10855 renamed = tb.TabName + "(" + i + ")";
10857 tb.TabName = renamed;
10859 _statuses.AddTab(tb);
10860 AddNewTab(tb, startup: false);
10862 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10863 listView = (DetailsListView)tabPage.Tag;
10864 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10868 if (listView != null)
10870 using (ControlTransaction.Update(listView))
10872 listView.VirtualListSize = tb.AllCount;
10878 private async Task doMoveToRTHome()
10880 if (_curList.SelectedIndices.Count > 0)
10882 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
10883 if (post.RetweetedId != null)
10885 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
10890 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10892 await this.doMoveToRTHome();
10895 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10897 var screenName = this._curPost?.ScreenName;
10898 if (screenName != null)
10899 this.ListManageUserContext(screenName);
10902 public void ListManageUserContext(string screenName)
10904 using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10906 listSelectForm.ShowDialog(this);
10910 private void SearchControls_Enter(object sender, EventArgs e)
10912 Control pnl = (Control)sender;
10913 foreach (Control ctl in pnl.Controls)
10915 ctl.TabStop = true;
10919 private void SearchControls_Leave(object sender, EventArgs e)
10921 Control pnl = (Control)sender;
10922 foreach (Control ctl in pnl.Controls)
10924 ctl.TabStop = false;
10928 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10930 if (ListTab.SelectedTab != null)
10932 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
10933 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
10937 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10939 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10942 private void HashManageMenuItem_Click(object sender, EventArgs e)
10944 DialogResult rslt = DialogResult.Cancel;
10947 rslt = HashMgr.ShowDialog();
10953 this.TopMost = SettingManager.Common.AlwaysTop;
10954 if (rslt == DialogResult.Cancel) return;
10955 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10957 HashStripSplitButton.Text = HashMgr.UseHash;
10958 HashTogglePullDownMenuItem.Checked = true;
10959 HashToggleMenuItem.Checked = true;
10963 HashStripSplitButton.Text = "#[-]";
10964 HashTogglePullDownMenuItem.Checked = false;
10965 HashToggleMenuItem.Checked = false;
10967 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10969 // int sidx = StatusText.SelectionStart;
10970 // string hash = HashMgr.UseHash + " ";
10973 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10974 // hash = " " + hash;
10976 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
10977 // sidx += hash.Length;
10978 // StatusText.SelectionStart = sidx;
10979 // StatusText.Focus();
10981 ModifySettingCommon = true;
10982 this.StatusText_TextChanged(null, null);
10985 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10987 HashMgr.ToggleHash();
10988 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10990 HashStripSplitButton.Text = HashMgr.UseHash;
10991 HashToggleMenuItem.Checked = true;
10992 HashTogglePullDownMenuItem.Checked = true;
10996 HashStripSplitButton.Text = "#[-]";
10997 HashToggleMenuItem.Checked = false;
10998 HashTogglePullDownMenuItem.Checked = false;
11000 ModifySettingCommon = true;
11001 this.StatusText_TextChanged(null, null);
11004 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
11006 HashToggleMenuItem_Click(null, null);
11009 public void SetPermanentHashtag(string hashtag)
11011 HashMgr.SetPermanentHash("#" + hashtag);
11012 HashStripSplitButton.Text = HashMgr.UseHash;
11013 HashTogglePullDownMenuItem.Checked = true;
11014 HashToggleMenuItem.Checked = true;
11016 ModifySettingCommon = true;
11019 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
11021 if (ListTab.SelectedTab == null) return;
11022 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
11023 if (!this.ExistCurrentPost)
11025 this.ReplyOpMenuItem.Enabled = false;
11026 this.ReplyAllOpMenuItem.Enabled = false;
11027 this.DmOpMenuItem.Enabled = false;
11028 this.ShowProfMenuItem.Enabled = false;
11029 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
11030 this.ListManageMenuItem.Enabled = false;
11031 this.OpenFavOpMenuItem.Enabled = false;
11032 this.CreateTabRuleOpMenuItem.Enabled = false;
11033 this.CreateIdRuleOpMenuItem.Enabled = false;
11034 this.CreateSourceRuleOpMenuItem.Enabled = false;
11035 this.ReadOpMenuItem.Enabled = false;
11036 this.UnreadOpMenuItem.Enabled = false;
11040 this.ReplyOpMenuItem.Enabled = true;
11041 this.ReplyAllOpMenuItem.Enabled = true;
11042 this.DmOpMenuItem.Enabled = true;
11043 this.ShowProfMenuItem.Enabled = true;
11044 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
11045 this.ListManageMenuItem.Enabled = true;
11046 this.OpenFavOpMenuItem.Enabled = true;
11047 this.CreateTabRuleOpMenuItem.Enabled = true;
11048 this.CreateIdRuleOpMenuItem.Enabled = true;
11049 this.CreateSourceRuleOpMenuItem.Enabled = true;
11050 this.ReadOpMenuItem.Enabled = true;
11051 this.UnreadOpMenuItem.Enabled = true;
11054 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
11056 this.FavOpMenuItem.Enabled = false;
11057 this.UnFavOpMenuItem.Enabled = false;
11058 this.OpenStatusOpMenuItem.Enabled = false;
11059 this.OpenFavotterOpMenuItem.Enabled = false;
11060 this.ShowRelatedStatusesMenuItem2.Enabled = false;
11061 this.RtOpMenuItem.Enabled = false;
11062 this.RtUnOpMenuItem.Enabled = false;
11063 this.QtOpMenuItem.Enabled = false;
11064 this.FavoriteRetweetMenuItem.Enabled = false;
11065 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11069 this.FavOpMenuItem.Enabled = true;
11070 this.UnFavOpMenuItem.Enabled = true;
11071 this.OpenStatusOpMenuItem.Enabled = true;
11072 this.OpenFavotterOpMenuItem.Enabled = true;
11073 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
11075 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
11077 this.RtOpMenuItem.Enabled = false;
11078 this.RtUnOpMenuItem.Enabled = false;
11079 this.QtOpMenuItem.Enabled = false;
11080 this.FavoriteRetweetMenuItem.Enabled = false;
11081 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11085 this.RtOpMenuItem.Enabled = true;
11086 this.RtUnOpMenuItem.Enabled = true;
11087 this.QtOpMenuItem.Enabled = true;
11088 this.FavoriteRetweetMenuItem.Enabled = true;
11089 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11093 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11095 this.RefreshPrevOpMenuItem.Enabled = true;
11099 this.RefreshPrevOpMenuItem.Enabled = false;
11101 if (!this.ExistCurrentPost
11102 || _curPost.InReplyToStatusId == null)
11104 OpenRepSourceOpMenuItem.Enabled = false;
11108 OpenRepSourceOpMenuItem.Enabled = true;
11110 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11112 OpenRterHomeMenuItem.Enabled = false;
11116 OpenRterHomeMenuItem.Enabled = true;
11119 if (this.ExistCurrentPost)
11121 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11125 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11127 ContextMenuTabProperty_Opening(sender, null);
11130 public Twitter TwitterInstance
11135 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11137 if (this._initialLayout)
11140 int splitterDistance;
11141 switch (this.WindowState)
11143 case FormWindowState.Normal:
11144 splitterDistance = this.SplitContainer3.SplitterDistance;
11146 case FormWindowState.Maximized:
11147 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11148 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11149 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11150 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11156 this._mySpDis3 = splitterDistance;
11157 this.ModifySettingLocal = true;
11160 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11162 if (_statuses.RemovedTab.Count == 0)
11164 UndoRemoveTabMenuItem.Enabled = false;
11168 UndoRemoveTabMenuItem.Enabled = true;
11170 if (ListTab.SelectedTab != null)
11172 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11173 PublicSearchQueryMenuItem.Enabled = true;
11175 PublicSearchQueryMenuItem.Enabled = false;
11179 PublicSearchQueryMenuItem.Enabled = false;
11181 if (!this.ExistCurrentPost)
11183 this.CopySTOTMenuItem.Enabled = false;
11184 this.CopyURLMenuItem.Enabled = false;
11185 this.CopyUserIdStripMenuItem.Enabled = false;
11189 this.CopySTOTMenuItem.Enabled = true;
11190 this.CopyURLMenuItem.Enabled = true;
11191 this.CopyUserIdStripMenuItem.Enabled = true;
11192 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11193 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11197 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11199 SetNotifyIconText();
11202 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11204 var id = _curPost?.ScreenName ?? "";
11206 await this.ShowUserStatus(id);
11209 private async Task doShowUserStatus(string id, bool ShowInputDialog)
11211 TwitterUser user = null;
11213 if (ShowInputDialog)
11215 using (var inputName = new InputTabName())
11217 inputName.FormTitle = "Show UserStatus";
11218 inputName.FormDescription = Properties.Resources.FRMessage1;
11219 inputName.TabName = id;
11221 if (inputName.ShowDialog(this) != DialogResult.OK)
11223 if (string.IsNullOrWhiteSpace(inputName.TabName))
11226 id = inputName.TabName.Trim();
11230 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11232 var cancellationToken = dialog.EnableCancellation();
11236 var task = this.twitterApi.UsersShow(id);
11237 user = await dialog.WaitForAsync(this, task);
11239 catch (WebApiException ex)
11241 if (!cancellationToken.IsCancellationRequested)
11242 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11246 if (cancellationToken.IsCancellationRequested)
11250 await this.doShowUserStatus(user);
11253 private async Task doShowUserStatus(TwitterUser user)
11255 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
11257 var showUserTask = userDialog.ShowUserAsync(user);
11258 userDialog.ShowDialog(this);
11261 this.BringToFront();
11263 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11264 await showUserTask;
11268 internal Task ShowUserStatus(string id, bool ShowInputDialog)
11270 return this.doShowUserStatus(id, ShowInputDialog);
11273 internal Task ShowUserStatus(string id)
11275 return this.doShowUserStatus(id, true);
11278 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
11280 if (_curPost != null)
11282 await this.ShowUserStatus(_curPost.ScreenName, false);
11286 private async void RtCountMenuItem_Click(object sender, EventArgs e)
11288 if (!this.ExistCurrentPost)
11291 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11292 TwitterStatus status;
11294 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11296 var cancellationToken = dialog.EnableCancellation();
11300 var task = this.twitterApi.StatusesShow(statusId);
11301 status = await dialog.WaitForAsync(this, task);
11303 catch (WebApiException ex)
11305 if (!cancellationToken.IsCancellationRequested)
11306 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11310 if (cancellationToken.IsCancellationRequested)
11314 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11317 private HookGlobalHotkey _hookGlobalHotkey;
11320 _hookGlobalHotkey = new HookGlobalHotkey(this);
11322 // この呼び出しは、Windows フォーム デザイナで必要です。
11323 InitializeComponent();
11325 // InitializeComponent() 呼び出しの後で初期化を追加します。
11327 if (!this.DesignMode)
11329 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11330 this.StatusText.Dock = DockStyle.Fill;
11333 this.tweetDetailsView.Owner = this;
11335 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11336 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11337 this.gh.NotifyClicked += GrowlHelper_Callback;
11339 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11340 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11342 this.ImageSelector.Visible = false;
11343 this.ImageSelector.Enabled = false;
11344 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11346 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11348 this.ReplaceAppName();
11349 this.InitializeShortcuts();
11352 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11354 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11357 this.Visible = false;
11359 else if (Form.ActiveForm == null)
11361 this.Visible = true;
11362 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11364 this.BringToFront();
11365 this.StatusText.Focus();
11369 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11371 this.MultiLinePullDownMenuItem.PerformClick();
11374 public PostClass CurPost
11376 get { return _curPost; }
11380 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11382 if (ImageSelector.Visible)
11383 ImageSelector.EndSelection();
11385 ImageSelector.BeginSelection();
11388 private void SelectMedia_DragEnter(DragEventArgs e)
11390 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11392 e.Effect = DragDropEffects.Copy;
11395 e.Effect = DragDropEffects.None;
11398 private void SelectMedia_DragDrop(DragEventArgs e)
11401 this.BringToFront();
11402 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11403 StatusText.Focus();
11406 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11408 TimelinePanel.Visible = false;
11409 TimelinePanel.Enabled = false;
11412 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11414 TimelinePanel.Visible = true;
11415 TimelinePanel.Enabled = true;
11416 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11419 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11421 this.AllowDrop = false;
11424 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11426 this.AllowDrop = true;
11429 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11431 if (ImageSelector.Visible)
11433 ModifySettingCommon = true;
11434 SaveConfigsAll(true);
11436 this.StatusText_TextChanged(null, null);
11440 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11442 this.StatusText_TextChanged(null, null);
11446 /// StatusTextでCtrl+Vが押下された時の処理
11448 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11452 if (Clipboard.ContainsText())
11454 // clipboardにテキストがある場合は貼り付け処理
11455 this.StatusText.Paste(Clipboard.GetText());
11457 else if (Clipboard.ContainsImage())
11460 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11461 Properties.Resources.PostPictureWarn4,
11462 MessageBoxButtons.OKCancel,
11463 MessageBoxIcon.Question,
11464 MessageBoxDefaultButton.Button2)
11465 == DialogResult.OK)
11467 // clipboardから画像を取得
11468 using (var image = Clipboard.GetImage())
11470 this.ImageSelector.BeginSelection(image);
11475 catch (ExternalException ex)
11477 MessageBox.Show(ex.Message);
11482 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11484 using (ListManage form = new ListManage(tw))
11486 form.ShowDialog(this);
11490 public bool ModifySettingCommon { get; set; }
11491 public bool ModifySettingLocal { get; set; }
11492 public bool ModifySettingAtId { get; set; }
11494 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11496 if (this.ExistCurrentPost && !_curPost.IsDm)
11497 RtCountMenuItem.Enabled = true;
11499 RtCountMenuItem.Enabled = false;
11501 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11502 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11504 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11507 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11512 private void CopyUserId()
11514 if (_curPost == null) return;
11515 string clstr = _curPost.ScreenName;
11518 Clipboard.SetDataObject(clstr, false, 5, 100);
11520 catch (Exception ex)
11522 MessageBox.Show(ex.Message);
11526 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11528 if (this.ExistCurrentPost && !_curPost.IsDm)
11532 await this.OpenRelatedTab(this._curPost);
11534 catch (TabException ex)
11536 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11542 /// 指定されたツイートに対する関連発言タブを開きます
11544 /// <param name="statusId">表示するツイートのID</param>
11545 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11546 public async Task OpenRelatedTab(long statusId)
11548 var post = this._statuses[statusId];
11553 post = await this.tw.GetStatusApi(false, statusId);
11555 catch (WebApiException ex)
11557 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11562 await this.OpenRelatedTab(post);
11566 /// 指定されたツイートに対する関連発言タブを開きます
11568 /// <param name="post">表示する対象となるツイート</param>
11569 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11570 private async Task OpenRelatedTab(PostClass post)
11572 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11573 if (tabRelated != null)
11575 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11578 var tabName = this._statuses.MakeTabName("Related Tweets");
11580 tabRelated = new RelatedPostsTabModel(tabName, post);
11581 tabRelated.UnreadManage = false;
11582 tabRelated.Notify = false;
11584 this._statuses.AddTab(tabRelated);
11585 this.AddNewTab(tabRelated, startup: false);
11588 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
11590 tabPage = this.ListTab.TabPages[i];
11591 if (tabName == tabPage.Text)
11593 this.ListTab.SelectedIndex = i;
11598 await this.GetRelatedTweetsAsync(tabRelated);
11600 tabPage = this.ListTab.TabPages.Cast<TabPage>()
11601 .FirstOrDefault(x => x.Text == tabRelated.TabName);
11603 if (tabPage != null)
11605 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11607 var listView = (DetailsListView)tabPage.Tag;
11608 var targetPost = tabRelated.TargetPost;
11609 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11611 if (index != -1 && index < listView.Items.Count)
11613 listView.SelectedIndices.Add(index);
11614 listView.Items[index].Focused = true;
11619 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11621 StringBuilder buf = new StringBuilder();
11622 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11623 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11624 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11625 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11626 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11629 private void tw_UserIdChanged()
11631 this.ModifySettingCommon = true;
11634 #region "Userstream"
11635 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11639 if (InvokeRequired && !IsDisposed)
11641 await this.InvokeAsync(async () =>
11643 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11644 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
11646 this.PurgeListViewItemCache();
11647 ((DetailsListView)_curTab.Tag).Update();
11648 if (_curPost != null && _curPost.StatusId == e.StatusId)
11649 await this.DispSelectedPost(true);
11655 catch (ObjectDisposedException)
11659 catch (InvalidOperationException)
11665 private int userStreamsRefreshing = 0;
11667 private async void tw_NewPostFromStream(object sender, EventArgs e)
11669 if (SettingManager.Common.ReadOldPosts)
11671 _statuses.SetReadHomeTab(); //新着時未読クリア
11674 this._statuses.DistributePosts();
11676 if (SettingManager.Common.UserstreamPeriod > 0) return;
11678 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
11679 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
11683 await this.InvokeAsync(() => this.RefreshTimeline())
11684 .ConfigureAwait(false);
11688 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
11693 private async void tw_UserStreamStarted(object sender, EventArgs e)
11697 if (InvokeRequired && !IsDisposed)
11699 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11703 catch (ObjectDisposedException)
11707 catch (InvalidOperationException)
11712 this.RefreshUserStreamsMenu();
11713 this.MenuItemUserStream.Enabled = true;
11715 StatusLabel.Text = "UserStream Started.";
11718 private async void tw_UserStreamStopped(object sender, EventArgs e)
11722 if (InvokeRequired && !IsDisposed)
11724 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11728 catch (ObjectDisposedException)
11732 catch (InvalidOperationException)
11737 this.RefreshUserStreamsMenu();
11738 this.MenuItemUserStream.Enabled = true;
11740 StatusLabel.Text = "UserStream Stopped.";
11743 private void RefreshUserStreamsMenu()
11745 if (this.tw.UserStreamActive)
11747 this.MenuItemUserStream.Text = "&UserStream ▶";
11748 this.StopToolStripMenuItem.Text = "&Stop";
11752 this.MenuItemUserStream.Text = "&UserStream ■";
11753 this.StopToolStripMenuItem.Text = "&Start";
11757 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11761 if (InvokeRequired && !IsDisposed)
11763 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11767 catch (ObjectDisposedException)
11771 catch (InvalidOperationException)
11775 var ev = e.EventData;
11776 StatusLabel.Text = "Event: " + ev.Event;
11777 //if (ev.Event == "favorite")
11779 // NotifyFavorite(ev);
11782 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11784 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
11786 this.PurgeListViewItemCache();
11787 ((DetailsListView)_curTab.Tag).Update();
11789 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
11791 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11792 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11797 private void NotifyEvent(Twitter.FormattedEvent ev)
11800 if (BalloonRequired(ev))
11802 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11803 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11804 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11805 StringBuilder title = new StringBuilder();
11806 if (SettingManager.Common.DispUsername)
11808 title.Append(tw.Username);
11809 title.Append(" - ");
11815 title.Append(Application.ProductName);
11816 title.Append(" [");
11817 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11818 title.Append("] by ");
11819 if (!string.IsNullOrEmpty(ev.Username))
11821 title.Append(ev.Username);
11825 //title.Append("");
11828 if (!string.IsNullOrEmpty(ev.Target))
11830 //NotifyIcon1.BalloonTipText = ev.Target;
11835 //NotifyIcon1.BalloonTipText = " ";
11838 //NotifyIcon1.ShowBalloonTip(500);
11839 if (SettingManager.Common.IsUseNotifyGrowl)
11841 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11842 ev.Id.ToString(), title.ToString(), text);
11846 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11847 NotifyIcon1.BalloonTipTitle = title.ToString();
11848 NotifyIcon1.BalloonTipText = text;
11849 NotifyIcon1.ShowBalloonTip(500);
11854 string snd = SettingManager.Common.EventSoundFile;
11855 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11857 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11861 string dir = Application.StartupPath;
11862 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11864 dir = Path.Combine(dir, "Sounds");
11866 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11878 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11880 MenuItemUserStream.Enabled = false;
11881 if (StopRefreshAllMenuItem.Checked)
11883 StopRefreshAllMenuItem.Checked = false;
11886 if (this.tw.UserStreamActive)
11888 tw.StopUserStream();
11892 tw.StartUserStream();
11896 private static string inputTrack = "";
11898 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11900 if (TrackToolStripMenuItem.Checked)
11902 using (InputTabName inputForm = new InputTabName())
11904 inputForm.TabName = inputTrack;
11905 inputForm.FormTitle = "Input track word";
11906 inputForm.FormDescription = "Track word";
11907 if (inputForm.ShowDialog() != DialogResult.OK)
11909 TrackToolStripMenuItem.Checked = false;
11912 inputTrack = inputForm.TabName.Trim();
11914 if (!inputTrack.Equals(tw.TrackWord))
11916 tw.TrackWord = inputTrack;
11917 this.ModifySettingCommon = true;
11918 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11919 tw.ReconnectUserStream();
11925 tw.ReconnectUserStream();
11927 this.ModifySettingCommon = true;
11930 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11932 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11933 this.ModifySettingCommon = true;
11934 tw.ReconnectUserStream();
11937 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11939 if (evtDialog == null || evtDialog.IsDisposed)
11942 evtDialog = new EventViewerDialog();
11943 evtDialog.Owner = this;
11945 Point pos = evtDialog.Location;
11946 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
11947 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
11948 evtDialog.Location = pos;
11950 evtDialog.EventSource = tw.StoredEvent;
11951 if (!evtDialog.Visible)
11953 evtDialog.Show(this);
11957 evtDialog.Activate();
11959 this.TopMost = SettingManager.Common.AlwaysTop;
11963 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11965 MyCommon._endingFlag = true;
11969 Application.Restart();
11973 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
11977 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
11979 if (!string.IsNullOrEmpty(tw.Username))
11980 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
11983 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11985 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11988 private bool ExistCurrentPost
11992 if (_curPost == null) return false;
11993 if (_curPost.IsDeleted) return false;
11998 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
12000 ShowUserTimeline();
12003 private string GetUserIdFromCurPostOrInput(string caption)
12005 var id = _curPost?.ScreenName ?? "";
12007 using (InputTabName inputName = new InputTabName())
12009 inputName.FormTitle = caption;
12010 inputName.FormDescription = Properties.Resources.FRMessage1;
12011 inputName.TabName = id;
12012 if (inputName.ShowDialog() == DialogResult.OK &&
12013 !string.IsNullOrEmpty(inputName.TabName.Trim()))
12015 id = inputName.TabName.Trim();
12025 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
12027 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
12028 if (!string.IsNullOrEmpty(id))
12030 AddNewTabForUserTimeline(id);
12034 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
12036 string id = GetUserIdFromCurPostOrInput("Show Favstar");
12037 if (!string.IsNullOrEmpty(id))
12039 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
12043 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
12045 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
12048 private void TimelineRefreshEnableChange(bool isEnable)
12052 tw.StartUserStream();
12056 tw.StopUserStream();
12058 TimerTimeline.Enabled = isEnable;
12061 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
12063 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
12066 private async Task OpenUserAppointUrl()
12068 if (SettingManager.Common.UserAppointUrl != null)
12070 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
12072 if (_curPost != null)
12074 string xUrl = SettingManager.Common.UserAppointUrl;
12075 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
12077 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
12078 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
12080 await this.OpenUriInBrowserAsync(xUrl);
12085 await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
12090 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12092 await this.OpenUserAppointUrl();
12095 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
12097 if (Form.ActiveForm == null)
12099 await this.InvokeAsync(() =>
12101 this.Visible = true;
12102 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12104 this.BringToFront();
12105 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
12107 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12111 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12117 private void ReplaceAppName()
12119 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12120 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12123 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12125 this.SplitContainer3.Panel2Collapsed = false;
12128 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12130 await this.OpenThumbnailPicture(e.Thumbnail);
12133 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
12135 await this.OpenUriInBrowserAsync(e.ImageUrl);
12138 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
12140 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
12142 await this.OpenUriInBrowserAsync(url);
12145 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
12147 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
12150 private void PostButton_KeyDown(object sender, KeyEventArgs e)
12152 if (e.KeyCode == Keys.Space)
12154 this.JumpUnreadMenuItem_Click(null, null);
12156 e.SuppressKeyPress = true;
12160 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
12162 this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
12163 this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
12164 this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
12165 this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
12166 this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
12168 this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
12171 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
12173 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
12176 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
12178 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
12181 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
12183 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
12186 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
12188 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
12191 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
12193 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
12196 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
12198 if (SettingManager.Common.IconSize == iconSize) return;
12200 var oldIconCol = _iconCol;
12202 SettingManager.Common.IconSize = iconSize;
12203 ApplyListViewIconSize(iconSize);
12205 if (_iconCol != oldIconCol)
12207 foreach (TabPage tp in ListTab.TabPages)
12209 ResetColumns((DetailsListView)tp.Tag);
12213 _curList?.Refresh();
12215 ModifySettingCommon = true;
12218 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
12220 var state = this.LockListSortOrderToolStripMenuItem.Checked;
12221 if (SettingManager.Common.SortOrderLock == state) return;
12223 SettingManager.Common.SortOrderLock = state;
12225 ModifySettingCommon = true;
12228 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
12230 if (!string.IsNullOrEmpty(e.StatusText))
12232 this.StatusLabelUrl.Text = e.StatusText;
12236 this.SetStatusLabelUrl();