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<StatusTextHistory> _history = new List<StatusTextHistory>(); //発言履歴
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 StatusTextHistory
318 public string status = "";
319 public long? inReplyToId = null;
320 public string inReplyToName = null;
321 public string imageService = ""; //画像投稿サービス名
322 public IMediaItem[] mediaItems = null;
323 public StatusTextHistory()
326 public StatusTextHistory(string status, long? replyToId, string replyToName)
328 this.status = status;
329 this.inReplyToId = replyToId;
330 this.inReplyToName = replyToName;
334 private void TweenMain_Activated(object sender, EventArgs e)
336 //画面がアクティブになったら、発言欄の背景色戻す
337 if (StatusText.Focused)
339 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
343 private bool disposed = false;
346 /// 使用中のリソースをすべてクリーンアップします。
348 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
349 protected override void Dispose(bool disposing)
351 base.Dispose(disposing);
358 this.components?.Dispose();
361 SearchDialog.Dispose();
364 NIconAtRed?.Dispose();
365 NIconAtSmoke?.Dispose();
366 foreach (var iconRefresh in this.NIconRefresh)
368 iconRefresh?.Dispose();
372 ReplyIcon?.Dispose();
373 ReplyIconBlink?.Dispose();
374 _listViewImageList.Dispose();
375 _brsHighLight.Dispose();
376 _brsBackColorMine?.Dispose();
377 _brsBackColorAt?.Dispose();
378 _brsBackColorYou?.Dispose();
379 _brsBackColorAtYou?.Dispose();
380 _brsBackColorAtFromTarget?.Dispose();
381 _brsBackColorAtTo?.Dispose();
382 _brsBackColorNone?.Dispose();
383 _brsDeactiveSelection?.Dispose();
387 this.workerCts.Cancel();
389 if (IconCache != null)
391 this.IconCache.CancelAsync();
392 this.IconCache.Dispose();
395 this.thumbnailTokenSource?.Dispose();
398 this.twitterApi.Dispose();
399 this._hookGlobalHotkey.Dispose();
402 // 終了時にRemoveHandlerしておかないとメモリリークする
403 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
404 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
406 this.disposed = true;
409 private void LoadIcons()
411 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
412 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
415 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
418 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
421 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
424 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
426 // タスクトレイ: オフライン時アイコン
427 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
429 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
430 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
431 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
433 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
434 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
435 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
436 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
437 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
439 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
441 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
442 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
443 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
444 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
445 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
447 if (iconReply != null && iconReplyBlink != null)
449 this.ReplyIcon = iconReply;
450 this.ReplyIconBlink = iconReplyBlink;
454 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
455 this.ReplyIconBlink = this.NIconAt;
458 if (iconRefresh1 == null)
460 this.NIconRefresh = new[] {
461 Properties.Resources.Refresh, Properties.Resources.Refresh2,
462 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
465 else if (iconRefresh2 == null)
467 this.NIconRefresh = new[] { iconRefresh1 };
469 else if (iconRefresh3 == null)
471 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
473 else if (iconRefresh4 == null)
475 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
477 else // iconRefresh1 から iconRefresh4 まで全て揃っている
479 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
483 private Icon LoadIcon(string filePath)
485 if (!File.Exists(filePath))
490 return new Icon(filePath);
498 private void InitColumns(ListView list, bool startup)
500 this.InitColumnText();
502 ColumnHeader[] columns = null;
509 new ColumnHeader(), // アイコン
510 new ColumnHeader(), // 本文
513 columns[0].Text = this.ColumnText[0];
514 columns[1].Text = this.ColumnText[2];
518 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
520 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
521 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
522 columns[0].DisplayIndex = 0;
523 columns[1].DisplayIndex = 1;
528 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
530 columns[idx].Width = curListColumn.Width;
531 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
540 new ColumnHeader(), // アイコン
541 new ColumnHeader(), // ニックネーム
542 new ColumnHeader(), // 本文
543 new ColumnHeader(), // 日付
544 new ColumnHeader(), // ユーザID
545 new ColumnHeader(), // 未読
546 new ColumnHeader(), // マーク&プロテクト
547 new ColumnHeader(), // ソース
550 foreach (var i in Enumerable.Range(0, columns.Length))
551 columns[i].Text = this.ColumnText[i];
555 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
557 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
558 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width2);
559 columns[2].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
560 columns[3].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width4);
561 columns[4].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width5);
562 columns[5].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width6);
563 columns[6].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width7);
564 columns[7].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width8);
566 var displayIndex = new[] {
567 SettingManager.Local.DisplayIndex1, SettingManager.Local.DisplayIndex2,
568 SettingManager.Local.DisplayIndex3, SettingManager.Local.DisplayIndex4,
569 SettingManager.Local.DisplayIndex5, SettingManager.Local.DisplayIndex6,
570 SettingManager.Local.DisplayIndex7, SettingManager.Local.DisplayIndex8
573 foreach (var i in Enumerable.Range(0, displayIndex.Length))
575 columns[i].DisplayIndex = displayIndex[i];
581 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
583 columns[idx].Width = curListColumn.Width;
584 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
590 list.Columns.AddRange(columns);
598 foreach (var column in columns)
604 private void InitColumnText()
607 ColumnText[1] = Properties.Resources.AddNewTabText2;
608 ColumnText[2] = Properties.Resources.AddNewTabText3;
609 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
610 ColumnText[4] = Properties.Resources.AddNewTabText5;
613 ColumnText[7] = "Source";
615 ColumnOrgText[0] = "";
616 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
617 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
618 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
619 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
620 ColumnOrgText[5] = "";
621 ColumnOrgText[6] = "";
622 ColumnOrgText[7] = "Source";
625 switch (_statuses.SortMode)
627 case ComparerMode.Nickname: //ニックネーム
630 case ComparerMode.Data: //本文
633 case ComparerMode.Id: //時刻=発言Id
636 case ComparerMode.Name: //名前
639 case ComparerMode.Source: //Source
646 if (_statuses.SortOrder == SortOrder.Descending)
648 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
649 ColumnText[2] = ColumnOrgText[2] + "▾";
653 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
654 ColumnText[2] = ColumnOrgText[2] + "▴";
659 if (_statuses.SortOrder == SortOrder.Descending)
661 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
662 ColumnText[c] = ColumnOrgText[c] + "▾";
666 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
667 ColumnText[c] = ColumnOrgText[c] + "▴";
672 private void InitializeTraceFrag()
675 TraceOutToolStripMenuItem.Checked = true;
676 MyCommon.TraceFlag = true;
678 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
680 TraceOutToolStripMenuItem.Checked = true;
681 MyCommon.TraceFlag = true;
685 private void TweenMain_Load(object sender, EventArgs e)
687 _ignoreConfigSave = true;
688 this.Visible = false;
690 if (MyApplication.StartupOptions.ContainsKey("d"))
691 MyCommon.TraceFlag = true;
693 InitializeTraceFrag();
695 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
697 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
698 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
700 Regex.CacheSize = 100;
703 _statuses = TabInformations.GetInstance();
707 this.Icon = MainIcon; //メインフォーム(TweenMain)
708 NotifyIcon1.Icon = NIconAt; //タスクトレイ
709 TabImage.Images.Add(TabIcon); //タブ見出し
711 //<<<<<<<<<設定関連>>>>>>>>>
715 // 現在の DPI と設定保存時の DPI との比を取得する
716 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
719 var fontUIGlobal = SettingManager.Local.FontUIGlobal;
720 if (fontUIGlobal != null)
722 OTBaseForm.GlobalFont = fontUIGlobal;
723 this.Font = fontUIGlobal;
727 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
729 if (SettingManager.Common.TimelinePeriod < 15 && SettingManager.Common.TimelinePeriod > 0)
730 SettingManager.Common.TimelinePeriod = 15;
732 if (SettingManager.Common.ReplyPeriod < 15 && SettingManager.Common.ReplyPeriod > 0)
733 SettingManager.Common.ReplyPeriod = 15;
735 if (SettingManager.Common.DMPeriod < 15 && SettingManager.Common.DMPeriod > 0)
736 SettingManager.Common.DMPeriod = 15;
738 if (SettingManager.Common.PubSearchPeriod < 30 && SettingManager.Common.PubSearchPeriod > 0)
739 SettingManager.Common.PubSearchPeriod = 30;
741 if (SettingManager.Common.UserTimelinePeriod < 15 && SettingManager.Common.UserTimelinePeriod > 0)
742 SettingManager.Common.UserTimelinePeriod = 15;
744 if (SettingManager.Common.ListsPeriod < 15 && SettingManager.Common.ListsPeriod > 0)
745 SettingManager.Common.ListsPeriod = 15;
748 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, SettingManager.Common.CountApi))
749 SettingManager.Common.CountApi = 60;
750 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, SettingManager.Common.CountApiReply))
751 SettingManager.Common.CountApiReply = 40;
753 if (SettingManager.Common.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(SettingManager.Common.MoreCountApi))
754 SettingManager.Common.MoreCountApi = 200;
755 if (SettingManager.Common.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(SettingManager.Common.FirstCountApi))
756 SettingManager.Common.FirstCountApi = 100;
758 if (SettingManager.Common.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, SettingManager.Common.FavoritesCountApi))
759 SettingManager.Common.FavoritesCountApi = 40;
760 if (SettingManager.Common.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, SettingManager.Common.ListCountApi))
761 SettingManager.Common.ListCountApi = 100;
762 if (SettingManager.Common.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, SettingManager.Common.SearchCountApi))
763 SettingManager.Common.SearchCountApi = 100;
764 if (SettingManager.Common.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, SettingManager.Common.UserTimelineCountApi))
765 SettingManager.Common.UserTimelineCountApi = 20;
767 //廃止サービスが選択されていた場合ux.nuへ読み替え
768 if (SettingManager.Common.AutoShortUrlFirst < 0)
769 SettingManager.Common.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
771 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
772 this.tw = new Twitter(this.twitterApi);
775 if (string.IsNullOrEmpty(SettingManager.Common.Token)) SettingManager.Common.UserName = "";
776 tw.Initialize(SettingManager.Common.Token, SettingManager.Common.TokenSecret, SettingManager.Common.UserName, SettingManager.Common.UserId);
780 Networking.Initialize();
782 bool saveRequired = false;
783 bool firstRun = false;
785 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
786 if (string.IsNullOrEmpty(tw.Username))
791 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
792 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
793 string.IsNullOrEmpty(tw.Username))
795 Application.Exit(); //強制終了
801 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
802 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
803 Networking.SetWebProxy(SettingManager.Local.ProxyType,
804 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
805 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
806 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
808 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
809 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
810 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
811 tw.TrackWord = SettingManager.Common.TrackWord;
812 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
813 tw.AllAtReply = SettingManager.Common.AllAtReply;
814 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
815 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
816 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
817 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
818 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
820 // アクセストークンが有効であるか確認する
821 // ここが Twitter API への最初のアクセスになるようにすること
824 this.tw.VerifyCredentials();
826 catch (WebApiException ex)
828 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
829 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
833 //プロキシ設定等の通信まわりの初期化が済んでから処理する
834 ThumbnailGenerator.InitializeGenerator();
836 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
837 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
838 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
840 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
843 ImageSelector.Initialize(tw, this.tw.Configuration, SettingManager.Common.UseImageServiceName, SettingManager.Common.UseImageService);
846 AtIdSupl = new AtIdSupplement(SettingManager.AtIdList.AtIdList, "@");
847 HashSupl = new AtIdSupplement(SettingManager.Common.HashTags, "#");
848 HashMgr = new HashtagManage(HashSupl,
849 SettingManager.Common.HashTags.ToArray(),
850 SettingManager.Common.HashSelected,
851 SettingManager.Common.HashIsPermanent,
852 SettingManager.Common.HashIsHead,
853 SettingManager.Common.HashIsNotAddToAtReply);
854 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
857 this.IconCache = new ImageCache();
858 this.tweetDetailsView.IconCache = this.IconCache;
861 _fntUnread = SettingManager.Local.FontUnread;
862 _clUnread = SettingManager.Local.ColorUnread;
863 _fntReaded = SettingManager.Local.FontRead;
864 _clReaded = SettingManager.Local.ColorRead;
865 _clFav = SettingManager.Local.ColorFav;
866 _clOWL = SettingManager.Local.ColorOWL;
867 _clRetweet = SettingManager.Local.ColorRetweet;
868 _fntDetail = SettingManager.Local.FontDetail;
869 _clDetail = SettingManager.Local.ColorDetail;
870 _clDetailLink = SettingManager.Local.ColorDetailLink;
871 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
872 _clSelf = SettingManager.Local.ColorSelf;
873 _clAtSelf = SettingManager.Local.ColorAtSelf;
874 _clTarget = SettingManager.Local.ColorTarget;
875 _clAtTarget = SettingManager.Local.ColorAtTarget;
876 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
877 _clAtTo = SettingManager.Local.ColorAtTo;
878 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
879 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
880 _clInputFont = SettingManager.Local.ColorInputFont;
881 _fntInputFont = SettingManager.Local.FontInputFont;
883 _brsBackColorMine = new SolidBrush(_clSelf);
884 _brsBackColorAt = new SolidBrush(_clAtSelf);
885 _brsBackColorYou = new SolidBrush(_clTarget);
886 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
887 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
888 _brsBackColorAtTo = new SolidBrush(_clAtTo);
889 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
890 _brsBackColorNone = new SolidBrush(_clListBackcolor);
892 // StringFormatオブジェクトへの事前設定
893 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
894 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
895 //sf.FormatFlags = StringFormatFlags.LineLimit; //
896 sfTab.Alignment = StringAlignment.Center;
897 sfTab.LineAlignment = StringAlignment.Center;
899 InitDetailHtmlFormat();
901 //Regex statregex = new Regex("^0*");
902 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
904 _history.Add(new StatusTextHistory());
906 this.inReplyTo = null;
909 SearchDialog.Owner = this;
910 UrlDialog.Owner = this;
913 NewPostPopMenuItem.Checked = SettingManager.Common.NewAllPop;
914 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
916 //新着取得時のリストスクロールをするか。trueならスクロールしない
917 ListLockMenuItem.Checked = SettingManager.Common.ListLock;
918 this.LockListFileMenuItem.Checked = SettingManager.Common.ListLock;
920 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
921 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
924 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
925 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
926 _myLoc = SettingManager.Local.FormLocation;
928 if (this.WindowState != FormWindowState.Minimized)
930 Rectangle tbarRect = new Rectangle(this._myLoc, new Size(_mySize.Width, SystemInformation.CaptionHeight));
931 bool outOfScreen = true;
932 if (Screen.AllScreens.Length == 1) //ハングするとの報告
934 foreach (Screen scr in Screen.AllScreens)
936 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
944 this._myLoc = new Point(0, 0);
946 this.DesktopLocation = this._myLoc;
948 this.TopMost = SettingManager.Common.AlwaysTop;
949 _mySpDis = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
950 _mySpDis2 = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
951 if (SettingManager.Local.PreviewDistance == -1)
953 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
954 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
955 SettingManager.Local.PreviewDistance = _mySpDis3;
959 _mySpDis3 = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
961 //this.Tween_ClientSizeChanged(this, null);
962 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
963 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
965 StatusText.Font = _fntInputFont;
966 StatusText.ForeColor = _clInputFont;
968 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
969 this.StatusText.Multiline = false; // SettingManager.Local.StatusMultiline の設定は後で反映される
970 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
972 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
973 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
975 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
976 if (SettingManager.Common.UnreadManage == false)
978 ReadedStripMenuItem.Enabled = false;
979 UnreadStripMenuItem.Enabled = false;
982 //リンク先URL表示部の初期化(画面左下)
983 StatusLabelUrl.Text = "";
985 StatusLabel.Text = "";
986 StatusLabel.AutoToolTip = false;
987 StatusLabel.ToolTipText = "";
989 lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
991 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
992 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
993 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
994 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
996 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
997 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
998 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
999 this.SplitContainer2.Panel2.AccessibleName = "";
1001 ////////////////////////////////////////////////////////////////////////////////
1002 var sortOrder = (SortOrder)SettingManager.Common.SortOrder;
1003 var mode = ComparerMode.Id;
1004 switch (SettingManager.Common.SortColumn)
1006 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1010 mode = ComparerMode.Id; //Idソートに読み替え
1013 mode = ComparerMode.Nickname;
1016 mode = ComparerMode.Data;
1019 mode = ComparerMode.Id;
1022 mode = ComparerMode.Name;
1025 mode = ComparerMode.Source;
1028 _statuses.SetSortMode(mode, sortOrder);
1029 ////////////////////////////////////////////////////////////////////////////////
1031 ApplyListViewIconSize(SettingManager.Common.IconSize);
1033 //<<<<<<<<タブ関連>>>>>>>
1037 //デフォルトタブの存在チェック、ない場合には追加
1038 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1039 this._statuses.AddTab(new HomeTabModel());
1041 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1042 this._statuses.AddTab(new MentionsTabModel());
1044 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1045 this._statuses.AddTab(new DirectMessagesTabModel());
1047 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1048 this._statuses.AddTab(new FavoritesTabModel());
1050 if (this._statuses.GetTabByType<MuteTabModel>() == null)
1051 this._statuses.AddTab(new MuteTabModel());
1053 foreach (var tab in _statuses.Tabs.Values)
1056 if (tab.TabType == MyCommon.TabUsageType.Mute)
1059 if (!AddNewTab(tab, startup: true))
1060 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1063 _curTab = ListTab.SelectedTab;
1065 _curList = (DetailsListView)_curTab.Tag;
1067 if (SettingManager.Common.TabIconDisp)
1069 ListTab.DrawMode = TabDrawMode.Normal;
1073 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1074 ListTab.DrawItem += ListTab_DrawItem;
1075 ListTab.ImageList = null;
1078 if (SettingManager.Common.HotkeyEnabled)
1081 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1082 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
1083 modKey |= HookGlobalHotkey.ModKeys.Alt;
1084 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
1085 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1086 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
1087 modKey |= HookGlobalHotkey.ModKeys.Shift;
1088 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
1089 modKey |= HookGlobalHotkey.ModKeys.Win;
1091 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
1094 if (SettingManager.Common.IsUseNotifyGrowl)
1097 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1099 SetMainWindowTitle();
1100 SetNotifyIconText();
1102 if (!SettingManager.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1104 this.Visible = true;
1108 TimerTimeline.AutoReset = true;
1109 TimerTimeline.SynchronizingObject = this;
1111 TimerTimeline.Interval = 1000;
1112 TimerTimeline.Enabled = true;
1114 TimerRefreshIcon.Interval = 200;
1115 TimerRefreshIcon.Enabled = true;
1117 _ignoreConfigSave = false;
1118 this.TweenMain_Resize(null, null);
1119 if (saveRequired) SaveConfigsAll(false);
1121 foreach (var ua in SettingManager.Common.UserAccounts)
1123 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1125 ua.UserId = tw.UserId;
1132 // 初回起動時だけ右下のメニューを目立たせる
1133 HashStripSplitButton.ShowDropDown();
1137 private void InitDetailHtmlFormat()
1139 if (SettingManager.Common.IsMonospace)
1141 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1142 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1146 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1147 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1150 detailHtmlFormatHeader = detailHtmlFormatHeader
1151 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1152 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1153 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1154 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1155 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1156 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1159 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1164 txt = ListTab.TabPages[e.Index].Text;
1171 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1172 if (e.State == DrawItemState.Selected)
1174 e.DrawFocusRectangle();
1179 if (_statuses.Tabs[txt].UnreadCount > 0)
1182 fore = System.Drawing.SystemBrushes.ControlText;
1186 fore = System.Drawing.SystemBrushes.ControlText;
1188 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1191 private void LoadConfig()
1193 SettingManager.Local = SettingManager.Local;
1195 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1196 if (SettingManager.Local.ScaleDimension.IsEmpty)
1197 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
1199 var tabSettings = SettingManager.Tabs;
1200 foreach (var tabSetting in tabSettings.Tabs)
1203 switch (tabSetting.TabType)
1205 case MyCommon.TabUsageType.Home:
1206 tab = new HomeTabModel(tabSetting.TabName);
1208 case MyCommon.TabUsageType.Mentions:
1209 tab = new MentionsTabModel(tabSetting.TabName);
1211 case MyCommon.TabUsageType.DirectMessage:
1212 tab = new DirectMessagesTabModel(tabSetting.TabName);
1214 case MyCommon.TabUsageType.Favorites:
1215 tab = new FavoritesTabModel(tabSetting.TabName);
1217 case MyCommon.TabUsageType.UserDefined:
1218 tab = new FilterTabModel(tabSetting.TabName);
1220 case MyCommon.TabUsageType.UserTimeline:
1221 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1223 case MyCommon.TabUsageType.PublicSearch:
1224 tab = new PublicSearchTabModel(tabSetting.TabName)
1226 SearchWords = tabSetting.SearchWords,
1227 SearchLang = tabSetting.SearchLang,
1230 case MyCommon.TabUsageType.Lists:
1231 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1233 case MyCommon.TabUsageType.Mute:
1234 tab = new MuteTabModel(tabSetting.TabName);
1240 tab.UnreadManage = tabSetting.UnreadManage;
1241 tab.Protected = tabSetting.Protected;
1242 tab.Notify = tabSetting.Notify;
1243 tab.SoundFile = tabSetting.SoundFile;
1245 if (tab.IsDistributableTabType)
1247 var filterTab = (FilterTabModel)tab;
1248 filterTab.FilterArray = tabSetting.FilterArray;
1249 filterTab.FilterModified = false;
1252 if (this._statuses.ContainsTab(tab.TabName))
1253 tab.TabName = this._statuses.MakeTabName("MyTab");
1255 this._statuses.AddTab(tab);
1257 if (_statuses.Tabs.Count == 0)
1259 _statuses.AddTab(new HomeTabModel());
1260 _statuses.AddTab(new MentionsTabModel());
1261 _statuses.AddTab(new DirectMessagesTabModel());
1262 _statuses.AddTab(new FavoritesTabModel());
1266 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1268 if (!TimerTimeline.Enabled) return;
1272 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1274 private static int homeCounter = 0;
1275 private static int mentionCounter = 0;
1276 private static int dmCounter = 0;
1277 private static int pubSearchCounter = 0;
1278 private static int userTimelineCounter = 0;
1279 private static int listsCounter = 0;
1280 private static int usCounter = 0;
1281 private static int ResumeWait = 0;
1282 private static int refreshFollowers = 0;
1284 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1286 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1287 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1288 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1289 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1290 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1291 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1292 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1293 Interlocked.Increment(ref refreshFollowers);
1295 var refreshTasks = new List<Task>();
1298 if (ResetTimers.Timeline || homeCounter <= 0 && SettingManager.Common.TimelinePeriod > 0)
1300 Interlocked.Exchange(ref homeCounter, SettingManager.Common.TimelinePeriod);
1301 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1302 refreshTasks.Add(this.GetHomeTimelineAsync());
1303 ResetTimers.Timeline = false;
1305 if (ResetTimers.Reply || mentionCounter <= 0 && SettingManager.Common.ReplyPeriod > 0)
1307 Interlocked.Exchange(ref mentionCounter, SettingManager.Common.ReplyPeriod);
1308 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1309 refreshTasks.Add(this.GetReplyAsync());
1310 ResetTimers.Reply = false;
1312 if (ResetTimers.DirectMessage || dmCounter <= 0 && SettingManager.Common.DMPeriod > 0)
1314 Interlocked.Exchange(ref dmCounter, SettingManager.Common.DMPeriod);
1315 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1316 refreshTasks.Add(this.GetDirectMessagesAsync());
1317 ResetTimers.DirectMessage = false;
1319 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && SettingManager.Common.PubSearchPeriod > 0)
1321 Interlocked.Exchange(ref pubSearchCounter, SettingManager.Common.PubSearchPeriod);
1322 if (!ResetTimers.PublicSearch)
1323 refreshTasks.Add(this.GetPublicSearchAllAsync());
1324 ResetTimers.PublicSearch = false;
1326 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && SettingManager.Common.UserTimelinePeriod > 0)
1328 Interlocked.Exchange(ref userTimelineCounter, SettingManager.Common.UserTimelinePeriod);
1329 if (!ResetTimers.UserTimeline)
1330 refreshTasks.Add(this.GetUserTimelineAllAsync());
1331 ResetTimers.UserTimeline = false;
1333 if (ResetTimers.Lists || listsCounter <= 0 && SettingManager.Common.ListsPeriod > 0)
1335 Interlocked.Exchange(ref listsCounter, SettingManager.Common.ListsPeriod);
1336 if (!ResetTimers.Lists)
1337 refreshTasks.Add(this.GetListTimelineAllAsync());
1338 ResetTimers.Lists = false;
1340 if (ResetTimers.UserStream || usCounter <= 0 && SettingManager.Common.UserstreamPeriod > 0)
1342 Interlocked.Exchange(ref usCounter, SettingManager.Common.UserstreamPeriod);
1343 if (this.tw.UserStreamActive)
1344 this.RefreshTimeline();
1345 ResetTimers.UserStream = false;
1347 if (refreshFollowers > 6 * 3600)
1349 Interlocked.Exchange(ref refreshFollowers, 0);
1350 refreshTasks.AddRange(new[]
1352 this.doGetFollowersMenu(),
1353 this.RefreshNoRetweetIdsAsync(),
1354 this.RefreshTwitterConfigurationAsync(),
1359 Interlocked.Increment(ref ResumeWait);
1360 if (ResumeWait > 30)
1363 Interlocked.Exchange(ref ResumeWait, 0);
1364 refreshTasks.AddRange(new[]
1366 this.GetHomeTimelineAsync(),
1367 this.GetReplyAsync(),
1368 this.GetDirectMessagesAsync(),
1369 this.GetPublicSearchAllAsync(),
1370 this.GetUserTimelineAllAsync(),
1371 this.GetListTimelineAllAsync(),
1372 this.doGetFollowersMenu(),
1373 this.RefreshTwitterConfigurationAsync(),
1378 await Task.WhenAll(refreshTasks);
1381 private void RefreshTimeline()
1383 var curTabModel = this._statuses.Tabs[this._curTab.Text];
1385 // 現在表示中のタブのスクロール位置を退避
1386 var curListScroll = this.SaveListViewScroll(this._curList, curTabModel);
1388 // 各タブのリスト上の選択位置などを退避
1389 var listSelections = this.SaveListViewSelection();
1393 addCount = _statuses.SubmitUpdate(out var soundFile, out var notifyPosts,
1394 out var newMentionOrDm, out var isDelete);
1396 if (MyCommon._endingFlag) return;
1399 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1401 var listView = (DetailsListView)tabPage.Tag;
1402 var tabModel = this._statuses.Tabs[tabPage.Text];
1404 if (listView.VirtualListSize != tabModel.AllCount || isDelete)
1406 using (ControlTransaction.Update(listView))
1408 if (listView == this._curList)
1409 this.PurgeListViewItemCache();
1414 listView.VirtualListSize = tabModel.AllCount;
1416 catch (NullReferenceException ex)
1418 // WinForms 内部で ListView.set_TopItem が発生させている例外
1419 // https://ja.osdn.net/ticket/browse.php?group_id=6526&tid=36588
1420 MyCommon.TraceOut(ex, $"TabType: {tabModel.TabType}, Count: {tabModel.AllCount}, ListSize: {listView.VirtualListSize}");
1424 this.RestoreListViewSelection(listView, tabModel, listSelections[tabModel.TabName]);
1431 if (SettingManager.Common.TabIconDisp)
1433 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1435 var tabModel = this._statuses.Tabs[tabPage.Text];
1436 if (tabModel.UnreadCount > 0 && tabPage.ImageIndex != 0)
1437 tabPage.ImageIndex = 0; // 未読アイコン
1442 this.ListTab.Refresh();
1447 this.RestoreListViewScroll(this._curList, curTabModel, curListScroll);
1450 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1452 SetMainWindowTitle();
1453 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1455 HashSupl.AddRangeItem(tw.GetHashList());
1459 internal struct ListViewScroll
1461 public ScrollLockMode ScrollLockMode { get; set; }
1462 public long? TopItemStatusId { get; set; }
1465 internal enum ScrollLockMode
1467 /// <summary>固定しない</summary>
1470 /// <summary>最上部に固定する</summary>
1473 /// <summary>最下部に固定する</summary>
1476 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1481 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1483 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1485 var listScroll = new ListViewScroll
1487 ScrollLockMode = this.GetScrollLockMode(listView),
1490 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1492 var topItemIndex = listView.TopItem?.Index ?? -1;
1493 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
1494 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItemIndex);
1500 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1502 if (this._statuses.SortMode == ComparerMode.Id)
1504 if (this._statuses.SortOrder == SortOrder.Ascending)
1507 if (this.ListLockMenuItem.Checked)
1508 return ScrollLockMode.None;
1510 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1513 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1514 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1515 return ScrollLockMode.FixedToBottom;
1517 return ScrollLockMode.None;
1522 if (this.ListLockMenuItem.Checked)
1523 return ScrollLockMode.FixedToItem;
1525 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1526 var topItem = listView.TopItem;
1527 if (topItem == null || topItem.Index == 0)
1528 return ScrollLockMode.FixedToTop;
1530 return ScrollLockMode.FixedToItem;
1535 return ScrollLockMode.FixedToItem;
1539 internal struct ListViewSelection
1541 public long[] SelectedStatusIds { get; set; }
1542 public long? SelectionMarkStatusId { get; set; }
1543 public long? FocusedStatusId { get; set; }
1547 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1549 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1551 var listsDict = new Dictionary<string, ListViewSelection>();
1553 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1555 var listView = (DetailsListView)tabPage.Tag;
1556 var tab = _statuses.Tabs[tabPage.Text];
1558 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1565 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1567 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1569 if (listView.VirtualListSize == 0)
1571 return new ListViewSelection
1573 SelectedStatusIds = new long[0],
1574 SelectionMarkStatusId = null,
1575 FocusedStatusId = null,
1579 return new ListViewSelection
1581 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1582 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1583 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1587 private long[] GetSelectedStatusIds(DetailsListView listView, TabModel tab)
1589 var selectedIndices = listView.SelectedIndices;
1590 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1591 return tab.GetStatusIdAt(selectedIndices.Cast<int>());
1596 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1598 var index = listView.FocusedItem?.Index ?? -1;
1600 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1603 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1605 var index = listView.SelectionMark;
1607 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1611 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1613 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1615 if (listView.VirtualListSize == 0)
1618 switch (listScroll.ScrollLockMode)
1620 case ScrollLockMode.FixedToTop:
1621 listView.EnsureVisible(0);
1623 case ScrollLockMode.FixedToBottom:
1624 listView.EnsureVisible(listView.VirtualListSize - 1);
1626 case ScrollLockMode.FixedToItem:
1627 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1630 var topItem = listView.Items[topIndex];
1633 listView.TopItem = topItem;
1635 catch (NullReferenceException)
1637 listView.EnsureVisible(listView.VirtualListSize - 1);
1638 listView.EnsureVisible(topIndex);
1642 case ScrollLockMode.None:
1649 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1651 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1653 // status_id から ListView 上のインデックスに変換
1654 int[] selectedIndices = null;
1655 if (listSelection.SelectedStatusIds != null)
1656 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1658 var focusedIndex = -1;
1659 if (listSelection.FocusedStatusId != null)
1660 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1662 var selectionMarkIndex = -1;
1663 if (listSelection.SelectionMarkStatusId != null)
1664 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1666 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1669 private bool BalloonRequired()
1671 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1672 ev.Eventtype = MyCommon.EVENTTYPE.None;
1674 return BalloonRequired(ev);
1677 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1679 if (type == MyCommon.EVENTTYPE.None)
1682 if (!SettingManager.Common.EventNotifyEnabled)
1685 return SettingManager.Common.EventNotifyFlag.HasFlag(type);
1688 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1693 return SettingManager.Common.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1696 private bool BalloonRequired(Twitter.FormattedEvent ev)
1701 if (NativeMethods.IsScreenSaverRunning())
1705 if (!this.NewPostPopMenuItem.Checked)
1707 // 「新着通知が無効でもイベントを通知する」にも該当しない
1708 if (!SettingManager.Common.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1712 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1713 if (SettingManager.Common.LimitBalloon)
1715 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1719 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1722 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1724 if (SettingManager.Common.ReadOwnPost)
1726 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1731 if (BalloonRequired())
1733 if (notifyPosts != null && notifyPosts.Length > 0)
1735 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1736 if (SettingManager.Common.IsUseNotifyGrowl)
1738 StringBuilder sb = new StringBuilder();
1742 foreach (PostClass post in notifyPosts)
1744 if (!(notifyPosts.Length > 3))
1750 if (post.IsReply && !post.IsExcludeReply) reply = true;
1751 if (post.IsDm) dm = true;
1752 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1753 switch (SettingManager.Common.NameBalloon)
1755 case MyCommon.NameBalloonEnum.UserID:
1756 sb.Append(post.ScreenName).Append(" : ");
1758 case MyCommon.NameBalloonEnum.NickName:
1759 sb.Append(post.Nickname).Append(" : ");
1762 sb.Append(post.TextFromApi);
1763 if (notifyPosts.Length > 3)
1765 if (notifyPosts.Last() != post) continue;
1768 StringBuilder title = new StringBuilder();
1769 GrowlHelper.NotifyType nt;
1770 if (SettingManager.Common.DispUsername)
1772 title.Append(tw.Username);
1773 title.Append(" - ");
1781 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1782 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1783 title.Append(Application.ProductName);
1784 title.Append(" [DM] ");
1785 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1786 nt = GrowlHelper.NotifyType.DirectMessage;
1790 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1791 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1792 title.Append(Application.ProductName);
1793 title.Append(" [Reply!] ");
1794 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1795 nt = GrowlHelper.NotifyType.Reply;
1799 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1800 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1801 title.Append(Application.ProductName);
1803 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1804 nt = GrowlHelper.NotifyType.Notify;
1806 string bText = sb.ToString();
1807 if (string.IsNullOrEmpty(bText)) return;
1809 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1810 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1815 StringBuilder sb = new StringBuilder();
1818 foreach (PostClass post in notifyPosts)
1820 if (post.IsReply && !post.IsExcludeReply) reply = true;
1821 if (post.IsDm) dm = true;
1822 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1823 switch (SettingManager.Common.NameBalloon)
1825 case MyCommon.NameBalloonEnum.UserID:
1826 sb.Append(post.ScreenName).Append(" : ");
1828 case MyCommon.NameBalloonEnum.NickName:
1829 sb.Append(post.Nickname).Append(" : ");
1832 sb.Append(post.TextFromApi);
1835 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1836 StringBuilder title = new StringBuilder();
1838 if (SettingManager.Common.DispUsername)
1840 title.Append(tw.Username);
1841 title.Append(" - ");
1849 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1850 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1851 ntIcon = ToolTipIcon.Warning;
1852 title.Append(Application.ProductName);
1853 title.Append(" [DM] ");
1854 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1858 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1859 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1860 ntIcon = ToolTipIcon.Warning;
1861 title.Append(Application.ProductName);
1862 title.Append(" [Reply!] ");
1863 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1867 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1868 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1869 ntIcon = ToolTipIcon.Info;
1870 title.Append(Application.ProductName);
1872 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1874 string bText = sb.ToString();
1875 if (string.IsNullOrEmpty(bText)) return;
1876 //NotifyIcon1.BalloonTipText = sb.ToString();
1877 //NotifyIcon1.ShowBalloonTip(500);
1878 NotifyIcon1.BalloonTipTitle = title.ToString();
1879 NotifyIcon1.BalloonTipText = bText;
1880 NotifyIcon1.BalloonTipIcon = ntIcon;
1881 NotifyIcon1.ShowBalloonTip(500);
1887 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(soundFile))
1891 string dir = Application.StartupPath;
1892 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1894 dir = Path.Combine(dir, "Sounds");
1896 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1906 //mentions新着時に画面ブリンク
1907 if (!_initial && SettingManager.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1909 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1913 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1915 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1917 _curItemIndex = _curList.SelectedIndices[0];
1918 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1922 this._curPost = GetCurTabPost(_curItemIndex);
1924 catch (ArgumentException)
1929 this.PushSelectPostChain();
1931 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1933 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1939 private void ChangeCacheStyleRead(bool Read, int Index)
1941 var tabInfo = _statuses.Tabs[_curTab.Text];
1942 //Read:true=既読 false=未読
1943 //未読管理していなかったら既読として扱う
1944 if (!tabInfo.UnreadManage ||
1945 !SettingManager.Common.UnreadManage) Read = true;
1947 var listCache = this._listItemCache;
1948 if (listCache == null)
1951 // キャッシュに含まれていないアイテムは対象外
1952 if (!listCache.TryGetValue(Index, out var itm, out var post))
1955 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1958 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1965 Item.SubItems[5].Text = "";
1970 Item.SubItems[5].Text = "★";
1976 else if (Post.RetweetedId != null)
1978 else if (Post.IsOwl && (Post.IsDm || SettingManager.Common.OneWayLove))
1980 else if (Read || !SettingManager.Common.UseUnreadStyle)
1985 if (DList == null || Item.Index == -1)
1987 Item.ForeColor = cl;
1988 if (SettingManager.Common.UseUnreadStyle)
1994 if (SettingManager.Common.UseUnreadStyle)
1995 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1997 DList.ChangeItemForeColor(Item.Index, cl);
1998 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2002 private void ColorizeList()
2004 //Index:更新対象のListviewItem.Index。Colorを返す。
2005 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2008 _post = _anchorPost;
2012 if (_post == null) return;
2014 var listCache = this._listItemCache;
2015 if (listCache == null)
2018 var index = listCache.StartIndex;
2019 foreach (var cachedPost in listCache.Post)
2021 var backColor = this.JudgeColor(_post, cachedPost);
2022 this._curList.ChangeItemBackColor(index++, backColor);
2026 private void ColorizeList(ListViewItem Item, int Index)
2028 //Index:更新対象のListviewItem.Index。Colorを返す。
2029 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2032 _post = _anchorPost;
2036 PostClass tPost = GetCurTabPost(Index);
2038 if (_post == null) return;
2040 if (Item.Index == -1)
2041 Item.BackColor = JudgeColor(_post, tPost);
2043 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2046 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2049 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2052 else if (TargetPost.IsMe)
2055 else if (TargetPost.IsReply)
2058 else if (BasePost.ReplyToList.Any(x => x.Item1 == TargetPost.UserId))
2060 cl = _clAtFromTarget;
2061 else if (TargetPost.ReplyToList.Any(x => x.Item1 == BasePost.UserId))
2064 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2069 cl = _clListBackcolor;
2074 private async void PostButton_Click(object sender, EventArgs e)
2076 if (StatusText.Text.Trim().Length == 0)
2078 if (!ImageSelector.Enabled)
2080 await this.DoRefresh();
2085 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2087 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2089 MessageBoxButtons.YesNoCancel,
2090 MessageBoxIcon.Question);
2093 case DialogResult.Yes:
2094 StatusText.Text = "";
2095 await this.doReTweetOfficial(false);
2097 case DialogResult.Cancel:
2102 var inReplyToStatusId = this.inReplyTo?.Item1;
2103 var inReplyToScreenName = this.inReplyTo?.Item2;
2104 _history[_history.Count - 1] = new StatusTextHistory(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2106 if (SettingManager.Common.Nicoms)
2108 StatusText.SelectionStart = StatusText.Text.Length;
2109 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2111 //if (SettingDialog.UrlConvertAuto)
2113 // StatusText.SelectionStart = StatusText.Text.Length;
2114 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2116 //else if (SettingDialog.Nicoms)
2118 // StatusText.SelectionStart = StatusText.Text.Length;
2119 // UrlConvert(UrlConverter.Nicoms);
2121 StatusText.SelectionStart = StatusText.Text.Length;
2122 CheckReplyTo(StatusText.Text);
2124 var statusText = this.StatusText.Text;
2126 long[] autoPopulatedUserIds;
2127 string attachmentUrl;
2128 statusText = this.FormatStatusTextExtended(statusText, out autoPopulatedUserIds, out attachmentUrl);
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 PostStatusParams
2141 InReplyToStatusId = this.inReplyTo?.Item1,
2144 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Item1] : null;
2145 if (replyToPost != null && !status.Text.Contains("RT @"))
2147 status.AutoPopulateReplyMetadata = true;
2149 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
2150 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.Item1).Except(autoPopulatedUserIds)
2154 status.AttachmentUrl = attachmentUrl;
2156 IMediaUploadService uploadService = null;
2157 IMediaItem[] uploadItems = null;
2158 if (ImageSelector.Visible)
2162 if (!ImageSelector.TryGetSelectedMedia(out serviceName, out uploadItems))
2165 uploadService = this.ImageSelector.GetService(serviceName);
2168 this.inReplyTo = null;
2169 StatusText.Text = "";
2170 _history.Add(new StatusTextHistory());
2171 _hisIdx = _history.Count - 1;
2172 if (!SettingManager.Common.FocusLockToStatusText)
2173 ((Control)ListTab.SelectedTab.Tag).Focus();
2174 urlUndoBuffer = null;
2175 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2178 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2180 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2181 await this.OpenUriInBrowserAsync(tmp);
2184 await this.PostMessageAsync(status, uploadService, uploadItems);
2187 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2189 MyCommon._endingFlag = true;
2193 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2195 if (!SettingManager.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2197 //_endingFlag=false:フォームの×ボタン
2199 this.Visible = false;
2203 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2204 _ignoreConfigSave = true;
2205 MyCommon._endingFlag = true;
2206 TimerTimeline.Enabled = false;
2207 TimerRefreshIcon.Enabled = false;
2211 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2213 this.Visible = true;
2214 if (this.WindowState == FormWindowState.Minimized)
2216 this.WindowState = FormWindowState.Normal;
2219 this.BringToFront();
2222 private static int errorCount = 0;
2224 private static bool CheckAccountValid()
2226 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2232 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2241 private Task GetHomeTimelineAsync()
2243 return this.GetHomeTimelineAsync(loadMore: false);
2246 private async Task GetHomeTimelineAsync(bool loadMore)
2248 await this.workerSemaphore.WaitAsync();
2252 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
2253 await homeTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2255 this.RefreshTimeline();
2257 catch (WebApiException ex)
2259 this._myStatusError = true;
2260 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2264 this.workerSemaphore.Release();
2268 private Task GetReplyAsync()
2270 return this.GetReplyAsync(loadMore: false);
2273 private async Task GetReplyAsync(bool loadMore)
2275 await this.workerSemaphore.WaitAsync();
2279 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
2280 await replyTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2282 this.RefreshTimeline();
2284 catch (WebApiException ex)
2286 this._myStatusError = true;
2287 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2291 this.workerSemaphore.Release();
2295 private Task GetDirectMessagesAsync()
2297 return this.GetDirectMessagesAsync(loadMore: false);
2300 private async Task GetDirectMessagesAsync(bool loadMore)
2302 await this.workerSemaphore.WaitAsync();
2306 var dmTab = this._statuses.GetTabByType<DirectMessagesTabModel>();
2307 await dmTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2309 this.RefreshTimeline();
2311 catch (WebApiException ex)
2313 this._myStatusError = true;
2314 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2318 this.workerSemaphore.Release();
2322 private Task GetFavoritesAsync()
2324 return this.GetFavoritesAsync(loadMore: false);
2327 private async Task GetFavoritesAsync(bool loadMore)
2329 await this.workerSemaphore.WaitAsync();
2333 var favTab = this._statuses.GetTabByType<FavoritesTabModel>();
2334 await favTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2336 this.RefreshTimeline();
2338 catch (WebApiException ex)
2340 this._myStatusError = true;
2341 this.StatusLabel.Text = ex.Message;
2345 this.workerSemaphore.Release();
2349 private Task GetPublicSearchAllAsync()
2351 var tabs = this._statuses.GetTabsByType<PublicSearchTabModel>();
2353 return this.GetPublicSearchAsync(tabs, loadMore: false);
2356 private Task GetPublicSearchAsync(PublicSearchTabModel tab)
2358 return this.GetPublicSearchAsync(tab, loadMore: false);
2361 private Task GetPublicSearchAsync(PublicSearchTabModel tab, bool loadMore)
2363 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2366 private async Task GetPublicSearchAsync(IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2368 await this.workerSemaphore.WaitAsync();
2372 foreach (var tab in tabs)
2376 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2378 catch (WebApiException ex)
2380 this._myStatusError = true;
2381 this.StatusLabel.Text = $"Err:{ex.Message}(GetSearch)";
2385 this.RefreshTimeline();
2389 this.workerSemaphore.Release();
2393 private Task GetUserTimelineAllAsync()
2395 var tabs = this._statuses.GetTabsByType<UserTimelineTabModel>();
2397 return this.GetUserTimelineAsync(tabs, loadMore: false);
2400 private Task GetUserTimelineAsync(UserTimelineTabModel tab)
2402 return this.GetUserTimelineAsync(tab, loadMore: false);
2405 private Task GetUserTimelineAsync(UserTimelineTabModel tab, bool loadMore)
2407 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2410 private async Task GetUserTimelineAsync(IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2412 await this.workerSemaphore.WaitAsync();
2416 foreach (var tab in tabs)
2420 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2422 catch (WebApiException ex)
2424 this._myStatusError = true;
2425 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2429 this.RefreshTimeline();
2433 this.workerSemaphore.Release();
2437 private Task GetListTimelineAllAsync()
2439 var tabs = this._statuses.GetTabsByType<ListTimelineTabModel>();
2441 return this.GetListTimelineAsync(tabs, loadMore: false);
2444 private Task GetListTimelineAsync(ListTimelineTabModel tab)
2446 return this.GetListTimelineAsync(tab, loadMore: false);
2449 private Task GetListTimelineAsync(ListTimelineTabModel tab, bool loadMore)
2451 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2454 private async Task GetListTimelineAsync(IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2456 await this.workerSemaphore.WaitAsync();
2460 foreach (var tab in tabs)
2464 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2466 catch (WebApiException ex)
2468 this._myStatusError = true;
2469 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2473 this.RefreshTimeline();
2477 this.workerSemaphore.Release();
2481 private async Task GetRelatedTweetsAsync(RelatedPostsTabModel tab)
2483 await this.workerSemaphore.WaitAsync();
2487 await tab.RefreshAsync(this.tw, this._initial, this.workerProgress);
2489 this.RefreshTimeline();
2491 catch (WebApiException ex)
2493 this._myStatusError = true;
2494 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2498 this.workerSemaphore.Release();
2502 private async Task FavAddAsync(long statusId, TabModel tab)
2504 await this.workerSemaphore.WaitAsync();
2508 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2510 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2512 catch (WebApiException ex)
2514 this._myStatusError = true;
2515 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2519 this.workerSemaphore.Release();
2523 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2525 if (ct.IsCancellationRequested)
2528 if (!CheckAccountValid())
2529 throw new WebApiException("Auth error. Check your account");
2531 if (!tab.Posts.TryGetValue(statusId, out var post))
2537 await Task.Run(async () =>
2539 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2545 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2547 .ConfigureAwait(false);
2549 catch (TwitterApiException ex)
2550 when (ex.ErrorResponse.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
2552 // エラーコード 139 のみの場合は成功と見なす
2555 if (SettingManager.Common.RestrictFavCheck)
2557 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2558 .ConfigureAwait(false);
2560 if (status.Favorited != true)
2561 throw new WebApiException("NG(Restricted?)");
2564 this._favTimestamps.Add(DateTime.Now);
2567 if (this._statuses.ContainsKey(statusId))
2569 var postTl = this._statuses[statusId];
2570 postTl.IsFav = true;
2572 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2573 favTab.AddPostQueue(postTl);
2576 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2577 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2579 if (tb.Contains(statusId))
2580 tb.Posts[statusId].IsFav = true;
2583 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2585 catch (WebApiException)
2587 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2592 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2593 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2595 if (this._favTimestamps[i] < oneHour)
2596 this._favTimestamps.RemoveAt(i);
2599 this._statuses.DistributePosts();
2602 if (ct.IsCancellationRequested)
2605 this.RefreshTimeline();
2607 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2609 using (ControlTransaction.Update(this._curList))
2611 var idx = tab.IndexOf(statusId);
2613 this.ChangeCacheStyleRead(post.IsRead, idx);
2616 if (statusId == this._curPost.StatusId)
2617 await this.DispSelectedPost(true); // 選択アイテム再表示
2621 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2623 await this.workerSemaphore.WaitAsync();
2627 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2629 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2631 catch (WebApiException ex)
2633 this._myStatusError = true;
2634 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2638 this.workerSemaphore.Release();
2642 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2644 if (ct.IsCancellationRequested)
2647 if (!CheckAccountValid())
2648 throw new WebApiException("Auth error. Check your account");
2650 var successIds = new List<long>();
2652 await Task.Run(async () =>
2656 var failedCount = 0;
2657 foreach (var statusId in statusIds)
2661 var post = tab.Posts[statusId];
2663 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2670 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2672 .ConfigureAwait(false);
2674 catch (WebApiException)
2680 successIds.Add(statusId);
2681 post.IsFav = false; // リスト再描画必要
2683 if (this._statuses.ContainsKey(statusId))
2685 this._statuses[statusId].IsFav = false;
2688 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2689 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2691 if (tb.Contains(statusId))
2692 tb.Posts[statusId].IsFav = false;
2697 if (ct.IsCancellationRequested)
2700 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2701 foreach (var statusId in successIds)
2703 // ツイートが削除された訳ではないので IsDeleted はセットしない
2704 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2707 this.RefreshTimeline();
2709 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2711 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2717 using (ControlTransaction.Update(this._curList))
2719 foreach (var statusId in successIds)
2721 var idx = tab.IndexOf(statusId);
2725 var post = tab.Posts[statusId];
2726 this.ChangeCacheStyleRead(post.IsRead, idx);
2730 if (successIds.Contains(this._curPost.StatusId))
2731 await this.DispSelectedPost(true); // 選択アイテム再表示
2736 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService uploadService, IMediaItem[] uploadItems)
2738 await this.workerSemaphore.WaitAsync();
2742 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2744 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
2746 catch (WebApiException ex)
2748 this._myStatusError = true;
2749 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2753 this.workerSemaphore.Release();
2757 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostStatusParams postParams,
2758 IMediaUploadService uploadService, IMediaItem[] uploadItems)
2760 if (ct.IsCancellationRequested)
2763 if (!CheckAccountValid())
2764 throw new WebApiException("Auth error. Check your account");
2766 p.Report("Posting...");
2772 await Task.Run(async () =>
2774 var postParamsWithMedia = postParams;
2776 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
2778 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
2779 .ConfigureAwait(false);
2782 await this.tw.PostStatus(postParamsWithMedia)
2783 .ConfigureAwait(false);
2786 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2788 catch (WebApiException ex)
2790 // 処理は中断せずエラーの表示のみ行う
2791 errMsg = $"Err:{ex.Message}(PostMessage)";
2793 this._myStatusError = true;
2795 catch (UnauthorizedAccessException ex)
2797 // アップロード対象のファイルが開けなかった場合など
2798 errMsg = $"Err:{ex.Message}(PostMessage)";
2800 this._myStatusError = true;
2804 // 使い終わった MediaItem は破棄する
2805 if (uploadItems != null)
2807 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
2809 disposableItem.Dispose();
2814 if (ct.IsCancellationRequested)
2817 if (!string.IsNullOrEmpty(errMsg) &&
2818 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2819 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2821 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
2823 var ret = MessageBox.Show(
2825 "Failed to update status",
2826 MessageBoxButtons.RetryCancel,
2827 MessageBoxIcon.Question);
2829 if (ret == DialogResult.Retry)
2831 await this.PostMessageAsync(postParams, uploadService, uploadItems);
2835 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2836 if (SettingManager.Common.FocusLockToStatusText)
2837 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2842 this._postTimestamps.Add(DateTime.Now);
2844 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2845 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2847 if (this._postTimestamps[i] < oneHour)
2848 this._postTimestamps.RemoveAt(i);
2851 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2853 this.HashMgr.ClearHashtag();
2854 this.HashStripSplitButton.Text = "#[-]";
2855 this.HashTogglePullDownMenuItem.Checked = false;
2856 this.HashToggleMenuItem.Checked = false;
2859 this.SetMainWindowTitle();
2861 if (SettingManager.Common.PostAndGet)
2863 if (this.tw.UserStreamActive)
2864 this.RefreshTimeline();
2866 await this.GetHomeTimelineAsync();
2870 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2872 await this.workerSemaphore.WaitAsync();
2876 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2878 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2880 if (SettingManager.Common.PostAndGet && !this.tw.UserStreamActive)
2881 await this.GetHomeTimelineAsync();
2883 catch (WebApiException ex)
2885 this._myStatusError = true;
2886 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2890 this.workerSemaphore.Release();
2894 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2896 if (ct.IsCancellationRequested)
2899 if (!CheckAccountValid())
2900 throw new WebApiException("Auth error. Check your account");
2903 if (!SettingManager.Common.UnreadManage)
2906 read = this._initial && SettingManager.Common.Read;
2908 p.Report("Posting...");
2910 foreach (var statusId in statusIds)
2912 await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2915 if (ct.IsCancellationRequested)
2918 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2920 this._postTimestamps.Add(DateTime.Now);
2922 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2923 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2925 if (this._postTimestamps[i] < oneHour)
2926 this._postTimestamps.RemoveAt(i);
2930 private async Task RefreshFollowerIdsAsync()
2932 await this.workerSemaphore.WaitAsync();
2935 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2937 await this.tw.RefreshFollowerIds();
2939 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2941 this.RefreshTimeline();
2942 this.PurgeListViewItemCache();
2943 this._curList?.Refresh();
2945 catch (WebApiException ex)
2947 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2951 this.workerSemaphore.Release();
2955 private async Task RefreshNoRetweetIdsAsync()
2957 await this.workerSemaphore.WaitAsync();
2960 await this.tw.RefreshNoRetweetIds();
2962 this.StatusLabel.Text = "NoRetweetIds refreshed";
2964 catch (WebApiException ex)
2966 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2970 this.workerSemaphore.Release();
2974 private async Task RefreshBlockIdsAsync()
2976 await this.workerSemaphore.WaitAsync();
2979 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2981 await this.tw.RefreshBlockIds();
2983 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2985 catch (WebApiException ex)
2987 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2991 this.workerSemaphore.Release();
2995 private async Task RefreshTwitterConfigurationAsync()
2997 await this.workerSemaphore.WaitAsync();
3000 await this.tw.RefreshConfiguration();
3002 if (this.tw.Configuration.PhotoSizeLimit != 0)
3004 foreach (var service in this.ImageSelector.GetServices())
3006 service.UpdateTwitterConfiguration(this.tw.Configuration);
3010 this.PurgeListViewItemCache();
3012 this._curList?.Refresh();
3014 catch (WebApiException ex)
3016 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
3020 this.workerSemaphore.Release();
3024 private async Task RefreshMuteUserIdsAsync()
3026 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3030 await tw.RefreshMuteUserIdsAsync();
3032 catch (WebApiException ex)
3034 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3038 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3041 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3043 if (e.Button == MouseButtons.Left)
3045 this.Visible = true;
3046 if (this.WindowState == FormWindowState.Minimized)
3048 this.WindowState = _formWindowState;
3051 this.BringToFront();
3055 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3057 switch (SettingManager.Common.ListDoubleClickAction)
3060 MakeReplyOrDirectStatus();
3063 await this.FavoriteChange(true);
3066 if (_curPost != null)
3067 await this.ShowUserStatus(_curPost.ScreenName, false);
3073 ShowRelatedStatusesMenuItem_Click(null, null);
3076 MoveToHomeToolStripMenuItem_Click(null, null);
3079 StatusOpenMenuItem_Click(null, null);
3087 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3089 await this.FavoriteChange(true);
3092 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3094 await this.FavoriteChange(false);
3098 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3100 await this.FavoritesRetweetOfficial();
3103 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3105 await this.FavoritesRetweetUnofficial();
3108 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3110 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3113 //trueでFavAdd,falseでFavRemove
3114 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3115 || !this.ExistCurrentPost) return;
3117 if (this._curList.SelectedIndices.Count > 1)
3122 // https://support.twitter.com/articles/76915#favoriting
3123 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3124 _DoFavRetweetFlags = false;
3129 if (multiFavoriteChangeDialogEnable)
3131 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3132 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3133 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3135 if (confirm == DialogResult.Cancel)
3143 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3144 if (selectedPost.IsFav)
3146 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3150 await this.FavAddAsync(selectedPost.StatusId, tab);
3154 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3155 .Select(x => this.GetCurTabPost(x))
3156 .Where(x => x.IsFav);
3158 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3159 if (statusIds.Length == 0)
3161 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3165 await this.FavRemoveAsync(statusIds, tab);
3169 private PostClass GetCurTabPost(int Index)
3171 var listCache = this._listItemCache;
3172 if (listCache != null)
3174 if (listCache.TryGetValue(Index, out var item, out var post))
3178 return _statuses.Tabs[_curTab.Text][Index];
3181 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3183 if (_curList.SelectedIndices.Count > 0)
3184 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3185 else if (_curList.SelectedIndices.Count == 0)
3186 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3189 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3191 if (_curList.SelectedIndices.Count > 0)
3192 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3195 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3197 if ((!_initialLayout) && this.Visible)
3199 if (this.WindowState == FormWindowState.Normal)
3201 _mySize = this.ClientSize;
3202 _mySpDis = this.SplitContainer1.SplitterDistance;
3203 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3204 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3205 ModifySettingLocal = true;
3210 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3212 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3213 if (comparerMode == null)
3216 this.SetSortColumn(comparerMode.Value);
3220 /// 列インデックスからソートを行う ComparerMode を求める
3222 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3223 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3224 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3227 return ComparerMode.Id;
3229 switch (columnIndex)
3232 return ComparerMode.Nickname;
3234 return ComparerMode.Data;
3236 return ComparerMode.Id;
3238 return ComparerMode.Name;
3240 return ComparerMode.Source;
3242 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3248 /// 発言一覧の指定した位置の列でソートする
3250 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3251 private void SetSortColumnByDisplayIndex(int columnIndex)
3253 // 表示上の列の位置から ColumnHeader を求める
3254 var col = this._curList.Columns.Cast<ColumnHeader>()
3255 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3260 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3261 if (comparerMode == null)
3264 this.SetSortColumn(comparerMode.Value);
3268 /// 発言一覧の最後列の項目でソートする
3270 private void SetSortLastColumn()
3272 // 表示上の最後列にある ColumnHeader を求める
3273 var col = this._curList.Columns.Cast<ColumnHeader>()
3274 .OrderByDescending(x => x.DisplayIndex)
3277 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3278 if (comparerMode == null)
3281 this.SetSortColumn(comparerMode.Value);
3285 /// 発言一覧を指定された ComparerMode に基づいてソートする
3287 private void SetSortColumn(ComparerMode sortColumn)
3289 if (SettingManager.Common.SortOrderLock)
3292 this._statuses.ToggleSortOrder(sortColumn);
3293 this.InitColumnText();
3295 var list = this._curList;
3298 list.Columns[0].Text = this.ColumnText[0];
3299 list.Columns[1].Text = this.ColumnText[2];
3303 for (var i = 0; i <= 7; i++)
3305 list.Columns[i].Text = this.ColumnText[i];
3309 this.PurgeListViewItemCache();
3311 var tab = this._statuses.Tabs[this._curTab.Text];
3312 if (tab.AllCount > 0 && this._curPost != null)
3314 var idx = tab.IndexOf(this._curPost.StatusId);
3317 this.SelectListItem(list, idx);
3318 list.EnsureVisible(idx);
3323 this.ModifySettingCommon = true;
3326 private void TweenMain_LocationChanged(object sender, EventArgs e)
3328 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3330 _myLoc = this.DesktopLocation;
3331 ModifySettingLocal = true;
3335 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3337 if (ListTab.SelectedTab == null) return;
3338 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3339 if (!this.ExistCurrentPost)
3341 ReplyStripMenuItem.Enabled = false;
3342 ReplyAllStripMenuItem.Enabled = false;
3343 DMStripMenuItem.Enabled = false;
3344 ShowProfileMenuItem.Enabled = false;
3345 ShowUserTimelineContextMenuItem.Enabled = false;
3346 ListManageUserContextToolStripMenuItem2.Enabled = false;
3347 MoveToFavToolStripMenuItem.Enabled = false;
3348 TabMenuItem.Enabled = false;
3349 IDRuleMenuItem.Enabled = false;
3350 SourceRuleMenuItem.Enabled = false;
3351 ReadedStripMenuItem.Enabled = false;
3352 UnreadStripMenuItem.Enabled = false;
3356 ShowProfileMenuItem.Enabled = true;
3357 ListManageUserContextToolStripMenuItem2.Enabled = true;
3358 ReplyStripMenuItem.Enabled = true;
3359 ReplyAllStripMenuItem.Enabled = true;
3360 DMStripMenuItem.Enabled = true;
3361 ShowUserTimelineContextMenuItem.Enabled = true;
3362 MoveToFavToolStripMenuItem.Enabled = true;
3363 TabMenuItem.Enabled = true;
3364 IDRuleMenuItem.Enabled = true;
3365 SourceRuleMenuItem.Enabled = true;
3366 ReadedStripMenuItem.Enabled = true;
3367 UnreadStripMenuItem.Enabled = true;
3369 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3371 FavAddToolStripMenuItem.Enabled = false;
3372 FavRemoveToolStripMenuItem.Enabled = false;
3373 StatusOpenMenuItem.Enabled = false;
3374 FavorareMenuItem.Enabled = false;
3375 ShowRelatedStatusesMenuItem.Enabled = false;
3377 ReTweetStripMenuItem.Enabled = false;
3378 ReTweetUnofficialStripMenuItem.Enabled = false;
3379 QuoteStripMenuItem.Enabled = false;
3380 FavoriteRetweetContextMenu.Enabled = false;
3381 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3385 FavAddToolStripMenuItem.Enabled = true;
3386 FavRemoveToolStripMenuItem.Enabled = true;
3387 StatusOpenMenuItem.Enabled = true;
3388 FavorareMenuItem.Enabled = true;
3389 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3391 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
3393 ReTweetStripMenuItem.Enabled = false;
3394 ReTweetUnofficialStripMenuItem.Enabled = false;
3395 QuoteStripMenuItem.Enabled = false;
3396 FavoriteRetweetContextMenu.Enabled = false;
3397 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3401 ReTweetStripMenuItem.Enabled = true;
3402 ReTweetUnofficialStripMenuItem.Enabled = true;
3403 QuoteStripMenuItem.Enabled = true;
3404 FavoriteRetweetContextMenu.Enabled = true;
3405 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3408 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3410 // RefreshMoreStripMenuItem.Enabled = true;
3414 // RefreshMoreStripMenuItem.Enabled = false;
3416 if (!this.ExistCurrentPost
3417 || _curPost.InReplyToStatusId == null)
3419 RepliedStatusOpenMenuItem.Enabled = false;
3423 RepliedStatusOpenMenuItem.Enabled = true;
3425 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3427 MoveToRTHomeMenuItem.Enabled = false;
3431 MoveToRTHomeMenuItem.Enabled = true;
3434 if (this.ExistCurrentPost)
3436 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3437 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3438 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3440 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3444 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3446 MakeReplyOrDirectStatus(false, true);
3449 private void DMStripMenuItem_Click(object sender, EventArgs e)
3451 MakeReplyOrDirectStatus(false, false);
3454 private async Task doStatusDelete()
3456 if (this._curTab == null || this._curList == null)
3459 if (this._curList.SelectedIndices.Count == 0)
3462 var posts = this._curList.SelectedIndices.Cast<int>()
3463 .Select(x => this.GetCurTabPost(x))
3466 // 選択されたツイートの中に削除可能なものが一つでもあるか
3467 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3470 var ret = MessageBox.Show(this,
3471 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3472 Properties.Resources.DeleteStripMenuItem_ClickText2,
3473 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3475 if (ret != DialogResult.OK)
3478 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3480 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3482 Exception lastException = null;
3483 foreach (var post in posts)
3485 if (!post.CanDeleteBy(this.tw.UserId))
3492 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3497 if (post.RetweetedByUserId == this.tw.UserId)
3499 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3501 await this.twitterApi.StatusesDestroy(post.StatusId)
3506 if (post.UserId == this.tw.UserId)
3508 if (post.RetweetedId != null)
3509 // 他人に RT された自分のツイート
3510 // => RT 元の自分のツイートを削除
3511 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3516 await this.twitterApi.StatusesDestroy(post.StatusId)
3522 catch (WebApiException ex)
3528 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3531 if (lastException == null)
3532 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3534 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3536 this.PurgeListViewItemCache();
3537 this._curPost = null;
3538 this._curItemIndex = -1;
3540 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3542 var listView = (DetailsListView)tabPage.Tag;
3543 var tab = this._statuses.Tabs[tabPage.Text];
3545 using (ControlTransaction.Update(listView))
3547 listView.VirtualListSize = tab.AllCount;
3549 if (tabPage == this._curTab)
3551 listView.SelectedIndices.Clear();
3553 if (tab.AllCount != 0)
3556 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3557 selectedIndex = focusedIndex;
3559 selectedIndex = tab.AllCount - 1;
3561 listView.SelectedIndices.Add(selectedIndex);
3562 listView.EnsureVisible(selectedIndex);
3563 listView.FocusedItem = listView.Items[selectedIndex];
3568 if (SettingManager.Common.TabIconDisp && tab.UnreadCount == 0)
3570 if (tabPage.ImageIndex == 0)
3571 tabPage.ImageIndex = -1; // タブアイコン
3575 if (!SettingManager.Common.TabIconDisp)
3576 this.ListTab.Refresh();
3580 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3582 await this.doStatusDelete();
3585 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3587 using (ControlTransaction.Update(this._curList))
3589 foreach (int idx in _curList.SelectedIndices)
3591 var post = this._statuses.Tabs[this._curTab.Text][idx];
3592 this._statuses.SetReadAllTab(post.StatusId, read: true);
3593 ChangeCacheStyleRead(true, idx);
3597 foreach (TabPage tb in ListTab.TabPages)
3599 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3601 if (SettingManager.Common.TabIconDisp)
3603 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3607 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3610 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3612 using (ControlTransaction.Update(this._curList))
3614 foreach (int idx in _curList.SelectedIndices)
3616 var post = this._statuses.Tabs[this._curTab.Text][idx];
3617 this._statuses.SetReadAllTab(post.StatusId, read: false);
3618 ChangeCacheStyleRead(false, idx);
3622 foreach (TabPage tb in ListTab.TabPages)
3624 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3626 if (SettingManager.Common.TabIconDisp)
3628 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3632 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3635 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3637 await this.DoRefresh();
3640 private async Task DoRefresh()
3642 if (_curTab != null)
3644 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3649 case MentionsTabModel replyTab:
3650 await this.GetReplyAsync();
3652 case DirectMessagesTabModel dmTab:
3653 await this.GetDirectMessagesAsync();
3655 case FavoritesTabModel favTab:
3656 await this.GetFavoritesAsync();
3658 case PublicSearchTabModel searchTab:
3659 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3660 await this.GetPublicSearchAsync(searchTab);
3662 case UserTimelineTabModel userTab:
3663 await this.GetUserTimelineAsync(userTab);
3665 case ListTimelineTabModel listTab:
3666 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3667 await this.GetListTimelineAsync(listTab);
3670 await this.GetHomeTimelineAsync();
3676 await this.GetHomeTimelineAsync();
3680 private async Task DoRefreshMore()
3683 if (_curTab != null)
3685 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3690 case MentionsTabModel replyTab:
3691 await this.GetReplyAsync(loadMore: true);
3693 case DirectMessagesTabModel dmTab:
3694 await this.GetDirectMessagesAsync(loadMore: true);
3696 case FavoritesTabModel favTab:
3697 await this.GetFavoritesAsync(loadMore: true);
3699 case PublicSearchTabModel searchTab:
3700 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3701 await this.GetPublicSearchAsync(searchTab, loadMore: true);
3703 case UserTimelineTabModel userTab:
3704 await this.GetUserTimelineAsync(userTab, loadMore: true);
3706 case ListTimelineTabModel listTab:
3707 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3708 await this.GetListTimelineAsync(listTab, loadMore: true);
3711 await this.GetHomeTimelineAsync(loadMore: true);
3717 await this.GetHomeTimelineAsync(loadMore: true);
3721 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3723 DialogResult result = DialogResult.Abort;
3725 using (var settingDialog = new AppendSettingDialog())
3727 settingDialog.Icon = this.MainIcon;
3728 settingDialog.Owner = this;
3729 settingDialog.ShowInTaskbar = showTaskbarIcon;
3730 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3732 settingDialog.tw = this.tw;
3733 settingDialog.twitterApi = this.twitterApi;
3735 settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
3739 result = settingDialog.ShowDialog(this);
3743 return DialogResult.Abort;
3746 if (result == DialogResult.OK)
3750 settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
3758 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3761 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3763 var oldIconSz = SettingManager.Common.IconSize;
3765 if (ShowSettingDialog() == DialogResult.OK)
3769 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
3770 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
3771 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
3772 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
3773 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
3774 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
3775 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
3777 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
3778 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
3779 Networking.SetWebProxy(SettingManager.Local.ProxyType,
3780 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
3781 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
3782 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
3784 ImageSelector.Reset(tw, this.tw.Configuration);
3788 if (SettingManager.Common.TabIconDisp)
3790 ListTab.DrawItem -= ListTab_DrawItem;
3791 ListTab.DrawMode = TabDrawMode.Normal;
3792 ListTab.ImageList = this.TabImage;
3796 ListTab.DrawItem -= ListTab_DrawItem;
3797 ListTab.DrawItem += ListTab_DrawItem;
3798 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3799 ListTab.ImageList = null;
3802 catch (Exception ex)
3804 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3805 ex.Data["IsTerminatePermission"] = false;
3811 if (!SettingManager.Common.UnreadManage)
3813 ReadedStripMenuItem.Enabled = false;
3814 UnreadStripMenuItem.Enabled = false;
3815 if (SettingManager.Common.TabIconDisp)
3817 foreach (TabPage myTab in ListTab.TabPages)
3819 myTab.ImageIndex = -1;
3825 ReadedStripMenuItem.Enabled = true;
3826 UnreadStripMenuItem.Enabled = true;
3829 catch (Exception ex)
3831 ex.Data["Instance"] = "ListTab(UnreadManage)";
3832 ex.Data["IsTerminatePermission"] = false;
3839 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
3841 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3842 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
3843 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
3845 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
3846 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
3847 _fntUnread = SettingManager.Local.FontUnread;
3848 _clUnread = SettingManager.Local.ColorUnread;
3849 _fntReaded = SettingManager.Local.FontRead;
3850 _clReaded = SettingManager.Local.ColorRead;
3851 _clFav = SettingManager.Local.ColorFav;
3852 _clOWL = SettingManager.Local.ColorOWL;
3853 _clRetweet = SettingManager.Local.ColorRetweet;
3854 _fntDetail = SettingManager.Local.FontDetail;
3855 _clDetail = SettingManager.Local.ColorDetail;
3856 _clDetailLink = SettingManager.Local.ColorDetailLink;
3857 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
3858 _clSelf = SettingManager.Local.ColorSelf;
3859 _clAtSelf = SettingManager.Local.ColorAtSelf;
3860 _clTarget = SettingManager.Local.ColorTarget;
3861 _clAtTarget = SettingManager.Local.ColorAtTarget;
3862 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
3863 _clAtTo = SettingManager.Local.ColorAtTo;
3864 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
3865 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
3866 _clInputFont = SettingManager.Local.ColorInputFont;
3867 _fntInputFont = SettingManager.Local.FontInputFont;
3868 _brsBackColorMine.Dispose();
3869 _brsBackColorAt.Dispose();
3870 _brsBackColorYou.Dispose();
3871 _brsBackColorAtYou.Dispose();
3872 _brsBackColorAtFromTarget.Dispose();
3873 _brsBackColorAtTo.Dispose();
3874 _brsBackColorNone.Dispose();
3875 _brsBackColorMine = new SolidBrush(_clSelf);
3876 _brsBackColorAt = new SolidBrush(_clAtSelf);
3877 _brsBackColorYou = new SolidBrush(_clTarget);
3878 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3879 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3880 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3881 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3885 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3886 StatusText.Font = _fntInputFont;
3887 StatusText.ForeColor = _clInputFont;
3889 catch (Exception ex)
3891 MessageBox.Show(ex.Message);
3896 InitDetailHtmlFormat();
3898 catch (Exception ex)
3900 ex.Data["Instance"] = "Font";
3901 ex.Data["IsTerminatePermission"] = false;
3907 foreach (TabPage tb in ListTab.TabPages)
3909 if (SettingManager.Common.TabIconDisp)
3911 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3918 catch (Exception ex)
3920 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3921 ex.Data["IsTerminatePermission"] = false;
3927 var oldIconCol = _iconCol;
3929 if (SettingManager.Common.IconSize != oldIconSz)
3930 ApplyListViewIconSize(SettingManager.Common.IconSize);
3932 foreach (TabPage tp in ListTab.TabPages)
3934 DetailsListView lst = (DetailsListView)tp.Tag;
3936 using (ControlTransaction.Update(lst))
3938 lst.GridLines = SettingManager.Common.ShowGrid;
3939 lst.Font = _fntReaded;
3940 lst.BackColor = _clListBackcolor;
3942 if (_iconCol != oldIconCol)
3947 catch (Exception ex)
3949 ex.Data["Instance"] = "ListView(IconSize)";
3950 ex.Data["IsTerminatePermission"] = false;
3954 SetMainWindowTitle();
3955 SetNotifyIconText();
3957 this.PurgeListViewItemCache();
3958 _curList?.Refresh();
3961 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3962 if (SettingManager.Common.HotkeyEnabled)
3964 ///グローバルホットキーの登録。設定で変更可能にするかも
3965 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
3966 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
3967 modKey |= HookGlobalHotkey.ModKeys.Alt;
3968 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
3969 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3970 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
3971 modKey |= HookGlobalHotkey.ModKeys.Shift;
3972 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
3973 modKey |= HookGlobalHotkey.ModKeys.Win;
3975 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
3978 if (SettingManager.Common.IsUseNotifyGrowl) gh.RegisterGrowl();
3981 StatusText_TextChanged(null, null);
3990 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3991 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3994 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3996 this.TopMost = SettingManager.Common.AlwaysTop;
3997 SaveConfigsAll(false);
3999 if (tw.Username != oldUser.Username)
4000 await this.doGetFollowersMenu();
4006 private void SetTabAlignment()
4008 var newAlignment = SettingManager.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4009 if (ListTab.Alignment == newAlignment) return;
4011 // 各タブのリスト上の選択位置などを退避
4012 var listSelections = this.SaveListViewSelection();
4014 ListTab.Alignment = newAlignment;
4016 foreach (TabPage tab in ListTab.TabPages)
4018 DetailsListView lst = (DetailsListView)tab.Tag;
4019 TabModel tabInfo = _statuses.Tabs[tab.Text];
4020 using (ControlTransaction.Update(lst))
4023 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4028 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4034 case MyCommon.IconSizes.IconNone:
4037 case MyCommon.IconSizes.Icon16:
4040 case MyCommon.IconSizes.Icon24:
4043 case MyCommon.IconSizes.Icon48:
4046 case MyCommon.IconSizes.Icon48_2:
4054 // ディスプレイの DPI 設定を考慮したサイズを設定する
4055 _listViewImageList.ImageSize = new Size(
4057 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4061 _listViewImageList.ImageSize = new Size(1, 1);
4065 private void ResetColumns(DetailsListView list)
4067 using (ControlTransaction.Update(list))
4068 using (ControlTransaction.Layout(list, false))
4071 list.ColumnClick -= MyList_ColumnClick;
4072 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4073 list.ColumnReordered -= MyList_ColumnReordered;
4074 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4076 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4077 list.Columns.Clear();
4078 cols.ForEach(col => col.Dispose());
4081 InitColumns(list, true);
4083 list.ColumnClick += MyList_ColumnClick;
4084 list.DrawColumnHeader += MyList_DrawColumnHeader;
4085 list.ColumnReordered += MyList_ColumnReordered;
4086 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4090 public void AddNewTabForSearch(string searchWord)
4092 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4093 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4095 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4097 foreach (TabPage tp in ListTab.TabPages)
4099 if (tb.TabName == tp.Text)
4101 ListTab.SelectedTab = tp;
4108 string tabName = searchWord;
4109 for (int i = 0; i <= 100; i++)
4111 if (_statuses.ContainsTab(tabName))
4117 var tab = new PublicSearchTabModel(tabName);
4118 _statuses.AddTab(tab);
4119 AddNewTab(tab, startup: false);
4121 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4123 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4124 cmb.Items.Add(searchWord);
4125 cmb.Text = searchWord;
4128 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4131 private void ShowUserTimeline()
4133 if (!this.ExistCurrentPost) return;
4134 AddNewTabForUserTimeline(_curPost.ScreenName);
4137 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4139 if (e.KeyCode == Keys.Escape)
4141 TabPage relTp = ListTab.SelectedTab;
4142 RemoveSpecifiedTab(relTp.Text, false);
4144 e.SuppressKeyPress = true;
4148 public void AddNewTabForUserTimeline(string user)
4150 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4151 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4153 if (tb.ScreenName == user)
4155 foreach (TabPage tp in ListTab.TabPages)
4157 if (tb.TabName == tp.Text)
4159 ListTab.SelectedTab = tp;
4166 string tabName = "user:" + user;
4167 while (_statuses.ContainsTab(tabName))
4172 var tab = new UserTimelineTabModel(tabName, user);
4173 this._statuses.AddTab(tab);
4174 this.AddNewTab(tab, startup: false);
4176 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4179 this.GetUserTimelineAsync(tab);
4182 public bool AddNewTab(TabModel tab, bool startup)
4185 foreach (TabPage tb in ListTab.TabPages)
4187 if (tb.Text == tab.TabName) return false;
4191 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4193 var _tabPage = new TabPage();
4194 var _listCustom = new DetailsListView();
4196 int cnt = ListTab.TabPages.Count;
4198 ///ToDo:Create and set controls follow tabtypes
4200 using (ControlTransaction.Update(_listCustom))
4201 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4202 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4203 using (ControlTransaction.Layout(this.SplitContainer1, false))
4204 using (ControlTransaction.Layout(this.ListTab, false))
4205 using (ControlTransaction.Layout(this))
4206 using (ControlTransaction.Layout(_tabPage, false))
4208 _tabPage.Controls.Add(_listCustom);
4211 var userTab = tab as UserTimelineTabModel;
4212 var listTab = tab as ListTimelineTabModel;
4213 var searchTab = tab as PublicSearchTabModel;
4215 if (userTab != null || listTab != null)
4217 var label = new Label();
4218 label.Dock = DockStyle.Top;
4219 label.Name = "labelUser";
4222 if (listTab != null)
4224 label.Text = listTab.ListInfo.ToString();
4226 else if (userTab != null)
4228 label.Text = userTab.ScreenName + "'s Timeline";
4230 label.TextAlign = ContentAlignment.MiddleLeft;
4231 using (ComboBox tmpComboBox = new ComboBox())
4233 label.Height = tmpComboBox.Height;
4235 _tabPage.Controls.Add(label);
4238 else if (searchTab != null)
4240 var pnl = new Panel();
4242 var lbl = new Label();
4243 var cmb = new ComboBox();
4244 var btn = new Button();
4245 var cmbLang = new ComboBox();
4247 using (ControlTransaction.Layout(pnl, false))
4249 pnl.Controls.Add(cmb);
4250 pnl.Controls.Add(cmbLang);
4251 pnl.Controls.Add(btn);
4252 pnl.Controls.Add(lbl);
4253 pnl.Name = "panelSearch";
4255 pnl.Dock = DockStyle.Top;
4256 pnl.Height = cmb.Height;
4257 pnl.Enter += SearchControls_Enter;
4258 pnl.Leave += SearchControls_Leave;
4261 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4262 cmb.Dock = DockStyle.Fill;
4263 cmb.Name = "comboSearch";
4264 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4265 cmb.ImeMode = ImeMode.NoControl;
4266 cmb.TabStop = false;
4268 cmb.AutoCompleteMode = AutoCompleteMode.None;
4269 cmb.KeyDown += SearchComboBox_KeyDown;
4272 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4273 cmbLang.Dock = DockStyle.Right;
4275 cmbLang.Name = "comboLang";
4276 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4277 cmbLang.TabStop = false;
4278 cmbLang.TabIndex = 2;
4279 cmbLang.Items.Add("");
4280 cmbLang.Items.Add("ja");
4281 cmbLang.Items.Add("en");
4282 cmbLang.Items.Add("ar");
4283 cmbLang.Items.Add("da");
4284 cmbLang.Items.Add("nl");
4285 cmbLang.Items.Add("fa");
4286 cmbLang.Items.Add("fi");
4287 cmbLang.Items.Add("fr");
4288 cmbLang.Items.Add("de");
4289 cmbLang.Items.Add("hu");
4290 cmbLang.Items.Add("is");
4291 cmbLang.Items.Add("it");
4292 cmbLang.Items.Add("no");
4293 cmbLang.Items.Add("pl");
4294 cmbLang.Items.Add("pt");
4295 cmbLang.Items.Add("ru");
4296 cmbLang.Items.Add("es");
4297 cmbLang.Items.Add("sv");
4298 cmbLang.Items.Add("th");
4300 lbl.Text = "Search(C-S-f)";
4301 lbl.Name = "label1";
4302 lbl.Dock = DockStyle.Left;
4304 lbl.Height = cmb.Height;
4305 lbl.TextAlign = ContentAlignment.MiddleLeft;
4308 btn.Text = "Search";
4309 btn.Name = "buttonSearch";
4310 btn.UseVisualStyleBackColor = true;
4311 btn.Dock = DockStyle.Right;
4312 btn.TabStop = false;
4314 btn.Click += SearchButton_Click;
4316 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4318 cmb.Items.Add(searchTab.SearchWords);
4319 cmb.Text = searchTab.SearchWords;
4322 cmbLang.Text = searchTab.SearchLang;
4324 _tabPage.Controls.Add(pnl);
4328 _tabPage.Tag = _listCustom;
4329 this.ListTab.Controls.Add(_tabPage);
4331 _tabPage.Location = new Point(4, 4);
4332 _tabPage.Name = "CTab" + cnt;
4333 _tabPage.Size = new Size(380, 260);
4334 _tabPage.TabIndex = 2 + cnt;
4335 _tabPage.Text = tab.TabName;
4336 _tabPage.UseVisualStyleBackColor = true;
4337 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4339 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4340 _listCustom.TabIndex = 1;
4341 _listCustom.AllowColumnReorder = true;
4342 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4343 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4344 _listCustom.Dock = DockStyle.Fill;
4345 _listCustom.FullRowSelect = true;
4346 _listCustom.HideSelection = false;
4347 _listCustom.Location = new Point(0, 0);
4348 _listCustom.Margin = new Padding(0);
4349 _listCustom.Name = "CList" + Environment.TickCount;
4350 _listCustom.ShowItemToolTips = true;
4351 _listCustom.Size = new Size(380, 260);
4352 _listCustom.UseCompatibleStateImageBehavior = false;
4353 _listCustom.View = View.Details;
4354 _listCustom.OwnerDraw = true;
4355 _listCustom.VirtualMode = true;
4356 _listCustom.Font = _fntReaded;
4357 _listCustom.BackColor = _clListBackcolor;
4359 _listCustom.GridLines = SettingManager.Common.ShowGrid;
4360 _listCustom.AllowDrop = true;
4362 _listCustom.SmallImageList = _listViewImageList;
4364 InitColumns(_listCustom, startup);
4366 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4367 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4368 _listCustom.ColumnClick += MyList_ColumnClick;
4369 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4370 _listCustom.DragDrop += TweenMain_DragDrop;
4371 _listCustom.DragEnter += TweenMain_DragEnter;
4372 _listCustom.DragOver += TweenMain_DragOver;
4373 _listCustom.DrawItem += MyList_DrawItem;
4374 _listCustom.MouseClick += MyList_MouseClick;
4375 _listCustom.ColumnReordered += MyList_ColumnReordered;
4376 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4377 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4378 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4379 _listCustom.DrawSubItem += MyList_DrawSubItem;
4380 _listCustom.HScrolled += MyList_HScrolled;
4386 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4388 var tabInfo = _statuses.GetTabByName(TabName);
4389 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4393 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4394 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4395 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4401 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4402 if (_tabPage == null) return false;
4404 SetListProperty(); //他のタブに列幅等を反映
4407 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4408 _tabPage.Tag = null;
4410 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4411 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4412 using (ControlTransaction.Layout(this.SplitContainer1, false))
4413 using (ControlTransaction.Layout(this.ListTab, false))
4414 using (ControlTransaction.Layout(this))
4415 using (ControlTransaction.Layout(_tabPage, false))
4417 if (this.ListTab.SelectedTab == _tabPage)
4419 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4420 this._beforeSelectedTab = null;
4422 this.ListTab.Controls.Remove(_tabPage);
4425 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4427 using (Control label = _tabPage.Controls["labelUser"])
4429 _tabPage.Controls.Remove(label);
4432 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4434 using (Control pnl = _tabPage.Controls["panelSearch"])
4436 pnl.Enter -= SearchControls_Enter;
4437 pnl.Leave -= SearchControls_Leave;
4438 _tabPage.Controls.Remove(pnl);
4440 foreach (Control ctrl in pnl.Controls)
4442 if (ctrl.Name == "buttonSearch")
4444 ctrl.Click -= SearchButton_Click;
4446 else if (ctrl.Name == "comboSearch")
4448 ctrl.KeyDown -= SearchComboBox_KeyDown;
4450 pnl.Controls.Remove(ctrl);
4456 _tabPage.Controls.Remove(_listCustom);
4458 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4459 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4460 _listCustom.ColumnClick -= MyList_ColumnClick;
4461 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4462 _listCustom.DragDrop -= TweenMain_DragDrop;
4463 _listCustom.DragEnter -= TweenMain_DragEnter;
4464 _listCustom.DragOver -= TweenMain_DragOver;
4465 _listCustom.DrawItem -= MyList_DrawItem;
4466 _listCustom.MouseClick -= MyList_MouseClick;
4467 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4468 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4469 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4470 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4471 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4472 _listCustom.HScrolled -= MyList_HScrolled;
4474 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4475 _listCustom.Columns.Clear();
4476 cols.ForEach(col => col.Dispose());
4479 _listCustom.ContextMenuStrip = null;
4480 _listCustom.ColumnHeaderContextMenuStrip = null;
4481 _listCustom.Font = null;
4483 _listCustom.SmallImageList = null;
4484 _listCustom.ListViewItemSorter = null;
4487 if (_curTab.Equals(_tabPage))
4494 this.PurgeListViewItemCache();
4498 _listCustom.Dispose();
4499 _statuses.RemoveTab(TabName);
4501 foreach (TabPage tp in ListTab.TabPages)
4503 DetailsListView lst = (DetailsListView)tp.Tag;
4504 var count = _statuses.Tabs[tp.Text].AllCount;
4505 lst.VirtualListSize = count;
4511 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4513 this.PurgeListViewItemCache();
4514 _beforeSelectedTab = e.TabPage;
4517 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4521 if (!SettingManager.Common.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4524 Rectangle dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4525 if (!dragEnableRectangle.Contains(e.Location))
4527 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4528 tn = ListTab.SelectedTab.Text;
4531 if (string.IsNullOrEmpty(tn)) return;
4533 foreach (TabPage tb in ListTab.TabPages)
4537 ListTab.DoDragDrop(tb, DragDropEffects.All);
4547 Point cpos = new Point(e.X, e.Y);
4548 for (int i = 0; i < ListTab.TabPages.Count; i++)
4550 Rectangle rect = ListTab.GetTabRect(i);
4551 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4552 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4554 _rclickTabName = ListTab.TabPages[i].Text;
4560 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4562 //_curList.Refresh();
4563 SetMainWindowTitle();
4564 SetStatusLabelUrl();
4565 SetApiStatusLabel();
4566 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4567 TabMenuControl(ListTab.SelectedTab.Text);
4568 this.PushSelectPostChain();
4569 await DispSelectedPost();
4572 private void SetListProperty()
4574 //削除などで見つからない場合は処理せず
4575 if (_curList == null) return;
4576 if (!_isColumnChanged) return;
4578 int[] dispOrder = new int[_curList.Columns.Count];
4579 for (int i = 0; i < _curList.Columns.Count; i++)
4581 for (int j = 0; j < _curList.Columns.Count; j++)
4583 if (_curList.Columns[j].DisplayIndex == i)
4592 foreach (TabPage tb in ListTab.TabPages)
4594 if (!tb.Equals(_curTab))
4596 if (tb.Tag != null && tb.Controls.Count > 0)
4598 DetailsListView lst = (DetailsListView)tb.Tag;
4599 for (int i = 0; i < lst.Columns.Count; i++)
4601 lst.Columns[dispOrder[i]].DisplayIndex = i;
4602 lst.Columns[i].Width = _curList.Columns[i].Width;
4608 _isColumnChanged = false;
4611 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4613 if (e.KeyChar == '@')
4615 if (!SettingManager.Common.UseAtIdSupplement) return;
4617 int cnt = AtIdSupl.ItemCount;
4618 ShowSuplDialog(StatusText, AtIdSupl);
4619 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
4622 else if (e.KeyChar == '#')
4624 if (!SettingManager.Common.UseHashSupplement) return;
4625 ShowSuplDialog(StatusText, HashSupl);
4630 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4632 ShowSuplDialog(owner, dialog, 0, "");
4635 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4637 ShowSuplDialog(owner, dialog, offset, "");
4640 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4642 dialog.StartsWith = startswith;
4649 dialog.ShowDialog();
4651 this.TopMost = SettingManager.Common.AlwaysTop;
4652 int selStart = owner.SelectionStart;
4655 if (dialog.DialogResult == DialogResult.OK)
4657 if (!string.IsNullOrEmpty(dialog.inputText))
4661 fHalf = owner.Text.Substring(0, selStart - offset);
4663 if (selStart < owner.Text.Length)
4665 eHalf = owner.Text.Substring(selStart);
4667 owner.Text = fHalf + dialog.inputText + eHalf;
4668 owner.SelectionStart = selStart + dialog.inputText.Length;
4675 fHalf = owner.Text.Substring(0, selStart);
4677 if (selStart < owner.Text.Length)
4679 eHalf = owner.Text.Substring(selStart);
4681 owner.Text = fHalf + eHalf;
4684 owner.SelectionStart = selStart;
4690 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4693 if (!e.Alt && !e.Control && !e.Shift)
4695 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4697 bool isSpace = false;
4698 foreach (char c in StatusText.Text)
4700 if (c == ' ' || c == ' ')
4713 StatusText.Text = "";
4714 JumpUnreadMenuItem_Click(null, null);
4718 this.StatusText_TextChanged(null, null);
4721 private void StatusText_TextChanged(object sender, EventArgs e)
4724 int pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
4725 lblLen.Text = pLen.ToString();
4728 StatusText.ForeColor = Color.Red;
4732 StatusText.ForeColor = _clInputFont;
4735 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4737 if (string.IsNullOrEmpty(StatusText.Text))
4739 this.inReplyTo = null;
4744 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
4746 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
4748 List<long> _autoPopulatedUserIds = new List<long>();
4750 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Item1] : null;
4751 if (replyToPost != null)
4753 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
4755 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
4756 _autoPopulatedUserIds.Add(replyToPost.UserId);
4758 foreach (var reply in replyToPost.ReplyToList)
4760 if (statusText.StartsWith($"@{reply.Item2} ", StringComparison.Ordinal))
4762 statusText = statusText.Substring(reply.Item2.Length + 2);
4763 _autoPopulatedUserIds.Add(reply.Item1);
4769 autoPopulatedUserIds = _autoPopulatedUserIds.ToArray();
4775 /// attachment_url に指定可能な URL が含まれていれば除去
4777 private string RemoveAttachmentUrl(string statusText, out string attachmentUrl)
4779 var match = Twitter.AttachmentUrlRegex.Match(statusText);
4782 attachmentUrl = null;
4786 attachmentUrl = match.Value;
4789 statusText = statusText.Substring(0, match.Index);
4791 // テキストと URL の間にスペースが含まれていれば除去
4792 return statusText.TrimEnd(' ');
4795 private string FormatStatusTextExtended(string statusText)
4797 long[] autoPopulatedUserIds;
4798 string attachmentUrl;
4800 return this.FormatStatusTextExtended(statusText, out autoPopulatedUserIds, out attachmentUrl);
4804 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
4806 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string attachmentUrl)
4808 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
4810 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
4812 return this.FormatStatusText(statusText);
4816 /// ツイート投稿前のフッター付与などの前処理を行います
4818 private string FormatStatusText(string statusText)
4820 statusText = statusText.Replace("\r\n", "\n");
4822 if (this.urlMultibyteSplit)
4825 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4828 if (SettingManager.Common.WideSpaceConvert)
4830 // 文中の全角スペースを半角スペース1個にする
4831 statusText = statusText.Replace(" ", " ");
4834 // DM の場合はこれ以降の処理を行わない
4835 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4839 if (SettingManager.Common.PostShiftEnter)
4841 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4845 if (this.StatusText.Multiline && !SettingManager.Common.PostCtrlEnter)
4846 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4848 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4851 if (statusText.Contains("RT @"))
4852 disableFooter = true;
4854 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
4855 if (this.inReplyTo != null && this.inReplyTo.Item2 == this.tw.Username)
4857 var mentionSelf = $"@{this.tw.Username} ";
4858 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
4860 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
4861 statusText = statusText.Substring(mentionSelf.Length);
4868 var hashtag = this.HashMgr.UseHash;
4869 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4872 header = HashMgr.UseHash + " ";
4874 footer = " " + HashMgr.UseHash;
4879 if (SettingManager.Local.UseRecommendStatus)
4882 footer += this.recommendedStatusFooter;
4884 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4886 // テキストボックスに入力されている文字列を使用する
4887 footer += " " + SettingManager.Local.StatusText.Trim();
4891 statusText = header + statusText + footer;
4893 if (this.preventSmsCommand)
4895 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4896 // 参照: https://support.twitter.com/articles/14020
4898 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4899 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4901 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4902 statusText = '\u200b' + statusText;
4910 /// 投稿欄に表示する入力可能な文字数を計算します
4912 private int GetRestStatusCount(string statusText)
4914 var remainCount = this.tw.GetTextLengthRemain(statusText);
4916 var uploadService = this.GetSelectedImageService();
4917 if (uploadService != null)
4919 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4920 remainCount -= uploadService.GetReservedTextLength(1);
4926 private IMediaUploadService GetSelectedImageService()
4927 => this.ImageSelector.Visible ? this.ImageSelector.SelectedService : null;
4929 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4931 if (sender != this._curList)
4934 var listCache = this._listItemCache;
4935 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4937 // If the newly requested cache is a subset of the old cache,
4938 // no need to rebuild everything, so do nothing.
4942 // Now we need to rebuild the cache.
4943 this.CreateCache(e.StartIndex, e.EndIndex);
4946 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4948 var listCache = this._listItemCache;
4949 if (listCache?.TargetList == sender)
4951 if (listCache.TryGetValue(e.ItemIndex, out var item, out var cacheItemPost))
4958 // A cache miss, so create a new ListViewItem and pass it back.
4959 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4962 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4966 // 不正な要求に対する間に合わせの応答
4967 string[] sitem = {"", "", "", "", "", "", "", ""};
4968 e.Item = new ImageListViewItem(sitem);
4972 private void CreateCache(int startIndex, int endIndex)
4974 var tabInfo = this._statuses.Tabs[this._curTab.Text];
4976 if (tabInfo.AllCount == 0)
4979 // インデックスを 0...(tabInfo.AllCount - 1) の範囲内にする
4980 int FilterRange(int index)
4981 => Math.Max(Math.Min(index, tabInfo.AllCount - 1), 0);
4983 // キャッシュ要求(要求範囲±30を作成)
4984 startIndex = FilterRange(startIndex - 30);
4985 endIndex = FilterRange(endIndex + 30);
4987 var cacheLength = endIndex - startIndex + 1;
4989 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4990 var listItems = Enumerable.Range(0, cacheLength)
4991 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4994 var listCache = new ListViewItemCache
4996 TargetList = this._curList,
4997 StartIndex = startIndex,
4998 EndIndex = endIndex,
5000 ListItem = listItems,
5003 Interlocked.Exchange(ref this._listItemCache, listCache);
5007 /// DetailsListView のための ListViewItem のキャッシュを消去する
5009 private void PurgeListViewItemCache()
5011 Interlocked.Exchange(ref this._listItemCache, null);
5014 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5016 StringBuilder mk = new StringBuilder();
5017 //if (Post.IsDeleted) mk.Append("×");
5018 //if (Post.IsMark) mk.Append("♪");
5019 //if (Post.IsProtect) mk.Append("Ю");
5020 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5021 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
5022 ImageListViewItem itm;
5023 if (Post.RetweetedId == null)
5025 string[] sitem= {"",
5027 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
5028 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
5033 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5037 string[] sitem = {"",
5039 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
5040 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
5041 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5045 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5047 itm.StateIndex = Post.StateIndex;
5050 bool read = Post.IsRead;
5051 //未読管理していなかったら既読として扱う
5052 if (!_statuses.Tabs[Tab.Text].UnreadManage || !SettingManager.Common.UnreadManage) read = true;
5053 ChangeItemStyleRead(read, itm, Post, null);
5054 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5059 /// 全てのタブの振り分けルールを反映し直します
5061 private void ApplyPostFilters()
5063 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5065 this.PurgeListViewItemCache();
5066 this._curPost = null;
5067 this._curItemIndex = -1;
5068 this._statuses.FilterAll();
5070 foreach (TabPage tabPage in this.ListTab.TabPages)
5072 var tab = this._statuses.Tabs[tabPage.Text];
5074 var listview = (DetailsListView)tabPage.Tag;
5075 using (ControlTransaction.Update(listview))
5077 listview.VirtualListSize = tab.AllCount;
5080 if (SettingManager.Common.TabIconDisp)
5082 if (tab.UnreadCount > 0)
5083 tabPage.ImageIndex = 0;
5085 tabPage.ImageIndex = -1;
5089 if (!SettingManager.Common.TabIconDisp)
5090 this.ListTab.Refresh();
5092 SetMainWindowTitle();
5093 SetStatusLabelUrl();
5097 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5099 e.DrawDefault = true;
5102 private void MyList_HScrolled(object sender, EventArgs e)
5104 DetailsListView listView = (DetailsListView)sender;
5108 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5110 if (e.State == 0) return;
5111 e.DrawDefault = false;
5113 SolidBrush brs2 = null;
5114 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5116 if (e.Item.BackColor == _clSelf)
5117 brs2 = _brsBackColorMine;
5118 else if (e.Item.BackColor == _clAtSelf)
5119 brs2 = _brsBackColorAt;
5120 else if (e.Item.BackColor == _clTarget)
5121 brs2 = _brsBackColorYou;
5122 else if (e.Item.BackColor == _clAtTarget)
5123 brs2 = _brsBackColorAtYou;
5124 else if (e.Item.BackColor == _clAtFromTarget)
5125 brs2 = _brsBackColorAtFromTarget;
5126 else if (e.Item.BackColor == _clAtTo)
5127 brs2 = _brsBackColorAtTo;
5129 brs2 = _brsBackColorNone;
5134 if (((Control)sender).Focused)
5135 brs2 = _brsHighLight;
5137 brs2 = _brsDeactiveSelection;
5139 e.Graphics.FillRectangle(brs2, e.Bounds);
5140 e.DrawFocusRectangle();
5141 this.DrawListViewItemIcon(e);
5144 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5146 if (e.ItemState == 0) return;
5148 if (e.ColumnIndex > 0)
5151 var post = (PostClass)e.Item.Tag;
5153 RectangleF rct = e.Bounds;
5154 rct.Width = e.Header.Width;
5155 int fontHeight = e.Item.Font.Height;
5158 rct.Y += fontHeight;
5159 rct.Height -= fontHeight;
5162 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out var heightDiff));
5164 //if (heightDiff > fontHeight * 0.7)
5166 // rct.Height += fontHeight;
5167 // drawLineCount += 1;
5170 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5171 if (!_iconCol && drawLineCount <= 1)
5173 //rct.Inflate(0, heightDiff / -2);
5174 //rct.Height += fontHeight / 2;
5176 else if (heightDiff < fontHeight * 0.7)
5178 //最終行が70%以上欠けていたら、最終行は表示しない
5179 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5180 rct.Height = (fontHeight * drawLineCount) - 1;
5187 //if (!_iconCol && drawLineCount > 1)
5189 // rct.Y += fontHeight * 0.2;
5190 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5195 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5196 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5201 Rectangle rctB = e.Bounds;
5202 rctB.Width = e.Header.Width;
5203 rctB.Height = fontHeight;
5205 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5207 TextRenderer.DrawText(e.Graphics,
5208 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5210 Rectangle.Round(rct),
5212 TextFormatFlags.WordBreak |
5213 TextFormatFlags.EndEllipsis |
5214 TextFormatFlags.GlyphOverhangPadding |
5215 TextFormatFlags.NoPrefix);
5216 TextRenderer.DrawText(e.Graphics,
5217 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 + "]",
5221 TextFormatFlags.SingleLine |
5222 TextFormatFlags.EndEllipsis |
5223 TextFormatFlags.GlyphOverhangPadding |
5224 TextFormatFlags.NoPrefix);
5230 if (e.ColumnIndex != 2)
5231 text = e.SubItem.Text;
5233 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5235 if (drawLineCount == 1)
5237 TextRenderer.DrawText(e.Graphics,
5240 Rectangle.Round(rct),
5242 TextFormatFlags.SingleLine |
5243 TextFormatFlags.EndEllipsis |
5244 TextFormatFlags.GlyphOverhangPadding |
5245 TextFormatFlags.NoPrefix |
5246 TextFormatFlags.VerticalCenter);
5250 TextRenderer.DrawText(e.Graphics,
5253 Rectangle.Round(rct),
5255 TextFormatFlags.WordBreak |
5256 TextFormatFlags.EndEllipsis |
5257 TextFormatFlags.GlyphOverhangPadding |
5258 TextFormatFlags.NoPrefix);
5261 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5266 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5268 if (_iconSz == 0) return;
5270 ImageListViewItem item = (ImageListViewItem)e.Item;
5272 //e.Bounds.Leftが常に0を指すから自前で計算
5273 Rectangle itemRect = item.Bounds;
5274 var col0 = e.Item.ListView.Columns[0];
5275 itemRect.Width = col0.Width;
5277 if (col0.DisplayIndex > 0)
5279 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5281 if (clm.DisplayIndex < col0.DisplayIndex)
5282 itemRect.X += clm.Width;
5286 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5287 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5288 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5291 var img = item.Image;
5294 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5295 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5297 if (iconRect.Width > 0)
5299 e.Graphics.FillRectangle(Brushes.White, iconRect);
5300 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5303 e.Graphics.DrawImage(img.Image, iconRect);
5305 catch (ArgumentException)
5307 item.RefreshImageAsync();
5313 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5314 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5316 item.GetImageAsync();
5319 if (item.StateIndex > -1)
5321 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5322 if (stateRect.Width > 0)
5324 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5325 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5326 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5331 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5333 base.ScaleControl(factor, specified);
5335 ScaleChildControl(this.TabImage, factor);
5337 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5338 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5340 foreach (var listview in listviews)
5342 ScaleChildControl(listview, factor);
5346 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5348 // ImageListViewItem item = (ImageListViewItem)e.Item;
5349 // if (item.StateImageIndex > -1)
5351 // ////e.Bounds.Leftが常に0を指すから自前で計算
5352 // //Rectangle itemRect = item.Bounds;
5353 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5355 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5357 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5359 // // itemRect.X += clm.Width;
5363 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5364 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5366 // if (rct.Width > 0)
5368 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5369 // //e.Graphics.FillRectangle(Brushes.White, rct);
5370 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5371 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5376 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5378 var tab = this._statuses.Tabs[this._curTab.Text];
5380 if (tab.AllCount == 0)
5382 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5386 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5391 case SEARCHTYPE.NextSearch: // 次を検索
5392 if (selectedIndex != -1)
5393 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5397 case SEARCHTYPE.PrevSearch: // 前を検索
5398 if (selectedIndex != -1)
5399 startIndex = Math.Max(selectedIndex - 1, 0);
5401 startIndex = tab.AllCount - 1;
5403 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5405 if (selectedIndex != -1)
5406 startIndex = selectedIndex;
5412 Func<string, bool> stringComparer;
5415 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5417 catch (ArgumentException)
5419 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5423 var reverse = searchType == SEARCHTYPE.PrevSearch;
5424 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5425 .DefaultIfEmpty(-1).First();
5427 if (foundIndex == -1)
5429 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5433 this.SelectListItem(this._curList, foundIndex);
5434 this._curList.EnsureVisible(foundIndex);
5437 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5440 this.ShowSearchDialog();
5443 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5445 var previousSearch = this.SearchDialog.ResultOptions;
5446 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5448 this.SearchDialog.Reset();
5449 this.ShowSearchDialog();
5455 previousSearch.Query,
5456 previousSearch.CaseSensitive,
5457 previousSearch.UseRegex,
5458 SEARCHTYPE.NextSearch);
5461 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5463 var previousSearch = this.SearchDialog.ResultOptions;
5464 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5466 this.SearchDialog.Reset();
5467 this.ShowSearchDialog();
5473 previousSearch.Query,
5474 previousSearch.CaseSensitive,
5475 previousSearch.UseRegex,
5476 SEARCHTYPE.PrevSearch);
5480 /// 検索ダイアログを表示し、検索を実行します
5482 private void ShowSearchDialog()
5484 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5486 this.TopMost = SettingManager.Common.AlwaysTop;
5489 this.TopMost = SettingManager.Common.AlwaysTop;
5491 var searchOptions = this.SearchDialog.ResultOptions;
5492 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5494 if (searchOptions.NewTab)
5496 var tabName = Properties.Resources.SearchResults_TabName;
5500 tabName = this._statuses.MakeTabName(tabName);
5502 catch (TabException ex)
5504 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5507 var resultTab = new LocalSearchTabModel(tabName);
5508 this.AddNewTab(resultTab, startup: false);
5509 this._statuses.AddTab(resultTab);
5511 var targetTab = this._statuses.Tabs[this._curTab.Text];
5513 Func<string, bool> stringComparer;
5516 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5518 catch (ArgumentException)
5520 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5524 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5525 if (foundIndices.Length == 0)
5527 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5531 var foundPosts = foundIndices.Select(x => targetTab[x]);
5532 foreach (var post in foundPosts)
5534 resultTab.AddPostQueue(post);
5537 this._statuses.DistributePosts();
5538 this.RefreshTimeline();
5540 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5541 .First(x => x.Text == tabName);
5543 this.ListTab.SelectedTab = tabPage;
5548 searchOptions.Query,
5549 searchOptions.CaseSensitive,
5550 searchOptions.UseRegex,
5551 SEARCHTYPE.DialogSearch);
5554 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5556 this.AddNewTabForSearch(searchOptions.Query);
5560 /// <summary>発言検索に使用するメソッドを生成します</summary>
5561 /// <exception cref="ArgumentException">
5562 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5564 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5568 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5569 var regex = new Regex(query, regexOption);
5571 return x => regex.IsMatch(x);
5575 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5577 return x => x.IndexOf(query, comparisonType) != -1;
5581 private void AboutMenuItem_Click(object sender, EventArgs e)
5583 using (TweenAboutBox about = new TweenAboutBox())
5585 about.ShowDialog(this);
5587 this.TopMost = SettingManager.Common.AlwaysTop;
5590 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5592 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5594 if (ImageSelector.Enabled)
5597 TabModel foundTab = null;
5600 DetailsListView lst = null;
5603 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5605 var tabPage = this.ListTab.TabPages[i];
5606 var tab = this._statuses.Tabs[tabPage.Text];
5607 var unreadIndex = tab.NextUnreadIndex;
5609 if (unreadIndex != -1)
5611 ListTab.SelectedIndex = i;
5613 foundIndex = unreadIndex;
5614 lst = (DetailsListView)tabPage.Tag;
5619 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5620 if (foundTab == null && bgnIdx > 0)
5622 for (int i = 0; i < bgnIdx; i++)
5624 var tabPage = this.ListTab.TabPages[i];
5625 var tab = this._statuses.Tabs[tabPage.Text];
5626 var unreadIndex = tab.NextUnreadIndex;
5628 if (unreadIndex != -1)
5630 ListTab.SelectedIndex = i;
5632 foundIndex = unreadIndex;
5633 lst = (DetailsListView)tabPage.Tag;
5639 if (foundTab == null)
5641 //全部調べたが未読見つからず→先頭タブの最新発言へ
5642 ListTab.SelectedIndex = 0;
5643 var tabPage = this.ListTab.TabPages[0];
5644 var tab = this._statuses.Tabs[tabPage.Text];
5646 if (tab.AllCount == 0)
5649 if (_statuses.SortOrder == SortOrder.Ascending)
5650 foundIndex = tab.AllCount - 1;
5654 lst = (DetailsListView)tabPage.Tag;
5657 SelectListItem(lst, foundIndex);
5659 if (_statuses.SortMode == ComparerMode.Id)
5661 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5662 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5668 lst.EnsureVisible(foundIndex);
5673 lst.EnsureVisible(foundIndex);
5679 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5681 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5683 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5684 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5688 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5690 if (_curList.SelectedIndices.Count > 0)
5692 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5693 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5697 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5699 await this.CheckNewVersion(false);
5702 private void RunTweenUp()
5704 ProcessStartInfo pinfo = new ProcessStartInfo();
5705 pinfo.UseShellExecute = true;
5706 pinfo.WorkingDirectory = MyCommon.settingPath;
5707 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5708 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5711 Process.Start(pinfo);
5715 MessageBox.Show("Failed to execute TweenUp3.exe.");
5719 public class VersionInfo
5721 public Version Version { get; set; }
5722 public Uri DownloadUri { get; set; }
5723 public string ReleaseNote { get; set; }
5727 /// OpenTween の最新バージョンの情報を取得します
5729 public async Task<VersionInfo> GetVersionInfoAsync()
5731 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5732 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5734 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5735 .ConfigureAwait(false);
5737 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5738 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5740 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5741 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5743 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5745 return new VersionInfo
5747 Version = Version.Parse(msgHeader[0]),
5748 DownloadUri = new Uri(msgHeader[1]),
5749 ReleaseNote = msgBody,
5753 private async Task CheckNewVersion(bool startup = false)
5755 if (ApplicationSettings.VersionInfoUrl == null)
5756 return; // 更新チェック無効化
5760 var versionInfo = await this.GetVersionInfoAsync();
5762 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5767 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5768 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5769 msgtext = MyCommon.ReplaceAppName(msgtext);
5771 MessageBox.Show(msgtext,
5772 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5773 MessageBoxButtons.OK, MessageBoxIcon.Information);
5778 using (var dialog = new UpdateDialog())
5780 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5781 MyCommon.GetReadableVersion(versionInfo.Version));
5782 dialog.DetailsText = versionInfo.ReleaseNote;
5784 if (dialog.ShowDialog(this) == DialogResult.Yes)
5786 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5792 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5795 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5796 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5797 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5802 private async Task Colorize()
5805 await this.DispSelectedPost();
5806 //件数関連の場合、タイトル即時書き換え
5807 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5808 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5809 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5810 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5812 SetMainWindowTitle();
5814 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5815 SetStatusLabelUrl();
5816 foreach (TabPage tb in ListTab.TabPages)
5818 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5820 if (SettingManager.Common.TabIconDisp)
5822 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5826 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
5829 public string createDetailHtml(string orgdata)
5831 if (SettingManager.Local.UseTwemoji)
5832 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5834 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5837 private Task DispSelectedPost()
5839 return this.DispSelectedPost(false);
5842 private PostClass displayPost = new PostClass();
5845 /// サムネイル表示に使用する CancellationToken の生成元
5847 private CancellationTokenSource thumbnailTokenSource = null;
5849 private async Task DispSelectedPost(bool forceupdate)
5851 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5854 var oldDisplayPost = this.displayPost;
5855 this.displayPost = this._curPost;
5857 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5860 var loadTasks = new List<Task>
5862 this.tweetDetailsView.ShowPostDetails(this._curPost),
5865 this.SplitContainer3.Panel2Collapsed = true;
5867 if (SettingManager.Common.PreviewEnable)
5869 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5870 oldTokenSource?.Cancel();
5872 var token = this.thumbnailTokenSource.Token;
5873 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5878 await Task.WhenAll(loadTasks);
5880 catch (OperationCanceledException) { }
5883 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5885 await this.OpenApplicationWebsite();
5888 private async Task OpenApplicationWebsite()
5890 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5893 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5895 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5898 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5900 if (ListTab.SelectedTab != null)
5902 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
5904 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
5905 if (pnl.Controls["comboSearch"].Focused ||
5906 pnl.Controls["comboLang"].Focused ||
5907 pnl.Controls["buttonSearch"].Focused) return;
5910 if (e.Control || e.Shift || e.Alt)
5911 this._anchorFlag = false;
5913 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
5916 e.SuppressKeyPress = true;
5919 if (asyncTask != null)
5924 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
5926 private void InitializeShortcuts()
5928 this.shortcutCommands = new[]
5930 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5931 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5932 .FocusedOn(FocusedControl.ListTab)
5933 .Do(() => SendKeys.Send("{DOWN}")),
5935 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5936 .FocusedOn(FocusedControl.ListTab)
5937 .Do(() => SendKeys.Send("{UP}")),
5939 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5940 .FocusedOn(FocusedControl.ListTab)
5941 .Do(() => SendKeys.Send("{PGDN}")),
5943 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5944 .FocusedOn(FocusedControl.ListTab)
5945 .Do(() => SendKeys.Send("{PGUP}")),
5947 ShortcutCommand.Create(Keys.F1)
5948 .Do(() => this.OpenApplicationWebsite()),
5950 ShortcutCommand.Create(Keys.F3)
5951 .Do(() => this.MenuItemSearchNext_Click(null, null)),
5953 ShortcutCommand.Create(Keys.F5)
5954 .Do(() => this.DoRefresh()),
5956 ShortcutCommand.Create(Keys.F6)
5957 .Do(() => this.GetReplyAsync()),
5959 ShortcutCommand.Create(Keys.F7)
5960 .Do(() => this.GetDirectMessagesAsync()),
5962 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5963 .NotFocusedOn(FocusedControl.StatusText)
5964 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5966 ShortcutCommand.Create(Keys.G)
5967 .NotFocusedOn(FocusedControl.StatusText)
5968 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5970 ShortcutCommand.Create(Keys.Right, Keys.N)
5971 .FocusedOn(FocusedControl.ListTab)
5972 .Do(() => this.GoRelPost(forward: true)),
5974 ShortcutCommand.Create(Keys.Left, Keys.P)
5975 .FocusedOn(FocusedControl.ListTab)
5976 .Do(() => this.GoRelPost(forward: false)),
5978 ShortcutCommand.Create(Keys.OemPeriod)
5979 .FocusedOn(FocusedControl.ListTab)
5980 .Do(() => this.GoAnchor()),
5982 ShortcutCommand.Create(Keys.I)
5983 .FocusedOn(FocusedControl.ListTab)
5984 .OnlyWhen(() => this.StatusText.Enabled)
5985 .Do(() => this.StatusText.Focus()),
5987 ShortcutCommand.Create(Keys.Enter)
5988 .FocusedOn(FocusedControl.ListTab)
5989 .Do(() => this.MakeReplyOrDirectStatus()),
5991 ShortcutCommand.Create(Keys.R)
5992 .FocusedOn(FocusedControl.ListTab)
5993 .Do(() => this.DoRefresh()),
5995 ShortcutCommand.Create(Keys.L)
5996 .FocusedOn(FocusedControl.ListTab)
5997 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5999 ShortcutCommand.Create(Keys.H)
6000 .FocusedOn(FocusedControl.ListTab)
6001 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6003 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6004 .FocusedOn(FocusedControl.ListTab)
6005 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6007 ShortcutCommand.Create(Keys.S)
6008 .FocusedOn(FocusedControl.ListTab)
6009 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6011 ShortcutCommand.Create(Keys.A)
6012 .FocusedOn(FocusedControl.ListTab)
6013 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6015 // ] in_reply_to参照元へ戻る
6016 ShortcutCommand.Create(Keys.Oem4)
6017 .FocusedOn(FocusedControl.ListTab)
6018 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6020 // [ in_reply_toへジャンプ
6021 ShortcutCommand.Create(Keys.Oem6)
6022 .FocusedOn(FocusedControl.ListTab)
6023 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6025 ShortcutCommand.Create(Keys.Escape)
6026 .FocusedOn(FocusedControl.ListTab)
6028 this._anchorFlag = false;
6029 if (ListTab.SelectedTab != null)
6031 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6032 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6034 var relTp = ListTab.SelectedTab;
6035 RemoveSpecifiedTab(relTp.Text, false);
6041 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
6042 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
6043 .FocusedOn(FocusedControl.ListTab)
6044 .Do(() => this._anchorFlag = false, preventDefault: false),
6046 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6047 ShortcutCommand.Create(Keys.Up, Keys.Down)
6048 .FocusedOn(FocusedControl.PostBrowser)
6051 ShortcutCommand.Create(Keys.Control | Keys.R)
6052 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6054 ShortcutCommand.Create(Keys.Control | Keys.D)
6055 .Do(() => this.doStatusDelete()),
6057 ShortcutCommand.Create(Keys.Control | Keys.M)
6058 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6060 ShortcutCommand.Create(Keys.Control | Keys.S)
6061 .Do(() => this.FavoriteChange(FavAdd: true)),
6063 ShortcutCommand.Create(Keys.Control | Keys.I)
6064 .Do(() => this.doRepliedStatusOpen()),
6066 ShortcutCommand.Create(Keys.Control | Keys.Q)
6067 .Do(() => this.doQuoteOfficial()),
6069 ShortcutCommand.Create(Keys.Control | Keys.B)
6070 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6072 ShortcutCommand.Create(Keys.Control | Keys.T)
6073 .Do(() => this.HashManageMenuItem_Click(null, null)),
6075 ShortcutCommand.Create(Keys.Control | Keys.L)
6076 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6078 ShortcutCommand.Create(Keys.Control | Keys.Y)
6079 .NotFocusedOn(FocusedControl.PostBrowser)
6080 .Do(() => this.MultiLineMenuItem_Click(null, null)),
6082 ShortcutCommand.Create(Keys.Control | Keys.F)
6083 .Do(() => this.MenuItemSubSearch_Click(null, null)),
6085 ShortcutCommand.Create(Keys.Control | Keys.U)
6086 .Do(() => this.ShowUserTimeline()),
6088 ShortcutCommand.Create(Keys.Control | Keys.H)
6089 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6091 ShortcutCommand.Create(Keys.Control | Keys.G)
6092 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6094 ShortcutCommand.Create(Keys.Control | Keys.O)
6095 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6097 ShortcutCommand.Create(Keys.Control | Keys.E)
6098 .Do(() => this.OpenURLMenuItem_Click(null, null)),
6100 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6101 .FocusedOn(FocusedControl.ListTab)
6102 .Do(() => this._colorize = true, preventDefault: false),
6104 ShortcutCommand.Create(Keys.Control | Keys.N)
6105 .FocusedOn(FocusedControl.ListTab)
6106 .Do(() => this.GoNextTab(forward: true)),
6108 ShortcutCommand.Create(Keys.Control | Keys.P)
6109 .FocusedOn(FocusedControl.ListTab)
6110 .Do(() => this.GoNextTab(forward: false)),
6112 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6113 .FocusedOn(FocusedControl.ListTab)
6114 .Do(() => this.CopyStot()),
6116 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6117 ShortcutCommand.Create(Keys.Control | Keys.D1)
6118 .FocusedOn(FocusedControl.ListTab)
6119 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6120 .Do(() => this.ListTab.SelectedIndex = 0),
6122 ShortcutCommand.Create(Keys.Control | Keys.D2)
6123 .FocusedOn(FocusedControl.ListTab)
6124 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6125 .Do(() => this.ListTab.SelectedIndex = 1),
6127 ShortcutCommand.Create(Keys.Control | Keys.D3)
6128 .FocusedOn(FocusedControl.ListTab)
6129 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6130 .Do(() => this.ListTab.SelectedIndex = 2),
6132 ShortcutCommand.Create(Keys.Control | Keys.D4)
6133 .FocusedOn(FocusedControl.ListTab)
6134 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6135 .Do(() => this.ListTab.SelectedIndex = 3),
6137 ShortcutCommand.Create(Keys.Control | Keys.D5)
6138 .FocusedOn(FocusedControl.ListTab)
6139 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6140 .Do(() => this.ListTab.SelectedIndex = 4),
6142 ShortcutCommand.Create(Keys.Control | Keys.D6)
6143 .FocusedOn(FocusedControl.ListTab)
6144 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6145 .Do(() => this.ListTab.SelectedIndex = 5),
6147 ShortcutCommand.Create(Keys.Control | Keys.D7)
6148 .FocusedOn(FocusedControl.ListTab)
6149 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6150 .Do(() => this.ListTab.SelectedIndex = 6),
6152 ShortcutCommand.Create(Keys.Control | Keys.D8)
6153 .FocusedOn(FocusedControl.ListTab)
6154 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6155 .Do(() => this.ListTab.SelectedIndex = 7),
6157 ShortcutCommand.Create(Keys.Control | Keys.D9)
6158 .FocusedOn(FocusedControl.ListTab)
6159 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6161 ShortcutCommand.Create(Keys.Control | Keys.A)
6162 .FocusedOn(FocusedControl.StatusText)
6163 .Do(() => this.StatusText.SelectAll()),
6165 ShortcutCommand.Create(Keys.Control | Keys.V)
6166 .FocusedOn(FocusedControl.StatusText)
6167 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6169 ShortcutCommand.Create(Keys.Control | Keys.Up)
6170 .FocusedOn(FocusedControl.StatusText)
6172 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6174 var inReplyToStatusId = this.inReplyTo?.Item1;
6175 var inReplyToScreenName = this.inReplyTo?.Item2;
6176 _history[_hisIdx] = new StatusTextHistory(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6179 if (_hisIdx < 0) _hisIdx = 0;
6181 var historyItem = this._history[this._hisIdx];
6182 if (historyItem.inReplyToId != null)
6183 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6185 this.inReplyTo = null;
6186 StatusText.Text = historyItem.status;
6187 StatusText.SelectionStart = StatusText.Text.Length;
6190 ShortcutCommand.Create(Keys.Control | Keys.Down)
6191 .FocusedOn(FocusedControl.StatusText)
6193 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6195 var inReplyToStatusId = this.inReplyTo?.Item1;
6196 var inReplyToScreenName = this.inReplyTo?.Item2;
6197 _history[_hisIdx] = new StatusTextHistory(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6200 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6202 var historyItem = this._history[this._hisIdx];
6203 if (historyItem.inReplyToId != null)
6204 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6206 this.inReplyTo = null;
6207 StatusText.Text = historyItem.status;
6208 StatusText.SelectionStart = StatusText.Text.Length;
6211 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6212 .FocusedOn(FocusedControl.StatusText)
6214 if (ListTab.SelectedIndex == 0)
6216 ListTab.SelectedIndex = ListTab.TabCount - 1;
6220 ListTab.SelectedIndex -= 1;
6225 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6226 .FocusedOn(FocusedControl.StatusText)
6228 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6230 ListTab.SelectedIndex = 0;
6234 ListTab.SelectedIndex += 1;
6239 ShortcutCommand.Create(Keys.Control | Keys.Y)
6240 .FocusedOn(FocusedControl.PostBrowser)
6242 var multiline = !SettingManager.Local.StatusMultiline;
6243 SettingManager.Local.StatusMultiline = multiline;
6244 MultiLineMenuItem.Checked = multiline;
6245 MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
6248 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6249 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6251 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6252 .Do(() => this.DoRefreshMore()),
6254 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6255 .Do(() => this.GetReplyAsync(loadMore: true)),
6257 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6258 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6260 ShortcutCommand.Create(Keys.Shift | Keys.R)
6261 .NotFocusedOn(FocusedControl.StatusText)
6262 .Do(() => this.DoRefreshMore()),
6264 ShortcutCommand.Create(Keys.Shift | Keys.H)
6265 .FocusedOn(FocusedControl.ListTab)
6266 .Do(() => this.GoTopEnd(GoTop: true)),
6268 ShortcutCommand.Create(Keys.Shift | Keys.L)
6269 .FocusedOn(FocusedControl.ListTab)
6270 .Do(() => this.GoTopEnd(GoTop: false)),
6272 ShortcutCommand.Create(Keys.Shift | Keys.M)
6273 .FocusedOn(FocusedControl.ListTab)
6274 .Do(() => this.GoMiddle()),
6276 ShortcutCommand.Create(Keys.Shift | Keys.G)
6277 .FocusedOn(FocusedControl.ListTab)
6278 .Do(() => this.GoLast()),
6280 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6281 .FocusedOn(FocusedControl.ListTab)
6282 .Do(() => this.MoveMiddle()),
6284 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6285 .FocusedOn(FocusedControl.ListTab)
6286 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6288 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6289 .FocusedOn(FocusedControl.ListTab)
6290 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6292 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6293 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6294 .FocusedOn(FocusedControl.ListTab)
6295 .Do(() => this.GoFav(forward: true)),
6297 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6298 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6299 .FocusedOn(FocusedControl.ListTab)
6300 .Do(() => this.GoFav(forward: false)),
6302 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6303 .FocusedOn(FocusedControl.ListTab)
6304 .Do(() => this.GoBackSelectPostChain()),
6306 ShortcutCommand.Create(Keys.Alt | Keys.R)
6307 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6309 ShortcutCommand.Create(Keys.Alt | Keys.P)
6310 .OnlyWhen(() => this._curPost != null)
6311 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6313 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6314 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6316 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6317 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6319 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6320 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6322 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6323 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6325 // 別タブの同じ書き込みへ(ALT+←/→)
6326 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6327 .FocusedOn(FocusedControl.ListTab)
6328 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6330 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6331 .FocusedOn(FocusedControl.ListTab)
6332 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6334 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6335 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6337 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6338 .Do(() => this.CopyIdUri()),
6340 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6341 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6342 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6343 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6345 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6346 .Do(() => this.FavoriteChange(FavAdd: false)),
6348 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6349 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6351 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6352 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6354 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6355 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6357 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6358 .Do(() => this.doMoveToRTHome()),
6360 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6361 .Do(() => this.FavorareMenuItem_Click(null, null)),
6363 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6364 .FocusedOn(FocusedControl.StatusText)
6366 if (_curList != null && _curList.VirtualListSize != 0 &&
6367 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6369 var idx = _curList.SelectedIndices[0] - 1;
6370 SelectListItem(_curList, idx);
6371 _curList.EnsureVisible(idx);
6375 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6376 .FocusedOn(FocusedControl.StatusText)
6378 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6379 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6381 var idx = _curList.SelectedIndices[0] + 1;
6382 SelectListItem(_curList, idx);
6383 _curList.EnsureVisible(idx);
6387 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6388 .FocusedOn(FocusedControl.StatusText)
6390 if (StatusText.SelectionStart > 0)
6392 int endidx = StatusText.SelectionStart - 1;
6393 string startstr = "";
6394 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6396 char c = StatusText.Text[i];
6397 if (Char.IsLetterOrDigit(c) || c == '_')
6403 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6404 int cnt = AtIdSupl.ItemCount;
6405 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6406 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6410 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6411 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6421 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6422 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6423 .FocusedOn(FocusedControl.ListTab)
6424 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6426 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6427 .FocusedOn(FocusedControl.ListTab)
6428 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6430 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6431 .FocusedOn(FocusedControl.ListTab)
6432 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6434 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6435 .FocusedOn(FocusedControl.ListTab)
6436 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6438 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6439 .FocusedOn(FocusedControl.ListTab)
6440 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6442 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6443 .FocusedOn(FocusedControl.ListTab)
6444 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6446 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6447 .FocusedOn(FocusedControl.ListTab)
6448 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6450 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6451 .FocusedOn(FocusedControl.ListTab)
6452 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6454 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6455 .FocusedOn(FocusedControl.ListTab)
6456 .Do(() => this.SetSortLastColumn()),
6458 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6459 .Do(() => this.FavoritesRetweetOfficial()),
6461 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6462 .Do(() => this.FavoritesRetweetUnofficial()),
6464 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6465 .Do(() => this.OpenUserAppointUrl()),
6467 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6468 .FocusedOn(FocusedControl.PostBrowser)
6469 .Do(() => this.doReTweetUnofficial()),
6471 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6472 .OnlyWhen(() => this.ExistCurrentPost)
6473 .Do(() => this.tweetDetailsView.DoTranslation()),
6475 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6476 .Do(() => this.doReTweetUnofficial()),
6478 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6479 .Do(() => this.CopyUserId()),
6481 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6482 .Do(() => this.tweetThumbnail1.ScrollUp()),
6484 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6485 .Do(() => this.tweetThumbnail1.ScrollDown()),
6487 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6488 .FocusedOn(FocusedControl.ListTab)
6489 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6490 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6494 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6496 // Task を返す非同期処理があれば asyncTask に代入する
6499 // ShortcutCommand に対応しているコマンドはここで処理される
6500 foreach (var command in this.shortcutCommands)
6502 if (command.IsMatch(keyData, focusedOn))
6504 asyncTask = command.RunCommand();
6505 return command.PreventDefault;
6512 private void GoNextTab(bool forward)
6514 int idx = ListTab.SelectedIndex;
6518 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6523 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6525 ListTab.SelectedIndex = idx;
6528 private void CopyStot()
6531 StringBuilder sb = new StringBuilder();
6532 bool IsProtected = false;
6534 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6535 foreach (int idx in _curList.SelectedIndices)
6537 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6538 if (post.IsDeleted) continue;
6541 if (post.RetweetedId != null)
6542 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6544 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6548 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6553 MessageBox.Show(Properties.Resources.CopyStotText1);
6557 clstr = sb.ToString();
6560 Clipboard.SetDataObject(clstr, false, 5, 100);
6562 catch (Exception ex)
6564 MessageBox.Show(ex.Message);
6569 private void CopyIdUri()
6571 if (this._curTab == null)
6574 var tab = this._statuses.GetTabByName(this._curTab.Text);
6575 if (tab == null || tab is DirectMessagesTabModel)
6578 var copyUrls = new List<string>();
6579 foreach (int idx in _curList.SelectedIndices)
6581 var post = tab[idx];
6582 copyUrls.Add(MyCommon.GetStatusUrl(post));
6585 if (copyUrls.Count == 0)
6590 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6592 catch (ExternalException ex)
6594 MessageBox.Show(ex.Message);
6598 private void GoFav(bool forward)
6600 if (_curList.VirtualListSize == 0) return;
6607 if (_curList.SelectedIndices.Count == 0)
6613 fIdx = _curList.SelectedIndices[0] + 1;
6614 if (fIdx > _curList.VirtualListSize - 1) return;
6616 toIdx = _curList.VirtualListSize;
6621 if (_curList.SelectedIndices.Count == 0)
6623 fIdx = _curList.VirtualListSize - 1;
6627 fIdx = _curList.SelectedIndices[0] - 1;
6628 if (fIdx < 0) return;
6634 for (int idx = fIdx; idx != toIdx; idx += stp)
6636 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6638 SelectListItem(_curList, idx);
6639 _curList.EnsureVisible(idx);
6645 private void GoSamePostToAnotherTab(bool left)
6647 if (this._curList.SelectedIndices.Count == 0)
6650 var tab = this._statuses.Tabs[this._curTab.Text];
6652 // Directタブは対象外(見つかるはずがない)
6653 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6656 var selectedIndex = this._curList.SelectedIndices[0];
6657 var selectedStatusId = tab.GetStatusIdAt(selectedIndex);
6659 int fIdx, toIdx, stp;
6664 if (ListTab.SelectedIndex == 0)
6670 fIdx = ListTab.SelectedIndex - 1;
6678 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6684 fIdx = ListTab.SelectedIndex + 1;
6686 toIdx = ListTab.TabCount;
6690 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6692 var targetTab = this._statuses.Tabs[this.ListTab.TabPages[tabidx].Text];
6695 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6698 var foundIndex = targetTab.IndexOf(selectedStatusId);
6699 if (foundIndex != -1)
6701 ListTab.SelectedIndex = tabidx;
6702 SelectListItem(_curList, foundIndex);
6703 _curList.EnsureVisible(foundIndex);
6709 private void GoPost(bool forward)
6711 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6714 var tab = this._statuses.Tabs[this._curTab.Text];
6715 var selectedIndex = this._curList.SelectedIndices[0];
6717 int fIdx, toIdx, stp;
6721 fIdx = selectedIndex + 1;
6722 if (fIdx > tab.AllCount - 1) return;
6723 toIdx = tab.AllCount;
6728 fIdx = selectedIndex - 1;
6729 if (fIdx < 0) return;
6735 if (_curPost.RetweetedId == null)
6737 name = _curPost.ScreenName;
6741 name = _curPost.RetweetedBy;
6743 for (int idx = fIdx; idx != toIdx; idx += stp)
6745 var post = tab[idx];
6746 if (post.RetweetedId == null)
6748 if (post.ScreenName == name)
6750 SelectListItem(_curList, idx);
6751 _curList.EnsureVisible(idx);
6757 if (post.RetweetedBy == name)
6759 SelectListItem(_curList, idx);
6760 _curList.EnsureVisible(idx);
6767 private void GoRelPost(bool forward)
6769 if (this._curList.SelectedIndices.Count == 0)
6772 var tab = this._statuses.Tabs[this._curTab.Text];
6773 var selectedIndex = this._curList.SelectedIndices[0];
6775 int fIdx, toIdx, stp;
6779 fIdx = selectedIndex + 1;
6780 if (fIdx > tab.AllCount - 1) return;
6781 toIdx = tab.AllCount;
6786 fIdx = selectedIndex - 1;
6787 if (fIdx < 0) return;
6794 if (_curPost == null) return;
6795 _anchorPost = _curPost;
6800 if (_anchorPost == null) return;
6803 for (int idx = fIdx; idx != toIdx; idx += stp)
6805 var post = tab[idx];
6806 if (post.ScreenName == _anchorPost.ScreenName ||
6807 post.RetweetedBy == _anchorPost.ScreenName ||
6808 post.ScreenName == _anchorPost.RetweetedBy ||
6809 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6810 _anchorPost.ReplyToList.Any(x => x.Item1 == post.UserId) ||
6811 _anchorPost.ReplyToList.Any(x => x.Item1 == post.RetweetedByUserId) ||
6812 post.ReplyToList.Any(x => x.Item1 == _anchorPost.UserId) ||
6813 post.ReplyToList.Any(x => x.Item1 == _anchorPost.RetweetedByUserId))
6815 SelectListItem(_curList, idx);
6816 _curList.EnsureVisible(idx);
6822 private void GoAnchor()
6824 if (_anchorPost == null) return;
6825 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6826 if (idx == -1) return;
6828 SelectListItem(_curList, idx);
6829 _curList.EnsureVisible(idx);
6832 private void GoTopEnd(bool GoTop)
6834 if (_curList.VirtualListSize == 0)
6842 _item = _curList.GetItemAt(0, 25);
6850 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6852 idx = _curList.VirtualListSize - 1;
6856 SelectListItem(_curList, idx);
6859 private void GoMiddle()
6861 if (_curList.VirtualListSize == 0)
6869 _item = _curList.GetItemAt(0, 0);
6879 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6882 idx2 = _curList.VirtualListSize - 1;
6888 idx3 = (idx1 + idx2) / 2;
6890 SelectListItem(_curList, idx3);
6893 private void GoLast()
6895 if (_curList.VirtualListSize == 0) return;
6897 if (_statuses.SortOrder == SortOrder.Ascending)
6899 SelectListItem(_curList, _curList.VirtualListSize - 1);
6900 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6904 SelectListItem(_curList, 0);
6905 _curList.EnsureVisible(0);
6909 private void MoveTop()
6911 if (_curList.SelectedIndices.Count == 0) return;
6912 int idx = _curList.SelectedIndices[0];
6913 if (_statuses.SortOrder == SortOrder.Ascending)
6915 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6919 _curList.EnsureVisible(0);
6921 _curList.EnsureVisible(idx);
6924 private async Task GoInReplyToPostTree()
6926 if (_curPost == null) return;
6928 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6930 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
6934 var post = await tw.GetStatusApi(false, _curPost.StatusId);
6936 _curPost.InReplyToStatusId = post.InReplyToStatusId;
6937 _curPost.InReplyToUser = post.InReplyToUser;
6938 _curPost.IsReply = post.IsReply;
6939 this.PurgeListViewItemCache();
6940 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
6942 catch (WebApiException ex)
6944 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6948 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
6950 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
6952 replyChains = new Stack<ReplyChain>();
6954 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
6957 string inReplyToTabName;
6958 long inReplyToId = _curPost.InReplyToStatusId.Value;
6959 string inReplyToUser = _curPost.InReplyToUser;
6960 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6962 var inReplyToPosts = from tab in _statuses.Tabs.Values
6963 orderby tab != curTabClass
6964 from post in tab.Posts.Values
6965 where post.StatusId == inReplyToId
6966 let index = tab.IndexOf(post.StatusId)
6968 select new {Tab = tab, Index = index};
6970 var inReplyPost = inReplyToPosts.FirstOrDefault();
6971 if (inReplyPost == null)
6975 await Task.Run(async () =>
6977 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
6978 .ConfigureAwait(false);
6981 _statuses.AddPost(post);
6982 _statuses.DistributePosts();
6985 catch (WebApiException ex)
6987 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6988 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6992 this.RefreshTimeline();
6994 inReplyPost = inReplyToPosts.FirstOrDefault();
6995 if (inReplyPost == null)
6997 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
7001 inReplyToTabName = inReplyPost.Tab.TabName;
7002 inReplyToIndex = inReplyPost.Index;
7004 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7005 DetailsListView listView = (DetailsListView)tabPage.Tag;
7007 if (_curTab != tabPage)
7009 this.ListTab.SelectTab(tabPage);
7012 this.SelectListItem(listView, inReplyToIndex);
7013 listView.EnsureVisible(inReplyToIndex);
7016 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7018 if (_curPost == null) return;
7020 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
7021 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7025 if (_curPost.InReplyToStatusId != null)
7027 var posts = from t in _statuses.Tabs
7028 from p in t.Value.Posts
7029 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7030 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7032 orderby isForward ? indexOf : indexOf * -1
7033 orderby t.Value != curTabClass
7034 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7037 var postList = posts.ToList();
7038 for (int i = postList.Count - 1; i >= 0; i--)
7041 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7043 postList.RemoveAt(index);
7046 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7047 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7048 if (post == null) post = postList.First();
7049 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7050 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7051 SelectListItem(listView, post.Index);
7052 listView.EnsureVisible(post.Index);
7054 catch (InvalidOperationException)
7062 if (replyChains == null || replyChains.Count < 1)
7064 var posts = from t in _statuses.Tabs
7065 from p in t.Value.Posts
7066 where p.Value.InReplyToStatusId == _curPost.StatusId
7067 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7070 orderby t.Value != curTabClass
7071 select new {Tab = t.Value, Index = indexOf};
7074 var post = posts.First();
7075 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7076 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7077 SelectListItem(listView, post.Index);
7078 listView.EnsureVisible(post.Index);
7080 catch (InvalidOperationException)
7087 ReplyChain chainHead = replyChains.Pop();
7088 if (chainHead.InReplyToId == _curPost.StatusId)
7090 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7099 ListTab.SelectTab(chainHead.OriginalTab);
7105 SelectListItem(_curList, idx);
7106 _curList.EnsureVisible(idx);
7112 this.GoBackInReplyToPostTree(parallel);
7118 private void GoBackSelectPostChain()
7120 if (this.selectPostChains.Count > 1)
7129 this.selectPostChains.Pop();
7130 var (tabPage, post) = this.selectPostChains.Peek();
7132 if (!this.ListTab.TabPages.Contains(tabPage)) continue; //該当タブが存在しないので無視
7136 idx = this._statuses.Tabs[tabPage.Text].IndexOf(post.StatusId);
7137 if (idx == -1) continue; //該当ポストが存在しないので無視
7142 this.selectPostChains.Pop();
7144 catch (InvalidOperationException)
7150 while (this.selectPostChains.Count > 1);
7155 //履歴が残り1つであればクリアしておく
7156 if (this.selectPostChains.Count == 1)
7157 this.selectPostChains.Clear();
7161 DetailsListView lst = (DetailsListView)tp.Tag;
7162 this.ListTab.SelectedTab = tp;
7165 SelectListItem(lst, idx);
7166 lst.EnsureVisible(idx);
7172 private void PushSelectPostChain()
7174 int count = this.selectPostChains.Count;
7177 var (tabPage, post) = this.selectPostChains.Peek();
7178 if (tabPage == this._curTab)
7180 if (post == this._curPost) return; //最新の履歴と同一
7181 if (post == null) this.selectPostChains.Pop(); //置き換えるため削除
7184 if (count >= 2500) TrimPostChain();
7185 this.selectPostChains.Push((this._curTab, this._curPost));
7188 private void TrimPostChain()
7190 if (this.selectPostChains.Count <= 2000) return;
7191 var p = new Stack<ValueTuple<TabPage, PostClass>>(2000);
7192 for (int i = 0; i < 2000; i++)
7194 p.Push(this.selectPostChains.Pop());
7196 this.selectPostChains.Clear();
7197 for (int i = 0; i < 2000; i++)
7199 this.selectPostChains.Push(p.Pop());
7203 private bool GoStatus(long statusId)
7205 if (statusId == 0) return false;
7206 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7208 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7210 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7211 ListTab.SelectedIndex = tabidx;
7212 SelectListItem(_curList, idx);
7213 _curList.EnsureVisible(idx);
7220 private bool GoDirectMessage(long statusId)
7222 if (statusId == 0) return false;
7223 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7225 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7227 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7228 ListTab.SelectedIndex = tabidx;
7229 SelectListItem(_curList, idx);
7230 _curList.EnsureVisible(idx);
7237 private void MyList_MouseClick(object sender, MouseEventArgs e)
7239 _anchorFlag = false;
7242 private void StatusText_Enter(object sender, EventArgs e)
7244 // フォーカスの戻り先を StatusText に設定
7245 this.Tag = StatusText;
7246 StatusText.BackColor = _clInputBackcolor;
7249 public Color InputBackColor
7251 get => _clInputBackcolor;
7252 set => _clInputBackcolor = value;
7255 private void StatusText_Leave(object sender, EventArgs e)
7257 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7258 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7259 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7262 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7264 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
7267 e.SuppressKeyPress = true;
7270 this.StatusText_TextChanged(null, null);
7272 if (asyncTask != null)
7276 private void SaveConfigsAll(bool ifModified)
7280 SaveConfigsCommon();
7287 if (ModifySettingCommon) SaveConfigsCommon();
7288 if (ModifySettingLocal) SaveConfigsLocal();
7289 if (ModifySettingAtId) SaveConfigsAtId();
7293 private void SaveConfigsAtId()
7295 if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7297 ModifySettingAtId = false;
7298 SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7299 SettingManager.SaveAtIdList();
7302 private void SaveConfigsCommon()
7304 if (_ignoreConfigSave) return;
7306 ModifySettingCommon = false;
7309 SettingManager.Common.UserName = tw.Username;
7310 SettingManager.Common.UserId = tw.UserId;
7311 SettingManager.Common.Token = tw.AccessToken;
7312 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7313 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7314 switch (_statuses.SortMode)
7316 case ComparerMode.Nickname: //ニックネーム
7317 SettingManager.Common.SortColumn = 1;
7319 case ComparerMode.Data: //本文
7320 SettingManager.Common.SortColumn = 2;
7322 case ComparerMode.Id: //時刻=発言Id
7323 SettingManager.Common.SortColumn = 3;
7325 case ComparerMode.Name: //名前
7326 SettingManager.Common.SortColumn = 4;
7328 case ComparerMode.Source: //Source
7329 SettingManager.Common.SortColumn = 7;
7333 SettingManager.Common.HashTags = HashMgr.HashHistories;
7334 if (HashMgr.IsPermanent)
7336 SettingManager.Common.HashSelected = HashMgr.UseHash;
7340 SettingManager.Common.HashSelected = "";
7342 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7343 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7344 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7345 SettingManager.Common.TrackWord = tw.TrackWord;
7346 SettingManager.Common.AllAtReply = tw.AllAtReply;
7347 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7348 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7350 SettingManager.SaveCommon();
7354 private void SaveConfigsLocal()
7356 if (_ignoreConfigSave) return;
7359 ModifySettingLocal = false;
7360 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7361 SettingManager.Local.FormSize = _mySize;
7362 SettingManager.Local.FormLocation = _myLoc;
7363 SettingManager.Local.SplitterDistance = _mySpDis;
7364 SettingManager.Local.PreviewDistance = _mySpDis3;
7365 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7366 SettingManager.Local.StatusTextHeight = _mySpDis2;
7368 SettingManager.Local.FontUnread = _fntUnread;
7369 SettingManager.Local.ColorUnread = _clUnread;
7370 SettingManager.Local.FontRead = _fntReaded;
7371 SettingManager.Local.ColorRead = _clReaded;
7372 SettingManager.Local.FontDetail = _fntDetail;
7373 SettingManager.Local.ColorDetail = _clDetail;
7374 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7375 SettingManager.Local.ColorDetailLink = _clDetailLink;
7376 SettingManager.Local.ColorFav = _clFav;
7377 SettingManager.Local.ColorOWL = _clOWL;
7378 SettingManager.Local.ColorRetweet = _clRetweet;
7379 SettingManager.Local.ColorSelf = _clSelf;
7380 SettingManager.Local.ColorAtSelf = _clAtSelf;
7381 SettingManager.Local.ColorTarget = _clTarget;
7382 SettingManager.Local.ColorAtTarget = _clAtTarget;
7383 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7384 SettingManager.Local.ColorAtTo = _clAtTo;
7385 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7386 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7387 SettingManager.Local.ColorInputFont = _clInputFont;
7388 SettingManager.Local.FontInputFont = _fntInputFont;
7390 if (_ignoreConfigSave) return;
7391 SettingManager.SaveLocal();
7395 private void SaveConfigsTabs()
7397 var tabSettingList = new List<SettingTabs.SettingTabItem>();
7399 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7400 .Select(x => this._statuses.Tabs[x.Text])
7401 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7403 foreach (var tab in tabs)
7405 if (!tab.IsPermanentTabType)
7408 var tabSetting = new SettingTabs.SettingTabItem
7410 TabName = tab.TabName,
7411 TabType = tab.TabType,
7412 UnreadManage = tab.UnreadManage,
7413 Protected = tab.Protected,
7414 Notify = tab.Notify,
7415 SoundFile = tab.SoundFile,
7420 case FilterTabModel filterTab:
7421 tabSetting.FilterArray = filterTab.FilterArray;
7423 case UserTimelineTabModel userTab:
7424 tabSetting.User = userTab.ScreenName;
7426 case PublicSearchTabModel searchTab:
7427 tabSetting.SearchWords = searchTab.SearchWords;
7428 tabSetting.SearchLang = searchTab.SearchLang;
7430 case ListTimelineTabModel listTab:
7431 tabSetting.ListInfo = listTab.ListInfo;
7435 tabSettingList.Add(tabSetting);
7438 SettingManager.Tabs.Tabs = tabSettingList;
7439 SettingManager.SaveTabs();
7442 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7444 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
7445 if (ret != DialogResult.OK)
7448 var match = Twitter.StatusUrlRegex.Match(inputText);
7451 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7452 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7458 var statusId = long.Parse(match.Groups["StatusId"].Value);
7459 await this.OpenRelatedTab(statusId);
7461 catch (TabException ex)
7463 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7467 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7469 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7470 Properties.Resources.SaveLogMenuItem_ClickText2,
7471 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7472 if (rslt == DialogResult.Cancel) return;
7474 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7475 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7476 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7477 SaveFileDialog1.FilterIndex = 0;
7478 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7479 SaveFileDialog1.RestoreDirectory = true;
7481 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7483 if (!SaveFileDialog1.ValidateNames) return;
7484 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7486 if (rslt == DialogResult.Yes)
7489 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7491 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7492 string protect = "";
7493 if (post.IsProtect) protect = "Protect";
7494 sw.WriteLine(post.Nickname + "\t" +
7495 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7496 post.CreatedAt + "\t" +
7497 post.ScreenName + "\t" +
7498 post.StatusId + "\t" +
7499 post.ImageUrl + "\t" +
7500 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7506 foreach (int idx in _curList.SelectedIndices)
7508 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7509 string protect = "";
7510 if (post.IsProtect) protect = "Protect";
7511 sw.WriteLine(post.Nickname + "\t" +
7512 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7513 post.CreatedAt + "\t" +
7514 post.ScreenName + "\t" +
7515 post.StatusId + "\t" +
7516 post.ImageUrl + "\t" +
7517 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7523 this.TopMost = SettingManager.Common.AlwaysTop;
7526 public bool TabRename(string origTabName, out string newTabName)
7530 using (InputTabName inputName = new InputTabName())
7532 inputName.TabName = origTabName;
7533 inputName.ShowDialog();
7534 if (inputName.DialogResult == DialogResult.Cancel) return false;
7535 newTabName = inputName.TabName;
7537 this.TopMost = SettingManager.Common.AlwaysTop;
7538 if (!string.IsNullOrEmpty(newTabName))
7541 for (int i = 0; i < ListTab.TabCount; i++)
7543 if (ListTab.TabPages[i].Text == newTabName)
7545 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7546 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7551 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
7552 .FirstOrDefault(x => x.Text == origTabName);
7555 if (tabPage != null)
7556 tabPage.Text = newTabName;
7558 _statuses.RenameTab(origTabName, newTabName);
7560 SaveConfigsCommon();
7562 _rclickTabName = newTabName;
7571 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7573 if (e.Button == MouseButtons.Middle)
7575 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7577 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7579 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7580 this.SaveConfigsTabs();
7587 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7589 TabRename(this.ListTab.SelectedTab.Text, out var _);
7592 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7594 if (SettingManager.Common.TabMouseLock) return;
7595 if (e.Button == MouseButtons.Left)
7597 for (int i = 0; i < ListTab.TabPages.Count; i++)
7599 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7602 _tabMouseDownPoint = e.Location;
7613 private void ListTab_DragEnter(object sender, DragEventArgs e)
7615 if (e.Data.GetDataPresent(typeof(TabPage)))
7616 e.Effect = DragDropEffects.Move;
7618 e.Effect = DragDropEffects.None;
7621 private void ListTab_DragDrop(object sender, DragEventArgs e)
7623 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7628 Point cpos = new Point(e.X, e.Y);
7629 Point spos = ListTab.PointToClient(cpos);
7631 for (i = 0; i < ListTab.TabPages.Count; i++)
7633 Rectangle rect = ListTab.GetTabRect(i);
7634 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7635 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7637 tn = ListTab.TabPages[i].Text;
7638 if (spos.X <= (rect.Left + rect.Right) / 2)
7647 //タブのないところにドロップ->最後尾へ移動
7648 if (string.IsNullOrEmpty(tn))
7650 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7652 i = ListTab.TabPages.Count - 1;
7655 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7656 if (tp.Text == tn) return;
7658 ReOrderTab(tp.Text, tn, bef);
7661 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7663 var baseIndex = this.GetTabPageIndex(baseTabText);
7664 if (baseIndex == -1)
7667 var targetIndex = this.GetTabPageIndex(targetTabText);
7668 if (targetIndex == -1)
7671 using (ControlTransaction.Layout(this.ListTab))
7673 var mTp = this.ListTab.TabPages[targetIndex];
7674 this.ListTab.TabPages.Remove(mTp);
7676 if (targetIndex < baseIndex)
7679 if (isBeforeBaseTab)
7680 ListTab.TabPages.Insert(baseIndex, mTp);
7682 ListTab.TabPages.Insert(baseIndex + 1, mTp);
7688 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7690 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7691 //isReply:true=@,false=DM
7692 if (!StatusText.Enabled) return;
7693 if (_curList == null) return;
7694 if (_curTab == null) return;
7695 if (!this.ExistCurrentPost) return;
7697 // 複数あてリプライはReplyではなく通常ポスト
7698 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7699 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7700 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7702 if (_curList.SelectedIndices.Count > 0)
7705 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7708 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7711 this.inReplyTo = null;
7712 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7713 StatusText.SelectionStart = StatusText.Text.Length;
7717 if (string.IsNullOrEmpty(StatusText.Text))
7720 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7721 var inReplyToScreenName = this._curPost.ScreenName;
7722 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7724 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7725 StatusText.Text = "@" + _curPost.ScreenName + " ";
7733 //1件選んでEnter or DoubleClick
7734 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7736 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7739 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7740 var inReplyToScreenName = this._curPost.ScreenName;
7741 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7745 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7748 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7751 this.inReplyTo = null;
7752 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7757 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7758 var inReplyToScreenName = this._curPost.ScreenName;
7759 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7760 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7767 this.inReplyTo = null;
7768 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7769 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7774 //1件選んでCtrl-Rの場合(返信先操作せず)
7775 int sidx = StatusText.SelectionStart;
7776 string id = "@" + _curPost.ScreenName + " ";
7779 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7784 StatusText.Text = StatusText.Text.Insert(sidx, id);
7786 //if (StatusText.Text.StartsWith("@"))
7789 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7790 // sidx += 5 + _curPost.ScreenName.Length;
7795 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7796 // sidx += 3 + _curPost.ScreenName.Length;
7798 StatusText.SelectionStart = sidx;
7801 //_reply_to_name = null;
7809 if (!isAuto && !isReply) return;
7811 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7815 //Enter or DoubleClick
7817 string sTxt = StatusText.Text;
7818 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7821 this.inReplyTo = null;
7823 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7825 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7826 if (!sTxt.Contains("@" + post.ScreenName + " "))
7828 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7829 //sTxt = "@" + post.ScreenName + " " + sTxt;
7832 StatusText.Text = sTxt;
7837 if (_curList.SelectedIndices.Count > 1)
7842 int sidx = StatusText.SelectionStart;
7843 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7845 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7846 if (!ids.Contains("@" + post.ScreenName + " ") &&
7847 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7849 ids += "@" + post.ScreenName + " ";
7853 foreach (string nm in post.ReplyToList.Select(x => x.Item2))
7855 if (!ids.Contains("@" + nm + " ") &&
7856 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7858 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7860 ids += "@" + m.Result("${id}") + " ";
7862 ids += "@" + nm + " ";
7867 if (ids.Length == 0) return;
7868 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7870 this.inReplyTo = null;
7871 StatusText.Text = ". " + StatusText.Text;
7876 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7881 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7883 //if (StatusText.Text.StartsWith("@"))
7885 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7886 // sidx += 2 + ids.Length;
7890 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7891 // sidx += 1 + ids.Length;
7893 StatusText.SelectionStart = sidx;
7899 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7902 int sidx = StatusText.SelectionStart;
7903 PostClass post = _curPost;
7904 if (!ids.Contains("@" + post.ScreenName + " ") &&
7905 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7907 ids += "@" + post.ScreenName + " ";
7909 foreach (string nm in post.ReplyToList.Select(x => x.Item2))
7911 if (!ids.Contains("@" + nm + " ") &&
7912 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7914 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7916 ids += "@" + m.Result("${id}") + " ";
7918 ids += "@" + nm + " ";
7921 if (!string.IsNullOrEmpty(post.RetweetedBy))
7923 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
7924 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7926 ids += "@" + post.RetweetedBy + " ";
7929 if (ids.Length == 0) return;
7930 if (string.IsNullOrEmpty(StatusText.Text))
7933 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7934 var inReplyToScreenName = this._curPost.ScreenName;
7935 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7937 StatusText.Text = ids;
7938 StatusText.SelectionStart = ids.Length;
7945 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7950 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7952 StatusText.SelectionStart = sidx;
7958 StatusText.SelectionStart = StatusText.Text.Length;
7963 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7968 private static int iconCnt = 0;
7969 private static int blinkCnt = 0;
7970 private static bool blink = false;
7971 private static bool idle = false;
7973 private async Task RefreshTasktrayIcon()
7976 await this.Colorize();
7978 if (!TimerRefreshIcon.Enabled) return;
7979 //Static usCheckCnt As int = 0
7981 //Static iconDlListTopItem As ListViewItem = null
7983 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7984 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7986 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7988 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7994 //if (usCheckCnt > 300) //1min
7997 // if (!this.IsReceivedUserStream)
7999 // TraceOut("ReconnectUserStream");
8000 // tw.ReconnectUserStream();
8004 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8006 if (iconCnt >= this.NIconRefresh.Length)
8014 SaveConfigsAll(true);
8019 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8021 _myStatusError = false;
8025 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8026 if (SettingManager.Common.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8028 if (blinkCnt > 0) return;
8030 if (blink || SettingManager.Common.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8032 NotifyIcon1.Icon = ReplyIcon;
8036 NotifyIcon1.Icon = ReplyIconBlink;
8044 //優先度:エラー→オフライン→アイドル
8048 NotifyIcon1.Icon = NIconAtRed;
8051 if (_myStatusOnline)
8053 NotifyIcon1.Icon = NIconAt;
8057 NotifyIcon1.Icon = NIconAtSmoke;
8061 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8064 await this.RefreshTasktrayIcon();
8067 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8069 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8070 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8072 if (ListTab != null && ListTab.SelectedTab != null)
8073 _rclickTabName = ListTab.SelectedTab.Text;
8078 if (_statuses == null) return;
8079 if (_statuses.Tabs == null) return;
8081 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out var tb))
8084 NotifyDispMenuItem.Checked = tb.Notify;
8085 this.NotifyTbMenuItem.Checked = tb.Notify;
8087 soundfileListup = true;
8088 SoundFileComboBox.Items.Clear();
8089 this.SoundFileTbComboBox.Items.Clear();
8090 SoundFileComboBox.Items.Add("");
8091 this.SoundFileTbComboBox.Items.Add("");
8092 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8093 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8095 oDir = oDir.GetDirectories("Sounds")[0];
8097 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8099 SoundFileComboBox.Items.Add(oFile.Name);
8100 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8102 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8103 if (idx == -1) idx = 0;
8104 SoundFileComboBox.SelectedIndex = idx;
8105 this.SoundFileTbComboBox.SelectedIndex = idx;
8106 soundfileListup = false;
8107 UreadManageMenuItem.Checked = tb.UnreadManage;
8108 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8110 TabMenuControl(_rclickTabName);
8113 private void TabMenuControl(string tabName)
8115 var tabInfo = _statuses.GetTabByName(tabName);
8117 this.FilterEditMenuItem.Enabled = true;
8118 this.EditRuleTbMenuItem.Enabled = true;
8120 if (tabInfo.IsDefaultTabType)
8122 this.ProtectTabMenuItem.Enabled = false;
8123 this.ProtectTbMenuItem.Enabled = false;
8127 this.ProtectTabMenuItem.Enabled = true;
8128 this.ProtectTbMenuItem.Enabled = true;
8131 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8133 this.ProtectTabMenuItem.Checked = true;
8134 this.ProtectTbMenuItem.Checked = true;
8135 this.DeleteTabMenuItem.Enabled = false;
8136 this.DeleteTbMenuItem.Enabled = false;
8140 this.ProtectTabMenuItem.Checked = false;
8141 this.ProtectTbMenuItem.Checked = false;
8142 this.DeleteTabMenuItem.Enabled = true;
8143 this.DeleteTbMenuItem.Enabled = true;
8147 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8149 var checkState = ((ToolStripMenuItem)sender).Checked;
8152 this.ProtectTbMenuItem.Checked = checkState;
8153 this.ProtectTabMenuItem.Checked = checkState;
8156 this.DeleteTabMenuItem.Enabled = !checkState;
8157 this.DeleteTbMenuItem.Enabled = !checkState;
8159 if (string.IsNullOrEmpty(_rclickTabName)) return;
8160 _statuses.Tabs[_rclickTabName].Protected = checkState;
8165 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8167 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8168 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8170 if (string.IsNullOrEmpty(_rclickTabName)) return;
8171 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8176 public void ChangeTabUnreadManage(string tabName, bool isManage)
8178 var idx = this.GetTabPageIndex(tabName);
8182 _statuses.Tabs[tabName].UnreadManage = isManage;
8183 if (SettingManager.Common.TabIconDisp)
8185 if (_statuses.Tabs[tabName].UnreadCount > 0)
8186 ListTab.TabPages[idx].ImageIndex = 0;
8188 ListTab.TabPages[idx].ImageIndex = -1;
8191 if (_curTab.Text == tabName)
8193 this.PurgeListViewItemCache();
8197 SetMainWindowTitle();
8198 SetStatusLabelUrl();
8199 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8202 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8204 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8205 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8207 if (string.IsNullOrEmpty(_rclickTabName)) return;
8209 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8214 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8216 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8218 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8223 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8225 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8227 RemoveSpecifiedTab(_rclickTabName, true);
8231 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8233 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8235 using (var fltDialog = new FilterDialog())
8237 fltDialog.Owner = this;
8238 fltDialog.SetCurrent(_rclickTabName);
8239 fltDialog.ShowDialog(this);
8241 this.TopMost = SettingManager.Common.AlwaysTop;
8243 this.ApplyPostFilters();
8247 private void AddTabMenuItem_Click(object sender, EventArgs e)
8249 string tabName = null;
8250 MyCommon.TabUsageType tabUsage;
8251 using (InputTabName inputName = new InputTabName())
8253 inputName.TabName = _statuses.MakeTabName("MyTab");
8254 inputName.IsShowUsage = true;
8255 inputName.ShowDialog();
8256 if (inputName.DialogResult == DialogResult.Cancel) return;
8257 tabName = inputName.TabName;
8258 tabUsage = inputName.Usage;
8260 this.TopMost = SettingManager.Common.AlwaysTop;
8261 if (!string.IsNullOrEmpty(tabName))
8264 ListElement list = null;
8265 if (tabUsage == MyCommon.TabUsageType.Lists)
8267 using (ListAvailable listAvail = new ListAvailable())
8269 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8270 if (listAvail.SelectedList == null) return;
8271 list = listAvail.SelectedList;
8278 case MyCommon.TabUsageType.UserDefined:
8279 tab = new FilterTabModel(tabName);
8281 case MyCommon.TabUsageType.PublicSearch:
8282 tab = new PublicSearchTabModel(tabName);
8284 case MyCommon.TabUsageType.Lists:
8285 tab = new ListTimelineTabModel(tabName, list);
8291 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8293 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8294 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8300 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8302 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8303 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8305 if (tabUsage == MyCommon.TabUsageType.Lists)
8307 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8308 var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8309 this.GetListTimelineAsync(listTab);
8315 private void TabMenuItem_Click(object sender, EventArgs e)
8317 using (var fltDialog = new FilterDialog())
8319 fltDialog.Owner = this;
8322 foreach (int idx in _curList.SelectedIndices)
8325 if (!SelectTab(out var tabName)) return;
8327 fltDialog.SetCurrent(tabName);
8328 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8330 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8334 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8336 fltDialog.ShowDialog(this);
8337 this.TopMost = SettingManager.Common.AlwaysTop;
8341 this.ApplyPostFilters();
8343 if (this.ListTab.SelectedTab != null &&
8344 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8346 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8350 protected override bool ProcessDialogKey(Keys keyData)
8352 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8353 if ((keyData & Keys.KeyCode) == Keys.Enter)
8355 if (StatusText.Focused)
8357 bool _NewLine = false;
8360 if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8362 if (StatusText.Multiline)
8364 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8366 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8370 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8374 else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8376 if (StatusText.Multiline)
8378 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8380 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8384 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8390 if (StatusText.Multiline)
8392 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8394 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8395 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8399 if (((keyData & Keys.Shift) == Keys.Shift) ||
8400 (((keyData & Keys.Control) != Keys.Control) &&
8401 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8407 int pos1 = StatusText.SelectionStart;
8408 if (StatusText.SelectionLength > 0)
8410 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8412 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8413 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8418 PostButton_Click(null, null);
8422 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8423 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8424 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8426 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8431 return base.ProcessDialogKey(keyData);
8434 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8436 MakeReplyOrDirectStatus(false, true, true);
8439 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8442 if (_curList.SelectedIndices.Count == 0) return;
8444 var tab = this._statuses.Tabs[this._curTab.Text];
8445 var screenNameArray = this._curList.SelectedIndices.Cast<int>()
8446 .Select(x => tab[x])
8447 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8450 this.AddFilterRuleByScreenName(screenNameArray);
8452 if (screenNameArray.Length != 0)
8454 List<string> atids = new List<string>();
8455 foreach (var screenName in screenNameArray)
8457 atids.Add("@" + screenName);
8459 int cnt = AtIdSupl.ItemCount;
8460 AtIdSupl.AddRangeItem(atids.ToArray());
8461 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8465 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8467 if (this._curList.SelectedIndices.Count == 0)
8470 var tab = this._statuses.Tabs[this._curTab.Text];
8471 var sourceArray = this._curList.SelectedIndices.Cast<int>()
8472 .Select(x => tab[x].Source).ToArray();
8474 this.AddFilterRuleBySource(sourceArray);
8477 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8480 if (!SelectTab(out var tabName)) return;
8482 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8486 if (tab.TabType != MyCommon.TabUsageType.Mute)
8488 this.MoveOrCopy(out mv, out mk);
8492 // ミュートタブでは常に MoveMatches を true にする
8497 foreach (var screenName in screenNameArray)
8499 tab.AddFilter(new PostFilterRule
8501 FilterName = screenName,
8502 UseNameField = true,
8506 FilterByUrl = false,
8510 this.ApplyPostFilters();
8514 public void AddFilterRuleBySource(params string[] sourceArray)
8516 // タブ選択ダイアログを表示(or追加)
8517 if (!this.SelectTab(out var tabName))
8520 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8524 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8526 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8527 this.MoveOrCopy(out mv, out mk);
8531 // ミュートタブでは常に MoveMatches を true にする
8536 // 振り分けルールに追加するSource
8537 foreach (var source in sourceArray)
8539 filterTab.AddFilter(new PostFilterRule
8541 FilterSource = source,
8545 FilterByUrl = false,
8549 this.ApplyPostFilters();
8550 this.SaveConfigsTabs();
8553 private bool SelectTab(out string tabName)
8560 using (var dialog = new TabsDialog(_statuses))
8562 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8564 var selectedTab = dialog.SelectedTab;
8565 tabName = selectedTab == null ? null : selectedTab.TabName;
8568 ListTab.SelectedTab.Focus();
8570 if (tabName == null)
8572 using (InputTabName inputName = new InputTabName())
8574 inputName.TabName = _statuses.MakeTabName("MyTab");
8575 inputName.ShowDialog();
8576 if (inputName.DialogResult == DialogResult.Cancel) return false;
8577 tabName = inputName.TabName;
8579 this.TopMost = SettingManager.Common.AlwaysTop;
8580 if (!string.IsNullOrEmpty(tabName))
8582 var tab = new FilterTabModel(tabName);
8583 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8585 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8586 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8604 private void MoveOrCopy(out bool move, out bool mark)
8608 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8609 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8617 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8618 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8628 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8633 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8638 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8640 if (StatusText.Focused)
8643 StatusText.SelectAll();
8647 // ListView上でのCtrl+A
8648 NativeMethods.SelectAllItems(this._curList);
8652 private void MoveMiddle()
8658 if (_curList.SelectedIndices.Count == 0) return;
8660 int idx = _curList.SelectedIndices[0];
8662 _item = _curList.GetItemAt(0, 25);
8668 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8670 idx2 = _curList.VirtualListSize - 1;
8674 idx -= Math.Abs(idx1 - idx2) / 2;
8675 if (idx < 0) idx = 0;
8677 _curList.EnsureVisible(_curList.VirtualListSize - 1);
8678 _curList.EnsureVisible(idx);
8681 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8683 var linkElements = this.tweetDetailsView.GetLinkElements();
8685 if (linkElements.Length > 0)
8687 UrlDialog.ClearUrl();
8689 string openUrlStr = "";
8691 if (linkElements.Length == 1)
8693 // ツイートに含まれる URL が 1 つのみの場合
8694 // => OpenURL ダイアログを表示せずにリンクを開く
8699 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8701 catch (ArgumentException)
8710 if (string.IsNullOrEmpty(urlStr)) return;
8711 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8713 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8714 await this.OpenUriAsync(new Uri(openUrlStr));
8718 // ツイートに含まれる URL が複数ある場合
8719 // => OpenURL を表示しユーザーが選択したリンクを開く
8721 foreach (var linkElm in linkElements)
8724 string linkText = "";
8728 urlStr = linkElm.GetAttribute("title");
8729 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8730 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8731 linkText = linkElm.InnerText;
8733 catch (ArgumentException)
8742 if (string.IsNullOrEmpty(urlStr)) continue;
8743 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8747 if (UrlDialog.ShowDialog() == DialogResult.OK)
8749 openUrlStr = UrlDialog.SelectedUrl;
8751 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8752 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8759 this.TopMost = SettingManager.Common.AlwaysTop;
8764 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8766 if (string.IsNullOrEmpty(_rclickTabName)) return;
8767 ClearTab(_rclickTabName, true);
8770 private void ClearTab(string tabName, bool showWarning)
8774 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8775 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8781 _statuses.ClearTabIds(tabName);
8782 if (ListTab.SelectedTab.Text == tabName)
8785 _anchorFlag = false;
8786 this.PurgeListViewItemCache();
8790 foreach (TabPage tb in ListTab.TabPages)
8792 if (tb.Text == tabName)
8794 ((DetailsListView)tb.Tag).VirtualListSize = 0;
8799 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8801 SetMainWindowTitle();
8802 SetStatusLabelUrl();
8805 private static long followers = 0;
8807 private void SetMainWindowTitle()
8810 StringBuilder ttl = new StringBuilder(256);
8813 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8814 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8815 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8816 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8818 foreach (var tab in _statuses.Tabs.Values)
8820 ur += tab.UnreadCount;
8825 if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8826 ttl.Append(Application.ProductName);
8828 switch (SettingManager.Common.DispLatestPost)
8830 case MyCommon.DispTitleEnum.Ver:
8831 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8833 case MyCommon.DispTitleEnum.Post:
8834 if (_history != null && _history.Count > 1)
8835 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8837 case MyCommon.DispTitleEnum.UnreadRepCount:
8838 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8840 case MyCommon.DispTitleEnum.UnreadAllCount:
8841 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8843 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8844 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8846 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8847 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8849 case MyCommon.DispTitleEnum.OwnStatus:
8850 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8851 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8857 this.Text = ttl.ToString();
8859 catch (AccessViolationException)
8861 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8865 private string GetStatusLabelText()
8868 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8869 if (_statuses == null) return "";
8870 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8871 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8872 if (tbRep == null || tbDm == null) return "";
8873 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8878 StringBuilder slbl = new StringBuilder(256);
8881 foreach (var tab in _statuses.Tabs.Values)
8883 ur += tab.UnreadCount;
8885 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
8887 tur = tab.UnreadCount;
8898 UnreadAtCounter = urat;
8900 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8902 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8903 if (SettingManager.Common.TimelinePeriod == 0)
8905 slbl.Append(Properties.Resources.SetStatusLabelText2);
8909 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8911 return slbl.ToString();
8914 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8918 if (this.InvokeRequired && !this.IsDisposed)
8920 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8924 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8925 SetApiStatusLabel(endpointName);
8928 catch (ObjectDisposedException)
8932 catch (InvalidOperationException)
8938 private void SetApiStatusLabel(string endpointName = null)
8940 if (_curTab == null)
8942 this.toolStripApiGauge.ApiEndpoint = null;
8946 var tabType = _statuses.Tabs[_curTab.Text].TabType;
8948 if (endpointName == null)
8953 case MyCommon.TabUsageType.Home:
8954 case MyCommon.TabUsageType.UserDefined:
8955 endpointName = "/statuses/home_timeline";
8958 case MyCommon.TabUsageType.Mentions:
8959 endpointName = "/statuses/mentions_timeline";
8962 case MyCommon.TabUsageType.Favorites:
8963 endpointName = "/favorites/list";
8966 case MyCommon.TabUsageType.DirectMessage:
8967 endpointName = "/direct_messages";
8970 case MyCommon.TabUsageType.UserTimeline:
8971 endpointName = "/statuses/user_timeline";
8974 case MyCommon.TabUsageType.Lists:
8975 endpointName = "/lists/statuses";
8978 case MyCommon.TabUsageType.PublicSearch:
8979 endpointName = "/search/tweets";
8982 case MyCommon.TabUsageType.Related:
8983 endpointName = "/statuses/show/:id";
8990 this.toolStripApiGauge.ApiEndpoint = endpointName;
8994 // 表示中のタブに関連する endpoint であれば更新
8997 switch (endpointName)
8999 case "/statuses/home_timeline":
9000 update = tabType == MyCommon.TabUsageType.Home ||
9001 tabType == MyCommon.TabUsageType.UserDefined;
9004 case "/statuses/mentions_timeline":
9005 update = tabType == MyCommon.TabUsageType.Mentions;
9008 case "/favorites/list":
9009 update = tabType == MyCommon.TabUsageType.Favorites;
9012 case "/direct_messages:":
9013 update = tabType == MyCommon.TabUsageType.DirectMessage;
9016 case "/statuses/user_timeline":
9017 update = tabType == MyCommon.TabUsageType.UserTimeline;
9020 case "/lists/statuses":
9021 update = tabType == MyCommon.TabUsageType.Lists;
9024 case "/search/tweets":
9025 update = tabType == MyCommon.TabUsageType.PublicSearch;
9028 case "/statuses/show/:id":
9029 update = tabType == MyCommon.TabUsageType.Related;
9038 this.toolStripApiGauge.ApiEndpoint = endpointName;
9044 private void SetStatusLabelUrl()
9046 StatusLabelUrl.Text = GetStatusLabelText();
9049 public void SetStatusLabel(string text)
9051 StatusLabel.Text = text;
9054 private void SetNotifyIconText()
9056 var ur = new StringBuilder(64);
9058 // タスクトレイアイコンのツールチップテキスト書き換え
9060 ur.Remove(0, ur.Length);
9061 if (SettingManager.Common.DispUsername)
9063 ur.Append(tw.Username);
9066 ur.Append(Application.ProductName);
9068 ur.Append("(Debug Build)");
9070 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9073 ur.Append(UnreadCounter);
9075 ur.Append(UnreadAtCounter);
9078 NotifyIcon1.Text = ur.ToString();
9081 internal void CheckReplyTo(string StatusText)
9085 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9087 foreach (Match hm in m)
9089 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9091 hstr += "#" + hm.Result("$3") + " ";
9092 HashSupl.AddItem("#" + hm.Result("$3"));
9095 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9097 hstr += HashMgr.UseHash;
9099 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9101 // 本当にリプライ先指定すべきかどうかの判定
9102 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9104 if (SettingManager.Common.UseAtIdSupplement)
9106 int bCnt = AtIdSupl.ItemCount;
9107 foreach (Match mid in m)
9109 AtIdSupl.AddItem(mid.Result("${id}"));
9111 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9114 // リプライ先ステータスIDの指定がない場合は指定しない
9115 if (this.inReplyTo == null)
9119 // 次の条件を満たす場合に in_reply_to_status_id 指定
9120 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9121 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9122 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9126 var inReplyToScreenName = this.inReplyTo.Item2;
9127 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9129 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9133 foreach (Match mid in m)
9135 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9140 this.inReplyTo = null;
9143 private void TweenMain_Resize(object sender, EventArgs e)
9145 if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
9147 this.Visible = false;
9149 if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
9151 // 現在の DPI と設定保存時の DPI との比を取得する
9152 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9154 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
9157 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
9158 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9159 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9161 this.SplitContainer1.SplitterDistance = splitterDistance;
9165 StatusText.Multiline = SettingManager.Local.StatusMultiline;
9166 if (StatusText.Multiline)
9168 var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
9169 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9170 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9172 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9174 StatusText.Height = statusTextHeight;
9178 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9180 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9184 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
9185 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9187 this.SplitContainer3.SplitterDistance = previewDistance;
9190 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9191 this.SplitContainer3.Panel2Collapsed = true;
9193 _initialLayout = false;
9195 if (this.WindowState != FormWindowState.Minimized)
9197 _formWindowState = this.WindowState;
9201 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9203 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9204 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9205 if (PlaySoundMenuItem.Checked)
9207 SettingManager.Common.PlaySound = true;
9211 SettingManager.Common.PlaySound = false;
9213 ModifySettingCommon = true;
9216 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9218 if (this._initialLayout)
9221 int splitterDistance;
9222 switch (this.WindowState)
9224 case FormWindowState.Normal:
9225 splitterDistance = this.SplitContainer1.SplitterDistance;
9227 case FormWindowState.Maximized:
9228 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9229 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9230 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9231 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9237 this._mySpDis = splitterDistance;
9238 this.ModifySettingLocal = true;
9241 private async Task doRepliedStatusOpen()
9243 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9245 if (MyCommon.IsKeyDown(Keys.Shift))
9247 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9250 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9252 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9253 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9257 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9259 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9260 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9261 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9264 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9269 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9271 await this.doRepliedStatusOpen();
9274 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9276 if (this._initialLayout)
9277 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
9279 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9280 if (multiline != this.StatusText.Multiline)
9282 this.StatusText.Multiline = multiline;
9283 SettingManager.Local.StatusMultiline = multiline;
9284 ModifySettingLocal = true;
9288 private void StatusText_MultilineChanged(object sender, EventArgs e)
9290 if (this.StatusText.Multiline)
9291 this.StatusText.ScrollBars = ScrollBars.Vertical;
9293 this.StatusText.ScrollBars = ScrollBars.None;
9295 ModifySettingLocal = true;
9298 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9301 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
9302 StatusText.Multiline = menuItemChecked;
9303 SettingManager.Local.StatusMultiline = menuItemChecked;
9304 if (menuItemChecked)
9306 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9307 SplitContainer2.SplitterDistance = 0;
9309 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9313 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9315 ModifySettingLocal = true;
9318 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9320 if (Converter_Type == MyCommon.UrlConverter.Bitly || Converter_Type == MyCommon.UrlConverter.Jmp)
9322 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
9323 if (string.IsNullOrEmpty(SettingManager.Common.BitlyAccessToken) &&
9324 (string.IsNullOrEmpty(SettingManager.Common.BilyUser) || string.IsNullOrEmpty(SettingManager.Common.BitlyPwd)))
9326 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
9331 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9332 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9334 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9335 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9336 //Appendix A. Collected ABNF for URI
9337 //http://www.ietf.org/rfc/rfc3986.txt
9341 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9343 if (StatusText.SelectionLength > 0)
9345 string tmp = StatusText.SelectedText;
9346 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9347 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9349 // 文字列が選択されている場合はその文字列について処理
9351 //nico.ms使用、nicovideoにマッチしたら変換
9352 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9354 result = nicoms.Shorten(tmp);
9356 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9358 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9361 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9362 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9363 result = resultUri.AbsoluteUri;
9365 catch (WebApiException e)
9367 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9370 catch (UriFormatException e)
9372 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9381 if (!string.IsNullOrEmpty(result))
9383 urlUndo undotmp = new urlUndo();
9385 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9386 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9387 if (origUrlIndex == -1)
9390 StatusText.Select(origUrlIndex, tmp.Length);
9391 StatusText.SelectedText = result;
9394 undotmp.Before = tmp;
9395 undotmp.After = result;
9397 if (urlUndoBuffer == null)
9399 urlUndoBuffer = new List<urlUndo>();
9400 UrlUndoToolStripMenuItem.Enabled = true;
9403 urlUndoBuffer.Add(undotmp);
9409 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9410 @"(?<url>(?<protocol>https?://)" +
9411 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9412 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9413 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9414 // 正規表現にマッチしたURL文字列をtinyurl化
9415 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9417 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9418 string tmp = mt.Result("${url}");
9419 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9420 urlUndo undotmp = new urlUndo();
9423 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9425 //nico.ms使用、nicovideoにマッチしたら変換
9426 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9428 result = nicoms.Shorten(tmp);
9430 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9432 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9435 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9436 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9437 result = resultUri.AbsoluteUri;
9439 catch (HttpRequestException e)
9441 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9442 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9443 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9445 this.StatusLabel.Text = Converter_Type + ":" + message;
9448 catch (WebApiException e)
9450 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9453 catch (UriFormatException e)
9455 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9464 if (!string.IsNullOrEmpty(result))
9466 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9467 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9468 if (origUrlIndex == -1)
9471 StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9472 StatusText.SelectedText = result;
9474 undotmp.Before = mt.Result("${url}");
9475 undotmp.After = result;
9477 if (urlUndoBuffer == null)
9479 urlUndoBuffer = new List<urlUndo>();
9480 UrlUndoToolStripMenuItem.Enabled = true;
9483 urlUndoBuffer.Add(undotmp);
9491 private void doUrlUndo()
9493 if (urlUndoBuffer != null)
9495 string tmp = StatusText.Text;
9496 foreach (urlUndo data in urlUndoBuffer)
9498 tmp = tmp.Replace(data.After, data.Before);
9500 StatusText.Text = tmp;
9501 urlUndoBuffer = null;
9502 UrlUndoToolStripMenuItem.Enabled = false;
9503 StatusText.SelectionStart = 0;
9504 StatusText.SelectionLength = 0;
9508 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9510 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9513 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9515 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9518 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9520 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9523 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9525 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9528 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9530 if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9532 MyCommon.UrlConverter svc = SettingManager.Common.AutoShortUrlFirst;
9533 Random rnd = new Random();
9534 // 前回使用した短縮URLサービス以外を選択する
9537 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9539 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9540 await UrlConvertAsync(svc);
9544 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9549 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9551 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9552 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9553 SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9554 ModifySettingCommon = true;
9557 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9559 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9560 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9561 SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9562 ModifySettingCommon = true;
9565 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9567 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9568 MenuStrip1.Tag = new Object();
9569 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9572 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9574 if (this.Tag != null) // 設定された戻り先へ遷移
9576 if (this.Tag == this.ListTab.SelectedTab)
9577 ((Control)this.ListTab.SelectedTab.Tag).Select();
9579 ((Control)this.Tag).Select();
9581 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9583 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9585 this.Tag = ListTab.SelectedTab.Tag;
9586 ((Control)this.Tag).Select();
9589 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9590 MenuStrip1.Tag = null;
9593 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9595 DetailsListView lst = (DetailsListView)sender;
9596 if (SettingManager.Local == null) return;
9600 SettingManager.Local.Width1 = lst.Columns[0].Width;
9601 SettingManager.Local.Width3 = lst.Columns[1].Width;
9605 int[] darr = new int[lst.Columns.Count];
9606 for (int i = 0; i < lst.Columns.Count; i++)
9608 darr[lst.Columns[i].DisplayIndex] = i;
9610 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9612 for (int i = 0; i < lst.Columns.Count; i++)
9617 SettingManager.Local.DisplayIndex1 = i;
9620 SettingManager.Local.DisplayIndex2 = i;
9623 SettingManager.Local.DisplayIndex3 = i;
9626 SettingManager.Local.DisplayIndex4 = i;
9629 SettingManager.Local.DisplayIndex5 = i;
9632 SettingManager.Local.DisplayIndex6 = i;
9635 SettingManager.Local.DisplayIndex7 = i;
9638 SettingManager.Local.DisplayIndex8 = i;
9642 SettingManager.Local.Width1 = lst.Columns[0].Width;
9643 SettingManager.Local.Width2 = lst.Columns[1].Width;
9644 SettingManager.Local.Width3 = lst.Columns[2].Width;
9645 SettingManager.Local.Width4 = lst.Columns[3].Width;
9646 SettingManager.Local.Width5 = lst.Columns[4].Width;
9647 SettingManager.Local.Width6 = lst.Columns[5].Width;
9648 SettingManager.Local.Width7 = lst.Columns[6].Width;
9649 SettingManager.Local.Width8 = lst.Columns[7].Width;
9651 ModifySettingLocal = true;
9652 _isColumnChanged = true;
9655 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9657 DetailsListView lst = (DetailsListView)sender;
9658 if (SettingManager.Local == null) return;
9661 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9663 SettingManager.Local.Width1 = lst.Columns[0].Width;
9664 ModifySettingLocal = true;
9665 _isColumnChanged = true;
9667 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9669 SettingManager.Local.Width3 = lst.Columns[1].Width;
9670 ModifySettingLocal = true;
9671 _isColumnChanged = true;
9676 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9678 SettingManager.Local.Width1 = lst.Columns[0].Width;
9679 ModifySettingLocal = true;
9680 _isColumnChanged = true;
9682 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9684 SettingManager.Local.Width2 = lst.Columns[1].Width;
9685 ModifySettingLocal = true;
9686 _isColumnChanged = true;
9688 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9690 SettingManager.Local.Width3 = lst.Columns[2].Width;
9691 ModifySettingLocal = true;
9692 _isColumnChanged = true;
9694 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9696 SettingManager.Local.Width4 = lst.Columns[3].Width;
9697 ModifySettingLocal = true;
9698 _isColumnChanged = true;
9700 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9702 SettingManager.Local.Width5 = lst.Columns[4].Width;
9703 ModifySettingLocal = true;
9704 _isColumnChanged = true;
9706 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9708 SettingManager.Local.Width6 = lst.Columns[5].Width;
9709 ModifySettingLocal = true;
9710 _isColumnChanged = true;
9712 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9714 SettingManager.Local.Width7 = lst.Columns[6].Width;
9715 ModifySettingLocal = true;
9716 _isColumnChanged = true;
9718 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9720 SettingManager.Local.Width8 = lst.Columns[7].Width;
9721 ModifySettingLocal = true;
9722 _isColumnChanged = true;
9725 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9728 // SaveConfigsLocal();
9732 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9734 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9735 ModifySettingLocal = true;
9738 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9740 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9742 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9744 SelectMedia_DragDrop(e);
9747 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9749 var (url, title) = GetUrlFromDataObject(e.Data);
9755 appendText = title + " " + url;
9757 if (this.StatusText.TextLength == 0)
9758 this.StatusText.Text = appendText;
9760 this.StatusText.Text += " " + appendText;
9762 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9764 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9766 this.StatusText.Text += text;
9768 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9770 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9771 if (data != null) StatusText.Text += data;
9776 /// IDataObject から URL とタイトルの対を取得します
9779 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9781 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9782 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9783 internal static (string Url, string Title) GetUrlFromDataObject(IDataObject data)
9785 if (data.GetDataPresent("text/x-moz-url"))
9787 // Firefox, Google Chrome で利用可能
9788 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9790 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9792 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9793 if (lines.Length < 2)
9794 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9796 return (lines[0], lines[1]);
9799 else if (data.GetDataPresent("IESiteModeToUrl"))
9801 // Internet Exproler 用
9802 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9804 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9806 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9807 if (lines.Length < 2)
9808 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9810 return (lines[0], lines[1]);
9813 else if (data.GetDataPresent("UniformResourceLocatorW"))
9817 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9819 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9824 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9827 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9829 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9831 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9833 SelectMedia_DragEnter(e);
9837 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9839 e.Effect = DragDropEffects.Copy;
9842 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9844 e.Effect = DragDropEffects.Copy;
9847 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9849 e.Effect = DragDropEffects.Copy;
9853 e.Effect = DragDropEffects.None;
9856 private void TweenMain_DragOver(object sender, DragEventArgs e)
9860 public bool IsNetworkAvailable()
9863 nw = MyCommon.IsNetworkAvailable();
9864 _myStatusOnline = nw;
9868 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9870 var uriStr = uri.AbsoluteUri;
9872 // OpenTween 内部で使用する URL
9873 if (uri.Authority == "opentween")
9875 await this.OpenInternalUriAsync(uri);
9879 // ハッシュタグを含む Twitter 検索
9880 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9883 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9884 var pos = unescapedQuery.IndexOf('#');
9885 if (pos == -1) return;
9887 var hash = unescapedQuery.Substring(pos);
9888 this.HashSupl.AddItem(hash);
9889 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9890 this.AddNewTabForSearch(hash);
9895 // フラグが立っている場合は設定と逆の動作をする
9896 if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9897 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9899 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9900 if (userUriMatch.Success)
9902 var screenName = userUriMatch.Groups["ScreenName"].Value;
9903 if (this.IsTwitterId(screenName))
9905 this.AddNewTabForUserTimeline(screenName);
9912 await this.OpenUriInBrowserAsync(uriStr);
9916 /// OpenTween 内部の機能を呼び出すための URL を開きます
9918 private async Task OpenInternalUriAsync(Uri uri)
9920 // ツイートを開く (//opentween/status/:status_id)
9921 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9924 var statusId = long.Parse(match.Groups[1].Value);
9925 await this.OpenRelatedTab(statusId);
9930 public Task OpenUriInBrowserAsync(string UriString)
9932 return Task.Run(() =>
9934 string myPath = UriString;
9938 var configBrowserPath = SettingManager.Local.BrowserPath;
9939 if (!string.IsNullOrEmpty(configBrowserPath))
9941 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9943 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9944 string browserPath = configBrowserPath.Substring(1, sep - 1);
9946 if (sep < configBrowserPath.Length - 1)
9948 arg = configBrowserPath.Substring(sep + 1);
9950 myPath = arg + " " + myPath;
9951 System.Diagnostics.Process.Start(browserPath, myPath);
9955 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9960 System.Diagnostics.Process.Start(myPath);
9965 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9970 private void ListTabSelect(TabPage _tab)
9974 this.PurgeListViewItemCache();
9977 _curList = (DetailsListView)_tab.Tag;
9979 if (_curList.SelectedIndices.Count > 0)
9981 _curItemIndex = _curList.SelectedIndices[0];
9982 _curPost = GetCurTabPost(_curItemIndex);
9991 _anchorFlag = false;
9995 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
9999 for (int i = 0; i < _curList.Columns.Count; i++)
10001 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10006 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10008 ListTabSelect(e.TabPage);
10011 private void SelectListItem(DetailsListView LView, int Index)
10014 Rectangle bnd = new Rectangle();
10016 var item = LView.FocusedItem;
10025 LView.SelectedIndices.Clear();
10027 while (LView.SelectedIndices.Count > 0);
10028 item = LView.Items[Index];
10029 item.Selected = true;
10030 item.Focused = true;
10032 if (flg) LView.Invalidate(bnd);
10035 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
10038 Rectangle bnd = new Rectangle();
10040 var item = LView.FocusedItem;
10051 LView.SelectedIndices.Clear();
10053 while (LView.SelectedIndices.Count > 0);
10054 LView.SelectItems(Index);
10056 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
10058 LView.SelectionMark = selectionMarkIndex;
10060 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
10062 LView.Items[focusedIndex].Focused = true;
10064 else if (Index != null && Index.Length != 0)
10066 LView.Items[Index.Last()].Focused = true;
10069 if (flg) LView.Invalidate(bnd);
10072 private void StartUserStream()
10074 tw.NewPostFromStream += tw_NewPostFromStream;
10075 tw.UserStreamStarted += tw_UserStreamStarted;
10076 tw.UserStreamStopped += tw_UserStreamStopped;
10077 tw.PostDeleted += tw_PostDeleted;
10078 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
10080 this.RefreshUserStreamsMenu();
10082 if (SettingManager.Common.UserstreamStartup)
10083 tw.StartUserStream();
10086 private async void TweenMain_Shown(object sender, EventArgs e)
10088 NotifyIcon1.Visible = true;
10090 if (this.IsNetworkAvailable())
10094 var loadTasks = new List<Task>
10096 this.RefreshMuteUserIdsAsync(),
10097 this.RefreshBlockIdsAsync(),
10098 this.RefreshNoRetweetIdsAsync(),
10099 this.RefreshTwitterConfigurationAsync(),
10100 this.GetHomeTimelineAsync(),
10101 this.GetReplyAsync(),
10102 this.GetDirectMessagesAsync(),
10103 this.GetPublicSearchAllAsync(),
10104 this.GetUserTimelineAllAsync(),
10105 this.GetListTimelineAllAsync(),
10108 if (SettingManager.Common.StartupFollowers)
10109 loadTasks.Add(this.RefreshFollowerIdsAsync());
10111 if (SettingManager.Common.GetFav)
10112 loadTasks.Add(this.GetFavoritesAsync());
10114 var allTasks = Task.WhenAll(loadTasks);
10119 var timeout = Task.Delay(5000);
10120 if (await Task.WhenAny(allTasks, timeout) != timeout)
10124 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10126 if (MyCommon._endingFlag)
10130 if (MyCommon._endingFlag) return;
10132 if (ApplicationSettings.VersionInfoUrl != null)
10134 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10135 if (SettingManager.Common.StartupVersion)
10136 await this.CheckNewVersion(true);
10140 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10141 this.VerUpMenuItem.Enabled = false;
10142 this.VerUpMenuItem.Available = false;
10143 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10146 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10147 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10149 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10150 SettingStripMenuItem_Click(null, null);
10154 var reloadTasks = new List<Task>();
10156 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
10157 reloadTasks.Add(this.RefreshFollowerIdsAsync());
10159 if (!tw.GetNoRetweetSuccess)
10160 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10162 if (this.tw.Configuration.PhotoSizeLimit == 0)
10163 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10165 await Task.WhenAll(reloadTasks);
10170 TimerTimeline.Enabled = true;
10173 private async Task doGetFollowersMenu()
10175 await this.RefreshFollowerIdsAsync();
10176 await this.DispSelectedPost(true);
10179 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10181 await this.doGetFollowersMenu();
10184 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10186 doReTweetUnofficial();
10189 private async Task doReTweetOfficial(bool isConfirm)
10192 if (this.ExistCurrentPost)
10194 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10196 if (this._curPost.IsProtect)
10197 MessageBox.Show("Protected.");
10199 _DoFavRetweetFlags = false;
10202 if (_curList.SelectedIndices.Count > 15)
10204 MessageBox.Show(Properties.Resources.RetweetLimitText);
10205 _DoFavRetweetFlags = false;
10208 else if (_curList.SelectedIndices.Count > 1)
10210 string QuestionText = Properties.Resources.RetweetQuestion2;
10211 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10212 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10214 case DialogResult.Cancel:
10215 case DialogResult.No:
10216 _DoFavRetweetFlags = false;
10222 if (!SettingManager.Common.RetweetNoConfirm)
10224 string Questiontext = Properties.Resources.RetweetQuestion1;
10225 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10226 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10228 _DoFavRetweetFlags = false;
10234 var statusIds = new List<long>();
10235 foreach (int idx in _curList.SelectedIndices)
10237 PostClass post = GetCurTabPost(idx);
10238 if (post.CanRetweetBy(this.twitterApi.CurrentUserId))
10239 statusIds.Add(post.StatusId);
10242 await this.RetweetAsync(statusIds);
10246 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10248 await this.doReTweetOfficial(true);
10251 private async Task FavoritesRetweetOfficial()
10253 if (!this.ExistCurrentPost) return;
10254 _DoFavRetweetFlags = true;
10255 var retweetTask = this.doReTweetOfficial(true);
10256 if (_DoFavRetweetFlags)
10258 _DoFavRetweetFlags = false;
10259 var favoriteTask = this.FavoriteChange(true, false);
10261 await Task.WhenAll(retweetTask, favoriteTask);
10269 private async Task FavoritesRetweetUnofficial()
10271 if (this.ExistCurrentPost && !_curPost.IsDm)
10273 _DoFavRetweetFlags = true;
10274 var favoriteTask = this.FavoriteChange(true);
10275 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10277 _DoFavRetweetFlags = false;
10278 doReTweetUnofficial();
10281 await favoriteTask;
10286 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10288 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10289 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10290 /// <returns>復元されたツイート本文</returns>
10291 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10293 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10296 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10298 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10300 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10304 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10306 statusHtml = statusHtml.Replace("<br>", " ");
10308 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10309 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10310 statusHtml = statusHtml.Replace(" ", " ");
10312 return WebUtility.HtmlDecode(statusHtml);
10315 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10317 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10319 if (_curPost != null)
10320 await this.DispSelectedPost(true);
10323 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10325 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10326 DebugModeToolStripMenuItem.Visible = true;
10328 DebugModeToolStripMenuItem.Visible = false;
10331 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
10333 this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
10336 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
10338 this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
10341 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
10343 SettingManager.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
10346 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
10348 SettingManager.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
10349 ModifySettingCommon = true;
10352 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10354 SettingManager.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
10355 ModifySettingCommon = true;
10358 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
10360 UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
10361 PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
10362 UrlAutoShortenMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10363 IdeographicSpaceToSpaceMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10364 MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
10365 FocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10368 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10370 UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
10371 PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
10372 UrlAutoShortenPullDownMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10373 IdeographicSpaceToSpacePullDownMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10374 MultiLinePullDownMenuItem.Checked = SettingManager.Local.StatusMultiline;
10375 FocusLockPullDownMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10378 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10380 if (TraceOutToolStripMenuItem.Checked)
10381 MyCommon.TraceFlag = true;
10383 MyCommon.TraceFlag = false;
10386 private void TweenMain_Deactivate(object sender, EventArgs e)
10388 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10389 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10392 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10394 if (string.IsNullOrEmpty(_rclickTabName)) return;
10396 TabRename(_rclickTabName, out var _);
10399 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10401 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10404 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10406 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10409 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10411 TwitterApiStatus apiStatus;
10413 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10415 var cancellationToken = dialog.EnableCancellation();
10419 var task = this.tw.GetInfoApi();
10420 apiStatus = await dialog.WaitForAsync(this, task);
10422 catch (WebApiException)
10427 if (cancellationToken.IsCancellationRequested)
10430 if (apiStatus == null)
10432 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10437 using (var apiDlg = new ApiInfoDialog())
10439 apiDlg.ShowDialog(this);
10443 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10445 var id = _curPost?.ScreenName ?? "";
10447 await this.FollowCommand(id);
10450 internal async Task FollowCommand(string id)
10452 using (var inputName = new InputTabName())
10454 inputName.FormTitle = "Follow";
10455 inputName.FormDescription = Properties.Resources.FRMessage1;
10456 inputName.TabName = id;
10458 if (inputName.ShowDialog(this) != DialogResult.OK)
10460 if (string.IsNullOrWhiteSpace(inputName.TabName))
10463 id = inputName.TabName.Trim();
10466 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10470 var task = this.twitterApi.FriendshipsCreate(id).IgnoreResponse();
10471 await dialog.WaitForAsync(this, task);
10473 catch (WebApiException ex)
10475 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10480 MessageBox.Show(Properties.Resources.FRMessage3);
10483 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10485 var id = _curPost?.ScreenName ?? "";
10487 await this.RemoveCommand(id, false);
10490 internal async Task RemoveCommand(string id, bool skipInput)
10494 using (var inputName = new InputTabName())
10496 inputName.FormTitle = "Unfollow";
10497 inputName.FormDescription = Properties.Resources.FRMessage1;
10498 inputName.TabName = id;
10500 if (inputName.ShowDialog(this) != DialogResult.OK)
10502 if (string.IsNullOrWhiteSpace(inputName.TabName))
10505 id = inputName.TabName.Trim();
10509 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10513 var task = this.twitterApi.FriendshipsDestroy(id).IgnoreResponse();
10514 await dialog.WaitForAsync(this, task);
10516 catch (WebApiException ex)
10518 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10523 MessageBox.Show(Properties.Resources.FRMessage3);
10526 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10528 var id = _curPost?.ScreenName ?? "";
10530 await this.ShowFriendship(id);
10533 internal async Task ShowFriendship(string id)
10535 using (var inputName = new InputTabName())
10537 inputName.FormTitle = "Show Friendships";
10538 inputName.FormDescription = Properties.Resources.FRMessage1;
10539 inputName.TabName = id;
10541 if (inputName.ShowDialog(this) != DialogResult.OK)
10543 if (string.IsNullOrWhiteSpace(inputName.TabName))
10546 id = inputName.TabName.Trim();
10549 bool isFollowing, isFollowed;
10551 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10553 var cancellationToken = dialog.EnableCancellation();
10557 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10558 var friendship = await dialog.WaitForAsync(this, task);
10560 isFollowing = friendship.Relationship.Source.Following;
10561 isFollowed = friendship.Relationship.Source.FollowedBy;
10563 catch (WebApiException ex)
10565 if (!cancellationToken.IsCancellationRequested)
10566 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10570 if (cancellationToken.IsCancellationRequested)
10574 string result = "";
10577 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10581 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10585 result += Properties.Resources.GetFriendshipInfo3;
10589 result += Properties.Resources.GetFriendshipInfo4;
10591 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10592 MessageBox.Show(result);
10595 internal async Task ShowFriendship(string[] ids)
10597 foreach (string id in ids)
10599 bool isFollowing, isFollowed;
10601 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10603 var cancellationToken = dialog.EnableCancellation();
10607 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10608 var friendship = await dialog.WaitForAsync(this, task);
10610 isFollowing = friendship.Relationship.Source.Following;
10611 isFollowed = friendship.Relationship.Source.FollowedBy;
10613 catch (WebApiException ex)
10615 if (!cancellationToken.IsCancellationRequested)
10616 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10620 if (cancellationToken.IsCancellationRequested)
10624 string result = "";
10630 ff += Properties.Resources.GetFriendshipInfo1;
10634 ff += Properties.Resources.GetFriendshipInfo2;
10637 ff += System.Environment.NewLine + " ";
10640 ff += Properties.Resources.GetFriendshipInfo3;
10644 ff += Properties.Resources.GetFriendshipInfo4;
10646 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10649 if (MessageBox.Show(
10650 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10651 MessageBoxButtons.YesNo,
10652 MessageBoxIcon.Question,
10653 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10655 await this.RemoveCommand(id, true);
10660 MessageBox.Show(result);
10665 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10667 await this.doShowUserStatus(tw.Username, false);
10668 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
10670 // doShowUserStatus(tw.Username, false);
10674 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
10679 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10680 // URLから切り出した文字列を渡す
10682 public bool IsTwitterId(string name)
10684 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10685 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10687 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
10690 private void doQuoteOfficial()
10692 if (this.ExistCurrentPost)
10694 if (_curPost.IsDm ||
10695 !StatusText.Enabled) return;
10697 if (_curPost.IsProtect)
10699 MessageBox.Show("Protected.");
10703 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10705 this.inReplyTo = null;
10707 StatusText.Text += " " + MyCommon.GetStatusUrl(_curPost);
10709 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10710 StatusText.Focus();
10714 private void doReTweetUnofficial()
10717 if (this.ExistCurrentPost)
10719 if (_curPost.IsDm || !StatusText.Enabled)
10722 if (_curPost.IsProtect)
10724 MessageBox.Show("Protected.");
10727 string rtdata = _curPost.Text;
10728 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10730 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10732 // 投稿時に in_reply_to_status_id を付加する
10733 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
10734 var inReplyToScreenName = this._curPost.ScreenName;
10735 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
10737 StatusText.Text += " RT @" + _curPost.ScreenName + ": " + rtdata;
10739 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10740 StatusText.Focus();
10744 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
10749 private void SearchButton_Click(object sender, EventArgs e)
10752 Control pnl = ((Control)sender).Parent;
10753 if (pnl == null) return;
10754 string tbName = pnl.Parent.Text;
10755 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10756 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10757 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10758 cmb.Text = cmb.Text.Trim();
10759 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10760 bool Quote = false;
10761 StringBuilder buf = new StringBuilder();
10762 char[] c = cmb.Text.ToCharArray();
10763 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10765 if (cnt > cmb.Text.Length - 4)
10767 buf.Append(cmb.Text.Substring(cnt));
10776 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10778 buf.Append(" OR ");
10783 buf.Append(c[cnt]);
10785 cmb.Text = buf.ToString();
10787 var listView = (DetailsListView)pnl.Parent.Tag;
10789 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10791 tb.SearchWords = cmb.Text;
10792 tb.SearchLang = cmbLang.Text;
10793 if (string.IsNullOrEmpty(cmb.Text))
10801 int idx = cmb.Items.IndexOf(tb.SearchWords);
10802 if (idx > -1) cmb.Items.RemoveAt(idx);
10803 cmb.Items.Insert(0, tb.SearchWords);
10804 cmb.Text = tb.SearchWords;
10806 this.PurgeListViewItemCache();
10807 listView.VirtualListSize = 0;
10808 _statuses.ClearTabIds(tbName);
10809 SaveConfigsTabs(); //検索条件の保存
10812 this.GetPublicSearchAsync(tb);
10816 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10819 await this.DoRefreshMore();
10823 /// 指定されたタブのListTabにおける位置を返します
10826 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10828 public int GetTabPageIndex(string tabName)
10831 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
10833 if (tabPage.Text == tabName)
10842 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10844 if (_statuses.RemovedTab.Count == 0)
10846 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10851 DetailsListView listView = null;
10853 TabModel tb = _statuses.RemovedTab.Pop();
10854 if (tb.TabType == MyCommon.TabUsageType.Related)
10856 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10857 if (relatedTab != null)
10859 // 関連発言なら既存のタブを置き換える
10860 tb.TabName = relatedTab.TabName;
10861 this.ClearTab(tb.TabName, false);
10862 _statuses.Tabs[tb.TabName] = tb;
10864 for (int i = 0; i < ListTab.TabPages.Count; i++)
10866 var tabPage = ListTab.TabPages[i];
10867 if (tb.TabName == tabPage.Text)
10869 listView = (DetailsListView)tabPage.Tag;
10870 ListTab.SelectedIndex = i;
10877 const string TabName = "Related Tweets";
10878 string renamed = TabName;
10879 for (int i = 2; i <= 100; i++)
10881 if (!_statuses.ContainsTab(renamed)) break;
10882 renamed = TabName + i;
10884 tb.TabName = renamed;
10886 _statuses.AddTab(tb);
10887 AddNewTab(tb, startup: false);
10889 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10890 listView = (DetailsListView)tabPage.Tag;
10891 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10896 string renamed = tb.TabName;
10897 for (int i = 1; i < int.MaxValue; i++)
10899 if (!_statuses.ContainsTab(renamed)) break;
10900 renamed = tb.TabName + "(" + i + ")";
10902 tb.TabName = renamed;
10904 _statuses.AddTab(tb);
10905 AddNewTab(tb, startup: false);
10907 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10908 listView = (DetailsListView)tabPage.Tag;
10909 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10913 if (listView != null)
10915 using (ControlTransaction.Update(listView))
10917 listView.VirtualListSize = tb.AllCount;
10923 private async Task doMoveToRTHome()
10925 if (_curList.SelectedIndices.Count > 0)
10927 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
10928 if (post.RetweetedId != null)
10930 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
10935 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10937 await this.doMoveToRTHome();
10940 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10942 var screenName = this._curPost?.ScreenName;
10943 if (screenName != null)
10944 this.ListManageUserContext(screenName);
10947 public void ListManageUserContext(string screenName)
10949 using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10951 listSelectForm.ShowDialog(this);
10955 private void SearchControls_Enter(object sender, EventArgs e)
10957 Control pnl = (Control)sender;
10958 foreach (Control ctl in pnl.Controls)
10960 ctl.TabStop = true;
10964 private void SearchControls_Leave(object sender, EventArgs e)
10966 Control pnl = (Control)sender;
10967 foreach (Control ctl in pnl.Controls)
10969 ctl.TabStop = false;
10973 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10975 if (ListTab.SelectedTab != null)
10977 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
10978 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
10982 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10984 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10987 private void HashManageMenuItem_Click(object sender, EventArgs e)
10989 DialogResult rslt = DialogResult.Cancel;
10992 rslt = HashMgr.ShowDialog();
10998 this.TopMost = SettingManager.Common.AlwaysTop;
10999 if (rslt == DialogResult.Cancel) return;
11000 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11002 HashStripSplitButton.Text = HashMgr.UseHash;
11003 HashTogglePullDownMenuItem.Checked = true;
11004 HashToggleMenuItem.Checked = true;
11008 HashStripSplitButton.Text = "#[-]";
11009 HashTogglePullDownMenuItem.Checked = false;
11010 HashToggleMenuItem.Checked = false;
11012 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
11014 // int sidx = StatusText.SelectionStart;
11015 // string hash = HashMgr.UseHash + " ";
11018 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
11019 // hash = " " + hash;
11021 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
11022 // sidx += hash.Length;
11023 // StatusText.SelectionStart = sidx;
11024 // StatusText.Focus();
11026 ModifySettingCommon = true;
11027 this.StatusText_TextChanged(null, null);
11030 private void HashToggleMenuItem_Click(object sender, EventArgs e)
11032 HashMgr.ToggleHash();
11033 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11035 HashStripSplitButton.Text = HashMgr.UseHash;
11036 HashToggleMenuItem.Checked = true;
11037 HashTogglePullDownMenuItem.Checked = true;
11041 HashStripSplitButton.Text = "#[-]";
11042 HashToggleMenuItem.Checked = false;
11043 HashTogglePullDownMenuItem.Checked = false;
11045 ModifySettingCommon = true;
11046 this.StatusText_TextChanged(null, null);
11049 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
11051 HashToggleMenuItem_Click(null, null);
11054 public void SetPermanentHashtag(string hashtag)
11056 HashMgr.SetPermanentHash("#" + hashtag);
11057 HashStripSplitButton.Text = HashMgr.UseHash;
11058 HashTogglePullDownMenuItem.Checked = true;
11059 HashToggleMenuItem.Checked = true;
11061 ModifySettingCommon = true;
11064 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
11066 if (ListTab.SelectedTab == null) return;
11067 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
11068 if (!this.ExistCurrentPost)
11070 this.ReplyOpMenuItem.Enabled = false;
11071 this.ReplyAllOpMenuItem.Enabled = false;
11072 this.DmOpMenuItem.Enabled = false;
11073 this.ShowProfMenuItem.Enabled = false;
11074 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
11075 this.ListManageMenuItem.Enabled = false;
11076 this.OpenFavOpMenuItem.Enabled = false;
11077 this.CreateTabRuleOpMenuItem.Enabled = false;
11078 this.CreateIdRuleOpMenuItem.Enabled = false;
11079 this.CreateSourceRuleOpMenuItem.Enabled = false;
11080 this.ReadOpMenuItem.Enabled = false;
11081 this.UnreadOpMenuItem.Enabled = false;
11085 this.ReplyOpMenuItem.Enabled = true;
11086 this.ReplyAllOpMenuItem.Enabled = true;
11087 this.DmOpMenuItem.Enabled = true;
11088 this.ShowProfMenuItem.Enabled = true;
11089 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
11090 this.ListManageMenuItem.Enabled = true;
11091 this.OpenFavOpMenuItem.Enabled = true;
11092 this.CreateTabRuleOpMenuItem.Enabled = true;
11093 this.CreateIdRuleOpMenuItem.Enabled = true;
11094 this.CreateSourceRuleOpMenuItem.Enabled = true;
11095 this.ReadOpMenuItem.Enabled = true;
11096 this.UnreadOpMenuItem.Enabled = true;
11099 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
11101 this.FavOpMenuItem.Enabled = false;
11102 this.UnFavOpMenuItem.Enabled = false;
11103 this.OpenStatusOpMenuItem.Enabled = false;
11104 this.OpenFavotterOpMenuItem.Enabled = false;
11105 this.ShowRelatedStatusesMenuItem2.Enabled = false;
11106 this.RtOpMenuItem.Enabled = false;
11107 this.RtUnOpMenuItem.Enabled = false;
11108 this.QtOpMenuItem.Enabled = false;
11109 this.FavoriteRetweetMenuItem.Enabled = false;
11110 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11114 this.FavOpMenuItem.Enabled = true;
11115 this.UnFavOpMenuItem.Enabled = true;
11116 this.OpenStatusOpMenuItem.Enabled = true;
11117 this.OpenFavotterOpMenuItem.Enabled = true;
11118 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
11120 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
11122 this.RtOpMenuItem.Enabled = false;
11123 this.RtUnOpMenuItem.Enabled = false;
11124 this.QtOpMenuItem.Enabled = false;
11125 this.FavoriteRetweetMenuItem.Enabled = false;
11126 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11130 this.RtOpMenuItem.Enabled = true;
11131 this.RtUnOpMenuItem.Enabled = true;
11132 this.QtOpMenuItem.Enabled = true;
11133 this.FavoriteRetweetMenuItem.Enabled = true;
11134 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11138 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11140 this.RefreshPrevOpMenuItem.Enabled = true;
11144 this.RefreshPrevOpMenuItem.Enabled = false;
11146 if (!this.ExistCurrentPost
11147 || _curPost.InReplyToStatusId == null)
11149 OpenRepSourceOpMenuItem.Enabled = false;
11153 OpenRepSourceOpMenuItem.Enabled = true;
11155 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11157 OpenRterHomeMenuItem.Enabled = false;
11161 OpenRterHomeMenuItem.Enabled = true;
11164 if (this.ExistCurrentPost)
11166 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11170 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11172 ContextMenuTabProperty_Opening(sender, null);
11175 public Twitter TwitterInstance
11180 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11182 if (this._initialLayout)
11185 int splitterDistance;
11186 switch (this.WindowState)
11188 case FormWindowState.Normal:
11189 splitterDistance = this.SplitContainer3.SplitterDistance;
11191 case FormWindowState.Maximized:
11192 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11193 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11194 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11195 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11201 this._mySpDis3 = splitterDistance;
11202 this.ModifySettingLocal = true;
11205 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11207 if (_statuses.RemovedTab.Count == 0)
11209 UndoRemoveTabMenuItem.Enabled = false;
11213 UndoRemoveTabMenuItem.Enabled = true;
11215 if (ListTab.SelectedTab != null)
11217 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11218 PublicSearchQueryMenuItem.Enabled = true;
11220 PublicSearchQueryMenuItem.Enabled = false;
11224 PublicSearchQueryMenuItem.Enabled = false;
11226 if (!this.ExistCurrentPost)
11228 this.CopySTOTMenuItem.Enabled = false;
11229 this.CopyURLMenuItem.Enabled = false;
11230 this.CopyUserIdStripMenuItem.Enabled = false;
11234 this.CopySTOTMenuItem.Enabled = true;
11235 this.CopyURLMenuItem.Enabled = true;
11236 this.CopyUserIdStripMenuItem.Enabled = true;
11237 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11238 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11242 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11244 SetNotifyIconText();
11247 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11249 var id = _curPost?.ScreenName ?? "";
11251 await this.ShowUserStatus(id);
11254 private async Task doShowUserStatus(string id, bool ShowInputDialog)
11256 TwitterUser user = null;
11258 if (ShowInputDialog)
11260 using (var inputName = new InputTabName())
11262 inputName.FormTitle = "Show UserStatus";
11263 inputName.FormDescription = Properties.Resources.FRMessage1;
11264 inputName.TabName = id;
11266 if (inputName.ShowDialog(this) != DialogResult.OK)
11268 if (string.IsNullOrWhiteSpace(inputName.TabName))
11271 id = inputName.TabName.Trim();
11275 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11277 var cancellationToken = dialog.EnableCancellation();
11281 var task = this.twitterApi.UsersShow(id);
11282 user = await dialog.WaitForAsync(this, task);
11284 catch (WebApiException ex)
11286 if (!cancellationToken.IsCancellationRequested)
11287 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11291 if (cancellationToken.IsCancellationRequested)
11295 await this.doShowUserStatus(user);
11298 private async Task doShowUserStatus(TwitterUser user)
11300 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
11302 var showUserTask = userDialog.ShowUserAsync(user);
11303 userDialog.ShowDialog(this);
11306 this.BringToFront();
11308 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11309 await showUserTask;
11313 internal Task ShowUserStatus(string id, bool ShowInputDialog)
11315 return this.doShowUserStatus(id, ShowInputDialog);
11318 internal Task ShowUserStatus(string id)
11320 return this.doShowUserStatus(id, true);
11323 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
11325 if (_curPost != null)
11327 await this.ShowUserStatus(_curPost.ScreenName, false);
11331 private async void RtCountMenuItem_Click(object sender, EventArgs e)
11333 if (!this.ExistCurrentPost)
11336 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11337 TwitterStatus status;
11339 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11341 var cancellationToken = dialog.EnableCancellation();
11345 var task = this.twitterApi.StatusesShow(statusId);
11346 status = await dialog.WaitForAsync(this, task);
11348 catch (WebApiException ex)
11350 if (!cancellationToken.IsCancellationRequested)
11351 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11355 if (cancellationToken.IsCancellationRequested)
11359 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11362 private HookGlobalHotkey _hookGlobalHotkey;
11365 _hookGlobalHotkey = new HookGlobalHotkey(this);
11367 // この呼び出しは、Windows フォーム デザイナで必要です。
11368 InitializeComponent();
11370 // InitializeComponent() 呼び出しの後で初期化を追加します。
11372 if (!this.DesignMode)
11374 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11375 this.StatusText.Dock = DockStyle.Fill;
11378 this.tweetDetailsView.Owner = this;
11380 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11381 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11382 this.gh.NotifyClicked += GrowlHelper_Callback;
11384 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11385 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11387 this.ImageSelector.Visible = false;
11388 this.ImageSelector.Enabled = false;
11389 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11391 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11393 this.ReplaceAppName();
11394 this.InitializeShortcuts();
11397 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11399 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11402 this.Visible = false;
11404 else if (Form.ActiveForm == null)
11406 this.Visible = true;
11407 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11409 this.BringToFront();
11410 this.StatusText.Focus();
11414 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11416 this.MultiLinePullDownMenuItem.PerformClick();
11419 public PostClass CurPost
11421 get { return _curPost; }
11425 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11427 if (ImageSelector.Visible)
11428 ImageSelector.EndSelection();
11430 ImageSelector.BeginSelection();
11433 private void SelectMedia_DragEnter(DragEventArgs e)
11435 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11437 e.Effect = DragDropEffects.Copy;
11440 e.Effect = DragDropEffects.None;
11443 private void SelectMedia_DragDrop(DragEventArgs e)
11446 this.BringToFront();
11447 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11448 StatusText.Focus();
11451 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11453 TimelinePanel.Visible = false;
11454 TimelinePanel.Enabled = false;
11457 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11459 TimelinePanel.Visible = true;
11460 TimelinePanel.Enabled = true;
11461 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11464 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11466 this.AllowDrop = false;
11469 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11471 this.AllowDrop = true;
11474 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11476 if (ImageSelector.Visible)
11478 ModifySettingCommon = true;
11479 SaveConfigsAll(true);
11481 this.StatusText_TextChanged(null, null);
11485 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11487 this.StatusText_TextChanged(null, null);
11491 /// StatusTextでCtrl+Vが押下された時の処理
11493 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11497 if (Clipboard.ContainsText())
11499 // clipboardにテキストがある場合は貼り付け処理
11500 this.StatusText.Paste(Clipboard.GetText());
11502 else if (Clipboard.ContainsImage())
11505 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11506 Properties.Resources.PostPictureWarn4,
11507 MessageBoxButtons.OKCancel,
11508 MessageBoxIcon.Question,
11509 MessageBoxDefaultButton.Button2)
11510 == DialogResult.OK)
11512 // clipboardから画像を取得
11513 using (var image = Clipboard.GetImage())
11515 this.ImageSelector.BeginSelection(image);
11520 catch (ExternalException ex)
11522 MessageBox.Show(ex.Message);
11527 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11529 using (ListManage form = new ListManage(tw))
11531 form.ShowDialog(this);
11535 public bool ModifySettingCommon { get; set; }
11536 public bool ModifySettingLocal { get; set; }
11537 public bool ModifySettingAtId { get; set; }
11539 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11541 if (this.ExistCurrentPost && !_curPost.IsDm)
11542 RtCountMenuItem.Enabled = true;
11544 RtCountMenuItem.Enabled = false;
11546 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11547 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11549 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11552 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11557 private void CopyUserId()
11559 if (_curPost == null) return;
11560 string clstr = _curPost.ScreenName;
11563 Clipboard.SetDataObject(clstr, false, 5, 100);
11565 catch (Exception ex)
11567 MessageBox.Show(ex.Message);
11571 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11573 if (this.ExistCurrentPost && !_curPost.IsDm)
11577 await this.OpenRelatedTab(this._curPost);
11579 catch (TabException ex)
11581 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11587 /// 指定されたツイートに対する関連発言タブを開きます
11589 /// <param name="statusId">表示するツイートのID</param>
11590 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11591 public async Task OpenRelatedTab(long statusId)
11593 var post = this._statuses[statusId];
11598 post = await this.tw.GetStatusApi(false, statusId);
11600 catch (WebApiException ex)
11602 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11607 await this.OpenRelatedTab(post);
11611 /// 指定されたツイートに対する関連発言タブを開きます
11613 /// <param name="post">表示する対象となるツイート</param>
11614 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11615 private async Task OpenRelatedTab(PostClass post)
11617 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11618 if (tabRelated != null)
11620 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11623 var tabName = this._statuses.MakeTabName("Related Tweets");
11625 tabRelated = new RelatedPostsTabModel(tabName, post);
11626 tabRelated.UnreadManage = false;
11627 tabRelated.Notify = false;
11629 this._statuses.AddTab(tabRelated);
11630 this.AddNewTab(tabRelated, startup: false);
11633 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
11635 tabPage = this.ListTab.TabPages[i];
11636 if (tabName == tabPage.Text)
11638 this.ListTab.SelectedIndex = i;
11643 await this.GetRelatedTweetsAsync(tabRelated);
11645 tabPage = this.ListTab.TabPages.Cast<TabPage>()
11646 .FirstOrDefault(x => x.Text == tabRelated.TabName);
11648 if (tabPage != null)
11650 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11652 var listView = (DetailsListView)tabPage.Tag;
11653 var targetPost = tabRelated.TargetPost;
11654 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11656 if (index != -1 && index < listView.Items.Count)
11658 listView.SelectedIndices.Add(index);
11659 listView.Items[index].Focused = true;
11664 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11666 StringBuilder buf = new StringBuilder();
11667 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11668 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11669 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11670 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11671 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11674 private void tw_UserIdChanged()
11676 this.ModifySettingCommon = true;
11679 #region "Userstream"
11680 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11684 if (InvokeRequired && !IsDisposed)
11686 await this.InvokeAsync(async () =>
11688 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11689 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
11691 this.PurgeListViewItemCache();
11692 ((DetailsListView)_curTab.Tag).Update();
11693 if (_curPost != null && _curPost.StatusId == e.StatusId)
11694 await this.DispSelectedPost(true);
11700 catch (ObjectDisposedException)
11704 catch (InvalidOperationException)
11710 private int userStreamsRefreshing = 0;
11712 private async void tw_NewPostFromStream(object sender, EventArgs e)
11714 if (SettingManager.Common.ReadOldPosts)
11716 _statuses.SetReadHomeTab(); //新着時未読クリア
11719 this._statuses.DistributePosts();
11721 if (SettingManager.Common.UserstreamPeriod > 0) return;
11723 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
11724 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
11728 await this.InvokeAsync(() => this.RefreshTimeline())
11729 .ConfigureAwait(false);
11733 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
11738 private async void tw_UserStreamStarted(object sender, EventArgs e)
11742 if (InvokeRequired && !IsDisposed)
11744 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11748 catch (ObjectDisposedException)
11752 catch (InvalidOperationException)
11757 this.RefreshUserStreamsMenu();
11758 this.MenuItemUserStream.Enabled = true;
11760 StatusLabel.Text = "UserStream Started.";
11763 private async void tw_UserStreamStopped(object sender, EventArgs e)
11767 if (InvokeRequired && !IsDisposed)
11769 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11773 catch (ObjectDisposedException)
11777 catch (InvalidOperationException)
11782 this.RefreshUserStreamsMenu();
11783 this.MenuItemUserStream.Enabled = true;
11785 StatusLabel.Text = "UserStream Stopped.";
11788 private void RefreshUserStreamsMenu()
11790 if (this.tw.UserStreamActive)
11792 this.MenuItemUserStream.Text = "&UserStream ▶";
11793 this.StopToolStripMenuItem.Text = "&Stop";
11797 this.MenuItemUserStream.Text = "&UserStream ■";
11798 this.StopToolStripMenuItem.Text = "&Start";
11802 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11806 if (InvokeRequired && !IsDisposed)
11808 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11812 catch (ObjectDisposedException)
11816 catch (InvalidOperationException)
11820 var ev = e.EventData;
11821 StatusLabel.Text = "Event: " + ev.Event;
11822 //if (ev.Event == "favorite")
11824 // NotifyFavorite(ev);
11827 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11829 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
11831 this.PurgeListViewItemCache();
11832 ((DetailsListView)_curTab.Tag).Update();
11834 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
11836 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11837 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11842 private void NotifyEvent(Twitter.FormattedEvent ev)
11845 if (BalloonRequired(ev))
11847 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11848 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11849 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11850 StringBuilder title = new StringBuilder();
11851 if (SettingManager.Common.DispUsername)
11853 title.Append(tw.Username);
11854 title.Append(" - ");
11860 title.Append(Application.ProductName);
11861 title.Append(" [");
11862 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11863 title.Append("] by ");
11864 if (!string.IsNullOrEmpty(ev.Username))
11866 title.Append(ev.Username);
11870 //title.Append("");
11873 if (!string.IsNullOrEmpty(ev.Target))
11875 //NotifyIcon1.BalloonTipText = ev.Target;
11880 //NotifyIcon1.BalloonTipText = " ";
11883 //NotifyIcon1.ShowBalloonTip(500);
11884 if (SettingManager.Common.IsUseNotifyGrowl)
11886 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11887 ev.Id.ToString(), title.ToString(), text);
11891 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11892 NotifyIcon1.BalloonTipTitle = title.ToString();
11893 NotifyIcon1.BalloonTipText = text;
11894 NotifyIcon1.ShowBalloonTip(500);
11899 string snd = SettingManager.Common.EventSoundFile;
11900 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11902 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11906 string dir = Application.StartupPath;
11907 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11909 dir = Path.Combine(dir, "Sounds");
11911 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11923 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11925 MenuItemUserStream.Enabled = false;
11926 if (StopRefreshAllMenuItem.Checked)
11928 StopRefreshAllMenuItem.Checked = false;
11931 if (this.tw.UserStreamActive)
11933 tw.StopUserStream();
11937 tw.StartUserStream();
11941 private static string inputTrack = "";
11943 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11945 if (TrackToolStripMenuItem.Checked)
11947 using (InputTabName inputForm = new InputTabName())
11949 inputForm.TabName = inputTrack;
11950 inputForm.FormTitle = "Input track word";
11951 inputForm.FormDescription = "Track word";
11952 if (inputForm.ShowDialog() != DialogResult.OK)
11954 TrackToolStripMenuItem.Checked = false;
11957 inputTrack = inputForm.TabName.Trim();
11959 if (!inputTrack.Equals(tw.TrackWord))
11961 tw.TrackWord = inputTrack;
11962 this.ModifySettingCommon = true;
11963 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11964 tw.ReconnectUserStream();
11970 tw.ReconnectUserStream();
11972 this.ModifySettingCommon = true;
11975 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11977 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11978 this.ModifySettingCommon = true;
11979 tw.ReconnectUserStream();
11982 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11984 if (evtDialog == null || evtDialog.IsDisposed)
11987 evtDialog = new EventViewerDialog();
11988 evtDialog.Owner = this;
11990 Point pos = evtDialog.Location;
11991 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
11992 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
11993 evtDialog.Location = pos;
11995 evtDialog.EventSource = tw.StoredEvent;
11996 if (!evtDialog.Visible)
11998 evtDialog.Show(this);
12002 evtDialog.Activate();
12004 this.TopMost = SettingManager.Common.AlwaysTop;
12008 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
12010 MyCommon._endingFlag = true;
12014 Application.Restart();
12018 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
12022 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
12024 if (!string.IsNullOrEmpty(tw.Username))
12025 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
12028 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
12030 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
12033 private bool ExistCurrentPost
12037 if (_curPost == null) return false;
12038 if (_curPost.IsDeleted) return false;
12043 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
12045 ShowUserTimeline();
12048 private string GetUserIdFromCurPostOrInput(string caption)
12050 var id = _curPost?.ScreenName ?? "";
12052 using (InputTabName inputName = new InputTabName())
12054 inputName.FormTitle = caption;
12055 inputName.FormDescription = Properties.Resources.FRMessage1;
12056 inputName.TabName = id;
12057 if (inputName.ShowDialog() == DialogResult.OK &&
12058 !string.IsNullOrEmpty(inputName.TabName.Trim()))
12060 id = inputName.TabName.Trim();
12070 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
12072 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
12073 if (!string.IsNullOrEmpty(id))
12075 AddNewTabForUserTimeline(id);
12079 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
12081 string id = GetUserIdFromCurPostOrInput("Show Favstar");
12082 if (!string.IsNullOrEmpty(id))
12084 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
12088 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
12090 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
12093 private void TimelineRefreshEnableChange(bool isEnable)
12097 tw.StartUserStream();
12101 tw.StopUserStream();
12103 TimerTimeline.Enabled = isEnable;
12106 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
12108 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
12111 private async Task OpenUserAppointUrl()
12113 if (SettingManager.Common.UserAppointUrl != null)
12115 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
12117 if (_curPost != null)
12119 string xUrl = SettingManager.Common.UserAppointUrl;
12120 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
12122 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
12123 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
12125 await this.OpenUriInBrowserAsync(xUrl);
12130 await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
12135 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12137 await this.OpenUserAppointUrl();
12140 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
12142 if (Form.ActiveForm == null)
12144 await this.InvokeAsync(() =>
12146 this.Visible = true;
12147 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12149 this.BringToFront();
12150 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
12152 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12156 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12162 private void ReplaceAppName()
12164 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12165 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12168 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12170 this.SplitContainer3.Panel2Collapsed = false;
12173 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12175 await this.OpenThumbnailPicture(e.Thumbnail);
12178 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
12180 await this.OpenUriInBrowserAsync(e.ImageUrl);
12183 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
12185 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
12187 await this.OpenUriInBrowserAsync(url);
12190 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
12192 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
12195 private void PostButton_KeyDown(object sender, KeyEventArgs e)
12197 if (e.KeyCode == Keys.Space)
12199 this.JumpUnreadMenuItem_Click(null, null);
12201 e.SuppressKeyPress = true;
12205 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
12207 this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
12208 this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
12209 this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
12210 this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
12211 this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
12213 this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
12216 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
12218 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
12221 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
12223 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
12226 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
12228 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
12231 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
12233 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
12236 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
12238 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
12241 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
12243 if (SettingManager.Common.IconSize == iconSize) return;
12245 var oldIconCol = _iconCol;
12247 SettingManager.Common.IconSize = iconSize;
12248 ApplyListViewIconSize(iconSize);
12250 if (_iconCol != oldIconCol)
12252 foreach (TabPage tp in ListTab.TabPages)
12254 ResetColumns((DetailsListView)tp.Tag);
12258 _curList?.Refresh();
12260 ModifySettingCommon = true;
12263 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
12265 var state = this.LockListSortOrderToolStripMenuItem.Checked;
12266 if (SettingManager.Common.SortOrderLock == state) return;
12268 SettingManager.Common.SortOrderLock = state;
12270 ModifySettingCommon = true;
12273 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
12275 if (!string.IsNullOrEmpty(e.StatusText))
12277 this.StatusLabelUrl.Text = e.StatusText;
12281 this.SetStatusLabelUrl();