OSDN Git Service

using var を使用する
[opentween/open-tween.git] / OpenTween / Tween.cs
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.
9 // 
10 // This file is part of OpenTween.
11 // 
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)
15 // any later version.
16 // 
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
20 // for more details. 
21 // 
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.
26
27 //コンパイル後コマンド
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)"
30
31 using System;
32 using System.Collections.Concurrent;
33 using System.Collections.Generic;
34 using System.ComponentModel;
35 using System.Diagnostics;
36 using System.Drawing;
37 using System.Globalization;
38 using System.IO;
39 using System.Linq;
40 using System.Media;
41 using System.Net;
42 using System.Net.Http;
43 using System.Reflection;
44 using System.Runtime.InteropServices;
45 using System.Text;
46 using System.Text.RegularExpressions;
47 using System.Threading;
48 using System.Threading.Tasks;
49 using System.Windows.Forms;
50 using OpenTween.Api;
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;
57
58 namespace OpenTween
59 {
60     public partial class TweenMain : OTBaseForm
61     {
62         //各種設定
63
64         /// <summary>画面サイズ</summary>
65         private Size _mySize;
66
67         /// <summary>画面位置</summary>
68         private Point _myLoc;
69
70         /// <summary>区切り位置</summary>
71         private int _mySpDis;
72
73         /// <summary>発言欄区切り位置</summary>
74         private int _mySpDis2;
75
76         /// <summary>プレビュー区切り位置</summary>
77         private int _mySpDis3;
78
79         /// <summary>アイコンサイズ</summary>
80         /// <remarks>
81         /// 現在は16、24、48の3種類。将来直接数字指定可能とする
82         /// 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様
83         /// </remarks>
84         private int _iconSz;
85
86         private bool _iconCol; // 1列表示の時true(48サイズのとき)
87
88         //雑多なフラグ類
89         private bool _initial; // true:起動時処理中
90         private bool _initialLayout = true;
91         private bool _ignoreConfigSave; // true:起動時処理中
92
93         /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
94         private bool _tabDrag;
95
96         private TabPage _beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
97         private Point _tabMouseDownPoint;
98
99         /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
100         private string _rclickTabName;
101
102         private readonly object _syncObject = new object(); // ロック用
103
104         private const string detailHtmlFormatHeaderMono = 
105             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
106             + "<style type=\"text/css\"><!-- "
107             + "body, p, pre {margin: 0;} "
108             + "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%);} "
109             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
110             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
111             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
112             + ".quote-tweet.reply {border-color: #f33;} "
113             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
114             + "--></style>"
115             + "</head><body><pre>";
116         private const string detailHtmlFormatFooterMono = "</pre></body></html>";
117         private const string detailHtmlFormatHeaderColor = 
118             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
119             + "<style type=\"text/css\"><!-- "
120             + "body, p, pre {margin: 0;} "
121             + "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%);} "
122             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
123             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
124             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
125             + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
126             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
127             + "--></style>"
128             + "</head><body><p>";
129         private const string detailHtmlFormatFooterColor = "</p></body></html>";
130         private string detailHtmlFormatHeader;
131         private string detailHtmlFormatFooter;
132
133         private bool _myStatusError = false;
134         private bool _myStatusOnline = false;
135         private bool soundfileListup = false;
136         private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
137
138         //twitter解析部
139         private readonly TwitterApi twitterApi = new TwitterApi();
140         private Twitter tw;
141
142         //Growl呼び出し部
143         private readonly GrowlHelper gh = new GrowlHelper(ApplicationSettings.ApplicationName);
144
145         //サブ画面インスタンス
146
147         /// <summary>検索画面インスタンス</summary>
148         internal SearchWordDialog SearchDialog = new SearchWordDialog();
149
150         private readonly OpenURL UrlDialog = new OpenURL();
151
152         /// <summary>@id補助</summary>
153         public AtIdSupplement AtIdSupl;
154
155         /// <summary>Hashtag補助</summary>
156         public AtIdSupplement HashSupl;
157
158         public HashtagManage HashMgr;
159         private EventViewerDialog evtDialog;
160
161         //表示フォント、色、アイコン
162
163         /// <summary>未読用フォント</summary>
164         private Font _fntUnread;
165
166         /// <summary>未読用文字色</summary>
167         private Color _clUnread;
168
169         /// <summary>既読用フォント</summary>
170         private Font _fntReaded;
171
172         /// <summary>既読用文字色</summary>
173         private Color _clReaded;
174
175         /// <summary>Fav用文字色</summary>
176         private Color _clFav;
177
178         /// <summary>片思い用文字色</summary>
179         private Color _clOWL;
180
181         /// <summary>Retweet用文字色</summary>
182         private Color _clRetweet;
183
184         /// <summary>選択中の行用文字色</summary>
185         private readonly Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText);
186
187         /// <summary>発言詳細部用フォント</summary>
188         private Font _fntDetail;
189
190         /// <summary>発言詳細部用色</summary>
191         private Color _clDetail;
192
193         /// <summary>発言詳細部用リンク文字色</summary>
194         private Color _clDetailLink;
195
196         /// <summary>発言詳細部用背景色</summary>
197         private Color _clDetailBackcolor;
198
199         /// <summary>自分の発言用背景色</summary>
200         private Color _clSelf;
201
202         /// <summary>自分宛返信用背景色</summary>
203         private Color _clAtSelf;
204
205         /// <summary>選択発言者の他の発言用背景色</summary>
206         private Color _clTarget;
207
208         /// <summary>選択発言中の返信先用背景色</summary>
209         private Color _clAtTarget;
210
211         /// <summary>選択発言者への返信発言用背景色</summary>
212         private Color _clAtFromTarget;
213
214         /// <summary>選択発言の唯一@先</summary>
215         private Color _clAtTo;
216
217         /// <summary>リスト部通常発言背景色</summary>
218         private Color _clListBackcolor;
219
220         /// <summary>入力欄背景色</summary>
221         private Color _clInputBackcolor;
222
223         /// <summary>入力欄文字色</summary>
224         private Color _clInputFont;
225
226         /// <summary>入力欄フォント</summary>
227         private Font _fntInputFont;
228
229         /// <summary>アイコン画像リスト</summary>
230         private ImageCache IconCache;
231
232         /// <summary>タスクトレイアイコン:通常時 (At.ico)</summary>
233         private Icon NIconAt;
234
235         /// <summary>タスクトレイアイコン:通信エラー時 (AtRed.ico)</summary>
236         private Icon NIconAtRed;
237
238         /// <summary>タスクトレイアイコン:オフライン時 (AtSmoke.ico)</summary>
239         private Icon NIconAtSmoke;
240
241         /// <summary>タスクトレイアイコン:更新中 (Refresh.ico)</summary>
242         private Icon[] NIconRefresh = new Icon[4];
243
244         /// <summary>未読のあるタブ用アイコン (Tab.ico)</summary>
245         private Icon TabIcon;
246
247         /// <summary>画面左上のアイコン (Main.ico)</summary>
248         private Icon MainIcon;
249
250         private Icon ReplyIcon;
251         private Icon ReplyIconBlink;
252
253         private readonly ImageList _listViewImageList = new ImageList(); // ListViewItemの高さ変更用
254
255         private PostClass _anchorPost;
256         private bool _anchorFlag; // true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
257
258         /// <summary>発言履歴</summary>
259         private readonly List<StatusTextHistory> _history = new List<StatusTextHistory>();
260
261         /// <summary>発言履歴カレントインデックス</summary>
262         private int _hisIdx;
263
264         //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
265
266         /// <summary>リプライ先のステータスID・スクリーン名</summary>
267         private (long StatusId, string ScreenName)? inReplyTo = null;
268
269         //時速表示用
270         private readonly List<DateTimeUtc> _postTimestamps = new List<DateTimeUtc>();
271         private readonly List<DateTimeUtc> _favTimestamps = new List<DateTimeUtc>();
272
273         // 以下DrawItem関連
274         private readonly SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
275         private SolidBrush _brsBackColorMine;
276         private SolidBrush _brsBackColorAt;
277         private SolidBrush _brsBackColorYou;
278         private SolidBrush _brsBackColorAtYou;
279         private SolidBrush _brsBackColorAtFromTarget;
280         private SolidBrush _brsBackColorAtTo;
281         private SolidBrush _brsBackColorNone;
282
283         /// <summary>Listにフォーカスないときの選択行の背景色</summary>
284         private readonly SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace));
285
286         private readonly StringFormat sfTab = new StringFormat();
287
288         //////////////////////////////////////////////////////////////////////////////////////////////////////////
289         private TabInformations _statuses;
290
291         /// <summary>
292         /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
293         /// </summary>
294         /// <remarks>
295         /// キャッシュクリアのために null が代入されることがあるため、
296         /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
297         /// 一旦ローカル変数に代入してから参照すること。
298         /// </remarks>
299         private ListViewItemCache _listItemCache = null;
300
301         internal class ListViewItemCache
302         {
303             /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
304             public ListView TargetList { get; set; }
305
306             /// <summary>キャッシュする範囲の開始インデックス</summary>
307             public int StartIndex { get; set; }
308
309             /// <summary>キャッシュする範囲の終了インデックス</summary>
310             public int EndIndex { get; set; }
311
312             /// <summary>キャッシュされた範囲に対応する <see cref="ListViewItem"/> と <see cref="PostClass"/> の組</summary>
313             public (ListViewItem, PostClass)[] Cache { get; set; }
314
315             /// <summary>キャッシュされたアイテムの件数</summary>
316             public int Count
317                 => this.EndIndex - this.StartIndex + 1;
318
319             /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
320             /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
321             public bool Contains(int index)
322                 => index >= this.StartIndex && index <= this.EndIndex;
323
324             /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
325             /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
326             public bool IsSupersetOf(int rangeStart, int rangeEnd)
327                 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
328
329             /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
330             /// <returns>取得に成功すれば true、それ以外は false</returns>
331             public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
332             {
333                 if (this.Contains(index))
334                 {
335                     (item, post) = this.Cache[index - this.StartIndex];
336                     return true;
337                 }
338                 else
339                 {
340                     item = null;
341                     post = null;
342                     return false;
343                 }
344             }
345         }
346
347         private bool _isColumnChanged = false;
348
349         private const int MAX_WORKER_THREADS = 20;
350         private readonly SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
351         private readonly CancellationTokenSource workerCts = new CancellationTokenSource();
352         private readonly IProgress<string> workerProgress;
353
354         private int UnreadCounter = -1;
355         private int UnreadAtCounter = -1;
356
357         private readonly string[] ColumnOrgText = new string[9];
358         private readonly string[] ColumnText = new string[9];
359
360         private bool _DoFavRetweetFlags = false;
361
362         //////////////////////////////////////////////////////////////////////////////////////////////////////////
363
364         private readonly TimelineScheduler timelineScheduler = new TimelineScheduler();
365         private ThrottlingTimer RefreshThrottlingTimer;
366         private ThrottlingTimer colorizeDebouncer;
367         private ThrottlingTimer selectionDebouncer;
368         private ThrottlingTimer saveConfigDebouncer;
369
370         private string recommendedStatusFooter;
371         private bool urlMultibyteSplit = false;
372         private bool preventSmsCommand = true;
373
374         // URL短縮のUndo用
375         private struct urlUndo
376         {
377             public string Before;
378             public string After;
379         }
380
381         private List<urlUndo> urlUndoBuffer = null;
382
383         private readonly struct ReplyChain
384         {
385             public readonly long OriginalId;
386             public readonly long InReplyToId;
387             public readonly TabModel OriginalTab;
388
389             public ReplyChain(long originalId, long inReplyToId, TabModel originalTab)
390             {
391                 this.OriginalId = originalId;
392                 this.InReplyToId = inReplyToId;
393                 this.OriginalTab = originalTab;
394             }
395         }
396
397         /// <summary>[, ]でのリプライ移動の履歴</summary>
398         private Stack<ReplyChain> replyChains;
399
400         /// <summary>ポスト選択履歴</summary>
401         private readonly Stack<(TabModel, PostClass)> selectPostChains = new Stack<(TabModel, PostClass)>();
402
403         public TabModel CurrentTab
404             => this._statuses.SelectedTab;
405
406         public string CurrentTabName
407             => this._statuses.SelectedTabName;
408
409         public TabPage CurrentTabPage
410             => this.ListTab.TabPages[this._statuses.Tabs.IndexOf(this.CurrentTabName)];
411
412         public DetailsListView CurrentListView
413             => (DetailsListView)this.CurrentTabPage.Tag;
414
415         public PostClass CurrentPost
416             => this.CurrentTab.SelectedPost;
417
418         /// <summary>検索処理タイプ</summary>
419         internal enum SEARCHTYPE
420         {
421             DialogSearch,
422             NextSearch,
423             PrevSearch,
424         }
425
426         private class StatusTextHistory
427         {
428             public string status = "";
429             public (long StatusId, string ScreenName)? inReplyTo = null;
430
431             /// <summary>画像投稿サービス名</summary>
432             public string imageService = "";
433
434             public IMediaItem[] mediaItems = null;
435             public StatusTextHistory()
436             {
437             }
438             public StatusTextHistory(string status, (long StatusId, string ScreenName)? inReplyTo)
439             {
440                 this.status = status;
441                 this.inReplyTo = inReplyTo;
442             }
443         }
444
445         private void TweenMain_Activated(object sender, EventArgs e)
446         {
447             //画面がアクティブになったら、発言欄の背景色戻す
448             if (StatusText.Focused)
449             {
450                 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
451             }
452         }
453
454         private bool disposed = false;
455
456         /// <summary>
457         /// 使用中のリソースをすべてクリーンアップします。
458         /// </summary>
459         /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
460         protected override void Dispose(bool disposing)
461         {
462             base.Dispose(disposing);
463
464             if (this.disposed)
465                 return;
466
467             if (disposing)
468             {
469                 this.components?.Dispose();
470
471                 //後始末
472                 SearchDialog.Dispose();
473                 UrlDialog.Dispose();
474                 NIconAt?.Dispose();
475                 NIconAtRed?.Dispose();
476                 NIconAtSmoke?.Dispose();
477                 foreach (var iconRefresh in this.NIconRefresh)
478                 {
479                     iconRefresh?.Dispose();
480                 }
481                 TabIcon?.Dispose();
482                 MainIcon?.Dispose();
483                 ReplyIcon?.Dispose();
484                 ReplyIconBlink?.Dispose();
485                 _listViewImageList.Dispose();
486                 _brsHighLight.Dispose();
487                 _brsBackColorMine?.Dispose();
488                 _brsBackColorAt?.Dispose();
489                 _brsBackColorYou?.Dispose();
490                 _brsBackColorAtYou?.Dispose();
491                 _brsBackColorAtFromTarget?.Dispose();
492                 _brsBackColorAtTo?.Dispose();
493                 _brsBackColorNone?.Dispose();
494                 _brsDeactiveSelection?.Dispose();
495                 //sf.Dispose();
496                 sfTab.Dispose();
497
498                 this.workerCts.Cancel();
499
500                 if (IconCache != null)
501                 {
502                     this.IconCache.CancelAsync();
503                     this.IconCache.Dispose();
504                 }
505
506                 this.thumbnailTokenSource?.Dispose();
507
508                 this.tw.Dispose();
509                 this.twitterApi.Dispose();
510                 this._hookGlobalHotkey.Dispose();
511             }
512
513             // 終了時にRemoveHandlerしておかないとメモリリークする
514             // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
515             Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
516             Microsoft.Win32.SystemEvents.TimeChanged -= SystemEvents_TimeChanged;
517
518             this.disposed = true;
519         }
520
521         private void LoadIcons()
522         {
523             // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
524             var iconsDir = Path.Combine(Application.StartupPath, "Icons");
525
526             // ウィンドウ左上のアイコン
527             var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
528
529             // タブ見出し未読表示アイコン
530             var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
531
532             // タスクトレイ: 通常時アイコン
533             var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
534
535             // タスクトレイ: エラー時アイコン
536             var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
537
538             // タスクトレイ: オフライン時アイコン
539             var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
540
541             // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
542             var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
543             var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
544
545             // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
546             var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
547             var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
548             var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
549             var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
550
551             // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
552
553             this.MainIcon = iconMain ?? Properties.Resources.MIcon;
554             this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
555             this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
556             this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
557             this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
558
559             if (iconReply != null && iconReplyBlink != null)
560             {
561                 this.ReplyIcon = iconReply;
562                 this.ReplyIconBlink = iconReplyBlink;
563             }
564             else
565             {
566                 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
567                 this.ReplyIconBlink = this.NIconAt;
568             }
569
570             if (iconRefresh1 == null)
571             {
572                 this.NIconRefresh = new[] {
573                     Properties.Resources.Refresh, Properties.Resources.Refresh2,
574                     Properties.Resources.Refresh3, Properties.Resources.Refresh4,
575                 };
576             }
577             else if (iconRefresh2 == null)
578             {
579                 this.NIconRefresh = new[] { iconRefresh1 };
580             }
581             else if (iconRefresh3 == null)
582             {
583                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
584             }
585             else if (iconRefresh4 == null)
586             {
587                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
588             }
589             else // iconRefresh1 から iconRefresh4 まで全て揃っている
590             {
591                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
592             }
593         }
594
595         private Icon LoadIcon(string filePath)
596         {
597             if (!File.Exists(filePath))
598                 return null;
599
600             try
601             {
602                 return new Icon(filePath);
603             }
604             catch (Exception)
605             {
606                 return null;
607             }
608         }
609
610         private void InitColumns(ListView list, bool startup)
611         {
612             this.InitColumnText();
613
614             ColumnHeader[] columns = null;
615             try
616             {
617                 if (this._iconCol)
618                 {
619                     columns = new[]
620                     {
621                         new ColumnHeader(), // アイコン
622                         new ColumnHeader(), // 本文
623                     };
624
625                     columns[0].Text = this.ColumnText[0];
626                     columns[1].Text = this.ColumnText[2];
627
628                     if (startup)
629                     {
630                         var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
631
632                         columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
633                         columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
634                         columns[0].DisplayIndex = 0;
635                         columns[1].DisplayIndex = 1;
636                     }
637                     else
638                     {
639                         var idx = 0;
640                         foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
641                         {
642                             columns[idx].Width = curListColumn.Width;
643                             columns[idx].DisplayIndex = curListColumn.DisplayIndex;
644                             idx++;
645                         }
646                     }
647                 }
648                 else
649                 {
650                     columns = new[]
651                     {
652                         new ColumnHeader(), // アイコン
653                         new ColumnHeader(), // ニックネーム
654                         new ColumnHeader(), // 本文
655                         new ColumnHeader(), // 日付
656                         new ColumnHeader(), // ユーザID
657                         new ColumnHeader(), // 未読
658                         new ColumnHeader(), // マーク&プロテクト
659                         new ColumnHeader(), // ソース
660                     };
661
662                     foreach (var i in Enumerable.Range(0, columns.Length))
663                         columns[i].Text = this.ColumnText[i];
664
665                     if (startup)
666                     {
667                         var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
668
669                         columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
670                         columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width2);
671                         columns[2].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
672                         columns[3].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width4);
673                         columns[4].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width5);
674                         columns[5].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width6);
675                         columns[6].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width7);
676                         columns[7].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width8);
677
678                         var displayIndex = new[] {
679                             SettingManager.Local.DisplayIndex1, SettingManager.Local.DisplayIndex2,
680                             SettingManager.Local.DisplayIndex3, SettingManager.Local.DisplayIndex4,
681                             SettingManager.Local.DisplayIndex5, SettingManager.Local.DisplayIndex6,
682                             SettingManager.Local.DisplayIndex7, SettingManager.Local.DisplayIndex8
683                         };
684
685                         foreach (var i in Enumerable.Range(0, displayIndex.Length))
686                         {
687                             columns[i].DisplayIndex = displayIndex[i];
688                         }
689                     }
690                     else
691                     {
692                         var idx = 0;
693                         foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
694                         {
695                             columns[idx].Width = curListColumn.Width;
696                             columns[idx].DisplayIndex = curListColumn.DisplayIndex;
697                             idx++;
698                         }
699                     }
700                 }
701
702                 list.Columns.AddRange(columns);
703
704                 columns = null;
705             }
706             finally
707             {
708                 if (columns != null)
709                 {
710                     foreach (var column in columns)
711                         column?.Dispose();
712                 }
713             }
714         }
715
716         private void InitColumnText()
717         {
718             ColumnText[0] = "";
719             ColumnText[1] = Properties.Resources.AddNewTabText2;
720             ColumnText[2] = Properties.Resources.AddNewTabText3;
721             ColumnText[3] = Properties.Resources.AddNewTabText4_2;
722             ColumnText[4] = Properties.Resources.AddNewTabText5;
723             ColumnText[5] = "";
724             ColumnText[6] = "";
725             ColumnText[7] = "Source";
726
727             ColumnOrgText[0] = "";
728             ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
729             ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
730             ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
731             ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
732             ColumnOrgText[5] = "";
733             ColumnOrgText[6] = "";
734             ColumnOrgText[7] = "Source";
735
736             var c = 0;
737             switch (_statuses.SortMode)
738             {
739                 case ComparerMode.Nickname:  //ニックネーム
740                     c = 1;
741                     break;
742                 case ComparerMode.Data:  //本文
743                     c = 2;
744                     break;
745                 case ComparerMode.Id:  //時刻=発言Id
746                     c = 3;
747                     break;
748                 case ComparerMode.Name:  //名前
749                     c = 4;
750                     break;
751                 case ComparerMode.Source:  //Source
752                     c = 7;
753                     break;
754             }
755
756             if (_iconCol)
757             {
758                 if (_statuses.SortOrder == SortOrder.Descending)
759                 {
760                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
761                     ColumnText[2] = ColumnOrgText[2] + "▾";
762                 }
763                 else
764                 {
765                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
766                     ColumnText[2] = ColumnOrgText[2] + "▴";
767                 }
768             }
769             else
770             {
771                 if (_statuses.SortOrder == SortOrder.Descending)
772                 {
773                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
774                     ColumnText[c] = ColumnOrgText[c] + "▾";
775                 }
776                 else
777                 {
778                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
779                     ColumnText[c] = ColumnOrgText[c] + "▴";
780                 }
781             }
782         }
783
784         private void InitializeTraceFrag()
785         {
786 #if DEBUG
787             TraceOutToolStripMenuItem.Checked = true;
788             MyCommon.TraceFlag = true;
789 #endif
790             if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
791             {
792                 TraceOutToolStripMenuItem.Checked = true;
793                 MyCommon.TraceFlag = true;
794             }
795         }
796
797         private void TweenMain_Load(object sender, EventArgs e)
798         {
799             _ignoreConfigSave = true;
800             this.Visible = false;
801
802             if (MyApplication.StartupOptions.ContainsKey("d"))
803                 MyCommon.TraceFlag = true;
804
805             InitializeTraceFrag();
806
807             //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
808
809             Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
810
811             Regex.CacheSize = 100;
812
813             //発言保持クラス
814             _statuses = TabInformations.GetInstance();
815
816             //アイコン設定
817             LoadIcons();
818             this.Icon = MainIcon;              //メインフォーム(TweenMain)
819             NotifyIcon1.Icon = NIconAt;      //タスクトレイ
820             TabImage.Images.Add(TabIcon);    //タブ見出し
821
822             //<<<<<<<<<設定関連>>>>>>>>>
823             ////設定読み出し
824             LoadConfig();
825
826             // 現在の DPI と設定保存時の DPI との比を取得する
827             var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
828
829             // UIフォント設定
830             var fontUIGlobal = SettingManager.Local.FontUIGlobal;
831             if (fontUIGlobal != null)
832             {
833                 OTBaseForm.GlobalFont = fontUIGlobal;
834                 this.Font = fontUIGlobal;
835             }
836
837             //不正値チェック
838             if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
839             {
840                 if (SettingManager.Common.TimelinePeriod < 15 && SettingManager.Common.TimelinePeriod > 0)
841                     SettingManager.Common.TimelinePeriod = 15;
842
843                 if (SettingManager.Common.ReplyPeriod < 15 && SettingManager.Common.ReplyPeriod > 0)
844                     SettingManager.Common.ReplyPeriod = 15;
845
846                 if (SettingManager.Common.DMPeriod < 15 && SettingManager.Common.DMPeriod > 0)
847                     SettingManager.Common.DMPeriod = 15;
848
849                 if (SettingManager.Common.PubSearchPeriod < 30 && SettingManager.Common.PubSearchPeriod > 0)
850                     SettingManager.Common.PubSearchPeriod = 30;
851
852                 if (SettingManager.Common.UserTimelinePeriod < 15 && SettingManager.Common.UserTimelinePeriod > 0)
853                     SettingManager.Common.UserTimelinePeriod = 15;
854
855                 if (SettingManager.Common.ListsPeriod < 15 && SettingManager.Common.ListsPeriod > 0)
856                     SettingManager.Common.ListsPeriod = 15;
857             }
858
859             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, SettingManager.Common.CountApi))
860                 SettingManager.Common.CountApi = 60;
861             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, SettingManager.Common.CountApiReply))
862                 SettingManager.Common.CountApiReply = 40;
863
864             if (SettingManager.Common.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(SettingManager.Common.MoreCountApi))
865                 SettingManager.Common.MoreCountApi = 200;
866             if (SettingManager.Common.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(SettingManager.Common.FirstCountApi))
867                 SettingManager.Common.FirstCountApi = 100;
868
869             if (SettingManager.Common.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, SettingManager.Common.FavoritesCountApi))
870                 SettingManager.Common.FavoritesCountApi = 40;
871             if (SettingManager.Common.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, SettingManager.Common.ListCountApi))
872                 SettingManager.Common.ListCountApi = 100;
873             if (SettingManager.Common.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, SettingManager.Common.SearchCountApi))
874                 SettingManager.Common.SearchCountApi = 100;
875             if (SettingManager.Common.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, SettingManager.Common.UserTimelineCountApi))
876                 SettingManager.Common.UserTimelineCountApi = 20;
877
878             //廃止サービスが選択されていた場合ux.nuへ読み替え
879             if (SettingManager.Common.AutoShortUrlFirst < 0)
880                 SettingManager.Common.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
881
882             TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
883             this.tw = new Twitter(this.twitterApi);
884
885             //認証関連
886             if (string.IsNullOrEmpty(SettingManager.Common.Token)) SettingManager.Common.UserName = "";
887             tw.Initialize(SettingManager.Common.Token, SettingManager.Common.TokenSecret, SettingManager.Common.UserName, SettingManager.Common.UserId);
888
889             _initial = true;
890
891             Networking.Initialize();
892
893             var saveRequired = false;
894             var firstRun = false;
895
896             //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
897             if (string.IsNullOrEmpty(tw.Username))
898             {
899                 saveRequired = true;
900                 firstRun = true;
901
902                 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
903                 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
904                     string.IsNullOrEmpty(tw.Username))
905                 {
906                     Application.Exit();  //強制終了
907                     return;
908                 }
909             }
910
911             //Twitter用通信クラス初期化
912             Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
913             Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
914             Networking.SetWebProxy(SettingManager.Local.ProxyType,
915                 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
916                 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
917             Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
918
919             TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
920             tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
921             tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
922             tw.TrackWord = SettingManager.Common.TrackWord;
923             TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(tw.TrackWord);
924             tw.AllAtReply = SettingManager.Common.AllAtReply;
925             AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
926             ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
927             ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
928             ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
929             ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
930
931             // アクセストークンが有効であるか確認する
932             // ここが Twitter API への最初のアクセスになるようにすること
933             try
934             {
935                 this.tw.VerifyCredentials();
936             }
937             catch (WebApiException ex)
938             {
939                 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
940                     ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
941             }
942
943             //サムネイル関連の初期化
944             //プロキシ設定等の通信まわりの初期化が済んでから処理する
945             ThumbnailGenerator.InitializeGenerator();
946
947             var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
948             imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
949             imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
950
951             Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
952
953             //画像投稿サービス
954             ImageSelector.Initialize(tw, this.tw.Configuration, SettingManager.Common.UseImageServiceName, SettingManager.Common.UseImageService);
955
956             //ハッシュタグ/@id関連
957             AtIdSupl = new AtIdSupplement(SettingManager.AtIdList.AtIdList, "@");
958             HashSupl = new AtIdSupplement(SettingManager.Common.HashTags, "#");
959             HashMgr = new HashtagManage(HashSupl,
960                                     SettingManager.Common.HashTags.ToArray(),
961                                     SettingManager.Common.HashSelected,
962                                     SettingManager.Common.HashIsPermanent,
963                                     SettingManager.Common.HashIsHead,
964                                     SettingManager.Common.HashIsNotAddToAtReply);
965             if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
966
967             //アイコンリスト作成
968             this.IconCache = new ImageCache();
969             this.tweetDetailsView.IconCache = this.IconCache;
970
971             //フォント&文字色&背景色保持
972             _fntUnread = SettingManager.Local.FontUnread;
973             _clUnread = SettingManager.Local.ColorUnread;
974             _fntReaded = SettingManager.Local.FontRead;
975             _clReaded = SettingManager.Local.ColorRead;
976             _clFav = SettingManager.Local.ColorFav;
977             _clOWL = SettingManager.Local.ColorOWL;
978             _clRetweet = SettingManager.Local.ColorRetweet;
979             _fntDetail = SettingManager.Local.FontDetail;
980             _clDetail = SettingManager.Local.ColorDetail;
981             _clDetailLink = SettingManager.Local.ColorDetailLink;
982             _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
983             _clSelf = SettingManager.Local.ColorSelf;
984             _clAtSelf = SettingManager.Local.ColorAtSelf;
985             _clTarget = SettingManager.Local.ColorTarget;
986             _clAtTarget = SettingManager.Local.ColorAtTarget;
987             _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
988             _clAtTo = SettingManager.Local.ColorAtTo;
989             _clListBackcolor = SettingManager.Local.ColorListBackcolor;
990             _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
991             _clInputFont = SettingManager.Local.ColorInputFont;
992             _fntInputFont = SettingManager.Local.FontInputFont;
993
994             _brsBackColorMine = new SolidBrush(_clSelf);
995             _brsBackColorAt = new SolidBrush(_clAtSelf);
996             _brsBackColorYou = new SolidBrush(_clTarget);
997             _brsBackColorAtYou = new SolidBrush(_clAtTarget);
998             _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
999             _brsBackColorAtTo = new SolidBrush(_clAtTo);
1000             //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
1001             _brsBackColorNone = new SolidBrush(_clListBackcolor);
1002
1003             // StringFormatオブジェクトへの事前設定
1004             //sf.Alignment = StringAlignment.Near;             // Textを近くへ配置(左から右の場合は左寄せ)
1005             //sf.LineAlignment = StringAlignment.Near;         // Textを近くへ配置(上寄せ)
1006             //sf.FormatFlags = StringFormatFlags.LineLimit;    // 
1007             sfTab.Alignment = StringAlignment.Center;
1008             sfTab.LineAlignment = StringAlignment.Center;
1009
1010             InitDetailHtmlFormat();
1011
1012             //Regex statregex = new Regex("^0*");
1013             this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
1014
1015             _history.Add(new StatusTextHistory());
1016             _hisIdx = 0;
1017             this.inReplyTo = null;
1018
1019             //各種ダイアログ設定
1020             SearchDialog.Owner = this;
1021             UrlDialog.Owner = this;
1022
1023             //新着バルーン通知のチェック状態設定
1024             NewPostPopMenuItem.Checked = SettingManager.Common.NewAllPop;
1025             this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
1026
1027             //新着取得時のリストスクロールをするか。trueならスクロールしない
1028             ListLockMenuItem.Checked = SettingManager.Common.ListLock;
1029             this.LockListFileMenuItem.Checked = SettingManager.Common.ListLock;
1030             //サウンド再生(タブ別設定より優先)
1031             this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
1032             this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
1033
1034             //ウィンドウ設定
1035             this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
1036             _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
1037             _myLoc = SettingManager.Local.FormLocation;
1038             //タイトルバー領域
1039             if (this.WindowState != FormWindowState.Minimized)
1040             {
1041                 var tbarRect = new Rectangle(this._myLoc, new Size(_mySize.Width, SystemInformation.CaptionHeight));
1042                 var outOfScreen = true;
1043                 if (Screen.AllScreens.Length == 1)    //ハングするとの報告
1044                 {
1045                     foreach (var scr in Screen.AllScreens)
1046                     {
1047                         if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
1048                         {
1049                             outOfScreen = false;
1050                             break;
1051                         }
1052                     }
1053
1054                     if (outOfScreen)
1055                         this._myLoc = new Point(0, 0);
1056                 }
1057                 this.DesktopLocation = this._myLoc;
1058             }
1059             this.TopMost = SettingManager.Common.AlwaysTop;
1060             _mySpDis = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
1061             _mySpDis2 = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
1062             if (SettingManager.Local.PreviewDistance == -1)
1063             {
1064                 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
1065                 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
1066                 SettingManager.Local.PreviewDistance = _mySpDis3;
1067             }
1068             else
1069             {
1070                 _mySpDis3 = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
1071             }
1072             //this.Tween_ClientSizeChanged(this, null);
1073             this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
1074             this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
1075             //入力欄
1076             StatusText.Font = _fntInputFont;
1077             StatusText.ForeColor = _clInputFont;
1078
1079             // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
1080             this.StatusText.Multiline = false; // SettingManager.Local.StatusMultiline の設定は後で反映される
1081             this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
1082
1083             // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
1084             SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
1085
1086             //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
1087             if (SettingManager.Common.UnreadManage == false)
1088             {
1089                 ReadedStripMenuItem.Enabled = false;
1090                 UnreadStripMenuItem.Enabled = false;
1091             }
1092
1093             //リンク先URL表示部の初期化(画面左下)
1094             StatusLabelUrl.Text = "";
1095             //状態表示部の初期化(画面右下)
1096             StatusLabel.Text = "";
1097             StatusLabel.AutoToolTip = false;
1098             StatusLabel.ToolTipText = "";
1099             //文字カウンタ初期化
1100             lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
1101
1102             this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1103             CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1104             CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1105             CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1106
1107             // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1108             // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1109             // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1110             this.SplitContainer2.Panel2.AccessibleName = "";
1111
1112             ////////////////////////////////////////////////////////////////////////////////
1113             var sortOrder = (SortOrder)SettingManager.Common.SortOrder;
1114             var mode = ComparerMode.Id;
1115             switch (SettingManager.Common.SortColumn)
1116             {
1117                 case 0:    //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1118                 case 5:
1119                 case 6:
1120                     //ソートしない
1121                     mode = ComparerMode.Id;  //Idソートに読み替え
1122                     break;
1123                 case 1:  //ニックネーム
1124                     mode = ComparerMode.Nickname;
1125                     break;
1126                 case 2:  //本文
1127                     mode = ComparerMode.Data;
1128                     break;
1129                 case 3:  //時刻=発言Id
1130                     mode = ComparerMode.Id;
1131                     break;
1132                 case 4:  //名前
1133                     mode = ComparerMode.Name;
1134                     break;
1135                 case 7:  //Source
1136                     mode = ComparerMode.Source;
1137                     break;
1138             }
1139             _statuses.SetSortMode(mode, sortOrder);
1140             ////////////////////////////////////////////////////////////////////////////////
1141
1142             ApplyListViewIconSize(SettingManager.Common.IconSize);
1143
1144             //<<<<<<<<タブ関連>>>>>>>
1145             // タブの位置を調整する
1146             SetTabAlignment();
1147
1148             //デフォルトタブの存在チェック、ない場合には追加
1149             if (this._statuses.GetTabByType<HomeTabModel>() == null)
1150                 this._statuses.AddTab(new HomeTabModel());
1151
1152             if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1153                 this._statuses.AddTab(new MentionsTabModel());
1154
1155             if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1156                 this._statuses.AddTab(new DirectMessagesTabModel());
1157
1158             if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1159                 this._statuses.AddTab(new FavoritesTabModel());
1160
1161             if (this._statuses.MuteTab == null)
1162                 this._statuses.AddTab(new MuteTabModel());
1163
1164             foreach (var tab in _statuses.Tabs)
1165             {
1166                 if (!AddNewTab(tab, startup: true))
1167                     throw new TabException(Properties.Resources.TweenMain_LoadText1);
1168             }
1169
1170             this._statuses.SelectTab(this.ListTab.SelectedTab.Text);
1171
1172             MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
1173             Microsoft.Win32.SystemEvents.TimeChanged += SystemEvents_TimeChanged;
1174
1175             if (SettingManager.Common.TabIconDisp)
1176             {
1177                 ListTab.DrawMode = TabDrawMode.Normal;
1178             }
1179             else
1180             {
1181                 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1182                 ListTab.DrawItem += ListTab_DrawItem;
1183                 ListTab.ImageList = null;
1184             }
1185
1186             if (SettingManager.Common.HotkeyEnabled)
1187             {
1188                 //////グローバルホットキーの登録
1189                 var modKey = HookGlobalHotkey.ModKeys.None;
1190                 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
1191                     modKey |= HookGlobalHotkey.ModKeys.Alt;
1192                 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
1193                     modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1194                 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
1195                     modKey |= HookGlobalHotkey.ModKeys.Shift;
1196                 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
1197                     modKey |= HookGlobalHotkey.ModKeys.Win;
1198
1199                 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
1200             }
1201
1202             if (SettingManager.Common.IsUseNotifyGrowl)
1203                 gh.RegisterGrowl();
1204
1205             StatusLabel.Text = Properties.Resources.Form1_LoadText1;       //画面右下の状態表示を変更
1206
1207             SetMainWindowTitle();
1208             SetNotifyIconText();
1209
1210             if (!SettingManager.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1211             {
1212                 this.Visible = true;
1213             }
1214
1215             //タイマー設定
1216
1217             this.timelineScheduler.UpdateHome = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
1218             this.timelineScheduler.UpdateMention = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
1219             this.timelineScheduler.UpdateDm = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
1220             this.timelineScheduler.UpdatePublicSearch = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
1221             this.timelineScheduler.UpdateUser = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
1222             this.timelineScheduler.UpdateList = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
1223             this.timelineScheduler.UpdateConfig = () => this.InvokeAsync(() => Task.WhenAll(new[]
1224             {
1225                 this.doGetFollowersMenu(),
1226                 this.RefreshBlockIdsAsync(),
1227                 this.RefreshMuteUserIdsAsync(),
1228                 this.RefreshNoRetweetIdsAsync(),
1229                 this.RefreshTwitterConfigurationAsync(),
1230             }));
1231             this.RefreshTimelineScheduler();
1232
1233             var streamingRefreshInterval = TimeSpan.FromSeconds(SettingManager.Common.UserstreamPeriod);
1234             this.RefreshThrottlingTimer = ThrottlingTimer.Throttle(() => this.InvokeAsync(() => this.RefreshTimeline()), streamingRefreshInterval);
1235             this.colorizeDebouncer = ThrottlingTimer.Debounce(() => this.InvokeAsync(() => this.ColorizeList()), TimeSpan.FromMilliseconds(100), leading: true);
1236             this.selectionDebouncer = ThrottlingTimer.Debounce(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
1237             this.saveConfigDebouncer = ThrottlingTimer.Debounce(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
1238
1239             //更新中アイコンアニメーション間隔
1240             TimerRefreshIcon.Interval = 200;
1241             TimerRefreshIcon.Enabled = false;
1242
1243             _ignoreConfigSave = false;
1244             this.TweenMain_Resize(null, null);
1245             if (saveRequired) SaveConfigsAll(false);
1246
1247             foreach (var ua in SettingManager.Common.UserAccounts)
1248             {
1249                 if (ua.UserId == 0 && ua.Username.Equals(tw.Username, StringComparison.InvariantCultureIgnoreCase))
1250                 {
1251                     ua.UserId = tw.UserId;
1252                     break;
1253                 }
1254             }
1255
1256             if (firstRun)
1257             {
1258                 // 初回起動時だけ右下のメニューを目立たせる
1259                 HashStripSplitButton.ShowDropDown();
1260             }
1261         }
1262
1263         private void InitDetailHtmlFormat()
1264         {
1265             if (SettingManager.Common.IsMonospace)
1266             {
1267                 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1268                 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1269             }
1270             else
1271             {
1272                 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1273                 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1274             }
1275
1276             detailHtmlFormatHeader = detailHtmlFormatHeader
1277                     .Replace("%FONT_FAMILY%", _fntDetail.Name)
1278                     .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1279                     .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1280                     .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1281                     .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1282                     .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1283         }
1284
1285         private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1286         {
1287             string txt;
1288             try
1289             {
1290                 txt = this._statuses.Tabs[e.Index].TabName;
1291             }
1292             catch (Exception)
1293             {
1294                 return;
1295             }
1296
1297             e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1298             if (e.State == DrawItemState.Selected)
1299             {
1300                 e.DrawFocusRectangle();
1301             }
1302             Brush fore;
1303             try
1304             {
1305                 if (_statuses.Tabs[txt].UnreadCount > 0)
1306                     fore = Brushes.Red;
1307                 else
1308                     fore = System.Drawing.SystemBrushes.ControlText;
1309             }
1310             catch (Exception)
1311             {
1312                 fore = System.Drawing.SystemBrushes.ControlText;
1313             }
1314             e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1315         }
1316
1317         private void LoadConfig()
1318         {
1319             SettingManager.Local = SettingManager.Local;
1320
1321             // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1322             if (SettingManager.Local.ScaleDimension.IsEmpty)
1323                 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
1324
1325             var tabSettings = SettingManager.Tabs;
1326             foreach (var tabSetting in tabSettings.Tabs)
1327             {
1328                 TabModel tab;
1329                 switch (tabSetting.TabType)
1330                 {
1331                     case MyCommon.TabUsageType.Home:
1332                         tab = new HomeTabModel(tabSetting.TabName);
1333                         break;
1334                     case MyCommon.TabUsageType.Mentions:
1335                         tab = new MentionsTabModel(tabSetting.TabName);
1336                         break;
1337                     case MyCommon.TabUsageType.DirectMessage:
1338                         tab = new DirectMessagesTabModel(tabSetting.TabName);
1339                         break;
1340                     case MyCommon.TabUsageType.Favorites:
1341                         tab = new FavoritesTabModel(tabSetting.TabName);
1342                         break;
1343                     case MyCommon.TabUsageType.UserDefined:
1344                         tab = new FilterTabModel(tabSetting.TabName);
1345                         break;
1346                     case MyCommon.TabUsageType.UserTimeline:
1347                         tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1348                         break;
1349                     case MyCommon.TabUsageType.PublicSearch:
1350                         tab = new PublicSearchTabModel(tabSetting.TabName)
1351                         {
1352                             SearchWords = tabSetting.SearchWords,
1353                             SearchLang = tabSetting.SearchLang,
1354                         };
1355                         break;
1356                     case MyCommon.TabUsageType.Lists:
1357                         tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1358                         break;
1359                     case MyCommon.TabUsageType.Mute:
1360                         tab = new MuteTabModel(tabSetting.TabName);
1361                         break;
1362                     default:
1363                         continue;
1364                 }
1365
1366                 tab.UnreadManage = tabSetting.UnreadManage;
1367                 tab.Protected = tabSetting.Protected;
1368                 tab.Notify = tabSetting.Notify;
1369                 tab.SoundFile = tabSetting.SoundFile;
1370
1371                 if (tab.IsDistributableTabType)
1372                 {
1373                     var filterTab = (FilterTabModel)tab;
1374                     filterTab.FilterArray = tabSetting.FilterArray;
1375                     filterTab.FilterModified = false;
1376                 }
1377
1378                 if (this._statuses.ContainsTab(tab.TabName))
1379                     tab.TabName = this._statuses.MakeTabName("MyTab");
1380
1381                 this._statuses.AddTab(tab);
1382             }
1383             if (_statuses.Tabs.Count == 0)
1384             {
1385                 _statuses.AddTab(new HomeTabModel());
1386                 _statuses.AddTab(new MentionsTabModel());
1387                 _statuses.AddTab(new DirectMessagesTabModel());
1388                 _statuses.AddTab(new FavoritesTabModel());
1389             }
1390         }
1391
1392         private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1393         {
1394             if (e.UserStream)
1395             {
1396                 var interval = TimeSpan.FromSeconds(SettingManager.Common.UserstreamPeriod);
1397                 var newTimer = ThrottlingTimer.Throttle(() => this.InvokeAsync(() => this.RefreshTimeline()), interval);
1398                 var oldTimer = Interlocked.Exchange(ref this.RefreshThrottlingTimer, newTimer);
1399                 oldTimer.Dispose();
1400             }
1401
1402             this.RefreshTimelineScheduler();
1403         }
1404
1405         private void RefreshTimelineScheduler()
1406         {
1407             this.timelineScheduler.UpdateIntervalHome = TimeSpan.FromSeconds(SettingManager.Common.TimelinePeriod);
1408             this.timelineScheduler.UpdateIntervalMention = TimeSpan.FromSeconds(SettingManager.Common.ReplyPeriod);
1409             this.timelineScheduler.UpdateIntervalDm = TimeSpan.FromSeconds(SettingManager.Common.DMPeriod);
1410             this.timelineScheduler.UpdateIntervalPublicSearch = TimeSpan.FromSeconds(SettingManager.Common.PubSearchPeriod);
1411             this.timelineScheduler.UpdateIntervalUser = TimeSpan.FromSeconds(SettingManager.Common.UserTimelinePeriod);
1412             this.timelineScheduler.UpdateIntervalList = TimeSpan.FromSeconds(SettingManager.Common.ListsPeriod);
1413             this.timelineScheduler.UpdateIntervalConfig = TimeSpan.FromHours(6);
1414             this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
1415
1416             this.timelineScheduler.RefreshSchedule();
1417         }
1418
1419         private void MarkSettingCommonModified()
1420         {
1421             if (this.saveConfigDebouncer == null)
1422                 return;
1423
1424             this.ModifySettingCommon = true;
1425             this.saveConfigDebouncer.Call();
1426         }
1427
1428         private void MarkSettingLocalModified()
1429         {
1430             if (this.saveConfigDebouncer == null)
1431                 return;
1432
1433             this.ModifySettingLocal = true;
1434             this.saveConfigDebouncer.Call();
1435         }
1436
1437         internal void MarkSettingAtIdModified()
1438         {
1439             if (this.saveConfigDebouncer == null)
1440                 return;
1441
1442             this.ModifySettingAtId = true;
1443             this.saveConfigDebouncer.Call();
1444         }
1445
1446         private void RefreshTimeline()
1447         {
1448             var curTabModel = this.CurrentTab;
1449             var curListView = this.CurrentListView;
1450
1451             // 現在表示中のタブのスクロール位置を退避
1452             var curListScroll = this.SaveListViewScroll(curListView, curTabModel);
1453
1454             // 各タブのリスト上の選択位置などを退避
1455             var listSelections = this.SaveListViewSelection();
1456
1457             //更新確定
1458             int addCount;
1459             addCount = _statuses.SubmitUpdate(out var soundFile, out var notifyPosts,
1460                 out var newMentionOrDm, out var isDelete);
1461
1462             if (MyCommon._endingFlag) return;
1463
1464             // リストに反映&選択状態復元
1465             foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1466             {
1467                 var tabPage = this.ListTab.TabPages[index];
1468                 var listView = (DetailsListView)tabPage.Tag;
1469
1470                 if (listView.VirtualListSize != tab.AllCount || isDelete)
1471                 {
1472                     using (ControlTransaction.Update(listView))
1473                     {
1474                         if (listView == curListView)
1475                             this.PurgeListViewItemCache();
1476
1477                         try
1478                         {
1479                             // リスト件数更新
1480                             listView.VirtualListSize = tab.AllCount;
1481                         }
1482                         catch (NullReferenceException ex)
1483                         {
1484                             // WinForms 内部で ListView.set_TopItem が発生させている例外
1485                             // https://ja.osdn.net/ticket/browse.php?group_id=6526&tid=36588
1486                             MyCommon.TraceOut(ex, $"TabType: {tab.TabType}, Count: {tab.AllCount}, ListSize: {listView.VirtualListSize}");
1487                         }
1488
1489                         // 選択位置などを復元
1490                         this.RestoreListViewSelection(listView, tab, listSelections[tab.TabName]);
1491                     }
1492                 }
1493             }
1494
1495             if (addCount > 0)
1496             {
1497                 if (SettingManager.Common.TabIconDisp)
1498                 {
1499                     foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1500                     {
1501                         var tabPage = this.ListTab.TabPages[index];
1502                         if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
1503                             tabPage.ImageIndex = 0; // 未読アイコン
1504                     }
1505                 }
1506                 else
1507                 {
1508                     this.ListTab.Refresh();
1509                 }
1510             }
1511
1512             // スクロール位置を復元
1513             this.RestoreListViewScroll(curListView, curTabModel, curListScroll);
1514
1515             //新着通知
1516             NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1517
1518             SetMainWindowTitle();
1519             if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1520
1521             HashSupl.AddRangeItem(tw.GetHashList());
1522
1523         }
1524
1525         internal struct ListViewScroll
1526         {
1527             public ScrollLockMode ScrollLockMode { get; set; }
1528             public long? TopItemStatusId { get; set; }
1529         }
1530
1531         internal enum ScrollLockMode
1532         {
1533             /// <summary>固定しない</summary>
1534             None,
1535
1536             /// <summary>最上部に固定する</summary>
1537             FixedToTop,
1538
1539             /// <summary>最下部に固定する</summary>
1540             FixedToBottom,
1541
1542             /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1543             FixedToItem,
1544         }
1545
1546         /// <summary>
1547         /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1548         /// </summary>
1549         private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1550         {
1551             var listScroll = new ListViewScroll
1552             {
1553                 ScrollLockMode = this.GetScrollLockMode(listView),
1554             };
1555
1556             if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1557             {
1558                 var topItemIndex = listView.TopItem?.Index ?? -1;
1559                 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
1560                     listScroll.TopItemStatusId = tab.GetStatusIdAt(topItemIndex);
1561             }
1562
1563             return listScroll;
1564         }
1565
1566         private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1567         {
1568             if (this._statuses.SortMode == ComparerMode.Id)
1569             {
1570                 if (this._statuses.SortOrder == SortOrder.Ascending)
1571                 {
1572                     // Id昇順
1573                     if (this.ListLockMenuItem.Checked)
1574                         return ScrollLockMode.None;
1575
1576                     // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1577
1578                     // 一番下に表示されているアイテム
1579                     var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1580                     if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1581                         return ScrollLockMode.FixedToBottom;
1582                     else
1583                         return ScrollLockMode.None;
1584                 }
1585                 else
1586                 {
1587                     // Id降順
1588                     if (this.ListLockMenuItem.Checked)
1589                         return ScrollLockMode.FixedToItem;
1590
1591                     // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1592                     var topItem = listView.TopItem;
1593                     if (topItem == null || topItem.Index == 0)
1594                         return ScrollLockMode.FixedToTop;
1595                     else
1596                         return ScrollLockMode.FixedToItem;
1597                 }
1598             }
1599             else
1600             {
1601                 return ScrollLockMode.FixedToItem;
1602             }
1603         }
1604
1605         internal struct ListViewSelection
1606         {
1607             public long[] SelectedStatusIds { get; set; }
1608             public long? SelectionMarkStatusId { get; set; }
1609             public long? FocusedStatusId { get; set; }
1610         }
1611
1612         /// <summary>
1613         /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1614         /// </summary>
1615         private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1616         {
1617             var listsDict = new Dictionary<string, ListViewSelection>();
1618
1619             foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1620             {
1621                 var listView = (DetailsListView)this.ListTab.TabPages[index].Tag;
1622                 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1623             }
1624
1625             return listsDict;
1626         }
1627
1628         /// <summary>
1629         /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1630         /// </summary>
1631         private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1632         {
1633             if (listView.VirtualListSize == 0)
1634             {
1635                 return new ListViewSelection
1636                 {
1637                     SelectedStatusIds = Array.Empty<long>(),
1638                     SelectionMarkStatusId = null,
1639                     FocusedStatusId = null,
1640                 };
1641             }
1642
1643             return new ListViewSelection
1644             {
1645                 SelectedStatusIds = tab.SelectedStatusIds,
1646                 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1647                 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1648             };
1649         }
1650
1651         private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1652         {
1653             var index = listView.FocusedItem?.Index ?? -1;
1654
1655             return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1656         }
1657
1658         private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1659         {
1660             var index = listView.SelectionMark;
1661
1662             return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1663         }
1664
1665         /// <summary>
1666         /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1667         /// </summary>
1668         private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1669         {
1670             if (listView.VirtualListSize == 0)
1671                 return;
1672
1673             switch (listScroll.ScrollLockMode)
1674             {
1675                 case ScrollLockMode.FixedToTop:
1676                     listView.EnsureVisible(0);
1677                     break;
1678                 case ScrollLockMode.FixedToBottom:
1679                     listView.EnsureVisible(listView.VirtualListSize - 1);
1680                     break;
1681                 case ScrollLockMode.FixedToItem:
1682                     var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1683                     if (topIndex != -1)
1684                     {
1685                         var topItem = listView.Items[topIndex];
1686                         try
1687                         {
1688                             listView.TopItem = topItem;
1689                         }
1690                         catch (NullReferenceException)
1691                         {
1692                             listView.EnsureVisible(listView.VirtualListSize - 1);
1693                             listView.EnsureVisible(topIndex);
1694                         }
1695                     }
1696                     break;
1697                 case ScrollLockMode.None:
1698                 default:
1699                     break;
1700             }
1701         }
1702
1703         /// <summary>
1704         /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1705         /// </summary>
1706         private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1707         {
1708             // status_id から ListView 上のインデックスに変換
1709             int[] selectedIndices = null;
1710             if (listSelection.SelectedStatusIds != null)
1711                 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1712
1713             var focusedIndex = -1;
1714             if (listSelection.FocusedStatusId != null)
1715                 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1716
1717             var selectionMarkIndex = -1;
1718             if (listSelection.SelectionMarkStatusId != null)
1719                 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1720
1721             this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1722         }
1723
1724         private bool BalloonRequired()
1725         {
1726             var ev = new Twitter.FormattedEvent
1727             {
1728                 Eventtype = MyCommon.EVENTTYPE.None,
1729             };
1730
1731             return BalloonRequired(ev);
1732         }
1733
1734         private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1735         {
1736             if (type == MyCommon.EVENTTYPE.None)
1737                 return true;
1738
1739             if (!SettingManager.Common.EventNotifyEnabled)
1740                 return false;
1741
1742             return SettingManager.Common.EventNotifyFlag.HasFlag(type);
1743         }
1744
1745         private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1746         {
1747             if (!ev.IsMe)
1748                 return true;
1749
1750             return SettingManager.Common.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1751         }
1752
1753         private bool BalloonRequired(Twitter.FormattedEvent ev)
1754         {
1755             if (this._initial)
1756                 return false;
1757
1758             if (NativeMethods.IsScreenSaverRunning())
1759                 return false;
1760
1761             // 「新着通知」が無効
1762             if (!this.NewPostPopMenuItem.Checked)
1763             {
1764                 // 「新着通知が無効でもイベントを通知する」にも該当しない
1765                 if (!SettingManager.Common.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1766                     return false;
1767             }
1768
1769             // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1770             if (SettingManager.Common.LimitBalloon)
1771             {
1772                 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1773                     return false;
1774             }
1775
1776             return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1777         }
1778
1779         private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1780         {
1781             if (SettingManager.Common.ReadOwnPost)
1782             {
1783                 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1784                     return;
1785             }
1786
1787             //新着通知
1788             if (BalloonRequired())
1789             {
1790                 if (notifyPosts != null && notifyPosts.Length > 0)
1791                 {
1792                     //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1793                     if (SettingManager.Common.IsUseNotifyGrowl)
1794                     {
1795                         var sb = new StringBuilder();
1796                         var reply = false;
1797                         var dm = false;
1798
1799                         foreach (var post in notifyPosts)
1800                         {
1801                             if (!(notifyPosts.Length > 3))
1802                             {
1803                                 sb.Clear();
1804                                 reply = false;
1805                                 dm = false;
1806                             }
1807                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1808                             if (post.IsDm) dm = true;
1809                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1810                             switch (SettingManager.Common.NameBalloon)
1811                             {
1812                                 case MyCommon.NameBalloonEnum.UserID:
1813                                     sb.Append(post.ScreenName).Append(" : ");
1814                                     break;
1815                                 case MyCommon.NameBalloonEnum.NickName:
1816                                     sb.Append(post.Nickname).Append(" : ");
1817                                     break;
1818                             }
1819                             sb.Append(post.TextFromApi);
1820                             if (notifyPosts.Length > 3)
1821                             {
1822                                 if (notifyPosts.Last() != post) continue;
1823                             }
1824
1825                             var title = new StringBuilder();
1826                             GrowlHelper.NotifyType nt;
1827                             if (SettingManager.Common.DispUsername)
1828                             {
1829                                 title.Append(tw.Username);
1830                                 title.Append(" - ");
1831                             }
1832                             else
1833                             {
1834                                 //title.Clear();
1835                             }
1836                             if (dm)
1837                             {
1838                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1839                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1840                                 title.Append(ApplicationSettings.ApplicationName);
1841                                 title.Append(" [DM] ");
1842                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1843                                 nt = GrowlHelper.NotifyType.DirectMessage;
1844                             }
1845                             else if (reply)
1846                             {
1847                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1848                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1849                                 title.Append(ApplicationSettings.ApplicationName);
1850                                 title.Append(" [Reply!] ");
1851                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1852                                 nt = GrowlHelper.NotifyType.Reply;
1853                             }
1854                             else
1855                             {
1856                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1857                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1858                                 title.Append(ApplicationSettings.ApplicationName);
1859                                 title.Append(" ");
1860                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1861                                 nt = GrowlHelper.NotifyType.Notify;
1862                             }
1863                             var bText = sb.ToString();
1864                             if (string.IsNullOrEmpty(bText)) return;
1865
1866                             var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1867                             gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image?.Image, post.ImageUrl);
1868                         }
1869                     }
1870                     else
1871                     {
1872                         var sb = new StringBuilder();
1873                         var reply = false;
1874                         var dm = false;
1875                         foreach (var post in notifyPosts)
1876                         {
1877                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1878                             if (post.IsDm) dm = true;
1879                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1880                             switch (SettingManager.Common.NameBalloon)
1881                             {
1882                                 case MyCommon.NameBalloonEnum.UserID:
1883                                     sb.Append(post.ScreenName).Append(" : ");
1884                                     break;
1885                                 case MyCommon.NameBalloonEnum.NickName:
1886                                     sb.Append(post.Nickname).Append(" : ");
1887                                     break;
1888                             }
1889                             sb.Append(post.TextFromApi);
1890
1891                         }
1892                         //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1893                         var title = new StringBuilder();
1894                         ToolTipIcon ntIcon;
1895                         if (SettingManager.Common.DispUsername)
1896                         {
1897                             title.Append(tw.Username);
1898                             title.Append(" - ");
1899                         }
1900                         else
1901                         {
1902                             //title.Clear();
1903                         }
1904                         if (dm)
1905                         {
1906                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1907                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1908                             ntIcon = ToolTipIcon.Warning;
1909                             title.Append(ApplicationSettings.ApplicationName);
1910                             title.Append(" [DM] ");
1911                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1912                         }
1913                         else if (reply)
1914                         {
1915                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1916                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1917                             ntIcon = ToolTipIcon.Warning;
1918                             title.Append(ApplicationSettings.ApplicationName);
1919                             title.Append(" [Reply!] ");
1920                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1921                         }
1922                         else
1923                         {
1924                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1925                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1926                             ntIcon = ToolTipIcon.Info;
1927                             title.Append(ApplicationSettings.ApplicationName);
1928                             title.Append(" ");
1929                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1930                         }
1931                         var bText = sb.ToString();
1932                         if (string.IsNullOrEmpty(bText)) return;
1933                         //NotifyIcon1.BalloonTipText = sb.ToString();
1934                         //NotifyIcon1.ShowBalloonTip(500);
1935                         NotifyIcon1.BalloonTipTitle = title.ToString();
1936                         NotifyIcon1.BalloonTipText = bText;
1937                         NotifyIcon1.BalloonTipIcon = ntIcon;
1938                         NotifyIcon1.ShowBalloonTip(500);
1939                     }
1940                 }
1941             }
1942
1943             //サウンド再生
1944             if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(soundFile))
1945             {
1946                 try
1947                 {
1948                     var dir = Application.StartupPath;
1949                     if (Directory.Exists(Path.Combine(dir, "Sounds")))
1950                     {
1951                         dir = Path.Combine(dir, "Sounds");
1952                     }
1953                     using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1954                     player.Play();
1955                 }
1956                 catch (Exception)
1957                 {
1958                 }
1959             }
1960
1961             //mentions新着時に画面ブリンク
1962             if (!_initial && SettingManager.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1963             {
1964                 NativeMethods.FlashMyWindow(this.Handle, 3);
1965             }
1966         }
1967
1968         private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1969         {
1970             var listView = this.CurrentListView;
1971             if (listView != sender)
1972                 return;
1973
1974             var indices = listView.SelectedIndices.Cast<int>().ToArray();
1975             this.CurrentTab.SelectPosts(indices);
1976
1977             if (listView.SelectedIndices.Count != 1)
1978                 return;
1979
1980             var index = listView.SelectedIndices[0];
1981             if (index > listView.VirtualListSize - 1) return;
1982
1983             this.PushSelectPostChain();
1984
1985             var post = this.CurrentPost;
1986             this._statuses.SetReadAllTab(post.StatusId, read: true);
1987
1988             //キャッシュの書き換え
1989             ChangeCacheStyleRead(true, index); // 既読へ(フォント、文字色)
1990
1991             this.colorizeDebouncer.Call();
1992             this.selectionDebouncer.Call();
1993         }
1994
1995         private void ChangeCacheStyleRead(bool Read, int Index)
1996         {
1997             var tabInfo = this.CurrentTab;
1998             //Read:true=既読 false=未読
1999             //未読管理していなかったら既読として扱う
2000             if (!tabInfo.UnreadManage ||
2001                !SettingManager.Common.UnreadManage) Read = true;
2002
2003             var listCache = this._listItemCache;
2004             if (listCache == null)
2005                 return;
2006
2007             // キャッシュに含まれていないアイテムは対象外
2008             if (!listCache.TryGetValue(Index, out var itm, out var post))
2009                 return;
2010
2011             ChangeItemStyleRead(Read, itm, post, (DetailsListView)listCache.TargetList);
2012         }
2013
2014         private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
2015         {
2016             Font fnt;
2017             string star;
2018             //フォント
2019             if (Read)
2020             {
2021                 fnt = _fntReaded;
2022                 star = "";
2023             }
2024             else
2025             {
2026                 fnt = _fntUnread;
2027                 star = "★";
2028             }
2029             if (Item.SubItems[5].Text != star)
2030                 Item.SubItems[5].Text = star;
2031
2032             //文字色
2033             Color cl;
2034             if (Post.IsFav)
2035                 cl = _clFav;
2036             else if (Post.RetweetedId != null)
2037                 cl = _clRetweet;
2038             else if (Post.IsOwl && (Post.IsDm || SettingManager.Common.OneWayLove))
2039                 cl = _clOWL;
2040             else if (Read || !SettingManager.Common.UseUnreadStyle)
2041                 cl = _clReaded;
2042             else
2043                 cl = _clUnread;
2044
2045             if (DList == null || Item.Index == -1)
2046             {
2047                 Item.ForeColor = cl;
2048                 if (SettingManager.Common.UseUnreadStyle)
2049                     Item.Font = fnt;
2050             }
2051             else
2052             {
2053                 DList.Update();
2054                 if (SettingManager.Common.UseUnreadStyle)
2055                     DList.ChangeItemFontAndColor(Item, cl, fnt);
2056                 else
2057                     DList.ChangeItemForeColor(Item, cl);
2058                 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2059             }
2060         }
2061
2062         private void ColorizeList()
2063         {
2064             //Index:更新対象のListviewItem.Index。Colorを返す。
2065             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2066             PostClass _post;
2067             if (_anchorFlag)
2068                 _post = _anchorPost;
2069             else
2070                 _post = this.CurrentPost;
2071
2072             if (_post == null) return;
2073
2074             var listCache = this._listItemCache;
2075             if (listCache == null)
2076                 return;
2077
2078             var listView = (DetailsListView)listCache.TargetList;
2079
2080             // ValidateRectが呼ばれる前に選択色などの描画を済ませておく
2081             listView.Update();
2082
2083             foreach (var (listViewItem, cachedPost) in listCache.Cache)
2084             {
2085                 var backColor = this.JudgeColor(_post, cachedPost);
2086                 listView.ChangeItemBackColor(listViewItem, backColor);
2087             }
2088         }
2089
2090         private void ColorizeList(ListViewItem Item, PostClass post)
2091         {
2092             //Index:更新対象のListviewItem.Index。Colorを返す。
2093             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2094             PostClass _post;
2095             if (_anchorFlag)
2096                 _post = _anchorPost;
2097             else
2098                 _post = this.CurrentPost;
2099
2100             if (_post == null) return;
2101
2102             if (Item.Index == -1)
2103                 Item.BackColor = JudgeColor(_post, post);
2104             else
2105                 this.CurrentListView.ChangeItemBackColor(Item, JudgeColor(_post, post));
2106         }
2107
2108         private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2109         {
2110             Color cl;
2111             if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2112                 //@先
2113                 cl = _clAtTo;
2114             else if (TargetPost.IsMe)
2115                 //自分=発言者
2116                 cl = _clSelf;
2117             else if (TargetPost.IsReply)
2118                 //自分宛返信
2119                 cl = _clAtSelf;
2120             else if (BasePost.ReplyToList.Any(x => x.UserId == TargetPost.UserId))
2121                 //返信先
2122                 cl = _clAtFromTarget;
2123             else if (TargetPost.ReplyToList.Any(x => x.UserId == BasePost.UserId))
2124                 //その人への返信
2125                 cl = _clAtTarget;
2126             else if (TargetPost.UserId == BasePost.UserId)
2127                 //発言者
2128                 cl = _clTarget;
2129             else
2130                 //その他
2131                 cl = _clListBackcolor;
2132
2133             return cl;
2134         }
2135
2136         private void StatusTextHistoryBack()
2137         {
2138             if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
2139                 this._history[_hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
2140
2141             this._hisIdx -= 1;
2142             if (this._hisIdx < 0)
2143                 this._hisIdx = 0;
2144
2145             var historyItem = this._history[this._hisIdx];
2146             this.inReplyTo = historyItem.inReplyTo;
2147             this.StatusText.Text = historyItem.status;
2148             this.StatusText.SelectionStart = this.StatusText.Text.Length;
2149         }
2150
2151         private void StatusTextHistoryForward()
2152         {
2153             if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
2154                 this._history[this._hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
2155
2156             this._hisIdx += 1;
2157             if (this._hisIdx > this._history.Count - 1)
2158                 this._hisIdx = this._history.Count - 1;
2159
2160             var historyItem = this._history[this._hisIdx];
2161             this.inReplyTo = historyItem.inReplyTo;
2162             this.StatusText.Text = historyItem.status;
2163             this.StatusText.SelectionStart = this.StatusText.Text.Length;
2164         }
2165
2166         private async void PostButton_Click(object sender, EventArgs e)
2167         {
2168             if (StatusText.Text.Trim().Length == 0)
2169             {
2170                 if (!ImageSelector.Enabled)
2171                 {
2172                     await this.DoRefresh();
2173                     return;
2174                 }
2175             }
2176
2177             var currentPost = this.CurrentPost;
2178             if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
2179             {
2180                 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2181                                                                "Retweet",
2182                                                                MessageBoxButtons.YesNoCancel,
2183                                                                MessageBoxIcon.Question);
2184                 switch (rtResult)
2185                 {
2186                     case DialogResult.Yes:
2187                         StatusText.Text = "";
2188                         await this.doReTweetOfficial(false);
2189                         return;
2190                     case DialogResult.Cancel:
2191                         return;
2192                 }
2193             }
2194
2195             if (TextContainsOnlyMentions(this.StatusText.Text))
2196             {
2197                 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
2198                 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
2199
2200                 if (ret != DialogResult.OK)
2201                     return;
2202             }
2203
2204             _history[_history.Count - 1] = new StatusTextHistory(StatusText.Text, this.inReplyTo);
2205
2206             if (SettingManager.Common.Nicoms)
2207             {
2208                 StatusText.SelectionStart = StatusText.Text.Length;
2209                 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2210             }
2211             //if (SettingDialog.UrlConvertAuto)
2212             //{
2213             //    StatusText.SelectionStart = StatusText.Text.Length;
2214             //    UrlConvertAutoToolStripMenuItem_Click(null, null);
2215             //}
2216             //else if (SettingDialog.Nicoms)
2217             //{
2218             //    StatusText.SelectionStart = StatusText.Text.Length;
2219             //    UrlConvert(UrlConverter.Nicoms);
2220             //}
2221             StatusText.SelectionStart = StatusText.Text.Length;
2222             CheckReplyTo(StatusText.Text);
2223
2224             var status = new PostStatusParams();
2225
2226             var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
2227             if (this.GetRestStatusCount(statusTextCompat) >= 0)
2228             {
2229                 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
2230                 // 収まる場合はこれらのオプションを使用せずに投稿する
2231                 status.Text = statusTextCompat;
2232                 status.InReplyToStatusId = this.inReplyTo?.StatusId;
2233             }
2234             else
2235             {
2236                 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
2237                 status.InReplyToStatusId = this.inReplyTo?.StatusId;
2238
2239                 status.AttachmentUrl = attachmentUrl;
2240
2241                 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
2242                 //  (非公式 RT の場合など)
2243                 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Value.StatusId] : null;
2244                 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
2245                 {
2246                     status.AutoPopulateReplyMetadata = true;
2247
2248                     // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
2249                     status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
2250                         .ToArray();
2251                 }
2252             }
2253
2254             if (this.GetRestStatusCount(status.Text) < 0)
2255             {
2256                 // 文字数制限を超えているが強制的に投稿するか
2257                 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2258                 if (ret != DialogResult.OK)
2259                     return;
2260             }
2261
2262             IMediaUploadService uploadService = null;
2263             IMediaItem[] uploadItems = null;
2264             if (ImageSelector.Visible)
2265             {
2266                 //画像投稿
2267                 if (!ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
2268                     return;
2269
2270                 uploadService = this.ImageSelector.GetService(serviceName);
2271             }
2272
2273             this.inReplyTo = null;
2274             StatusText.Text = "";
2275             _history.Add(new StatusTextHistory());
2276             _hisIdx = _history.Count - 1;
2277             if (!SettingManager.Common.FocusLockToStatusText)
2278                 this.CurrentListView.Focus();
2279             urlUndoBuffer = null;
2280             UrlUndoToolStripMenuItem.Enabled = false;  //Undoをできないように設定
2281
2282             //Google検索(試験実装)
2283             if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2284             {
2285                 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2286                 await this.OpenUriInBrowserAsync(tmp);
2287             }
2288
2289             await this.PostMessageAsync(status, uploadService, uploadItems);
2290         }
2291
2292         private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2293         {
2294             MyCommon._endingFlag = true;
2295             this.Close();
2296         }
2297
2298         private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2299         {
2300             if (!SettingManager.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2301             {
2302                 //_endingFlag=false:フォームの×ボタン
2303                 e.Cancel = true;
2304                 this.Visible = false;
2305             }
2306             else
2307             {
2308                 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2309                 _ignoreConfigSave = true;
2310                 MyCommon._endingFlag = true;
2311                 this.timelineScheduler.Enabled = false;
2312                 TimerRefreshIcon.Enabled = false;
2313             }
2314         }
2315
2316         private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2317         {
2318             this.Visible = true;
2319             if (this.WindowState == FormWindowState.Minimized)
2320             {
2321                 this.WindowState = FormWindowState.Normal;
2322             }
2323             this.Activate();
2324             this.BringToFront();
2325         }
2326
2327         private static int errorCount = 0;
2328
2329         private static bool CheckAccountValid()
2330         {
2331             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2332             {
2333                 errorCount += 1;
2334                 if (errorCount > 5)
2335                 {
2336                     errorCount = 0;
2337                     Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2338                     return true;
2339                 }
2340                 return false;
2341             }
2342             errorCount = 0;
2343             return true;
2344         }
2345
2346         /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
2347         private Task RefreshTabAsync<T>() where T : TabModel
2348             => this.RefreshTabAsync<T>(backward: false);
2349
2350         /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
2351         private Task RefreshTabAsync<T>(bool backward) where T : TabModel
2352         {
2353             var loadTasks =
2354                 from tab in this._statuses.GetTabsByType<T>()
2355                 select this.RefreshTabAsync(tab, backward);
2356
2357             return Task.WhenAll(loadTasks);
2358         }
2359
2360         /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
2361         private Task RefreshTabAsync(TabModel tab)
2362             => this.RefreshTabAsync(tab, backward: false);
2363
2364         /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
2365         private async Task RefreshTabAsync(TabModel tab, bool backward)
2366         {
2367             await this.workerSemaphore.WaitAsync();
2368             this.RefreshTasktrayIcon();
2369
2370             try
2371             {
2372                 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this._initial, this.workerProgress));
2373                 this.RefreshTimeline();
2374             }
2375             catch (WebApiException ex)
2376             {
2377                 this._myStatusError = true;
2378
2379                 string tabType;
2380                 switch (tab)
2381                 {
2382                     case HomeTabModel _:
2383                         tabType = "GetTimeline";
2384                         break;
2385                     case MentionsTabModel _:
2386                         tabType = "GetTimeline";
2387                         break;
2388                     case DirectMessagesTabModel _:
2389                         tabType = "GetDirectMessage";
2390                         break;
2391                     case FavoritesTabModel _:
2392                         tabType = "GetFavorites";
2393                         break;
2394                     case PublicSearchTabModel _:
2395                         tabType = "GetSearch";
2396                         break;
2397                     case UserTimelineTabModel _:
2398                         tabType = "GetUserTimeline";
2399                         break;
2400                     case ListTimelineTabModel _:
2401                         tabType = "GetListStatus";
2402                         break;
2403                     case RelatedPostsTabModel _:
2404                         tabType = "GetRelatedTweets";
2405                         break;
2406                     default:
2407                         tabType = tab.GetType().Name.Replace("Model", "");
2408                         break;
2409                 }
2410
2411                 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
2412             }
2413             finally
2414             {
2415                 this.workerSemaphore.Release();
2416             }
2417         }
2418
2419         private async Task FavAddAsync(long statusId, TabModel tab)
2420         {
2421             await this.workerSemaphore.WaitAsync();
2422             this.RefreshTasktrayIcon();
2423
2424             try
2425             {
2426                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2427
2428                 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2429             }
2430             catch (WebApiException ex)
2431             {
2432                 this._myStatusError = true;
2433                 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2434             }
2435             finally
2436             {
2437                 this.workerSemaphore.Release();
2438             }
2439         }
2440
2441         private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2442         {
2443             if (ct.IsCancellationRequested)
2444                 return;
2445
2446             if (!CheckAccountValid())
2447                 throw new WebApiException("Auth error. Check your account");
2448
2449             if (!tab.Posts.TryGetValue(statusId, out var post))
2450                 return;
2451
2452             if (post.IsFav)
2453                 return;
2454
2455             await Task.Run(async () =>
2456             {
2457                 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2458
2459                 try
2460                 {
2461                     try
2462                     {
2463                         await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2464                             .IgnoreResponse()
2465                             .ConfigureAwait(false);
2466                     }
2467                     catch (TwitterApiException ex)
2468                         when (ex.ErrorResponse.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
2469                     {
2470                         // エラーコード 139 のみの場合は成功と見なす
2471                     }
2472
2473                     if (SettingManager.Common.RestrictFavCheck)
2474                     {
2475                         var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2476                             .ConfigureAwait(false);
2477
2478                         if (status.Favorited != true)
2479                             throw new WebApiException("NG(Restricted?)");
2480                     }
2481
2482                     this._favTimestamps.Add(DateTimeUtc.Now);
2483
2484                     // TLでも取得済みならfav反映
2485                     if (this._statuses.ContainsKey(statusId))
2486                     {
2487                         var postTl = this._statuses[statusId];
2488                         postTl.IsFav = true;
2489
2490                         var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2491                         favTab.AddPostQueue(postTl);
2492                     }
2493
2494                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
2495                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
2496                     {
2497                         if (tb.Contains(statusId))
2498                             tb.Posts[statusId].IsFav = true;
2499                     }
2500
2501                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2502                 }
2503                 catch (WebApiException)
2504                 {
2505                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2506                     throw;
2507                 }
2508
2509                 // 時速表示用
2510                 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2511                 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2512                 {
2513                     if (this._favTimestamps[i] < oneHour)
2514                         this._favTimestamps.RemoveAt(i);
2515                 }
2516
2517                 this._statuses.DistributePosts();
2518             });
2519
2520             if (ct.IsCancellationRequested)
2521                 return;
2522
2523             this.RefreshTimeline();
2524
2525             if (this.CurrentTabName == tab.TabName)
2526             {
2527                 using (ControlTransaction.Update(this.CurrentListView))
2528                 {
2529                     var idx = tab.IndexOf(statusId);
2530                     if (idx != -1)
2531                         this.ChangeCacheStyleRead(post.IsRead, idx);
2532                 }
2533
2534                 var currentPost = this.CurrentPost;
2535                 if (currentPost != null && statusId == currentPost.StatusId)
2536                     this.DispSelectedPost(true); // 選択アイテム再表示
2537             }
2538         }
2539
2540         private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2541         {
2542             await this.workerSemaphore.WaitAsync();
2543             this.RefreshTasktrayIcon();
2544
2545             try
2546             {
2547                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2548
2549                 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2550             }
2551             catch (WebApiException ex)
2552             {
2553                 this._myStatusError = true;
2554                 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2555             }
2556             finally
2557             {
2558                 this.workerSemaphore.Release();
2559             }
2560         }
2561
2562         private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2563         {
2564             if (ct.IsCancellationRequested)
2565                 return;
2566
2567             if (!CheckAccountValid())
2568                 throw new WebApiException("Auth error. Check your account");
2569
2570             var successIds = new List<long>();
2571
2572             await Task.Run(async () =>
2573             {
2574                 //スレッド処理はしない
2575                 var allCount = 0;
2576                 var failedCount = 0;
2577                 foreach (var statusId in statusIds)
2578                 {
2579                     allCount++;
2580
2581                     var post = tab.Posts[statusId];
2582
2583                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2584
2585                     if (!post.IsFav)
2586                         continue;
2587
2588                     try
2589                     {
2590                         await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2591                             .IgnoreResponse()
2592                             .ConfigureAwait(false);
2593                     }
2594                     catch (WebApiException)
2595                     {
2596                         failedCount++;
2597                         continue;
2598                     }
2599
2600                     successIds.Add(statusId);
2601                     post.IsFav = false; // リスト再描画必要
2602
2603                     if (this._statuses.ContainsKey(statusId))
2604                     {
2605                         this._statuses[statusId].IsFav = false;
2606                     }
2607
2608                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
2609                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
2610                     {
2611                         if (tb.Contains(statusId))
2612                             tb.Posts[statusId].IsFav = false;
2613                     }
2614                 }
2615             });
2616
2617             if (ct.IsCancellationRequested)
2618                 return;
2619
2620             var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2621             foreach (var statusId in successIds)
2622             {
2623                 // ツイートが削除された訳ではないので IsDeleted はセットしない
2624                 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2625             }
2626
2627             this.RefreshTimeline();
2628
2629             if (this.CurrentTabName == tab.TabName)
2630             {
2631                 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2632                 {
2633                     // 色変えは不要
2634                 }
2635                 else
2636                 {
2637                     using (ControlTransaction.Update(this.CurrentListView))
2638                     {
2639                         foreach (var statusId in successIds)
2640                         {
2641                             var idx = tab.IndexOf(statusId);
2642                             if (idx == -1)
2643                                 continue;
2644
2645                             var post = tab.Posts[statusId];
2646                             this.ChangeCacheStyleRead(post.IsRead, idx);
2647                         }
2648                     }
2649
2650                     var currentPost = this.CurrentPost;
2651                     if (currentPost != null && successIds.Contains(currentPost.StatusId))
2652                         this.DispSelectedPost(true); // 選択アイテム再表示
2653                 }
2654             }
2655         }
2656
2657         private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService uploadService, IMediaItem[] uploadItems)
2658         {
2659             await this.workerSemaphore.WaitAsync();
2660             this.RefreshTasktrayIcon();
2661
2662             try
2663             {
2664                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2665
2666                 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
2667             }
2668             catch (WebApiException ex)
2669             {
2670                 this._myStatusError = true;
2671                 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2672             }
2673             finally
2674             {
2675                 this.workerSemaphore.Release();
2676             }
2677         }
2678
2679         private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostStatusParams postParams,
2680             IMediaUploadService uploadService, IMediaItem[] uploadItems)
2681         {
2682             if (ct.IsCancellationRequested)
2683                 return;
2684
2685             if (!CheckAccountValid())
2686                 throw new WebApiException("Auth error. Check your account");
2687
2688             p.Report("Posting...");
2689
2690             PostClass post = null;
2691             var errMsg = "";
2692
2693             try
2694             {
2695                 await Task.Run(async () =>
2696                 {
2697                     var postParamsWithMedia = postParams;
2698
2699                     if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
2700                     {
2701                         postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
2702                             .ConfigureAwait(false);
2703                     }
2704
2705                     post = await this.tw.PostStatus(postParamsWithMedia)
2706                         .ConfigureAwait(false);
2707                 });
2708
2709                 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2710             }
2711             catch (WebApiException ex)
2712             {
2713                 // 処理は中断せずエラーの表示のみ行う
2714                 errMsg = $"Err:{ex.Message}(PostMessage)";
2715                 p.Report(errMsg);
2716                 this._myStatusError = true;
2717             }
2718             catch (UnauthorizedAccessException ex)
2719             {
2720                 // アップロード対象のファイルが開けなかった場合など
2721                 errMsg = $"Err:{ex.Message}(PostMessage)";
2722                 p.Report(errMsg);
2723                 this._myStatusError = true;
2724             }
2725             finally
2726             {
2727                 // 使い終わった MediaItem は破棄する
2728                 if (uploadItems != null)
2729                 {
2730                     foreach (var disposableItem in uploadItems.OfType<IDisposable>())
2731                     {
2732                         disposableItem.Dispose();
2733                     }
2734                 }
2735             }
2736
2737             if (ct.IsCancellationRequested)
2738                 return;
2739
2740             if (!string.IsNullOrEmpty(errMsg) &&
2741                 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2742                 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2743             {
2744                 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
2745
2746                 var ret = MessageBox.Show(
2747                     message,
2748                     "Failed to update status",
2749                     MessageBoxButtons.RetryCancel,
2750                     MessageBoxIcon.Question);
2751
2752                 if (ret == DialogResult.Retry)
2753                 {
2754                     await this.PostMessageAsync(postParams, uploadService, uploadItems);
2755                 }
2756                 else
2757                 {
2758                     this.StatusTextHistoryBack();
2759                     this.StatusText.Focus();
2760
2761                     // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2762                     if (SettingManager.Common.FocusLockToStatusText)
2763                         this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2764                 }
2765                 return;
2766             }
2767
2768             this._postTimestamps.Add(DateTimeUtc.Now);
2769
2770             var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2771             foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2772             {
2773                 if (this._postTimestamps[i] < oneHour)
2774                     this._postTimestamps.RemoveAt(i);
2775             }
2776
2777             if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2778             {
2779                 this.HashMgr.ClearHashtag();
2780                 this.HashStripSplitButton.Text = "#[-]";
2781                 this.HashTogglePullDownMenuItem.Checked = false;
2782                 this.HashToggleMenuItem.Checked = false;
2783             }
2784
2785             this.SetMainWindowTitle();
2786
2787             // TLに反映
2788             if (!this.tw.UserStreamActive)
2789             {
2790                 if (SettingManager.Common.PostAndGet)
2791                     await this.RefreshTabAsync<HomeTabModel>();
2792                 else
2793                 {
2794                     if (post != null)
2795                     {
2796                         this._statuses.AddPost(post);
2797                         this._statuses.DistributePosts();
2798                     }
2799                     this.RefreshTimeline();
2800                 }
2801             }
2802         }
2803
2804         private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2805         {
2806             await this.workerSemaphore.WaitAsync();
2807             this.RefreshTasktrayIcon();
2808
2809             try
2810             {
2811                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2812
2813                 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2814             }
2815             catch (WebApiException ex)
2816             {
2817                 this._myStatusError = true;
2818                 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2819             }
2820             finally
2821             {
2822                 this.workerSemaphore.Release();
2823             }
2824         }
2825
2826         private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2827         {
2828             if (ct.IsCancellationRequested)
2829                 return;
2830
2831             if (!CheckAccountValid())
2832                 throw new WebApiException("Auth error. Check your account");
2833
2834             bool read;
2835             if (!SettingManager.Common.UnreadManage)
2836                 read = true;
2837             else
2838                 read = this._initial && SettingManager.Common.Read;
2839
2840             p.Report("Posting...");
2841
2842             var posts = new List<PostClass>();
2843
2844             await Task.Run(async () =>
2845             {
2846                 foreach (var statusId in statusIds)
2847                 {
2848                     var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2849                     if (post != null) posts.Add(post);
2850                 }
2851             });
2852
2853             if (ct.IsCancellationRequested)
2854                 return;
2855
2856             p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2857
2858             this._postTimestamps.Add(DateTimeUtc.Now);
2859
2860             var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2861             foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2862             {
2863                 if (this._postTimestamps[i] < oneHour)
2864                     this._postTimestamps.RemoveAt(i);
2865             }
2866
2867             // TLに反映
2868             if (!this.tw.UserStreamActive)
2869             {
2870                 // 自分のRTはTLの更新では取得できない場合があるので、
2871                 // 投稿時取得の有無に関わらず追加しておく
2872                 posts.ForEach(post => this._statuses.AddPost(post));
2873
2874                 if (SettingManager.Common.PostAndGet)
2875                     await this.RefreshTabAsync<HomeTabModel>();
2876                 else
2877                 {
2878                     this._statuses.DistributePosts();
2879                     this.RefreshTimeline();
2880                 }
2881             }
2882         }
2883
2884         private async Task RefreshFollowerIdsAsync()
2885         {
2886             await this.workerSemaphore.WaitAsync();
2887             this.RefreshTasktrayIcon();
2888
2889             try
2890             {
2891                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2892
2893                 await this.tw.RefreshFollowerIds();
2894
2895                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2896
2897                 this.RefreshTimeline();
2898                 this.PurgeListViewItemCache();
2899                 this.CurrentListView.Refresh();
2900             }
2901             catch (WebApiException ex)
2902             {
2903                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2904             }
2905             finally
2906             {
2907                 this.workerSemaphore.Release();
2908             }
2909         }
2910
2911         private async Task RefreshNoRetweetIdsAsync()
2912         {
2913             await this.workerSemaphore.WaitAsync();
2914             this.RefreshTasktrayIcon();
2915
2916             try
2917             {
2918                 await this.tw.RefreshNoRetweetIds();
2919
2920                 this.StatusLabel.Text = "NoRetweetIds refreshed";
2921             }
2922             catch (WebApiException ex)
2923             {
2924                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2925             }
2926             finally
2927             {
2928                 this.workerSemaphore.Release();
2929             }
2930         }
2931
2932         private async Task RefreshBlockIdsAsync()
2933         {
2934             await this.workerSemaphore.WaitAsync();
2935             this.RefreshTasktrayIcon();
2936
2937             try
2938             {
2939                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2940
2941                 await this.tw.RefreshBlockIds();
2942
2943                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2944             }
2945             catch (WebApiException ex)
2946             {
2947                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2948             }
2949             finally
2950             {
2951                 this.workerSemaphore.Release();
2952             }
2953         }
2954
2955         private async Task RefreshTwitterConfigurationAsync()
2956         {
2957             await this.workerSemaphore.WaitAsync();
2958             this.RefreshTasktrayIcon();
2959
2960             try
2961             {
2962                 await this.tw.RefreshConfiguration();
2963
2964                 if (this.tw.Configuration.PhotoSizeLimit != 0)
2965                 {
2966                     foreach (var service in this.ImageSelector.GetServices())
2967                     {
2968                         service.UpdateTwitterConfiguration(this.tw.Configuration);
2969                     }
2970                 }
2971
2972                 this.PurgeListViewItemCache();
2973                 this.CurrentListView.Refresh();
2974             }
2975             catch (WebApiException ex)
2976             {
2977                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2978             }
2979             finally
2980             {
2981                 this.workerSemaphore.Release();
2982             }
2983         }
2984
2985         private async Task RefreshMuteUserIdsAsync()
2986         {
2987             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
2988
2989             try
2990             {
2991                 await tw.RefreshMuteUserIdsAsync();
2992             }
2993             catch (WebApiException ex)
2994             {
2995                 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
2996                 return;
2997             }
2998
2999             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3000         }
3001
3002         private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3003         {
3004             if (e.Button == MouseButtons.Left)
3005             {
3006                 this.Visible = true;
3007                 if (this.WindowState == FormWindowState.Minimized)
3008                 {
3009                     this.WindowState = _formWindowState;
3010                 }
3011                 this.Activate();
3012                 this.BringToFront();
3013             }
3014         }
3015
3016         private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3017         {
3018             switch (SettingManager.Common.ListDoubleClickAction)
3019             {
3020                 case 0:
3021                     MakeReplyOrDirectStatus();
3022                     break;
3023                 case 1:
3024                     await this.FavoriteChange(true);
3025                     break;
3026                 case 2:
3027                     var post = this.CurrentPost;
3028                     if (post != null)
3029                         await this.ShowUserStatus(post.ScreenName, false);
3030                     break;
3031                 case 3:
3032                     await ShowUserTimeline();
3033                     break;
3034                 case 4:
3035                     ShowRelatedStatusesMenuItem_Click(null, null);
3036                     break;
3037                 case 5:
3038                     MoveToHomeToolStripMenuItem_Click(null, null);
3039                     break;
3040                 case 6:
3041                     StatusOpenMenuItem_Click(null, null);
3042                     break;
3043                 case 7:
3044                     //動作なし
3045                     break;
3046             }
3047         }
3048
3049         private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3050             => await this.FavoriteChange(true);
3051
3052         private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3053             => await this.FavoriteChange(false);
3054
3055
3056         private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3057             => await this.FavoritesRetweetOfficial();
3058
3059         private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3060             => await this.FavoritesRetweetUnofficial();
3061
3062         private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3063         {
3064             var tab = this.CurrentTab;
3065             var posts = tab.SelectedPosts;
3066
3067             //trueでFavAdd,falseでFavRemove
3068             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
3069                 || !this.ExistCurrentPost) return;
3070
3071             if (posts.Length > 1)
3072             {
3073                 if (FavAdd)
3074                 {
3075                     // 複数ツイートの一括ふぁぼは禁止
3076                     // https://support.twitter.com/articles/76915#favoriting
3077                     MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3078                     _DoFavRetweetFlags = false;
3079                     return;
3080                 }
3081                 else
3082                 {
3083                     if (multiFavoriteChangeDialogEnable)
3084                     {
3085                         var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3086                             Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3087                             MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3088
3089                         if (confirm == DialogResult.Cancel)
3090                             return;
3091                     }
3092                 }
3093             }
3094
3095             if (FavAdd)
3096             {
3097                 var selectedPost = posts.Single();
3098                 if (selectedPost.IsFav)
3099                 {
3100                     this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3101                     return;
3102                 }
3103
3104                 await this.FavAddAsync(selectedPost.StatusId, tab);
3105             }
3106             else
3107             {
3108                 var selectedPosts = posts.Where(x => x.IsFav);
3109                 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3110                 if (statusIds.Length == 0)
3111                 {
3112                     this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3113                     return;
3114                 }
3115
3116                 await this.FavRemoveAsync(statusIds, tab);
3117             }
3118         }
3119
3120         private PostClass GetCurTabPost(int Index)
3121         {
3122             var listCache = this._listItemCache;
3123             if (listCache != null)
3124             {
3125                 if (listCache.TryGetValue(Index, out _, out var post))
3126                     return post;
3127             }
3128
3129             return this.CurrentTab[Index];
3130         }
3131
3132         private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3133         {
3134             var post = this.CurrentPost;
3135             if (post != null)
3136                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + post.ScreenName);
3137             else
3138                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3139         }
3140
3141         private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3142         {
3143             var post = this.CurrentPost;
3144             if (post != null)
3145                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + post.ScreenName + "/favorites");
3146         }
3147
3148         private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3149         {
3150             if ((!_initialLayout) && this.Visible)
3151             {
3152                 if (this.WindowState == FormWindowState.Normal)
3153                 {
3154                     _mySize = this.ClientSize;
3155                     _mySpDis = this.SplitContainer1.SplitterDistance;
3156                     _mySpDis3 = this.SplitContainer3.SplitterDistance;
3157                     if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3158                     this.MarkSettingLocalModified();
3159                 }
3160             }
3161         }
3162
3163         private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3164         {
3165             var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3166             if (comparerMode == null)
3167                 return;
3168
3169             this.SetSortColumn(comparerMode.Value);
3170         }
3171
3172         /// <summary>
3173         /// 列インデックスからソートを行う ComparerMode を求める
3174         /// </summary>
3175         /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3176         /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3177         private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3178         {
3179             if (this._iconCol)
3180                 return ComparerMode.Id;
3181
3182             switch (columnIndex)
3183             {
3184                 case 1: // ニックネーム
3185                     return ComparerMode.Nickname;
3186                 case 2: // 本文
3187                     return ComparerMode.Data;
3188                 case 3: // 時刻=発言Id
3189                     return ComparerMode.Id;
3190                 case 4: // 名前
3191                     return ComparerMode.Name;
3192                 case 7: // Source
3193                     return ComparerMode.Source;
3194                 default:
3195                     // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3196                     return null;
3197             }
3198         }
3199
3200         /// <summary>
3201         /// 発言一覧の指定した位置の列でソートする
3202         /// </summary>
3203         /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3204         private void SetSortColumnByDisplayIndex(int columnIndex)
3205         {
3206             // 表示上の列の位置から ColumnHeader を求める
3207             var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
3208                 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3209
3210             if (col == null)
3211                 return;
3212
3213             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3214             if (comparerMode == null)
3215                 return;
3216
3217             this.SetSortColumn(comparerMode.Value);
3218         }
3219
3220         /// <summary>
3221         /// 発言一覧の最後列の項目でソートする
3222         /// </summary>
3223         private void SetSortLastColumn()
3224         {
3225             // 表示上の最後列にある ColumnHeader を求める
3226             var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
3227                 .OrderByDescending(x => x.DisplayIndex)
3228                 .First();
3229
3230             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3231             if (comparerMode == null)
3232                 return;
3233
3234             this.SetSortColumn(comparerMode.Value);
3235         }
3236
3237         /// <summary>
3238         /// 発言一覧を指定された ComparerMode に基づいてソートする
3239         /// </summary>
3240         private void SetSortColumn(ComparerMode sortColumn)
3241         {
3242             if (SettingManager.Common.SortOrderLock)
3243                 return;
3244
3245             this._statuses.ToggleSortOrder(sortColumn);
3246             this.InitColumnText();
3247
3248             var list = this.CurrentListView;
3249             if (_iconCol)
3250             {
3251                 list.Columns[0].Text = this.ColumnText[0];
3252                 list.Columns[1].Text = this.ColumnText[2];
3253             }
3254             else
3255             {
3256                 for (var i = 0; i <= 7; i++)
3257                 {
3258                     list.Columns[i].Text = this.ColumnText[i];
3259                 }
3260             }
3261
3262             this.PurgeListViewItemCache();
3263
3264             var tab = this.CurrentTab;
3265             var post = this.CurrentPost;
3266             if (tab.AllCount > 0 && post != null)
3267             {
3268                 var idx = tab.IndexOf(post.StatusId);
3269                 if (idx > -1)
3270                 {
3271                     this.SelectListItem(list, idx);
3272                     list.EnsureVisible(idx);
3273                 }
3274             }
3275             list.Refresh();
3276
3277             this.MarkSettingCommonModified();
3278         }
3279
3280         private void TweenMain_LocationChanged(object sender, EventArgs e)
3281         {
3282             if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3283             {
3284                 _myLoc = this.DesktopLocation;
3285                 this.MarkSettingLocalModified();
3286             }
3287         }
3288
3289         private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3290         {
3291             if (!this.ExistCurrentPost)
3292             {
3293                 ReplyStripMenuItem.Enabled = false;
3294                 ReplyAllStripMenuItem.Enabled = false;
3295                 DMStripMenuItem.Enabled = false;
3296                 ShowProfileMenuItem.Enabled = false;
3297                 ShowUserTimelineContextMenuItem.Enabled = false;
3298                 ListManageUserContextToolStripMenuItem2.Enabled = false;
3299                 MoveToFavToolStripMenuItem.Enabled = false;
3300                 TabMenuItem.Enabled = false;
3301                 IDRuleMenuItem.Enabled = false;
3302                 SourceRuleMenuItem.Enabled = false;
3303                 ReadedStripMenuItem.Enabled = false;
3304                 UnreadStripMenuItem.Enabled = false;
3305             }
3306             else
3307             {
3308                 ShowProfileMenuItem.Enabled = true;
3309                 ListManageUserContextToolStripMenuItem2.Enabled = true;
3310                 ReplyStripMenuItem.Enabled = true;
3311                 ReplyAllStripMenuItem.Enabled = true;
3312                 DMStripMenuItem.Enabled = true;
3313                 ShowUserTimelineContextMenuItem.Enabled = true;
3314                 MoveToFavToolStripMenuItem.Enabled = true;
3315                 TabMenuItem.Enabled = true;
3316                 IDRuleMenuItem.Enabled = true;
3317                 SourceRuleMenuItem.Enabled = true;
3318                 ReadedStripMenuItem.Enabled = true;
3319                 UnreadStripMenuItem.Enabled = true;
3320             }
3321             var tab = this.CurrentTab;
3322             var post = this.CurrentPost;
3323             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post.IsDm)
3324             {
3325                 FavAddToolStripMenuItem.Enabled = false;
3326                 FavRemoveToolStripMenuItem.Enabled = false;
3327                 StatusOpenMenuItem.Enabled = false;
3328                 ShowRelatedStatusesMenuItem.Enabled = false;
3329
3330                 ReTweetStripMenuItem.Enabled = false;
3331                 ReTweetUnofficialStripMenuItem.Enabled = false;
3332                 QuoteStripMenuItem.Enabled = false;
3333                 FavoriteRetweetContextMenu.Enabled = false;
3334                 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3335             }
3336             else
3337             {
3338                 FavAddToolStripMenuItem.Enabled = true;
3339                 FavRemoveToolStripMenuItem.Enabled = true;
3340                 StatusOpenMenuItem.Enabled = true;
3341                 ShowRelatedStatusesMenuItem.Enabled = true;  //PublicSearchの時問題出るかも
3342
3343                 if (!post.CanRetweetBy(this.twitterApi.CurrentUserId))
3344                 {
3345                     ReTweetStripMenuItem.Enabled = false;
3346                     ReTweetUnofficialStripMenuItem.Enabled = false;
3347                     QuoteStripMenuItem.Enabled = false;
3348                     FavoriteRetweetContextMenu.Enabled = false;
3349                     FavoriteRetweetUnofficialContextMenu.Enabled = false;
3350                 }
3351                 else
3352                 {
3353                     ReTweetStripMenuItem.Enabled = true;
3354                     ReTweetUnofficialStripMenuItem.Enabled = true;
3355                     QuoteStripMenuItem.Enabled = true;
3356                     FavoriteRetweetContextMenu.Enabled = true;
3357                     FavoriteRetweetUnofficialContextMenu.Enabled = true;
3358                 }
3359             }
3360             //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3361             //{
3362             //    RefreshMoreStripMenuItem.Enabled = true;
3363             //}
3364             //else
3365             //{
3366             //    RefreshMoreStripMenuItem.Enabled = false;
3367             //}
3368             if (!this.ExistCurrentPost || post.InReplyToStatusId == null)
3369             {
3370                 RepliedStatusOpenMenuItem.Enabled = false;
3371             }
3372             else
3373             {
3374                 RepliedStatusOpenMenuItem.Enabled = true;
3375             }
3376             if (!this.ExistCurrentPost || string.IsNullOrEmpty(post.RetweetedBy))
3377             {
3378                 MoveToRTHomeMenuItem.Enabled = false;
3379             }
3380             else
3381             {
3382                 MoveToRTHomeMenuItem.Enabled = true;
3383             }
3384
3385             if (this.ExistCurrentPost)
3386             {
3387                 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
3388                 if (post.RetweetedByUserId == this.tw.UserId)
3389                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3390                 else
3391                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3392             }
3393         }
3394
3395         private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3396             => this.MakeReplyOrDirectStatus(false, true);
3397
3398         private void DMStripMenuItem_Click(object sender, EventArgs e)
3399             => this.MakeReplyOrDirectStatus(false, false);
3400
3401         private async Task doStatusDelete()
3402         {
3403             var posts = this.CurrentTab.SelectedPosts;
3404             if (posts.Length == 0)
3405                 return;
3406
3407             // 選択されたツイートの中に削除可能なものが一つでもあるか
3408             if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3409                 return;
3410
3411             var ret = MessageBox.Show(this,
3412                 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3413                 Properties.Resources.DeleteStripMenuItem_ClickText2,
3414                 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3415
3416             if (ret != DialogResult.OK)
3417                 return;
3418
3419             var currentListView = this.CurrentListView;
3420             var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
3421
3422             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3423             {
3424                 Exception lastException = null;
3425                 foreach (var post in posts)
3426                 {
3427                     if (!post.CanDeleteBy(this.tw.UserId))
3428                         continue;
3429
3430                     try
3431                     {
3432                         if (post.IsDm)
3433                         {
3434                             await this.twitterApi.DirectMessagesEventsDestroy(post.StatusId.ToString(CultureInfo.InvariantCulture));
3435                         }
3436                         else
3437                         {
3438                             if (post.RetweetedByUserId == this.tw.UserId)
3439                             {
3440                                 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3441                                 //   => RT を取り消し
3442                                 await this.twitterApi.StatusesDestroy(post.StatusId)
3443                                     .IgnoreResponse();
3444                             }
3445                             else
3446                             {
3447                                 if (post.UserId == this.tw.UserId)
3448                                 {
3449                                     if (post.RetweetedId != null)
3450                                         // 他人に RT された自分のツイート
3451                                         //   => RT 元の自分のツイートを削除
3452                                         await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3453                                             .IgnoreResponse();
3454                                     else
3455                                         // 自分のツイート
3456                                         //   => ツイートを削除
3457                                         await this.twitterApi.StatusesDestroy(post.StatusId)
3458                                             .IgnoreResponse();
3459                                 }
3460                             }
3461                         }
3462                     }
3463                     catch (WebApiException ex)
3464                     {
3465                         lastException = ex;
3466                         continue;
3467                     }
3468
3469                     this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3470                 }
3471
3472                 if (lastException == null)
3473                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3474                 else
3475                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3476
3477                 this.PurgeListViewItemCache();
3478
3479                 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3480                 {
3481                     var tabPage = this.ListTab.TabPages[index];
3482                     var listView = (DetailsListView)tabPage.Tag;
3483
3484                     using (ControlTransaction.Update(listView))
3485                     {
3486                         listView.VirtualListSize = tab.AllCount;
3487
3488                         if (tab.TabName == this.CurrentTabName)
3489                         {
3490                             listView.SelectedIndices.Clear();
3491
3492                             if (tab.AllCount != 0)
3493                             {
3494                                 int selectedIndex;
3495                                 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3496                                     selectedIndex = focusedIndex;
3497                                 else
3498                                     selectedIndex = tab.AllCount - 1;
3499
3500                                 listView.SelectedIndices.Add(selectedIndex);
3501                                 listView.EnsureVisible(selectedIndex);
3502                                 listView.FocusedItem = listView.Items[selectedIndex];
3503                             }
3504                         }
3505                     }
3506
3507                     if (SettingManager.Common.TabIconDisp && tab.UnreadCount == 0)
3508                     {
3509                         if (tabPage.ImageIndex == 0)
3510                             tabPage.ImageIndex = -1; // タブアイコン
3511                     }
3512                 }
3513
3514                 if (!SettingManager.Common.TabIconDisp)
3515                     this.ListTab.Refresh();
3516             }
3517         }
3518
3519         private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3520             => await this.doStatusDelete();
3521
3522         private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3523         {
3524             using (ControlTransaction.Update(this.CurrentListView))
3525             {
3526                 var tab = this.CurrentTab;
3527                 foreach (var statusId in tab.SelectedStatusIds)
3528                 {
3529                     this._statuses.SetReadAllTab(statusId, read: true);
3530                     var idx = tab.IndexOf(statusId);
3531                     ChangeCacheStyleRead(true, idx);
3532                 }
3533                 ColorizeList();
3534             }
3535             if (SettingManager.Common.TabIconDisp)
3536             {
3537                 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3538                 {
3539                     if (tab.UnreadCount == 0)
3540                     {
3541                         var tabPage = this.ListTab.TabPages[index];
3542                         if (tabPage.ImageIndex == 0)
3543                             tabPage.ImageIndex = -1; // タブアイコン
3544                     }
3545                 }
3546             }
3547             if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3548         }
3549
3550         private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3551         {
3552             using (ControlTransaction.Update(this.CurrentListView))
3553             {
3554                 var tab = this.CurrentTab;
3555                 foreach (var statusId in tab.SelectedStatusIds)
3556                 {
3557                     this._statuses.SetReadAllTab(statusId, read: false);
3558                     var idx = tab.IndexOf(statusId);
3559                     ChangeCacheStyleRead(false, idx);
3560                 }
3561                 ColorizeList();
3562             }
3563             if (SettingManager.Common.TabIconDisp)
3564             {
3565                 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3566                 {
3567                     if (tab.UnreadCount > 0)
3568                     {
3569                         var tabPage = this.ListTab.TabPages[index];
3570                         if (tabPage.ImageIndex == -1)
3571                             tabPage.ImageIndex = 0; // タブアイコン
3572                     }
3573                 }
3574             }
3575             if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3576         }
3577
3578         private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3579             => await this.DoRefresh();
3580
3581         private async Task DoRefresh()
3582             => await this.RefreshTabAsync(this.CurrentTab);
3583
3584         private async Task DoRefreshMore()
3585             => await this.RefreshTabAsync(this.CurrentTab, backward: true);
3586
3587         private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3588         {
3589             var result = DialogResult.Abort;
3590
3591             using var settingDialog = new AppendSettingDialog();
3592             settingDialog.Icon = this.MainIcon;
3593             settingDialog.Owner = this;
3594             settingDialog.ShowInTaskbar = showTaskbarIcon;
3595             settingDialog.IntervalChanged += this.TimerInterval_Changed;
3596
3597             settingDialog.tw = this.tw;
3598             settingDialog.twitterApi = this.twitterApi;
3599
3600             settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
3601
3602             try
3603             {
3604                 result = settingDialog.ShowDialog(this);
3605             }
3606             catch (Exception)
3607             {
3608                 return DialogResult.Abort;
3609             }
3610
3611             if (result == DialogResult.OK)
3612             {
3613                 lock (_syncObject)
3614                 {
3615                     settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
3616                 }
3617             }
3618
3619             return result;
3620         }
3621
3622         private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3623         {
3624             // 設定画面表示前のユーザー情報
3625             var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3626
3627             var oldIconSz = SettingManager.Common.IconSize;
3628
3629             if (ShowSettingDialog() == DialogResult.OK)
3630             {
3631                 lock (_syncObject)
3632                 {
3633                     tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
3634                     tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
3635                     ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
3636                     ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
3637                     ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
3638                     ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
3639                     TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
3640
3641                     Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
3642                     Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
3643                     Networking.SetWebProxy(SettingManager.Local.ProxyType,
3644                         SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
3645                         SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
3646                     Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
3647
3648                     ImageSelector.Reset(tw, this.tw.Configuration);
3649
3650                     try
3651                     {
3652                         if (SettingManager.Common.TabIconDisp)
3653                         {
3654                             ListTab.DrawItem -= ListTab_DrawItem;
3655                             ListTab.DrawMode = TabDrawMode.Normal;
3656                             ListTab.ImageList = this.TabImage;
3657                         }
3658                         else
3659                         {
3660                             ListTab.DrawItem -= ListTab_DrawItem;
3661                             ListTab.DrawItem += ListTab_DrawItem;
3662                             ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3663                             ListTab.ImageList = null;
3664                         }
3665                     }
3666                     catch (Exception ex)
3667                     {
3668                         ex.Data["Instance"] = "ListTab(TabIconDisp)";
3669                         ex.Data["IsTerminatePermission"] = false;
3670                         throw;
3671                     }
3672
3673                     try
3674                     {
3675                         if (!SettingManager.Common.UnreadManage)
3676                         {
3677                             ReadedStripMenuItem.Enabled = false;
3678                             UnreadStripMenuItem.Enabled = false;
3679                             if (SettingManager.Common.TabIconDisp)
3680                             {
3681                                 foreach (TabPage myTab in ListTab.TabPages)
3682                                 {
3683                                     myTab.ImageIndex = -1;
3684                                 }
3685                             }
3686                         }
3687                         else
3688                         {
3689                             ReadedStripMenuItem.Enabled = true;
3690                             UnreadStripMenuItem.Enabled = true;
3691                         }
3692                     }
3693                     catch (Exception ex)
3694                     {
3695                         ex.Data["Instance"] = "ListTab(UnreadManage)";
3696                         ex.Data["IsTerminatePermission"] = false;
3697                         throw;
3698                     }
3699
3700                     // タブの表示位置の決定
3701                     SetTabAlignment();
3702
3703                     SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
3704
3705                     var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3706                     imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
3707                     imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
3708
3709                     this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
3710                     this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
3711                     _fntUnread = SettingManager.Local.FontUnread;
3712                     _clUnread = SettingManager.Local.ColorUnread;
3713                     _fntReaded = SettingManager.Local.FontRead;
3714                     _clReaded = SettingManager.Local.ColorRead;
3715                     _clFav = SettingManager.Local.ColorFav;
3716                     _clOWL = SettingManager.Local.ColorOWL;
3717                     _clRetweet = SettingManager.Local.ColorRetweet;
3718                     _fntDetail = SettingManager.Local.FontDetail;
3719                     _clDetail = SettingManager.Local.ColorDetail;
3720                     _clDetailLink = SettingManager.Local.ColorDetailLink;
3721                     _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
3722                     _clSelf = SettingManager.Local.ColorSelf;
3723                     _clAtSelf = SettingManager.Local.ColorAtSelf;
3724                     _clTarget = SettingManager.Local.ColorTarget;
3725                     _clAtTarget = SettingManager.Local.ColorAtTarget;
3726                     _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
3727                     _clAtTo = SettingManager.Local.ColorAtTo;
3728                     _clListBackcolor = SettingManager.Local.ColorListBackcolor;
3729                     _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
3730                     _clInputFont = SettingManager.Local.ColorInputFont;
3731                     _fntInputFont = SettingManager.Local.FontInputFont;
3732                     _brsBackColorMine.Dispose();
3733                     _brsBackColorAt.Dispose();
3734                     _brsBackColorYou.Dispose();
3735                     _brsBackColorAtYou.Dispose();
3736                     _brsBackColorAtFromTarget.Dispose();
3737                     _brsBackColorAtTo.Dispose();
3738                     _brsBackColorNone.Dispose();
3739                     _brsBackColorMine = new SolidBrush(_clSelf);
3740                     _brsBackColorAt = new SolidBrush(_clAtSelf);
3741                     _brsBackColorYou = new SolidBrush(_clTarget);
3742                     _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3743                     _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3744                     _brsBackColorAtTo = new SolidBrush(_clAtTo);
3745                     _brsBackColorNone = new SolidBrush(_clListBackcolor);
3746
3747                     try
3748                     {
3749                         if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3750                         StatusText.Font = _fntInputFont;
3751                         StatusText.ForeColor = _clInputFont;
3752                     }
3753                     catch (Exception ex)
3754                     {
3755                         MessageBox.Show(ex.Message);
3756                     }
3757
3758                     try
3759                     {
3760                         InitDetailHtmlFormat();
3761                     }
3762                     catch (Exception ex)
3763                     {
3764                         ex.Data["Instance"] = "Font";
3765                         ex.Data["IsTerminatePermission"] = false;
3766                         throw;
3767                     }
3768
3769                     try
3770                     {
3771                         if (SettingManager.Common.TabIconDisp)
3772                         {
3773                             foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3774                             {
3775                                 var tabPage = this.ListTab.TabPages[index];
3776                                 if (tab.UnreadCount == 0)
3777                                     tabPage.ImageIndex = -1;
3778                                 else
3779                                     tabPage.ImageIndex = 0;
3780                             }
3781                         }
3782                     }
3783                     catch (Exception ex)
3784                     {
3785                         ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3786                         ex.Data["IsTerminatePermission"] = false;
3787                         throw;
3788                     }
3789
3790                     try
3791                     {
3792                         var oldIconCol = _iconCol;
3793
3794                         if (SettingManager.Common.IconSize != oldIconSz)
3795                             ApplyListViewIconSize(SettingManager.Common.IconSize);
3796
3797                         foreach (TabPage tp in ListTab.TabPages)
3798                         {
3799                             var lst = (DetailsListView)tp.Tag;
3800
3801                             using (ControlTransaction.Update(lst))
3802                             {
3803                                 lst.GridLines = SettingManager.Common.ShowGrid;
3804                                 lst.Font = _fntReaded;
3805                                 lst.BackColor = _clListBackcolor;
3806
3807                                 if (_iconCol != oldIconCol)
3808                                     ResetColumns(lst);
3809                             }
3810                         }
3811                     }
3812                     catch (Exception ex)
3813                     {
3814                         ex.Data["Instance"] = "ListView(IconSize)";
3815                         ex.Data["IsTerminatePermission"] = false;
3816                         throw;
3817                     }
3818
3819                     SetMainWindowTitle();
3820                     SetNotifyIconText();
3821
3822                     this.PurgeListViewItemCache();
3823                     this.CurrentListView.Refresh();
3824                     ListTab.Refresh();
3825
3826                     _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3827                     if (SettingManager.Common.HotkeyEnabled)
3828                     {
3829                         ///グローバルホットキーの登録。設定で変更可能にするかも
3830                         var modKey = HookGlobalHotkey.ModKeys.None;
3831                         if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
3832                             modKey |= HookGlobalHotkey.ModKeys.Alt;
3833                         if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
3834                             modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3835                         if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
3836                             modKey |=  HookGlobalHotkey.ModKeys.Shift;
3837                         if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
3838                             modKey |= HookGlobalHotkey.ModKeys.Win;
3839
3840                         _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
3841                     }
3842
3843                     if (SettingManager.Common.IsUseNotifyGrowl) gh.RegisterGrowl();
3844                     try
3845                     {
3846                         StatusText_TextChanged(null, null);
3847                     }
3848                     catch (Exception)
3849                     {
3850                     }
3851                 }
3852             }
3853             else
3854             {
3855                 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3856                 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3857             }
3858
3859             Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3860
3861             this.TopMost = SettingManager.Common.AlwaysTop;
3862             SaveConfigsAll(false);
3863
3864             if (tw.UserId != oldUser.UserId)
3865                 await this.doGetFollowersMenu();
3866         }
3867
3868         /// <summary>
3869         /// タブの表示位置を設定する
3870         /// </summary>
3871         private void SetTabAlignment()
3872         {
3873             var newAlignment = SettingManager.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3874             if (ListTab.Alignment == newAlignment) return;
3875
3876             // 各タブのリスト上の選択位置などを退避
3877             var listSelections = this.SaveListViewSelection();
3878
3879             ListTab.Alignment = newAlignment;
3880
3881             foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3882             {
3883                 var lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
3884                 using (ControlTransaction.Update(lst))
3885                 {
3886                     // 選択位置などを復元
3887                     this.RestoreListViewSelection(lst, tab, listSelections[tab.TabName]);
3888                 }
3889             }
3890         }
3891
3892         private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
3893         {
3894             // アイコンサイズの再設定
3895             _iconCol = false;
3896             switch (iconSz)
3897             {
3898                 case MyCommon.IconSizes.IconNone:
3899                     _iconSz = 0;
3900                     break;
3901                 case MyCommon.IconSizes.Icon16:
3902                     _iconSz = 16;
3903                     break;
3904                 case MyCommon.IconSizes.Icon24:
3905                     _iconSz = 26;
3906                     break;
3907                 case MyCommon.IconSizes.Icon48:
3908                     _iconSz = 48;
3909                     break;
3910                 case MyCommon.IconSizes.Icon48_2:
3911                     _iconSz = 48;
3912                     _iconCol = true;
3913                     break;
3914             }
3915
3916             if (_iconSz > 0)
3917             {
3918                 // ディスプレイの DPI 設定を考慮したサイズを設定する
3919                 _listViewImageList.ImageSize = new Size(
3920                     1,
3921                     (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
3922             }
3923             else
3924             {
3925                 _listViewImageList.ImageSize = new Size(1, 1);
3926             }
3927         }
3928
3929         private void ResetColumns(DetailsListView list)
3930         {
3931             using (ControlTransaction.Update(list))
3932             using (ControlTransaction.Layout(list, false))
3933             {
3934                 // カラムヘッダの再設定
3935                 list.ColumnClick -= MyList_ColumnClick;
3936                 list.DrawColumnHeader -= MyList_DrawColumnHeader;
3937                 list.ColumnReordered -= MyList_ColumnReordered;
3938                 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
3939
3940                 var cols = list.Columns.Cast<ColumnHeader>().ToList();
3941                 list.Columns.Clear();
3942                 cols.ForEach(col => col.Dispose());
3943                 cols.Clear();
3944
3945                 InitColumns(list, true);
3946
3947                 list.ColumnClick += MyList_ColumnClick;
3948                 list.DrawColumnHeader += MyList_DrawColumnHeader;
3949                 list.ColumnReordered += MyList_ColumnReordered;
3950                 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
3951             }
3952         }
3953
3954         public void AddNewTabForSearch(string searchWord)
3955         {
3956             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
3957             foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
3958             {
3959                 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
3960                 {
3961                     var tabIndex = this._statuses.Tabs.IndexOf(tb);
3962                     this.ListTab.SelectedIndex = tabIndex;
3963                     return;
3964                 }
3965             }
3966             //ユニークなタブ名生成
3967             var tabName = searchWord;
3968             for (var i = 0; i <= 100; i++)
3969             {
3970                 if (_statuses.ContainsTab(tabName))
3971                     tabName += "_";
3972                 else
3973                     break;
3974             }
3975             //タブ追加
3976             var tab = new PublicSearchTabModel(tabName);
3977             _statuses.AddTab(tab);
3978             AddNewTab(tab, startup: false);
3979             //追加したタブをアクティブに
3980             ListTab.SelectedIndex = this._statuses.Tabs.Count - 1;
3981             //検索条件の設定
3982             var tabPage = this.CurrentTabPage;
3983             var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
3984             cmb.Items.Add(searchWord);
3985             cmb.Text = searchWord;
3986             SaveConfigsTabs();
3987             //検索実行
3988             this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], null);
3989         }
3990
3991         private async Task ShowUserTimeline()
3992         {
3993             if (!this.ExistCurrentPost) return;
3994             await this.AddNewTabForUserTimeline(this.CurrentPost.ScreenName);
3995         }
3996
3997         private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
3998         {
3999             if (e.KeyCode == Keys.Escape)
4000             {
4001                 RemoveSpecifiedTab(this.CurrentTabName, false);
4002                 SaveConfigsTabs();
4003                 e.SuppressKeyPress = true;
4004             }
4005         }
4006
4007         public async Task AddNewTabForUserTimeline(string user)
4008         {
4009             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4010             foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4011             {
4012                 if (tb.ScreenName == user)
4013                 {
4014                     var tabIndex = this._statuses.Tabs.IndexOf(tb);
4015                     this.ListTab.SelectedIndex = tabIndex;
4016                     return;
4017                 }
4018             }
4019             //ユニークなタブ名生成
4020             var tabName = "user:" + user;
4021             while (_statuses.ContainsTab(tabName))
4022             {
4023                 tabName += "_";
4024             }
4025             //タブ追加
4026             var tab = new UserTimelineTabModel(tabName, user);
4027             this._statuses.AddTab(tab);
4028             this.AddNewTab(tab, startup: false);
4029             //追加したタブをアクティブに
4030             ListTab.SelectedIndex = this._statuses.Tabs.Count - 1;
4031             SaveConfigsTabs();
4032             //検索実行
4033             await this.RefreshTabAsync(tab);
4034         }
4035
4036         public bool AddNewTab(TabModel tab, bool startup)
4037         {
4038             //重複チェック
4039             if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
4040                 return false;
4041
4042             //新規タブ名チェック
4043             if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4044
4045             var _tabPage = new TabPage();
4046             var _listCustom = new DetailsListView();
4047
4048             var cnt = this._statuses.Tabs.Count;
4049
4050             ///ToDo:Create and set controls follow tabtypes
4051
4052             using (ControlTransaction.Update(_listCustom))
4053             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4054             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4055             using (ControlTransaction.Layout(this.SplitContainer1, false))
4056             using (ControlTransaction.Layout(this.ListTab, false))
4057             using (ControlTransaction.Layout(this))
4058             using (ControlTransaction.Layout(_tabPage, false))
4059             {
4060                 _tabPage.Controls.Add(_listCustom);
4061
4062                 /// UserTimeline関連
4063                 var userTab = tab as UserTimelineTabModel;
4064                 var listTab = tab as ListTimelineTabModel;
4065                 var searchTab = tab as PublicSearchTabModel;
4066
4067                 if (userTab != null || listTab != null)
4068                 {
4069                     var label = new Label
4070                     {
4071                         Dock = DockStyle.Top,
4072                         Name = "labelUser",
4073                         TabIndex = 0,
4074                     };
4075
4076                     if (listTab != null)
4077                     {
4078                         label.Text = listTab.ListInfo.ToString();
4079                     }
4080                     else if (userTab != null)
4081                     {
4082                         label.Text = userTab.ScreenName + "'s Timeline";
4083                     }
4084                     label.TextAlign = ContentAlignment.MiddleLeft;
4085                     using (var tmpComboBox = new ComboBox())
4086                     {
4087                         label.Height = tmpComboBox.Height;
4088                     }
4089                     _tabPage.Controls.Add(label);
4090                 }
4091                 /// 検索関連の準備
4092                 else if (searchTab != null)
4093                 {
4094                     var pnl = new Panel();
4095
4096                     var lbl = new Label();
4097                     var cmb = new ComboBox();
4098                     var btn = new Button();
4099                     var cmbLang = new ComboBox();
4100
4101                     using (ControlTransaction.Layout(pnl, false))
4102                     {
4103                         pnl.Controls.Add(cmb);
4104                         pnl.Controls.Add(cmbLang);
4105                         pnl.Controls.Add(btn);
4106                         pnl.Controls.Add(lbl);
4107                         pnl.Name = "panelSearch";
4108                         pnl.TabIndex = 0;
4109                         pnl.Dock = DockStyle.Top;
4110                         pnl.Height = cmb.Height;
4111                         pnl.Enter += SearchControls_Enter;
4112                         pnl.Leave += SearchControls_Leave;
4113
4114                         cmb.Text = "";
4115                         cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4116                         cmb.Dock = DockStyle.Fill;
4117                         cmb.Name = "comboSearch";
4118                         cmb.DropDownStyle = ComboBoxStyle.DropDown;
4119                         cmb.ImeMode = ImeMode.NoControl;
4120                         cmb.TabStop = false;
4121                         cmb.TabIndex = 1;
4122                         cmb.AutoCompleteMode = AutoCompleteMode.None;
4123                         cmb.KeyDown += SearchComboBox_KeyDown;
4124
4125                         cmbLang.Text = "";
4126                         cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4127                         cmbLang.Dock = DockStyle.Right;
4128                         cmbLang.Width = 50;
4129                         cmbLang.Name = "comboLang";
4130                         cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4131                         cmbLang.TabStop = false;
4132                         cmbLang.TabIndex = 2;
4133                         cmbLang.Items.Add("");
4134                         cmbLang.Items.Add("ja");
4135                         cmbLang.Items.Add("en");
4136                         cmbLang.Items.Add("ar");
4137                         cmbLang.Items.Add("da");
4138                         cmbLang.Items.Add("nl");
4139                         cmbLang.Items.Add("fa");
4140                         cmbLang.Items.Add("fi");
4141                         cmbLang.Items.Add("fr");
4142                         cmbLang.Items.Add("de");
4143                         cmbLang.Items.Add("hu");
4144                         cmbLang.Items.Add("is");
4145                         cmbLang.Items.Add("it");
4146                         cmbLang.Items.Add("no");
4147                         cmbLang.Items.Add("pl");
4148                         cmbLang.Items.Add("pt");
4149                         cmbLang.Items.Add("ru");
4150                         cmbLang.Items.Add("es");
4151                         cmbLang.Items.Add("sv");
4152                         cmbLang.Items.Add("th");
4153
4154                         lbl.Text = "Search(C-S-f)";
4155                         lbl.Name = "label1";
4156                         lbl.Dock = DockStyle.Left;
4157                         lbl.Width = 90;
4158                         lbl.Height = cmb.Height;
4159                         lbl.TextAlign = ContentAlignment.MiddleLeft;
4160                         lbl.TabIndex = 0;
4161
4162                         btn.Text = "Search";
4163                         btn.Name = "buttonSearch";
4164                         btn.UseVisualStyleBackColor = true;
4165                         btn.Dock = DockStyle.Right;
4166                         btn.TabStop = false;
4167                         btn.TabIndex = 3;
4168                         btn.Click += SearchButton_Click;
4169
4170                         if (!string.IsNullOrEmpty(searchTab.SearchWords))
4171                         {
4172                             cmb.Items.Add(searchTab.SearchWords);
4173                             cmb.Text = searchTab.SearchWords;
4174                         }
4175
4176                         cmbLang.Text = searchTab.SearchLang;
4177
4178                         _tabPage.Controls.Add(pnl);
4179                     }
4180                 }
4181
4182                 _tabPage.Tag = _listCustom;
4183                 this.ListTab.Controls.Add(_tabPage);
4184
4185                 _tabPage.Location = new Point(4, 4);
4186                 _tabPage.Name = "CTab" + cnt;
4187                 _tabPage.Size = new Size(380, 260);
4188                 _tabPage.TabIndex = 2 + cnt;
4189                 _tabPage.Text = tab.TabName;
4190                 _tabPage.UseVisualStyleBackColor = true;
4191                 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4192
4193                 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4194                 _listCustom.TabIndex = 1;
4195                 _listCustom.AllowColumnReorder = true;
4196                 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4197                 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4198                 _listCustom.Dock = DockStyle.Fill;
4199                 _listCustom.FullRowSelect = true;
4200                 _listCustom.HideSelection = false;
4201                 _listCustom.Location = new Point(0, 0);
4202                 _listCustom.Margin = new Padding(0);
4203                 _listCustom.Name = "CList" + Environment.TickCount;
4204                 _listCustom.ShowItemToolTips = true;
4205                 _listCustom.Size = new Size(380, 260);
4206                 _listCustom.UseCompatibleStateImageBehavior = false;
4207                 _listCustom.View = View.Details;
4208                 _listCustom.OwnerDraw = true;
4209                 _listCustom.VirtualMode = true;
4210                 _listCustom.Font = _fntReaded;
4211                 _listCustom.BackColor = _clListBackcolor;
4212
4213                 _listCustom.GridLines = SettingManager.Common.ShowGrid;
4214                 _listCustom.AllowDrop = true;
4215
4216                 _listCustom.SmallImageList = _listViewImageList;
4217
4218                 InitColumns(_listCustom, startup);
4219
4220                 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4221                 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4222                 _listCustom.ColumnClick += MyList_ColumnClick;
4223                 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4224                 _listCustom.DragDrop += TweenMain_DragDrop;
4225                 _listCustom.DragEnter += TweenMain_DragEnter;
4226                 _listCustom.DragOver += TweenMain_DragOver;
4227                 _listCustom.DrawItem += MyList_DrawItem;
4228                 _listCustom.MouseClick += MyList_MouseClick;
4229                 _listCustom.ColumnReordered += MyList_ColumnReordered;
4230                 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4231                 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4232                 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4233                 _listCustom.DrawSubItem += MyList_DrawSubItem;
4234                 _listCustom.HScrolled += MyList_HScrolled;
4235             }
4236
4237             return true;
4238         }
4239
4240         public bool RemoveSpecifiedTab(string TabName, bool confirm)
4241         {
4242             var tabInfo = _statuses.GetTabByName(TabName);
4243             if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4244
4245             if (confirm)
4246             {
4247                 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4248                 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4249                                  MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4250                 {
4251                     return false;
4252                 }
4253             }
4254
4255             var tabIndex = this._statuses.Tabs.IndexOf(TabName);
4256             if (tabIndex == -1)
4257                 return false;
4258
4259             var _tabPage = this.ListTab.TabPages[tabIndex];
4260
4261             SetListProperty();   //他のタブに列幅等を反映
4262
4263             //オブジェクトインスタンスの削除
4264             var _listCustom = (DetailsListView)_tabPage.Tag;
4265             _tabPage.Tag = null;
4266
4267             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4268             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4269             using (ControlTransaction.Layout(this.SplitContainer1, false))
4270             using (ControlTransaction.Layout(this.ListTab, false))
4271             using (ControlTransaction.Layout(this))
4272             using (ControlTransaction.Layout(_tabPage, false))
4273             {
4274                 if (this.CurrentTabName == TabName)
4275                 {
4276                     this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4277                     this._beforeSelectedTab = null;
4278                 }
4279                 this.ListTab.Controls.Remove(_tabPage);
4280
4281                 // 後付けのコントロールを破棄
4282                 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4283                 {
4284                     using var label = _tabPage.Controls["labelUser"];
4285                     _tabPage.Controls.Remove(label);
4286                 }
4287                 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4288                 {
4289                     using var pnl = _tabPage.Controls["panelSearch"];
4290
4291                     pnl.Enter -= SearchControls_Enter;
4292                     pnl.Leave -= SearchControls_Leave;
4293                     _tabPage.Controls.Remove(pnl);
4294
4295                     foreach (Control ctrl in pnl.Controls)
4296                     {
4297                         if (ctrl.Name == "buttonSearch")
4298                         {
4299                             ctrl.Click -= SearchButton_Click;
4300                         }
4301                         else if (ctrl.Name == "comboSearch")
4302                         {
4303                             ctrl.KeyDown -= SearchComboBox_KeyDown;
4304                         }
4305                         pnl.Controls.Remove(ctrl);
4306                         ctrl.Dispose();
4307                     }
4308                 }
4309
4310                 _tabPage.Controls.Remove(_listCustom);
4311
4312                 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4313                 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4314                 _listCustom.ColumnClick -= MyList_ColumnClick;
4315                 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4316                 _listCustom.DragDrop -= TweenMain_DragDrop;
4317                 _listCustom.DragEnter -= TweenMain_DragEnter;
4318                 _listCustom.DragOver -= TweenMain_DragOver;
4319                 _listCustom.DrawItem -= MyList_DrawItem;
4320                 _listCustom.MouseClick -= MyList_MouseClick;
4321                 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4322                 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4323                 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4324                 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4325                 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4326                 _listCustom.HScrolled -= MyList_HScrolled;
4327
4328                 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4329                 _listCustom.Columns.Clear();
4330                 cols.ForEach(col => col.Dispose());
4331                 cols.Clear();
4332
4333                 _listCustom.ContextMenuStrip = null;
4334                 _listCustom.ColumnHeaderContextMenuStrip = null;
4335                 _listCustom.Font = null;
4336
4337                 _listCustom.SmallImageList = null;
4338                 _listCustom.ListViewItemSorter = null;
4339
4340                 // キャッシュのクリア
4341                 this.PurgeListViewItemCache();
4342             }
4343
4344             _tabPage.Dispose();
4345             _listCustom.Dispose();
4346             _statuses.RemoveTab(TabName);
4347
4348             foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4349             {
4350                 var lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
4351                 lst.VirtualListSize = tab.AllCount;
4352             }
4353
4354             return true;
4355         }
4356
4357         private void ListTab_Deselected(object sender, TabControlEventArgs e)
4358         {
4359             this.PurgeListViewItemCache();
4360             _beforeSelectedTab = e.TabPage;
4361         }
4362
4363         private void ListTab_MouseMove(object sender, MouseEventArgs e)
4364         {
4365             //タブのD&D
4366
4367             if (!SettingManager.Common.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4368             {
4369                 var tn = "";
4370                 var dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4371                 if (!dragEnableRectangle.Contains(e.Location))
4372                 {
4373                     //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4374                     tn = this.CurrentTabName;
4375                 }
4376
4377                 if (string.IsNullOrEmpty(tn)) return;
4378
4379                 var tabIndex = this._statuses.Tabs.IndexOf(tn);
4380                 if (tabIndex != -1)
4381                 {
4382                     var tabPage = this.ListTab.TabPages[tabIndex];
4383                     ListTab.DoDragDrop(tabPage, DragDropEffects.All);
4384                 }
4385             }
4386             else
4387             {
4388                 _tabDrag = false;
4389             }
4390
4391             var cpos = new Point(e.X, e.Y);
4392             foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4393             {
4394                 var rect = ListTab.GetTabRect(index);
4395                 if (rect.Contains(cpos))
4396                 {
4397                     _rclickTabName = tab.TabName;
4398                     break;
4399                 }
4400             }
4401         }
4402
4403         private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4404         {
4405             //_curList.Refresh();
4406             SetMainWindowTitle();
4407             SetStatusLabelUrl();
4408             SetApiStatusLabel();
4409             if (ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
4410                 this.Tag = ListTab.Tag;
4411             TabMenuControl(this.CurrentTabName);
4412             this.PushSelectPostChain();
4413             DispSelectedPost();
4414         }
4415
4416         private void SetListProperty()
4417         {
4418             if (!_isColumnChanged) return;
4419
4420             var currentListView = this.CurrentListView;
4421
4422             var dispOrder = new int[currentListView.Columns.Count];
4423             for (var i = 0; i < currentListView.Columns.Count; i++)
4424             {
4425                 for (var j = 0; j < currentListView.Columns.Count; j++)
4426                 {
4427                     if (currentListView.Columns[j].DisplayIndex == i)
4428                     {
4429                         dispOrder[i] = j;
4430                         break;
4431                     }
4432                 }
4433             }
4434
4435             //列幅、列並びを他のタブに設定
4436             foreach (TabPage tb in ListTab.TabPages)
4437             {
4438                 if (tb.Text == this.CurrentTabName)
4439                     continue;
4440
4441                 if (tb.Tag != null && tb.Controls.Count > 0)
4442                 {
4443                     var lst = (DetailsListView)tb.Tag;
4444                     for (var i = 0; i < lst.Columns.Count; i++)
4445                     {
4446                         lst.Columns[dispOrder[i]].DisplayIndex = i;
4447                         lst.Columns[i].Width = currentListView.Columns[i].Width;
4448                     }
4449                 }
4450             }
4451
4452             _isColumnChanged = false;
4453         }
4454
4455         private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4456         {
4457             if (e.KeyChar == '@')
4458             {
4459                 if (!SettingManager.Common.UseAtIdSupplement) return;
4460                 //@マーク
4461                 var cnt = AtIdSupl.ItemCount;
4462                 ShowSuplDialog(StatusText, AtIdSupl);
4463                 if (cnt != AtIdSupl.ItemCount)
4464                     this.MarkSettingAtIdModified();
4465                 e.Handled = true;
4466             }
4467             else if (e.KeyChar == '#')
4468             {
4469                 if (!SettingManager.Common.UseHashSupplement) return;
4470                 ShowSuplDialog(StatusText, HashSupl);
4471                 e.Handled = true;
4472             }
4473         }
4474
4475         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4476             => this.ShowSuplDialog(owner, dialog, 0, "");
4477
4478         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4479             => this.ShowSuplDialog(owner, dialog, offset, "");
4480
4481         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4482         {
4483             dialog.StartsWith = startswith;
4484             if (dialog.Visible)
4485             {
4486                 dialog.Focus();
4487             }
4488             else
4489             {
4490                 dialog.ShowDialog();
4491             }
4492             this.TopMost = SettingManager.Common.AlwaysTop;
4493             var selStart = owner.SelectionStart;
4494             var fHalf = "";
4495             var eHalf = "";
4496             if (dialog.DialogResult == DialogResult.OK)
4497             {
4498                 if (!string.IsNullOrEmpty(dialog.inputText))
4499                 {
4500                     if (selStart > 0)
4501                     {
4502                         fHalf = owner.Text.Substring(0, selStart - offset);
4503                     }
4504                     if (selStart < owner.Text.Length)
4505                     {
4506                         eHalf = owner.Text.Substring(selStart);
4507                     }
4508                     owner.Text = fHalf + dialog.inputText + eHalf;
4509                     owner.SelectionStart = selStart + dialog.inputText.Length;
4510                 }
4511             }
4512             else
4513             {
4514                 if (selStart > 0)
4515                 {
4516                     fHalf = owner.Text.Substring(0, selStart);
4517                 }
4518                 if (selStart < owner.Text.Length)
4519                 {
4520                     eHalf = owner.Text.Substring(selStart);
4521                 }
4522                 owner.Text = fHalf + eHalf;
4523                 if (selStart > 0)
4524                 {
4525                     owner.SelectionStart = selStart;
4526                 }
4527             }
4528             owner.Focus();
4529         }
4530
4531         private void StatusText_KeyUp(object sender, KeyEventArgs e)
4532         {
4533             //スペースキーで未読ジャンプ
4534             if (!e.Alt && !e.Control && !e.Shift)
4535             {
4536                 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4537                 {
4538                     var isSpace = false;
4539                     foreach (var c in StatusText.Text)
4540                     {
4541                         if (c == ' ' || c == ' ')
4542                         {
4543                             isSpace = true;
4544                         }
4545                         else
4546                         {
4547                             isSpace = false;
4548                             break;
4549                         }
4550                     }
4551                     if (isSpace)
4552                     {
4553                         e.Handled = true;
4554                         StatusText.Text = "";
4555                         JumpUnreadMenuItem_Click(null, null);
4556                     }
4557                 }
4558             }
4559             this.StatusText_TextChanged(null, null);
4560         }
4561
4562         private void StatusText_TextChanged(object sender, EventArgs e)
4563         {
4564             //文字数カウント
4565             var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
4566             lblLen.Text = pLen.ToString();
4567             if (pLen < 0)
4568             {
4569                 StatusText.ForeColor = Color.Red;
4570             }
4571             else
4572             {
4573                 StatusText.ForeColor = _clInputFont;
4574             }
4575
4576             this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4577
4578             if (string.IsNullOrEmpty(StatusText.Text))
4579             {
4580                 this.inReplyTo = null;
4581             }
4582         }
4583
4584         /// <summary>
4585         /// メンション以外の文字列が含まれていないテキストであるか判定します
4586         /// </summary>
4587         internal static bool TextContainsOnlyMentions(string text)
4588         {
4589             var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
4590             var startIndex = 0;
4591
4592             foreach (var mention in mentions)
4593             {
4594                 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
4595
4596                 if (!string.IsNullOrWhiteSpace(textPart))
4597                     return false;
4598
4599                 startIndex = mention.Indices[1];
4600             }
4601
4602             var textPartLast = text.Substring(startIndex);
4603
4604             if (!string.IsNullOrWhiteSpace(textPartLast))
4605                 return false;
4606
4607             return true;
4608         }
4609
4610         /// <summary>
4611         /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
4612         /// </summary>
4613         private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
4614         {
4615             var _autoPopulatedUserIds = new List<long>();
4616
4617             var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Value.StatusId] : null;
4618             if (replyToPost != null)
4619             {
4620                 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
4621                 {
4622                     statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
4623                     _autoPopulatedUserIds.Add(replyToPost.UserId);
4624
4625                     foreach (var (userId, screenName) in replyToPost.ReplyToList)
4626                     {
4627                         if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
4628                         {
4629                             statusText = statusText.Substring(screenName.Length + 2);
4630                             _autoPopulatedUserIds.Add(userId);
4631                         }
4632                     }
4633                 }
4634             }
4635
4636             autoPopulatedUserIds = _autoPopulatedUserIds.ToArray();
4637
4638             return statusText;
4639         }
4640
4641         /// <summary>
4642         /// attachment_url に指定可能な URL が含まれていれば除去
4643         /// </summary>
4644         private string RemoveAttachmentUrl(string statusText, out string attachmentUrl)
4645         {
4646             attachmentUrl = null;
4647
4648             // attachment_url は media_id と同時に使用できない
4649             if (this.ImageSelector.Visible && this.ImageSelector.SelectedService is TwitterPhoto)
4650                 return statusText;
4651
4652             var match = Twitter.AttachmentUrlRegex.Match(statusText);
4653             if (!match.Success)
4654                 return statusText;
4655
4656             attachmentUrl = match.Value;
4657
4658             // マッチした URL を空白に置換
4659             statusText = statusText.Substring(0, match.Index);
4660
4661             // テキストと URL の間にスペースが含まれていれば除去
4662             return statusText.TrimEnd(' ');
4663         }
4664
4665         private string FormatStatusTextExtended(string statusText)
4666             => this.FormatStatusTextExtended(statusText, out _, out _);
4667
4668         /// <summary>
4669         /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
4670         /// </summary>
4671         private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string attachmentUrl)
4672         {
4673             statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
4674
4675             statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
4676
4677             return this.FormatStatusText(statusText);
4678         }
4679
4680         /// <summary>
4681         /// ツイート投稿前のフッター付与などの前処理を行います
4682         /// </summary>
4683         private string FormatStatusText(string statusText)
4684         {
4685             statusText = statusText.Replace("\r\n", "\n");
4686
4687             if (this.urlMultibyteSplit)
4688             {
4689                 // URLと全角文字の切り離し
4690                 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4691             }
4692
4693             if (SettingManager.Common.WideSpaceConvert)
4694             {
4695                 // 文中の全角スペースを半角スペース1個にする
4696                 statusText = statusText.Replace(" ", " ");
4697             }
4698
4699             // DM の場合はこれ以降の処理を行わない
4700             if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4701                 return statusText;
4702
4703             bool disableFooter;
4704             if (SettingManager.Common.PostShiftEnter)
4705             {
4706                 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4707             }
4708             else
4709             {
4710                 if (this.StatusText.Multiline && !SettingManager.Common.PostCtrlEnter)
4711                     disableFooter = MyCommon.IsKeyDown(Keys.Control);
4712                 else
4713                     disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4714             }
4715
4716             if (statusText.Contains("RT @"))
4717                 disableFooter = true;
4718
4719             // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
4720             if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
4721             {
4722                 var mentionSelf = $"@{this.tw.Username} ";
4723                 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
4724                 {
4725                     if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
4726                         statusText = statusText.Substring(mentionSelf.Length);
4727                 }
4728             }
4729
4730             var header = "";
4731             var footer = "";
4732
4733             var hashtag = this.HashMgr.UseHash;
4734             if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4735             {
4736                 if (HashMgr.IsHead)
4737                     header = HashMgr.UseHash + " ";
4738                 else
4739                     footer = " " + HashMgr.UseHash;
4740             }
4741
4742             if (!disableFooter)
4743             {
4744                 if (SettingManager.Local.UseRecommendStatus)
4745                 {
4746                     // 推奨ステータスを使用する
4747                     footer += this.recommendedStatusFooter;
4748                 }
4749                 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4750                 {
4751                     // テキストボックスに入力されている文字列を使用する
4752                     footer += " " + SettingManager.Local.StatusText.Trim();
4753                 }
4754             }
4755
4756             statusText = header + statusText + footer;
4757
4758             if (this.preventSmsCommand)
4759             {
4760                 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4761                 // 参照: https://support.twitter.com/articles/14020
4762
4763                 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4764                     && !Twitter.DMSendTextRegex.IsMatch(statusText))
4765                 {
4766                     // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4767                     statusText = '\u200b' + statusText;
4768                 }
4769             }
4770
4771             return statusText;
4772         }
4773
4774         /// <summary>
4775         /// 投稿欄に表示する入力可能な文字数を計算します
4776         /// </summary>
4777         private int GetRestStatusCount(string statusText)
4778         {
4779             var remainCount = this.tw.GetTextLengthRemain(statusText);
4780
4781             var uploadService = this.GetSelectedImageService();
4782             if (uploadService != null)
4783             {
4784                 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4785                 remainCount -= uploadService.GetReservedTextLength(1);
4786             }
4787
4788             return remainCount;
4789         }
4790
4791         private IMediaUploadService GetSelectedImageService()
4792             => this.ImageSelector.Visible ? this.ImageSelector.SelectedService : null;
4793
4794         private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4795         {
4796             if (sender != this.CurrentListView)
4797                 return;
4798
4799             var listCache = this._listItemCache;
4800             if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4801             {
4802                 // If the newly requested cache is a subset of the old cache,
4803                 // no need to rebuild everything, so do nothing.
4804                 return;
4805             }
4806
4807             // Now we need to rebuild the cache.
4808             this.CreateCache(e.StartIndex, e.EndIndex);
4809         }
4810
4811         private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4812         {
4813             var listCache = this._listItemCache;
4814             if (listCache?.TargetList == sender)
4815             {
4816                 if (listCache.TryGetValue(e.ItemIndex, out var item, out _))
4817                 {
4818                     e.Item = item;
4819                     return;
4820                 }
4821             }
4822
4823             // A cache miss, so create a new ListViewItem and pass it back.
4824             var tabPage = (TabPage)((DetailsListView)sender).Parent;
4825             var tab = this._statuses.Tabs[tabPage.Text];
4826             try
4827             {
4828                 e.Item = this.CreateItem(tab, tab[e.ItemIndex]);
4829             }
4830             catch (Exception)
4831             {
4832                 // 不正な要求に対する間に合わせの応答
4833                 string[] sitem = {"", "", "", "", "", "", "", ""};
4834                 e.Item = new ImageListViewItem(sitem);
4835             }
4836         }
4837
4838         private void CreateCache(int startIndex, int endIndex)
4839         {
4840             var tabInfo = this.CurrentTab;
4841
4842             if (tabInfo.AllCount == 0)
4843                 return;
4844
4845             // インデックスを 0...(tabInfo.AllCount - 1) の範囲内にする
4846             int FilterRange(int index)
4847                 => Math.Max(Math.Min(index, tabInfo.AllCount - 1), 0);
4848
4849             // キャッシュ要求(要求範囲±30を作成)
4850             startIndex = FilterRange(startIndex - 30);
4851             endIndex = FilterRange(endIndex + 30);
4852
4853             var cacheLength = endIndex - startIndex + 1;
4854
4855             var tab = this.CurrentTab;
4856             var posts = tabInfo[startIndex, endIndex]; //配列で取得
4857             var listItems = Enumerable.Range(0, cacheLength)
4858                 .Select(x => this.CreateItem(tab, posts[x]))
4859                 .ToArray();
4860
4861             var listCache = new ListViewItemCache
4862             {
4863                 TargetList = this.CurrentListView,
4864                 StartIndex = startIndex,
4865                 EndIndex = endIndex,
4866                 Cache = Enumerable.Zip(listItems, posts, (x, y) => (x, y)).ToArray(),
4867             };
4868
4869             Interlocked.Exchange(ref this._listItemCache, listCache);
4870         }
4871
4872         /// <summary>
4873         /// DetailsListView のための ListViewItem のキャッシュを消去する
4874         /// </summary>
4875         private void PurgeListViewItemCache()
4876             => Interlocked.Exchange(ref this._listItemCache, null);
4877
4878         private ListViewItem CreateItem(TabModel tab, PostClass Post)
4879         {
4880             var mk = new StringBuilder();
4881             //if (Post.IsDeleted) mk.Append("×");
4882             //if (Post.IsMark) mk.Append("♪");
4883             //if (Post.IsProtect) mk.Append("Ю");
4884             //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4885             if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4886             ImageListViewItem itm;
4887             if (Post.RetweetedId == null)
4888             {
4889                 string[] sitem= {"",
4890                                  Post.Nickname,
4891                                  Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4892                                  Post.CreatedAt.ToLocalTimeString(SettingManager.Common.DateTimeFormat),
4893                                  Post.ScreenName,
4894                                  "",
4895                                  mk.ToString(),
4896                                  Post.Source};
4897                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4898             }
4899             else
4900             {
4901                 string[] sitem = {"",
4902                                   Post.Nickname,
4903                                   Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4904                                   Post.CreatedAt.ToLocalTimeString(SettingManager.Common.DateTimeFormat),
4905                                   Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4906                                   "",
4907                                   mk.ToString(),
4908                                   Post.Source};
4909                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4910             }
4911             itm.StateIndex = Post.StateIndex;
4912             itm.Tag = Post;
4913
4914             var read = Post.IsRead;
4915             // 未読管理していなかったら既読として扱う
4916             if (!tab.UnreadManage || !SettingManager.Common.UnreadManage)
4917                 read = true;
4918
4919             ChangeItemStyleRead(read, itm, Post, null);
4920
4921             if (tab.TabName == this.CurrentTabName)
4922                 this.ColorizeList(itm, Post);
4923
4924             return itm;
4925         }
4926
4927         /// <summary>
4928         /// 全てのタブの振り分けルールを反映し直します
4929         /// </summary>
4930         private void ApplyPostFilters()
4931         {
4932             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4933             {
4934                 this.PurgeListViewItemCache();
4935                 this._statuses.FilterAll();
4936
4937                 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4938                 {
4939                     var tabPage = this.ListTab.TabPages[index];
4940                     var listview = (DetailsListView)tabPage.Tag;
4941                     using (ControlTransaction.Update(listview))
4942                     {
4943                         listview.VirtualListSize = tab.AllCount;
4944                     }
4945
4946                     if (SettingManager.Common.TabIconDisp)
4947                     {
4948                         if (tab.UnreadCount > 0)
4949                             tabPage.ImageIndex = 0;
4950                         else
4951                             tabPage.ImageIndex = -1;
4952                     }
4953                 }
4954
4955                 if (!SettingManager.Common.TabIconDisp)
4956                     this.ListTab.Refresh();
4957
4958                 SetMainWindowTitle();
4959                 SetStatusLabelUrl();
4960             }
4961         }
4962
4963         private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4964             => e.DrawDefault = true;
4965
4966         private void MyList_HScrolled(object sender, EventArgs e)
4967             => ((DetailsListView)sender).Refresh();
4968
4969         private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
4970         {
4971             if (e.State == 0) return;
4972             e.DrawDefault = false;
4973
4974             SolidBrush brs2;
4975             if (!e.Item.Selected)     //e.ItemStateでうまく判定できない???
4976             {
4977                 if (e.Item.BackColor == _clSelf)
4978                     brs2 = _brsBackColorMine;
4979                 else if (e.Item.BackColor == _clAtSelf)
4980                     brs2 = _brsBackColorAt;
4981                 else if (e.Item.BackColor == _clTarget)
4982                     brs2 = _brsBackColorYou;
4983                 else if (e.Item.BackColor == _clAtTarget)
4984                     brs2 = _brsBackColorAtYou;
4985                 else if (e.Item.BackColor == _clAtFromTarget)
4986                     brs2 = _brsBackColorAtFromTarget;
4987                 else if (e.Item.BackColor == _clAtTo)
4988                     brs2 = _brsBackColorAtTo;
4989                 else
4990                     brs2 = _brsBackColorNone;
4991             }
4992             else
4993             {
4994                 //選択中の行
4995                 if (((Control)sender).Focused)
4996                     brs2 = _brsHighLight;
4997                 else
4998                     brs2 = _brsDeactiveSelection;
4999             }
5000             e.Graphics.FillRectangle(brs2, e.Bounds);
5001             e.DrawFocusRectangle();
5002             this.DrawListViewItemIcon(e);
5003         }
5004
5005         private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5006         {
5007             if (e.ItemState == 0) return;
5008
5009             if (e.ColumnIndex > 0)
5010             {
5011                 //アイコン以外の列
5012                 var post = (PostClass)e.Item.Tag;
5013
5014                 RectangleF rct = e.Bounds;
5015                 rct.Width = e.Header.Width;
5016                 var fontHeight = e.Item.Font.Height;
5017                 if (_iconCol)
5018                 {
5019                     rct.Y += fontHeight;
5020                     rct.Height -= fontHeight;
5021                 }
5022
5023                 var drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out var heightDiff));
5024
5025                 //if (heightDiff > fontHeight * 0.7)
5026                 //{
5027                 //    rct.Height += fontHeight;
5028                 //    drawLineCount += 1;
5029                 //}
5030
5031                 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5032                 if (!_iconCol && drawLineCount <= 1)
5033                 {
5034                     //rct.Inflate(0, heightDiff / -2);
5035                     //rct.Height += fontHeight / 2;
5036                 }
5037                 else if (heightDiff < fontHeight * 0.7)
5038                 {
5039                     //最終行が70%以上欠けていたら、最終行は表示しない
5040                     //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5041                     rct.Height = (fontHeight * drawLineCount) - 1;
5042                 }
5043                 else
5044                 {
5045                     drawLineCount += 1;
5046                 }
5047
5048                 //if (!_iconCol && drawLineCount > 1)
5049                 //{
5050                 //    rct.Y += fontHeight * 0.2;
5051                 //    if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5052                 //}
5053
5054                 if (rct.Width > 0)
5055                 {
5056                     var color = (!e.Item.Selected) ? e.Item.ForeColor :   //選択されていない行
5057                         (((Control)sender).Focused) ? _clHighLight :        //選択中の行
5058                         _clUnread;
5059
5060                     if (_iconCol)
5061                     {
5062                         var rctB = e.Bounds;
5063                         rctB.Width = e.Header.Width;
5064                         rctB.Height = fontHeight;
5065
5066                         using var fnt = new Font(e.Item.Font, FontStyle.Bold);
5067
5068                         TextRenderer.DrawText(e.Graphics,
5069                             post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5070                             e.Item.Font,
5071                             Rectangle.Round(rct),
5072                             color,
5073                             TextFormatFlags.WordBreak |
5074                             TextFormatFlags.EndEllipsis |
5075                             TextFormatFlags.GlyphOverhangPadding |
5076                             TextFormatFlags.NoPrefix);
5077                         TextRenderer.DrawText(e.Graphics,
5078                             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 + "]",
5079                             fnt,
5080                             rctB,
5081                             color,
5082                             TextFormatFlags.SingleLine |
5083                             TextFormatFlags.EndEllipsis |
5084                             TextFormatFlags.GlyphOverhangPadding |
5085                             TextFormatFlags.NoPrefix);
5086                     }
5087                     else
5088                     {
5089                         string text;
5090                         if (e.ColumnIndex != 2)
5091                             text = e.SubItem.Text;
5092                         else
5093                             text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5094
5095                         if (drawLineCount == 1)
5096                         {
5097                             TextRenderer.DrawText(e.Graphics,
5098                                                     text,
5099                                                     e.Item.Font,
5100                                                     Rectangle.Round(rct),
5101                                                     color,
5102                                                     TextFormatFlags.SingleLine |
5103                                                     TextFormatFlags.EndEllipsis |
5104                                                     TextFormatFlags.GlyphOverhangPadding |
5105                                                     TextFormatFlags.NoPrefix |
5106                                                     TextFormatFlags.VerticalCenter);
5107                         }
5108                         else
5109                         {
5110                             TextRenderer.DrawText(e.Graphics,
5111                                                     text,
5112                                                     e.Item.Font,
5113                                                     Rectangle.Round(rct),
5114                                                     color,
5115                                                     TextFormatFlags.WordBreak |
5116                                                     TextFormatFlags.EndEllipsis |
5117                                                     TextFormatFlags.GlyphOverhangPadding |
5118                                                     TextFormatFlags.NoPrefix);
5119                         }
5120                     }
5121                     //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5122                 }
5123             }
5124         }
5125
5126         private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5127         {
5128             if (_iconSz == 0) return;
5129
5130             var item = (ImageListViewItem)e.Item;
5131
5132             //e.Bounds.Leftが常に0を指すから自前で計算
5133             var itemRect = item.Bounds;
5134             var col0 = e.Item.ListView.Columns[0];
5135             itemRect.Width = col0.Width;
5136
5137             if (col0.DisplayIndex > 0)
5138             {
5139                 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5140                 {
5141                     if (clm.DisplayIndex < col0.DisplayIndex)
5142                         itemRect.X += clm.Width;
5143                 }
5144             }
5145
5146             // ディスプレイの DPI 設定を考慮したアイコンサイズ
5147             var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5148             var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5149
5150             Rectangle iconRect;
5151             var img = item.Image;
5152             if (img != null)
5153             {
5154                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5155                 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5156
5157                 if (iconRect.Width > 0)
5158                 {
5159                     e.Graphics.FillRectangle(Brushes.White, iconRect);
5160                     e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5161                     try
5162                     {
5163                         e.Graphics.DrawImage(img.Image, iconRect);
5164                     }
5165                     catch (ArgumentException)
5166                     {
5167                         item.RefreshImageAsync();
5168                     }
5169                 }
5170             }
5171             else
5172             {
5173                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5174                 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5175
5176                 item.GetImageAsync();
5177             }
5178
5179             if (item.StateIndex > -1)
5180             {
5181                 var stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5182                 if (stateRect.Width > 0)
5183                 {
5184                     //e.Graphics.FillRectangle(Brushes.White, stateRect);
5185                     //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5186                     e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5187                 }
5188             }
5189         }
5190
5191         protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5192         {
5193             base.ScaleControl(factor, specified);
5194
5195             ScaleChildControl(this.TabImage, factor);
5196
5197             var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5198             var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5199
5200             foreach (var listview in listviews)
5201             {
5202                 ScaleChildControl(listview, factor);
5203             }
5204         }
5205
5206         //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5207         //{
5208         //    ImageListViewItem item = (ImageListViewItem)e.Item;
5209         //    if (item.StateImageIndex > -1)
5210         //    {
5211         //        ////e.Bounds.Leftが常に0を指すから自前で計算
5212         //        //Rectangle itemRect = item.Bounds;
5213         //        //itemRect.Width = e.Item.ListView.Columns[4].Width;
5214
5215         //        //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5216         //        //{
5217         //        //    if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5218         //        //    {
5219         //        //        itemRect.X += clm.Width;
5220         //        //    }
5221         //        //}
5222
5223         //        //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5224         //        //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5225
5226         //        if (rct.Width > 0)
5227         //        {
5228         //            RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5229         //            //e.Graphics.FillRectangle(Brushes.White, rct);
5230         //            //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5231         //            e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5232         //        }
5233         //    }
5234         //}
5235
5236         internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5237         {
5238             var tab = this.CurrentTab;
5239
5240             if (tab.AllCount == 0)
5241             {
5242                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5243                 return;
5244             }
5245
5246             var selectedIndex = tab.SelectedIndex;
5247
5248             int startIndex;
5249             switch (searchType)
5250             {
5251                 case SEARCHTYPE.NextSearch: // 次を検索
5252                     if (selectedIndex != -1)
5253                         startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5254                     else
5255                         startIndex = 0;
5256                     break;
5257                 case SEARCHTYPE.PrevSearch: // 前を検索
5258                     if (selectedIndex != -1)
5259                         startIndex = Math.Max(selectedIndex - 1, 0);
5260                     else
5261                         startIndex = tab.AllCount - 1;
5262                     break;
5263                 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5264                 default:
5265                     if (selectedIndex != -1)
5266                         startIndex = selectedIndex;
5267                     else
5268                         startIndex = 0;
5269                     break;
5270             }
5271
5272             Func<string, bool> stringComparer;
5273             try
5274             {
5275                 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5276             }
5277             catch (ArgumentException)
5278             {
5279                 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5280                 return;
5281             }
5282
5283             var reverse = searchType == SEARCHTYPE.PrevSearch;
5284             var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5285                 .DefaultIfEmpty(-1).First();
5286
5287             if (foundIndex == -1)
5288             {
5289                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5290                 return;
5291             }
5292
5293             var listView = this.CurrentListView;
5294             this.SelectListItem(listView, foundIndex);
5295             listView.EnsureVisible(foundIndex);
5296         }
5297
5298         private void MenuItemSubSearch_Click(object sender, EventArgs e)
5299             => this.ShowSearchDialog(); // 検索メニュー
5300
5301         private void MenuItemSearchNext_Click(object sender, EventArgs e)
5302         {
5303             var previousSearch = this.SearchDialog.ResultOptions;
5304             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5305             {
5306                 this.SearchDialog.Reset();
5307                 this.ShowSearchDialog();
5308                 return;
5309             }
5310
5311             // 次を検索
5312             this.DoTabSearch(
5313                 previousSearch.Query,
5314                 previousSearch.CaseSensitive,
5315                 previousSearch.UseRegex,
5316                 SEARCHTYPE.NextSearch);
5317         }
5318
5319         private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5320         {
5321             var previousSearch = this.SearchDialog.ResultOptions;
5322             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5323             {
5324                 this.SearchDialog.Reset();
5325                 this.ShowSearchDialog();
5326                 return;
5327             }
5328
5329             // 前を検索
5330             this.DoTabSearch(
5331                 previousSearch.Query,
5332                 previousSearch.CaseSensitive,
5333                 previousSearch.UseRegex,
5334                 SEARCHTYPE.PrevSearch);
5335         }
5336
5337         /// <summary>
5338         /// 検索ダイアログを表示し、検索を実行します
5339         /// </summary>
5340         private void ShowSearchDialog()
5341         {
5342             if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5343             {
5344                 this.TopMost = SettingManager.Common.AlwaysTop;
5345                 return;
5346             }
5347             this.TopMost = SettingManager.Common.AlwaysTop;
5348
5349             var searchOptions = this.SearchDialog.ResultOptions;
5350             if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5351             {
5352                 if (searchOptions.NewTab)
5353                 {
5354                     var tabName = Properties.Resources.SearchResults_TabName;
5355
5356                     try
5357                     {
5358                         tabName = this._statuses.MakeTabName(tabName);
5359                     }
5360                     catch (TabException ex)
5361                     {
5362                         MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5363                     }
5364
5365                     var resultTab = new LocalSearchTabModel(tabName);
5366                     this.AddNewTab(resultTab, startup: false);
5367                     this._statuses.AddTab(resultTab);
5368
5369                     var targetTab = this.CurrentTab;
5370
5371                     Func<string, bool> stringComparer;
5372                     try
5373                     {
5374                         stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5375                     }
5376                     catch (ArgumentException)
5377                     {
5378                         MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5379                         return;
5380                     }
5381
5382                     var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5383                     if (foundIndices.Length == 0)
5384                     {
5385                         MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5386                         return;
5387                     }
5388
5389                     var foundPosts = foundIndices.Select(x => targetTab[x]);
5390                     foreach (var post in foundPosts)
5391                     {
5392                         resultTab.AddPostQueue(post);
5393                     }
5394
5395                     this._statuses.DistributePosts();
5396                     this.RefreshTimeline();
5397
5398                     var tabIndex = this._statuses.Tabs.IndexOf(tabName);
5399                     this.ListTab.SelectedIndex = tabIndex;
5400                 }
5401                 else
5402                 {
5403                     this.DoTabSearch(
5404                         searchOptions.Query,
5405                         searchOptions.CaseSensitive,
5406                         searchOptions.UseRegex,
5407                         SEARCHTYPE.DialogSearch);
5408                 }
5409             }
5410             else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5411             {
5412                 this.AddNewTabForSearch(searchOptions.Query);
5413             }
5414         }
5415
5416         /// <summary>発言検索に使用するメソッドを生成します</summary>
5417         /// <exception cref="ArgumentException">
5418         /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5419         /// </exception>
5420         private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5421         {
5422             if (useRegex)
5423             {
5424                 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5425                 var regex = new Regex(query, regexOption);
5426
5427                 return x => regex.IsMatch(x);
5428             }
5429             else
5430             {
5431                 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5432
5433                 return x => x.IndexOf(query, comparisonType) != -1;
5434             }
5435         }
5436
5437         private void AboutMenuItem_Click(object sender, EventArgs e)
5438         {
5439             using (var about = new TweenAboutBox())
5440             {
5441                 about.ShowDialog(this);
5442             }
5443             this.TopMost = SettingManager.Common.AlwaysTop;
5444         }
5445
5446         private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5447         {
5448             var bgnIdx = this._statuses.SelectedTabIndex;
5449
5450             if (ImageSelector.Enabled)
5451                 return;
5452
5453             TabModel foundTab = null;
5454             var foundIndex = 0;
5455
5456             DetailsListView lst = null;
5457
5458             //現在タブから最終タブまで探索
5459             foreach (var (tab, index) in this._statuses.Tabs.WithIndex().Skip(bgnIdx))
5460             {
5461                 var unreadIndex = tab.NextUnreadIndex;
5462                 if (unreadIndex != -1)
5463                 {
5464                     ListTab.SelectedIndex = index;
5465                     foundTab = tab;
5466                     foundIndex = unreadIndex;
5467                     lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
5468                     break;
5469                 }
5470             }
5471
5472             //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5473             if (foundTab == null && bgnIdx > 0)
5474             {
5475                 foreach (var (tab, index) in this._statuses.Tabs.WithIndex().Take(bgnIdx))
5476                 {
5477                     var unreadIndex = tab.NextUnreadIndex;
5478                     if (unreadIndex != -1)
5479                     {
5480                         ListTab.SelectedIndex = index;
5481                         foundTab = tab;
5482                         foundIndex = unreadIndex;
5483                         lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
5484                         break;
5485                     }
5486                 }
5487             }
5488
5489             if (foundTab == null)
5490             {
5491                 //全部調べたが未読見つからず→先頭タブの最新発言へ
5492                 ListTab.SelectedIndex = 0;
5493                 var tabPage = this.ListTab.TabPages[0];
5494                 var tab = this._statuses.Tabs[0];
5495
5496                 if (tab.AllCount == 0)
5497                     return;
5498
5499                 if (_statuses.SortOrder == SortOrder.Ascending)
5500                     foundIndex = tab.AllCount - 1;
5501                 else
5502                     foundIndex = 0;
5503
5504                 lst = (DetailsListView)tabPage.Tag;
5505             }
5506
5507             SelectListItem(lst, foundIndex);
5508
5509             if (_statuses.SortMode == ComparerMode.Id)
5510             {
5511                 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5512                     _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5513                 {
5514                     MoveTop();
5515                 }
5516                 else
5517                 {
5518                     lst.EnsureVisible(foundIndex);
5519                 }
5520             }
5521             else
5522             {
5523                 lst.EnsureVisible(foundIndex);
5524             }
5525
5526             lst.Focus();
5527         }
5528
5529         private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5530         {
5531             var tab = this.CurrentTab;
5532             var post = this.CurrentPost;
5533             if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
5534                 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5535         }
5536
5537         private async void VerUpMenuItem_Click(object sender, EventArgs e)
5538             => await this.CheckNewVersion(false);
5539
5540         private void RunTweenUp()
5541         {
5542             var pinfo = new ProcessStartInfo
5543             {
5544                 UseShellExecute = true,
5545                 WorkingDirectory = MyCommon.settingPath,
5546                 FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe"),
5547                 Arguments = "\"" + Application.StartupPath + "\"",
5548             };
5549
5550             try
5551             {
5552                 Process.Start(pinfo);
5553             }
5554             catch (Exception)
5555             {
5556                 MessageBox.Show("Failed to execute TweenUp3.exe.");
5557             }
5558         }
5559
5560         public class VersionInfo
5561         {
5562             public Version Version { get; set; }
5563             public Uri DownloadUri { get; set; }
5564             public string ReleaseNote { get; set; }
5565         }
5566
5567         /// <summary>
5568         /// OpenTween の最新バージョンの情報を取得します
5569         /// </summary>
5570         public async Task<VersionInfo> GetVersionInfoAsync()
5571         {
5572             var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5573                 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5574
5575             var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5576                 .ConfigureAwait(false);
5577
5578             // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5579             var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5580
5581             var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5582             var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5583
5584             msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5585
5586             return new VersionInfo
5587             {
5588                 Version = Version.Parse(msgHeader[0]),
5589                 DownloadUri = new Uri(msgHeader[1]),
5590                 ReleaseNote = msgBody,
5591             };
5592         }
5593
5594         private async Task CheckNewVersion(bool startup = false)
5595         {
5596             if (ApplicationSettings.VersionInfoUrl == null)
5597                 return; // 更新チェック無効化
5598
5599             try
5600             {
5601                 var versionInfo = await this.GetVersionInfoAsync();
5602
5603                 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5604                 {
5605                     // 更新不要
5606                     if (!startup)
5607                     {
5608                         var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5609                             MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5610                         msgtext = MyCommon.ReplaceAppName(msgtext);
5611
5612                         MessageBox.Show(msgtext,
5613                             MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5614                             MessageBoxButtons.OK, MessageBoxIcon.Information);
5615                     }
5616                     return;
5617                 }
5618
5619                 if (startup && versionInfo.Version <= SettingManager.Common.SkipUpdateVersion)
5620                     return;
5621
5622                 using var dialog = new UpdateDialog();
5623
5624                 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5625                     MyCommon.GetReadableVersion(versionInfo.Version));
5626                 dialog.DetailsText = versionInfo.ReleaseNote;
5627
5628                 if (dialog.ShowDialog(this) == DialogResult.Yes)
5629                 {
5630                     await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5631                 }
5632                 else if (dialog.SkipButtonPressed)
5633                 {
5634                     SettingManager.Common.SkipUpdateVersion = versionInfo.Version;
5635                     this.MarkSettingCommonModified();
5636                 }
5637             }
5638             catch (Exception)
5639             {
5640                 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5641                 if (!startup)
5642                 {
5643                     MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5644                         MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5645                         MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5646                 }
5647             }
5648         }
5649
5650         private void UpdateSelectedPost()
5651         {
5652             //件数関連の場合、タイトル即時書き換え
5653             if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5654                SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5655                SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5656                SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5657             {
5658                 SetMainWindowTitle();
5659             }
5660             if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5661                 SetStatusLabelUrl();
5662
5663             if (SettingManager.Common.TabIconDisp)
5664             {
5665                 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
5666                 {
5667                     if (tab.UnreadCount == 0)
5668                     {
5669                         var tabPage = this.ListTab.TabPages[index];
5670                         if (tabPage.ImageIndex == 0)
5671                             tabPage.ImageIndex = -1;
5672                     }
5673                 }
5674             }
5675             else
5676             {
5677                 this.ListTab.Refresh();
5678             }
5679
5680             this.DispSelectedPost();
5681         }
5682
5683         public string createDetailHtml(string orgdata)
5684             => detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5685
5686         private void DispSelectedPost()
5687             => this.DispSelectedPost(false);
5688
5689         private PostClass displayPost = new PostClass();
5690
5691         /// <summary>
5692         /// サムネイル表示に使用する CancellationToken の生成元
5693         /// </summary>
5694         private CancellationTokenSource thumbnailTokenSource = null;
5695
5696         private void DispSelectedPost(bool forceupdate)
5697         {
5698             var currentPost = this.CurrentPost;
5699             if (currentPost == null)
5700                 return;
5701
5702             var oldDisplayPost = this.displayPost;
5703             this.displayPost = currentPost;
5704
5705             if (!forceupdate && currentPost.Equals(oldDisplayPost))
5706                 return;
5707
5708             var loadTasks = new List<Task>
5709             {
5710                 this.tweetDetailsView.ShowPostDetails(currentPost),
5711             };
5712
5713             this.SplitContainer3.Panel2Collapsed = true;
5714
5715             if (SettingManager.Common.PreviewEnable)
5716             {
5717                 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5718                 oldTokenSource?.Cancel();
5719
5720                 var token = this.thumbnailTokenSource.Token;
5721                 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(currentPost, token));
5722             }
5723
5724             async Task delayedTasks()
5725             {
5726                 try
5727                 {
5728                     await Task.WhenAll(loadTasks);
5729                 }
5730                 catch (OperationCanceledException) { }
5731             }
5732
5733             // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
5734             _ = delayedTasks();
5735         }
5736
5737         private async void MatomeMenuItem_Click(object sender, EventArgs e)
5738             => await this.OpenApplicationWebsite();
5739
5740         private async Task OpenApplicationWebsite()
5741             => await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5742
5743         private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5744             => await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5745
5746         private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5747         {
5748             var tab = this.CurrentTab;
5749             if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
5750             {
5751                 var pnl = this.CurrentTabPage.Controls["panelSearch"];
5752                 if (pnl.Controls["comboSearch"].Focused ||
5753                     pnl.Controls["comboLang"].Focused ||
5754                     pnl.Controls["buttonSearch"].Focused) return;
5755             }
5756
5757             if (e.Control || e.Shift || e.Alt)
5758                 this._anchorFlag = false;
5759
5760             if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
5761             {
5762                 e.Handled = true;
5763                 e.SuppressKeyPress = true;
5764             }
5765
5766             if (asyncTask != null)
5767                 await asyncTask;
5768         }
5769
5770         private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
5771
5772         private void InitializeShortcuts()
5773         {
5774             this.shortcutCommands = new[]
5775             {
5776                 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5777                 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5778                     .FocusedOn(FocusedControl.ListTab)
5779                     .Do(() => SendKeys.Send("{DOWN}")),
5780
5781                 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5782                     .FocusedOn(FocusedControl.ListTab)
5783                     .Do(() => SendKeys.Send("{UP}")),
5784
5785                 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5786                     .FocusedOn(FocusedControl.ListTab)
5787                     .Do(() => SendKeys.Send("{PGDN}")),
5788
5789                 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5790                     .FocusedOn(FocusedControl.ListTab)
5791                     .Do(() => SendKeys.Send("{PGUP}")),
5792
5793                 ShortcutCommand.Create(Keys.F1)
5794                     .Do(() => this.OpenApplicationWebsite()),
5795
5796                 ShortcutCommand.Create(Keys.F3)
5797                     .Do(() => this.MenuItemSearchNext_Click(null, null)),
5798
5799                 ShortcutCommand.Create(Keys.F5)
5800                     .Do(() => this.DoRefresh()),
5801
5802                 ShortcutCommand.Create(Keys.F6)
5803                     .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
5804
5805                 ShortcutCommand.Create(Keys.F7)
5806                     .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
5807
5808                 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5809                     .NotFocusedOn(FocusedControl.StatusText)
5810                     .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5811
5812                 ShortcutCommand.Create(Keys.G)
5813                     .NotFocusedOn(FocusedControl.StatusText)
5814                     .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5815
5816                 ShortcutCommand.Create(Keys.Right, Keys.N)
5817                     .FocusedOn(FocusedControl.ListTab)
5818                     .Do(() => this.GoRelPost(forward: true)),
5819
5820                 ShortcutCommand.Create(Keys.Left, Keys.P)
5821                     .FocusedOn(FocusedControl.ListTab)
5822                     .Do(() => this.GoRelPost(forward: false)),
5823
5824                 ShortcutCommand.Create(Keys.OemPeriod)
5825                     .FocusedOn(FocusedControl.ListTab)
5826                     .Do(() => this.GoAnchor()),
5827
5828                 ShortcutCommand.Create(Keys.I)
5829                     .FocusedOn(FocusedControl.ListTab)
5830                     .OnlyWhen(() => this.StatusText.Enabled)
5831                     .Do(() => this.StatusText.Focus()),
5832
5833                 ShortcutCommand.Create(Keys.Enter)
5834                     .FocusedOn(FocusedControl.ListTab)
5835                     .Do(() => this.MakeReplyOrDirectStatus()),
5836
5837                 ShortcutCommand.Create(Keys.R)
5838                     .FocusedOn(FocusedControl.ListTab)
5839                     .Do(() => this.DoRefresh()),
5840
5841                 ShortcutCommand.Create(Keys.L)
5842                     .FocusedOn(FocusedControl.ListTab)
5843                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5844
5845                 ShortcutCommand.Create(Keys.H)
5846                     .FocusedOn(FocusedControl.ListTab)
5847                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5848
5849                 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5850                     .FocusedOn(FocusedControl.ListTab)
5851                     .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5852
5853                 ShortcutCommand.Create(Keys.S)
5854                     .FocusedOn(FocusedControl.ListTab)
5855                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5856
5857                 ShortcutCommand.Create(Keys.A)
5858                     .FocusedOn(FocusedControl.ListTab)
5859                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5860
5861                 // ] in_reply_to参照元へ戻る
5862                 ShortcutCommand.Create(Keys.Oem4)
5863                     .FocusedOn(FocusedControl.ListTab)
5864                     .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5865
5866                 // [ in_reply_toへジャンプ
5867                 ShortcutCommand.Create(Keys.Oem6)
5868                     .FocusedOn(FocusedControl.ListTab)
5869                     .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5870
5871                 ShortcutCommand.Create(Keys.Escape)
5872                     .FocusedOn(FocusedControl.ListTab)
5873                     .Do(() => {
5874                         this._anchorFlag = false;
5875                         var tab = this.CurrentTab;
5876                         var tabtype = tab.TabType;
5877                         if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5878                         {
5879                             RemoveSpecifiedTab(tab.TabName, false);
5880                             SaveConfigsTabs();
5881                         }
5882                     }),
5883
5884                 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5885                 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5886                     .FocusedOn(FocusedControl.ListTab)
5887                     .Do(() => this._anchorFlag = false, preventDefault: false),
5888
5889                 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5890                 ShortcutCommand.Create(Keys.Up, Keys.Down)
5891                     .FocusedOn(FocusedControl.PostBrowser)
5892                     .Do(() => { }),
5893
5894                 ShortcutCommand.Create(Keys.Control | Keys.R)
5895                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5896
5897                 ShortcutCommand.Create(Keys.Control | Keys.D)
5898                     .Do(() => this.doStatusDelete()),
5899
5900                 ShortcutCommand.Create(Keys.Control | Keys.M)
5901                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5902
5903                 ShortcutCommand.Create(Keys.Control | Keys.S)
5904                     .Do(() => this.FavoriteChange(FavAdd: true)),
5905
5906                 ShortcutCommand.Create(Keys.Control | Keys.I)
5907                     .Do(() => this.doRepliedStatusOpen()),
5908
5909                 ShortcutCommand.Create(Keys.Control | Keys.Q)
5910                     .Do(() => this.doQuoteOfficial()),
5911
5912                 ShortcutCommand.Create(Keys.Control | Keys.B)
5913                     .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5914
5915                 ShortcutCommand.Create(Keys.Control | Keys.T)
5916                     .Do(() => this.HashManageMenuItem_Click(null, null)),
5917
5918                 ShortcutCommand.Create(Keys.Control | Keys.L)
5919                     .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5920
5921                 ShortcutCommand.Create(Keys.Control | Keys.Y)
5922                     .NotFocusedOn(FocusedControl.PostBrowser)
5923                     .Do(() => this.MultiLineMenuItem_Click(null, null)),
5924
5925                 ShortcutCommand.Create(Keys.Control | Keys.F)
5926                     .Do(() => this.MenuItemSubSearch_Click(null, null)),
5927
5928                 ShortcutCommand.Create(Keys.Control | Keys.U)
5929                     .Do(() => this.ShowUserTimeline()),
5930
5931                 ShortcutCommand.Create(Keys.Control | Keys.H)
5932                     .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5933
5934                 ShortcutCommand.Create(Keys.Control | Keys.G)
5935                     .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
5936
5937                 ShortcutCommand.Create(Keys.Control | Keys.O)
5938                     .Do(() => this.StatusOpenMenuItem_Click(null, null)),
5939
5940                 ShortcutCommand.Create(Keys.Control | Keys.E)
5941                     .Do(() => this.OpenURLMenuItem_Click(null, null)),
5942
5943                 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5944                     .FocusedOn(FocusedControl.ListTab)
5945                     .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
5946
5947                 ShortcutCommand.Create(Keys.Control | Keys.N)
5948                     .FocusedOn(FocusedControl.ListTab)
5949                     .Do(() => this.GoNextTab(forward: true)),
5950
5951                 ShortcutCommand.Create(Keys.Control | Keys.P)
5952                     .FocusedOn(FocusedControl.ListTab)
5953                     .Do(() => this.GoNextTab(forward: false)),
5954
5955                 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
5956                     .FocusedOn(FocusedControl.ListTab)
5957                     .Do(() => this.CopyStot()),
5958
5959                 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
5960                 ShortcutCommand.Create(Keys.Control | Keys.D1)
5961                     .FocusedOn(FocusedControl.ListTab)
5962                     .OnlyWhen(() => this._statuses.Tabs.Count >= 1)
5963                     .Do(() => this.ListTab.SelectedIndex = 0),
5964
5965                 ShortcutCommand.Create(Keys.Control | Keys.D2)
5966                     .FocusedOn(FocusedControl.ListTab)
5967                     .OnlyWhen(() => this._statuses.Tabs.Count >= 2)
5968                     .Do(() => this.ListTab.SelectedIndex = 1),
5969
5970                 ShortcutCommand.Create(Keys.Control | Keys.D3)
5971                     .FocusedOn(FocusedControl.ListTab)
5972                     .OnlyWhen(() => this._statuses.Tabs.Count >= 3)
5973                     .Do(() => this.ListTab.SelectedIndex = 2),
5974
5975                 ShortcutCommand.Create(Keys.Control | Keys.D4)
5976                     .FocusedOn(FocusedControl.ListTab)
5977                     .OnlyWhen(() => this._statuses.Tabs.Count >= 4)
5978                     .Do(() => this.ListTab.SelectedIndex = 3),
5979
5980                 ShortcutCommand.Create(Keys.Control | Keys.D5)
5981                     .FocusedOn(FocusedControl.ListTab)
5982                     .OnlyWhen(() => this._statuses.Tabs.Count >= 5)
5983                     .Do(() => this.ListTab.SelectedIndex = 4),
5984
5985                 ShortcutCommand.Create(Keys.Control | Keys.D6)
5986                     .FocusedOn(FocusedControl.ListTab)
5987                     .OnlyWhen(() => this._statuses.Tabs.Count >= 6)
5988                     .Do(() => this.ListTab.SelectedIndex = 5),
5989
5990                 ShortcutCommand.Create(Keys.Control | Keys.D7)
5991                     .FocusedOn(FocusedControl.ListTab)
5992                     .OnlyWhen(() => this._statuses.Tabs.Count >= 7)
5993                     .Do(() => this.ListTab.SelectedIndex = 6),
5994
5995                 ShortcutCommand.Create(Keys.Control | Keys.D8)
5996                     .FocusedOn(FocusedControl.ListTab)
5997                     .OnlyWhen(() => this._statuses.Tabs.Count >= 8)
5998                     .Do(() => this.ListTab.SelectedIndex = 7),
5999
6000                 ShortcutCommand.Create(Keys.Control | Keys.D9)
6001                     .FocusedOn(FocusedControl.ListTab)
6002                     .Do(() => this.ListTab.SelectedIndex = this._statuses.Tabs.Count - 1),
6003
6004                 ShortcutCommand.Create(Keys.Control | Keys.A)
6005                     .FocusedOn(FocusedControl.StatusText)
6006                     .Do(() => this.StatusText.SelectAll()),
6007
6008                 ShortcutCommand.Create(Keys.Control | Keys.V)
6009                     .FocusedOn(FocusedControl.StatusText)
6010                     .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6011
6012                 ShortcutCommand.Create(Keys.Control | Keys.Up)
6013                     .FocusedOn(FocusedControl.StatusText)
6014                     .Do(() => this.StatusTextHistoryBack()),
6015
6016                 ShortcutCommand.Create(Keys.Control | Keys.Down)
6017                     .FocusedOn(FocusedControl.StatusText)
6018                     .Do(() => this.StatusTextHistoryForward()),
6019
6020                 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6021                     .FocusedOn(FocusedControl.StatusText)
6022                     .Do(() => {
6023                         if (ListTab.SelectedIndex == 0)
6024                         {
6025                             ListTab.SelectedIndex = ListTab.TabCount - 1;
6026                         }
6027                         else
6028                         {
6029                             ListTab.SelectedIndex -= 1;
6030                         }
6031                         StatusText.Focus();
6032                     }),
6033
6034                 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6035                     .FocusedOn(FocusedControl.StatusText)
6036                     .Do(() => {
6037                         if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6038                         {
6039                             ListTab.SelectedIndex = 0;
6040                         }
6041                         else
6042                         {
6043                             ListTab.SelectedIndex += 1;
6044                         }
6045                         StatusText.Focus();
6046                     }),
6047
6048                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6049                     .FocusedOn(FocusedControl.PostBrowser)
6050                     .Do(() => {
6051                         var multiline = !SettingManager.Local.StatusMultiline;
6052                         SettingManager.Local.StatusMultiline = multiline;
6053                         MultiLineMenuItem.Checked = multiline;
6054                         MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
6055                     }),
6056
6057                 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6058                     .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6059
6060                 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6061                     .Do(() => this.DoRefreshMore()),
6062
6063                 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6064                     .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
6065
6066                 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6067                     .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
6068
6069                 ShortcutCommand.Create(Keys.Shift | Keys.R)
6070                     .NotFocusedOn(FocusedControl.StatusText)
6071                     .Do(() => this.DoRefreshMore()),
6072
6073                 ShortcutCommand.Create(Keys.Shift | Keys.H)
6074                     .FocusedOn(FocusedControl.ListTab)
6075                     .Do(() => this.GoTopEnd(GoTop: true)),
6076
6077                 ShortcutCommand.Create(Keys.Shift | Keys.L)
6078                     .FocusedOn(FocusedControl.ListTab)
6079                     .Do(() => this.GoTopEnd(GoTop: false)),
6080
6081                 ShortcutCommand.Create(Keys.Shift | Keys.M)
6082                     .FocusedOn(FocusedControl.ListTab)
6083                     .Do(() => this.GoMiddle()),
6084
6085                 ShortcutCommand.Create(Keys.Shift | Keys.G)
6086                     .FocusedOn(FocusedControl.ListTab)
6087                     .Do(() => this.GoLast()),
6088
6089                 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6090                     .FocusedOn(FocusedControl.ListTab)
6091                     .Do(() => this.MoveMiddle()),
6092
6093                 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6094                     .FocusedOn(FocusedControl.ListTab)
6095                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6096
6097                 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6098                     .FocusedOn(FocusedControl.ListTab)
6099                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6100
6101                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6102                 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6103                     .FocusedOn(FocusedControl.ListTab)
6104                     .Do(() => this.GoFav(forward: true)),
6105
6106                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6107                 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6108                     .FocusedOn(FocusedControl.ListTab)
6109                     .Do(() => this.GoFav(forward: false)),
6110
6111                 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6112                     .FocusedOn(FocusedControl.ListTab)
6113                     .Do(() => this.GoBackSelectPostChain()),
6114
6115                 ShortcutCommand.Create(Keys.Alt | Keys.R)
6116                     .Do(() => this.doReTweetOfficial(isConfirm: true)),
6117
6118                 ShortcutCommand.Create(Keys.Alt | Keys.P)
6119                     .OnlyWhen(() => this.CurrentPost != null)
6120                     .Do(() => this.doShowUserStatus(this.CurrentPost.ScreenName, ShowInputDialog: false)),
6121
6122                 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6123                     .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6124
6125                 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6126                     .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6127
6128                 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6129                     .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6130
6131                 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6132                     .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6133
6134                 // 別タブの同じ書き込みへ(ALT+←/→)
6135                 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6136                     .FocusedOn(FocusedControl.ListTab)
6137                     .Do(() => this.GoSamePostToAnotherTab(left: false)),
6138
6139                 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6140                     .FocusedOn(FocusedControl.ListTab)
6141                     .Do(() => this.GoSamePostToAnotherTab(left: true)),
6142
6143                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6144                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6145
6146                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6147                     .Do(() => this.CopyIdUri()),
6148
6149                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6150                     .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
6151                     .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6152
6153                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6154                     .Do(() => this.FavoriteChange(FavAdd: false)),
6155
6156                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6157                     .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6158
6159                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6160                     .Do(() => this.HashToggleMenuItem_Click(null, null)),
6161
6162                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6163                     .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6164
6165                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6166                     .Do(() => this.doMoveToRTHome()),
6167
6168                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6169                     .FocusedOn(FocusedControl.StatusText)
6170                     .Do(() => {
6171                         var tab = this.CurrentTab;
6172                         var selectedIndex = tab.SelectedIndex;
6173                         if (selectedIndex != -1 && selectedIndex > 0)
6174                         {
6175                             var listView = this.CurrentListView;
6176                             var idx = selectedIndex - 1;
6177                             SelectListItem(listView, idx);
6178                             listView.EnsureVisible(idx);
6179                         }
6180                     }),
6181
6182                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6183                     .FocusedOn(FocusedControl.StatusText)
6184                     .Do(() => {
6185                         var tab = this.CurrentTab;
6186                         var selectedIndex = tab.SelectedIndex;
6187                         if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
6188                         {
6189                             var listView = this.CurrentListView;
6190                             var idx = selectedIndex + 1;
6191                             SelectListItem(listView, idx);
6192                             listView.EnsureVisible(idx);
6193                         }
6194                     }),
6195
6196                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6197                     .FocusedOn(FocusedControl.StatusText)
6198                     .Do(() => {
6199                         if (StatusText.SelectionStart > 0)
6200                         {
6201                             var endidx = StatusText.SelectionStart - 1;
6202                             var startstr = "";
6203                             for (var i = StatusText.SelectionStart - 1; i >= 0; i--)
6204                             {
6205                                 var c = StatusText.Text[i];
6206                                 if (char.IsLetterOrDigit(c) || c == '_')
6207                                 {
6208                                     continue;
6209                                 }
6210                                 if (c == '@')
6211                                 {
6212                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6213                                     var cnt = AtIdSupl.ItemCount;
6214                                     ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6215                                     if (AtIdSupl.ItemCount != cnt)
6216                                         this.MarkSettingAtIdModified();
6217                                 }
6218                                 else if (c == '#')
6219                                 {
6220                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6221                                     ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6222                                 }
6223                                 else
6224                                 {
6225                                     break;
6226                                 }
6227                             }
6228                         }
6229                     }),
6230
6231                 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6232                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6233                     .FocusedOn(FocusedControl.ListTab)
6234                     .Do(() => this.SetSortColumnByDisplayIndex(0)),
6235
6236                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6237                     .FocusedOn(FocusedControl.ListTab)
6238                     .Do(() => this.SetSortColumnByDisplayIndex(1)),
6239
6240                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6241                     .FocusedOn(FocusedControl.ListTab)
6242                     .Do(() => this.SetSortColumnByDisplayIndex(2)),
6243
6244                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6245                     .FocusedOn(FocusedControl.ListTab)
6246                     .Do(() => this.SetSortColumnByDisplayIndex(3)),
6247
6248                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6249                     .FocusedOn(FocusedControl.ListTab)
6250                     .Do(() => this.SetSortColumnByDisplayIndex(4)),
6251
6252                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6253                     .FocusedOn(FocusedControl.ListTab)
6254                     .Do(() => this.SetSortColumnByDisplayIndex(5)),
6255
6256                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6257                     .FocusedOn(FocusedControl.ListTab)
6258                     .Do(() => this.SetSortColumnByDisplayIndex(6)),
6259
6260                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6261                     .FocusedOn(FocusedControl.ListTab)
6262                     .Do(() => this.SetSortColumnByDisplayIndex(7)),
6263
6264                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6265                     .FocusedOn(FocusedControl.ListTab)
6266                     .Do(() => this.SetSortLastColumn()),
6267
6268                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6269                     .FocusedOn(FocusedControl.ListTab)
6270                     .Do(() => this.FavoritesRetweetOfficial()),
6271
6272                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6273                     .FocusedOn(FocusedControl.ListTab)
6274                     .Do(() => this.FavoritesRetweetUnofficial()),
6275
6276                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6277                     .FocusedOn(FocusedControl.ListTab)
6278                     .Do(() => this.OpenUserAppointUrl()),
6279
6280                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6281                     .FocusedOn(FocusedControl.PostBrowser)
6282                     .Do(() => this.doReTweetUnofficial()),
6283
6284                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6285                     .OnlyWhen(() => this.ExistCurrentPost)
6286                     .Do(() => this.tweetDetailsView.DoTranslation()),
6287
6288                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6289                     .Do(() => this.doReTweetUnofficial()),
6290
6291                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6292                     .Do(() => this.CopyUserId()),
6293
6294                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6295                     .Do(() => this.tweetThumbnail1.ScrollUp()),
6296
6297                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6298                     .Do(() => this.tweetThumbnail1.ScrollDown()),
6299
6300                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6301                     .FocusedOn(FocusedControl.ListTab)
6302                     .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6303                     .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6304             };
6305         }
6306
6307         internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6308         {
6309             // Task を返す非同期処理があれば asyncTask に代入する
6310             asyncTask = null;
6311
6312             // ShortcutCommand に対応しているコマンドはここで処理される
6313             foreach (var command in this.shortcutCommands)
6314             {
6315                 if (command.IsMatch(keyData, focusedOn))
6316                 {
6317                     asyncTask = command.RunCommand();
6318                     return command.PreventDefault;
6319                 }
6320             }
6321
6322             return false;
6323         }
6324
6325         private void GoNextTab(bool forward)
6326         {
6327             var idx = this._statuses.SelectedTabIndex;
6328             var tabCount = this._statuses.Tabs.Count;
6329             if (forward)
6330             {
6331                 idx += 1;
6332                 if (idx > tabCount - 1) idx = 0;
6333             }
6334             else
6335             {
6336                 idx -= 1;
6337                 if (idx < 0) idx = tabCount - 1;
6338             }
6339             ListTab.SelectedIndex = idx;
6340         }
6341
6342         private void CopyStot()
6343         {
6344             var sb = new StringBuilder();
6345             var tab = this.CurrentTab;
6346             var IsProtected = false;
6347             var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
6348             foreach (var post in tab.SelectedPosts)
6349             {
6350                 if (post.IsDeleted) continue;
6351                 if (!isDm)
6352                 {
6353                     if (post.RetweetedId != null)
6354                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6355                     else
6356                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6357                 }
6358                 else
6359                 {
6360                     sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6361                 }
6362             }
6363             if (IsProtected)
6364             {
6365                 MessageBox.Show(Properties.Resources.CopyStotText1);
6366             }
6367             if (sb.Length > 0)
6368             {
6369                 var clstr = sb.ToString();
6370                 try
6371                 {
6372                     Clipboard.SetDataObject(clstr, false, 5, 100);
6373                 }
6374                 catch (Exception ex)
6375                 {
6376                     MessageBox.Show(ex.Message);
6377                 }
6378             }
6379         }
6380
6381         private void CopyIdUri()
6382         {
6383             var tab = this.CurrentTab;
6384             if (tab == null || tab is DirectMessagesTabModel)
6385                 return;
6386
6387             var copyUrls = new List<string>();
6388             foreach (var post in tab.SelectedPosts)
6389                 copyUrls.Add(MyCommon.GetStatusUrl(post));
6390
6391             if (copyUrls.Count == 0)
6392                 return;
6393
6394             try
6395             {
6396                 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6397             }
6398             catch (ExternalException ex)
6399             {
6400                 MessageBox.Show(ex.Message);
6401             }
6402         }
6403
6404         private void GoFav(bool forward)
6405         {
6406             var tab = this.CurrentTab;
6407             if (tab.AllCount == 0)
6408                 return;
6409
6410             var selectedIndex = tab.SelectedIndex;
6411
6412             int fIdx;
6413             int toIdx;
6414             int stp;
6415
6416             if (forward)
6417             {
6418                 if (selectedIndex == -1)
6419                 {
6420                     fIdx = 0;
6421                 }
6422                 else
6423                 {
6424                     fIdx = selectedIndex + 1;
6425                     if (fIdx > tab.AllCount - 1)
6426                         return;
6427                 }
6428                 toIdx = tab.AllCount;
6429                 stp = 1;
6430             }
6431             else
6432             {
6433                 if (selectedIndex == -1)
6434                 {
6435                     fIdx = tab.AllCount - 1;
6436                 }
6437                 else
6438                 {
6439                     fIdx = selectedIndex - 1;
6440                     if (fIdx < 0)
6441                         return;
6442                 }
6443                 toIdx = -1;
6444                 stp = -1;
6445             }
6446
6447             for (var idx = fIdx; idx != toIdx; idx += stp)
6448             {
6449                 if (tab[idx].IsFav)
6450                 {
6451                     var listView = this.CurrentListView;
6452                     SelectListItem(listView, idx);
6453                     listView.EnsureVisible(idx);
6454                     break;
6455                 }
6456             }
6457         }
6458
6459         private void GoSamePostToAnotherTab(bool left)
6460         {
6461             var tab = this.CurrentTab;
6462
6463             // Directタブは対象外(見つかるはずがない)
6464             if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6465                 return;
6466
6467             var selectedStatusId = tab.SelectedStatusId;
6468             if (selectedStatusId == -1)
6469                 return;
6470
6471             int fIdx, toIdx, stp;
6472
6473             if (left)
6474             {
6475                 // 左のタブへ
6476                 if (ListTab.SelectedIndex == 0)
6477                 {
6478                     return;
6479                 }
6480                 else
6481                 {
6482                     fIdx = ListTab.SelectedIndex - 1;
6483                 }
6484                 toIdx = -1;
6485                 stp = -1;
6486             }
6487             else
6488             {
6489                 // 右のタブへ
6490                 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6491                 {
6492                     return;
6493                 }
6494                 else
6495                 {
6496                     fIdx = ListTab.SelectedIndex + 1;
6497                 }
6498                 toIdx = ListTab.TabCount;
6499                 stp = 1;
6500             }
6501
6502             for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6503             {
6504                 var targetTab = this._statuses.Tabs[tabidx];
6505
6506                 // Directタブは対象外
6507                 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6508                     continue;
6509
6510                 var foundIndex = targetTab.IndexOf(selectedStatusId);
6511                 if (foundIndex != -1)
6512                 {
6513                     ListTab.SelectedIndex = tabidx;
6514                     var listView = this.CurrentListView;
6515                     SelectListItem(listView, foundIndex);
6516                     listView.EnsureVisible(foundIndex);
6517                     return;
6518                 }
6519             }
6520         }
6521
6522         private void GoPost(bool forward)
6523         {
6524             var tab = this.CurrentTab;
6525             var currentPost = this.CurrentPost;
6526
6527             if (currentPost == null)
6528                 return;
6529
6530             var selectedIndex = tab.SelectedIndex;
6531
6532             int fIdx, toIdx, stp;
6533
6534             if (forward)
6535             {
6536                 fIdx = selectedIndex + 1;
6537                 if (fIdx > tab.AllCount - 1) return;
6538                 toIdx = tab.AllCount;
6539                 stp = 1;
6540             }
6541             else
6542             {
6543                 fIdx = selectedIndex - 1;
6544                 if (fIdx < 0) return;
6545                 toIdx = -1;
6546                 stp = -1;
6547             }
6548
6549             string name;
6550             if (currentPost.RetweetedId == null)
6551             {
6552                 name = currentPost.ScreenName;
6553             }
6554             else
6555             {
6556                 name = currentPost.RetweetedBy;
6557             }
6558             for (var idx = fIdx; idx != toIdx; idx += stp)
6559             {
6560                 var post = tab[idx];
6561                 if (post.RetweetedId == null)
6562                 {
6563                     if (post.ScreenName == name)
6564                     {
6565                         var listView = this.CurrentListView;
6566                         SelectListItem(listView, idx);
6567                         listView.EnsureVisible(idx);
6568                         break;
6569                     }
6570                 }
6571                 else
6572                 {
6573                     if (post.RetweetedBy == name)
6574                     {
6575                         var listView = this.CurrentListView;
6576                         SelectListItem(listView, idx);
6577                         listView.EnsureVisible(idx);
6578                         break;
6579                     }
6580                 }
6581             }
6582         }
6583
6584         private void GoRelPost(bool forward)
6585         {
6586             var tab = this.CurrentTab;
6587             var selectedIndex = tab.SelectedIndex;
6588
6589             if (selectedIndex == -1)
6590                 return;
6591
6592             int fIdx, toIdx, stp;
6593
6594             if (forward)
6595             {
6596                 fIdx = selectedIndex + 1;
6597                 if (fIdx > tab.AllCount - 1) return;
6598                 toIdx = tab.AllCount;
6599                 stp = 1;
6600             }
6601             else
6602             {
6603                 fIdx = selectedIndex - 1;
6604                 if (fIdx < 0) return;
6605                 toIdx = -1;
6606                 stp = -1;
6607             }
6608
6609             if (!_anchorFlag)
6610             {
6611                 var currentPost = this.CurrentPost;
6612                 if (currentPost == null) return;
6613                 _anchorPost = currentPost;
6614                 _anchorFlag = true;
6615             }
6616             else
6617             {
6618                 if (_anchorPost == null) return;
6619             }
6620
6621             for (var idx = fIdx; idx != toIdx; idx += stp)
6622             {
6623                 var post = tab[idx];
6624                 if (post.ScreenName == _anchorPost.ScreenName ||
6625                     post.RetweetedBy == _anchorPost.ScreenName ||
6626                     post.ScreenName == _anchorPost.RetweetedBy ||
6627                     (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6628                     _anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
6629                     _anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
6630                     post.ReplyToList.Any(x => x.UserId == _anchorPost.UserId) ||
6631                     post.ReplyToList.Any(x => x.UserId == _anchorPost.RetweetedByUserId))
6632                 {
6633                     var listView = this.CurrentListView;
6634                     SelectListItem(listView, idx);
6635                     listView.EnsureVisible(idx);
6636                     break;
6637                 }
6638             }
6639         }
6640
6641         private void GoAnchor()
6642         {
6643             if (_anchorPost == null) return;
6644             var idx = this.CurrentTab.IndexOf(_anchorPost.StatusId);
6645             if (idx == -1) return;
6646
6647             var listView = this.CurrentListView;
6648             SelectListItem(listView, idx);
6649             listView.EnsureVisible(idx);
6650         }
6651
6652         private void GoTopEnd(bool GoTop)
6653         {
6654             var listView = this.CurrentListView;
6655             if (listView.VirtualListSize == 0)
6656                 return;
6657
6658             ListViewItem _item;
6659             int idx;
6660
6661             if (GoTop)
6662             {
6663                 _item = listView.GetItemAt(0, 25);
6664                 if (_item == null)
6665                     idx = 0;
6666                 else
6667                     idx = _item.Index;
6668             }
6669             else
6670             {
6671                 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6672                 if (_item == null)
6673                     idx = listView.VirtualListSize - 1;
6674                 else
6675                     idx = _item.Index;
6676             }
6677             SelectListItem(listView, idx);
6678         }
6679
6680         private void GoMiddle()
6681         {
6682             var listView = this.CurrentListView;
6683             if (listView.VirtualListSize == 0)
6684                 return;
6685
6686             ListViewItem _item;
6687             int idx1;
6688             int idx2;
6689             int idx3;
6690
6691             _item = listView.GetItemAt(0, 0);
6692             if (_item == null)
6693             {
6694                 idx1 = 0;
6695             }
6696             else
6697             {
6698                 idx1 = _item.Index;
6699             }
6700
6701             _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6702             if (_item == null)
6703             {
6704                 idx2 = listView.VirtualListSize - 1;
6705             }
6706             else
6707             {
6708                 idx2 = _item.Index;
6709             }
6710             idx3 = (idx1 + idx2) / 2;
6711
6712             SelectListItem(listView, idx3);
6713         }
6714
6715         private void GoLast()
6716         {
6717             var listView = this.CurrentListView;
6718             if (listView.VirtualListSize == 0) return;
6719
6720             if (_statuses.SortOrder == SortOrder.Ascending)
6721             {
6722                 SelectListItem(listView, listView.VirtualListSize - 1);
6723                 listView.EnsureVisible(listView.VirtualListSize - 1);
6724             }
6725             else
6726             {
6727                 SelectListItem(listView, 0);
6728                 listView.EnsureVisible(0);
6729             }
6730         }
6731
6732         private void MoveTop()
6733         {
6734             var listView = this.CurrentListView;
6735             if (listView.SelectedIndices.Count == 0) return;
6736             var idx = listView.SelectedIndices[0];
6737             if (_statuses.SortOrder == SortOrder.Ascending)
6738             {
6739                 listView.EnsureVisible(listView.VirtualListSize - 1);
6740             }
6741             else
6742             {
6743                 listView.EnsureVisible(0);
6744             }
6745             listView.EnsureVisible(idx);
6746         }
6747
6748         private async Task GoInReplyToPostTree()
6749         {
6750             var curTabClass = this.CurrentTab;
6751             var currentPost = this.CurrentPost;
6752
6753             if (currentPost == null)
6754                 return;
6755
6756             if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
6757             {
6758                 try
6759                 {
6760                     var post = await tw.GetStatusApi(false, currentPost.StatusId);
6761
6762                     currentPost.InReplyToStatusId = post.InReplyToStatusId;
6763                     currentPost.InReplyToUser = post.InReplyToUser;
6764                     currentPost.IsReply = post.IsReply;
6765                     this.PurgeListViewItemCache();
6766
6767                     var index = curTabClass.SelectedIndex;
6768                     this.CurrentListView.RedrawItems(index, index, false);
6769                 }
6770                 catch (WebApiException ex)
6771                 {
6772                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6773                 }
6774             }
6775
6776             if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
6777
6778             if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != currentPost.StatusId))
6779             {
6780                 replyChains = new Stack<ReplyChain>();
6781             }
6782             replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId.Value, curTabClass));
6783
6784             int inReplyToIndex;
6785             string inReplyToTabName;
6786             var inReplyToId = currentPost.InReplyToStatusId.Value;
6787             var inReplyToUser = currentPost.InReplyToUser;
6788
6789             var inReplyToPosts = from tab in _statuses.Tabs
6790                                  orderby tab != curTabClass
6791                                  from post in tab.Posts.Values
6792                                  where post.StatusId == inReplyToId
6793                                  let index = tab.IndexOf(post.StatusId)
6794                                  where index != -1
6795                                  select new {Tab = tab, Index = index};
6796
6797             var inReplyPost = inReplyToPosts.FirstOrDefault();
6798             if (inReplyPost == null)
6799             {
6800                 try
6801                 {
6802                     await Task.Run(async () =>
6803                     {
6804                         var post = await tw.GetStatusApi(false, currentPost.InReplyToStatusId.Value)
6805                             .ConfigureAwait(false);
6806                         post.IsRead = true;
6807
6808                         _statuses.AddPost(post);
6809                         _statuses.DistributePosts();
6810                     });
6811                 }
6812                 catch (WebApiException ex)
6813                 {
6814                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6815                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6816                     return;
6817                 }
6818
6819                 this.RefreshTimeline();
6820
6821                 inReplyPost = inReplyToPosts.FirstOrDefault();
6822                 if (inReplyPost == null)
6823                 {
6824                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6825                     return;
6826                 }
6827             }
6828             inReplyToTabName = inReplyPost.Tab.TabName;
6829             inReplyToIndex = inReplyPost.Index;
6830
6831             var tabIndex = this._statuses.Tabs.IndexOf(inReplyToTabName);
6832             var tabPage = this.ListTab.TabPages[tabIndex];
6833             var listView = (DetailsListView)tabPage.Tag;
6834
6835             if (this.CurrentTabName != inReplyToTabName)
6836             {
6837                 this.ListTab.SelectedIndex = tabIndex;
6838             }
6839
6840             this.SelectListItem(listView, inReplyToIndex);
6841             listView.EnsureVisible(inReplyToIndex);
6842         }
6843
6844         private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6845         {
6846             var curTabClass = this.CurrentTab;
6847             var currentPost = this.CurrentPost;
6848
6849             if (currentPost == null)
6850                 return;
6851
6852             if (parallel)
6853             {
6854                 if (currentPost.InReplyToStatusId != null)
6855                 {
6856                     var posts = from t in _statuses.Tabs
6857                                 from p in t.Posts
6858                                 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
6859                                 let indexOf = t.IndexOf(p.Value.StatusId)
6860                                 where indexOf > -1
6861                                 orderby isForward ? indexOf : indexOf * -1
6862                                 orderby t != curTabClass
6863                                 select new {Tab = t, Post = p.Value, Index = indexOf};
6864                     try
6865                     {
6866                         var postList = posts.ToList();
6867                         for (var i = postList.Count - 1; i >= 0; i--)
6868                         {
6869                             var index = i;
6870                             if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
6871                             {
6872                                 postList.RemoveAt(index);
6873                             }
6874                         }
6875                         var currentIndex = this.CurrentTab.SelectedIndex;
6876                         var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
6877                         if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
6878                         if (post == null) post = postList.First();
6879                         var tabIndex = this._statuses.Tabs.IndexOf(post.Tab);
6880                         this.ListTab.SelectedIndex = tabIndex;
6881                         var listView = this.CurrentListView;
6882                         SelectListItem(listView, post.Index);
6883                         listView.EnsureVisible(post.Index);
6884                     }
6885                     catch (InvalidOperationException)
6886                     {
6887                         return;
6888                     }
6889                 }
6890             }
6891             else
6892             {
6893                 if (replyChains == null || replyChains.Count < 1)
6894                 {
6895                     var posts = from t in _statuses.Tabs
6896                                 from p in t.Posts
6897                                 where p.Value.InReplyToStatusId == currentPost.StatusId
6898                                 let indexOf = t.IndexOf(p.Value.StatusId)
6899                                 where indexOf > -1
6900                                 orderby indexOf
6901                                 orderby t != curTabClass
6902                                 select new {Tab = t, Index = indexOf};
6903                     try
6904                     {
6905                         var post = posts.First();
6906                         var tabIndex = this._statuses.Tabs.IndexOf(post.Tab);
6907                         this.ListTab.SelectedIndex = tabIndex;
6908                         var listView = this.CurrentListView;
6909                         SelectListItem(listView, post.Index);
6910                         listView.EnsureVisible(post.Index);
6911                     }
6912                     catch (InvalidOperationException)
6913                     {
6914                         return;
6915                     }
6916                 }
6917                 else
6918                 {
6919                     var chainHead = replyChains.Pop();
6920                     if (chainHead.InReplyToId == currentPost.StatusId)
6921                     {
6922                         var tab = chainHead.OriginalTab;
6923                         if (!this._statuses.Tabs.Contains(tab))
6924                         {
6925                             replyChains = null;
6926                         }
6927                         else
6928                         {
6929                             var idx = tab.IndexOf(chainHead.OriginalId);
6930                             if (idx == -1)
6931                             {
6932                                 replyChains = null;
6933                             }
6934                             else
6935                             {
6936                                 var tabIndex = this._statuses.Tabs.IndexOf(tab);
6937                                 try
6938                                 {
6939                                     this.ListTab.SelectedIndex = tabIndex;
6940                                 }
6941                                 catch (Exception)
6942                                 {
6943                                     replyChains = null;
6944                                 }
6945                                 var listView = this.CurrentListView;
6946                                 SelectListItem(listView, idx);
6947                                 listView.EnsureVisible(idx);
6948                             }
6949                         }
6950                     }
6951                     else
6952                     {
6953                         replyChains = null;
6954                         this.GoBackInReplyToPostTree(parallel);
6955                     }
6956                 }
6957             }
6958         }
6959
6960         private void GoBackSelectPostChain()
6961         {
6962             if (this.selectPostChains.Count > 1)
6963             {
6964                 var idx = -1;
6965                 TabModel foundTab = null;
6966
6967                 do
6968                 {
6969                     try
6970                     {
6971                         this.selectPostChains.Pop();
6972                         var (tab, post) = this.selectPostChains.Peek();
6973
6974                         if (!this._statuses.Tabs.Contains(tab))
6975                             continue; // 該当タブが存在しないので無視
6976
6977                         if (post != null)
6978                         {
6979                             idx = tab.IndexOf(post.StatusId);
6980                             if (idx == -1) continue;  //該当ポストが存在しないので無視
6981                         }
6982
6983                         foundTab = tab;
6984
6985                         this.selectPostChains.Pop();
6986                     }
6987                     catch (InvalidOperationException)
6988                     {
6989                     }
6990
6991                     break;
6992                 }
6993                 while (this.selectPostChains.Count > 1);
6994
6995                 if (foundTab == null)
6996                 {
6997                     //状態がおかしいので処理を中断
6998                     //履歴が残り1つであればクリアしておく
6999                     if (this.selectPostChains.Count == 1)
7000                         this.selectPostChains.Clear();
7001                     return;
7002                 }
7003
7004                 var tabIndex = this._statuses.Tabs.IndexOf(foundTab);
7005                 var tabPage = this.ListTab.TabPages[tabIndex];
7006                 var lst = (DetailsListView)tabPage.Tag;
7007                 this.ListTab.SelectedIndex = tabIndex;
7008
7009                 if (idx > -1)
7010                 {
7011                     SelectListItem(lst, idx);
7012                     lst.EnsureVisible(idx);
7013                 }
7014                 lst.Focus();
7015             }
7016         }
7017
7018         private void PushSelectPostChain()
7019         {
7020             var currentTab = this.CurrentTab;
7021             var currentPost = this.CurrentPost;
7022
7023             var count = this.selectPostChains.Count;
7024             if (count > 0)
7025             {
7026                 var (tab, post) = this.selectPostChains.Peek();
7027                 if (tab == currentTab)
7028                 {
7029                     if (post == currentPost) return;  //最新の履歴と同一
7030                     if (post == null) this.selectPostChains.Pop();  //置き換えるため削除
7031                 }
7032             }
7033             if (count >= 2500) TrimPostChain();
7034             this.selectPostChains.Push((currentTab, currentPost));
7035         }
7036
7037         private void TrimPostChain()
7038         {
7039             if (this.selectPostChains.Count <= 2000) return;
7040             var p = new Stack<(TabModel, PostClass)>(2000);
7041             for (var i = 0; i < 2000; i++)
7042             {
7043                 p.Push(this.selectPostChains.Pop());
7044             }
7045             this.selectPostChains.Clear();
7046             for (var i = 0; i < 2000; i++)
7047             {
7048                 this.selectPostChains.Push(p.Pop());
7049             }
7050         }
7051
7052         private bool GoStatus(long statusId)
7053         {
7054             if (statusId == 0) return false;
7055
7056             var tab = this._statuses.Tabs
7057                 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
7058                 .Where(x => x.Contains(statusId))
7059                 .FirstOrDefault();
7060
7061             if (tab == null)
7062                 return false;
7063
7064             var index = tab.IndexOf(statusId);
7065
7066             var tabIndex = this._statuses.Tabs.IndexOf(tab);
7067             this.ListTab.SelectedIndex = tabIndex;
7068
7069             var listView = this.CurrentListView;
7070             this.SelectListItem(listView, index);
7071             listView.EnsureVisible(index);
7072
7073             return true;
7074         }
7075
7076         private bool GoDirectMessage(long statusId)
7077         {
7078             if (statusId == 0) return false;
7079
7080             var tab = this._statuses.GetTabByType<DirectMessagesTabModel>();
7081             var index = tab.IndexOf(statusId);
7082
7083             if (index == -1)
7084                 return false;
7085
7086             var tabIndex = this._statuses.Tabs.IndexOf(tab);
7087             this.ListTab.SelectedIndex = tabIndex;
7088
7089             var listView = this.CurrentListView;
7090             this.SelectListItem(listView, index);
7091             listView.EnsureVisible(index);
7092
7093             return true;
7094         }
7095
7096         private void MyList_MouseClick(object sender, MouseEventArgs e)
7097             => this._anchorFlag = false;
7098
7099         private void StatusText_Enter(object sender, EventArgs e)
7100         {
7101             // フォーカスの戻り先を StatusText に設定
7102             this.Tag = StatusText;
7103             StatusText.BackColor = _clInputBackcolor;
7104         }
7105
7106         public Color InputBackColor
7107         {
7108             get => _clInputBackcolor;
7109             set => _clInputBackcolor = value;
7110         }
7111
7112         private void StatusText_Leave(object sender, EventArgs e)
7113         {
7114             // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7115             if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7116             StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7117         }
7118
7119         private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7120         {
7121             if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
7122             {
7123                 e.Handled = true;
7124                 e.SuppressKeyPress = true;
7125             }
7126
7127             this.StatusText_TextChanged(null, null);
7128
7129             if (asyncTask != null)
7130                 await asyncTask;
7131         }
7132
7133         private void SaveConfigsAll(bool ifModified)
7134         {
7135             if (!ifModified)
7136             {
7137                 SaveConfigsCommon();
7138                 SaveConfigsLocal();
7139                 SaveConfigsTabs();
7140                 SaveConfigsAtId();
7141             }
7142             else
7143             {
7144                 if (ModifySettingCommon) SaveConfigsCommon();
7145                 if (ModifySettingLocal) SaveConfigsLocal();
7146                 if (ModifySettingAtId) SaveConfigsAtId();
7147             }
7148         }
7149
7150         private void SaveConfigsAtId()
7151         {
7152             if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7153
7154             ModifySettingAtId = false;
7155             SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7156             SettingManager.SaveAtIdList();
7157         }
7158
7159         private void SaveConfigsCommon()
7160         {
7161             if (_ignoreConfigSave) return;
7162
7163             ModifySettingCommon = false;
7164             lock (_syncObject)
7165             {
7166                 SettingManager.Common.UserName = tw.Username;
7167                 SettingManager.Common.UserId = tw.UserId;
7168                 SettingManager.Common.Token = tw.AccessToken;
7169                 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7170                 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7171                 switch (_statuses.SortMode)
7172                 {
7173                     case ComparerMode.Nickname:  //ニックネーム
7174                         SettingManager.Common.SortColumn = 1;
7175                         break;
7176                     case ComparerMode.Data:  //本文
7177                         SettingManager.Common.SortColumn = 2;
7178                         break;
7179                     case ComparerMode.Id:  //時刻=発言Id
7180                         SettingManager.Common.SortColumn = 3;
7181                         break;
7182                     case ComparerMode.Name:  //名前
7183                         SettingManager.Common.SortColumn = 4;
7184                         break;
7185                     case ComparerMode.Source:  //Source
7186                         SettingManager.Common.SortColumn = 7;
7187                         break;
7188                 }
7189
7190                 SettingManager.Common.HashTags = HashMgr.HashHistories;
7191                 if (HashMgr.IsPermanent)
7192                 {
7193                     SettingManager.Common.HashSelected = HashMgr.UseHash;
7194                 }
7195                 else
7196                 {
7197                     SettingManager.Common.HashSelected = "";
7198                 }
7199                 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7200                 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7201                 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7202                 SettingManager.Common.TrackWord = tw.TrackWord;
7203                 SettingManager.Common.AllAtReply = tw.AllAtReply;
7204                 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7205                 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7206
7207                 SettingManager.SaveCommon();
7208             }
7209         }
7210
7211         private void SaveConfigsLocal()
7212         {
7213             if (_ignoreConfigSave) return;
7214             lock (_syncObject)
7215             {
7216                 ModifySettingLocal = false;
7217                 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7218                 SettingManager.Local.FormSize = _mySize;
7219                 SettingManager.Local.FormLocation = _myLoc;
7220                 SettingManager.Local.SplitterDistance = _mySpDis;
7221                 SettingManager.Local.PreviewDistance = _mySpDis3;
7222                 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7223                 SettingManager.Local.StatusTextHeight = _mySpDis2;
7224
7225                 SettingManager.Local.FontUnread = _fntUnread;
7226                 SettingManager.Local.ColorUnread = _clUnread;
7227                 SettingManager.Local.FontRead = _fntReaded;
7228                 SettingManager.Local.ColorRead = _clReaded;
7229                 SettingManager.Local.FontDetail = _fntDetail;
7230                 SettingManager.Local.ColorDetail = _clDetail;
7231                 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7232                 SettingManager.Local.ColorDetailLink = _clDetailLink;
7233                 SettingManager.Local.ColorFav = _clFav;
7234                 SettingManager.Local.ColorOWL = _clOWL;
7235                 SettingManager.Local.ColorRetweet = _clRetweet;
7236                 SettingManager.Local.ColorSelf = _clSelf;
7237                 SettingManager.Local.ColorAtSelf = _clAtSelf;
7238                 SettingManager.Local.ColorTarget = _clTarget;
7239                 SettingManager.Local.ColorAtTarget = _clAtTarget;
7240                 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7241                 SettingManager.Local.ColorAtTo = _clAtTo;
7242                 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7243                 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7244                 SettingManager.Local.ColorInputFont = _clInputFont;
7245                 SettingManager.Local.FontInputFont = _fntInputFont;
7246
7247                 if (_ignoreConfigSave) return;
7248                 SettingManager.SaveLocal();
7249             }
7250         }
7251
7252         private void SaveConfigsTabs()
7253         {
7254             var tabSettingList = new List<SettingTabs.SettingTabItem>();
7255
7256             var tabs = this._statuses.Tabs.Append(this._statuses.MuteTab);
7257
7258             foreach (var tab in tabs)
7259             {
7260                 if (!tab.IsPermanentTabType)
7261                     continue;
7262
7263                 var tabSetting = new SettingTabs.SettingTabItem
7264                 {
7265                     TabName = tab.TabName,
7266                     TabType = tab.TabType,
7267                     UnreadManage = tab.UnreadManage,
7268                     Protected = tab.Protected,
7269                     Notify = tab.Notify,
7270                     SoundFile = tab.SoundFile,
7271                 };
7272
7273                 switch (tab)
7274                 {
7275                     case FilterTabModel filterTab:
7276                         tabSetting.FilterArray = filterTab.FilterArray;
7277                         break;
7278                     case UserTimelineTabModel userTab:
7279                         tabSetting.User = userTab.ScreenName;
7280                         break;
7281                     case PublicSearchTabModel searchTab:
7282                         tabSetting.SearchWords = searchTab.SearchWords;
7283                         tabSetting.SearchLang = searchTab.SearchLang;
7284                         break;
7285                     case ListTimelineTabModel listTab:
7286                         tabSetting.ListInfo = listTab.ListInfo;
7287                         break;
7288                 }
7289
7290                 tabSettingList.Add(tabSetting);
7291             }
7292
7293             SettingManager.Tabs.Tabs = tabSettingList;
7294             SettingManager.SaveTabs();
7295         }
7296
7297         private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7298         {
7299             var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
7300             if (ret != DialogResult.OK)
7301                 return;
7302
7303             var match = Twitter.StatusUrlRegex.Match(inputText);
7304             if (!match.Success)
7305             {
7306                 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7307                     Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7308                 return;
7309             }
7310
7311             try
7312             {
7313                 var statusId = long.Parse(match.Groups["StatusId"].Value);
7314                 await this.OpenRelatedTab(statusId);
7315             }
7316             catch (TabException ex)
7317             {
7318                 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7319             }
7320         }
7321
7322         private void SaveLogMenuItem_Click(object sender, EventArgs e)
7323         {
7324             var tab = this.CurrentTab;
7325
7326             var rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7327                     Properties.Resources.SaveLogMenuItem_ClickText2,
7328                     MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7329             if (rslt == DialogResult.Cancel) return;
7330
7331             SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
7332             SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7333             SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7334             SaveFileDialog1.FilterIndex = 0;
7335             SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7336             SaveFileDialog1.RestoreDirectory = true;
7337
7338             if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7339             {
7340                 if (!SaveFileDialog1.ValidateNames) return;
7341                 using var sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8);
7342                 if (rslt == DialogResult.Yes)
7343                 {
7344                     //All
7345                     for (var idx = 0; idx < tab.AllCount; idx++)
7346                     {
7347                         var post = tab[idx];
7348                         var protect = "";
7349                         if (post.IsProtect)
7350                             protect = "Protect";
7351                         sw.WriteLine(post.Nickname + "\t" +
7352                                  "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7353                                  post.CreatedAt.ToLocalTimeString() + "\t" +
7354                                  post.ScreenName + "\t" +
7355                                  post.StatusId + "\t" +
7356                                  post.ImageUrl + "\t" +
7357                                  "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7358                                  protect);
7359                     }
7360                 }
7361                 else
7362                 {
7363                     foreach (var post in this.CurrentTab.SelectedPosts)
7364                     {
7365                         var protect = "";
7366                         if (post.IsProtect)
7367                             protect = "Protect";
7368                         sw.WriteLine(post.Nickname + "\t" +
7369                                  "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7370                                  post.CreatedAt.ToLocalTimeString() + "\t" +
7371                                  post.ScreenName + "\t" +
7372                                  post.StatusId + "\t" +
7373                                  post.ImageUrl + "\t" +
7374                                  "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7375                                  protect);
7376                     }
7377                 }
7378             }
7379             this.TopMost = SettingManager.Common.AlwaysTop;
7380         }
7381
7382         public bool TabRename(string origTabName, out string newTabName)
7383         {
7384             //タブ名変更
7385             newTabName = null;
7386             using (var inputName = new InputTabName())
7387             {
7388                 inputName.TabName = origTabName;
7389                 inputName.ShowDialog();
7390                 if (inputName.DialogResult == DialogResult.Cancel) return false;
7391                 newTabName = inputName.TabName;
7392             }
7393             this.TopMost = SettingManager.Common.AlwaysTop;
7394             if (!string.IsNullOrEmpty(newTabName))
7395             {
7396                 //新タブ名存在チェック
7397                 if (this._statuses.ContainsTab(newTabName))
7398                 {
7399                     var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7400                     MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7401                     return false;
7402                 }
7403
7404                 var tabIndex = this._statuses.Tabs.IndexOf(origTabName);
7405                 var tabPage = this.ListTab.TabPages[tabIndex];
7406
7407                 // タブ名を変更
7408                 if (tabPage != null)
7409                     tabPage.Text = newTabName;
7410
7411                 _statuses.RenameTab(origTabName, newTabName);
7412
7413                 SaveConfigsCommon();
7414                 SaveConfigsTabs();
7415                 _rclickTabName = newTabName;
7416                 return true;
7417             }
7418             else
7419             {
7420                 return false;
7421             }
7422         }
7423
7424         private void ListTab_MouseClick(object sender, MouseEventArgs e)
7425         {
7426             if (e.Button == MouseButtons.Middle)
7427             {
7428                 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
7429                 {
7430                     if (this.ListTab.GetTabRect(index).Contains(e.Location))
7431                     {
7432                         this.RemoveSpecifiedTab(tab.TabName, true);
7433                         this.SaveConfigsTabs();
7434                         break;
7435                     }
7436                 }
7437             }
7438         }
7439
7440         private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7441             => this.TabRename(this.CurrentTabName, out _);
7442
7443         private void ListTab_MouseDown(object sender, MouseEventArgs e)
7444         {
7445             if (SettingManager.Common.TabMouseLock) return;
7446             if (e.Button == MouseButtons.Left)
7447             {
7448                 foreach (var i in Enumerable.Range(0, this._statuses.Tabs.Count))
7449                 {
7450                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
7451                     {
7452                         _tabDrag = true;
7453                         _tabMouseDownPoint = e.Location;
7454                         break;
7455                     }
7456                 }
7457             }
7458             else
7459             {
7460                 _tabDrag = false;
7461             }
7462         }
7463
7464         private void ListTab_DragEnter(object sender, DragEventArgs e)
7465         {
7466             if (e.Data.GetDataPresent(typeof(TabPage)))
7467                 e.Effect = DragDropEffects.Move;
7468             else
7469                 e.Effect = DragDropEffects.None;
7470         }
7471
7472         private void ListTab_DragDrop(object sender, DragEventArgs e)
7473         {
7474             if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7475
7476             _tabDrag = false;
7477             var tn = "";
7478             var bef = false;
7479             var cpos = new Point(e.X, e.Y);
7480             var spos = ListTab.PointToClient(cpos);
7481             foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
7482             {
7483                 var rect = ListTab.GetTabRect(index);
7484                 if (rect.Contains(spos))
7485                 {
7486                     tn = tab.TabName;
7487                     if (spos.X <= (rect.Left + rect.Right) / 2)
7488                         bef = true;
7489                     else
7490                         bef = false;
7491
7492                     break;
7493                 }
7494             }
7495
7496             //タブのないところにドロップ->最後尾へ移動
7497             if (string.IsNullOrEmpty(tn))
7498             {
7499                 var lastTab = this._statuses.Tabs.Last();
7500                 tn = lastTab.TabName;
7501                 bef = false;
7502             }
7503
7504             var tp = (TabPage)e.Data.GetData(typeof(TabPage));
7505             if (tp.Text == tn) return;
7506
7507             ReOrderTab(tp.Text, tn, bef);
7508         }
7509
7510         public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7511         {
7512             var baseIndex = this.GetTabPageIndex(baseTabText);
7513             if (baseIndex == -1)
7514                 return;
7515
7516             var targetIndex = this.GetTabPageIndex(targetTabText);
7517             if (targetIndex == -1)
7518                 return;
7519
7520             using (ControlTransaction.Layout(this.ListTab))
7521             {
7522                 var tab = this._statuses.Tabs[targetIndex];
7523                 var tabPage = this.ListTab.TabPages[targetIndex];
7524
7525                 this.ListTab.TabPages.Remove(tabPage);
7526
7527                 if (targetIndex < baseIndex)
7528                     baseIndex--;
7529
7530                 if (!isBeforeBaseTab)
7531                     baseIndex++;
7532
7533                 this._statuses.MoveTab(baseIndex, tab);
7534
7535                 ListTab.TabPages.Insert(baseIndex, tabPage);
7536             }
7537
7538             SaveConfigsTabs();
7539         }
7540
7541         private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7542         {
7543             //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7544             //isReply:true=@,false=DM
7545             if (!StatusText.Enabled) return;
7546             if (!this.ExistCurrentPost) return;
7547
7548             var tab = this.CurrentTab;
7549             var selectedPosts = tab.SelectedPosts;
7550
7551             // 複数あてリプライはReplyではなく通常ポスト
7552             //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7553             //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7554             //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7555
7556             if (selectedPosts.Length > 0)
7557             {
7558                 // アイテムが1件以上選択されている
7559                 if (selectedPosts.Length == 1 && !isAll && this.ExistCurrentPost)
7560                 {
7561                     var post = selectedPosts.Single();
7562
7563                     // 単独ユーザー宛リプライまたはDM
7564                     if ((tab.TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7565                     {
7566                         // ダイレクトメッセージ
7567                         this.inReplyTo = null;
7568                         StatusText.Text = "D " + post.ScreenName + " " + StatusText.Text;
7569                         StatusText.SelectionStart = StatusText.Text.Length;
7570                         StatusText.Focus();
7571                         return;
7572                     }
7573                     if (string.IsNullOrEmpty(StatusText.Text))
7574                     {
7575                         //空の場合
7576                         var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7577                         var inReplyToScreenName = post.ScreenName;
7578                         this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7579
7580                         // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7581                         StatusText.Text = "@" + post.ScreenName + " ";
7582                     }
7583                     else
7584                     {
7585                         //何か入力済の場合
7586
7587                         if (isAuto)
7588                         {
7589                             //1件選んでEnter or DoubleClick
7590                             if (StatusText.Text.Contains("@" + post.ScreenName + " "))
7591                             {
7592                                 if (this.inReplyTo?.ScreenName == post.ScreenName)
7593                                 {
7594                                     //返信先書き換え
7595                                     var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7596                                     var inReplyToScreenName = post.ScreenName;
7597                                     this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7598                                 }
7599                                 return;
7600                             }
7601                             if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7602                             {
7603                                 //文頭@以外
7604                                 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7605                                 {
7606                                     // 複数リプライ
7607                                     this.inReplyTo = null;
7608                                     StatusText.Text = StatusText.Text.Insert(2, "@" + post.ScreenName + " ");
7609                                 }
7610                                 else
7611                                 {
7612                                     // 単独リプライ
7613                                     var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7614                                     var inReplyToScreenName = post.ScreenName;
7615                                     this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7616                                     StatusText.Text = "@" + post.ScreenName + " " + StatusText.Text;
7617                                 }
7618                             }
7619                             else
7620                             {
7621                                 //文頭@
7622                                 // 複数リプライ
7623                                 this.inReplyTo = null;
7624                                 StatusText.Text = ". @" + post.ScreenName + " " + StatusText.Text;
7625                             }
7626                         }
7627                         else
7628                         {
7629                             //1件選んでCtrl-Rの場合(返信先操作せず)
7630                             var sidx = StatusText.SelectionStart;
7631                             var id = "@" + post.ScreenName + " ";
7632                             if (sidx > 0)
7633                             {
7634                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7635                                 {
7636                                     id = " " + id;
7637                                 }
7638                             }
7639                             StatusText.Text = StatusText.Text.Insert(sidx, id);
7640                             sidx += id.Length;
7641                             //if (StatusText.Text.StartsWith("@"))
7642                             //{
7643                             //    //複数リプライ
7644                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7645                             //    sidx += 5 + _curPost.ScreenName.Length;
7646                             //}
7647                             //else
7648                             //{
7649                             //    // 複数リプライ
7650                             //    StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7651                             //    sidx += 3 + _curPost.ScreenName.Length;
7652                             //}
7653                             StatusText.SelectionStart = sidx;
7654                             StatusText.Focus();
7655                             //_reply_to_id = 0;
7656                             //_reply_to_name = null;
7657                             return;
7658                         }
7659                     }
7660                 }
7661                 else
7662                 {
7663                     // 複数リプライ
7664                     if (!isAuto && !isReply) return;
7665
7666                     //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7667
7668                     if (isAuto)
7669                     {
7670                         //Enter or DoubleClick
7671
7672                         var sTxt = StatusText.Text;
7673                         if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7674                         {
7675                             sTxt = ". " + sTxt;
7676                             this.inReplyTo = null;
7677                         }
7678                         foreach (var post in selectedPosts)
7679                         {
7680                             if (!sTxt.Contains("@" + post.ScreenName + " "))
7681                             {
7682                                 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7683                                 //sTxt = "@" + post.ScreenName + " " + sTxt;
7684                             }
7685                         }
7686                         StatusText.Text = sTxt;
7687                     }
7688                     else
7689                     {
7690                         //C-S-r or C-r
7691
7692                         if (selectedPosts.Length > 1)
7693                         {
7694                             //複数ポスト選択
7695
7696                             var ids = "";
7697                             var sidx = StatusText.SelectionStart;
7698                             foreach (var post in selectedPosts)
7699                             {
7700                                 if (!ids.Contains("@" + post.ScreenName + " ") && post.UserId != tw.UserId)
7701                                 {
7702                                     ids += "@" + post.ScreenName + " ";
7703                                 }
7704                                 if (isAll)
7705                                 {
7706                                     foreach (var (_, screenName) in post.ReplyToList)
7707                                     {
7708                                         if (!ids.Contains("@" + screenName + " ") &&
7709                                             !screenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7710                                         {
7711                                             var m = Regex.Match(post.TextFromApi, "[@@](?<id>" + screenName + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7712                                             if (m.Success)
7713                                                 ids += "@" + m.Result("${id}") + " ";
7714                                             else
7715                                                 ids += "@" + screenName + " ";
7716                                         }
7717                                     }
7718                                 }
7719                             }
7720                             if (ids.Length == 0) return;
7721                             if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7722                             {
7723                                 this.inReplyTo = null;
7724                                 StatusText.Text = ". " + StatusText.Text;
7725                                 sidx += 2;
7726                             }
7727                             if (sidx > 0)
7728                             {
7729                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7730                                 {
7731                                     ids = " " + ids;
7732                                 }
7733                             }
7734                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
7735                             sidx += ids.Length;
7736                             //if (StatusText.Text.StartsWith("@"))
7737                             //{
7738                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7739                             //    sidx += 2 + ids.Length;
7740                             //}
7741                             //else
7742                             //{
7743                             //    StatusText.Text = StatusText.Text.Insert(sidx, ids);
7744                             //    sidx += 1 + ids.Length;
7745                             //}
7746                             StatusText.SelectionStart = sidx;
7747                             StatusText.Focus();
7748                             return;
7749                         }
7750                         else
7751                         {
7752                             //1件のみ選択のC-S-r(返信元付加する可能性あり)
7753
7754                             var ids = "";
7755                             var sidx = StatusText.SelectionStart;
7756                             var post = selectedPosts.Single();
7757                             if (!ids.Contains("@" + post.ScreenName + " ") && post.UserId != tw.UserId)
7758                             {
7759                                 ids += "@" + post.ScreenName + " ";
7760                             }
7761                             foreach (var (_, screenName) in post.ReplyToList)
7762                             {
7763                                 if (!ids.Contains("@" + screenName + " ") &&
7764                                     !screenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7765                                 {
7766                                     var m = Regex.Match(post.TextFromApi, "[@@](?<id>" + screenName + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7767                                     if (m.Success)
7768                                         ids += "@" + m.Result("${id}") + " ";
7769                                     else
7770                                         ids += "@" + screenName + " ";
7771                                 }
7772                             }
7773                             if (!string.IsNullOrEmpty(post.RetweetedBy))
7774                             {
7775                                 if (!ids.Contains("@" + post.RetweetedBy + " ") && post.RetweetedByUserId != tw.UserId)
7776                                 {
7777                                     ids += "@" + post.RetweetedBy + " ";
7778                                 }
7779                             }
7780                             if (ids.Length == 0) return;
7781                             if (string.IsNullOrEmpty(StatusText.Text))
7782                             {
7783                                 //未入力の場合のみ返信先付加
7784                                 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7785                                 var inReplyToScreenName = post.ScreenName;
7786                                 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7787
7788                                 StatusText.Text = ids;
7789                                 StatusText.SelectionStart = ids.Length;
7790                                 StatusText.Focus();
7791                                 return;
7792                             }
7793
7794                             if (sidx > 0)
7795                             {
7796                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7797                                 {
7798                                     ids = " " + ids;
7799                                 }
7800                             }
7801                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
7802                             sidx += ids.Length;
7803                             StatusText.SelectionStart = sidx;
7804                             StatusText.Focus();
7805                             return;
7806                         }
7807                     }
7808                 }
7809                 StatusText.SelectionStart = StatusText.Text.Length;
7810                 StatusText.Focus();
7811             }
7812         }
7813
7814         private void ListTab_MouseUp(object sender, MouseEventArgs e)
7815             => this._tabDrag = false;
7816
7817         private int iconCnt = 0;
7818         private int blinkCnt = 0;
7819         private bool blink = false;
7820
7821         private void RefreshTasktrayIcon()
7822         {
7823             void EnableTasktrayAnimation()
7824                 => this.TimerRefreshIcon.Enabled = true;
7825
7826             void DisableTasktrayAnimation()
7827                 => this.TimerRefreshIcon.Enabled = false;
7828
7829             var busyTasks = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7830             if (busyTasks)
7831             {
7832                 iconCnt += 1;
7833                 if (iconCnt >= this.NIconRefresh.Length)
7834                     iconCnt = 0;
7835
7836                 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7837                 _myStatusError = false;
7838                 EnableTasktrayAnimation();
7839                 return;
7840             }
7841
7842             var replyIconType = SettingManager.Common.ReplyIconState;
7843             var reply = false;
7844             if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
7845             {
7846                 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
7847                 if (replyTab != null && replyTab.UnreadCount > 0)
7848                     reply = true;
7849             }
7850
7851             if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
7852             {
7853                 blinkCnt += 1;
7854                 if (blinkCnt > 10)
7855                     blinkCnt = 0;
7856
7857                 if (blinkCnt == 0)
7858                     blink = !blink;
7859
7860                 NotifyIcon1.Icon = blink ? ReplyIconBlink : ReplyIcon;
7861                 EnableTasktrayAnimation();
7862                 return;
7863             }
7864
7865             DisableTasktrayAnimation();
7866
7867             iconCnt = 0;
7868             blinkCnt = 0;
7869             blink = false;
7870
7871             // 優先度:リプライ→エラー→オフライン→アイドル
7872             // エラーは更新アイコンでクリアされる
7873             if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
7874                 NotifyIcon1.Icon = ReplyIcon;
7875             else if (_myStatusError)
7876                 NotifyIcon1.Icon = NIconAtRed;
7877             else if (_myStatusOnline)
7878                 NotifyIcon1.Icon = NIconAt;
7879             else
7880                 NotifyIcon1.Icon = NIconAtSmoke;
7881         }
7882
7883         private void TimerRefreshIcon_Tick(object sender, EventArgs e)
7884             => this.RefreshTasktrayIcon(); // 200ms
7885
7886         private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7887         {
7888             //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7889             if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7890                 _rclickTabName = this.CurrentTabName;
7891
7892             if (_statuses == null) return;
7893             if (_statuses.Tabs == null) return;
7894
7895             if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out var tb))
7896                 return;
7897
7898             NotifyDispMenuItem.Checked = tb.Notify;
7899             this.NotifyTbMenuItem.Checked = tb.Notify;
7900
7901             soundfileListup = true;
7902             SoundFileComboBox.Items.Clear();
7903             this.SoundFileTbComboBox.Items.Clear();
7904             SoundFileComboBox.Items.Add("");
7905             this.SoundFileTbComboBox.Items.Add("");
7906             var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
7907             if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
7908             {
7909                 oDir = oDir.GetDirectories("Sounds")[0];
7910             }
7911             foreach (var oFile in oDir.GetFiles("*.wav"))
7912             {
7913                 SoundFileComboBox.Items.Add(oFile.Name);
7914                 this.SoundFileTbComboBox.Items.Add(oFile.Name);
7915             }
7916             var idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
7917             if (idx == -1) idx = 0;
7918             SoundFileComboBox.SelectedIndex = idx;
7919             this.SoundFileTbComboBox.SelectedIndex = idx;
7920             soundfileListup = false;
7921             UreadManageMenuItem.Checked = tb.UnreadManage;
7922             this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
7923
7924             TabMenuControl(_rclickTabName);
7925         }
7926
7927         private void TabMenuControl(string tabName)
7928         {
7929             var tabInfo = _statuses.GetTabByName(tabName);
7930
7931             this.FilterEditMenuItem.Enabled = true;
7932             this.EditRuleTbMenuItem.Enabled = true;
7933
7934             if (tabInfo.IsDefaultTabType)
7935             {
7936                 this.ProtectTabMenuItem.Enabled = false;
7937                 this.ProtectTbMenuItem.Enabled = false;
7938             }
7939             else
7940             {
7941                 this.ProtectTabMenuItem.Enabled = true;
7942                 this.ProtectTbMenuItem.Enabled = true;
7943             }
7944
7945             if (tabInfo.IsDefaultTabType || tabInfo.Protected)
7946             {
7947                 this.ProtectTabMenuItem.Checked = true;
7948                 this.ProtectTbMenuItem.Checked = true;
7949                 this.DeleteTabMenuItem.Enabled = false;
7950                 this.DeleteTbMenuItem.Enabled = false;
7951             }
7952             else
7953             {
7954                 this.ProtectTabMenuItem.Checked = false;
7955                 this.ProtectTbMenuItem.Checked = false;
7956                 this.DeleteTabMenuItem.Enabled = true;
7957                 this.DeleteTbMenuItem.Enabled = true;
7958             }
7959         }
7960
7961         private void ProtectTabMenuItem_Click(object sender, EventArgs e)
7962         {
7963             var checkState = ((ToolStripMenuItem)sender).Checked;
7964
7965             // チェック状態を同期
7966             this.ProtectTbMenuItem.Checked = checkState;
7967             this.ProtectTabMenuItem.Checked = checkState;
7968
7969             // ロック中はタブの削除を無効化
7970             this.DeleteTabMenuItem.Enabled = !checkState;
7971             this.DeleteTbMenuItem.Enabled = !checkState;
7972
7973             if (string.IsNullOrEmpty(_rclickTabName)) return;
7974             _statuses.Tabs[_rclickTabName].Protected = checkState;
7975
7976             SaveConfigsTabs();
7977         }
7978
7979         private void UreadManageMenuItem_Click(object sender, EventArgs e)
7980         {
7981             UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7982             this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
7983
7984             if (string.IsNullOrEmpty(_rclickTabName)) return;
7985             ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
7986
7987             SaveConfigsTabs();
7988         }
7989
7990         public void ChangeTabUnreadManage(string tabName, bool isManage)
7991         {
7992             var idx = this.GetTabPageIndex(tabName);
7993             if (idx == -1)
7994                 return;
7995
7996             var tab = this._statuses.Tabs[tabName];
7997             tab.UnreadManage = isManage;
7998
7999             if (SettingManager.Common.TabIconDisp)
8000             {
8001                 var tabPage = this.ListTab.TabPages[idx];
8002                 if (tab.UnreadCount > 0)
8003                     tabPage.ImageIndex = 0;
8004                 else
8005                     tabPage.ImageIndex = -1;
8006             }
8007
8008             if (this.CurrentTabName == tabName)
8009             {
8010                 this.PurgeListViewItemCache();
8011                 this.CurrentListView.Refresh();
8012             }
8013
8014             SetMainWindowTitle();
8015             SetStatusLabelUrl();
8016             if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8017         }
8018
8019         private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8020         {
8021             NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8022             this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8023
8024             if (string.IsNullOrEmpty(_rclickTabName)) return;
8025
8026             _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8027
8028             SaveConfigsTabs();
8029         }
8030
8031         private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8032         {
8033             if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8034
8035             _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8036
8037             SaveConfigsTabs();
8038         }
8039
8040         private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8041         {
8042             if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem)
8043                 _rclickTabName = this.CurrentTabName;
8044
8045             RemoveSpecifiedTab(_rclickTabName, true);
8046             SaveConfigsTabs();
8047         }
8048
8049         private void FilterEditMenuItem_Click(object sender, EventArgs e)
8050         {
8051             if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8052
8053             using (var fltDialog = new FilterDialog())
8054             {
8055                 fltDialog.Owner = this;
8056                 fltDialog.SetCurrent(_rclickTabName);
8057                 fltDialog.ShowDialog(this);
8058             }
8059             this.TopMost = SettingManager.Common.AlwaysTop;
8060
8061             this.ApplyPostFilters();
8062             SaveConfigsTabs();
8063         }
8064
8065         private async void AddTabMenuItem_Click(object sender, EventArgs e)
8066         {
8067             string tabName = null;
8068             MyCommon.TabUsageType tabUsage;
8069             using (var inputName = new InputTabName())
8070             {
8071                 inputName.TabName = _statuses.MakeTabName("MyTab");
8072                 inputName.IsShowUsage = true;
8073                 inputName.ShowDialog();
8074                 if (inputName.DialogResult == DialogResult.Cancel) return;
8075                 tabName = inputName.TabName;
8076                 tabUsage = inputName.Usage;
8077             }
8078             this.TopMost = SettingManager.Common.AlwaysTop;
8079             if (!string.IsNullOrEmpty(tabName))
8080             {
8081                 //List対応
8082                 ListElement list = null;
8083                 if (tabUsage == MyCommon.TabUsageType.Lists)
8084                 {
8085                     using var listAvail = new ListAvailable();
8086                     if (listAvail.ShowDialog(this) == DialogResult.Cancel)
8087                         return;
8088                     if (listAvail.SelectedList == null)
8089                         return;
8090                     list = listAvail.SelectedList;
8091                 }
8092
8093                 TabModel tab;
8094                 switch (tabUsage)
8095                 {
8096                     case MyCommon.TabUsageType.UserDefined:
8097                         tab = new FilterTabModel(tabName);
8098                         break;
8099                     case MyCommon.TabUsageType.PublicSearch:
8100                         tab = new PublicSearchTabModel(tabName);
8101                         break;
8102                     case MyCommon.TabUsageType.Lists:
8103                         tab = new ListTimelineTabModel(tabName, list);
8104                         break;
8105                     default:
8106                         return;
8107                 }
8108
8109                 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8110                 {
8111                     var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8112                     MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8113                 }
8114                 else
8115                 {
8116                     //成功
8117                     SaveConfigsTabs();
8118
8119                     var tabIndex = this._statuses.Tabs.Count - 1;
8120
8121                     if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8122                     {
8123                         ListTab.SelectedIndex = tabIndex;
8124                         this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8125                     }
8126                     if (tabUsage == MyCommon.TabUsageType.Lists)
8127                     {
8128                         ListTab.SelectedIndex = tabIndex;
8129                         await this.RefreshTabAsync(this.CurrentTab);
8130                     }
8131                 }
8132             }
8133         }
8134
8135         private void TabMenuItem_Click(object sender, EventArgs e)
8136         {
8137             using (var fltDialog = new FilterDialog())
8138             {
8139                 fltDialog.Owner = this;
8140
8141                 //選択発言を元にフィルタ追加
8142                 foreach (var post in this.CurrentTab.SelectedPosts)
8143                 {
8144                     //タブ選択(or追加)
8145                     if (!SelectTab(out var tabName)) return;
8146
8147                     fltDialog.SetCurrent(tabName);
8148
8149                     if (post.RetweetedId == null)
8150                     {
8151                         fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
8152                     }
8153                     else
8154                     {
8155                         fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
8156                     }
8157                     fltDialog.ShowDialog(this);
8158                     this.TopMost = SettingManager.Common.AlwaysTop;
8159                 }
8160             }
8161
8162             this.ApplyPostFilters();
8163             SaveConfigsTabs();
8164         }
8165
8166         protected override bool ProcessDialogKey(Keys keyData)
8167         {
8168             //TextBox1でEnterを押してもビープ音が鳴らないようにする
8169             if ((keyData & Keys.KeyCode) == Keys.Enter)
8170             {
8171                 if (StatusText.Focused)
8172                 {
8173                     var _NewLine = false;
8174                     var _Post = false;
8175
8176                     if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8177                     {
8178                         if (StatusText.Multiline)
8179                         {
8180                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8181
8182                             if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8183                         }
8184                         else
8185                         {
8186                             if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8187                         }
8188
8189                     }
8190                     else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8191                     {
8192                         if (StatusText.Multiline)
8193                         {
8194                             if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8195
8196                             if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8197                         }
8198                         else
8199                         {
8200                             if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8201                         }
8202
8203                     }
8204                     else //Enter投稿時
8205                     {
8206                         if (StatusText.Multiline)
8207                         {
8208                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8209
8210                             if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8211                                 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8212                         }
8213                         else
8214                         {
8215                             if (((keyData & Keys.Shift) == Keys.Shift) ||
8216                                 (((keyData & Keys.Control) != Keys.Control) &&
8217                                 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8218                         }
8219                     }
8220
8221                     if (_NewLine)
8222                     {
8223                         var pos1 = StatusText.SelectionStart;
8224                         if (StatusText.SelectionLength > 0)
8225                         {
8226                             StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength);  //選択状態文字列削除
8227                         }
8228                         StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine);  //改行挿入
8229                         StatusText.SelectionStart = pos1 + Environment.NewLine.Length;    //カーソルを改行の次の文字へ移動
8230                         return true;
8231                     }
8232                     else if (_Post)
8233                     {
8234                         PostButton_Click(null, null);
8235                         return true;
8236                     }
8237                 }
8238                 else
8239                 {
8240                     var tab = this.CurrentTab;
8241                     if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
8242                     {
8243                         var tabPage = this.CurrentTabPage;
8244                         if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8245                             tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
8246                         {
8247                             this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], null);
8248                             return true;
8249                         }
8250                     }
8251                 }
8252             }
8253
8254             return base.ProcessDialogKey(keyData);
8255         }
8256
8257         private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8258             => this.MakeReplyOrDirectStatus(false, true, true);
8259
8260         private void IDRuleMenuItem_Click(object sender, EventArgs e)
8261         {
8262             var tab = this.CurrentTab;
8263             var selectedPosts = tab.SelectedPosts;
8264
8265             // 未選択なら処理終了
8266             if (selectedPosts.Length == 0)
8267                 return;
8268
8269             var screenNameArray = selectedPosts
8270                 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8271                 .ToArray();
8272
8273             this.AddFilterRuleByScreenName(screenNameArray);
8274
8275             if (screenNameArray.Length != 0)
8276             {
8277                 var atids = new List<string>();
8278                 foreach (var screenName in screenNameArray)
8279                 {
8280                     atids.Add("@" + screenName);
8281                 }
8282                 var cnt = AtIdSupl.ItemCount;
8283                 AtIdSupl.AddRangeItem(atids.ToArray());
8284                 if (AtIdSupl.ItemCount != cnt)
8285                     this.MarkSettingAtIdModified();
8286             }
8287         }
8288
8289         private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8290         {
8291             var tab = this.CurrentTab;
8292             var selectedPosts = tab.SelectedPosts;
8293
8294             if (selectedPosts.Length == 0)
8295                 return;
8296
8297             var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
8298
8299             this.AddFilterRuleBySource(sourceArray);
8300         }
8301
8302         public void AddFilterRuleByScreenName(params string[] screenNameArray)
8303         {
8304             //タブ選択(or追加)
8305             if (!SelectTab(out var tabName)) return;
8306
8307             var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8308
8309             bool mv;
8310             bool mk;
8311             if (tab.TabType != MyCommon.TabUsageType.Mute)
8312             {
8313                 this.MoveOrCopy(out mv, out mk);
8314             }
8315             else
8316             {
8317                 // ミュートタブでは常に MoveMatches を true にする
8318                 mv = true;
8319                 mk = false;
8320             }
8321
8322             foreach (var screenName in screenNameArray)
8323             {
8324                 tab.AddFilter(new PostFilterRule
8325                 {
8326                     FilterName = screenName,
8327                     UseNameField = true,
8328                     MoveMatches = mv,
8329                     MarkMatches = mk,
8330                     UseRegex = false,
8331                     FilterByUrl = false,
8332                 });
8333             }
8334
8335             this.ApplyPostFilters();
8336             SaveConfigsTabs();
8337         }
8338
8339         public void AddFilterRuleBySource(params string[] sourceArray)
8340         {
8341             // タブ選択ダイアログを表示(or追加)
8342             if (!this.SelectTab(out var tabName))
8343                 return;
8344
8345             var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8346
8347             bool mv;
8348             bool mk;
8349             if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8350             {
8351                 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8352                 this.MoveOrCopy(out mv, out mk);
8353             }
8354             else
8355             {
8356                 // ミュートタブでは常に MoveMatches を true にする
8357                 mv = true;
8358                 mk = false;
8359             }
8360
8361             // 振り分けルールに追加するSource
8362             foreach (var source in sourceArray)
8363             {
8364                 filterTab.AddFilter(new PostFilterRule
8365                 {
8366                     FilterSource = source,
8367                     MoveMatches = mv,
8368                     MarkMatches = mk,
8369                     UseRegex = false,
8370                     FilterByUrl = false,
8371                 });
8372             }
8373
8374             this.ApplyPostFilters();
8375             this.SaveConfigsTabs();
8376         }
8377
8378         private bool SelectTab(out string tabName)
8379         {
8380             do
8381             {
8382                 tabName = null;
8383
8384                 //振り分け先タブ選択
8385                 using (var dialog = new TabsDialog(_statuses))
8386                 {
8387                     if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8388
8389                     tabName = dialog.SelectedTab?.TabName;
8390                 }
8391
8392                 this.CurrentTabPage.Focus();
8393                 //新規タブを選択→タブ作成
8394                 if (tabName == null)
8395                 {
8396                     using (var inputName = new InputTabName())
8397                     {
8398                         inputName.TabName = _statuses.MakeTabName("MyTab");
8399                         inputName.ShowDialog();
8400                         if (inputName.DialogResult == DialogResult.Cancel) return false;
8401                         tabName = inputName.TabName;
8402                     }
8403                     this.TopMost = SettingManager.Common.AlwaysTop;
8404                     if (!string.IsNullOrEmpty(tabName))
8405                     {
8406                         var tab = new FilterTabModel(tabName);
8407                         if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8408                         {
8409                             var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8410                             MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8411                             //もう一度タブ名入力
8412                         }
8413                         else
8414                         {
8415                             return true;
8416                         }
8417                     }
8418                 }
8419                 else
8420                 {
8421                     //既存タブを選択
8422                     return true;
8423                 }
8424             }
8425             while (true);
8426         }
8427
8428         private void MoveOrCopy(out bool move, out bool mark)
8429         {
8430             {
8431                 //移動するか?
8432                 var _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8433                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8434                     move = false;
8435                 else
8436                     move = true;
8437             }
8438             if (!move)
8439             {
8440                 //マークするか?
8441                 var _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8442                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8443                     mark = true;
8444                 else
8445                     mark = false;
8446             }
8447             else
8448             {
8449                 mark = false;
8450             }
8451         }
8452
8453         private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8454             => this.CopyStot();
8455
8456         private void CopyURLMenuItem_Click(object sender, EventArgs e)
8457             => this.CopyIdUri();
8458
8459         private void SelectAllMenuItem_Click(object sender, EventArgs e)
8460         {
8461             if (StatusText.Focused)
8462             {
8463                 // 発言欄でのCtrl+A
8464                 StatusText.SelectAll();
8465             }
8466             else
8467             {
8468                 // ListView上でのCtrl+A
8469                 NativeMethods.SelectAllItems(this.CurrentListView);
8470             }
8471         }
8472
8473         private void MoveMiddle()
8474         {
8475             ListViewItem _item;
8476             int idx1;
8477             int idx2;
8478
8479             var listView = this.CurrentListView;
8480             if (listView.SelectedIndices.Count == 0) return;
8481
8482             var idx = listView.SelectedIndices[0];
8483
8484             _item = listView.GetItemAt(0, 25);
8485             if (_item == null)
8486                 idx1 = 0;
8487             else
8488                 idx1 = _item.Index;
8489
8490             _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
8491             if (_item == null)
8492                 idx2 = listView.VirtualListSize - 1;
8493             else
8494                 idx2 = _item.Index;
8495
8496             idx -= Math.Abs(idx1 - idx2) / 2;
8497             if (idx < 0) idx = 0;
8498
8499             listView.EnsureVisible(listView.VirtualListSize - 1);
8500             listView.EnsureVisible(idx);
8501         }
8502
8503         private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8504         {
8505             var linkElements = this.tweetDetailsView.GetLinkElements();
8506
8507             if (linkElements.Length == 0)
8508                 return;
8509
8510             var links = new List<OpenUrlItem>(linkElements.Length);
8511
8512             foreach (var linkElm in linkElements)
8513             {
8514                 var displayUrl = linkElm.GetAttribute("title");
8515                 var href = linkElm.GetAttribute("href");
8516                 var linkedText = linkElm.InnerText;
8517
8518                 if (string.IsNullOrEmpty(displayUrl))
8519                     displayUrl = href;
8520
8521                 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
8522             }
8523
8524             string selectedUrl;
8525             bool isReverseSettings;
8526
8527             if (links.Count == 1)
8528             {
8529                 // ツイートに含まれる URL が 1 つのみの場合
8530                 //   => OpenURL ダイアログを表示せずにリンクを開く
8531                 selectedUrl = links[0].Href;
8532
8533                 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8534                 isReverseSettings = false;
8535             }
8536             else
8537             {
8538                 // ツイートに含まれる URL が複数ある場合
8539                 //   => OpenURL を表示しユーザーが選択したリンクを開く
8540                 this.UrlDialog.ClearUrl();
8541
8542                 foreach (var link in links)
8543                     this.UrlDialog.AddUrl(link);
8544
8545                 if (this.UrlDialog.ShowDialog(this) != DialogResult.OK)
8546                     return;
8547
8548                 this.TopMost = SettingManager.Common.AlwaysTop;
8549
8550                 selectedUrl = this.UrlDialog.SelectedUrl;
8551
8552                 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8553                 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
8554             }
8555
8556             await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
8557         }
8558
8559         private void ClearTabMenuItem_Click(object sender, EventArgs e)
8560         {
8561             if (string.IsNullOrEmpty(_rclickTabName)) return;
8562             ClearTab(_rclickTabName, true);
8563         }
8564
8565         private void ClearTab(string tabName, bool showWarning)
8566         {
8567             if (showWarning)
8568             {
8569                 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8570                 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8571                 {
8572                     return;
8573                 }
8574             }
8575
8576             _statuses.ClearTabIds(tabName);
8577             if (this.CurrentTabName == tabName)
8578             {
8579                 _anchorPost = null;
8580                 _anchorFlag = false;
8581                 this.PurgeListViewItemCache();
8582             }
8583
8584             var tabIndex = this._statuses.Tabs.IndexOf(tabName);
8585             var tabPage = this.ListTab.TabPages[tabIndex];
8586             tabPage.ImageIndex = -1;
8587
8588             var listView = (DetailsListView)tabPage.Tag;
8589             listView.VirtualListSize = 0;
8590
8591             if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8592
8593             SetMainWindowTitle();
8594             SetStatusLabelUrl();
8595         }
8596
8597         private static long followers = 0;
8598
8599         private void SetMainWindowTitle()
8600         {
8601             //メインウインドウタイトルの書き換え
8602             var ttl = new StringBuilder(256);
8603             var ur = 0;
8604             var al = 0;
8605             if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8606                 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8607                 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8608                 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8609             {
8610                 foreach (var tab in _statuses.Tabs)
8611                 {
8612                     ur += tab.UnreadCount;
8613                     al += tab.AllCount;
8614                 }
8615             }
8616
8617             if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8618             ttl.Append(ApplicationSettings.ApplicationName);
8619             ttl.Append("  ");
8620             switch (SettingManager.Common.DispLatestPost)
8621             {
8622                 case MyCommon.DispTitleEnum.Ver:
8623                     ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8624                     break;
8625                 case MyCommon.DispTitleEnum.Post:
8626                     if (_history != null && _history.Count > 1)
8627                         ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8628                     break;
8629                 case MyCommon.DispTitleEnum.UnreadRepCount:
8630                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8631                     break;
8632                 case MyCommon.DispTitleEnum.UnreadAllCount:
8633                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8634                     break;
8635                 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8636                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8637                     break;
8638                 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8639                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8640                     break;
8641                 case MyCommon.DispTitleEnum.OwnStatus:
8642                     if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8643                     ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8644                     break;
8645             }
8646
8647             try
8648             {
8649                 this.Text = ttl.ToString();
8650             }
8651             catch (AccessViolationException)
8652             {
8653                 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8654             }
8655         }
8656
8657         private string GetStatusLabelText()
8658         {
8659             //ステータス欄にカウント表示
8660             //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8661             if (_statuses == null) return "";
8662             var tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8663             var tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8664             if (tbRep == null || tbDm == null) return "";
8665             var urat = tbRep.UnreadCount + tbDm.UnreadCount;
8666             var ur = 0;
8667             var al = 0;
8668             var tur = 0;
8669             var tal = 0;
8670             var slbl = new StringBuilder(256);
8671             try
8672             {
8673                 foreach (var tab in _statuses.Tabs)
8674                 {
8675                     ur += tab.UnreadCount;
8676                     al += tab.AllCount;
8677                     if (tab.TabName == this.CurrentTabName)
8678                     {
8679                         tur = tab.UnreadCount;
8680                         tal = tab.AllCount;
8681                     }
8682                 }
8683             }
8684             catch (Exception)
8685             {
8686                 return "";
8687             }
8688
8689             UnreadCounter = ur;
8690             UnreadAtCounter = urat;
8691
8692             var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8693
8694             slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8695             if (SettingManager.Common.TimelinePeriod == 0)
8696             {
8697                 slbl.Append(Properties.Resources.SetStatusLabelText2);
8698             }
8699             else
8700             {
8701                 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8702             }
8703             return slbl.ToString();
8704         }
8705
8706         private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8707         {
8708             try
8709             {
8710                 if (this.InvokeRequired && !this.IsDisposed)
8711                 {
8712                     await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8713                 }
8714                 else
8715                 {
8716                     var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8717                     SetApiStatusLabel(endpointName);
8718                 }
8719             }
8720             catch (ObjectDisposedException)
8721             {
8722                 return;
8723             }
8724             catch (InvalidOperationException)
8725             {
8726                 return;
8727             }
8728         }
8729
8730         private void SetApiStatusLabel(string endpointName = null)
8731         {
8732             var tabType = this.CurrentTab.TabType;
8733
8734             if (endpointName == null)
8735             {
8736                 // 表示中のタブに応じて更新
8737                 switch (tabType)
8738                 {
8739                     case MyCommon.TabUsageType.Home:
8740                     case MyCommon.TabUsageType.UserDefined:
8741                         endpointName = "/statuses/home_timeline";
8742                         break;
8743
8744                     case MyCommon.TabUsageType.Mentions:
8745                         endpointName = "/statuses/mentions_timeline";
8746                         break;
8747
8748                     case MyCommon.TabUsageType.Favorites:
8749                         endpointName = "/favorites/list";
8750                         break;
8751
8752                     case MyCommon.TabUsageType.DirectMessage:
8753                         endpointName = "/direct_messages/events/list";
8754                         break;
8755
8756                     case MyCommon.TabUsageType.UserTimeline:
8757                         endpointName = "/statuses/user_timeline";
8758                         break;
8759
8760                     case MyCommon.TabUsageType.Lists:
8761                         endpointName = "/lists/statuses";
8762                         break;
8763
8764                     case MyCommon.TabUsageType.PublicSearch:
8765                         endpointName = "/search/tweets";
8766                         break;
8767
8768                     case MyCommon.TabUsageType.Related:
8769                         endpointName = "/statuses/show/:id";
8770                         break;
8771
8772                     default:
8773                         break;
8774                 }
8775
8776                 this.toolStripApiGauge.ApiEndpoint = endpointName;
8777             }
8778             else
8779             {
8780                 // 表示中のタブに関連する endpoint であれば更新
8781                 var update = false;
8782
8783                 switch (endpointName)
8784                 {
8785                     case "/statuses/home_timeline":
8786                         update = tabType == MyCommon.TabUsageType.Home ||
8787                                  tabType == MyCommon.TabUsageType.UserDefined;
8788                         break;
8789
8790                     case "/statuses/mentions_timeline":
8791                         update = tabType == MyCommon.TabUsageType.Mentions;
8792                         break;
8793
8794                     case "/favorites/list":
8795                         update = tabType == MyCommon.TabUsageType.Favorites;
8796                         break;
8797
8798                     case "/direct_messages/events/list":
8799                         update = tabType == MyCommon.TabUsageType.DirectMessage;
8800                         break;
8801
8802                     case "/statuses/user_timeline":
8803                         update = tabType == MyCommon.TabUsageType.UserTimeline;
8804                         break;
8805
8806                     case "/lists/statuses":
8807                         update = tabType == MyCommon.TabUsageType.Lists;
8808                         break;
8809
8810                     case "/search/tweets":
8811                         update = tabType == MyCommon.TabUsageType.PublicSearch;
8812                         break;
8813
8814                     case "/statuses/show/:id":
8815                         update = tabType == MyCommon.TabUsageType.Related;
8816                         break;
8817
8818                     default:
8819                         break;
8820                 }
8821
8822                 if (update)
8823                 {
8824                     this.toolStripApiGauge.ApiEndpoint = endpointName;
8825                 }
8826             }
8827         }
8828
8829         private void SetStatusLabelUrl()
8830             => this.StatusLabelUrl.Text = this.GetStatusLabelText();
8831
8832         public void SetStatusLabel(string text)
8833             => this.StatusLabel.Text = text;
8834
8835         private void SetNotifyIconText()
8836         {
8837             var ur = new StringBuilder(64);
8838
8839             // タスクトレイアイコンのツールチップテキスト書き換え
8840             // Tween [未読/@]
8841             ur.Remove(0, ur.Length);
8842             if (SettingManager.Common.DispUsername)
8843             {
8844                 ur.Append(tw.Username);
8845                 ur.Append(" - ");
8846             }
8847             ur.Append(ApplicationSettings.ApplicationName);
8848 #if DEBUG
8849             ur.Append("(Debug Build)");
8850 #endif
8851             if (UnreadCounter != -1 && UnreadAtCounter != -1)
8852             {
8853                 ur.Append(" [");
8854                 ur.Append(UnreadCounter);
8855                 ur.Append("/@");
8856                 ur.Append(UnreadAtCounter);
8857                 ur.Append("]");
8858             }
8859             NotifyIcon1.Text = ur.ToString();
8860         }
8861
8862         internal void CheckReplyTo(string StatusText)
8863         {
8864             MatchCollection m;
8865             //ハッシュタグの保存
8866             m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
8867             var hstr = "";
8868             foreach (Match hm in m)
8869             {
8870                 if (!hstr.Contains("#" + hm.Result("$3") + " "))
8871                 {
8872                     hstr += "#" + hm.Result("$3") + " ";
8873                     HashSupl.AddItem("#" + hm.Result("$3"));
8874                 }
8875             }
8876             if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
8877             {
8878                 hstr += HashMgr.UseHash;
8879             }
8880             if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
8881
8882             // 本当にリプライ先指定すべきかどうかの判定
8883             m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
8884
8885             if (SettingManager.Common.UseAtIdSupplement)
8886             {
8887                 var bCnt = AtIdSupl.ItemCount;
8888                 foreach (Match mid in m)
8889                 {
8890                     AtIdSupl.AddItem(mid.Result("${id}"));
8891                 }
8892                 if (bCnt != AtIdSupl.ItemCount)
8893                     this.MarkSettingAtIdModified();
8894             }
8895
8896             // リプライ先ステータスIDの指定がない場合は指定しない
8897             if (this.inReplyTo == null)
8898                 return;
8899
8900             // 通常Reply
8901             // 次の条件を満たす場合に in_reply_to_status_id 指定
8902             // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
8903             // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
8904             // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
8905
8906             if (m != null)
8907             {
8908                 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
8909                 if (StatusText.StartsWith("@", StringComparison.Ordinal))
8910                 {
8911                     if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
8912                 }
8913                 else
8914                 {
8915                     foreach (Match mid in m)
8916                     {
8917                         if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
8918                     }
8919                 }
8920             }
8921
8922             this.inReplyTo = null;
8923         }
8924
8925         private void TweenMain_Resize(object sender, EventArgs e)
8926         {
8927             if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
8928             {
8929                 this.Visible = false;
8930             }
8931             if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
8932             {
8933                 // 現在の DPI と設定保存時の DPI との比を取得する
8934                 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
8935
8936                 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
8937
8938                 // Splitterの位置設定
8939                 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
8940                 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
8941                     splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
8942                 {
8943                     this.SplitContainer1.SplitterDistance = splitterDistance;
8944                 }
8945
8946                 //発言欄複数行
8947                 StatusText.Multiline = SettingManager.Local.StatusMultiline;
8948                 if (StatusText.Multiline)
8949                 {
8950                     var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
8951                     var dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
8952                     if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
8953                     {
8954                         SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
8955                     }
8956                     StatusText.Height = statusTextHeight;
8957                 }
8958                 else
8959                 {
8960                     if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
8961                     {
8962                         SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
8963                     }
8964                 }
8965
8966                 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
8967                 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
8968                 {
8969                     this.SplitContainer3.SplitterDistance = previewDistance;
8970                 }
8971
8972                 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
8973                 this.SplitContainer3.Panel2Collapsed = true;
8974
8975                 _initialLayout = false;
8976             }
8977             if (this.WindowState != FormWindowState.Minimized)
8978             {
8979                 _formWindowState = this.WindowState;
8980             }
8981         }
8982
8983         private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
8984         {
8985             PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8986             this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
8987             if (PlaySoundMenuItem.Checked)
8988             {
8989                 SettingManager.Common.PlaySound = true;
8990             }
8991             else
8992             {
8993                 SettingManager.Common.PlaySound = false;
8994             }
8995             this.MarkSettingCommonModified();
8996         }
8997
8998         private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
8999         {
9000             if (this._initialLayout)
9001                 return;
9002
9003             int splitterDistance;
9004             switch (this.WindowState)
9005             {
9006                 case FormWindowState.Normal:
9007                     splitterDistance = this.SplitContainer1.SplitterDistance;
9008                     break;
9009                 case FormWindowState.Maximized:
9010                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9011                     var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9012                     splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9013                     splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9014                     break;
9015                 default:
9016                     return;
9017             }
9018
9019             this._mySpDis = splitterDistance;
9020             this.MarkSettingLocalModified();
9021         }
9022
9023         private async Task doRepliedStatusOpen()
9024         {
9025             var currentPost = this.CurrentPost;
9026             if (this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
9027             {
9028                 if (MyCommon.IsKeyDown(Keys.Shift))
9029                 {
9030                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
9031                     return;
9032                 }
9033                 if (_statuses.ContainsKey(currentPost.InReplyToStatusId.Value))
9034                 {
9035                     var repPost = _statuses[currentPost.InReplyToStatusId.Value];
9036                     MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname}   ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
9037                 }
9038                 else
9039                 {
9040                     foreach (var tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9041                     {
9042                         if (tb == null || !tb.Contains(currentPost.InReplyToStatusId.Value)) break;
9043                         var repPost = _statuses[currentPost.InReplyToStatusId.Value];
9044                         MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname}   ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
9045                         return;
9046                     }
9047                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
9048                 }
9049             }
9050         }
9051
9052         private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9053             => await this.doRepliedStatusOpen();
9054
9055         private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9056         {
9057             if (this._initialLayout)
9058                 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
9059
9060             var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9061             if (multiline != this.StatusText.Multiline)
9062             {
9063                 this.StatusText.Multiline = multiline;
9064                 SettingManager.Local.StatusMultiline = multiline;
9065                 this.MarkSettingLocalModified();
9066             }
9067         }
9068
9069         private void StatusText_MultilineChanged(object sender, EventArgs e)
9070         {
9071             if (this.StatusText.Multiline)
9072                 this.StatusText.ScrollBars = ScrollBars.Vertical;
9073             else
9074                 this.StatusText.ScrollBars = ScrollBars.None;
9075
9076             if (!this._initialLayout)
9077                 this.MarkSettingLocalModified();
9078         }
9079
9080         private void MultiLineMenuItem_Click(object sender, EventArgs e)
9081         {
9082             //発言欄複数行
9083             var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
9084             StatusText.Multiline = menuItemChecked;
9085             SettingManager.Local.StatusMultiline = menuItemChecked;
9086             if (menuItemChecked)
9087             {
9088                 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9089                     SplitContainer2.SplitterDistance = 0;
9090                 else
9091                     SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9092             }
9093             else
9094             {
9095                 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9096             }
9097             this.MarkSettingLocalModified();
9098         }
9099
9100         private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9101         {
9102             if (Converter_Type == MyCommon.UrlConverter.Bitly || Converter_Type == MyCommon.UrlConverter.Jmp)
9103             {
9104                 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
9105                 if (string.IsNullOrEmpty(SettingManager.Common.BitlyAccessToken) &&
9106                     (string.IsNullOrEmpty(SettingManager.Common.BilyUser) || string.IsNullOrEmpty(SettingManager.Common.BitlyPwd)))
9107                 {
9108                     MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
9109                     return false;
9110                 }
9111             }
9112
9113             //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9114             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9115
9116             //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9117             //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9118             //Appendix A.  Collected ABNF for URI
9119             //http://www.ietf.org/rfc/rfc3986.txt
9120
9121             const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9122
9123             string result;
9124             if (StatusText.SelectionLength > 0)
9125             {
9126                 var tmp = StatusText.SelectedText;
9127                 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9128                 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9129                 {
9130                     // 文字列が選択されている場合はその文字列について処理
9131
9132                     //nico.ms使用、nicovideoにマッチしたら変換
9133                     if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9134                     {
9135                         result = nicoms.Shorten(tmp);
9136                     }
9137                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9138                     {
9139                         // 短縮URL変換
9140                         try
9141                         {
9142                             var srcUri = new Uri(tmp);
9143                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9144                             result = resultUri.AbsoluteUri;
9145                         }
9146                         catch (WebApiException e)
9147                         {
9148                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9149                             return false;
9150                         }
9151                         catch (UriFormatException e)
9152                         {
9153                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9154                             return false;
9155                         }
9156                     }
9157                     else
9158                     {
9159                         return true;
9160                     }
9161
9162                     if (!string.IsNullOrEmpty(result))
9163                     {
9164                         var undotmp = new urlUndo();
9165
9166                         // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9167                         var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9168                         if (origUrlIndex == -1)
9169                             return false;
9170
9171                         StatusText.Select(origUrlIndex, tmp.Length);
9172                         StatusText.SelectedText = result;
9173
9174                         //undoバッファにセット
9175                         undotmp.Before = tmp;
9176                         undotmp.After = result;
9177
9178                         if (urlUndoBuffer == null)
9179                         {
9180                             urlUndoBuffer = new List<urlUndo>();
9181                             UrlUndoToolStripMenuItem.Enabled = true;
9182                         }
9183
9184                         urlUndoBuffer.Add(undotmp);
9185                     }
9186                 }
9187             }
9188             else
9189             {
9190                 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9191                                    @"(?<url>(?<protocol>https?://)" +
9192                                    @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9193                                    @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9194                                    @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9195                 // 正規表現にマッチしたURL文字列をtinyurl化
9196                 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9197                 {
9198                     if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
9199                         continue;
9200                     var tmp = mt.Result("${url}");
9201                     if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
9202                         tmp = "http://" + tmp;
9203                     var undotmp = new urlUndo();
9204
9205                     //選んだURLを選択(?)
9206                     StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9207
9208                     //nico.ms使用、nicovideoにマッチしたら変換
9209                     if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9210                     {
9211                         result = nicoms.Shorten(tmp);
9212                     }
9213                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9214                     {
9215                         // 短縮URL変換
9216                         try
9217                         {
9218                             var srcUri = new Uri(tmp);
9219                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9220                             result = resultUri.AbsoluteUri;
9221                         }
9222                         catch (HttpRequestException e)
9223                         {
9224                             // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9225                             // のように長いので「:」が含まれていればそれ以降のみを抽出する
9226                             var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9227
9228                             this.StatusLabel.Text = Converter_Type + ":" + message;
9229                             continue;
9230                         }
9231                         catch (WebApiException e)
9232                         {
9233                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9234                             continue;
9235                         }
9236                         catch (UriFormatException e)
9237                         {
9238                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9239                             continue;
9240                         }
9241                     }
9242                     else
9243                     {
9244                         continue;
9245                     }
9246
9247                     if (!string.IsNullOrEmpty(result))
9248                     {
9249                         // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9250                         var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9251                         if (origUrlIndex == -1)
9252                             return false;
9253
9254                         StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9255                         StatusText.SelectedText = result;
9256                         //undoバッファにセット
9257                         undotmp.Before = mt.Result("${url}");
9258                         undotmp.After = result;
9259
9260                         if (urlUndoBuffer == null)
9261                         {
9262                             urlUndoBuffer = new List<urlUndo>();
9263                             UrlUndoToolStripMenuItem.Enabled = true;
9264                         }
9265
9266                         urlUndoBuffer.Add(undotmp);
9267                     }
9268                 }
9269             }
9270
9271             return true;
9272         }
9273
9274         private void doUrlUndo()
9275         {
9276             if (urlUndoBuffer != null)
9277             {
9278                 var tmp = StatusText.Text;
9279                 foreach (var data in urlUndoBuffer)
9280                 {
9281                     tmp = tmp.Replace(data.After, data.Before);
9282                 }
9283                 StatusText.Text = tmp;
9284                 urlUndoBuffer = null;
9285                 UrlUndoToolStripMenuItem.Enabled = false;
9286                 StatusText.SelectionStart = 0;
9287                 StatusText.SelectionLength = 0;
9288             }
9289         }
9290
9291         private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9292             => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9293
9294         private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9295             => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9296
9297         private async void UxnuMenuItem_Click(object sender, EventArgs e)
9298             => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9299
9300         private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9301         {
9302             if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9303             {
9304                 var rnd = new Random();
9305
9306                 MyCommon.UrlConverter svc;
9307                 // 前回使用した短縮URLサービス以外を選択する
9308                 do
9309                 {
9310                     svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9311                 }
9312                 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9313                 await UrlConvertAsync(svc);
9314             }
9315         }
9316
9317         private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9318             => this.doUrlUndo();
9319
9320         private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9321         {
9322             this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9323             this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9324             SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9325             this.MarkSettingCommonModified();
9326         }
9327
9328         private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9329         {
9330             ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9331             this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9332             SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9333             this.MarkSettingCommonModified();
9334         }
9335
9336         private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9337         {
9338             // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9339             MenuStrip1.Tag = new object();
9340             MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9341         }
9342
9343         private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9344         {
9345             var currentTabPage = this.CurrentTabPage;
9346             if (this.Tag != null) // 設定された戻り先へ遷移
9347             {
9348                 if (this.Tag == currentTabPage)
9349                     ((Control)currentTabPage.Tag).Select();
9350                 else
9351                     ((Control)this.Tag).Select();
9352             }
9353             else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9354             {
9355                 this.Tag = currentTabPage.Tag;
9356                 ((Control)this.Tag).Select();
9357             }
9358             // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9359             MenuStrip1.Tag = null;
9360         }
9361
9362         private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9363         {
9364             var lst = (DetailsListView)sender;
9365             if (SettingManager.Local == null) return;
9366
9367             if (_iconCol)
9368             {
9369                 SettingManager.Local.Width1 = lst.Columns[0].Width;
9370                 SettingManager.Local.Width3 = lst.Columns[1].Width;
9371             }
9372             else
9373             {
9374                 var darr = new int[lst.Columns.Count];
9375                 for (var i = 0; i < lst.Columns.Count; i++)
9376                 {
9377                     darr[lst.Columns[i].DisplayIndex] = i;
9378                 }
9379                 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9380
9381                 for (var i = 0; i < lst.Columns.Count; i++)
9382                 {
9383                     switch (darr[i])
9384                     {
9385                         case 0:
9386                             SettingManager.Local.DisplayIndex1 = i;
9387                             break;
9388                         case 1:
9389                             SettingManager.Local.DisplayIndex2 = i;
9390                             break;
9391                         case 2:
9392                             SettingManager.Local.DisplayIndex3 = i;
9393                             break;
9394                         case 3:
9395                             SettingManager.Local.DisplayIndex4 = i;
9396                             break;
9397                         case 4:
9398                             SettingManager.Local.DisplayIndex5 = i;
9399                             break;
9400                         case 5:
9401                             SettingManager.Local.DisplayIndex6 = i;
9402                             break;
9403                         case 6:
9404                             SettingManager.Local.DisplayIndex7 = i;
9405                             break;
9406                         case 7:
9407                             SettingManager.Local.DisplayIndex8 = i;
9408                             break;
9409                     }
9410                 }
9411                 SettingManager.Local.Width1 = lst.Columns[0].Width;
9412                 SettingManager.Local.Width2 = lst.Columns[1].Width;
9413                 SettingManager.Local.Width3 = lst.Columns[2].Width;
9414                 SettingManager.Local.Width4 = lst.Columns[3].Width;
9415                 SettingManager.Local.Width5 = lst.Columns[4].Width;
9416                 SettingManager.Local.Width6 = lst.Columns[5].Width;
9417                 SettingManager.Local.Width7 = lst.Columns[6].Width;
9418                 SettingManager.Local.Width8 = lst.Columns[7].Width;
9419             }
9420             this.MarkSettingLocalModified();
9421             _isColumnChanged = true;
9422         }
9423
9424         private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9425         {
9426             var lst = (DetailsListView)sender;
9427             if (SettingManager.Local == null) return;
9428
9429             var modified = false;
9430             if (_iconCol)
9431             {
9432                 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9433                 {
9434                     SettingManager.Local.Width1 = lst.Columns[0].Width;
9435                     modified = true;
9436                 }
9437                 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9438                 {
9439                     SettingManager.Local.Width3 = lst.Columns[1].Width;
9440                     modified = true;
9441                 }
9442             }
9443             else
9444             {
9445                 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9446                 {
9447                     SettingManager.Local.Width1 = lst.Columns[0].Width;
9448                     modified = true;
9449                 }
9450                 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9451                 {
9452                     SettingManager.Local.Width2 = lst.Columns[1].Width;
9453                     modified = true;
9454                 }
9455                 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9456                 {
9457                     SettingManager.Local.Width3 = lst.Columns[2].Width;
9458                     modified = true;
9459                 }
9460                 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9461                 {
9462                     SettingManager.Local.Width4 = lst.Columns[3].Width;
9463                     modified = true;
9464                 }
9465                 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9466                 {
9467                     SettingManager.Local.Width5 = lst.Columns[4].Width;
9468                     modified = true;
9469                 }
9470                 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9471                 {
9472                     SettingManager.Local.Width6 = lst.Columns[5].Width;
9473                     modified = true;
9474                 }
9475                 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9476                 {
9477                     SettingManager.Local.Width7 = lst.Columns[6].Width;
9478                     modified = true;
9479                 }
9480                 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9481                 {
9482                     SettingManager.Local.Width8 = lst.Columns[7].Width;
9483                     modified = true;
9484                 }
9485             }
9486             if (modified)
9487             {
9488                 this.MarkSettingLocalModified();
9489                 this._isColumnChanged = true;
9490             }
9491             // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9492             //if (changed)
9493             //{
9494             //    SaveConfigsLocal();
9495             //}
9496         }
9497
9498         private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9499         {
9500             if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9501             this.MarkSettingLocalModified();
9502         }
9503
9504         private void TweenMain_DragDrop(object sender, DragEventArgs e)
9505         {
9506             if (e.Data.GetDataPresent(DataFormats.FileDrop))
9507             {
9508                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9509                 {
9510                     SelectMedia_DragDrop(e);
9511                 }
9512             }
9513             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9514             {
9515                 var (url, title) = GetUrlFromDataObject(e.Data);
9516
9517                 string appendText;
9518                 if (title == null)
9519                     appendText = url;
9520                 else
9521                     appendText = title + " " + url;
9522
9523                 if (this.StatusText.TextLength == 0)
9524                     this.StatusText.Text = appendText;
9525                 else
9526                     this.StatusText.Text += " " + appendText;
9527             }
9528             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9529             {
9530                 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9531                 if (text != null)
9532                     this.StatusText.Text += text;
9533             }
9534             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9535             {
9536                 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9537                 if (data != null) StatusText.Text += data;
9538             }
9539         }
9540
9541         /// <summary>
9542         /// IDataObject から URL とタイトルの対を取得します
9543         /// </summary>
9544         /// <remarks>
9545         /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9546         /// </remarks>
9547         /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9548         /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9549         internal static (string Url, string Title) GetUrlFromDataObject(IDataObject data)
9550         {
9551             if (data.GetDataPresent("text/x-moz-url"))
9552             {
9553                 // Firefox, Google Chrome で利用可能
9554                 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9555
9556                 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
9557                 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9558                 if (lines.Length < 2)
9559                     throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9560
9561                 return (lines[0], lines[1]);
9562             }
9563             else if (data.GetDataPresent("IESiteModeToUrl"))
9564             {
9565                 // Internet Exproler 用
9566                 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9567
9568                 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
9569                 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9570                 if (lines.Length < 2)
9571                     throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9572
9573                 return (lines[0], lines[1]);
9574             }
9575             else if (data.GetDataPresent("UniformResourceLocatorW"))
9576             {
9577                 // それ以外のブラウザ向け
9578
9579                 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
9580                 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9581                 return (url, null);
9582             }
9583
9584             throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9585         }
9586
9587         private void TweenMain_DragEnter(object sender, DragEventArgs e)
9588         {
9589             if (e.Data.GetDataPresent(DataFormats.FileDrop))
9590             {
9591                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9592                 {
9593                     SelectMedia_DragEnter(e);
9594                     return;
9595                 }
9596             }
9597             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9598             {
9599                 e.Effect = DragDropEffects.Copy;
9600                 return;
9601             }
9602             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9603             {
9604                 e.Effect = DragDropEffects.Copy;
9605                 return;
9606             }
9607             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9608             {
9609                 e.Effect = DragDropEffects.Copy;
9610                 return;
9611             }
9612
9613             e.Effect = DragDropEffects.None;
9614         }
9615
9616         private void TweenMain_DragOver(object sender, DragEventArgs e)
9617         {
9618         }
9619
9620         public bool IsNetworkAvailable()
9621         {
9622             var nw = MyCommon.IsNetworkAvailable();
9623             _myStatusOnline = nw;
9624             return nw;
9625         }
9626
9627         public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9628         {
9629             var uriStr = uri.AbsoluteUri;
9630
9631             // OpenTween 内部で使用する URL
9632             if (uri.Authority == "opentween")
9633             {
9634                 await this.OpenInternalUriAsync(uri);
9635                 return;
9636             }
9637
9638             // ハッシュタグを含む Twitter 検索
9639             if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9640             {
9641                 // ハッシュタグの場合は、タブで開く
9642                 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9643                 var pos = unescapedQuery.IndexOf('#');
9644                 if (pos == -1) return;
9645
9646                 var hash = unescapedQuery.Substring(pos);
9647                 this.HashSupl.AddItem(hash);
9648                 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9649                 this.AddNewTabForSearch(hash);
9650                 return;
9651             }
9652
9653             // ユーザープロフィールURL
9654             // フラグが立っている場合は設定と逆の動作をする
9655             if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9656                 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9657             {
9658                 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9659                 if (userUriMatch.Success)
9660                 {
9661                     var screenName = userUriMatch.Groups["ScreenName"].Value;
9662                     if (this.IsTwitterId(screenName))
9663                     {
9664                         await this.AddNewTabForUserTimeline(screenName);
9665                         return;
9666                     }
9667                 }
9668             }
9669
9670             // どのパターンにも該当しないURL
9671             await this.OpenUriInBrowserAsync(uriStr);
9672         }
9673
9674         /// <summary>
9675         /// OpenTween 内部の機能を呼び出すための URL を開きます
9676         /// </summary>
9677         private async Task OpenInternalUriAsync(Uri uri)
9678         {
9679             // ツイートを開く (//opentween/status/:status_id)
9680             var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9681             if (match.Success)
9682             {
9683                 var statusId = long.Parse(match.Groups[1].Value);
9684                 await this.OpenRelatedTab(statusId);
9685                 return;
9686             }
9687         }
9688
9689         public Task OpenUriInBrowserAsync(string UriString)
9690         {
9691             return Task.Run(() =>
9692             {
9693                 var myPath = UriString;
9694
9695                 try
9696                 {
9697                     var configBrowserPath = SettingManager.Local.BrowserPath;
9698                     if (!string.IsNullOrEmpty(configBrowserPath))
9699                     {
9700                         if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9701                         {
9702                             var sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9703                             var browserPath = configBrowserPath.Substring(1, sep - 1);
9704                             var arg = "";
9705                             if (sep < configBrowserPath.Length - 1)
9706                             {
9707                                 arg = configBrowserPath.Substring(sep + 1);
9708                             }
9709                             myPath = arg + " " + myPath;
9710                             System.Diagnostics.Process.Start(browserPath, myPath);
9711                         }
9712                         else
9713                         {
9714                             System.Diagnostics.Process.Start(configBrowserPath, myPath);
9715                         }
9716                     }
9717                     else
9718                     {
9719                         System.Diagnostics.Process.Start(myPath);
9720                     }
9721                 }
9722                 catch (Exception)
9723                 {
9724                     //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9725                 }
9726             });
9727         }
9728
9729         private void ListTabSelect(TabPage _tab)
9730         {
9731             SetListProperty();
9732
9733             this.PurgeListViewItemCache();
9734
9735             this._statuses.SelectTab(_tab.Text);
9736
9737             var listView = this.CurrentListView;
9738
9739             _anchorPost = null;
9740             _anchorFlag = false;
9741
9742             if (_iconCol)
9743             {
9744                 listView.Columns[1].Text = ColumnText[2];
9745             }
9746             else
9747             {
9748                 for (var i = 0; i < listView.Columns.Count; i++)
9749                 {
9750                     listView.Columns[i].Text = ColumnText[i];
9751                 }
9752             }
9753         }
9754
9755         private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9756             => this.ListTabSelect(e.TabPage);
9757
9758         private void SelectListItem(DetailsListView LView, int Index)
9759         {
9760             //単一
9761             var bnd = new Rectangle();
9762             var flg = false;
9763             var item = LView.FocusedItem;
9764             if (item != null)
9765             {
9766                 bnd = item.Bounds;
9767                 flg = true;
9768             }
9769
9770             do
9771             {
9772                 LView.SelectedIndices.Clear();
9773             }
9774             while (LView.SelectedIndices.Count > 0);
9775             item = LView.Items[Index];
9776             item.Selected = true;
9777             item.Focused = true;
9778
9779             if (flg) LView.Invalidate(bnd);
9780         }
9781
9782         private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9783         {
9784             //複数
9785             var bnd = new Rectangle();
9786             var flg = false;
9787             var item = LView.FocusedItem;
9788             if (item != null)
9789             {
9790                 bnd = item.Bounds;
9791                 flg = true;
9792             }
9793
9794             if (Index != null)
9795             {
9796                 do
9797                 {
9798                     LView.SelectedIndices.Clear();
9799                 }
9800                 while (LView.SelectedIndices.Count > 0);
9801                 LView.SelectItems(Index);
9802             }
9803             if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9804             {
9805                 LView.SelectionMark = selectionMarkIndex;
9806             }
9807             if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9808             {
9809                 LView.Items[focusedIndex].Focused = true;
9810             }
9811             else if (Index != null && Index.Length != 0)
9812             {
9813                 LView.Items[Index.Last()].Focused = true;
9814             }
9815
9816             if (flg) LView.Invalidate(bnd);
9817         }
9818
9819         private void StartUserStream()
9820         {
9821             tw.NewPostFromStream += tw_NewPostFromStream;
9822             tw.UserStreamStarted += tw_UserStreamStarted;
9823             tw.UserStreamStopped += tw_UserStreamStopped;
9824             tw.PostDeleted += tw_PostDeleted;
9825             tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9826
9827             this.RefreshUserStreamsMenu();
9828
9829             if (SettingManager.Common.UserstreamStartup)
9830                 tw.StartUserStream();
9831         }
9832
9833         private async void TweenMain_Shown(object sender, EventArgs e)
9834         {
9835             NotifyIcon1.Visible = true;
9836
9837             if (this.IsNetworkAvailable())
9838             {
9839                 StartUserStream();
9840
9841                 var loadTasks = new List<Task>
9842                 {
9843                     this.RefreshMuteUserIdsAsync(),
9844                     this.RefreshBlockIdsAsync(),
9845                     this.RefreshNoRetweetIdsAsync(),
9846                     this.RefreshTwitterConfigurationAsync(),
9847                     this.RefreshTabAsync<HomeTabModel>(),
9848                     this.RefreshTabAsync<MentionsTabModel>(),
9849                     this.RefreshTabAsync<DirectMessagesTabModel>(),
9850                     this.RefreshTabAsync<PublicSearchTabModel>(),
9851                     this.RefreshTabAsync<UserTimelineTabModel>(),
9852                     this.RefreshTabAsync<ListTimelineTabModel>(),
9853                 };
9854
9855                 if (SettingManager.Common.StartupFollowers)
9856                     loadTasks.Add(this.RefreshFollowerIdsAsync());
9857
9858                 if (SettingManager.Common.GetFav)
9859                     loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>());
9860
9861                 var allTasks = Task.WhenAll(loadTasks);
9862
9863                 var i = 0;
9864                 while (true)
9865                 {
9866                     var timeout = Task.Delay(5000);
9867                     if (await Task.WhenAny(allTasks, timeout) != timeout)
9868                         break;
9869
9870                     i += 1;
9871                     if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
9872
9873                     if (MyCommon._endingFlag)
9874                         return;
9875                 }
9876
9877                 if (MyCommon._endingFlag) return;
9878
9879                 if (ApplicationSettings.VersionInfoUrl != null)
9880                 {
9881                     //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
9882                     if (SettingManager.Common.StartupVersion)
9883                         await this.CheckNewVersion(true);
9884                 }
9885                 else
9886                 {
9887                     // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
9888                     this.VerUpMenuItem.Enabled = false;
9889                     this.VerUpMenuItem.Available = false;
9890                     this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
9891                 }
9892
9893                 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
9894                 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
9895                 {
9896                     MessageBox.Show(Properties.Resources.ReAuthorizeText);
9897                     SettingStripMenuItem_Click(null, null);
9898                 }
9899
9900                 // 取得失敗の場合は再試行する
9901                 var reloadTasks = new List<Task>();
9902
9903                 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
9904                     reloadTasks.Add(this.RefreshFollowerIdsAsync());
9905
9906                 if (!tw.GetNoRetweetSuccess)
9907                     reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
9908
9909                 if (this.tw.Configuration.PhotoSizeLimit == 0)
9910                     reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
9911
9912                 await Task.WhenAll(reloadTasks);
9913             }
9914
9915             _initial = false;
9916
9917             this.timelineScheduler.Enabled = true;
9918         }
9919
9920         private async Task doGetFollowersMenu()
9921         {
9922             await this.RefreshFollowerIdsAsync();
9923             this.DispSelectedPost(true);
9924         }
9925
9926         private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
9927             => await this.doGetFollowersMenu();
9928
9929         private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
9930             => this.doReTweetUnofficial();
9931
9932         private async Task doReTweetOfficial(bool isConfirm)
9933         {
9934             //公式RT
9935             if (this.ExistCurrentPost)
9936             {
9937                 var selectedPosts = this.CurrentTab.SelectedPosts;
9938
9939                 if (selectedPosts.Any(x => !x.CanRetweetBy(this.twitterApi.CurrentUserId)))
9940                 {
9941                     if (selectedPosts.Any(x => x.IsProtect))
9942                         MessageBox.Show("Protected.");
9943
9944                     _DoFavRetweetFlags = false;
9945                     return;
9946                 }
9947
9948                 if (selectedPosts.Length > 15)
9949                 {
9950                     MessageBox.Show(Properties.Resources.RetweetLimitText);
9951                     _DoFavRetweetFlags = false;
9952                     return;
9953                 }
9954                 else if (selectedPosts.Length > 1)
9955                 {
9956                     var QuestionText = Properties.Resources.RetweetQuestion2;
9957                     if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
9958                     switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
9959                     {
9960                         case DialogResult.Cancel:
9961                         case DialogResult.No:
9962                             _DoFavRetweetFlags = false;
9963                             return;
9964                     }
9965                 }
9966                 else
9967                 {
9968                     if (!SettingManager.Common.RetweetNoConfirm)
9969                     {
9970                         var Questiontext = Properties.Resources.RetweetQuestion1;
9971                         if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
9972                         if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9973                         {
9974                             _DoFavRetweetFlags = false;
9975                             return;
9976                         }
9977                     }
9978                 }
9979
9980                 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
9981
9982                 await this.RetweetAsync(statusIds);
9983             }
9984         }
9985
9986         private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
9987             => await this.doReTweetOfficial(true);
9988
9989         private async Task FavoritesRetweetOfficial()
9990         {
9991             if (!this.ExistCurrentPost) return;
9992             _DoFavRetweetFlags = true;
9993             var retweetTask = this.doReTweetOfficial(true);
9994             if (_DoFavRetweetFlags)
9995             {
9996                 _DoFavRetweetFlags = false;
9997                 var favoriteTask = this.FavoriteChange(true, false);
9998
9999                 await Task.WhenAll(retweetTask, favoriteTask);
10000             }
10001             else
10002             {
10003                 await retweetTask;
10004             }
10005         }
10006
10007         private async Task FavoritesRetweetUnofficial()
10008         {
10009             var post = this.CurrentPost;
10010             if (this.ExistCurrentPost && !post.IsDm)
10011             {
10012                 _DoFavRetweetFlags = true;
10013                 var favoriteTask = this.FavoriteChange(true);
10014                 if (!post.IsProtect && _DoFavRetweetFlags)
10015                 {
10016                     _DoFavRetweetFlags = false;
10017                     doReTweetUnofficial();
10018                 }
10019
10020                 await favoriteTask;
10021             }
10022         }
10023
10024         /// <summary>
10025         /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10026         /// </summary>
10027         /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10028         /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10029         /// <returns>復元されたツイート本文</returns>
10030         internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10031         {
10032             // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10033
10034             // 通常の URL
10035             statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10036             // メンション
10037             statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10038             // ハッシュタグ
10039             statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10040             // 絵文字
10041             statusHtml = Regex.Replace(statusHtml, "<img class=\"emoji\" src=\".+?\" alt=\"(?<text>.+?)\" />", "${text}");
10042
10043             // <br> 除去
10044             if (multiline)
10045                 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10046             else
10047                 statusHtml = statusHtml.Replace("<br>", " ");
10048
10049             // &nbsp; は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10050             // 現状では半角スペースの代用として &nbsp; を使用しているため U+0020 に置換します
10051             statusHtml = statusHtml.Replace("&nbsp;", " ");
10052
10053             return WebUtility.HtmlDecode(statusHtml);
10054         }
10055
10056         private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10057         {
10058             this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10059
10060             if (this.CurrentPost != null)
10061                 this.DispSelectedPost(true);
10062         }
10063
10064         private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10065         {
10066             if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10067                 DebugModeToolStripMenuItem.Visible = true;
10068             else
10069                 DebugModeToolStripMenuItem.Visible = false;
10070         }
10071
10072         private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
10073             => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
10074
10075         private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
10076             => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
10077
10078         private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
10079             => SettingManager.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
10080
10081         private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
10082         {
10083             SettingManager.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
10084             this.MarkSettingCommonModified();
10085         }
10086
10087         private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10088         {
10089             SettingManager.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
10090             this.MarkSettingCommonModified();
10091         }
10092
10093         private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
10094         {
10095             UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
10096             PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
10097             UrlAutoShortenMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10098             IdeographicSpaceToSpaceMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10099             MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
10100             FocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10101         }
10102
10103         private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10104         {
10105             UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
10106             PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
10107             UrlAutoShortenPullDownMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10108             IdeographicSpaceToSpacePullDownMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10109             MultiLinePullDownMenuItem.Checked = SettingManager.Local.StatusMultiline;
10110             FocusLockPullDownMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10111         }
10112
10113         private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10114         {
10115             if (TraceOutToolStripMenuItem.Checked)
10116                 MyCommon.TraceFlag = true;
10117             else
10118                 MyCommon.TraceFlag = false;
10119         }
10120
10121         private void TweenMain_Deactivate(object sender, EventArgs e)
10122             => this.StatusText_Leave(StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10123
10124         private void TabRenameMenuItem_Click(object sender, EventArgs e)
10125         {
10126             if (string.IsNullOrEmpty(_rclickTabName)) return;
10127
10128             _ = TabRename(_rclickTabName, out _);
10129         }
10130
10131         private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10132             => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10133
10134         private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10135             => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10136
10137         private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10138         {
10139             TwitterApiStatus apiStatus;
10140
10141             using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10142             {
10143                 var cancellationToken = dialog.EnableCancellation();
10144
10145                 try
10146                 {
10147                     var task = this.tw.GetInfoApi();
10148                     apiStatus = await dialog.WaitForAsync(this, task);
10149                 }
10150                 catch (WebApiException)
10151                 {
10152                     apiStatus = null;
10153                 }
10154
10155                 if (cancellationToken.IsCancellationRequested)
10156                     return;
10157
10158                 if (apiStatus == null)
10159                 {
10160                     MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10161                     return;
10162                 }
10163             }
10164
10165             using var apiDlg = new ApiInfoDialog();
10166             apiDlg.ShowDialog(this);
10167         }
10168
10169         private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10170         {
10171             var id = this.CurrentPost?.ScreenName ?? "";
10172
10173             await this.FollowCommand(id);
10174         }
10175
10176         internal async Task FollowCommand(string id)
10177         {
10178             using (var inputName = new InputTabName())
10179             {
10180                 inputName.FormTitle = "Follow";
10181                 inputName.FormDescription = Properties.Resources.FRMessage1;
10182                 inputName.TabName = id;
10183
10184                 if (inputName.ShowDialog(this) != DialogResult.OK)
10185                     return;
10186                 if (string.IsNullOrWhiteSpace(inputName.TabName))
10187                     return;
10188
10189                 id = inputName.TabName.Trim();
10190             }
10191
10192             using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10193             {
10194                 try
10195                 {
10196                     var task = this.twitterApi.FriendshipsCreate(id).IgnoreResponse();
10197                     await dialog.WaitForAsync(this, task);
10198                 }
10199                 catch (WebApiException ex)
10200                 {
10201                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10202                     return;
10203                 }
10204             }
10205
10206             MessageBox.Show(Properties.Resources.FRMessage3);
10207         }
10208
10209         private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10210         {
10211             var id = this.CurrentPost?.ScreenName ?? "";
10212
10213             await this.RemoveCommand(id, false);
10214         }
10215
10216         internal async Task RemoveCommand(string id, bool skipInput)
10217         {
10218             if (!skipInput)
10219             {
10220                 using var inputName = new InputTabName();
10221                 inputName.FormTitle = "Unfollow";
10222                 inputName.FormDescription = Properties.Resources.FRMessage1;
10223                 inputName.TabName = id;
10224
10225                 if (inputName.ShowDialog(this) != DialogResult.OK)
10226                     return;
10227                 if (string.IsNullOrWhiteSpace(inputName.TabName))
10228                     return;
10229
10230                 id = inputName.TabName.Trim();
10231             }
10232
10233             using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10234             {
10235                 try
10236                 {
10237                     var task = this.twitterApi.FriendshipsDestroy(id).IgnoreResponse();
10238                     await dialog.WaitForAsync(this, task);
10239                 }
10240                 catch (WebApiException ex)
10241                 {
10242                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10243                     return;
10244                 }
10245             }
10246
10247             MessageBox.Show(Properties.Resources.FRMessage3);
10248         }
10249
10250         private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10251         {
10252             var id = this.CurrentPost?.ScreenName ?? "";
10253
10254             await this.ShowFriendship(id);
10255         }
10256
10257         internal async Task ShowFriendship(string id)
10258         {
10259             using (var inputName = new InputTabName())
10260             {
10261                 inputName.FormTitle = "Show Friendships";
10262                 inputName.FormDescription = Properties.Resources.FRMessage1;
10263                 inputName.TabName = id;
10264
10265                 if (inputName.ShowDialog(this) != DialogResult.OK)
10266                     return;
10267                 if (string.IsNullOrWhiteSpace(inputName.TabName))
10268                     return;
10269
10270                 id = inputName.TabName.Trim();
10271             }
10272
10273             bool isFollowing, isFollowed;
10274
10275             using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10276             {
10277                 var cancellationToken = dialog.EnableCancellation();
10278
10279                 try
10280                 {
10281                     var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10282                     var friendship = await dialog.WaitForAsync(this, task);
10283
10284                     isFollowing = friendship.Relationship.Source.Following;
10285                     isFollowed = friendship.Relationship.Source.FollowedBy;
10286                 }
10287                 catch (WebApiException ex)
10288                 {
10289                     if (!cancellationToken.IsCancellationRequested)
10290                         MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10291                     return;
10292                 }
10293
10294                 if (cancellationToken.IsCancellationRequested)
10295                     return;
10296             }
10297
10298             string result;
10299             if (isFollowing)
10300             {
10301                 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10302             }
10303             else
10304             {
10305                 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10306             }
10307             if (isFollowed)
10308             {
10309                 result += Properties.Resources.GetFriendshipInfo3;
10310             }
10311             else
10312             {
10313                 result += Properties.Resources.GetFriendshipInfo4;
10314             }
10315             result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10316             MessageBox.Show(result);
10317         }
10318
10319         internal async Task ShowFriendship(string[] ids)
10320         {
10321             foreach (var id in ids)
10322             {
10323                 bool isFollowing, isFollowed;
10324
10325                 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10326                 {
10327                     var cancellationToken = dialog.EnableCancellation();
10328
10329                     try
10330                     {
10331                         var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10332                         var friendship = await dialog.WaitForAsync(this, task);
10333
10334                         isFollowing = friendship.Relationship.Source.Following;
10335                         isFollowed = friendship.Relationship.Source.FollowedBy;
10336                     }
10337                     catch (WebApiException ex)
10338                     {
10339                         if (!cancellationToken.IsCancellationRequested)
10340                             MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10341                         return;
10342                     }
10343
10344                     if (cancellationToken.IsCancellationRequested)
10345                         return;
10346                 }
10347
10348                 var result = "";
10349                 var ff = "";
10350
10351                 ff = "  ";
10352                 if (isFollowing)
10353                 {
10354                     ff += Properties.Resources.GetFriendshipInfo1;
10355                 }
10356                 else
10357                 {
10358                     ff += Properties.Resources.GetFriendshipInfo2;
10359                 }
10360
10361                 ff += System.Environment.NewLine + "  ";
10362                 if (isFollowed)
10363                 {
10364                     ff += Properties.Resources.GetFriendshipInfo3;
10365                 }
10366                 else
10367                 {
10368                     ff += Properties.Resources.GetFriendshipInfo4;
10369                 }
10370                 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10371                 if (isFollowing)
10372                 {
10373                     if (MessageBox.Show(
10374                         Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10375                         MessageBoxButtons.YesNo,
10376                         MessageBoxIcon.Question,
10377                         MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10378                     {
10379                         await this.RemoveCommand(id, true);
10380                     }
10381                 }
10382                 else
10383                 {
10384                     MessageBox.Show(result);
10385                 }
10386             }
10387         }
10388
10389         private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10390             => await this.doShowUserStatus(tw.Username, false);
10391
10392         // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10393         // URLから切り出した文字列を渡す
10394
10395         public bool IsTwitterId(string name)
10396         {
10397             if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10398                 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10399             else
10400                 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
10401         }
10402
10403         private void doQuoteOfficial()
10404         {
10405             if (this.ExistCurrentPost)
10406             {
10407                 var post = this.CurrentPost;
10408                 if (post.IsDm || !StatusText.Enabled)
10409                     return;
10410
10411                 if (post.IsProtect)
10412                 {
10413                     MessageBox.Show("Protected.");
10414                     return;
10415                 }
10416
10417                 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10418
10419                 this.inReplyTo = null;
10420
10421                 StatusText.Text += " " + MyCommon.GetStatusUrl(post);
10422
10423                 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10424                 StatusText.Focus();
10425             }
10426         }
10427
10428         private void doReTweetUnofficial()
10429         {
10430             //RT @id:内容
10431             if (this.ExistCurrentPost)
10432             {
10433                 var post = this.CurrentPost;
10434                 if (post.IsDm || !StatusText.Enabled)
10435                     return;
10436
10437                 if (post.IsProtect)
10438                 {
10439                     MessageBox.Show("Protected.");
10440                     return;
10441                 }
10442                 var rtdata = post.Text;
10443                 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10444
10445                 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10446
10447                 // 投稿時に in_reply_to_status_id を付加する
10448                 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
10449                 var inReplyToScreenName = post.ScreenName;
10450                 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
10451
10452                 StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
10453
10454                 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10455                 StatusText.Focus();
10456             }
10457         }
10458
10459         private void QuoteStripMenuItem_Click(object sender, EventArgs e)
10460             => this.doQuoteOfficial();
10461
10462         private async void SearchButton_Click(object sender, EventArgs e)
10463         {
10464             //公式検索
10465             var pnl = ((Control)sender).Parent;
10466             if (pnl == null) return;
10467             var tbName = pnl.Parent.Text;
10468             var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10469             var cmb = (ComboBox)pnl.Controls["comboSearch"];
10470             var cmbLang = (ComboBox)pnl.Controls["comboLang"];
10471             cmb.Text = cmb.Text.Trim();
10472             // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10473             var Quote = false;
10474             var buf = new StringBuilder();
10475             var c = cmb.Text.ToCharArray();
10476             for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
10477             {
10478                 if (cnt > cmb.Text.Length - 4)
10479                 {
10480                     buf.Append(cmb.Text.Substring(cnt));
10481                     break;
10482                 }
10483                 if (c[cnt] == '"')
10484                 {
10485                     Quote = !Quote;
10486                 }
10487                 else
10488                 {
10489                     if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10490                     {
10491                         buf.Append(" OR ");
10492                         cnt += 3;
10493                         continue;
10494                     }
10495                 }
10496                 buf.Append(c[cnt]);
10497             }
10498             cmb.Text = buf.ToString();
10499
10500             var listView = (DetailsListView)pnl.Parent.Tag;
10501
10502             var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10503
10504             tb.SearchWords = cmb.Text;
10505             tb.SearchLang = cmbLang.Text;
10506             if (string.IsNullOrEmpty(cmb.Text))
10507             {
10508                 listView.Focus();
10509                 SaveConfigsTabs();
10510                 return;
10511             }
10512             if (queryChanged)
10513             {
10514                 var idx = cmb.Items.IndexOf(tb.SearchWords);
10515                 if (idx > -1) cmb.Items.RemoveAt(idx);
10516                 cmb.Items.Insert(0, tb.SearchWords);
10517                 cmb.Text = tb.SearchWords;
10518                 cmb.SelectAll();
10519                 this.PurgeListViewItemCache();
10520                 listView.VirtualListSize = 0;
10521                 _statuses.ClearTabIds(tbName);
10522                 SaveConfigsTabs();   //検索条件の保存
10523             }
10524
10525             listView.Focus();
10526             await this.RefreshTabAsync(tb);
10527         }
10528
10529         private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10530             => await this.DoRefreshMore(); // もっと前を取得
10531
10532         /// <summary>
10533         /// 指定されたタブのListTabにおける位置を返します
10534         /// </summary>
10535         /// <remarks>
10536         /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10537         /// </remarks>
10538         public int GetTabPageIndex(string tabName)
10539             => this._statuses.Tabs.IndexOf(tabName);
10540
10541         private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10542         {
10543             if (_statuses.RemovedTab.Count == 0)
10544             {
10545                 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10546                 return;
10547             }
10548             else
10549             {
10550                 var tb = _statuses.RemovedTab.Pop();
10551                 DetailsListView listView;
10552                 if (tb.TabType == MyCommon.TabUsageType.Related)
10553                 {
10554                     var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10555                     if (relatedTab != null)
10556                     {
10557                         // 関連発言なら既存のタブを置き換える
10558                         tb.TabName = relatedTab.TabName;
10559                         this.ClearTab(tb.TabName, false);
10560
10561                         this._statuses.ReplaceTab(tb);
10562
10563                         var tabIndex = this._statuses.Tabs.IndexOf(tb);
10564                         var tabPage = this.ListTab.TabPages[tabIndex];
10565                         listView = (DetailsListView)tabPage.Tag;
10566                         this.ListTab.SelectedIndex = tabIndex;
10567                     }
10568                     else
10569                     {
10570                         const string TabName = "Related Tweets";
10571                         var renamed = TabName;
10572                         for (var i = 2; i <= 100; i++)
10573                         {
10574                             if (!_statuses.ContainsTab(renamed))
10575                                 break;
10576                             renamed = TabName + i;
10577                         }
10578                         tb.TabName = renamed;
10579
10580                         _statuses.AddTab(tb);
10581                         AddNewTab(tb, startup: false);
10582
10583                         var tabIndex = this._statuses.Tabs.Count - 1;
10584                         var tabPage = this.ListTab.TabPages[tabIndex];
10585
10586                         listView = (DetailsListView)tabPage.Tag;
10587                         this.ListTab.SelectedIndex = tabIndex;
10588                     }
10589                 }
10590                 else
10591                 {
10592                     var renamed = tb.TabName;
10593                     for (var i = 1; i < int.MaxValue; i++)
10594                     {
10595                         if (!_statuses.ContainsTab(renamed))
10596                             break;
10597                         renamed = tb.TabName + "(" + i + ")";
10598                     }
10599                     tb.TabName = renamed;
10600
10601                     _statuses.AddTab(tb);
10602                     AddNewTab(tb, startup: false);
10603
10604                     var tabIndex = this._statuses.Tabs.Count - 1;
10605                     var tabPage = this.ListTab.TabPages[tabIndex];
10606
10607                     listView = (DetailsListView)tabPage.Tag;
10608                     this.ListTab.SelectedIndex = tabIndex;
10609                 }
10610                 SaveConfigsTabs();
10611
10612                 if (listView != null)
10613                 {
10614                     using (ControlTransaction.Update(listView))
10615                     {
10616                         listView.VirtualListSize = tb.AllCount;
10617                     }
10618                 }
10619             }
10620         }
10621
10622         private async Task doMoveToRTHome()
10623         {
10624             var post = this.CurrentPost;
10625             if (post != null && post.RetweetedId != null)
10626                 await this.OpenUriInBrowserAsync("https://twitter.com/" + post.RetweetedBy);
10627         }
10628
10629         private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10630             => await this.doMoveToRTHome();
10631
10632         private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10633         {
10634             var screenName = this.CurrentPost?.ScreenName;
10635             if (screenName != null)
10636                 this.ListManageUserContext(screenName);
10637         }
10638
10639         public void ListManageUserContext(string screenName)
10640         {
10641             using var listSelectForm = new MyLists(screenName, this.twitterApi);
10642             listSelectForm.ShowDialog(this);
10643         }
10644
10645         private void SearchControls_Enter(object sender, EventArgs e)
10646         {
10647             var pnl = (Control)sender;
10648             foreach (Control ctl in pnl.Controls)
10649             {
10650                 ctl.TabStop = true;
10651             }
10652         }
10653
10654         private void SearchControls_Leave(object sender, EventArgs e)
10655         {
10656             var pnl = (Control)sender;
10657             foreach (Control ctl in pnl.Controls)
10658             {
10659                 ctl.TabStop = false;
10660             }
10661         }
10662
10663         private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10664         {
10665             var tab = this.CurrentTab;
10666             if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
10667             this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
10668         }
10669
10670         private void StatusLabel_DoubleClick(object sender, EventArgs e)
10671             => MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10672
10673         private void HashManageMenuItem_Click(object sender, EventArgs e)
10674         {
10675             DialogResult rslt;
10676             try
10677             {
10678                 rslt = HashMgr.ShowDialog();
10679             }
10680             catch (Exception)
10681             {
10682                 return;
10683             }
10684             this.TopMost = SettingManager.Common.AlwaysTop;
10685             if (rslt == DialogResult.Cancel) return;
10686             if (!string.IsNullOrEmpty(HashMgr.UseHash))
10687             {
10688                 HashStripSplitButton.Text = HashMgr.UseHash;
10689                 HashTogglePullDownMenuItem.Checked = true;
10690                 HashToggleMenuItem.Checked = true;
10691             }
10692             else
10693             {
10694                 HashStripSplitButton.Text = "#[-]";
10695                 HashTogglePullDownMenuItem.Checked = false;
10696                 HashToggleMenuItem.Checked = false;
10697             }
10698             //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10699             //{
10700             //    int sidx = StatusText.SelectionStart;
10701             //    string hash = HashMgr.UseHash + " ";
10702             //    if (sidx > 0)
10703             //    {
10704             //        if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10705             //            hash = " " + hash;
10706             //    }
10707             //    StatusText.Text = StatusText.Text.Insert(sidx, hash);
10708             //    sidx += hash.Length;
10709             //    StatusText.SelectionStart = sidx;
10710             //    StatusText.Focus();
10711             //}
10712             this.MarkSettingCommonModified();
10713             this.StatusText_TextChanged(null, null);
10714         }
10715
10716         private void HashToggleMenuItem_Click(object sender, EventArgs e)
10717         {
10718             HashMgr.ToggleHash();
10719             if (!string.IsNullOrEmpty(HashMgr.UseHash))
10720             {
10721                 HashStripSplitButton.Text = HashMgr.UseHash;
10722                 HashToggleMenuItem.Checked = true;
10723                 HashTogglePullDownMenuItem.Checked = true;
10724             }
10725             else
10726             {
10727                 HashStripSplitButton.Text = "#[-]";
10728                 HashToggleMenuItem.Checked = false;
10729                 HashTogglePullDownMenuItem.Checked = false;
10730             }
10731             this.MarkSettingCommonModified();
10732             this.StatusText_TextChanged(null, null);
10733         }
10734
10735         private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10736             => this.HashToggleMenuItem_Click(null, null);
10737
10738         public void SetPermanentHashtag(string hashtag)
10739         {
10740             HashMgr.SetPermanentHash("#" + hashtag);
10741             HashStripSplitButton.Text = HashMgr.UseHash;
10742             HashTogglePullDownMenuItem.Checked = true;
10743             HashToggleMenuItem.Checked = true;
10744             //使用ハッシュタグとして設定
10745             this.MarkSettingCommonModified();
10746         }
10747
10748         private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10749         {
10750             if (!this.ExistCurrentPost)
10751             {
10752                 this.ReplyOpMenuItem.Enabled = false;
10753                 this.ReplyAllOpMenuItem.Enabled = false;
10754                 this.DmOpMenuItem.Enabled = false;
10755                 this.ShowProfMenuItem.Enabled = false;
10756                 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10757                 this.ListManageMenuItem.Enabled = false;
10758                 this.OpenFavOpMenuItem.Enabled = false;
10759                 this.CreateTabRuleOpMenuItem.Enabled = false;
10760                 this.CreateIdRuleOpMenuItem.Enabled = false;
10761                 this.CreateSourceRuleOpMenuItem.Enabled = false;
10762                 this.ReadOpMenuItem.Enabled = false;
10763                 this.UnreadOpMenuItem.Enabled = false;
10764             }
10765             else
10766             {
10767                 this.ReplyOpMenuItem.Enabled = true;
10768                 this.ReplyAllOpMenuItem.Enabled = true;
10769                 this.DmOpMenuItem.Enabled = true;
10770                 this.ShowProfMenuItem.Enabled = true;
10771                 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10772                 this.ListManageMenuItem.Enabled = true;
10773                 this.OpenFavOpMenuItem.Enabled = true;
10774                 this.CreateTabRuleOpMenuItem.Enabled = true;
10775                 this.CreateIdRuleOpMenuItem.Enabled = true;
10776                 this.CreateSourceRuleOpMenuItem.Enabled = true;
10777                 this.ReadOpMenuItem.Enabled = true;
10778                 this.UnreadOpMenuItem.Enabled = true;
10779             }
10780
10781             var tab = this.CurrentTab;
10782             var post = this.CurrentPost;
10783             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post.IsDm)
10784             {
10785                 this.FavOpMenuItem.Enabled = false;
10786                 this.UnFavOpMenuItem.Enabled = false;
10787                 this.OpenStatusOpMenuItem.Enabled = false;
10788                 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10789                 this.RtOpMenuItem.Enabled = false;
10790                 this.RtUnOpMenuItem.Enabled = false;
10791                 this.QtOpMenuItem.Enabled = false;
10792                 this.FavoriteRetweetMenuItem.Enabled = false;
10793                 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10794             }
10795             else
10796             {
10797                 this.FavOpMenuItem.Enabled = true;
10798                 this.UnFavOpMenuItem.Enabled = true;
10799                 this.OpenStatusOpMenuItem.Enabled = true;
10800                 this.ShowRelatedStatusesMenuItem2.Enabled = true;  //PublicSearchの時問題出るかも
10801
10802                 if (!post.CanRetweetBy(this.twitterApi.CurrentUserId))
10803                 {
10804                     this.RtOpMenuItem.Enabled = false;
10805                     this.RtUnOpMenuItem.Enabled = false;
10806                     this.QtOpMenuItem.Enabled = false;
10807                     this.FavoriteRetweetMenuItem.Enabled = false;
10808                     this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10809                 }
10810                 else
10811                 {
10812                     this.RtOpMenuItem.Enabled = true;
10813                     this.RtUnOpMenuItem.Enabled = true;
10814                     this.QtOpMenuItem.Enabled = true;
10815                     this.FavoriteRetweetMenuItem.Enabled = true;
10816                     this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
10817                 }
10818             }
10819
10820             if (tab.TabType != MyCommon.TabUsageType.Favorites)
10821             {
10822                 this.RefreshPrevOpMenuItem.Enabled = true;
10823             }
10824             else
10825             {
10826                 this.RefreshPrevOpMenuItem.Enabled = false;
10827             }
10828             if (!this.ExistCurrentPost || post.InReplyToStatusId == null)
10829             {
10830                 OpenRepSourceOpMenuItem.Enabled = false;
10831             }
10832             else
10833             {
10834                 OpenRepSourceOpMenuItem.Enabled = true;
10835             }
10836             if (!this.ExistCurrentPost || string.IsNullOrEmpty(post.RetweetedBy))
10837             {
10838                 OpenRterHomeMenuItem.Enabled = false;
10839             }
10840             else
10841             {
10842                 OpenRterHomeMenuItem.Enabled = true;
10843             }
10844
10845             if (this.ExistCurrentPost)
10846             {
10847                 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
10848             }
10849         }
10850
10851         private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
10852             => this.ContextMenuTabProperty_Opening(sender, null);
10853
10854         public Twitter TwitterInstance
10855             => this.tw;
10856
10857         private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
10858         {
10859             if (this._initialLayout)
10860                 return;
10861
10862             int splitterDistance;
10863             switch (this.WindowState)
10864             {
10865                 case FormWindowState.Normal:
10866                     splitterDistance = this.SplitContainer3.SplitterDistance;
10867                     break;
10868                 case FormWindowState.Maximized:
10869                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
10870                     var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
10871                     splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
10872                     splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
10873                     break;
10874                 default:
10875                     return;
10876             }
10877
10878             this._mySpDis3 = splitterDistance;
10879             this.MarkSettingLocalModified();
10880         }
10881
10882         private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
10883         {
10884             if (_statuses.RemovedTab.Count == 0)
10885             {
10886                 UndoRemoveTabMenuItem.Enabled = false;
10887             }
10888             else
10889             {
10890                 UndoRemoveTabMenuItem.Enabled = true;
10891             }
10892
10893             if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
10894                 PublicSearchQueryMenuItem.Enabled = true;
10895             else
10896                 PublicSearchQueryMenuItem.Enabled = false;
10897
10898             if (!this.ExistCurrentPost)
10899             {
10900                 this.CopySTOTMenuItem.Enabled = false;
10901                 this.CopyURLMenuItem.Enabled = false;
10902                 this.CopyUserIdStripMenuItem.Enabled = false;
10903             }
10904             else
10905             {
10906                 this.CopySTOTMenuItem.Enabled = true;
10907                 this.CopyURLMenuItem.Enabled = true;
10908                 this.CopyUserIdStripMenuItem.Enabled = true;
10909
10910                 var post = this.CurrentPost;
10911                 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
10912                 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
10913             }
10914         }
10915
10916         private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
10917             => this.SetNotifyIconText();
10918
10919         private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
10920             => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
10921
10922         private async Task doShowUserStatus(string id, bool ShowInputDialog)
10923         {
10924             TwitterUser user = null;
10925
10926             if (ShowInputDialog)
10927             {
10928                 using var inputName = new InputTabName();
10929                 inputName.FormTitle = "Show UserStatus";
10930                 inputName.FormDescription = Properties.Resources.FRMessage1;
10931                 inputName.TabName = id;
10932
10933                 if (inputName.ShowDialog(this) != DialogResult.OK)
10934                     return;
10935                 if (string.IsNullOrWhiteSpace(inputName.TabName))
10936                     return;
10937
10938                 id = inputName.TabName.Trim();
10939             }
10940
10941             using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
10942             {
10943                 var cancellationToken = dialog.EnableCancellation();
10944
10945                 try
10946                 {
10947                     var task = this.twitterApi.UsersShow(id);
10948                     user = await dialog.WaitForAsync(this, task);
10949                 }
10950                 catch (WebApiException ex)
10951                 {
10952                     if (!cancellationToken.IsCancellationRequested)
10953                         MessageBox.Show($"Err:{ex.Message}(UsersShow)");
10954                     return;
10955                 }
10956
10957                 if (cancellationToken.IsCancellationRequested)
10958                     return;
10959             }
10960
10961             await this.doShowUserStatus(user);
10962         }
10963
10964         private async Task doShowUserStatus(TwitterUser user)
10965         {
10966             using var userDialog = new UserInfoDialog(this, this.twitterApi);
10967             var showUserTask = userDialog.ShowUserAsync(user);
10968             userDialog.ShowDialog(this);
10969
10970             this.Activate();
10971             this.BringToFront();
10972
10973             // ユーザー情報の表示が完了するまで userDialog を破棄しない
10974             await showUserTask;
10975         }
10976
10977         internal Task ShowUserStatus(string id, bool ShowInputDialog)
10978             => this.doShowUserStatus(id, ShowInputDialog);
10979
10980         internal Task ShowUserStatus(string id)
10981             => this.doShowUserStatus(id, true);
10982
10983         private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
10984         {
10985             var post = this.CurrentPost;
10986             if (post != null)
10987             {
10988                 await this.ShowUserStatus(post.ScreenName, false);
10989             }
10990         }
10991
10992         private async void RtCountMenuItem_Click(object sender, EventArgs e)
10993         {
10994             if (!this.ExistCurrentPost)
10995                 return;
10996
10997             var post = this.CurrentPost;
10998             var statusId = post.RetweetedId ?? post.StatusId;
10999             TwitterStatus status;
11000
11001             using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11002             {
11003                 var cancellationToken = dialog.EnableCancellation();
11004
11005                 try
11006                 {
11007                     var task = this.twitterApi.StatusesShow(statusId);
11008                     status = await dialog.WaitForAsync(this, task);
11009                 }
11010                 catch (WebApiException ex)
11011                 {
11012                     if (!cancellationToken.IsCancellationRequested)
11013                         MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11014                     return;
11015                 }
11016
11017                 if (cancellationToken.IsCancellationRequested)
11018                     return;
11019             }
11020
11021             MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11022         }
11023
11024         private readonly HookGlobalHotkey _hookGlobalHotkey;
11025         public TweenMain()
11026         {
11027             _hookGlobalHotkey = new HookGlobalHotkey(this);
11028
11029             // この呼び出しは、Windows フォーム デザイナで必要です。
11030             InitializeComponent();
11031
11032             // InitializeComponent() 呼び出しの後で初期化を追加します。
11033
11034             if (!this.DesignMode)
11035             {
11036                 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11037                 this.StatusText.Dock = DockStyle.Fill;
11038             }
11039
11040             this.tweetDetailsView.Owner = this;
11041
11042             this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11043             this.gh.NotifyClicked += GrowlHelper_Callback;
11044
11045             // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11046             this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11047
11048             this.ImageSelector.Visible = false;
11049             this.ImageSelector.Enabled = false;
11050             this.ImageSelector.FilePickDialog = OpenFileDialog1;
11051
11052             this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11053
11054             this.ReplaceAppName();
11055             this.InitializeShortcuts();
11056         }
11057
11058         private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11059         {
11060             if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11061             {
11062                 //アイコン化
11063                 this.Visible = false;
11064             }
11065             else if (Form.ActiveForm == null)
11066             {
11067                 this.Visible = true;
11068                 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11069                 this.Activate();
11070                 this.BringToFront();
11071                 this.StatusText.Focus();
11072             }
11073         }
11074
11075         private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11076             => this.MultiLinePullDownMenuItem.PerformClick();
11077
11078 #region "画像投稿"
11079         private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11080         {
11081             if (ImageSelector.Visible)
11082                 ImageSelector.EndSelection();
11083             else
11084                 ImageSelector.BeginSelection();
11085         }
11086
11087         private void SelectMedia_DragEnter(DragEventArgs e)
11088         {
11089             if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11090             {
11091                 e.Effect = DragDropEffects.Copy;
11092                 return;
11093             }
11094             e.Effect = DragDropEffects.None;
11095         }
11096
11097         private void SelectMedia_DragDrop(DragEventArgs e)
11098         {
11099             this.Activate();
11100             this.BringToFront();
11101             ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11102             StatusText.Focus();
11103         }
11104
11105         private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11106         {
11107             TimelinePanel.Visible = false;
11108             TimelinePanel.Enabled = false;
11109         }
11110
11111         private void ImageSelector_EndSelecting(object sender, EventArgs e)
11112         {
11113             TimelinePanel.Visible = true;
11114             TimelinePanel.Enabled = true;
11115             this.CurrentListView.Focus();
11116         }
11117
11118         private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11119             => this.AllowDrop = false;
11120
11121         private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11122             => this.AllowDrop = true;
11123
11124         private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11125         {
11126             if (ImageSelector.Visible)
11127             {
11128                 this.MarkSettingCommonModified();
11129                 this.StatusText_TextChanged(null, null);
11130             }
11131         }
11132
11133         private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11134             => this.StatusText_TextChanged(null, null);
11135
11136         /// <summary>
11137         /// StatusTextでCtrl+Vが押下された時の処理
11138         /// </summary>
11139         private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11140         {
11141             try
11142             {
11143                 if (Clipboard.ContainsText())
11144                 {
11145                     // clipboardにテキストがある場合は貼り付け処理
11146                     this.StatusText.Paste(Clipboard.GetText());
11147                 }
11148                 else if (Clipboard.ContainsImage())
11149                 {
11150                     // 画像があるので投稿処理を行う
11151                     if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11152                                        Properties.Resources.PostPictureWarn4,
11153                                        MessageBoxButtons.OKCancel,
11154                                        MessageBoxIcon.Question,
11155                                        MessageBoxDefaultButton.Button2)
11156                                    == DialogResult.OK)
11157                     {
11158                         // clipboardから画像を取得
11159                         using var image = Clipboard.GetImage();
11160                         this.ImageSelector.BeginSelection(image);
11161                     }
11162                 }
11163             }
11164             catch (ExternalException ex)
11165             {
11166                 MessageBox.Show(ex.Message);
11167             }
11168         }
11169 #endregion
11170
11171         private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11172         {
11173             using var form = new ListManage(tw);
11174             form.ShowDialog(this);
11175         }
11176
11177         private bool ModifySettingCommon { get; set; }
11178         private bool ModifySettingLocal { get; set; }
11179         private bool ModifySettingAtId { get; set; }
11180
11181         private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11182         {
11183             var post = this.CurrentPost;
11184             if (this.ExistCurrentPost && !post.IsDm)
11185                 RtCountMenuItem.Enabled = true;
11186             else
11187                 RtCountMenuItem.Enabled = false;
11188
11189             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11190             //    TinyUrlConvertToolStripMenuItem.Enabled = false;
11191             //else
11192             //    TinyUrlConvertToolStripMenuItem.Enabled = true;
11193         }
11194
11195         private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11196             => this.CopyUserId();
11197
11198         private void CopyUserId()
11199         {
11200             var post = this.CurrentPost;
11201             if (post == null) return;
11202             var clstr = post.ScreenName;
11203             try
11204             {
11205                 Clipboard.SetDataObject(clstr, false, 5, 100);
11206             }
11207             catch (Exception ex)
11208             {
11209                 MessageBox.Show(ex.Message);
11210             }
11211         }
11212
11213         private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11214         {
11215             var post = this.CurrentPost;
11216             if (this.ExistCurrentPost && !post.IsDm)
11217             {
11218                 try
11219                 {
11220                     await this.OpenRelatedTab(post);
11221                 }
11222                 catch (TabException ex)
11223                 {
11224                     MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11225                 }
11226             }
11227         }
11228
11229         /// <summary>
11230         /// 指定されたツイートに対する関連発言タブを開きます
11231         /// </summary>
11232         /// <param name="statusId">表示するツイートのID</param>
11233         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11234         public async Task OpenRelatedTab(long statusId)
11235         {
11236             var post = this._statuses[statusId];
11237             if (post == null)
11238             {
11239                 try
11240                 {
11241                     post = await this.tw.GetStatusApi(false, statusId);
11242                 }
11243                 catch (WebApiException ex)
11244                 {
11245                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11246                     return;
11247                 }
11248             }
11249
11250             await this.OpenRelatedTab(post);
11251         }
11252
11253         /// <summary>
11254         /// 指定されたツイートに対する関連発言タブを開きます
11255         /// </summary>
11256         /// <param name="post">表示する対象となるツイート</param>
11257         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11258         private async Task OpenRelatedTab(PostClass post)
11259         {
11260             var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11261             if (tabRelated != null)
11262             {
11263                 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11264             }
11265
11266             var tabName = this._statuses.MakeTabName("Related Tweets");
11267
11268             tabRelated = new RelatedPostsTabModel(tabName, post)
11269             {
11270                 UnreadManage = false,
11271                 Notify = false,
11272             };
11273
11274             this._statuses.AddTab(tabRelated);
11275             this.AddNewTab(tabRelated, startup: false);
11276
11277             this.ListTab.SelectedIndex = this._statuses.Tabs.IndexOf(tabName);
11278
11279             await this.RefreshTabAsync(tabRelated);
11280
11281             var tabIndex = this._statuses.Tabs.IndexOf(tabRelated.TabName);
11282
11283             if (tabIndex != -1)
11284             {
11285                 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11286
11287                 var tabPage = this.ListTab.TabPages[tabIndex];
11288                 var listView = (DetailsListView)tabPage.Tag;
11289                 var targetPost = tabRelated.TargetPost;
11290                 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11291
11292                 if (index != -1 && index < listView.Items.Count)
11293                 {
11294                     listView.SelectedIndices.Add(index);
11295                     listView.Items[index].Focused = true;
11296                 }
11297             }
11298         }
11299
11300         private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11301         {
11302             var buf = new StringBuilder();
11303             //buf.AppendFormat("キャッシュメモリ容量         : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11304             //buf.AppendFormat("物理メモリ使用割合           : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11305             buf.AppendFormat("キャッシュエントリ保持数     : {0}" + Environment.NewLine, IconCache.CacheCount);
11306             buf.AppendFormat("キャッシュエントリ破棄数     : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11307             MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11308         }
11309
11310 #region "Userstream"
11311         private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11312         {
11313             try
11314             {
11315                 if (InvokeRequired && !IsDisposed)
11316                 {
11317                     await this.InvokeAsync(() =>
11318                     {
11319                         this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11320                         if (this.CurrentTab.Contains(e.StatusId))
11321                         {
11322                             this.PurgeListViewItemCache();
11323                             this.CurrentListView.Update();
11324                             var post = this.CurrentPost;
11325                             if (post != null && post.StatusId == e.StatusId)
11326                                 this.DispSelectedPost(true);
11327                         }
11328                     });
11329                     return;
11330                 }
11331             }
11332             catch (ObjectDisposedException)
11333             {
11334                 return;
11335             }
11336             catch (InvalidOperationException)
11337             {
11338                 return;
11339             }
11340         }
11341
11342         private void tw_NewPostFromStream(object sender, EventArgs e)
11343         {
11344             if (SettingManager.Common.ReadOldPosts)
11345             {
11346                 _statuses.SetReadHomeTab(); //新着時未読クリア
11347             }
11348
11349             this._statuses.DistributePosts();
11350
11351             this.RefreshThrottlingTimer.Call();
11352         }
11353
11354         private async void tw_UserStreamStarted(object sender, EventArgs e)
11355         {
11356             try
11357             {
11358                 if (InvokeRequired && !IsDisposed)
11359                 {
11360                     await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11361                     return;
11362                 }
11363             }
11364             catch (ObjectDisposedException)
11365             {
11366                 return;
11367             }
11368             catch (InvalidOperationException)
11369             {
11370                 return;
11371             }
11372
11373             this.RefreshUserStreamsMenu();
11374             this.MenuItemUserStream.Enabled = true;
11375
11376             StatusLabel.Text = "UserStream Started.";
11377         }
11378
11379         private async void tw_UserStreamStopped(object sender, EventArgs e)
11380         {
11381             try
11382             {
11383                 if (InvokeRequired && !IsDisposed)
11384                 {
11385                     await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11386                     return;
11387                 }
11388             }
11389             catch (ObjectDisposedException)
11390             {
11391                 return;
11392             }
11393             catch (InvalidOperationException)
11394             {
11395                 return;
11396             }
11397
11398             this.RefreshUserStreamsMenu();
11399             this.MenuItemUserStream.Enabled = true;
11400
11401             StatusLabel.Text = "UserStream Stopped.";
11402         }
11403
11404         private void RefreshUserStreamsMenu()
11405         {
11406             if (this.tw.UserStreamActive)
11407             {
11408                 this.MenuItemUserStream.Text = "&UserStream ▶";
11409                 this.StopToolStripMenuItem.Text = "&Stop";
11410             }
11411             else
11412             {
11413                 this.MenuItemUserStream.Text = "&UserStream ■";
11414                 this.StopToolStripMenuItem.Text = "&Start";
11415             }
11416         }
11417
11418         private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11419         {
11420             try
11421             {
11422                 if (InvokeRequired && !IsDisposed)
11423                 {
11424                     await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11425                     return;
11426                 }
11427             }
11428             catch (ObjectDisposedException)
11429             {
11430                 return;
11431             }
11432             catch (InvalidOperationException)
11433             {
11434                 return;
11435             }
11436             var ev = e.EventData;
11437             StatusLabel.Text = "Event: " + ev.Event;
11438             //if (ev.Event == "favorite")
11439             //{
11440             //    NotifyFavorite(ev);
11441             //}
11442             NotifyEvent(ev);
11443             if (ev.Event == "favorite" || ev.Event == "unfavorite")
11444             {
11445                 if (this.CurrentTab.Contains(ev.Id))
11446                 {
11447                     this.PurgeListViewItemCache();
11448                     this.CurrentListView.Update();
11449                 }
11450                 if (ev.Event == "unfavorite" && ev.Username.Equals(tw.Username, StringComparison.InvariantCultureIgnoreCase))
11451                 {
11452                     var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11453                     favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11454                 }
11455             }
11456         }
11457
11458         private void NotifyEvent(Twitter.FormattedEvent ev)
11459         {
11460             //新着通知 
11461             if (BalloonRequired(ev))
11462             {
11463                 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11464                 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11465                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11466                 var title = new StringBuilder();
11467                 if (SettingManager.Common.DispUsername)
11468                 {
11469                     title.Append(tw.Username);
11470                     title.Append(" - ");
11471                 }
11472                 else
11473                 {
11474                     //title.Clear();
11475                 }
11476                 title.Append(ApplicationSettings.ApplicationName);
11477                 title.Append(" [");
11478                 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11479                 title.Append("] by ");
11480                 if (!string.IsNullOrEmpty(ev.Username))
11481                 {
11482                     title.Append(ev.Username);
11483                 }
11484                 else
11485                 {
11486                     //title.Append("");
11487                 }
11488                 string text;
11489                 if (!string.IsNullOrEmpty(ev.Target))
11490                 {
11491                     //NotifyIcon1.BalloonTipText = ev.Target;
11492                     text = ev.Target;
11493                 }
11494                 else
11495                 {
11496                     //NotifyIcon1.BalloonTipText = " ";
11497                     text = " ";
11498                 }
11499                 //NotifyIcon1.ShowBalloonTip(500);
11500                 if (SettingManager.Common.IsUseNotifyGrowl)
11501                 {
11502                     gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11503                               ev.Id.ToString(), title.ToString(), text);
11504                 }
11505                 else
11506                 {
11507                     NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11508                     NotifyIcon1.BalloonTipTitle = title.ToString();
11509                     NotifyIcon1.BalloonTipText = text;
11510                     NotifyIcon1.ShowBalloonTip(500);
11511                 }
11512             }
11513
11514             //サウンド再生
11515             var snd = SettingManager.Common.EventSoundFile;
11516             if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11517             {
11518                 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11519                 {
11520                     try
11521                     {
11522                         var dir = Application.StartupPath;
11523                         if (Directory.Exists(Path.Combine(dir, "Sounds")))
11524                         {
11525                             dir = Path.Combine(dir, "Sounds");
11526                         }
11527                         using var player = new SoundPlayer(Path.Combine(dir, snd));
11528                         player.Play();
11529                     }
11530                     catch (Exception)
11531                     {
11532                     }
11533                 }
11534             }
11535         }
11536
11537         private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11538         {
11539             MenuItemUserStream.Enabled = false;
11540             if (StopRefreshAllMenuItem.Checked)
11541             {
11542                 StopRefreshAllMenuItem.Checked = false;
11543                 return;
11544             }
11545             if (this.tw.UserStreamActive)
11546             {
11547                 tw.StopUserStream();
11548             }
11549             else
11550             {
11551                 tw.StartUserStream();
11552             }
11553         }
11554
11555         private static string inputTrack = "";
11556
11557         private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11558         {
11559             if (TrackToolStripMenuItem.Checked)
11560             {
11561                 using (var inputForm = new InputTabName())
11562                 {
11563                     inputForm.TabName = inputTrack;
11564                     inputForm.FormTitle = "Input track word";
11565                     inputForm.FormDescription = "Track word";
11566                     if (inputForm.ShowDialog() != DialogResult.OK)
11567                     {
11568                         TrackToolStripMenuItem.Checked = false;
11569                         return;
11570                     }
11571                     inputTrack = inputForm.TabName.Trim();
11572                 }
11573                 if (!inputTrack.Equals(tw.TrackWord))
11574                 {
11575                     tw.TrackWord = inputTrack;
11576                     this.MarkSettingCommonModified();
11577                     TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11578                     tw.ReconnectUserStream();
11579                 }
11580             }
11581             else
11582             {
11583                 tw.TrackWord = "";
11584                 tw.ReconnectUserStream();
11585             }
11586             this.MarkSettingCommonModified();
11587         }
11588
11589         private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11590         {
11591             tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11592             this.MarkSettingCommonModified();
11593             tw.ReconnectUserStream();
11594         }
11595
11596         private void EventViewerMenuItem_Click(object sender, EventArgs e)
11597         {
11598             if (evtDialog == null || evtDialog.IsDisposed)
11599             {
11600                 this.evtDialog = new EventViewerDialog
11601                 {
11602                     Owner = this,
11603                 };
11604
11605                 //親の中央に表示
11606                 this.evtDialog.Location = new Point
11607                 {
11608                     X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2),
11609                     Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2),
11610                 };
11611             }
11612             evtDialog.EventSource = tw.StoredEvent;
11613             if (!evtDialog.Visible)
11614             {
11615                 evtDialog.Show(this);
11616             }
11617             else
11618             {
11619                 evtDialog.Activate();
11620             }
11621             this.TopMost = SettingManager.Common.AlwaysTop;
11622         }
11623 #endregion
11624
11625         private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11626         {
11627             MyCommon._endingFlag = true;
11628             try
11629             {
11630                 this.Close();
11631                 Application.Restart();
11632             }
11633             catch (Exception)
11634             {
11635                 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
11636             }
11637         }
11638
11639         private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11640             => await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11641
11642         private bool ExistCurrentPost
11643         {
11644             get
11645             {
11646                 var post = this.CurrentPost;
11647                 return post != null && !post.IsDeleted;
11648             }
11649         }
11650
11651         private async void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11652             => await this.ShowUserTimeline();
11653
11654         private string GetUserIdFromCurPostOrInput(string caption)
11655         {
11656             var id = this.CurrentPost?.ScreenName ?? "";
11657
11658             using var inputName = new InputTabName();
11659             inputName.FormTitle = caption;
11660             inputName.FormDescription = Properties.Resources.FRMessage1;
11661             inputName.TabName = id;
11662
11663             if (inputName.ShowDialog() == DialogResult.OK &&
11664                 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11665             {
11666                 id = inputName.TabName.Trim();
11667             }
11668             else
11669             {
11670                 id = "";
11671             }
11672             return id;
11673         }
11674
11675         private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11676         {
11677             var id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11678             if (!string.IsNullOrEmpty(id))
11679             {
11680                 await this.AddNewTabForUserTimeline(id);
11681             }
11682         }
11683
11684         private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11685         {
11686             if (e.Mode == Microsoft.Win32.PowerModes.Resume)
11687                 this.timelineScheduler.SystemResumed();
11688         }
11689
11690         private void SystemEvents_TimeChanged(object sender, EventArgs e)
11691         {
11692             var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
11693
11694             TimeZoneInfo.ClearCachedData();
11695
11696             var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
11697
11698             if (curTimeOffset != prevTimeOffset)
11699             {
11700                 // タイムゾーンの変更を反映
11701                 this.PurgeListViewItemCache();
11702                 this.CurrentListView.Refresh();
11703
11704                 this.DispSelectedPost(forceupdate: true);
11705             }
11706         }
11707
11708         private void TimelineRefreshEnableChange(bool isEnable)
11709         {
11710             if (isEnable)
11711             {
11712                 tw.StartUserStream();
11713             }
11714             else
11715             {
11716                 tw.StopUserStream();
11717             }
11718             this.timelineScheduler.Enabled = isEnable;
11719         }
11720
11721         private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11722             => this.TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
11723
11724         private async Task OpenUserAppointUrl()
11725         {
11726             if (SettingManager.Common.UserAppointUrl != null)
11727             {
11728                 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
11729                 {
11730                     var post = this.CurrentPost;
11731                     if (post != null)
11732                     {
11733                         var xUrl = SettingManager.Common.UserAppointUrl;
11734                         xUrl = xUrl.Replace("{ID}", post.ScreenName);
11735
11736                         var statusId = post.RetweetedId ?? post.StatusId;
11737                         xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
11738
11739                         await this.OpenUriInBrowserAsync(xUrl);
11740                     }
11741                 }
11742                 else
11743                 {
11744                     await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
11745                 }
11746             }
11747         }
11748
11749         private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
11750             => await this.OpenUserAppointUrl();
11751
11752         private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
11753         {
11754             if (Form.ActiveForm == null)
11755             {
11756                 await this.InvokeAsync(() =>
11757                 {
11758                     this.Visible = true;
11759                     if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11760                     this.Activate();
11761                     this.BringToFront();
11762                     if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
11763                     {
11764                         if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
11765                     }
11766                     else
11767                     {
11768                         if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
11769                     }
11770                 });
11771             }
11772         }
11773
11774         private void ReplaceAppName()
11775         {
11776             MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
11777             AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
11778         }
11779
11780         private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
11781             => this.SplitContainer3.Panel2Collapsed = false;
11782
11783         private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
11784             => await this.OpenThumbnailPicture(e.Thumbnail);
11785
11786         private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
11787             => await this.OpenUriInBrowserAsync(e.ImageUrl);
11788
11789         private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
11790         {
11791             var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
11792
11793             await this.OpenUriInBrowserAsync(url);
11794         }
11795
11796         private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
11797             => await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
11798
11799         private void PostButton_KeyDown(object sender, KeyEventArgs e)
11800         {
11801             if (e.KeyCode == Keys.Space)
11802             {
11803                 this.JumpUnreadMenuItem_Click(null, null);
11804
11805                 e.SuppressKeyPress = true;
11806             }
11807         }
11808
11809         private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
11810         {
11811             this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
11812             this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
11813             this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
11814             this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
11815             this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
11816
11817             this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
11818         }
11819
11820         private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
11821             => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
11822
11823         private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
11824             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
11825
11826         private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
11827             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
11828
11829         private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
11830             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
11831
11832         private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
11833             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
11834
11835         private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
11836         {
11837             if (SettingManager.Common.IconSize == iconSize) return;
11838
11839             var oldIconCol = _iconCol;
11840
11841             SettingManager.Common.IconSize = iconSize;
11842             ApplyListViewIconSize(iconSize);
11843
11844             if (_iconCol != oldIconCol)
11845             {
11846                 foreach (TabPage tp in ListTab.TabPages)
11847                 {
11848                     ResetColumns((DetailsListView)tp.Tag);
11849                 }
11850             }
11851
11852             this.CurrentListView.Refresh();
11853             this.MarkSettingCommonModified();
11854         }
11855
11856         private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
11857         {
11858             var state = this.LockListSortOrderToolStripMenuItem.Checked;
11859             if (SettingManager.Common.SortOrderLock == state) return;
11860
11861             SettingManager.Common.SortOrderLock = state;
11862             this.MarkSettingCommonModified();
11863         }
11864
11865         private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
11866         {
11867             if (!string.IsNullOrEmpty(e.StatusText))
11868             {
11869                 this.StatusLabelUrl.Text = e.StatusText;
11870             }
11871             else
11872             {
11873                 this.SetStatusLabelUrl();
11874             }
11875         }
11876     }
11877 }