1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
28 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
29 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
32 using System.Collections.Generic;
33 using System.ComponentModel;
34 using System.Diagnostics;
40 using System.Net.Http;
41 using System.Reflection;
43 using System.Text.RegularExpressions;
44 using System.Threading;
45 using System.Threading.Tasks;
46 using System.Windows.Forms;
48 using OpenTween.Connection;
49 using OpenTween.OpenTweenCustomControl;
50 using OpenTween.Thumbnail;
54 public partial class TweenMain : OTBaseForm
56 private readonly HttpClient http;
59 private Size _mySize; //画面サイズ
60 private Point _myLoc; //画面位置
61 private int _mySpDis; //区切り位置
62 private int _mySpDis2; //発言欄区切り位置
63 private int _mySpDis3; //プレビュー区切り位置
64 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
65 private bool _iconCol; //1列表示の時true(48サイズのとき)
68 private bool _initial; //true:起動時処理中
69 private bool _initialLayout = true;
70 private bool _ignoreConfigSave; //true:起動時処理中
71 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
72 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
73 private Point _tabMouseDownPoint;
74 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
75 private readonly object _syncObject = new object(); //ロック用
76 private const string detailHtmlFormatMono1 = "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\"><style type=\"text/css\"><!-- pre {font-family: \"";
77 private const string detailHtmlFormat2 = "\", sans-serif; font-size: ";
78 private const string detailHtmlFormat3 = "pt; margin: 0; word-wrap: break-word; white-space: pre-wrap; color:rgb(";
79 private const string detailHtmlFormat4 = ");} a:link, a:visited, a:active, a:hover {color:rgb(";
80 private const string detailHtmlFormat5 = "); } --></style></head><body style=\"margin:0px; background-color:rgb(";
81 private const string detailHtmlFormatMono6 = ");\"><pre>";
82 private const string detailHtmlFormatMono7 = "</pre></body></html>";
83 private const string detailHtmlFormat1 = "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\"><style type=\"text/css\"><!-- p {font-family: \"";
84 private const string detailHtmlFormat6 = ");\"><p><span style=\"vertical-align:text-bottom\">";
85 private const string detailHtmlFormat7 = "</span></p></body></html>";
86 private string detailHtmlFormatHeader;
87 private string detailHtmlFormatFooter;
88 private bool _myStatusError = false;
89 private bool _myStatusOnline = false;
90 private bool soundfileListup = false;
91 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
94 //private SettingToConfig _cfg; //旧
95 private SettingLocal _cfgLocal;
96 private SettingCommon _cfgCommon;
97 private bool _modifySettingLocal = false;
98 private bool _modifySettingCommon = false;
99 private bool _modifySettingAtId = false;
102 private Twitter tw = new Twitter();
105 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
108 private AppendSettingDialog SettingDialog = AppendSettingDialog.Instance; //設定画面インスタンス
109 private SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
110 private FilterDialog fltDialog = new FilterDialog(); //フィルター編集画面
111 private OpenURL UrlDialog = new OpenURL();
112 public AtIdSupplement AtIdSupl; //@id補助
113 public AtIdSupplement HashSupl; //Hashtag補助
114 public HashtagManage HashMgr;
115 private EventViewerDialog evtDialog;
118 private Font _fntUnread; //未読用フォント
119 private Color _clUnread; //未読用文字色
120 private Font _fntReaded; //既読用フォント
121 private Color _clReaded; //既読用文字色
122 private Color _clFav; //Fav用文字色
123 private Color _clOWL; //片思い用文字色
124 private Color _clRetweet; //Retweet用文字色
125 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
126 private Font _fntDetail; //発言詳細部用フォント
127 private Color _clDetail; //発言詳細部用色
128 private Color _clDetailLink; //発言詳細部用リンク文字色
129 private Color _clDetailBackcolor; //発言詳細部用背景色
130 private Color _clSelf; //自分の発言用背景色
131 private Color _clAtSelf; //自分宛返信用背景色
132 private Color _clTarget; //選択発言者の他の発言用背景色
133 private Color _clAtTarget; //選択発言中の返信先用背景色
134 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
135 private Color _clAtTo; //選択発言の唯一@先
136 private Color _clListBackcolor; //リスト部通常発言背景色
137 private Color _clInputBackcolor; //入力欄背景色
138 private Color _clInputFont; //入力欄文字色
139 private Font _fntInputFont; //入力欄フォント
140 private ImageCache IconCache; //アイコン画像リスト
141 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
142 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
143 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
144 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
145 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
146 private Icon MainIcon; //Main.ico 画面左上のアイコン
147 private Icon ReplyIcon; //5g
148 private Icon ReplyIconBlink; //6g
150 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
152 private PostClass _anchorPost;
153 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
155 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
156 private int _hisIdx; //発言履歴カレントインデックス
158 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
159 private long? _reply_to_id; // リプライ先のステータスID 0の場合はリプライではない 注:複数あてのものはリプライではない
160 private string _reply_to_name; // リプライ先ステータスの書き込み者の名前
163 private List<DateTime> _postTimestamps = new List<DateTime>();
164 private List<DateTime> _favTimestamps = new List<DateTime>();
165 private Dictionary<DateTime, int> _tlTimestamps = new Dictionary<DateTime, int>();
166 private int _tlCount;
169 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
170 private SolidBrush _brsBackColorMine;
171 private SolidBrush _brsBackColorAt;
172 private SolidBrush _brsBackColorYou;
173 private SolidBrush _brsBackColorAtYou;
174 private SolidBrush _brsBackColorAtFromTarget;
175 private SolidBrush _brsBackColorAtTo;
176 private SolidBrush _brsBackColorNone;
177 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
178 private StringFormat sfTab = new StringFormat();
180 //////////////////////////////////////////////////////////////////////////////////////////////////////////
181 private ToolStripAPIGauge _apiGauge;
182 private TabInformations _statuses;
184 // ListViewItem のキャッシュ関連
185 private int _itemCacheIndex;
186 private ListViewItem[] _itemCache;
187 private PostClass[] _postCache;
188 private ReaderWriterLockSlim itemCacheLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
190 private TabPage _curTab;
191 private int _curItemIndex;
192 private DetailsListView _curList;
193 private PostClass _curPost;
194 private bool _isColumnChanged = false;
195 private bool _waitTimeline = false;
196 private bool _waitReply = false;
197 private bool _waitDm = false;
198 private bool _waitFav = false;
199 private bool _waitPubSearch = false;
200 private bool _waitUserTimeline = false;
201 private bool _waitLists = false;
202 private BackgroundWorker[] _bw = new BackgroundWorker[20];
203 private BackgroundWorker _bwFollower;
204 private InternetSecurityManager SecurityManager;
206 private int UnreadCounter = -1;
207 private int UnreadAtCounter = -1;
209 private string[] ColumnOrgText = new string[9];
210 private string[] ColumnText = new string[9];
212 private bool _DoFavRetweetFlags = false;
213 private bool osResumed = false;
214 private Dictionary<string, IMultimediaShareService> pictureService;
216 //////////////////////////////////////////////////////////////////////////////////////////////////////////
217 private string _postBrowserStatusText = "";
219 private bool _colorize = false;
221 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
223 private ImageListViewItem displayItem;
226 /// デザイン時の DPI (96dpi) と実際の表示時の DPI との比を表します
228 protected SizeF currentScaleFactor = new SizeF();
231 private struct urlUndo
233 public string Before;
237 private List<urlUndo> urlUndoBuffer = null;
239 private struct ReplyChain
241 public long OriginalId;
242 public long InReplyToId;
243 public TabPage OriginalTab;
245 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
247 this.OriginalId = originalId;
248 this.InReplyToId = inReplyToId;
249 this.OriginalTab = originalTab;
253 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
254 private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
256 //Backgroundworkerの処理結果通知用引数構造体
257 private class GetWorkerResult
259 public string retMsg = ""; //処理結果詳細メッセージ。エラー時に値がセットされる
260 public int page; //取得対象ページ番号
261 public int endPage = 0; //取得終了ページ番号(継続可能ならインクリメントされて返る。pageと比較して継続判定)
262 public MyCommon.WORKERTYPE type; //処理種別
263 public Dictionary<string, Image> imgs = null; //新規取得したアイコンイメージ
264 public string tName = ""; //Fav追加・削除時のタブ名
265 public List<long> ids = null; //Fav追加・削除時のID
266 public List<long> sIds = null; //Fav追加・削除成功分のID
267 public bool newDM = false;
269 public PostingStatus status;
272 //Backgroundworkerへ処理内容を通知するための引数用構造体
273 private class GetWorkerArg
275 public int page; //処理対象ページ番号
276 public int endPage; //処理終了ページ番号(起動時の読み込みページ数。通常時はpageと同じ値をセット)
277 public MyCommon.WORKERTYPE type; //処理種別
278 public string url = ""; //URLをブラウザで開くときのアドレス
279 public PostingStatus status = new PostingStatus(); //発言POST時の発言内容
280 public List<long> ids; //Fav追加・削除時のItemIndex
281 public List<long> sIds; //Fav追加・削除成功分のItemIndex
282 public string tName = ""; //Fav追加・削除時のタブ名
286 private enum SEARCHTYPE
293 private class PostingStatus
295 public string status = "";
296 public long? inReplyToId = null;
297 public string inReplyToName = null;
298 public string imageService = ""; //画像投稿サービス名
299 public string imagePath = "";
300 public PostingStatus()
303 public PostingStatus(string status, long? replyToId, string replyToName)
305 this.status = status;
306 this.inReplyToId = replyToId;
307 this.inReplyToName = replyToName;
311 private void TweenMain_Activated(object sender, EventArgs e)
313 //画面がアクティブになったら、発言欄の背景色戻す
314 if (StatusText.Focused)
316 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
320 private void TweenMain_Disposed(object sender, EventArgs e)
323 SettingDialog.Dispose();
324 SearchDialog.Dispose();
327 if (NIconAt != null) NIconAt.Dispose();
328 if (NIconAtRed != null) NIconAtRed.Dispose();
329 if (NIconAtSmoke != null) NIconAtSmoke.Dispose();
330 if (NIconRefresh[0] != null) NIconRefresh[0].Dispose();
331 if (NIconRefresh[1] != null) NIconRefresh[1].Dispose();
332 if (NIconRefresh[2] != null) NIconRefresh[2].Dispose();
333 if (NIconRefresh[3] != null) NIconRefresh[3].Dispose();
334 if (TabIcon != null) TabIcon.Dispose();
335 if (MainIcon != null) MainIcon.Dispose();
336 if (ReplyIcon != null) ReplyIcon.Dispose();
337 if (ReplyIconBlink != null) ReplyIconBlink.Dispose();
338 _listViewImageList.Dispose();
339 _brsHighLight.Dispose();
340 if (_brsBackColorMine != null) _brsBackColorMine.Dispose();
341 if (_brsBackColorAt != null) _brsBackColorAt.Dispose();
342 if (_brsBackColorYou != null) _brsBackColorYou.Dispose();
343 if (_brsBackColorAtYou != null) _brsBackColorAtYou.Dispose();
344 if (_brsBackColorAtFromTarget != null) _brsBackColorAtFromTarget.Dispose();
345 if (_brsBackColorAtTo != null) _brsBackColorAtTo.Dispose();
346 if (_brsBackColorNone != null) _brsBackColorNone.Dispose();
347 if (_brsDeactiveSelection != null) _brsDeactiveSelection.Dispose();
350 foreach (BackgroundWorker bw in _bw)
355 if (_bwFollower != null)
357 _bwFollower.Dispose();
359 this._apiGauge.Dispose();
360 if (IconCache != null)
362 this.IconCache.CancelAsync();
363 this.IconCache.Dispose();
368 // 終了時にRemoveHandlerしておかないとメモリリークする
369 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
370 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
373 private void LoadIcon(ref Icon IconInstance, string FileName)
375 string dir = Application.StartupPath;
376 if (File.Exists(Path.Combine(dir, FileName)))
380 IconInstance = new Icon(Path.Combine(dir, FileName));
388 private void LoadIcons()
392 string dir = Application.StartupPath;
394 NIconAt = Properties.Resources.At;
395 NIconAtRed = Properties.Resources.AtRed;
396 NIconAtSmoke = Properties.Resources.AtSmoke;
397 NIconRefresh[0] = Properties.Resources.Refresh;
398 NIconRefresh[1] = Properties.Resources.Refresh2;
399 NIconRefresh[2] = Properties.Resources.Refresh3;
400 NIconRefresh[3] = Properties.Resources.Refresh4;
401 TabIcon = Properties.Resources.TabIcon;
402 MainIcon = Properties.Resources.MIcon;
403 ReplyIcon = Properties.Resources.Reply;
404 ReplyIconBlink = Properties.Resources.ReplyBlink;
406 if (!Directory.Exists(Path.Combine(dir, "Icons")))
409 LoadIcon(ref NIconAt, "Icons\\At.ico");
412 LoadIcon(ref NIconAtRed, "Icons\\AtRed.ico");
415 LoadIcon(ref NIconAtSmoke, "Icons\\AtSmoke.ico");
418 //アニメーション対応により4種類読み込み
419 LoadIcon(ref NIconRefresh[0], "Icons\\Refresh.ico");
420 LoadIcon(ref NIconRefresh[1], "Icons\\Refresh2.ico");
421 LoadIcon(ref NIconRefresh[2], "Icons\\Refresh3.ico");
422 LoadIcon(ref NIconRefresh[3], "Icons\\Refresh4.ico");
425 LoadIcon(ref TabIcon, "Icons\\Tab.ico");
428 LoadIcon(ref MainIcon, "Icons\\MIcon.ico");
431 LoadIcon(ref ReplyIcon, "Icons\\Reply.ico");
434 LoadIcon(ref ReplyIconBlink, "Icons\\ReplyBlink.ico");
437 private void InitColumns(ListView list, bool startup)
439 ColumnHeader _colHd1 = new ColumnHeader(); //アイコン
440 ColumnHeader _colHd2 = new ColumnHeader(); //ニックネーム
441 ColumnHeader _colHd3 = new ColumnHeader(); //本文
442 ColumnHeader _colHd4 = new ColumnHeader(); //日付
443 ColumnHeader _colHd5 = new ColumnHeader(); //ユーザID
444 ColumnHeader _colHd6 = new ColumnHeader(); //未読
445 ColumnHeader _colHd7 = new ColumnHeader(); //マーク&プロテクト
446 ColumnHeader _colHd8 = new ColumnHeader(); //ソース
450 list.Columns.AddRange(new ColumnHeader[] { _colHd1, _colHd2, _colHd3, _colHd4, _colHd5, _colHd6, _colHd7, _colHd8 });
454 list.Columns.AddRange(new ColumnHeader[] { _colHd1, _colHd3 });
458 _colHd1.Text = ColumnText[0];
460 _colHd2.Text = ColumnText[1];
462 _colHd3.Text = ColumnText[2];
464 _colHd4.Text = ColumnText[3];
466 _colHd5.Text = ColumnText[4];
468 _colHd6.Text = ColumnText[5];
470 _colHd7.Text = ColumnText[6];
472 _colHd8.Text = ColumnText[7];
475 int[] dispOrder = new int[8];
478 for (int i = 0; i < _curList.Columns.Count; i++)
480 for (int j = 0; j < _curList.Columns.Count; j++)
482 if (_curList.Columns[j].DisplayIndex == i)
489 for (int i = 0; i < _curList.Columns.Count; i++)
491 list.Columns[i].Width = _curList.Columns[i].Width;
492 list.Columns[dispOrder[i]].DisplayIndex = i;
499 list.Columns[0].Width = _cfgLocal.Width1;
500 list.Columns[1].Width = _cfgLocal.Width3;
501 list.Columns[0].DisplayIndex = 0;
502 list.Columns[1].DisplayIndex = 1;
506 for (int i = 0; i <= 7; i++)
508 if (_cfgLocal.DisplayIndex1 == i)
510 else if (_cfgLocal.DisplayIndex2 == i)
512 else if (_cfgLocal.DisplayIndex3 == i)
514 else if (_cfgLocal.DisplayIndex4 == i)
516 else if (_cfgLocal.DisplayIndex5 == i)
518 else if (_cfgLocal.DisplayIndex6 == i)
520 else if (_cfgLocal.DisplayIndex7 == i)
522 else if (_cfgLocal.DisplayIndex8 == i)
525 list.Columns[0].Width = _cfgLocal.Width1;
526 list.Columns[1].Width = _cfgLocal.Width2;
527 list.Columns[2].Width = _cfgLocal.Width3;
528 list.Columns[3].Width = _cfgLocal.Width4;
529 list.Columns[4].Width = _cfgLocal.Width5;
530 list.Columns[5].Width = _cfgLocal.Width6;
531 list.Columns[6].Width = _cfgLocal.Width7;
532 list.Columns[7].Width = _cfgLocal.Width8;
533 for (int i = 0; i <= 7; i++)
535 list.Columns[dispOrder[i]].DisplayIndex = i;
541 private void InitColumnText()
544 ColumnText[1] = Properties.Resources.AddNewTabText2;
545 ColumnText[2] = Properties.Resources.AddNewTabText3;
546 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
547 ColumnText[4] = Properties.Resources.AddNewTabText5;
550 ColumnText[7] = "Source";
552 ColumnOrgText[0] = "";
553 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
554 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
555 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
556 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
557 ColumnOrgText[5] = "";
558 ColumnOrgText[6] = "";
559 ColumnOrgText[7] = "Source";
562 switch (_statuses.SortMode)
564 case IdComparerClass.ComparerMode.Nickname: //ニックネーム
567 case IdComparerClass.ComparerMode.Data: //本文
570 case IdComparerClass.ComparerMode.Id: //時刻=発言Id
573 case IdComparerClass.ComparerMode.Name: //名前
576 case IdComparerClass.ComparerMode.Source: //Source
583 if (_statuses.SortOrder == SortOrder.Descending)
585 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
586 ColumnText[2] = ColumnOrgText[2] + "▾";
590 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
591 ColumnText[2] = ColumnOrgText[2] + "▴";
596 if (_statuses.SortOrder == SortOrder.Descending)
598 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
599 ColumnText[c] = ColumnOrgText[c] + "▾";
603 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
604 ColumnText[c] = ColumnOrgText[c] + "▴";
609 private void InitializeTraceFrag()
612 TraceOutToolStripMenuItem.Checked = true;
613 MyCommon.TraceFlag = true;
615 if (!MyCommon.FileVersion.EndsWith("0"))
617 TraceOutToolStripMenuItem.Checked = true;
618 MyCommon.TraceFlag = true;
622 private void TweenMain_Load(object sender, EventArgs e)
624 _ignoreConfigSave = true;
625 this.Visible = false;
627 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
629 SecurityManager = new InternetSecurityManager(PostBrowser);
630 this.PostBrowser.AllowWebBrowserDrop = false; // COMException を回避するため、ActiveX の初期化が終わってから設定する
632 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
633 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
635 if (MyApplication.StartupOptions.ContainsKey("d"))
636 MyCommon.TraceFlag = true;
638 Regex.CacheSize = 100;
640 InitializeTraceFrag();
641 LoadIcons(); // アイコン読み込み
644 _statuses = TabInformations.GetInstance();
647 this.Icon = MainIcon; //メインフォーム(TweenMain)
648 NotifyIcon1.Icon = NIconAt; //タスクトレイ
649 TabImage.Images.Add(TabIcon); //タブ見出し
651 SettingDialog.Owner = this;;
652 SearchDialog.Owner = this;
653 fltDialog.Owner = this;
654 UrlDialog.Owner = this;
656 _history.Add(new PostingStatus());
659 _reply_to_name = null;
661 //<<<<<<<<<設定関連>>>>>>>>>
668 ThumbnailGenerator.InitializeGenerator(this.http);
670 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
671 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
672 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
674 Thumbnail.Services.TonTwitterCom.InitializeOAuthToken = x =>
675 x.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
676 this.tw.AccessToken, this.tw.AccessTokenSecret, "", "");
679 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
680 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
683 _fntUnread = _cfgLocal.FontUnread;
684 _clUnread = _cfgLocal.ColorUnread;
685 _fntReaded = _cfgLocal.FontRead;
686 _clReaded = _cfgLocal.ColorRead;
687 _clFav = _cfgLocal.ColorFav;
688 _clOWL = _cfgLocal.ColorOWL;
689 _clRetweet = _cfgLocal.ColorRetweet;
690 _fntDetail = _cfgLocal.FontDetail;
691 _clDetail = _cfgLocal.ColorDetail;
692 _clDetailLink = _cfgLocal.ColorDetailLink;
693 _clDetailBackcolor = _cfgLocal.ColorDetailBackcolor;
694 _clSelf = _cfgLocal.ColorSelf;
695 _clAtSelf = _cfgLocal.ColorAtSelf;
696 _clTarget = _cfgLocal.ColorTarget;
697 _clAtTarget = _cfgLocal.ColorAtTarget;
698 _clAtFromTarget = _cfgLocal.ColorAtFromTarget;
699 _clAtTo = _cfgLocal.ColorAtTo;
700 _clListBackcolor = _cfgLocal.ColorListBackcolor;
701 _clInputBackcolor = _cfgLocal.ColorInputBackcolor;
702 _clInputFont = _cfgLocal.ColorInputFont;
703 _fntInputFont = _cfgLocal.FontInputFont;
705 var fontUIGlobal = this._cfgLocal.FontUIGlobal;
706 if (fontUIGlobal != null)
708 OTBaseForm.GlobalFont = fontUIGlobal;
709 this.Font = fontUIGlobal;
712 // StringFormatオブジェクトへの事前設定
713 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
714 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
715 //sf.FormatFlags = StringFormatFlags.LineLimit; //
716 sfTab.Alignment = StringAlignment.Center;
717 sfTab.LineAlignment = StringAlignment.Center;
720 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
721 SettingDialog.TwitterApiUrl = _cfgCommon.TwitterUrl;
724 if (string.IsNullOrEmpty(_cfgCommon.Token)) _cfgCommon.UserName = "";
725 tw.Initialize(_cfgCommon.Token, _cfgCommon.TokenSecret, _cfgCommon.UserName, _cfgCommon.UserId);
727 SettingDialog.UserAccounts = _cfgCommon.UserAccounts;
729 SettingDialog.TimelinePeriodInt = _cfgCommon.TimelinePeriod;
730 SettingDialog.ReplyPeriodInt = _cfgCommon.ReplyPeriod;
731 SettingDialog.DMPeriodInt = _cfgCommon.DMPeriod;
732 SettingDialog.PubSearchPeriodInt = _cfgCommon.PubSearchPeriod;
733 SettingDialog.UserTimelinePeriodInt = _cfgCommon.UserTimelinePeriod;
734 SettingDialog.ListsPeriodInt = _cfgCommon.ListsPeriod;
736 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
738 if (SettingDialog.TimelinePeriodInt < 15 && SettingDialog.TimelinePeriodInt > 0) SettingDialog.TimelinePeriodInt = 15;
739 if (SettingDialog.ReplyPeriodInt < 15 && SettingDialog.ReplyPeriodInt > 0) SettingDialog.ReplyPeriodInt = 15;
740 if (SettingDialog.DMPeriodInt < 15 && SettingDialog.DMPeriodInt > 0) SettingDialog.DMPeriodInt = 15;
741 if (SettingDialog.PubSearchPeriodInt < 30 && SettingDialog.PubSearchPeriodInt > 0) SettingDialog.PubSearchPeriodInt = 30;
742 if (SettingDialog.UserTimelinePeriodInt < 15 && SettingDialog.UserTimelinePeriodInt > 0) SettingDialog.UserTimelinePeriodInt = 15;
743 if (SettingDialog.ListsPeriodInt < 15 && SettingDialog.ListsPeriodInt > 0) SettingDialog.ListsPeriodInt = 15;
746 //起動時読み込み分を既読にするか。trueなら既読として処理
747 SettingDialog.Readed = _cfgCommon.Read;
748 //新着取得時のリストスクロールをするか。trueならスクロールしない
749 ListLockMenuItem.Checked = _cfgCommon.ListLock;
750 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
751 SettingDialog.IconSz = _cfgCommon.IconSize;
753 SettingDialog.Status = _cfgLocal.StatusText;
755 SettingDialog.UnreadManage = _cfgCommon.UnreadManage;
757 SettingDialog.PlaySound = _cfgCommon.PlaySound;
758 PlaySoundMenuItem.Checked = SettingDialog.PlaySound;
759 this.PlaySoundFileMenuItem.Checked = SettingDialog.PlaySound;
760 //片思い表示。trueなら片思い表示する
761 SettingDialog.OneWayLove = _cfgCommon.OneWayLove;
763 SettingDialog.FontUnread = _fntUnread;
764 SettingDialog.ColorUnread = _clUnread;
765 SettingDialog.FontReaded = _fntReaded;
766 SettingDialog.ColorReaded = _clReaded;
767 SettingDialog.ColorFav = _clFav;
768 SettingDialog.ColorOWL = _clOWL;
769 SettingDialog.ColorRetweet = _clRetweet;
770 SettingDialog.FontDetail = _fntDetail;
771 SettingDialog.ColorDetail = _clDetail;
772 SettingDialog.ColorDetailLink = _clDetailLink;
773 SettingDialog.ColorDetailBackcolor = _clDetailBackcolor;
774 SettingDialog.ColorSelf = _clSelf;
775 SettingDialog.ColorAtSelf = _clAtSelf;
776 SettingDialog.ColorTarget = _clTarget;
777 SettingDialog.ColorAtTarget = _clAtTarget;
778 SettingDialog.ColorAtFromTarget = _clAtFromTarget;
779 SettingDialog.ColorAtTo = _clAtTo;
780 SettingDialog.ColorListBackcolor = _clListBackcolor;
781 SettingDialog.ColorInputBackcolor = _clInputBackcolor;
782 SettingDialog.ColorInputFont = _clInputFont;
783 SettingDialog.FontInputFont = _fntInputFont;
785 SettingDialog.NameBalloon = _cfgCommon.NameBalloon;
786 SettingDialog.PostCtrlEnter = _cfgCommon.PostCtrlEnter;
787 SettingDialog.PostShiftEnter = _cfgCommon.PostShiftEnter;
789 SettingDialog.CountApi = _cfgCommon.CountApi;
790 SettingDialog.CountApiReply = _cfgCommon.CountApiReply;
791 if (SettingDialog.CountApi < 20 || SettingDialog.CountApi > 200) SettingDialog.CountApi = 60;
792 if (SettingDialog.CountApiReply < 20 || SettingDialog.CountApiReply > 200) SettingDialog.CountApiReply = 40;
794 SettingDialog.BrowserPath = _cfgLocal.BrowserPath;
795 SettingDialog.PostAndGet = _cfgCommon.PostAndGet;
796 SettingDialog.UseRecommendStatus = _cfgLocal.UseRecommendStatus;
797 SettingDialog.DispUsername = _cfgCommon.DispUsername;
798 SettingDialog.CloseToExit = _cfgCommon.CloseToExit;
799 SettingDialog.MinimizeToTray = _cfgCommon.MinimizeToTray;
800 SettingDialog.DispLatestPost = _cfgCommon.DispLatestPost;
801 SettingDialog.SortOrderLock = _cfgCommon.SortOrderLock;
802 SettingDialog.ViewTabBottom = _cfgCommon.ViewTabBottom;
803 SettingDialog.TinyUrlResolve = _cfgCommon.TinyUrlResolve;
805 SettingDialog.SelectedProxyType = _cfgLocal.ProxyType;
806 SettingDialog.ProxyAddress = _cfgLocal.ProxyAddress;
807 SettingDialog.ProxyPort = _cfgLocal.ProxyPort;
808 SettingDialog.ProxyUser = _cfgLocal.ProxyUser;
809 SettingDialog.ProxyPassword = _cfgLocal.ProxyPassword;
811 SettingDialog.StartupVersion = _cfgCommon.StartupVersion;
812 SettingDialog.StartupFollowers = _cfgCommon.StartupFollowers;
813 SettingDialog.RestrictFavCheck = _cfgCommon.RestrictFavCheck;
814 SettingDialog.AlwaysTop = _cfgCommon.AlwaysTop;
815 SettingDialog.UrlConvertAuto = false;
816 //SettingDialog.UrlConvertAuto = _cfgCommon.UrlConvertAuto;
818 SettingDialog.UseUnreadStyle = _cfgCommon.UseUnreadStyle;
819 SettingDialog.DefaultTimeOut = _cfgCommon.DefaultTimeOut;
820 SettingDialog.RetweetNoConfirm = _cfgCommon.RetweetNoConfirm;
821 SettingDialog.PlaySound = _cfgCommon.PlaySound;
822 SettingDialog.DateTimeFormat = _cfgCommon.DateTimeFormat;
823 SettingDialog.LimitBalloon = _cfgCommon.LimitBalloon;
824 SettingDialog.EventNotifyEnabled = _cfgCommon.EventNotifyEnabled;
825 SettingDialog.EventNotifyFlag = _cfgCommon.EventNotifyFlag;
826 SettingDialog.IsMyEventNotifyFlag = _cfgCommon.IsMyEventNotifyFlag;
827 SettingDialog.ForceEventNotify = _cfgCommon.ForceEventNotify;
828 SettingDialog.FavEventUnread = _cfgCommon.FavEventUnread;
829 SettingDialog.TranslateLanguage = _cfgCommon.TranslateLanguage;
830 SettingDialog.EventSoundFile = _cfgCommon.EventSoundFile;
832 //廃止サービスが選択されていた場合bit.lyへ読み替え
833 if (_cfgCommon.AutoShortUrlFirst < 0)
834 _cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
836 SettingDialog.AutoShortUrlFirst = _cfgCommon.AutoShortUrlFirst;
837 SettingDialog.TabIconDisp = _cfgCommon.TabIconDisp;
838 SettingDialog.ReplyIconState = _cfgCommon.ReplyIconState;
839 SettingDialog.ReadOwnPost = _cfgCommon.ReadOwnPost;
840 SettingDialog.GetFav = _cfgCommon.GetFav;
841 SettingDialog.ReadOldPosts = _cfgCommon.ReadOldPosts;
842 SettingDialog.BitlyUser = _cfgCommon.BilyUser;
843 SettingDialog.BitlyPwd = _cfgCommon.BitlyPwd;
844 SettingDialog.ShowGrid = _cfgCommon.ShowGrid;
845 SettingDialog.Language = _cfgCommon.Language;
846 SettingDialog.UseAtIdSupplement = _cfgCommon.UseAtIdSupplement;
847 SettingDialog.UseHashSupplement = _cfgCommon.UseHashSupplement;
848 SettingDialog.PreviewEnable = _cfgCommon.PreviewEnable;
849 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
851 SettingDialog.IsMonospace = _cfgCommon.IsMonospace;
853 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
854 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
856 //Regex statregex = new Regex("^0*");
857 SettingDialog.RecommendStatusText = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
862 if (DateTime.Now.ToString(SettingDialog.DateTimeFormat).Length == 0)
864 // このブロックは絶対に実行されないはず
865 // 変換が成功した場合にLengthが0にならない
866 SettingDialog.DateTimeFormat = "yyyy/MM/dd H:mm:ss";
869 catch (FormatException)
871 // FormatExceptionが発生したら初期値を設定 (=yyyy/MM/dd H:mm:ssとみなされる)
872 SettingDialog.DateTimeFormat = "yyyy/MM/dd H:mm:ss";
875 SettingDialog.Nicoms = _cfgCommon.Nicoms;
876 SettingDialog.HotkeyEnabled = _cfgCommon.HotkeyEnabled;
877 SettingDialog.HotkeyMod = _cfgCommon.HotkeyModifier;
878 SettingDialog.HotkeyKey = _cfgCommon.HotkeyKey;
879 SettingDialog.HotkeyValue = _cfgCommon.HotkeyValue;
881 SettingDialog.BlinkNewMentions = _cfgCommon.BlinkNewMentions;
883 SettingDialog.UseAdditionalCount = _cfgCommon.UseAdditionalCount;
884 SettingDialog.MoreCountApi = _cfgCommon.MoreCountApi;
885 SettingDialog.FirstCountApi = _cfgCommon.FirstCountApi;
886 SettingDialog.SearchCountApi = _cfgCommon.SearchCountApi;
887 SettingDialog.FavoritesCountApi = _cfgCommon.FavoritesCountApi;
888 SettingDialog.UserTimelineCountApi = _cfgCommon.UserTimelineCountApi;
889 SettingDialog.ListCountApi = _cfgCommon.ListCountApi;
891 SettingDialog.UserstreamStartup = _cfgCommon.UserstreamStartup;
892 SettingDialog.UserstreamPeriodInt = _cfgCommon.UserstreamPeriod;
893 SettingDialog.OpenUserTimeline = _cfgCommon.OpenUserTimeline;
894 SettingDialog.ListDoubleClickAction = _cfgCommon.ListDoubleClickAction;
895 SettingDialog.UserAppointUrl = _cfgCommon.UserAppointUrl;
896 SettingDialog.HideDuplicatedRetweets = _cfgCommon.HideDuplicatedRetweets;
898 SettingDialog.EnableImgAzyobuziNet = _cfgCommon.EnableImgAzyobuziNet;
899 SettingDialog.ImgAzyobuziNetDisabledInDM = _cfgCommon.ImgAzyobuziNetDisabledInDM;
900 SettingDialog.MapThumbnailProvider = _cfgCommon.MapThumbnailProvider;
901 SettingDialog.MapThumbnailHeight = _cfgCommon.MapThumbnailHeight;
902 SettingDialog.MapThumbnailWidth = _cfgCommon.MapThumbnailWidth;
903 SettingDialog.MapThumbnailZoom = _cfgCommon.MapThumbnailZoom;
904 SettingDialog.IsListStatusesIncludeRts = _cfgCommon.IsListsIncludeRts;
905 SettingDialog.TabMouseLock = _cfgCommon.TabMouseLock;
906 SettingDialog.IsRemoveSameEvent = _cfgCommon.IsRemoveSameEvent;
907 SettingDialog.IsNotifyUseGrowl = _cfgCommon.IsUseNotifyGrowl;
910 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
911 HashMgr = new HashtagManage(HashSupl,
912 _cfgCommon.HashTags.ToArray(),
913 _cfgCommon.HashSelected,
914 _cfgCommon.HashIsPermanent,
915 _cfgCommon.HashIsHead,
916 _cfgCommon.HashIsNotAddToAtReply);
917 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
922 this.IconCache = new ImageCache(this.http);
924 bool saveRequired = false;
925 bool firstRun = false;
927 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
928 if (string.IsNullOrEmpty(tw.Username))
932 SettingDialog.ShowInTaskbar = true;
934 //設定せずにキャンセルされた場合はプログラム終了
935 if (SettingDialog.ShowDialog(this) == DialogResult.Cancel)
937 Application.Exit(); //強制終了
940 //設定されたが、依然ユーザー名とパスワードが未設定ならプログラム終了
941 if (string.IsNullOrEmpty(tw.Username))
943 Application.Exit(); //強制終了
946 SettingDialog.ShowInTaskbar = false;
950 _fntUnread = SettingDialog.FontUnread;
951 _clUnread = SettingDialog.ColorUnread;
952 _fntReaded = SettingDialog.FontReaded;
953 _clReaded = SettingDialog.ColorReaded;
954 _clFav = SettingDialog.ColorFav;
955 _clOWL = SettingDialog.ColorOWL;
956 _clRetweet = SettingDialog.ColorRetweet;
957 _fntDetail = SettingDialog.FontDetail;
958 _clDetail = SettingDialog.ColorDetail;
959 _clDetailLink = SettingDialog.ColorDetailLink;
960 _clDetailBackcolor = SettingDialog.ColorDetailBackcolor;
961 _clSelf = SettingDialog.ColorSelf;
962 _clAtSelf = SettingDialog.ColorAtSelf;
963 _clTarget = SettingDialog.ColorTarget;
964 _clAtTarget = SettingDialog.ColorAtTarget;
965 _clAtFromTarget = SettingDialog.ColorAtFromTarget;
966 _clAtTo = SettingDialog.ColorAtTo;
967 _clListBackcolor = SettingDialog.ColorListBackcolor;
968 _clInputBackcolor = SettingDialog.ColorInputBackcolor;
969 _clInputFont = SettingDialog.ColorInputFont;
970 _fntInputFont = SettingDialog.FontInputFont;
972 //他の設定項目は、随時設定画面で保持している値を読み出して使用
975 _brsBackColorMine = new SolidBrush(_clSelf);
976 _brsBackColorAt = new SolidBrush(_clAtSelf);
977 _brsBackColorYou = new SolidBrush(_clTarget);
978 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
979 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
980 _brsBackColorAtTo = new SolidBrush(_clAtTo);
981 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
982 _brsBackColorNone = new SolidBrush(_clListBackcolor);
984 InitDetailHtmlFormat();
986 if (SettingDialog.HotkeyEnabled)
989 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
990 if ((SettingDialog.HotkeyMod & Keys.Alt) == Keys.Alt) modKey = modKey | HookGlobalHotkey.ModKeys.Alt;
991 if ((SettingDialog.HotkeyMod & Keys.Control) == Keys.Control) modKey = modKey | HookGlobalHotkey.ModKeys.Ctrl;
992 if ((SettingDialog.HotkeyMod & Keys.Shift) == Keys.Shift) modKey = modKey | HookGlobalHotkey.ModKeys.Shift;
993 if ((SettingDialog.HotkeyMod & Keys.LWin) == Keys.LWin) modKey = modKey | HookGlobalHotkey.ModKeys.Win;
995 _hookGlobalHotkey.RegisterOriginalHotkey(SettingDialog.HotkeyKey, SettingDialog.HotkeyValue, modKey);
999 HttpConnection.InitializeConnection(SettingDialog.DefaultTimeOut,
1000 SettingDialog.SelectedProxyType,
1001 SettingDialog.ProxyAddress,
1002 SettingDialog.ProxyPort,
1003 SettingDialog.ProxyUser,
1004 SettingDialog.ProxyPassword);
1006 tw.RestrictFavCheck = SettingDialog.RestrictFavCheck;
1007 tw.ReadOwnPost = SettingDialog.ReadOwnPost;
1008 ShortUrl.Instance.DisableExpanding = !SettingDialog.TinyUrlResolve;
1009 ShortUrl.Instance.BitlyId = SettingDialog.BitlyUser;
1010 ShortUrl.Instance.BitlyKey = SettingDialog.BitlyPwd;
1011 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
1012 tw.TrackWord = _cfgCommon.TrackWord;
1013 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
1014 tw.AllAtReply = _cfgCommon.AllAtReply;
1015 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
1018 this.CreatePictureServices();
1019 SetImageServiceCombo();
1020 ImageSelectionPanel.Enabled = false;
1022 SelectImageServiceComboItem(_cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
1025 this.ClientSize = _cfgLocal.FormSize;
1026 _mySize = _cfgLocal.FormSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
1027 _myLoc = _cfgLocal.FormLocation;
1029 if (this.WindowState != FormWindowState.Minimized)
1031 this.DesktopLocation = _cfgLocal.FormLocation;
1032 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
1033 bool outOfScreen = true;
1034 if (Screen.AllScreens.Length == 1) //ハングするとの報告
1036 foreach (Screen scr in Screen.AllScreens)
1038 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
1040 outOfScreen = false;
1046 this.DesktopLocation = new Point(0, 0);
1047 _myLoc = this.DesktopLocation;
1051 this.TopMost = SettingDialog.AlwaysTop;
1052 _mySpDis = _cfgLocal.SplitterDistance;
1053 _mySpDis2 = _cfgLocal.StatusTextHeight;
1054 _mySpDis3 = _cfgLocal.PreviewDistance;
1055 if (_mySpDis3 == -1)
1057 _mySpDis3 = _mySize.Width - 150;
1058 if (_mySpDis3 < 1) _mySpDis3 = 50;
1059 _cfgLocal.PreviewDistance = _mySpDis3;
1061 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
1062 //this.Tween_ClientSizeChanged(this, null);
1063 PlaySoundMenuItem.Checked = SettingDialog.PlaySound;
1064 this.PlaySoundFileMenuItem.Checked = SettingDialog.PlaySound;
1066 StatusText.Font = _fntInputFont;
1067 StatusText.ForeColor = _clInputFont;
1069 // NameLabel のフォントを OTBaseForm.GlobalFont に変更
1070 this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
1072 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
1073 if (SettingDialog.UnreadManage == false)
1075 ReadedStripMenuItem.Enabled = false;
1076 UnreadStripMenuItem.Enabled = false;
1079 if (SettingDialog.IsNotifyUseGrowl) gh.RegisterGrowl();
1082 TimerTimeline.AutoReset = true;
1083 TimerTimeline.SynchronizingObject = this;
1085 TimerTimeline.Interval = 1000;
1086 TimerTimeline.Enabled = true;
1089 TimerRefreshIcon.Interval = 200;
1090 TimerRefreshIcon.Enabled = true;
1093 StatusLabel.Text = "";
1094 StatusLabel.AutoToolTip = false;
1095 StatusLabel.ToolTipText = "";
1097 lblLen.Text = GetRestStatusCount(true, false).ToString();
1099 ////////////////////////////////////////////////////////////////////////////////
1100 _statuses.SortOrder = (SortOrder)_cfgCommon.SortOrder;
1101 IdComparerClass.ComparerMode mode = IdComparerClass.ComparerMode.Id;
1102 switch (_cfgCommon.SortColumn)
1104 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1108 mode = IdComparerClass.ComparerMode.Id; //Idソートに読み替え
1111 mode = IdComparerClass.ComparerMode.Nickname;
1114 mode = IdComparerClass.ComparerMode.Data;
1117 mode = IdComparerClass.ComparerMode.Id;
1120 mode = IdComparerClass.ComparerMode.Name;
1123 mode = IdComparerClass.ComparerMode.Source;
1126 _statuses.SortMode = mode;
1127 ////////////////////////////////////////////////////////////////////////////////
1129 ApplyListViewIconSize(SettingDialog.IconSz);
1131 tw.TinyUrlResolve = SettingDialog.TinyUrlResolve;
1133 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1134 StatusLabelUrl.Text = ""; //画面左下のリンク先URL表示部を初期化
1135 NameLabel.Text = ""; //発言詳細部名前ラベル初期化
1136 DateTimeLabel.Text = ""; //発言詳細部日時ラベル初期化
1137 SourceLinkLabel.Text = ""; //Source部分初期化
1139 //<<<<<<<<タブ関連>>>>>>>
1140 //デフォルトタブの存在チェック、ない場合には追加
1141 if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1144 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1146 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1150 tab.TabType = MyCommon.TabUsageType.Home;
1153 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1156 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1158 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1162 tab.TabType = MyCommon.TabUsageType.Mentions;
1165 if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1168 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1170 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1174 tab.TabType = MyCommon.TabUsageType.DirectMessage;
1177 if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1180 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1182 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1186 tab.TabType = MyCommon.TabUsageType.Favorites;
1189 foreach (var tab in _statuses.Tabs.Values)
1191 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1193 tab.TabType = MyCommon.TabUsageType.UserDefined;
1195 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo)) throw new Exception(Properties.Resources.TweenMain_LoadText1);
1198 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1199 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1200 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1201 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1203 if (SettingDialog.MinimizeToTray == false || this.WindowState != FormWindowState.Minimized)
1205 this.Visible = true;
1207 _curTab = ListTab.SelectedTab;
1209 _curList = (DetailsListView)_curTab.Tag;
1210 SetMainWindowTitle();
1211 SetNotifyIconText();
1213 if (SettingDialog.TabIconDisp)
1215 ListTab.DrawMode = TabDrawMode.Normal;
1219 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1220 ListTab.DrawItem += ListTab_DrawItem;
1221 ListTab.ImageList = null;
1224 _ignoreConfigSave = false;
1225 this.TweenMain_Resize(null, null);
1226 if (saveRequired) SaveConfigsAll(false);
1230 tw.VerifyCredentials();
1231 foreach (UserAccount ua in _cfgCommon.UserAccounts)
1233 if (ua.Username.ToLower() == tw.Username.ToLower())
1235 ua.UserId = tw.UserId;
1240 foreach (UserAccount ua in SettingDialog.UserAccounts)
1242 if (ua.UserId == 0 && ua.Username.ToLower() == tw.Username.ToLower())
1244 ua.UserId = tw.UserId;
1251 // 初回起動時だけ右下のメニューを目立たせる
1252 HashStripSplitButton.ShowDropDown();
1259 private void InitDetailHtmlFormat()
1261 if (SettingDialog.IsMonospace)
1263 detailHtmlFormatHeader = detailHtmlFormatMono1;
1264 detailHtmlFormatFooter = detailHtmlFormatMono7;
1268 detailHtmlFormatHeader = detailHtmlFormat1;
1269 detailHtmlFormatFooter = detailHtmlFormat7;
1271 detailHtmlFormatHeader += _fntDetail.Name + detailHtmlFormat2 + _fntDetail.Size.ToString() + detailHtmlFormat3 + _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString() + detailHtmlFormat4 + _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString() + detailHtmlFormat5 + _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString();
1272 if (SettingDialog.IsMonospace)
1274 detailHtmlFormatHeader += detailHtmlFormatMono6;
1278 detailHtmlFormatHeader += detailHtmlFormat6;
1282 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1287 txt = ListTab.TabPages[e.Index].Text;
1294 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1295 if (e.State == DrawItemState.Selected)
1297 e.DrawFocusRectangle();
1302 if (_statuses.Tabs[txt].UnreadCount > 0)
1305 fore = System.Drawing.SystemBrushes.ControlText;
1309 fore = System.Drawing.SystemBrushes.ControlText;
1311 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1314 private void LoadConfig()
1316 _cfgCommon = SettingCommon.Load();
1317 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1319 _cfgCommon.UserAccounts = new List<UserAccount>();
1320 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1322 UserAccount account = new UserAccount();
1323 account.Username = _cfgCommon.UserName;
1324 account.UserId = _cfgCommon.UserId;
1325 account.Token = _cfgCommon.Token;
1326 account.TokenSecret = _cfgCommon.TokenSecret;
1328 _cfgCommon.UserAccounts.Add(account);
1331 _cfgLocal = SettingLocal.Load();
1332 List<TabClass> tabs = SettingTabs.Load().Tabs;
1333 foreach (TabClass tb in tabs)
1337 _statuses.Tabs.Add(tb.TabName, tb);
1341 tb.TabName = _statuses.GetUniqueTabName();
1342 _statuses.Tabs.Add(tb.TabName, tb);
1345 if (_statuses.Tabs.Count == 0)
1347 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1348 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1349 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1350 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1354 private void TimerInterval_Changed(object sender, AppendSettingDialog.IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1356 if (!TimerTimeline.Enabled) return;
1360 private AppendSettingDialog.IntervalChangedEventArgs ResetTimers = new AppendSettingDialog.IntervalChangedEventArgs();
1362 private static int homeCounter = 0;
1363 private static int mentionCounter = 0;
1364 private static int dmCounter = 0;
1365 private static int pubSearchCounter = 0;
1366 private static int userTimelineCounter = 0;
1367 private static int listsCounter = 0;
1368 private static int usCounter = 0;
1369 private static int ResumeWait = 0;
1370 private static int refreshFollowers = 0;
1372 private void TimerTimeline_Elapsed(object sender, EventArgs e)
1374 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1375 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1376 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1377 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1378 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1379 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1380 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1381 Interlocked.Increment(ref refreshFollowers);
1384 if (ResetTimers.Timeline || homeCounter <= 0 && SettingDialog.TimelinePeriodInt > 0)
1386 Interlocked.Exchange(ref homeCounter, SettingDialog.TimelinePeriodInt);
1387 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline) GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
1388 ResetTimers.Timeline = false;
1390 if (ResetTimers.Reply || mentionCounter <= 0 && SettingDialog.ReplyPeriodInt > 0)
1392 Interlocked.Exchange(ref mentionCounter, SettingDialog.ReplyPeriodInt);
1393 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply) GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
1394 ResetTimers.Reply = false;
1396 if (ResetTimers.DirectMessage || dmCounter <= 0 && SettingDialog.DMPeriodInt > 0)
1398 Interlocked.Exchange(ref dmCounter, SettingDialog.DMPeriodInt);
1399 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage) GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
1400 ResetTimers.DirectMessage = false;
1402 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && SettingDialog.PubSearchPeriodInt > 0)
1404 Interlocked.Exchange(ref pubSearchCounter, SettingDialog.PubSearchPeriodInt);
1405 if (!ResetTimers.PublicSearch) GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, "");
1406 ResetTimers.PublicSearch = false;
1408 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && SettingDialog.UserTimelinePeriodInt > 0)
1410 Interlocked.Exchange(ref userTimelineCounter, SettingDialog.UserTimelinePeriodInt);
1411 if (!ResetTimers.UserTimeline) GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, "");
1412 ResetTimers.UserTimeline = false;
1414 if (ResetTimers.Lists || listsCounter <= 0 && SettingDialog.ListsPeriodInt > 0)
1416 Interlocked.Exchange(ref listsCounter, SettingDialog.ListsPeriodInt);
1417 if (!ResetTimers.Lists) GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, "");
1418 ResetTimers.Lists = false;
1420 if (ResetTimers.UserStream || usCounter <= 0 && SettingDialog.UserstreamPeriodInt > 0)
1422 Interlocked.Exchange(ref usCounter, SettingDialog.UserstreamPeriodInt);
1423 if (this._isActiveUserstream) RefreshTimeline(true);
1424 ResetTimers.UserStream = false;
1426 if (refreshFollowers > 6 * 3600)
1428 Interlocked.Exchange(ref refreshFollowers, 0);
1429 doGetFollowersMenu();
1430 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, 0, "");
1431 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
1435 Interlocked.Increment(ref ResumeWait);
1436 if (ResumeWait > 30)
1439 Interlocked.Exchange(ref ResumeWait, 0);
1440 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
1441 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
1442 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
1443 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, "");
1444 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, "");
1445 GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, "");
1446 doGetFollowersMenu();
1447 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
1452 private void RefreshTimeline(bool isUserStream)
1454 if (isUserStream) this.RefreshTasktrayIcon(true);
1456 int smode = -1; //-1:制御しない,-2:最新へ,その他:topitem使用
1457 long topId = GetScrollPos(ref smode);
1458 int befCnt = _curList.VirtualListSize;
1461 Dictionary<string, long[]> selId = new Dictionary<string, long[]>();
1462 Dictionary<string, long[]> focusedId = new Dictionary<string, long[]>();
1463 SaveSelectedStatus(selId, focusedId);
1466 int dmCount = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount;
1469 PostClass[] notifyPosts = null;
1470 string soundFile = "";
1472 bool isMention = false;
1473 bool isDelete = false;
1474 addCount = _statuses.SubmitUpdate(ref soundFile, ref notifyPosts, ref isMention, ref isDelete, isUserStream);
1476 if (MyCommon._endingFlag) return;
1481 foreach (TabPage tab in ListTab.TabPages)
1483 DetailsListView lst = (DetailsListView)tab.Tag;
1484 TabClass tabInfo = _statuses.Tabs[tab.Text];
1485 using (ControlTransaction.Update(lst))
1487 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1489 if (lst.Equals(_curList))
1491 this.PurgeListViewItemCache();
1495 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1501 this.SelectListItem(lst,
1502 _statuses.IndexOf(tab.Text, selId[tab.Text]),
1503 _statuses.IndexOf(tab.Text, focusedId[tab.Text]));
1506 if (tabInfo.UnreadCount > 0)
1507 if (SettingDialog.TabIconDisp)
1508 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1510 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
1514 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1523 if (befCnt != _curList.VirtualListSize)
1529 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(0);
1533 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(_curList.VirtualListSize - 1);
1540 if (_curList.VirtualListSize > 0 && _statuses.IndexOf(_curTab.Text, topId) > -1)
1542 _curList.EnsureVisible(_curList.VirtualListSize - 1);
1543 _curList.EnsureVisible(_statuses.IndexOf(_curTab.Text, topId));
1549 catch (Exception ex)
1551 ex.Data["Msg"] = "Ref2";
1557 NotifyNewPosts(notifyPosts,
1560 isMention || dmCount != _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount);
1562 SetMainWindowTitle();
1563 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
1565 HashSupl.AddRangeItem(tw.GetHashList());
1569 private long GetScrollPos(ref int smode)
1572 if (_curList != null && _curTab != null && _curList.VirtualListSize > 0)
1574 if (_statuses.SortMode == IdComparerClass.ComparerMode.Id)
1576 if (_statuses.SortOrder == SortOrder.Ascending)
1579 if (ListLockMenuItem.Checked)
1584 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1589 //最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1591 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1); //一番下
1592 if (_item == null) _item = _curList.Items[_curList.VirtualListSize - 1];
1593 if (_item.Index == _curList.VirtualListSize - 1)
1600 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1608 if (ListLockMenuItem.Checked)
1611 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1616 //最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1619 _item = _curList.GetItemAt(0, 10); //一番上
1620 if (_item == null) _item = _curList.Items[0];
1621 if (_item.Index == 0)
1627 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1636 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1647 private void SaveSelectedStatus(Dictionary<string, long[]> selId, Dictionary<string, long[]> focusedId)
1649 if (MyCommon._endingFlag) return;
1650 foreach (TabPage tab in ListTab.TabPages)
1652 DetailsListView lst = (DetailsListView)tab.Tag;
1653 if (lst.SelectedIndices.Count > 0 && lst.SelectedIndices.Count < 61)
1655 selId.Add(tab.Text, _statuses.GetId(tab.Text, lst.SelectedIndices));
1659 selId.Add(tab.Text, new long[1] {-2});
1662 var fIds = new long[2]; // 0 = focus, 1 = selection mark
1663 var item = lst.FocusedItem;
1664 fIds[0] = (item != null) ? _statuses.GetId(tab.Text, item.Index) : -2;
1665 var mIdx = lst.SelectionMark;
1666 fIds[1] = (mIdx > -1) ? _statuses.GetId(tab.Text, mIdx) : -2;
1667 focusedId.Add(tab.Text, fIds);
1672 private bool BalloonRequired()
1674 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1675 ev.Eventtype = MyCommon.EVENTTYPE.None;
1677 return BalloonRequired(ev);
1680 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1682 return SettingDialog.EventNotifyEnabled && (type & SettingDialog.EventNotifyFlag) != 0 || type == MyCommon.EVENTTYPE.None;
1685 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1687 return (ev.Eventtype & SettingDialog.IsMyEventNotifyFlag) != 0 ? true : !ev.IsMe;
1690 private bool BalloonRequired(Twitter.FormattedEvent ev)
1693 IsEventNotifyAsEventType(ev.Eventtype) && IsMyEventNotityAsEventType(ev) &&
1694 (NewPostPopMenuItem.Checked || (SettingDialog.ForceEventNotify && ev.Eventtype != MyCommon.EVENTTYPE.None)) &&
1698 SettingDialog.LimitBalloon &&
1700 this.WindowState == FormWindowState.Minimized ||
1702 Form.ActiveForm == null
1705 !SettingDialog.LimitBalloon
1708 !Win32Api.IsScreenSaverRunning())
1718 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1720 if (notifyPosts != null &&
1721 notifyPosts.Length > 0 &&
1722 this.SettingDialog.ReadOwnPost &&
1723 notifyPosts.All((post) => { return post.UserId == tw.UserId || post.ScreenName == tw.Username; }))
1729 if (BalloonRequired())
1731 if (notifyPosts != null && notifyPosts.Length > 0)
1733 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1734 if (SettingDialog.IsNotifyUseGrowl)
1736 StringBuilder sb = new StringBuilder();
1740 foreach (PostClass post in notifyPosts)
1742 if (!(notifyPosts.Length > 3))
1748 if (post.IsReply && !post.IsExcludeReply) reply = true;
1749 if (post.IsDm) dm = true;
1750 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1751 switch (SettingDialog.NameBalloon)
1753 case MyCommon.NameBalloonEnum.UserID:
1754 sb.Append(post.ScreenName).Append(" : ");
1756 case MyCommon.NameBalloonEnum.NickName:
1757 sb.Append(post.Nickname).Append(" : ");
1760 sb.Append(post.TextFromApi);
1761 if (notifyPosts.Length > 3)
1763 if (notifyPosts.Last() != post) continue;
1766 StringBuilder title = new StringBuilder();
1767 GrowlHelper.NotifyType nt;
1768 if (SettingDialog.DispUsername)
1770 title.Append(tw.Username);
1771 title.Append(" - ");
1779 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1780 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1781 title.Append(Application.ProductName);
1782 title.Append(" [DM] ");
1783 title.Append(Properties.Resources.RefreshDirectMessageText1);
1785 title.Append(addCount);
1786 title.Append(Properties.Resources.RefreshDirectMessageText2);
1787 nt = GrowlHelper.NotifyType.DirectMessage;
1791 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1792 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1793 title.Append(Application.ProductName);
1794 title.Append(" [Reply!] ");
1795 title.Append(Properties.Resources.RefreshTimelineText1);
1797 title.Append(addCount);
1798 title.Append(Properties.Resources.RefreshTimelineText2);
1799 nt = GrowlHelper.NotifyType.Reply;
1803 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1804 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1805 title.Append(Application.ProductName);
1807 title.Append(Properties.Resources.RefreshTimelineText1);
1809 title.Append(addCount);
1810 title.Append(Properties.Resources.RefreshTimelineText2);
1811 nt = GrowlHelper.NotifyType.Notify;
1813 string bText = sb.ToString();
1814 if (string.IsNullOrEmpty(bText)) return;
1816 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1817 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1822 StringBuilder sb = new StringBuilder();
1825 foreach (PostClass post in notifyPosts)
1827 if (post.IsReply && !post.IsExcludeReply) reply = true;
1828 if (post.IsDm) dm = true;
1829 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1830 switch (SettingDialog.NameBalloon)
1832 case MyCommon.NameBalloonEnum.UserID:
1833 sb.Append(post.ScreenName).Append(" : ");
1835 case MyCommon.NameBalloonEnum.NickName:
1836 sb.Append(post.Nickname).Append(" : ");
1839 sb.Append(post.TextFromApi);
1842 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1843 StringBuilder title = new StringBuilder();
1845 if (SettingDialog.DispUsername)
1847 title.Append(tw.Username);
1848 title.Append(" - ");
1856 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1857 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1858 ntIcon = ToolTipIcon.Warning;
1859 title.Append(Application.ProductName);
1860 title.Append(" [DM] ");
1861 title.Append(Properties.Resources.RefreshDirectMessageText1);
1863 title.Append(addCount);
1864 title.Append(Properties.Resources.RefreshDirectMessageText2);
1868 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1869 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1870 ntIcon = ToolTipIcon.Warning;
1871 title.Append(Application.ProductName);
1872 title.Append(" [Reply!] ");
1873 title.Append(Properties.Resources.RefreshTimelineText1);
1875 title.Append(addCount);
1876 title.Append(Properties.Resources.RefreshTimelineText2);
1880 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1881 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1882 ntIcon = ToolTipIcon.Info;
1883 title.Append(Application.ProductName);
1885 title.Append(Properties.Resources.RefreshTimelineText1);
1887 title.Append(addCount);
1888 title.Append(Properties.Resources.RefreshTimelineText2);
1890 string bText = sb.ToString();
1891 if (string.IsNullOrEmpty(bText)) return;
1892 //NotifyIcon1.BalloonTipText = sb.ToString();
1893 //NotifyIcon1.ShowBalloonTip(500);
1894 NotifyIcon1.BalloonTipTitle = title.ToString();
1895 NotifyIcon1.BalloonTipText = bText;
1896 NotifyIcon1.BalloonTipIcon = ntIcon;
1897 NotifyIcon1.ShowBalloonTip(500);
1903 if (!_initial && SettingDialog.PlaySound && !string.IsNullOrEmpty(soundFile))
1907 string dir = Application.StartupPath;
1908 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1910 dir = Path.Combine(dir, "Sounds");
1912 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1922 //mentions新着時に画面ブリンク
1923 if (!_initial && SettingDialog.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1925 Win32Api.FlashMyWindow(this.Handle, Win32Api.FlashSpecification.FlashTray, 3);
1929 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1931 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1933 _curItemIndex = _curList.SelectedIndices[0];
1934 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1938 _curPost = GetCurTabPost(_curItemIndex);
1940 catch (ArgumentException)
1945 this.PushSelectPostChain();
1947 if (SettingDialog.UnreadManage) _statuses.SetReadAllTab(true, _curTab.Text, _curItemIndex);
1949 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1955 private void ChangeCacheStyleRead(bool Read, int Index)
1957 //Read:true=既読 false=未読
1958 //未読管理していなかったら既読として扱う
1959 if (!_statuses.Tabs[_curTab.Text].UnreadManage ||
1960 !SettingDialog.UnreadManage) Read = true;
1963 ListViewItem itm = null;
1964 PostClass post = null;
1966 this.TryGetListViewItemCache(Index, out itm, out post);
1968 if (itm == null || post == null)
1970 itm = ((DetailsListView)_curTab.Tag).Items[Index];
1971 post = _statuses[_curTab.Text, Index];
1974 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1977 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1984 Item.SubItems[5].Text = "";
1989 Item.SubItems[5].Text = "★";
1995 else if (Post.RetweetedId != null)
1997 else if (Post.IsOwl && (Post.IsDm || SettingDialog.OneWayLove))
1999 else if (Read || !SettingDialog.UseUnreadStyle)
2004 if (DList == null || Item.Index == -1)
2006 Item.ForeColor = cl;
2007 if (SettingDialog.UseUnreadStyle)
2013 if (SettingDialog.UseUnreadStyle)
2014 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2016 DList.ChangeItemForeColor(Item.Index, cl);
2017 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2021 private void ColorizeList()
2023 //Index:更新対象のListviewItem.Index。Colorを返す。
2024 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2027 _post = _anchorPost;
2031 if (_post == null) return;
2033 var itemColors = new Color[] { };
2036 this.itemCacheLock.EnterReadLock();
2039 if (this._itemCache == null) return;
2042 from i in Enumerable.Range(0, this._itemCache.Length)
2043 select this.JudgeColor(_post, this._postCache[i]);
2045 itemColors = query.ToArray();
2046 itemIndex = _itemCacheIndex;
2048 finally { this.itemCacheLock.ExitReadLock(); }
2050 if (itemIndex < 0) return;
2052 foreach (var backColor in itemColors)
2054 // この処理中に MyList_CacheVirtualItems が呼ばれることがあるため、
2055 // 同一スレッド内での二重ロックを避けるためにロックの外で実行する必要がある
2056 _curList.ChangeItemBackColor(itemIndex++, backColor);
2060 private void ColorizeList(ListViewItem Item, int Index)
2062 //Index:更新対象のListviewItem.Index。Colorを返す。
2063 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2066 _post = _anchorPost;
2070 PostClass tPost = GetCurTabPost(Index);
2072 if (_post == null) return;
2074 if (Item.Index == -1)
2075 Item.BackColor = JudgeColor(_post, tPost);
2077 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2080 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2083 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2086 else if (TargetPost.IsMe)
2089 else if (TargetPost.IsReply)
2092 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLower()))
2094 cl = _clAtFromTarget;
2095 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLower()))
2098 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2103 cl = _clListBackcolor;
2108 private async void PostButton_Click(object sender, EventArgs e)
2110 if (StatusText.Text.Trim().Length == 0)
2112 if (!ImageSelectionPanel.Enabled)
2119 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2121 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2123 MessageBoxButtons.YesNoCancel,
2124 MessageBoxIcon.Question);
2127 case DialogResult.Yes:
2128 doReTweetOfficial(false);
2129 StatusText.Text = "";
2131 case DialogResult.Cancel:
2136 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
2138 if (SettingDialog.Nicoms)
2140 StatusText.SelectionStart = StatusText.Text.Length;
2141 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2143 //if (SettingDialog.UrlConvertAuto)
2145 // StatusText.SelectionStart = StatusText.Text.Length;
2146 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2148 //else if (SettingDialog.Nicoms)
2150 // StatusText.SelectionStart = StatusText.Text.Length;
2151 // UrlConvert(UrlConverter.Nicoms);
2153 StatusText.SelectionStart = StatusText.Text.Length;
2154 GetWorkerArg args = new GetWorkerArg();
2157 args.type = MyCommon.WORKERTYPE.PostMessage;
2158 CheckReplyTo(StatusText.Text);
2161 int adjustCount = 0;
2162 string tmpStatus = StatusText.Text.Trim();
2163 if (ToolStripMenuItemApiCommandEvasion.Checked)
2166 if (Regex.IsMatch(tmpStatus,
2167 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2168 RegexOptions.IgnoreCase)
2169 && tmpStatus.EndsWith(" .") == false) adjustCount += 2;
2172 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2175 adjustCount += Regex.Matches(tmpStatus, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+").Count;
2178 bool isCutOff = false;
2179 bool isRemoveFooter = MyCommon.IsKeyDown(Keys.Shift);
2180 if (StatusText.Multiline && !SettingDialog.PostCtrlEnter)
2182 //複数行でEnter投稿の場合、Ctrlも押されていたらフッタ付加しない
2183 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2185 if (SettingDialog.PostShiftEnter)
2187 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2189 if (!isRemoveFooter && (StatusText.Text.Contains("RT @") || StatusText.Text.Contains("QT @")))
2191 isRemoveFooter = true;
2193 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2195 if (MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
2198 //if (!SettingDialog.UrlConvertAuto) UrlConvertAutoToolStripMenuItem_Click(null, null);
2199 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2201 isRemoveFooter = true;
2212 if (StatusText.Text.StartsWith("D ") || StatusText.Text.StartsWith("d "))
2220 if (HashMgr.IsNotAddToAtReply)
2222 if (!string.IsNullOrEmpty(HashMgr.UseHash) && _reply_to_id == null && string.IsNullOrEmpty(_reply_to_name))
2225 header = HashMgr.UseHash + " ";
2227 footer = " " + HashMgr.UseHash;
2232 if (!string.IsNullOrEmpty(HashMgr.UseHash))
2235 header = HashMgr.UseHash + " ";
2237 footer = " " + HashMgr.UseHash;
2240 if (!isRemoveFooter)
2242 if (SettingDialog.UseRecommendStatus)
2244 footer += SettingDialog.RecommendStatusText;
2246 // テキストボックスに入力されている文字列を使用する
2247 footer += " " + SettingDialog.Status.Trim();
2250 args.status.status = header + StatusText.Text + footer;
2252 if (ToolStripMenuItemApiCommandEvasion.Checked)
2255 if (Regex.IsMatch(args.status.status,
2256 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2257 RegexOptions.IgnoreCase)
2258 && args.status.status.EndsWith(" .") == false) args.status.status += " .";
2261 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2264 Match mc2 = Regex.Match(args.status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+");
2265 if (mc2.Success) args.status.status = Regex.Replace(args.status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
2268 if (IdeographicSpaceToSpaceToolStripMenuItem.Checked)
2270 // 文中の全角スペースを半角スペース1個にする
2271 args.status.status = args.status.status.Replace(" ", " ");
2274 if (isCutOff && args.status.status.Length > 140)
2276 args.status.status = args.status.status.Substring(0, 140);
2277 string AtId = @"(@|@)[a-z0-9_/]+$";
2278 string HashTag = @"(^|[^0-9A-Z&\/\?]+)(#|#)([0-9A-Z_]*[A-Z_]+)$";
2279 string Url = @"https?:\/\/[a-z0-9!\*'\(\);:&=\+\$\/%#\[\]\-_\.,~?]+$"; //簡易判定
2280 string pattern = string.Format("({0})|({1})|({2})", AtId, HashTag, Url);
2281 Match mc = Regex.Match(args.status.status, pattern, RegexOptions.IgnoreCase);
2284 //さらに@ID、ハッシュタグ、URLと推測される文字列をカットする
2285 args.status.status = args.status.status.Substring(0, 140 - mc.Value.Length);
2287 if (MessageBox.Show(args.status.status, "Post or Cancel?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return;
2290 args.status.inReplyToId = _reply_to_id;
2291 args.status.inReplyToName = _reply_to_name;
2292 if (ImageSelectionPanel.Visible)
2295 if (!TryGetSelectedMedia(out args.status.imageService, out args.status.imagePath))
2301 _reply_to_id = null;
2302 _reply_to_name = null;
2303 StatusText.Text = "";
2304 _history.Add(new PostingStatus());
2305 _hisIdx = _history.Count - 1;
2306 if (!ToolStripFocusLockMenuItem.Checked)
2307 ((Control)ListTab.SelectedTab.Tag).Focus();
2308 urlUndoBuffer = null;
2309 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2312 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2314 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeUriString(StatusText.Text.Substring(7)));
2315 await this.OpenUriAsync(tmp);
2319 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2321 MyCommon._endingFlag = true;
2325 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2327 if (!SettingDialog.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2329 //_endingFlag=false:フォームの×ボタン
2331 this.Visible = false;
2335 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2336 _ignoreConfigSave = true;
2337 MyCommon._endingFlag = true;
2338 TimerTimeline.Enabled = false;
2339 TimerRefreshIcon.Enabled = false;
2343 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2345 this.Visible = true;
2346 if (this.WindowState == FormWindowState.Minimized)
2348 this.WindowState = FormWindowState.Normal;
2351 this.BringToFront();
2354 private static int errorCount = 0;
2356 private static bool CheckAccountValid()
2358 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2364 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2373 private void GetTimelineWorker_DoWork(object sender, DoWorkEventArgs e)
2375 BackgroundWorker bw = (BackgroundWorker)sender;
2376 if (bw.CancellationPending || MyCommon._endingFlag)
2382 Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
2384 MyApplication.InitCulture();
2387 GetWorkerResult rslt = new GetWorkerResult();
2389 bool read = !SettingDialog.UnreadManage;
2390 if (_initial && SettingDialog.UnreadManage) read = SettingDialog.Readed;
2392 GetWorkerArg args = (GetWorkerArg)e.Argument;
2394 if (!CheckAccountValid())
2396 rslt.retMsg = "Auth error. Check your account";
2397 rslt.type = MyCommon.WORKERTYPE.ErrorState; //エラー表示のみ行ない、後処理キャンセル
2398 rslt.tName = args.tName;
2403 bw.ReportProgress(0, ""); //Notifyアイコンアニメーション開始
2407 case MyCommon.WORKERTYPE.Timeline:
2408 case MyCommon.WORKERTYPE.Reply:
2409 bw.ReportProgress(50, MakeStatusMessage(args, false));
2410 ret = tw.GetTimelineApi(read, args.type, args.page == -1, _initial);
2412 if (string.IsNullOrEmpty(ret) && args.type == MyCommon.WORKERTYPE.Timeline && SettingDialog.ReadOldPosts)
2413 _statuses.SetRead();
2415 rslt.addCount = _statuses.DistributePosts();
2417 case MyCommon.WORKERTYPE.DirectMessegeRcv: //送信分もまとめて取得
2418 bw.ReportProgress(50, MakeStatusMessage(args, false));
2419 ret = tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, args.page == -1);
2420 if (string.IsNullOrEmpty(ret)) ret = tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, args.page == -1);
2421 rslt.addCount = _statuses.DistributePosts();
2424 case MyCommon.WORKERTYPE.FavAdd:
2428 if (_statuses.Tabs.TryGetValue(args.tName, out tab))
2430 for (int i = 0; i <= args.ids.Count - 1; i++)
2432 var post = tab.Posts[args.ids[i]];
2435 bw.ReportProgress(50, MakeStatusMessage(args, false));
2438 if (post.RetweetedId == null)
2439 ret = tw.PostFavAdd(post.StatusId);
2441 ret = tw.PostFavAdd(post.RetweetedId.Value);
2443 if (ret.Length == 0)
2445 args.sIds.Add(post.StatusId);
2446 post.IsFav = true; //リスト再描画必要
2447 _favTimestamps.Add(DateTime.Now);
2448 if (string.IsNullOrEmpty(post.RelTabName))
2450 //検索,リストUserTimeline.Relatedタブからのfavは、favタブへ追加せず。それ以外は追加
2451 _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).Add(post.StatusId, post.IsRead, false);
2455 //検索,リスト,UserTimeline.Relatedタブからのfavで、TLでも取得済みならfav反映
2456 if (_statuses.ContainsKey(post.StatusId))
2458 PostClass postTl = _statuses[post.StatusId];
2459 postTl.IsFav = true;
2460 _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).Add(postTl.StatusId, postTl.IsRead, false);
2463 //検索,リスト,UserTimeline,Relatedの各タブに反映
2464 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch | MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.UserTimeline | MyCommon.TabUsageType.Related))
2466 if (tb.Contains(post.StatusId)) tb.Posts[post.StatusId].IsFav = true;
2472 rslt.sIds = args.sIds;
2476 case MyCommon.WORKERTYPE.FavRemove:
2480 if (_statuses.Tabs.TryGetValue(args.tName, out tab))
2482 for (int i = 0; i <= args.ids.Count - 1; i++)
2484 var post = tab.Posts[args.ids[i]];
2487 bw.ReportProgress(50, MakeStatusMessage(args, false));
2490 if (post.RetweetedId == null)
2491 ret = tw.PostFavRemove(post.StatusId);
2493 ret = tw.PostFavRemove(post.RetweetedId.Value);
2495 if (ret.Length == 0)
2497 args.sIds.Add(post.StatusId);
2498 post.IsFav = false; //リスト再描画必要
2499 if (_statuses.ContainsKey(post.StatusId)) _statuses[post.StatusId].IsFav = false;
2500 //検索,リスト,UserTimeline,Relatedの各タブに反映
2501 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch | MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.UserTimeline | MyCommon.TabUsageType.Related))
2503 if (tb.Contains(post.StatusId)) tb.Posts[post.StatusId].IsFav = false;
2509 rslt.sIds = args.sIds;
2513 case MyCommon.WORKERTYPE.PostMessage:
2514 bw.ReportProgress(200);
2515 if (string.IsNullOrEmpty(args.status.imagePath))
2517 ret = tw.PostStatus(args.status.status, args.status.inReplyToId);
2521 ret = this.pictureService[args.status.imageService].Upload(ref args.status.imagePath,
2522 ref args.status.status,
2523 args.status.inReplyToId);
2525 bw.ReportProgress(300);
2526 rslt.status = args.status;
2528 case MyCommon.WORKERTYPE.Retweet:
2529 bw.ReportProgress(200);
2530 for (int i = 0; i <= args.ids.Count - 1; i++)
2532 ret = tw.PostRetweet(args.ids[i], read);
2534 bw.ReportProgress(300);
2536 case MyCommon.WORKERTYPE.Follower:
2537 bw.ReportProgress(50, Properties.Resources.UpdateFollowersMenuItem1_ClickText1);
2540 tw.RefreshFollowerIds();
2542 catch (WebApiException ex) { ret = ex.Message; }
2544 case MyCommon.WORKERTYPE.NoRetweetIds:
2547 tw.RefreshNoRetweetIds();
2549 catch (WebApiException ex) { ret = ex.Message; }
2551 case MyCommon.WORKERTYPE.Configuration:
2554 this.SettingDialog.TwitterConfiguration = tw.ConfigurationApi();
2556 catch (WebApiException ex) { ret = ex.Message; }
2558 case MyCommon.WORKERTYPE.Favorites:
2559 bw.ReportProgress(50, MakeStatusMessage(args, false));
2560 ret = tw.GetFavoritesApi(read, args.type, args.page == -1);
2561 rslt.addCount = _statuses.DistributePosts();
2563 case MyCommon.WORKERTYPE.PublicSearch:
2564 bw.ReportProgress(50, MakeStatusMessage(args, false));
2565 if (string.IsNullOrEmpty(args.tName))
2567 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
2569 //if (!string.IsNullOrEmpty(tb.SearchWords)) ret = tw.GetPhoenixSearch(read, tb, false);
2570 if (!string.IsNullOrEmpty(tb.SearchWords)) ret = tw.GetSearch(read, tb, false);
2575 TabClass tb = _statuses.GetTabByName(args.tName);
2578 //ret = tw.GetPhoenixSearch(read, tb, false);
2579 ret = tw.GetSearch(read, tb, false);
2580 if (string.IsNullOrEmpty(ret) && args.page == -1)
2582 //ret = tw.GetPhoenixSearch(read, tb, true)
2583 ret = tw.GetSearch(read, tb, true);
2588 rslt.addCount = _statuses.DistributePosts();
2590 case MyCommon.WORKERTYPE.UserTimeline:
2591 bw.ReportProgress(50, MakeStatusMessage(args, false));
2593 if (SettingDialog.UseAdditionalCount) count = SettingDialog.UserTimelineCountApi;
2594 if (string.IsNullOrEmpty(args.tName))
2596 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
2598 if (!string.IsNullOrEmpty(tb.User)) ret = tw.GetUserTimelineApi(read, count, tb.User, tb, false);
2603 TabClass tb = _statuses.GetTabByName(args.tName);
2606 ret = tw.GetUserTimelineApi(read, count, tb.User, tb, args.page == -1);
2610 rslt.addCount = _statuses.DistributePosts();
2612 case MyCommon.WORKERTYPE.List:
2613 bw.ReportProgress(50, MakeStatusMessage(args, false));
2614 if (string.IsNullOrEmpty(args.tName))
2617 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists))
2619 if (tb.ListInfo != null && tb.ListInfo.Id != 0) ret = tw.GetListStatus(read, tb, false, _initial);
2625 TabClass tb = _statuses.GetTabByName(args.tName);
2628 ret = tw.GetListStatus(read, tb, args.page == -1, _initial);
2632 rslt.addCount = _statuses.DistributePosts();
2635 case MyCommon.WORKERTYPE.Related:
2637 bw.ReportProgress(50, MakeStatusMessage(args, false));
2638 TabClass tab = _statuses.GetTabByName(args.tName);
2639 ret = tw.GetRelatedResult(read, tab);
2640 rslt.addCount = _statuses.DistributePosts();
2644 case MyCommon.WORKERTYPE.BlockIds:
2645 bw.ReportProgress(50, Properties.Resources.UpdateBlockUserText1);
2648 tw.RefreshBlockIds();
2650 catch (WebApiException ex) { ret = ex.Message; }
2654 if (bw.CancellationPending)
2661 if (args.type == MyCommon.WORKERTYPE.FavAdd)
2663 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2664 for (int i = _favTimestamps.Count - 1; i >= 0; i--)
2666 if (_favTimestamps[i].CompareTo(oneHour) < 0)
2668 _favTimestamps.RemoveAt(i);
2672 if (args.type == MyCommon.WORKERTYPE.Timeline && !_initial)
2676 DateTime tm = DateTime.Now;
2677 if (_tlTimestamps.ContainsKey(tm))
2678 _tlTimestamps[tm] += rslt.addCount;
2680 _tlTimestamps.Add(tm, rslt.addCount);
2682 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2683 List<DateTime> keys = new List<DateTime>();
2685 foreach (DateTime key in _tlTimestamps.Keys)
2687 if (key.CompareTo(oneHour) < 0)
2693 _tlCount += _tlTimestamps[key];
2696 foreach (DateTime key in keys)
2698 _tlTimestamps.Remove(key);
2705 bw.ReportProgress(100, MakeStatusMessage(args, true)); //ステータス書き換え、Notifyアイコンアニメーション開始
2708 rslt.type = args.type;
2709 rslt.tName = args.tName;
2710 if (args.type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
2711 args.type == MyCommon.WORKERTYPE.DirectMessegeSnt ||
2712 args.type == MyCommon.WORKERTYPE.Reply ||
2713 args.type == MyCommon.WORKERTYPE.Timeline ||
2714 args.type == MyCommon.WORKERTYPE.Favorites)
2716 rslt.page = args.page - 1; //値が正しいか後でチェック。10ページ毎の継続確認
2722 private string MakeStatusMessage(GetWorkerArg AsyncArg, bool Finish)
2728 switch (AsyncArg.type)
2730 case MyCommon.WORKERTYPE.Timeline:
2731 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2733 case MyCommon.WORKERTYPE.Reply:
2734 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2736 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2737 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2739 case MyCommon.WORKERTYPE.FavAdd:
2740 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15 + AsyncArg.page.ToString() + "/" + AsyncArg.ids.Count.ToString() +
2741 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText16 + (AsyncArg.page - AsyncArg.sIds.Count - 1).ToString();
2743 case MyCommon.WORKERTYPE.FavRemove:
2744 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17 + AsyncArg.page.ToString() + "/" + AsyncArg.ids.Count.ToString() +
2745 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText18 + (AsyncArg.page - AsyncArg.sIds.Count - 1).ToString();
2747 case MyCommon.WORKERTYPE.Favorites:
2748 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19;
2750 case MyCommon.WORKERTYPE.PublicSearch:
2751 smsg = "Search refreshing...";
2753 case MyCommon.WORKERTYPE.List:
2754 smsg = "List refreshing...";
2756 case MyCommon.WORKERTYPE.Related:
2757 smsg = "Related refreshing...";
2759 case MyCommon.WORKERTYPE.UserTimeline:
2760 smsg = "UserTimeline refreshing...";
2767 switch (AsyncArg.type)
2769 case MyCommon.WORKERTYPE.Timeline:
2770 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1;
2772 case MyCommon.WORKERTYPE.Reply:
2773 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9;
2775 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2776 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11;
2778 case MyCommon.WORKERTYPE.DirectMessegeSnt:
2779 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText13;
2781 case MyCommon.WORKERTYPE.FavAdd:
2784 case MyCommon.WORKERTYPE.FavRemove:
2787 case MyCommon.WORKERTYPE.Favorites:
2788 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20;
2790 case MyCommon.WORKERTYPE.Follower:
2791 smsg = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2793 case MyCommon.WORKERTYPE.NoRetweetIds:
2794 smsg = "NoRetweetIds refreshed";
2796 case MyCommon.WORKERTYPE.Configuration:
2799 case MyCommon.WORKERTYPE.PublicSearch:
2800 smsg = "Search refreshed";
2802 case MyCommon.WORKERTYPE.List:
2803 smsg = "List refreshed";
2805 case MyCommon.WORKERTYPE.Related:
2806 smsg = "Related refreshed";
2808 case MyCommon.WORKERTYPE.UserTimeline:
2809 smsg = "UserTimeline refreshed";
2811 case MyCommon.WORKERTYPE.BlockIds:
2812 smsg = Properties.Resources.UpdateBlockUserText3;
2819 private void GetTimelineWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
2821 if (MyCommon._endingFlag) return;
2822 if (e.ProgressPercentage > 100)
2825 if (e.ProgressPercentage == 200) //開始
2826 StatusLabel.Text = "Posting...";
2827 if (e.ProgressPercentage == 300) //終了
2828 StatusLabel.Text = Properties.Resources.PostWorker_RunWorkerCompletedText4;
2832 string smsg = (string)e.UserState;
2833 if (smsg.Length > 0) StatusLabel.Text = smsg;
2837 private void GetTimelineWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
2839 if (MyCommon._endingFlag || e.Cancelled) return; //キャンセル
2841 if (e.Error != null)
2843 _myStatusError = true;
2844 _waitTimeline = false;
2848 _waitPubSearch = false;
2849 _waitUserTimeline = false;
2851 throw new Exception("BackgroundWorker Exception", e.Error);
2854 GetWorkerResult rslt = (GetWorkerResult)e.Result;
2857 if (rslt.retMsg.Length > 0)
2859 _myStatusError = true;
2860 StatusLabel.Text = rslt.retMsg;
2863 if (rslt.type == MyCommon.WORKERTYPE.ErrorState) return;
2865 if (rslt.type == MyCommon.WORKERTYPE.FavRemove)
2867 this.RemovePostFromFavTab(rslt.sIds.ToArray());
2871 //bool busy = false;
2872 //foreach (BackgroundWorker bw in _bw)
2874 // if (bw != null && bw.IsBusy)
2880 //if (!busy) RefreshTimeline(); //background処理なければ、リスト反映
2881 if (rslt.type == MyCommon.WORKERTYPE.Timeline ||
2882 rslt.type == MyCommon.WORKERTYPE.Reply ||
2883 rslt.type == MyCommon.WORKERTYPE.List ||
2884 rslt.type == MyCommon.WORKERTYPE.PublicSearch ||
2885 rslt.type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
2886 rslt.type == MyCommon.WORKERTYPE.DirectMessegeSnt ||
2887 rslt.type == MyCommon.WORKERTYPE.Favorites ||
2888 rslt.type == MyCommon.WORKERTYPE.Follower ||
2889 rslt.type == MyCommon.WORKERTYPE.NoRetweetIds ||
2890 rslt.type == MyCommon.WORKERTYPE.FavAdd ||
2891 rslt.type == MyCommon.WORKERTYPE.FavRemove ||
2892 rslt.type == MyCommon.WORKERTYPE.Related ||
2893 rslt.type == MyCommon.WORKERTYPE.UserTimeline ||
2894 rslt.type == MyCommon.WORKERTYPE.BlockIds ||
2895 rslt.type == MyCommon.WORKERTYPE.Configuration)
2897 RefreshTimeline(false); //リスト反映
2902 case MyCommon.WORKERTYPE.Timeline:
2903 _waitTimeline = false;
2906 // //API使用時の取得調整は別途考える(カウント調整?)
2909 case MyCommon.WORKERTYPE.Reply:
2911 if (rslt.newDM && !_initial)
2913 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
2916 case MyCommon.WORKERTYPE.Favorites:
2919 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2922 case MyCommon.WORKERTYPE.FavAdd:
2923 case MyCommon.WORKERTYPE.FavRemove:
2924 if (_curList != null && _curTab != null)
2926 using (ControlTransaction.Update(this._curList))
2928 if (rslt.type == MyCommon.WORKERTYPE.FavRemove && _statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.Favorites)
2934 for (int i = 0; i <= rslt.sIds.Count - 1; i++)
2936 if (_curTab.Text.Equals(rslt.tName))
2938 int idx = _statuses.Tabs[rslt.tName].IndexOf(rslt.sIds[i]);
2941 PostClass post = null;
2942 TabClass tb = _statuses.Tabs[rslt.tName];
2945 if (tb.TabType == MyCommon.TabUsageType.Lists || tb.TabType == MyCommon.TabUsageType.PublicSearch)
2947 post = tb.Posts[rslt.sIds[i]];
2951 post = _statuses[rslt.sIds[i]];
2953 ChangeCacheStyleRead(post.IsRead, idx);
2955 if (idx == _curItemIndex) DispSelectedPost(true); //選択アイテム再表示
2963 case MyCommon.WORKERTYPE.PostMessage:
2964 if (string.IsNullOrEmpty(rslt.retMsg) ||
2965 rslt.retMsg.StartsWith("OK:") ||
2966 rslt.retMsg == "Warn:Status is a duplicate.")
2968 _postTimestamps.Add(DateTime.Now);
2969 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2970 for (int i = _postTimestamps.Count - 1; i >= 0; i--)
2972 if (_postTimestamps[i].CompareTo(oneHour) < 0)
2974 _postTimestamps.RemoveAt(i);
2978 if (!HashMgr.IsPermanent && !string.IsNullOrEmpty(HashMgr.UseHash))
2980 HashMgr.ClearHashtag();
2981 this.HashStripSplitButton.Text = "#[-]";
2982 this.HashToggleMenuItem.Checked = false;
2983 this.HashToggleToolStripMenuItem.Checked = false;
2985 SetMainWindowTitle();
2993 retry = MessageBox.Show(string.Format("{0} ---> [ " + rslt.retMsg + " ]" + Environment.NewLine + "\"" + rslt.status.status + "\"" + Environment.NewLine + "{1}",
2994 Properties.Resources.StatusUpdateFailed1,
2995 Properties.Resources.StatusUpdateFailed2),
2996 "Failed to update status",
2997 MessageBoxButtons.RetryCancel,
2998 MessageBoxIcon.Question);
3002 retry = DialogResult.Abort;
3004 if (retry == DialogResult.Retry)
3006 GetWorkerArg args = new GetWorkerArg();
3009 args.type = MyCommon.WORKERTYPE.PostMessage;
3010 args.status = rslt.status;
3015 if (ToolStripFocusLockMenuItem.Checked)
3017 //連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3018 StatusText_Enter(StatusText, new EventArgs());
3022 if (rslt.retMsg.Length == 0 && SettingDialog.PostAndGet)
3024 if (_isActiveUserstream)
3026 RefreshTimeline(true);
3030 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3034 case MyCommon.WORKERTYPE.Retweet:
3035 if (rslt.retMsg.Length == 0)
3037 _postTimestamps.Add(DateTime.Now);
3038 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
3039 for (int i = _postTimestamps.Count - 1; i >= 0; i--)
3041 if (_postTimestamps[i].CompareTo(oneHour) < 0)
3043 _postTimestamps.RemoveAt(i);
3046 if (!_isActiveUserstream && SettingDialog.PostAndGet) GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3049 case MyCommon.WORKERTYPE.Follower:
3050 //_waitFollower = false;
3051 this.PurgeListViewItemCache();
3052 if (_curList != null) _curList.Refresh();
3054 case MyCommon.WORKERTYPE.NoRetweetIds:
3056 case MyCommon.WORKERTYPE.Configuration:
3057 //_waitFollower = false
3058 if (SettingDialog.TwitterConfiguration.PhotoSizeLimit != 0)
3060 pictureService["Twitter"].Configuration("MaxUploadFilesize", SettingDialog.TwitterConfiguration.PhotoSizeLimit);
3062 this.PurgeListViewItemCache();
3063 if (_curList != null) _curList.Refresh();
3065 case MyCommon.WORKERTYPE.PublicSearch:
3066 _waitPubSearch = false;
3068 case MyCommon.WORKERTYPE.UserTimeline:
3069 _waitUserTimeline = false;
3071 case MyCommon.WORKERTYPE.List:
3074 case MyCommon.WORKERTYPE.Related:
3075 TabClass tab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
3076 if (tab != null && tab.RelationTargetPost != null && tab.Contains(tab.RelationTargetPost.StatusId))
3078 foreach (TabPage tp in ListTab.TabPages)
3080 if (tp.Text == tab.TabName)
3082 ((DetailsListView)tp.Tag).SelectedIndices.Add(tab.IndexOf(tab.RelationTargetPost.StatusId));
3083 ((DetailsListView)tp.Tag).Items[tab.IndexOf(tab.RelationTargetPost.StatusId)].Focused = true;
3092 private async Task RefreshMuteUserIdsAsync()
3094 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3098 await tw.RefreshMuteUserIdsAsync();
3100 catch (WebApiException ex)
3102 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3106 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3109 private void RemovePostFromFavTab(Int64[] ids)
3111 string favTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).TabName;
3113 if (_curTab.Text.Equals(favTabName))
3115 if (_curList.FocusedItem != null)
3116 fidx = _curList.FocusedItem.Index;
3117 else if (_curList.TopItem != null)
3118 fidx = _curList.TopItem.Index;
3123 foreach (long i in ids)
3127 _statuses.RemoveFavPost(i);
3134 if (_curTab != null && _curTab.Text.Equals(favTabName))
3136 this.PurgeListViewItemCache();
3138 //_curItemIndex = -1;
3140 foreach (TabPage tp in ListTab.TabPages)
3142 if (tp.Text == favTabName)
3144 ((DetailsListView)tp.Tag).VirtualListSize = _statuses.Tabs[favTabName].AllCount;
3148 if (_curTab.Text.Equals(favTabName))
3152 _curList.SelectedIndices.Clear();
3154 while (_curList.SelectedIndices.Count > 0);
3156 if (_statuses.Tabs[favTabName].AllCount > 0)
3158 if (_statuses.Tabs[favTabName].AllCount - 1 > fidx && fidx > -1)
3160 _curList.SelectedIndices.Add(fidx);
3164 _curList.SelectedIndices.Add(_statuses.Tabs[favTabName].AllCount - 1);
3166 if (_curList.SelectedIndices.Count > 0)
3168 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3169 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3175 private static Dictionary<MyCommon.WORKERTYPE, DateTime> lastTime = new Dictionary<MyCommon.WORKERTYPE, DateTime>();
3177 private void GetTimeline(MyCommon.WORKERTYPE WkType, int fromPage, int toPage, string tabName)
3179 if (!this.IsNetworkAvailable()) return;
3182 GetWorkerArg args = new GetWorkerArg();
3183 args.page = fromPage;
3184 args.endPage = toPage;
3186 args.tName = tabName;
3188 if (!lastTime.ContainsKey(WkType)) lastTime.Add(WkType, new DateTime());
3189 double period = DateTime.Now.Subtract(lastTime[WkType]).TotalSeconds;
3190 if (period > 1 || period < -1)
3192 lastTime[WkType] = DateTime.Now;
3196 //Timeline取得モードの場合はReplyも同時に取得
3197 //if (!SettingDialog.UseAPI &&
3199 // WkType == MyCommon.WORKERTYPE.Timeline &&
3200 // SettingDialog.CheckReply)
3202 // //TimerReply.Enabled = false;
3203 // _mentionCounter = SettingDialog.ReplyPeriodInt;
3204 // GetWorkerArg _args = new GetWorkerArg();
3205 // _args.page = fromPage;
3206 // _args.endPage = toPage;
3207 // _args.type = MyCommon.WORKERTYPE.Reply;
3212 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3214 if (e.Button == MouseButtons.Left)
3216 this.Visible = true;
3217 if (this.WindowState == FormWindowState.Minimized)
3219 this.WindowState = _formWindowState;
3222 this.BringToFront();
3226 private void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3228 switch (SettingDialog.ListDoubleClickAction)
3231 MakeReplyOrDirectStatus();
3234 FavoriteChange(true);
3237 if (_curPost != null)
3238 ShowUserStatus(_curPost.ScreenName, false);
3244 ShowRelatedStatusesMenuItem_Click(null, null);
3247 MoveToHomeToolStripMenuItem_Click(null, null);
3250 StatusOpenMenuItem_Click(null, null);
3258 private void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3260 FavoriteChange(true);
3263 private void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3265 FavoriteChange(false);
3269 private void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3271 FavoritesRetweetOriginal();
3274 private void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3276 FavoritesRetweetUnofficial();
3279 private void FavoriteChange(bool FavAdd , bool multiFavoriteChangeDialogEnable = true)
3281 //trueでFavAdd,falseでFavRemove
3282 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3283 || !this.ExistCurrentPost) return;
3286 if (_curList.SelectedIndices.Count > 250 && FavAdd)
3288 MessageBox.Show(Properties.Resources.FavoriteLimitCountText);
3289 _DoFavRetweetFlags = false;
3292 else if (multiFavoriteChangeDialogEnable && _curList.SelectedIndices.Count > 1)
3296 string QuestionText = Properties.Resources.FavAddToolStripMenuItem_ClickText1;
3297 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText3;
3298 if (MessageBox.Show(QuestionText, Properties.Resources.FavAddToolStripMenuItem_ClickText2,
3299 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3301 _DoFavRetweetFlags = false;
3307 if (MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1, Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3308 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3315 GetWorkerArg args = new GetWorkerArg();
3316 args.ids = new List<long>();
3317 args.sIds = new List<long>();
3318 args.tName = _curTab.Text;
3321 args.type = MyCommon.WORKERTYPE.FavAdd;
3325 args.type = MyCommon.WORKERTYPE.FavRemove;
3327 foreach (int idx in _curList.SelectedIndices)
3329 PostClass post = GetCurTabPost(idx);
3332 if (!post.IsFav) args.ids.Add(post.StatusId);
3336 if (post.IsFav) args.ids.Add(post.StatusId);
3339 if (args.ids.Count == 0)
3342 StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3344 StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3352 private PostClass GetCurTabPost(int Index)
3354 this.itemCacheLock.EnterReadLock();
3357 if (_postCache != null && Index >= _itemCacheIndex && Index < _itemCacheIndex + _postCache.Length)
3358 return _postCache[Index - _itemCacheIndex];
3360 finally { this.itemCacheLock.ExitReadLock(); }
3362 return _statuses[_curTab.Text, Index];
3366 private void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3368 if (_curList.SelectedIndices.Count > 0)
3369 OpenUriAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3370 else if (_curList.SelectedIndices.Count == 0)
3371 OpenUriAsync(MyCommon.TwitterUrl);
3374 private void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3376 if (_curList.SelectedIndices.Count > 0)
3377 OpenUriAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3380 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3382 if ((!_initialLayout) && this.Visible)
3384 if (this.WindowState == FormWindowState.Normal)
3386 _mySize = this.ClientSize;
3387 _mySpDis = this.SplitContainer1.SplitterDistance;
3388 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3389 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3390 _modifySettingLocal = true;
3395 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3397 if (SettingDialog.SortOrderLock) return;
3398 IdComparerClass.ComparerMode mode = IdComparerClass.ComparerMode.Id;
3401 mode = IdComparerClass.ComparerMode.Id;
3409 case 6: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
3413 mode = IdComparerClass.ComparerMode.Nickname;
3416 mode = IdComparerClass.ComparerMode.Data;
3419 mode = IdComparerClass.ComparerMode.Id;
3422 mode = IdComparerClass.ComparerMode.Name;
3425 mode = IdComparerClass.ComparerMode.Source;
3429 _statuses.ToggleSortOrder(mode);
3432 DetailsListView list = (DetailsListView)sender;
3435 list.Columns[0].Text = ColumnOrgText[0];
3436 list.Columns[1].Text = ColumnText[2];
3440 for (int i = 0; i <= 7; i++)
3442 list.Columns[i].Text = ColumnOrgText[i];
3444 list.Columns[e.Column].Text = ColumnText[e.Column];
3447 this.PurgeListViewItemCache();
3449 if (_statuses.Tabs[_curTab.Text].AllCount > 0 && _curPost != null)
3451 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_curPost.StatusId);
3454 SelectListItem(_curList, idx);
3455 _curList.EnsureVisible(idx);
3459 _modifySettingCommon = true;
3462 private void TweenMain_LocationChanged(object sender, EventArgs e)
3464 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3466 _myLoc = this.DesktopLocation;
3467 _modifySettingLocal = true;
3471 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3473 if (ListTab.SelectedTab == null) return;
3474 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3475 if (!this.ExistCurrentPost)
3477 ReplyStripMenuItem.Enabled = false;
3478 ReplyAllStripMenuItem.Enabled = false;
3479 DMStripMenuItem.Enabled = false;
3480 ShowProfileMenuItem.Enabled = false;
3481 ShowUserTimelineContextMenuItem.Enabled = false;
3482 ListManageUserContextToolStripMenuItem2.Enabled = false;
3483 MoveToFavToolStripMenuItem.Enabled = false;
3484 TabMenuItem.Enabled = false;
3485 IDRuleMenuItem.Enabled = false;
3486 ReadedStripMenuItem.Enabled = false;
3487 UnreadStripMenuItem.Enabled = false;
3491 ShowProfileMenuItem.Enabled = true;
3492 ListManageUserContextToolStripMenuItem2.Enabled = true;
3493 ReplyStripMenuItem.Enabled = true;
3494 ReplyAllStripMenuItem.Enabled = true;
3495 DMStripMenuItem.Enabled = true;
3496 ShowUserTimelineContextMenuItem.Enabled = true;
3497 MoveToFavToolStripMenuItem.Enabled = true;
3498 TabMenuItem.Enabled = true;
3499 IDRuleMenuItem.Enabled = true;
3500 ReadedStripMenuItem.Enabled = true;
3501 UnreadStripMenuItem.Enabled = true;
3503 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3504 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3506 FavAddToolStripMenuItem.Enabled = false;
3507 FavRemoveToolStripMenuItem.Enabled = false;
3508 StatusOpenMenuItem.Enabled = false;
3509 FavorareMenuItem.Enabled = false;
3510 ShowRelatedStatusesMenuItem.Enabled = false;
3512 ReTweetStripMenuItem.Enabled = false;
3513 ReTweetOriginalStripMenuItem.Enabled = false;
3514 QuoteStripMenuItem.Enabled = false;
3515 FavoriteRetweetContextMenu.Enabled = false;
3516 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3517 if (this.ExistCurrentPost && _curPost.IsDm)
3518 DeleteStripMenuItem.Enabled = true;
3520 DeleteStripMenuItem.Enabled = false;
3524 FavAddToolStripMenuItem.Enabled = true;
3525 FavRemoveToolStripMenuItem.Enabled = true;
3526 StatusOpenMenuItem.Enabled = true;
3527 FavorareMenuItem.Enabled = true;
3528 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3532 ReTweetOriginalStripMenuItem.Enabled = false;
3533 FavoriteRetweetContextMenu.Enabled = false;
3534 if (string.IsNullOrEmpty(_curPost.RetweetedBy))
3536 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3540 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3542 DeleteStripMenuItem.Enabled = true;
3546 if (string.IsNullOrEmpty(_curPost.RetweetedBy))
3548 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3552 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3554 DeleteStripMenuItem.Enabled = false;
3555 if (_curPost.IsProtect)
3557 ReTweetOriginalStripMenuItem.Enabled = false;
3558 ReTweetStripMenuItem.Enabled = false;
3559 QuoteStripMenuItem.Enabled = false;
3560 FavoriteRetweetContextMenu.Enabled = false;
3561 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3565 ReTweetOriginalStripMenuItem.Enabled = true;
3566 ReTweetStripMenuItem.Enabled = true;
3567 QuoteStripMenuItem.Enabled = true;
3568 FavoriteRetweetContextMenu.Enabled = true;
3569 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3573 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3575 // RefreshMoreStripMenuItem.Enabled = true;
3579 // RefreshMoreStripMenuItem.Enabled = false;
3581 if (!this.ExistCurrentPost
3582 || _curPost.InReplyToStatusId == null)
3584 RepliedStatusOpenMenuItem.Enabled = false;
3588 RepliedStatusOpenMenuItem.Enabled = true;
3590 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3592 MoveToRTHomeMenuItem.Enabled = false;
3596 MoveToRTHomeMenuItem.Enabled = true;
3600 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3602 MakeReplyOrDirectStatus(false, true);
3605 private void DMStripMenuItem_Click(object sender, EventArgs e)
3607 MakeReplyOrDirectStatus(false, false);
3610 private void doStatusDelete()
3612 if (_curTab == null || _curList == null) return;
3613 if (_statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
3615 bool myPost = false;
3616 foreach (int idx in _curList.SelectedIndices)
3618 if (GetCurTabPost(idx).IsMe ||
3619 GetCurTabPost(idx).RetweetedBy.ToLower() == tw.Username.ToLower())
3625 if (!myPost) return;
3629 if (_curList.SelectedIndices.Count == 0)
3633 string tmp = string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine);
3635 if (MessageBox.Show(tmp, Properties.Resources.DeleteStripMenuItem_ClickText2,
3636 MessageBoxButtons.OKCancel,
3637 MessageBoxIcon.Question) == DialogResult.Cancel) return;
3640 if (_curList.FocusedItem != null)
3641 fidx = _curList.FocusedItem.Index;
3642 else if (_curList.TopItem != null)
3643 fidx = _curList.TopItem.Index;
3649 this.Cursor = Cursors.WaitCursor;
3652 foreach (long Id in _statuses.GetId(_curTab.Text, _curList.SelectedIndices))
3655 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)
3657 rtn = tw.RemoveDirectMessage(Id, _statuses[Id]);
3661 if (_statuses[Id].IsMe || _statuses[Id].RetweetedBy.ToLower() == tw.Username.ToLower())
3662 rtn = tw.RemoveStatus(Id);
3673 _statuses.RemovePost(Id);
3678 StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; //失敗
3680 StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; //成功
3682 this.PurgeListViewItemCache();
3685 foreach (TabPage tb in ListTab.TabPages)
3687 ((DetailsListView)tb.Tag).VirtualListSize = _statuses.Tabs[tb.Text].AllCount;
3688 if (_curTab.Equals(tb))
3692 _curList.SelectedIndices.Clear();
3694 while (_curList.SelectedIndices.Count > 0);
3696 if (_statuses.Tabs[tb.Text].AllCount > 0)
3698 if (_statuses.Tabs[tb.Text].AllCount - 1 > fidx && fidx > -1)
3699 _curList.SelectedIndices.Add(fidx);
3701 _curList.SelectedIndices.Add(_statuses.Tabs[tb.Text].AllCount - 1);
3703 if (_curList.SelectedIndices.Count > 0)
3705 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3706 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3710 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3712 if (SettingDialog.TabIconDisp)
3714 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3718 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3722 this.Cursor = Cursors.Default;
3726 private void DeleteStripMenuItem_Click(object sender, EventArgs e)
3731 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3733 using (ControlTransaction.Update(this._curList))
3735 if (SettingDialog.UnreadManage)
3737 foreach (int idx in _curList.SelectedIndices)
3739 _statuses.SetReadAllTab(true, _curTab.Text, idx);
3742 foreach (int idx in _curList.SelectedIndices)
3744 ChangeCacheStyleRead(true, idx);
3748 foreach (TabPage tb in ListTab.TabPages)
3750 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3752 if (SettingDialog.TabIconDisp)
3754 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3758 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3761 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3763 using (ControlTransaction.Update(this._curList))
3765 if (SettingDialog.UnreadManage)
3767 foreach (int idx in _curList.SelectedIndices)
3769 _statuses.SetReadAllTab(false, _curTab.Text, idx);
3772 foreach (int idx in _curList.SelectedIndices)
3774 ChangeCacheStyleRead(false, idx);
3778 foreach (TabPage tb in ListTab.TabPages)
3780 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3782 if (SettingDialog.TabIconDisp)
3784 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3788 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3791 private void RefreshStripMenuItem_Click(object sender, EventArgs e)
3796 private void DoRefresh()
3798 if (_curTab != null)
3800 switch (_statuses.Tabs[_curTab.Text].TabType)
3802 case MyCommon.TabUsageType.Mentions:
3803 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
3805 case MyCommon.TabUsageType.DirectMessage:
3806 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
3808 case MyCommon.TabUsageType.Favorites:
3809 GetTimeline(MyCommon.WORKERTYPE.Favorites, 1, 0, "");
3811 //case MyCommon.TabUsageType.Profile:
3813 case MyCommon.TabUsageType.PublicSearch:
3815 TabClass tb = _statuses.Tabs[_curTab.Text];
3816 if (string.IsNullOrEmpty(tb.SearchWords)) return;
3817 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, _curTab.Text);
3819 case MyCommon.TabUsageType.UserTimeline:
3820 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, _curTab.Text);
3822 case MyCommon.TabUsageType.Lists:
3824 TabClass tab = _statuses.Tabs[_curTab.Text];
3825 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
3826 GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, _curTab.Text);
3829 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3835 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3839 private void DoRefreshMore()
3842 if (_curTab != null)
3844 switch (_statuses.Tabs[_curTab.Text].TabType)
3846 case MyCommon.TabUsageType.Mentions:
3847 GetTimeline(MyCommon.WORKERTYPE.Reply, -1, 0, "");
3849 case MyCommon.TabUsageType.DirectMessage:
3850 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, -1, 0, "");
3852 case MyCommon.TabUsageType.Favorites:
3853 GetTimeline(MyCommon.WORKERTYPE.Favorites, -1, 0, "");
3855 case MyCommon.TabUsageType.Profile:
3858 case MyCommon.TabUsageType.PublicSearch:
3860 TabClass tb = _statuses.Tabs[_curTab.Text];
3861 if (string.IsNullOrEmpty(tb.SearchWords)) return;
3862 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, -1, 0, _curTab.Text);
3864 case MyCommon.TabUsageType.UserTimeline:
3865 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, -1, 0, _curTab.Text);
3867 case MyCommon.TabUsageType.Lists:
3869 TabClass tab = _statuses.Tabs[_curTab.Text];
3870 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
3871 GetTimeline(MyCommon.WORKERTYPE.List, -1, 0, _curTab.Text);
3874 GetTimeline(MyCommon.WORKERTYPE.Timeline, -1, 0, "");
3880 GetTimeline(MyCommon.WORKERTYPE.Timeline, -1, 0, "");
3884 private void SettingStripMenuItem_Click(object sender, EventArgs e)
3886 DialogResult result;
3887 string uid = tw.Username.ToLower();
3888 var oldIconSz = SettingDialog.IconSz;
3892 result = SettingDialog.ShowDialog(this);
3899 if (result == DialogResult.OK)
3903 tw.TinyUrlResolve = SettingDialog.TinyUrlResolve;
3904 tw.RestrictFavCheck = SettingDialog.RestrictFavCheck;
3905 tw.ReadOwnPost = SettingDialog.ReadOwnPost;
3906 ShortUrl.Instance.DisableExpanding = !SettingDialog.TinyUrlResolve;
3907 ShortUrl.Instance.BitlyId = SettingDialog.BitlyUser;
3908 ShortUrl.Instance.BitlyKey = SettingDialog.BitlyPwd;
3909 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
3911 HttpConnection.InitializeConnection(SettingDialog.DefaultTimeOut,
3912 SettingDialog.SelectedProxyType,
3913 SettingDialog.ProxyAddress,
3914 SettingDialog.ProxyPort,
3915 SettingDialog.ProxyUser,
3916 SettingDialog.ProxyPassword);
3917 this.CreatePictureServices();
3921 if (SettingDialog.TabIconDisp)
3923 ListTab.DrawItem -= ListTab_DrawItem;
3924 ListTab.DrawMode = TabDrawMode.Normal;
3925 ListTab.ImageList = this.TabImage;
3929 ListTab.DrawItem -= ListTab_DrawItem;
3930 ListTab.DrawItem += ListTab_DrawItem;
3931 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3932 ListTab.ImageList = null;
3935 catch (Exception ex)
3937 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3938 ex.Data["IsTerminatePermission"] = false;
3944 if (!SettingDialog.UnreadManage)
3946 ReadedStripMenuItem.Enabled = false;
3947 UnreadStripMenuItem.Enabled = false;
3948 if (SettingDialog.TabIconDisp)
3950 foreach (TabPage myTab in ListTab.TabPages)
3952 myTab.ImageIndex = -1;
3958 ReadedStripMenuItem.Enabled = true;
3959 UnreadStripMenuItem.Enabled = true;
3962 catch (Exception ex)
3964 ex.Data["Instance"] = "ListTab(UnreadManage)";
3965 ex.Data["IsTerminatePermission"] = false;
3972 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3973 imgazyobizinet.Enabled = this.SettingDialog.EnableImgAzyobuziNet;
3974 imgazyobizinet.DisabledInDM = this.SettingDialog.ImgAzyobuziNetDisabledInDM;
3976 PlaySoundMenuItem.Checked = SettingDialog.PlaySound;
3977 this.PlaySoundFileMenuItem.Checked = SettingDialog.PlaySound;
3978 _fntUnread = SettingDialog.FontUnread;
3979 _clUnread = SettingDialog.ColorUnread;
3980 _fntReaded = SettingDialog.FontReaded;
3981 _clReaded = SettingDialog.ColorReaded;
3982 _clFav = SettingDialog.ColorFav;
3983 _clOWL = SettingDialog.ColorOWL;
3984 _clRetweet = SettingDialog.ColorRetweet;
3985 _fntDetail = SettingDialog.FontDetail;
3986 _clDetail = SettingDialog.ColorDetail;
3987 _clDetailLink = SettingDialog.ColorDetailLink;
3988 _clDetailBackcolor = SettingDialog.ColorDetailBackcolor;
3989 _clSelf = SettingDialog.ColorSelf;
3990 _clAtSelf = SettingDialog.ColorAtSelf;
3991 _clTarget = SettingDialog.ColorTarget;
3992 _clAtTarget = SettingDialog.ColorAtTarget;
3993 _clAtFromTarget = SettingDialog.ColorAtFromTarget;
3994 _clAtTo = SettingDialog.ColorAtTo;
3995 _clListBackcolor = SettingDialog.ColorListBackcolor;
3996 _clInputBackcolor = SettingDialog.ColorInputBackcolor;
3997 _clInputFont = SettingDialog.ColorInputFont;
3998 _fntInputFont = SettingDialog.FontInputFont;
3999 _brsBackColorMine.Dispose();
4000 _brsBackColorAt.Dispose();
4001 _brsBackColorYou.Dispose();
4002 _brsBackColorAtYou.Dispose();
4003 _brsBackColorAtFromTarget.Dispose();
4004 _brsBackColorAtTo.Dispose();
4005 _brsBackColorNone.Dispose();
4006 _brsBackColorMine = new SolidBrush(_clSelf);
4007 _brsBackColorAt = new SolidBrush(_clAtSelf);
4008 _brsBackColorYou = new SolidBrush(_clTarget);
4009 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4010 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4011 _brsBackColorAtTo = new SolidBrush(_clAtTo);
4012 _brsBackColorNone = new SolidBrush(_clListBackcolor);
4016 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4017 StatusText.Font = _fntInputFont;
4018 StatusText.ForeColor = _clInputFont;
4020 catch (Exception ex)
4022 MessageBox.Show(ex.Message);
4027 InitDetailHtmlFormat();
4029 catch (Exception ex)
4031 ex.Data["Instance"] = "Font";
4032 ex.Data["IsTerminatePermission"] = false;
4038 _statuses.SetUnreadManage(SettingDialog.UnreadManage);
4040 catch (Exception ex)
4042 ex.Data["Instance"] = "_statuses";
4043 ex.Data["IsTerminatePermission"] = false;
4049 foreach (TabPage tb in ListTab.TabPages)
4051 if (SettingDialog.TabIconDisp)
4053 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4060 catch (Exception ex)
4062 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4063 ex.Data["IsTerminatePermission"] = false;
4069 var oldIconCol = _iconCol;
4071 if (SettingDialog.IconSz != oldIconSz)
4072 ApplyListViewIconSize(SettingDialog.IconSz);
4074 foreach (TabPage tp in ListTab.TabPages)
4076 DetailsListView lst = (DetailsListView)tp.Tag;
4078 using (ControlTransaction.Update(lst))
4080 lst.GridLines = SettingDialog.ShowGrid;
4081 lst.Font = _fntReaded;
4082 lst.BackColor = _clListBackcolor;
4084 if (_iconCol != oldIconCol)
4089 catch (Exception ex)
4091 ex.Data["Instance"] = "ListView(IconSize)";
4092 ex.Data["IsTerminatePermission"] = false;
4096 SetMainWindowTitle();
4097 SetNotifyIconText();
4099 this.PurgeListViewItemCache();
4100 if (_curList != null) _curList.Refresh();
4103 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4104 if (SettingDialog.HotkeyEnabled)
4106 ///グローバルホットキーの登録。設定で変更可能にするかも
4107 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4108 if ((SettingDialog.HotkeyMod & Keys.Alt) == Keys.Alt) modKey = modKey | HookGlobalHotkey.ModKeys.Alt;
4109 if ((SettingDialog.HotkeyMod & Keys.Control) == Keys.Control) modKey = modKey | HookGlobalHotkey.ModKeys.Ctrl;
4110 if ((SettingDialog.HotkeyMod & Keys.Shift) == Keys.Shift) modKey = modKey | HookGlobalHotkey.ModKeys.Shift;
4111 if ((SettingDialog.HotkeyMod & Keys.LWin) == Keys.LWin) modKey = modKey | HookGlobalHotkey.ModKeys.Win;
4113 _hookGlobalHotkey.RegisterOriginalHotkey(SettingDialog.HotkeyKey, SettingDialog.HotkeyValue, modKey);
4116 if (uid != tw.Username) this.doGetFollowersMenu();
4118 SetImageServiceCombo();
4119 if (SettingDialog.IsNotifyUseGrowl) gh.RegisterGrowl();
4122 StatusText_TextChanged(null, null);
4130 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4132 this.TopMost = SettingDialog.AlwaysTop;
4133 SaveConfigsAll(false);
4139 private void SetTabAlignment()
4141 ListTab.Alignment = (SettingDialog.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top);
4144 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4150 case MyCommon.IconSizes.IconNone:
4153 case MyCommon.IconSizes.Icon16:
4156 case MyCommon.IconSizes.Icon24:
4159 case MyCommon.IconSizes.Icon48:
4162 case MyCommon.IconSizes.Icon48_2:
4170 // ディスプレイの DPI 設定を考慮したサイズを設定する
4171 _listViewImageList.ImageSize = new Size(
4173 (int)Math.Ceiling(this._iconSz * this.currentScaleFactor.Height));
4177 _listViewImageList.ImageSize = new Size(1, 1);
4181 private void ResetColumns(DetailsListView list)
4183 using (ControlTransaction.Update(list))
4184 using (ControlTransaction.Layout(list, false))
4187 list.ColumnClick -= MyList_ColumnClick;
4188 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4189 list.ColumnReordered -= MyList_ColumnReordered;
4190 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4192 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4193 list.Columns.Clear();
4194 cols.ForEach(col => col.Dispose());
4197 InitColumns(list, true);
4199 list.ColumnClick += MyList_ColumnClick;
4200 list.DrawColumnHeader += MyList_DrawColumnHeader;
4201 list.ColumnReordered += MyList_ColumnReordered;
4202 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4206 private void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4208 if (e.Url.AbsoluteUri != "about:blank")
4211 OpenUriAsync(e.Url.OriginalString);
4215 private void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4217 if (e.Url.Scheme == "data")
4219 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4221 else if (e.Url.AbsoluteUri != "about:blank")
4225 if (e.Url.AbsoluteUri.StartsWith("http://twitter.com/search?q=%23") ||
4226 e.Url.AbsoluteUri.StartsWith("https://twitter.com/search?q=%23"))
4229 string urlStr = Uri.UnescapeDataString(e.Url.AbsoluteUri);
4230 int i = urlStr.IndexOf('#');
4231 if (i == -1) return;
4233 string hash = urlStr.Substring(i);
4234 HashSupl.AddItem(hash);
4235 HashMgr.AddHashToHistory(hash.Trim(), false);
4236 AddNewTabForSearch(hash);
4241 Match m = Regex.Match(e.Url.AbsoluteUri, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
4242 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
4244 // Ctrlを押しながらリンクをクリックした場合は設定と逆の動作をする
4245 if (SettingDialog.OpenUserTimeline)
4247 if (MyCommon.IsKeyDown(Keys.Control))
4248 OpenUriAsync(e.Url.OriginalString);
4250 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4254 if (MyCommon.IsKeyDown(Keys.Control))
4255 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4257 OpenUriAsync(e.Url.OriginalString);
4262 OpenUriAsync(e.Url.OriginalString);
4268 public void AddNewTabForSearch(string searchWord)
4270 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4271 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4273 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4275 foreach (TabPage tp in ListTab.TabPages)
4277 if (tb.TabName == tp.Text)
4279 ListTab.SelectedTab = tp;
4286 string tabName = searchWord;
4287 for (int i = 0; i <= 100; i++)
4289 if (_statuses.ContainsTab(tabName))
4295 _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4296 AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4298 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4300 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4301 cmb.Items.Add(searchWord);
4302 cmb.Text = searchWord;
4305 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4308 private void ShowUserTimeline()
4310 if (!this.ExistCurrentPost) return;
4311 AddNewTabForUserTimeline(_curPost.ScreenName);
4314 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4316 if (e.KeyCode == Keys.Escape)
4318 TabPage relTp = ListTab.SelectedTab;
4319 RemoveSpecifiedTab(relTp.Text, false);
4321 e.SuppressKeyPress = true;
4325 public void AddNewTabForUserTimeline(string user)
4327 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4328 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4330 if (tb.User == user)
4332 foreach (TabPage tp in ListTab.TabPages)
4334 if (tb.TabName == tp.Text)
4336 ListTab.SelectedTab = tp;
4343 string tabName = "user:" + user;
4344 while (_statuses.ContainsTab(tabName))
4349 _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4350 _statuses.Tabs[tabName].User = user;
4351 AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4353 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4357 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, tabName);
4360 public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4363 foreach (TabPage tb in ListTab.TabPages)
4365 if (tb.Text == tabName) return false;
4369 if (tabName == Properties.Resources.AddNewTabText1) return false;
4374 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4375 tabType == MyCommon.TabUsageType.Favorites ||
4376 tabType == MyCommon.TabUsageType.Home ||
4377 tabType == MyCommon.TabUsageType.Mentions ||
4378 tabType == MyCommon.TabUsageType.Related)
4380 if (_statuses.GetTabByType(tabType) != null) return false;
4384 TabPage _tabPage = new TabPage();
4385 DetailsListView _listCustom = new DetailsListView();
4387 int cnt = ListTab.TabPages.Count;
4389 ///ToDo:Create and set controls follow tabtypes
4391 using (ControlTransaction.Update(_listCustom))
4392 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4393 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4394 using (ControlTransaction.Layout(this.SplitContainer1, false))
4395 using (ControlTransaction.Layout(this.ListTab, false))
4396 using (ControlTransaction.Layout(this))
4397 using (ControlTransaction.Layout(_tabPage, false))
4401 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4403 label = new Label();
4404 label.Dock = DockStyle.Top;
4405 label.Name = "labelUser";
4406 if (tabType == MyCommon.TabUsageType.Lists)
4408 label.Text = listInfo.ToString();
4412 label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4414 label.TextAlign = ContentAlignment.MiddleLeft;
4415 using (ComboBox tmpComboBox = new ComboBox())
4417 label.Height = tmpComboBox.Height;
4419 _tabPage.Controls.Add(label);
4424 if (tabType == MyCommon.TabUsageType.PublicSearch)
4428 Label lbl = new Label();
4429 ComboBox cmb = new ComboBox();
4430 Button btn = new Button();
4431 ComboBox cmbLang = new ComboBox();
4433 pnl.SuspendLayout();
4435 pnl.Controls.Add(cmb);
4436 pnl.Controls.Add(cmbLang);
4437 pnl.Controls.Add(btn);
4438 pnl.Controls.Add(lbl);
4439 pnl.Name = "panelSearch";
4440 pnl.Dock = DockStyle.Top;
4441 pnl.Height = cmb.Height;
4442 pnl.Enter += SearchControls_Enter;
4443 pnl.Leave += SearchControls_Leave;
4446 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4447 cmb.Dock = DockStyle.Fill;
4448 cmb.Name = "comboSearch";
4449 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4450 cmb.ImeMode = ImeMode.NoControl;
4451 cmb.TabStop = false;
4452 cmb.AutoCompleteMode = AutoCompleteMode.None;
4453 cmb.KeyDown += SearchComboBox_KeyDown;
4455 if (_statuses.ContainsTab(tabName))
4457 cmb.Items.Add(_statuses.Tabs[tabName].SearchWords);
4458 cmb.Text = _statuses.Tabs[tabName].SearchWords;
4462 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4463 cmbLang.Dock = DockStyle.Right;
4465 cmbLang.Name = "comboLang";
4466 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4467 cmbLang.TabStop = false;
4468 cmbLang.Items.Add("");
4469 cmbLang.Items.Add("ja");
4470 cmbLang.Items.Add("en");
4471 cmbLang.Items.Add("ar");
4472 cmbLang.Items.Add("da");
4473 cmbLang.Items.Add("nl");
4474 cmbLang.Items.Add("fa");
4475 cmbLang.Items.Add("fi");
4476 cmbLang.Items.Add("fr");
4477 cmbLang.Items.Add("de");
4478 cmbLang.Items.Add("hu");
4479 cmbLang.Items.Add("is");
4480 cmbLang.Items.Add("it");
4481 cmbLang.Items.Add("no");
4482 cmbLang.Items.Add("pl");
4483 cmbLang.Items.Add("pt");
4484 cmbLang.Items.Add("ru");
4485 cmbLang.Items.Add("es");
4486 cmbLang.Items.Add("sv");
4487 cmbLang.Items.Add("th");
4488 if (_statuses.ContainsTab(tabName)) cmbLang.Text = _statuses.Tabs[tabName].SearchLang;
4490 lbl.Text = "Search(C-S-f)";
4491 lbl.Name = "label1";
4492 lbl.Dock = DockStyle.Left;
4494 lbl.Height = cmb.Height;
4495 lbl.TextAlign = ContentAlignment.MiddleLeft;
4497 btn.Text = "Search";
4498 btn.Name = "buttonSearch";
4499 btn.UseVisualStyleBackColor = true;
4500 btn.Dock = DockStyle.Right;
4501 btn.TabStop = false;
4502 btn.Click += SearchButton_Click;
4505 this.ListTab.Controls.Add(_tabPage);
4506 _tabPage.Controls.Add(_listCustom);
4508 if (tabType == MyCommon.TabUsageType.PublicSearch) _tabPage.Controls.Add(pnl);
4509 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists) _tabPage.Controls.Add(label);
4511 _tabPage.Location = new Point(4, 4);
4512 _tabPage.Name = "CTab" + cnt.ToString();
4513 _tabPage.Size = new Size(380, 260);
4514 _tabPage.TabIndex = 2 + cnt;
4515 _tabPage.Text = tabName;
4516 _tabPage.UseVisualStyleBackColor = true;
4518 _listCustom.AllowColumnReorder = true;
4519 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4520 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4521 _listCustom.Dock = DockStyle.Fill;
4522 _listCustom.FullRowSelect = true;
4523 _listCustom.HideSelection = false;
4524 _listCustom.Location = new Point(0, 0);
4525 _listCustom.Margin = new Padding(0);
4526 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4527 _listCustom.ShowItemToolTips = true;
4528 _listCustom.Size = new Size(380, 260);
4529 _listCustom.UseCompatibleStateImageBehavior = false;
4530 _listCustom.View = View.Details;
4531 _listCustom.OwnerDraw = true;
4532 _listCustom.VirtualMode = true;
4533 _listCustom.Font = _fntReaded;
4534 _listCustom.BackColor = _clListBackcolor;
4536 _listCustom.GridLines = SettingDialog.ShowGrid;
4537 _listCustom.AllowDrop = true;
4539 _listCustom.SmallImageList = _listViewImageList;
4541 InitColumns(_listCustom, startup);
4543 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4544 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4545 _listCustom.ColumnClick += MyList_ColumnClick;
4546 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4547 _listCustom.DragDrop += TweenMain_DragDrop;
4548 _listCustom.DragEnter += TweenMain_DragEnter;
4549 _listCustom.DragOver += TweenMain_DragOver;
4550 _listCustom.DrawItem += MyList_DrawItem;
4551 _listCustom.MouseClick += MyList_MouseClick;
4552 _listCustom.ColumnReordered += MyList_ColumnReordered;
4553 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4554 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4555 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4556 _listCustom.DrawSubItem += MyList_DrawSubItem;
4557 _listCustom.HScrolled += MyList_HScrolled;
4559 if (tabType == MyCommon.TabUsageType.PublicSearch) pnl.ResumeLayout(false);
4562 _tabPage.Tag = _listCustom;
4566 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4568 if (_statuses.IsDefaultTab(TabName) || _statuses.Tabs[TabName].Protected) return false;
4572 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4573 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4574 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4580 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault<TabPage>(tp => tp.Text == TabName);
4581 if (_tabPage == null) return false;
4583 SetListProperty(); //他のタブに列幅等を反映
4585 MyCommon.TabUsageType tabType = _statuses.Tabs[TabName].TabType;
4588 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4589 _tabPage.Tag = null;
4591 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4592 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4593 using (ControlTransaction.Layout(this.SplitContainer1, false))
4594 using (ControlTransaction.Layout(this.ListTab, false))
4595 using (ControlTransaction.Layout(this))
4596 using (ControlTransaction.Layout(_tabPage, false))
4598 if (this.ListTab.SelectedTab == _tabPage)
4600 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4601 this._beforeSelectedTab = null;
4603 this.ListTab.Controls.Remove(_tabPage);
4606 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4608 using (Control label = _tabPage.Controls["labelUser"])
4610 _tabPage.Controls.Remove(label);
4613 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4615 using (Control pnl = _tabPage.Controls["panelSearch"])
4617 pnl.Enter -= SearchControls_Enter;
4618 pnl.Leave -= SearchControls_Leave;
4619 _tabPage.Controls.Remove(pnl);
4621 foreach (Control ctrl in pnl.Controls)
4623 if (ctrl.Name == "buttonSearch")
4625 ctrl.Click -= SearchButton_Click;
4627 else if (ctrl.Name == "comboSearch")
4629 ctrl.KeyDown -= SearchComboBox_KeyDown;
4631 pnl.Controls.Remove(ctrl);
4637 _tabPage.Controls.Remove(_listCustom);
4639 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4640 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4641 _listCustom.ColumnClick -= MyList_ColumnClick;
4642 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4643 _listCustom.DragDrop -= TweenMain_DragDrop;
4644 _listCustom.DragEnter -= TweenMain_DragEnter;
4645 _listCustom.DragOver -= TweenMain_DragOver;
4646 _listCustom.DrawItem -= MyList_DrawItem;
4647 _listCustom.MouseClick -= MyList_MouseClick;
4648 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4649 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4650 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4651 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4652 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4653 _listCustom.HScrolled -= MyList_HScrolled;
4655 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4656 _listCustom.Columns.Clear();
4657 cols.ForEach(col => col.Dispose());
4660 _listCustom.ContextMenuStrip = null;
4661 _listCustom.ColumnHeaderContextMenuStrip = null;
4662 _listCustom.Font = null;
4664 _listCustom.SmallImageList = null;
4665 _listCustom.ListViewItemSorter = null;
4668 if (_curTab.Equals(_tabPage))
4675 this.PurgeListViewItemCache();
4679 _listCustom.Dispose();
4680 _statuses.RemoveTab(TabName);
4682 foreach (TabPage tp in ListTab.TabPages)
4684 DetailsListView lst = (DetailsListView)tp.Tag;
4685 var count = _statuses.Tabs[tp.Text].AllCount;
4686 if (lst.VirtualListSize != count)
4688 lst.VirtualListSize = count;
4695 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4697 this.PurgeListViewItemCache();
4698 _beforeSelectedTab = e.TabPage;
4701 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4705 if (!SettingDialog.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4708 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4709 if (!dragEnableRectangle.Contains(e.Location))
4711 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4712 tn = ListTab.SelectedTab.Text;
4715 if (string.IsNullOrEmpty(tn)) return;
4717 foreach (TabPage tb in ListTab.TabPages)
4721 ListTab.DoDragDrop(tb, DragDropEffects.All);
4731 Point cpos = new Point(e.X, e.Y);
4732 for (int i = 0; i < ListTab.TabPages.Count; i++)
4734 Rectangle rect = ListTab.GetTabRect(i);
4735 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4736 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4738 _rclickTabName = ListTab.TabPages[i].Text;
4744 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4746 //_curList.Refresh();
4748 SetMainWindowTitle();
4749 SetStatusLabelUrl();
4750 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4751 TabMenuControl(ListTab.SelectedTab.Text);
4752 this.PushSelectPostChain();
4755 private void SetListProperty()
4757 //削除などで見つからない場合は処理せず
4758 if (_curList == null) return;
4759 if (!_isColumnChanged) return;
4761 int[] dispOrder = new int[_curList.Columns.Count];
4762 for (int i = 0; i < _curList.Columns.Count; i++)
4764 for (int j = 0; j < _curList.Columns.Count; j++)
4766 if (_curList.Columns[j].DisplayIndex == i)
4775 foreach (TabPage tb in ListTab.TabPages)
4777 if (!tb.Equals(_curTab))
4779 if (tb.Tag != null && tb.Controls.Count > 0)
4781 DetailsListView lst = (DetailsListView)tb.Tag;
4782 for (int i = 0; i < lst.Columns.Count; i++)
4784 lst.Columns[dispOrder[i]].DisplayIndex = i;
4785 lst.Columns[i].Width = _curList.Columns[i].Width;
4791 _isColumnChanged = false;
4794 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
4798 if (PostBrowser.StatusText.StartsWith("http") || PostBrowser.StatusText.StartsWith("ftp")
4799 || PostBrowser.StatusText.StartsWith("data"))
4801 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4803 if (string.IsNullOrEmpty(PostBrowser.StatusText))
4805 SetStatusLabelUrl();
4813 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4815 if (e.KeyChar == '@')
4817 if (!SettingDialog.UseAtIdSupplement) return;
4819 int cnt = AtIdSupl.ItemCount;
4820 ShowSuplDialog(StatusText, AtIdSupl);
4821 if (cnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
4824 else if (e.KeyChar == '#')
4826 if (!SettingDialog.UseHashSupplement) return;
4827 ShowSuplDialog(StatusText, HashSupl);
4832 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4834 ShowSuplDialog(owner, dialog, 0, "");
4837 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4839 ShowSuplDialog(owner, dialog, offset, "");
4842 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4844 dialog.StartsWith = startswith;
4851 dialog.ShowDialog();
4853 this.TopMost = SettingDialog.AlwaysTop;
4854 int selStart = owner.SelectionStart;
4857 if (dialog.DialogResult == DialogResult.OK)
4859 if (!string.IsNullOrEmpty(dialog.inputText))
4863 fHalf = owner.Text.Substring(0, selStart - offset);
4865 if (selStart < owner.Text.Length)
4867 eHalf = owner.Text.Substring(selStart);
4869 owner.Text = fHalf + dialog.inputText + eHalf;
4870 owner.SelectionStart = selStart + dialog.inputText.Length;
4877 fHalf = owner.Text.Substring(0, selStart);
4879 if (selStart < owner.Text.Length)
4881 eHalf = owner.Text.Substring(selStart);
4883 owner.Text = fHalf + eHalf;
4886 owner.SelectionStart = selStart;
4892 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4895 if (!e.Alt && !e.Control && !e.Shift)
4897 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4899 bool isSpace = false;
4900 foreach (char c in StatusText.Text.ToCharArray())
4902 if (c == ' ' || c == ' ')
4915 StatusText.Text = "";
4916 JumpUnreadMenuItem_Click(null, null);
4920 this.StatusText_TextChanged(null, null);
4923 private void StatusText_TextChanged(object sender, EventArgs e)
4926 int pLen = GetRestStatusCount(true, false);
4927 lblLen.Text = pLen.ToString();
4930 StatusText.ForeColor = Color.Red;
4934 StatusText.ForeColor = _clInputFont;
4936 if (string.IsNullOrEmpty(StatusText.Text))
4938 _reply_to_id = null;
4939 _reply_to_name = null;
4943 private int GetRestStatusCount(bool isAuto, bool isAddFooter)
4946 var statusText = this.StatusText.Text;
4947 statusText = statusText.Replace("\r\n", "\n");
4949 int pLen = 140 - statusText.Length;
4950 if (this.NotifyIcon1 == null || !this.NotifyIcon1.Visible) return pLen;
4951 if ((isAuto && !MyCommon.IsKeyDown(Keys.Control) && SettingDialog.PostShiftEnter) ||
4952 (isAuto && !MyCommon.IsKeyDown(Keys.Shift) && !SettingDialog.PostShiftEnter) ||
4953 (!isAuto && isAddFooter))
4955 if (SettingDialog.UseRecommendStatus)
4956 pLen -= SettingDialog.RecommendStatusText.Length;
4957 else if (SettingDialog.Status.Length > 0)
4958 pLen -= SettingDialog.Status.Length + 1;
4960 if (!string.IsNullOrEmpty(HashMgr.UseHash))
4962 pLen -= HashMgr.UseHash.Length + 1;
4964 //foreach (Match m in Regex.Matches(statusText, "https?:\/\/[-_.!~*//()a-zA-Z0-9;\/?:\@&=+\$,%#^]+"))
4966 // pLen += m.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4968 foreach (Match m in Regex.Matches(statusText, Twitter.rgUrl, RegexOptions.IgnoreCase))
4970 string before = m.Result("${before}");
4971 string url = m.Result("${url}");
4972 string protocol = m.Result("${protocol}");
4973 string domain = m.Result("${domain}");
4974 string path = m.Result("${path}");
4975 if (protocol.Length == 0)
4977 if (Regex.IsMatch(before, Twitter.url_invalid_without_protocol_preceding_chars))
4982 bool last_url_invalid_match = false;
4983 string lasturl = null;
4984 foreach (Match mm in Regex.Matches(domain, Twitter.url_valid_ascii_domain, RegexOptions.IgnoreCase))
4986 lasturl = mm.ToString();
4987 last_url_invalid_match = Regex.IsMatch(lasturl, Twitter.url_invalid_short_domain, RegexOptions.IgnoreCase);
4988 if (!last_url_invalid_match)
4990 pLen += lasturl.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4994 if (path.Length != 0)
4996 if (last_url_invalid_match)
4998 pLen += lasturl.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
5000 pLen += path.Length;
5005 int shortUrlLength = protocol == "https://"
5006 ? SettingDialog.TwitterConfiguration.ShortUrlLengthHttps
5007 : SettingDialog.TwitterConfiguration.ShortUrlLength;
5009 pLen += url.Length - shortUrlLength;
5012 //if (m.Result("${url}").Length > SettingDialog.TwitterConfiguration.ShortUrlLength)
5014 // pLen += m.Result("${url}").Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
5017 if (ImageSelectionPanel.Visible && ImageSelectedPicture.Tag != null && !string.IsNullOrEmpty(this.ImageService))
5019 pLen -= SettingDialog.TwitterConfiguration.CharactersReservedPerMedia;
5024 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5026 this.itemCacheLock.EnterUpgradeableReadLock();
5029 if (_curList.Equals(sender))
5031 if (_itemCache != null &&
5032 e.StartIndex >= _itemCacheIndex &&
5033 e.EndIndex < _itemCacheIndex + _itemCache.Length)
5035 //If the newly requested cache is a subset of the old cache,
5036 //no need to rebuild everything, so do nothing.
5040 //Now we need to rebuild the cache.
5041 CreateCache(e.StartIndex, e.EndIndex);
5044 finally { this.itemCacheLock.ExitUpgradeableReadLock(); }
5047 private async void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5049 ListViewItem item = null;
5050 PostClass cacheItemPost = null;
5052 if (_curList.Equals(sender))
5053 this.TryGetListViewItemCache(e.ItemIndex, out item, out cacheItemPost);
5057 //A cache miss, so create a new ListViewItem and pass it back.
5058 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5061 item = this.CreateItem(tb, _statuses[tb.Text, e.ItemIndex], e.ItemIndex);
5066 string[] sitem = {"", "", "", "", "", "", "", ""};
5067 item = new ImageListViewItem(sitem);
5071 // e.Item に値をセットする前に await しないこと
5074 await ((ImageListViewItem)item).GetImageAsync();
5077 private void CreateCache(int StartIndex, int EndIndex)
5079 this.itemCacheLock.EnterWriteLock();
5082 //キャッシュ要求(要求範囲±30を作成)
5084 if (StartIndex < 0) StartIndex = 0;
5086 if (EndIndex >= _statuses.Tabs[_curTab.Text].AllCount) EndIndex = _statuses.Tabs[_curTab.Text].AllCount - 1;
5087 _postCache = _statuses[_curTab.Text, StartIndex, EndIndex]; //配列で取得
5088 _itemCacheIndex = StartIndex;
5090 _itemCache = new ListViewItem[0] {};
5091 Array.Resize(ref _itemCache, _postCache.Length);
5093 for (int i = 0; i < _postCache.Length; i++)
5095 _itemCache[i] = CreateItem(_curTab, _postCache[i], StartIndex + i);
5100 //キャッシュ要求が実データとずれるため(イベントの遅延?)
5102 _itemCacheIndex = -1;
5105 finally { this.itemCacheLock.ExitWriteLock(); }
5109 /// DetailsListView のための ListViewItem のキャッシュを消去する
5111 private void PurgeListViewItemCache()
5113 this.itemCacheLock.EnterWriteLock();
5116 this._itemCache = null;
5117 this._itemCacheIndex = -1;
5118 this._postCache = null;
5120 finally { this.itemCacheLock.ExitWriteLock(); }
5123 private bool TryGetListViewItemCache(int index, out ListViewItem item, out PostClass post)
5125 this.itemCacheLock.EnterReadLock();
5128 if (this._itemCache != null && index >= this._itemCacheIndex && index < this._itemCacheIndex + this._itemCache.Length)
5130 item = this._itemCache[index - _itemCacheIndex];
5131 post = this._postCache[index - _itemCacheIndex];
5135 finally { this.itemCacheLock.ExitReadLock(); }
5142 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5144 StringBuilder mk = new StringBuilder();
5145 //if (Post.IsDeleted) mk.Append("×");
5146 //if (Post.IsMark) mk.Append("♪");
5147 //if (Post.IsProtect) mk.Append("Ю");
5148 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5149 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5150 ImageListViewItem itm;
5151 if (Post.RetweetedId == null)
5153 string[] sitem= {"",
5155 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5156 Post.CreatedAt.ToString(SettingDialog.DateTimeFormat),
5161 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5165 string[] sitem = {"",
5167 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5168 Post.CreatedAt.ToString(SettingDialog.DateTimeFormat),
5169 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5173 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5175 itm.StateImageIndex = Post.StateIndex;
5177 bool read = Post.IsRead;
5178 //未読管理していなかったら既読として扱う
5179 if (!_statuses.Tabs[Tab.Text].UnreadManage || !SettingDialog.UnreadManage) read = true;
5180 ChangeItemStyleRead(read, itm, Post, null);
5181 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5186 /// 全てのタブの振り分けルールを反映し直します
5188 private void ApplyPostFilters()
5192 this.Cursor = Cursors.WaitCursor;
5194 this.PurgeListViewItemCache();
5195 this._curPost = null;
5196 this._curItemIndex = -1;
5197 this._statuses.FilterAll();
5199 foreach (TabPage tabPage in this.ListTab.TabPages)
5201 var tab = this._statuses.Tabs[tabPage.Text];
5203 var listview = (DetailsListView)tabPage.Tag;
5204 listview.VirtualListSize = tab.AllCount;
5206 if (this.SettingDialog.TabIconDisp)
5208 if (tab.UnreadCount > 0)
5209 tabPage.ImageIndex = 0;
5211 tabPage.ImageIndex = -1;
5215 if (!this.SettingDialog.TabIconDisp)
5216 this.ListTab.Refresh();
5220 this.Cursor = Cursors.Default;
5224 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5226 e.DrawDefault = true;
5229 private void MyList_HScrolled(object sender, EventArgs e)
5231 DetailsListView listView = (DetailsListView)sender;
5235 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5237 if (e.State == 0) return;
5238 e.DrawDefault = false;
5239 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5241 SolidBrush brs2 = null;
5243 if (e.Item.BackColor == _clSelf)
5244 brs2 = _brsBackColorMine;
5245 else if (e.Item.BackColor == _clAtSelf)
5246 brs2 = _brsBackColorAt;
5247 else if (e.Item.BackColor == _clTarget)
5248 brs2 = _brsBackColorYou;
5249 else if (e.Item.BackColor == _clAtTarget)
5250 brs2 = _brsBackColorAtYou;
5251 else if (e.Item.BackColor == _clAtFromTarget)
5252 brs2 = _brsBackColorAtFromTarget;
5253 else if (e.Item.BackColor == _clAtTo)
5254 brs2 = _brsBackColorAtTo;
5256 brs2 = _brsBackColorNone;
5258 e.Graphics.FillRectangle(brs2, e.Bounds);
5263 if (((Control)sender).Focused)
5264 e.Graphics.FillRectangle(_brsHighLight, e.Bounds);
5266 e.Graphics.FillRectangle(_brsDeactiveSelection, e.Bounds);
5268 if ((e.State & ListViewItemStates.Focused) == ListViewItemStates.Focused) e.DrawFocusRectangle();
5269 this.DrawListViewItemIcon(e);
5272 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5274 if (e.ItemState == 0) return;
5276 if (e.ColumnIndex > 0)
5279 RectangleF rct = e.Bounds;
5280 rct.Width = e.Header.Width;
5283 rct.Y += e.Item.Font.Height;
5284 rct.Height -= e.Item.Font.Height;
5288 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, e.Item.Font.Height, out heightDiff));
5290 //if (heightDiff > e.Item.Font.Height * 0.7)
5292 // rct.Height += e.Item.Font.Height;
5293 // drawLineCount += 1;
5296 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5297 if (!_iconCol && drawLineCount <= 1)
5299 //rct.Inflate(0, heightDiff / -2);
5300 //rct.Height += e.Item.Font.Height / 2;
5302 else if (heightDiff < e.Item.Font.Height * 0.7)
5304 //最終行が70%以上欠けていたら、最終行は表示しない
5305 //rct.Height = (float)((e.Item.Font.Height * drawLineCount) + (e.Item.Font.Height / 2));
5306 rct.Height = (e.Item.Font.Height * drawLineCount) - 1;
5313 //if (!_iconCol && drawLineCount > 1)
5315 // rct.Y += e.Item.Font.Height * 0.2;
5316 // if (heightDiff >= e.Item.Font.Height * 0.8) rct.Height -= e.Item.Font.Height * 0.2;
5321 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5322 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5327 RectangleF rctB = e.Bounds;
5328 rctB.Width = e.Header.Width;
5329 rctB.Height = e.Item.Font.Height;
5331 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5333 TextRenderer.DrawText(e.Graphics,
5334 e.Item.SubItems[2].Text,
5336 Rectangle.Round(rct),
5338 TextFormatFlags.WordBreak |
5339 TextFormatFlags.EndEllipsis |
5340 TextFormatFlags.GlyphOverhangPadding |
5341 TextFormatFlags.NoPrefix);
5342 TextRenderer.DrawText(e.Graphics,
5343 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 + "]",
5345 Rectangle.Round(rctB),
5347 TextFormatFlags.SingleLine |
5348 TextFormatFlags.EndEllipsis |
5349 TextFormatFlags.GlyphOverhangPadding |
5350 TextFormatFlags.NoPrefix);
5353 else if (drawLineCount == 1)
5355 TextRenderer.DrawText(e.Graphics,
5358 Rectangle.Round(rct),
5360 TextFormatFlags.SingleLine |
5361 TextFormatFlags.EndEllipsis |
5362 TextFormatFlags.GlyphOverhangPadding |
5363 TextFormatFlags.NoPrefix |
5364 TextFormatFlags.VerticalCenter);
5368 TextRenderer.DrawText(e.Graphics,
5371 Rectangle.Round(rct),
5373 TextFormatFlags.WordBreak |
5374 TextFormatFlags.EndEllipsis |
5375 TextFormatFlags.GlyphOverhangPadding |
5376 TextFormatFlags.NoPrefix);
5378 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5383 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5385 ImageListViewItem item = (ImageListViewItem)e.Item;
5387 //e.Bounds.Leftが常に0を指すから自前で計算
5388 Rectangle itemRect = item.Bounds;
5389 itemRect.Width = e.Item.ListView.Columns[0].Width;
5391 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5393 if (clm.DisplayIndex < e.Item.ListView.Columns[0].DisplayIndex)
5394 itemRect.X += clm.Width;
5397 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5398 var realIconSize = new SizeF(this._iconSz * this.currentScaleFactor.Width, this._iconSz * this.currentScaleFactor.Height).ToSize();
5399 var realStateSize = new SizeF(16 * this.currentScaleFactor.Width, 16 * this.currentScaleFactor.Height).ToSize();
5402 Rectangle stateRect;
5403 if (item.Image != null)
5405 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5406 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5407 stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5411 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5412 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5413 stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5416 var img = item.Image;
5417 if (img != null && iconRect.Width > 0)
5419 e.Graphics.FillRectangle(Brushes.White, iconRect);
5420 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5423 e.Graphics.DrawImage(img.Image, iconRect);
5425 catch (ArgumentException)
5427 item.RefreshImageAsync();
5431 if (item.StateImageIndex > -1)
5433 if (stateRect.Width > 0)
5435 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5436 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5437 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateImageIndex], stateRect);
5442 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5444 base.ScaleControl(factor, specified);
5446 const int baseDpi = 96;
5448 // デザイン時の DPI (96dpi) との比を更新する
5449 this.currentScaleFactor = new SizeF(
5450 this.CurrentAutoScaleDimensions.Width / baseDpi,
5451 this.CurrentAutoScaleDimensions.Height / baseDpi);
5454 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5456 // ImageListViewItem item = (ImageListViewItem)e.Item;
5457 // if (item.StateImageIndex > -1)
5459 // ////e.Bounds.Leftが常に0を指すから自前で計算
5460 // //Rectangle itemRect = item.Bounds;
5461 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5463 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5465 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5467 // // itemRect.X += clm.Width;
5471 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5472 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5474 // if (rct.Width > 0)
5476 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5477 // //e.Graphics.FillRectangle(Brushes.White, rct);
5478 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5479 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5484 private void DoTabSearch(string _word,
5494 if (_curList.VirtualListSize == 0)
5496 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5499 if (_curList.SelectedIndices.Count > 0)
5501 cidx = _curList.SelectedIndices[0];
5503 toIdx = _curList.VirtualListSize;
5507 case SEARCHTYPE.DialogSearch: //ダイアログからの検索
5508 if (_curList.SelectedIndices.Count > 0)
5509 cidx = _curList.SelectedIndices[0];
5513 case SEARCHTYPE.NextSearch: //次を検索
5514 if (_curList.SelectedIndices.Count > 0)
5516 cidx = _curList.SelectedIndices[0] + 1;
5517 if (cidx > toIdx) cidx = toIdx;
5524 case SEARCHTYPE.PrevSearch: //前を検索
5525 if (_curList.SelectedIndices.Count > 0)
5527 cidx = _curList.SelectedIndices[0] - 1;
5528 if (cidx < 0) cidx = 0;
5539 RegexOptions regOpt = RegexOptions.None;
5540 StringComparison fndOpt = StringComparison.Ordinal;
5543 regOpt = RegexOptions.IgnoreCase;
5544 fndOpt = StringComparison.OrdinalIgnoreCase;
5555 _search = new Regex(_word, regOpt);
5556 for (int idx = cidx; idx != toIdx; idx += stp)
5561 post = _statuses[_curTab.Text, idx];
5567 if (_search.IsMatch(post.Nickname)
5568 || _search.IsMatch(post.TextFromApi)
5569 || _search.IsMatch(post.ScreenName))
5571 SelectListItem(_curList, idx);
5572 _curList.EnsureVisible(idx);
5577 catch (ArgumentException)
5579 MessageBox.Show(Properties.Resources.DoTabSearchText1, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
5586 for (int idx = cidx; idx != toIdx; idx += stp)
5591 post = _statuses[_curTab.Text, idx];
5597 if (post.Nickname.IndexOf(_word, fndOpt) > -1
5598 || post.TextFromApi.IndexOf(_word, fndOpt) > -1
5599 || post.ScreenName.IndexOf(_word, fndOpt) > -1)
5601 SelectListItem(_curList, idx);
5602 _curList.EnsureVisible(idx);
5612 case SEARCHTYPE.DialogSearch:
5613 case SEARCHTYPE.NextSearch:
5617 case SEARCHTYPE.PrevSearch:
5619 cidx = _curList.VirtualListSize - 1;
5626 catch (ArgumentOutOfRangeException)
5629 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5632 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5635 this.ShowSearchDialog();
5638 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5640 var previousSearch = this.SearchDialog.ResultOptions;
5641 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5643 this.SearchDialog.Reset();
5644 this.ShowSearchDialog();
5650 previousSearch.Query,
5651 previousSearch.CaseSensitive,
5652 previousSearch.UseRegex,
5653 SEARCHTYPE.NextSearch);
5656 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5658 var previousSearch = this.SearchDialog.ResultOptions;
5659 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5661 this.SearchDialog.Reset();
5662 this.ShowSearchDialog();
5668 previousSearch.Query,
5669 previousSearch.CaseSensitive,
5670 previousSearch.UseRegex,
5671 SEARCHTYPE.PrevSearch);
5675 /// 検索ダイアログを表示し、検索を実行します
5677 private void ShowSearchDialog()
5679 // Recentタブの検索時以外では「新規タブに表示」ボタンを無効化する
5680 if (this._statuses.Tabs[this._curTab.Text].TabType == MyCommon.TabUsageType.Home)
5681 this.SearchDialog.DisableNewTabButton = false;
5683 this.SearchDialog.DisableNewTabButton = true;
5685 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5687 this.TopMost = this.SettingDialog.AlwaysTop;
5690 this.TopMost = this.SettingDialog.AlwaysTop;
5692 var searchOptions = this.SearchDialog.ResultOptions;
5693 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5695 if (searchOptions.NewTab)
5697 var tabName = searchOptions.Query;
5701 tabName = this._statuses.MakeTabName(tabName);
5703 catch (TabException ex)
5705 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5708 this.AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined);
5709 this._statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null);
5711 var filter = new PostFilterRule
5713 FilterBody = new[] { searchOptions.Query },
5714 UseRegex = searchOptions.UseRegex,
5715 CaseSensitive = searchOptions.CaseSensitive,
5717 this._statuses.Tabs[tabName].AddFilter(filter);
5719 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5720 .First(x => x.Text == tabName);
5722 this.ListTab.SelectedTab = tabPage;
5723 this.ListTabSelect(tabPage);
5725 this.ApplyPostFilters();
5726 this.SaveConfigsTabs();
5731 searchOptions.Query,
5732 searchOptions.CaseSensitive,
5733 searchOptions.UseRegex,
5734 SEARCHTYPE.DialogSearch);
5737 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5739 this.AddNewTabForSearch(searchOptions.Query);
5743 private void AboutMenuItem_Click(object sender, EventArgs e)
5745 using (TweenAboutBox about = new TweenAboutBox())
5747 about.ShowDialog(this);
5749 this.TopMost = SettingDialog.AlwaysTop;
5752 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5754 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5756 DetailsListView lst = null;
5758 if (ImageSelectionPanel.Enabled)
5762 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5765 idx = _statuses.GetOldestUnreadIndex(ListTab.TabPages[i].Text);
5768 ListTab.SelectedIndex = i;
5769 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5770 //_curTab = ListTab.TabPages[i];
5775 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5776 if (idx == -1 && bgnIdx > 0)
5778 for (int i = 0; i < bgnIdx; i++)
5780 idx = _statuses.GetOldestUnreadIndex(ListTab.TabPages[i].Text);
5783 ListTab.SelectedIndex = i;
5784 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5785 //_curTab = ListTab.TabPages[i];
5791 //全部調べたが未読見つからず→先頭タブの最新発言へ
5794 ListTab.SelectedIndex = 0;
5795 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5796 //_curTab = ListTab.TabPages[0];
5797 if (_statuses.SortOrder == SortOrder.Ascending)
5798 idx = lst.VirtualListSize - 1;
5803 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5805 SelectListItem(lst, idx);
5806 if (_statuses.SortMode == IdComparerClass.ComparerMode.Id)
5808 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5809 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5815 lst.EnsureVisible(idx);
5820 lst.EnsureVisible(idx);
5826 private void StatusOpenMenuItem_Click(object sender, EventArgs e)
5828 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5830 var post = _statuses[_curTab.Text, _curList.SelectedIndices[0]];
5831 OpenUriAsync(MyCommon.GetStatusUrl(post));
5835 private void FavorareMenuItem_Click(object sender, EventArgs e)
5837 if (_curList.SelectedIndices.Count > 0)
5839 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[0]];
5840 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5844 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5846 await this.CheckNewVersion(false);
5849 private void RunTweenUp()
5851 ProcessStartInfo pinfo = new ProcessStartInfo();
5852 pinfo.UseShellExecute = true;
5853 pinfo.WorkingDirectory = MyCommon.settingPath;
5854 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5855 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5858 Process.Start(pinfo);
5862 MessageBox.Show("Failed to execute TweenUp3.exe.");
5866 public class VersionInfo
5868 public Version Version { get; set; }
5869 public Uri DownloadUri { get; set; }
5870 public string ReleaseNote { get; set; }
5874 /// OpenTween の最新バージョンの情報を取得します
5876 public async Task<VersionInfo> GetVersionInfoAsync()
5878 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5879 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5881 var responseText = await this.http.GetStringAsync(versionInfoUrl)
5882 .ConfigureAwait(false);
5884 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5885 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5887 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5888 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5890 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5892 return new VersionInfo
5894 Version = Version.Parse(msgHeader[0]),
5895 DownloadUri = new Uri(msgHeader[1]),
5896 ReleaseNote = msgBody,
5900 private async Task CheckNewVersion(bool startup = false)
5902 if (ApplicationSettings.VersionInfoUrl == null)
5903 return; // 更新チェック無効化
5907 var versionInfo = await this.GetVersionInfoAsync();
5909 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5914 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5915 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5916 msgtext = MyCommon.ReplaceAppName(msgtext);
5918 MessageBox.Show(msgtext,
5919 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5920 MessageBoxButtons.OK, MessageBoxIcon.Information);
5925 using (var dialog = new UpdateDialog())
5927 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5928 MyCommon.GetReadableVersion(versionInfo.Version));
5929 dialog.DetailsText = versionInfo.ReleaseNote;
5931 if (dialog.ShowDialog(this) == DialogResult.Yes)
5933 await this.OpenUriAsync(versionInfo.DownloadUri.OriginalString);
5939 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5942 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5943 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5944 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5949 private void Colorize()
5953 //件数関連の場合、タイトル即時書き換え
5954 if (SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.None &&
5955 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5956 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5957 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5959 SetMainWindowTitle();
5961 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
5962 foreach (TabPage tb in ListTab.TabPages)
5964 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5966 if (SettingDialog.TabIconDisp)
5968 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5972 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
5975 public string createDetailHtml(string orgdata)
5977 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5980 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
5982 if (sender.Equals(displayItem))
5984 this.ClearUserPicture();
5986 var img = displayItem.Image;
5990 img = await img.CloneAsync();
5992 UserPicture.Image = img;
5996 UserPicture.ShowErrorImage();
6001 private void DispSelectedPost()
6003 DispSelectedPost(false);
6006 private static PostClass displaypost = new PostClass();
6009 /// サムネイルの表示処理を表すタスク
6011 private Task thumbnailTask = null;
6014 /// サムネイル表示に使用する CancellationToken の生成元
6016 private CancellationTokenSource thumbnailTokenSource = null;
6018 private void DispSelectedPost(bool forceupdate)
6020 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6023 if (!forceupdate && _curPost.Equals(displaypost))
6026 displaypost = _curPost;
6027 if (displayItem != null)
6029 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6032 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6033 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6035 string dTxt = createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6038 SourceLinkLabel.Tag = null;
6039 SourceLinkLabel.Text = "";
6043 Match mc = Regex.Match(_curPost.SourceHtml, "<a href=\"(?<sourceurl>.+?)\"");
6046 string src = mc.Groups["sourceurl"].Value;
6047 SourceLinkLabel.Tag = mc.Groups["sourceurl"].Value;
6048 mc = Regex.Match(src, "^https?://");
6051 src = src.Insert(0, "https://twitter.com");
6053 SourceLinkLabel.Tag = src;
6057 SourceLinkLabel.Tag = null;
6059 if (string.IsNullOrEmpty(_curPost.Source))
6061 SourceLinkLabel.Text = "";
6062 //SourceLinkLabel.Visible = false;
6066 SourceLinkLabel.Text = _curPost.Source;
6067 //SourceLinkLabel.Visible = true;
6070 SourceLinkLabel.TabStop = false;
6072 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && !_curPost.IsOwl)
6074 NameLabel.Text = "DM TO -> ";
6076 else if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)
6078 NameLabel.Text = "DM FROM <- ";
6082 NameLabel.Text = "";
6084 NameLabel.Text += _curPost.ScreenName + "/" + _curPost.Nickname;
6085 NameLabel.Tag = _curPost.ScreenName;
6086 if (!string.IsNullOrEmpty(_curPost.RetweetedBy))
6088 NameLabel.Text += " (RT:" + _curPost.RetweetedBy + ")";
6091 this.ClearUserPicture();
6093 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6095 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6098 UserPicture.Image = image != null ? image.Clone() : null;
6102 UserPicture.ShowErrorImage();
6106 NameLabel.ForeColor = System.Drawing.SystemColors.ControlText;
6107 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6108 if (_curPost.IsOwl && (SettingDialog.OneWayLove || _statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)) NameLabel.ForeColor = _clOWL;
6109 if (_curPost.RetweetedId != null) NameLabel.ForeColor = _clRetweet;
6110 if (_curPost.IsFav) NameLabel.ForeColor = _clFav;
6112 if (DumpPostClassToolStripMenuItem.Checked)
6114 StringBuilder sb = new StringBuilder(512);
6116 sb.Append("-----Start PostClass Dump<br>");
6117 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
6118 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6119 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
6120 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
6121 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
6122 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
6123 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
6124 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
6125 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
6126 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
6127 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
6128 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
6129 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
6130 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
6131 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
6133 foreach (string nm in _curPost.ReplyToList)
6135 sb.AppendFormat("ReplyToList : {0}<br>", nm);
6138 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
6139 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
6140 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
6141 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
6142 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
6143 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
6144 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
6145 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
6146 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
6147 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
6148 sb.AppendFormat("SearchTabName : {0}<br>", _curPost.RelTabName);
6149 sb.Append("-----End PostClass Dump<br>");
6151 PostBrowser.Visible = false;
6152 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6153 PostBrowser.Visible = true;
6159 if (PostBrowser.DocumentText != dTxt)
6161 PostBrowser.Visible = false;
6162 PostBrowser.DocumentText = dTxt;
6164 this.SplitContainer3.Panel2Collapsed = true;
6166 if (this.IsPreviewEnable)
6168 if (this.thumbnailTokenSource != null)
6170 var oldTokenSource = this.thumbnailTokenSource;
6171 oldTokenSource.Cancel();
6172 this.thumbnailTask.ContinueWith(_ => oldTokenSource.Dispose());
6175 this.thumbnailTokenSource = new CancellationTokenSource();
6177 var token = this.thumbnailTokenSource.Token;
6178 this.thumbnailTask = this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token);
6182 catch (System.Runtime.InteropServices.COMException)
6186 catch (UriFormatException)
6188 PostBrowser.DocumentText = dTxt;
6192 PostBrowser.Visible = true;
6197 private void MatomeMenuItem_Click(object sender, EventArgs e)
6199 OpenApplicationWebsite();
6202 private void OpenApplicationWebsite()
6204 OpenUriAsync(ApplicationSettings.WebsiteUrl);
6207 private void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6209 OpenUriAsync(ApplicationSettings.ShortcutKeyUrl);
6212 private void ListTab_KeyDown(object sender, KeyEventArgs e)
6214 if (ListTab.SelectedTab != null)
6216 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6218 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6219 if (pnl.Controls["comboSearch"].Focused ||
6220 pnl.Controls["comboLang"].Focused ||
6221 pnl.Controls["buttonSearch"].Focused) return;
6223 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
6224 if (State == ModifierState.NotFlags) return;
6225 if (State != ModifierState.None) _anchorFlag = false;
6226 if (CommonKeyDown(e.KeyCode, FocusedControl.ListTab, State))
6229 e.SuppressKeyPress = true;
6234 private ModifierState GetModifierState(bool sControl, bool sShift, bool sAlt)
6236 ModifierState state = ModifierState.None;
6237 if (sControl) state = state | ModifierState.Ctrl;
6238 if (sShift) state = state | ModifierState.Shift;
6239 if (sAlt) state = state | ModifierState.Alt;
6244 private enum ModifierState
6256 //PostBrowser = 102,
6260 private enum FocusedControl : int
6268 private bool CommonKeyDown(Keys KeyCode, FocusedControl Focused, ModifierState Modifier)
6270 //リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6271 if (Focused == FocusedControl.ListTab)
6273 if (Modifier == (ModifierState.Ctrl | ModifierState.Shift) ||
6274 Modifier == ModifierState.Ctrl ||
6275 Modifier == ModifierState.None ||
6276 Modifier == ModifierState.Shift)
6278 if (KeyCode == Keys.J)
6280 SendKeys.Send("{DOWN}");
6283 else if (KeyCode == Keys.K)
6285 SendKeys.Send("{UP}");
6289 if (Modifier == ModifierState.Shift ||
6290 Modifier == ModifierState.None)
6292 if (KeyCode == Keys.F)
6294 SendKeys.Send("{PGDN}");
6297 else if (KeyCode == Keys.B)
6299 SendKeys.Send("{PGUP}");
6308 case ModifierState.None:
6313 OpenApplicationWebsite();
6316 MenuItemSearchNext_Click(null, null);
6322 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
6325 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
6328 if (Focused != FocusedControl.StatusText)
6334 case Keys.ProcessKey:
6335 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6336 JumpUnreadMenuItem_Click(null, null);
6339 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6340 ShowRelatedStatusesMenuItem_Click(null, null);
6344 if (Focused == FocusedControl.ListTab)
6357 case Keys.OemPeriod:
6361 if (this.StatusText.Enabled) this.StatusText.Focus();
6364 MakeReplyOrDirectStatus();
6371 _anchorFlag = false;
6391 // ] in_reply_to参照元へ戻る
6392 GoInReplyToPostTree();
6395 // [ in_reply_toへジャンプ
6396 GoBackInReplyToPostTree();
6399 if (ListTab.SelectedTab != null)
6401 MyCommon.TabUsageType tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6402 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch)
6404 TabPage relTp = ListTab.SelectedTab;
6405 RemoveSpecifiedTab(relTp.Text, false);
6413 else if (Focused == FocusedControl.PostBrowser)
6420 //スクロールを発生させるため、true を返す
6425 case ModifierState.Ctrl:
6430 MakeReplyOrDirectStatus(false, true);
6436 MakeReplyOrDirectStatus(false, false);
6439 FavoriteChange(true);
6442 doRepliedStatusOpen();
6448 ReadedStripMenuItem_Click(null, null);
6451 HashManageMenuItem_Click(null, null);
6454 UrlConvertAutoToolStripMenuItem_Click(null, null);
6457 if (Focused != FocusedControl.PostBrowser)
6459 MultiLineMenuItem_Click(null, null);
6464 MenuItemSubSearch_Click(null, null);
6471 MoveToHomeToolStripMenuItem_Click(null, null);
6475 MoveToFavToolStripMenuItem_Click(null, null);
6479 StatusOpenMenuItem_Click(null, null);
6483 OpenURLMenuItem_Click(null, null);
6487 if (Focused == FocusedControl.ListTab)
6494 return false; //スルーする
6512 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6513 int tabNo = KeyCode - Keys.D1;
6514 if (ListTab.TabPages.Count < tabNo)
6516 ListTab.SelectedIndex = tabNo;
6517 ListTabSelect(ListTab.TabPages[tabNo]);
6520 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
6521 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
6525 else if (Focused == FocusedControl.StatusText)
6531 StatusText.SelectAll();
6535 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6537 _history[_hisIdx] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
6539 if (KeyCode == Keys.Up)
6542 if (_hisIdx < 0) _hisIdx = 0;
6547 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6549 StatusText.Text = _history[_hisIdx].status;
6550 _reply_to_id = _history[_hisIdx].inReplyToId;
6551 _reply_to_name = _history[_hisIdx].inReplyToName;
6552 StatusText.SelectionStart = StatusText.Text.Length;
6556 if (ListTab.SelectedIndex == 0)
6558 ListTab.SelectedIndex = ListTab.TabCount - 1;
6562 ListTab.SelectedIndex -= 1;
6568 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6570 ListTab.SelectedIndex = 0;
6574 ListTab.SelectedIndex += 1;
6582 //フォーカスPostBrowserもしくは関係なし
6586 PostBrowser.Document.ExecCommand("SelectAll", false, null);
6590 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
6591 if (!string.IsNullOrEmpty(_selText))
6595 Clipboard.SetDataObject(_selText, false, 5, 100);
6597 catch (Exception ex)
6599 MessageBox.Show(ex.Message);
6604 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6605 MultiLineMenuItem_Click(null, null);
6610 case ModifierState.Shift:
6615 MenuItemSearchPrev_Click(null, null);
6621 GetTimeline(MyCommon.WORKERTYPE.Reply, -1, 0, "");
6624 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, -1, 0, "");
6628 if (Focused != FocusedControl.StatusText)
6630 if (KeyCode == Keys.R)
6637 if (Focused == FocusedControl.ListTab)
6657 GoBackInReplyToPostTree(true, false);
6660 GoBackInReplyToPostTree(true, true);
6664 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6669 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6673 this.GoBackSelectPostChain();
6678 case ModifierState.Alt:
6682 doReTweetOfficial(true);
6685 if (_curPost != null)
6687 doShowUserStatus(_curPost.ScreenName, false);
6692 ScrollDownPostBrowser(false);
6695 ScrollDownPostBrowser(true);
6698 PageDownPostBrowser(false);
6701 PageDownPostBrowser(true);
6704 if (Focused == FocusedControl.ListTab)
6706 // 別タブの同じ書き込みへ(ALT+←/→)
6707 if (KeyCode == Keys.Right)
6709 GoSamePostToAnotherTab(false);
6712 else if (KeyCode == Keys.Left)
6714 GoSamePostToAnotherTab(true);
6719 case ModifierState.Ctrl | ModifierState.Shift:
6723 MakeReplyOrDirectStatus(false, true, true);
6729 if (ListTab.SelectedTab != null)
6731 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6733 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
6739 FavoriteChange(false);
6742 UnreadStripMenuItem_Click(null, null);
6745 HashToggleMenuItem_Click(null, null);
6748 ImageSelectMenuItem_Click(null, null);
6754 FavorareMenuItem_Click(null, null);
6757 if (Focused == FocusedControl.StatusText)
6763 if (_curList != null && _curList.VirtualListSize != 0 &&
6764 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6766 idx = _curList.SelectedIndices[0] - 1;
6767 SelectListItem(_curList, idx);
6768 _curList.EnsureVisible(idx);
6773 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6774 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6776 idx = _curList.SelectedIndices[0] + 1;
6777 SelectListItem(_curList, idx);
6778 _curList.EnsureVisible(idx);
6783 if (StatusText.SelectionStart > 0)
6785 int endidx = StatusText.SelectionStart - 1;
6786 string startstr = "";
6787 bool pressed = false;
6788 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6790 char c = StatusText.Text[i];
6791 if (Char.IsLetterOrDigit(c) || c == '_')
6798 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6799 int cnt = AtIdSupl.ItemCount;
6800 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6801 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
6806 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6807 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6819 else if (Focused == FocusedControl.ListTab)
6821 DetailsListView lst = (DetailsListView)ListTab.SelectedTab.Tag;
6833 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6834 int colNo = KeyCode - Keys.D1;
6835 if (lst.Columns.Count < colNo) return false;
6836 col = lst.Columns.Cast<ColumnHeader>().Where((x) => { return x.DisplayIndex == colNo; }).FirstOrDefault();
6837 if (col == null) return false;
6838 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
6841 col = lst.Columns.Cast<ColumnHeader>().OrderByDescending((x) => { return x.DisplayIndex; }).First();
6842 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
6847 case ModifierState.Ctrl | ModifierState.Alt:
6848 if (KeyCode == Keys.S)
6850 FavoritesRetweetOriginal();
6853 else if (KeyCode == Keys.R)
6855 FavoritesRetweetUnofficial();
6858 else if (KeyCode == Keys.H)
6860 OpenUserAppointUrl();
6864 case ModifierState.Alt | ModifierState.Shift:
6865 if (Focused == FocusedControl.PostBrowser)
6867 if (KeyCode == Keys.R)
6868 doReTweetUnofficial();
6869 else if (KeyCode == Keys.C)
6876 if (!this.ExistCurrentPost) return false;
6877 doTranslation(_curPost.TextFromApi);
6880 doReTweetUnofficial();
6886 this.tweetThumbnail1.ScrollUp();
6889 this.tweetThumbnail1.ScrollDown();
6892 if (Focused == FocusedControl.ListTab && KeyCode == Keys.Enter)
6894 if (!this.SplitContainer3.Panel2Collapsed)
6896 OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail);
6906 private void ScrollDownPostBrowser(bool forward)
6908 var doc = PostBrowser.Document;
6909 if (doc == null) return;
6911 var tags = doc.GetElementsByTagName("html");
6915 tags[0].ScrollTop += SettingDialog.FontDetail.Height;
6917 tags[0].ScrollTop -= SettingDialog.FontDetail.Height;
6921 private void PageDownPostBrowser(bool forward)
6923 var doc = PostBrowser.Document;
6924 if (doc == null) return;
6926 var tags = doc.GetElementsByTagName("html");
6930 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - SettingDialog.FontDetail.Height;
6932 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - SettingDialog.FontDetail.Height;
6936 private void GoNextTab(bool forward)
6938 int idx = ListTab.SelectedIndex;
6942 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6947 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6949 ListTab.SelectedIndex = idx;
6950 ListTabSelect(ListTab.TabPages[idx]);
6953 private void CopyStot()
6956 StringBuilder sb = new StringBuilder();
6957 bool IsProtected = false;
6959 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6960 foreach (int idx in _curList.SelectedIndices)
6962 PostClass post = _statuses[_curTab.Text, idx];
6968 if (post.IsDeleted) continue;
6971 if (post.RetweetedId != null)
6972 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6974 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6978 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6983 MessageBox.Show(Properties.Resources.CopyStotText1);
6987 clstr = sb.ToString();
6990 Clipboard.SetDataObject(clstr, false, 5, 100);
6992 catch (Exception ex)
6994 MessageBox.Show(ex.Message);
6999 private void CopyIdUri()
7002 StringBuilder sb = new StringBuilder();
7003 if (this._curTab == null) return;
7004 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7005 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7006 foreach (int idx in _curList.SelectedIndices)
7008 var post = _statuses[_curTab.Text, idx];
7009 sb.Append(MyCommon.GetStatusUrl(post));
7010 sb.Append(Environment.NewLine);
7014 clstr = sb.ToString();
7017 Clipboard.SetDataObject(clstr, false, 5, 100);
7019 catch (Exception ex)
7021 MessageBox.Show(ex.Message);
7026 private void GoFav(bool forward)
7028 if (_curList.VirtualListSize == 0) return;
7035 if (_curList.SelectedIndices.Count == 0)
7041 fIdx = _curList.SelectedIndices[0] + 1;
7042 if (fIdx > _curList.VirtualListSize - 1) return;
7044 toIdx = _curList.VirtualListSize;
7049 if (_curList.SelectedIndices.Count == 0)
7051 fIdx = _curList.VirtualListSize - 1;
7055 fIdx = _curList.SelectedIndices[0] - 1;
7056 if (fIdx < 0) return;
7062 for (int idx = fIdx; idx != toIdx; idx += stp)
7064 if (_statuses[_curTab.Text, idx].IsFav)
7066 SelectListItem(_curList, idx);
7067 _curList.EnsureVisible(idx);
7073 private void GoSamePostToAnotherTab(bool left)
7075 if (_curList.VirtualListSize == 0) return;
7081 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7082 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7084 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7089 if (ListTab.SelectedIndex == 0)
7095 fIdx = ListTab.SelectedIndex - 1;
7103 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7109 fIdx = ListTab.SelectedIndex + 1;
7111 toIdx = ListTab.TabCount;
7116 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7118 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7119 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7121 if (_statuses[ListTab.TabPages[tabidx].Text, idx].StatusId == targetId)
7123 ListTab.SelectedIndex = tabidx;
7124 ListTabSelect(ListTab.TabPages[tabidx]);
7125 SelectListItem(_curList, idx);
7126 _curList.EnsureVisible(idx);
7135 private void GoPost(bool forward)
7137 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7144 fIdx = _curList.SelectedIndices[0] + 1;
7145 if (fIdx > _curList.VirtualListSize - 1) return;
7146 toIdx = _curList.VirtualListSize;
7151 fIdx = _curList.SelectedIndices[0] - 1;
7152 if (fIdx < 0) return;
7158 if (_curPost.RetweetedId == null)
7160 name = _curPost.ScreenName;
7164 name = _curPost.RetweetedBy;
7166 for (int idx = fIdx; idx != toIdx; idx += stp)
7168 if (_statuses[_curTab.Text, idx].RetweetedId == null)
7170 if (_statuses[_curTab.Text, idx].ScreenName == name)
7172 SelectListItem(_curList, idx);
7173 _curList.EnsureVisible(idx);
7179 if (_statuses[_curTab.Text, idx].RetweetedBy == name)
7181 SelectListItem(_curList, idx);
7182 _curList.EnsureVisible(idx);
7189 private void GoRelPost(bool forward)
7191 if (_curList.SelectedIndices.Count == 0) return;
7198 fIdx = _curList.SelectedIndices[0] + 1;
7199 if (fIdx > _curList.VirtualListSize - 1) return;
7200 toIdx = _curList.VirtualListSize;
7205 fIdx = _curList.SelectedIndices[0] - 1;
7206 if (fIdx < 0) return;
7213 if (_curPost == null) return;
7214 _anchorPost = _curPost;
7219 if (_anchorPost == null) return;
7222 for (int idx = fIdx; idx != toIdx; idx += stp)
7224 PostClass post = _statuses[_curTab.Text, idx];
7225 if (post.ScreenName == _anchorPost.ScreenName ||
7226 post.RetweetedBy == _anchorPost.ScreenName ||
7227 post.ScreenName == _anchorPost.RetweetedBy ||
7228 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7229 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLower()) ||
7230 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLower()) ||
7231 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLower()) ||
7232 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLower()))
7234 SelectListItem(_curList, idx);
7235 _curList.EnsureVisible(idx);
7241 private void GoAnchor()
7243 if (_anchorPost == null) return;
7244 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7245 if (idx == -1) return;
7247 SelectListItem(_curList, idx);
7248 _curList.EnsureVisible(idx);
7251 private void GoTopEnd(bool GoTop)
7258 _item = _curList.GetItemAt(0, 25);
7266 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7268 idx = _curList.VirtualListSize - 1;
7272 SelectListItem(_curList, idx);
7275 private void GoMiddle()
7282 _item = _curList.GetItemAt(0, 0);
7292 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7295 idx2 = _curList.VirtualListSize - 1;
7301 idx3 = (idx1 + idx2) / 2;
7303 SelectListItem(_curList, idx3);
7306 private void GoLast()
7308 if (_curList.VirtualListSize == 0) return;
7310 if (_statuses.SortOrder == SortOrder.Ascending)
7312 SelectListItem(_curList, _curList.VirtualListSize - 1);
7313 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7317 SelectListItem(_curList, 0);
7318 _curList.EnsureVisible(0);
7322 private void MoveTop()
7324 if (_curList.SelectedIndices.Count == 0) return;
7325 int idx = _curList.SelectedIndices[0];
7326 if (_statuses.SortOrder == SortOrder.Ascending)
7328 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7332 _curList.EnsureVisible(0);
7334 _curList.EnsureVisible(idx);
7337 private void GoInReplyToPostTree()
7339 if (_curPost == null) return;
7341 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7343 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7345 PostClass post = null;
7346 string r = tw.GetStatusApi(false, _curPost.StatusId, ref post);
7347 if (string.IsNullOrEmpty(r) && post != null)
7349 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7350 _curPost.InReplyToUser = post.InReplyToUser;
7351 _curPost.IsReply = post.IsReply;
7352 this.PurgeListViewItemCache();
7353 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7357 this.StatusLabel.Text = r;
7361 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7363 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7365 replyChains = new Stack<ReplyChain>();
7367 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7370 string inReplyToTabName;
7371 long inReplyToId = _curPost.InReplyToStatusId.Value;
7372 string inReplyToUser = _curPost.InReplyToUser;
7373 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7375 var inReplyToPosts = from tab in _statuses.Tabs.Values
7376 orderby tab != curTabClass
7377 from post in tab.Posts.Values
7378 where post.StatusId == inReplyToId
7379 let index = tab.IndexOf(post.StatusId)
7381 select new {Tab = tab, Index = index};
7385 var inReplyPost = inReplyToPosts.First();
7386 inReplyToTabName = inReplyPost.Tab.TabName;
7387 inReplyToIndex = inReplyPost.Index;
7389 catch (InvalidOperationException)
7391 PostClass post = null;
7392 string r = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value, ref post);
7393 if (string.IsNullOrEmpty(r) && post != null)
7396 _statuses.AddPost(post);
7397 _statuses.DistributePosts();
7398 //_statuses.SubmitUpdate(null, null, null, false);
7399 this.RefreshTimeline(false);
7402 var inReplyPost = inReplyToPosts.First();
7403 inReplyToTabName = inReplyPost.Tab.TabName;
7404 inReplyToIndex = inReplyPost.Index;
7406 catch (InvalidOperationException)
7408 OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7414 this.StatusLabel.Text = r;
7415 OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7420 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7421 DetailsListView listView = (DetailsListView)tabPage.Tag;
7423 if (_curTab != tabPage)
7425 this.ListTab.SelectTab(tabPage);
7428 this.SelectListItem(listView, inReplyToIndex);
7429 listView.EnsureVisible(inReplyToIndex);
7432 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7434 if (_curPost == null) return;
7436 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7437 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7441 if (_curPost.InReplyToStatusId != null)
7443 var posts = from t in _statuses.Tabs
7444 from p in t.Value.Posts
7445 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7446 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7448 orderby isForward ? indexOf : indexOf * -1
7449 orderby t.Value != curTabClass
7450 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7453 var postList = posts.ToList();
7454 for (int i = postList.Count - 1; i >= 0; i--)
7457 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7459 postList.RemoveAt(index);
7462 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7463 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7464 if (post == null) post = postList.First();
7465 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7466 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7467 SelectListItem(listView, post.Index);
7468 listView.EnsureVisible(post.Index);
7470 catch (InvalidOperationException)
7478 if (replyChains == null || replyChains.Count < 1)
7480 var posts = from t in _statuses.Tabs
7481 from p in t.Value.Posts
7482 where p.Value.InReplyToStatusId == _curPost.StatusId
7483 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7486 orderby t.Value != curTabClass
7487 select new {Tab = t.Value, Index = indexOf};
7490 var post = posts.First();
7491 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7492 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7493 SelectListItem(listView, post.Index);
7494 listView.EnsureVisible(post.Index);
7496 catch (InvalidOperationException)
7503 ReplyChain chainHead = replyChains.Pop();
7504 if (chainHead.InReplyToId == _curPost.StatusId)
7506 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7515 ListTab.SelectTab(chainHead.OriginalTab);
7521 SelectListItem(_curList, idx);
7522 _curList.EnsureVisible(idx);
7528 this.GoBackInReplyToPostTree(parallel);
7534 private void GoBackSelectPostChain()
7536 if (this.selectPostChains.Count > 1)
7545 this.selectPostChains.Pop();
7546 var tabPostPair = this.selectPostChains.Peek();
7548 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7550 if (tabPostPair.Item2 != null)
7552 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7553 if (idx == -1) continue; //該当ポストが存在しないので無視
7556 tp = tabPostPair.Item1;
7558 this.selectPostChains.Pop();
7560 catch (InvalidOperationException)
7566 while (this.selectPostChains.Count > 1);
7571 //履歴が残り1つであればクリアしておく
7572 if (this.selectPostChains.Count == 1)
7573 this.selectPostChains.Clear();
7577 DetailsListView lst = (DetailsListView)tp.Tag;
7578 this.ListTab.SelectedTab = tp;
7581 SelectListItem(lst, idx);
7582 lst.EnsureVisible(idx);
7588 private void PushSelectPostChain()
7590 int count = this.selectPostChains.Count;
7593 var p = this.selectPostChains.Peek();
7594 if (p.Item1 == this._curTab)
7596 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7597 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7600 if (count >= 2500) TrimPostChain();
7601 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7604 private void TrimPostChain()
7606 if (this.selectPostChains.Count <= 2000) return;
7607 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7608 for (int i = 0; i < 2000; i++)
7610 p.Push(this.selectPostChains.Pop());
7612 this.selectPostChains.Clear();
7613 for (int i = 0; i < 2000; i++)
7615 this.selectPostChains.Push(p.Pop());
7619 private bool GoStatus(long statusId)
7621 if (statusId == 0) return false;
7622 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7624 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7626 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7627 ListTab.SelectedIndex = tabidx;
7628 ListTabSelect(ListTab.TabPages[tabidx]);
7629 SelectListItem(_curList, idx);
7630 _curList.EnsureVisible(idx);
7637 private bool GoDirectMessage(long statusId)
7639 if (statusId == 0) return false;
7640 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7642 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7644 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7645 ListTab.SelectedIndex = tabidx;
7646 ListTabSelect(ListTab.TabPages[tabidx]);
7647 SelectListItem(_curList, idx);
7648 _curList.EnsureVisible(idx);
7655 private void MyList_MouseClick(object sender, MouseEventArgs e)
7657 _anchorFlag = false;
7660 private void StatusText_Enter(object sender, EventArgs e)
7662 // フォーカスの戻り先を StatusText に設定
7663 this.Tag = StatusText;
7664 StatusText.BackColor = _clInputBackcolor;
7667 public Color InputBackColor
7669 get { return _clInputBackcolor; }
7670 set { _clInputBackcolor = value; }
7673 private void StatusText_Leave(object sender, EventArgs e)
7675 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7676 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7677 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7680 private void StatusText_KeyDown(object sender, KeyEventArgs e)
7682 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
7683 if (State == ModifierState.NotFlags) return;
7684 if (CommonKeyDown(e.KeyCode, FocusedControl.StatusText, State))
7687 e.SuppressKeyPress = true;
7690 this.StatusText_TextChanged(null, null);
7693 private void SaveConfigsAll(bool ifModified)
7697 SaveConfigsCommon();
7704 if (_modifySettingCommon) SaveConfigsCommon();
7705 if (_modifySettingLocal) SaveConfigsLocal();
7706 if (_modifySettingAtId) SaveConfigsAtId();
7710 private void SaveConfigsAtId()
7712 if (_ignoreConfigSave || !SettingDialog.UseAtIdSupplement && AtIdSupl == null) return;
7714 _modifySettingAtId = false;
7715 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7719 private void SaveConfigsCommon()
7721 if (_ignoreConfigSave) return;
7723 _modifySettingCommon = false;
7726 _cfgCommon.UserName = tw.Username;
7727 _cfgCommon.UserId = tw.UserId;
7728 _cfgCommon.Password = tw.Password;
7729 _cfgCommon.Token = tw.AccessToken;
7730 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7731 _cfgCommon.UserAccounts = SettingDialog.UserAccounts;
7732 _cfgCommon.UserstreamStartup = SettingDialog.UserstreamStartup;
7733 _cfgCommon.UserstreamPeriod = SettingDialog.UserstreamPeriodInt;
7734 _cfgCommon.TimelinePeriod = SettingDialog.TimelinePeriodInt;
7735 _cfgCommon.ReplyPeriod = SettingDialog.ReplyPeriodInt;
7736 _cfgCommon.DMPeriod = SettingDialog.DMPeriodInt;
7737 _cfgCommon.PubSearchPeriod = SettingDialog.PubSearchPeriodInt;
7738 _cfgCommon.ListsPeriod = SettingDialog.ListsPeriodInt;
7739 _cfgCommon.UserTimelinePeriod = SettingDialog.UserTimelinePeriodInt;
7740 _cfgCommon.Read = SettingDialog.Readed;
7741 _cfgCommon.IconSize = SettingDialog.IconSz;
7742 _cfgCommon.UnreadManage = SettingDialog.UnreadManage;
7743 _cfgCommon.PlaySound = SettingDialog.PlaySound;
7744 _cfgCommon.OneWayLove = SettingDialog.OneWayLove;
7746 _cfgCommon.NameBalloon = SettingDialog.NameBalloon;
7747 _cfgCommon.PostCtrlEnter = SettingDialog.PostCtrlEnter;
7748 _cfgCommon.PostShiftEnter = SettingDialog.PostShiftEnter;
7749 _cfgCommon.CountApi = SettingDialog.CountApi;
7750 _cfgCommon.CountApiReply = SettingDialog.CountApiReply;
7751 _cfgCommon.PostAndGet = SettingDialog.PostAndGet;
7752 _cfgCommon.DispUsername = SettingDialog.DispUsername;
7753 _cfgCommon.MinimizeToTray = SettingDialog.MinimizeToTray;
7754 _cfgCommon.CloseToExit = SettingDialog.CloseToExit;
7755 _cfgCommon.DispLatestPost = SettingDialog.DispLatestPost;
7756 _cfgCommon.SortOrderLock = SettingDialog.SortOrderLock;
7757 _cfgCommon.ViewTabBottom = SettingDialog.ViewTabBottom;
7758 _cfgCommon.TinyUrlResolve = SettingDialog.TinyUrlResolve;
7759 _cfgCommon.StartupVersion = SettingDialog.StartupVersion;
7760 _cfgCommon.StartupFollowers = SettingDialog.StartupFollowers;
7761 _cfgCommon.RestrictFavCheck = SettingDialog.RestrictFavCheck;
7762 _cfgCommon.AlwaysTop = SettingDialog.AlwaysTop;
7763 _cfgCommon.UrlConvertAuto = SettingDialog.UrlConvertAuto;
7764 _cfgCommon.UseUnreadStyle = SettingDialog.UseUnreadStyle;
7765 _cfgCommon.DateTimeFormat = SettingDialog.DateTimeFormat;
7766 _cfgCommon.DefaultTimeOut = SettingDialog.DefaultTimeOut;
7767 _cfgCommon.RetweetNoConfirm = SettingDialog.RetweetNoConfirm;
7768 _cfgCommon.LimitBalloon = SettingDialog.LimitBalloon;
7769 _cfgCommon.EventNotifyEnabled = SettingDialog.EventNotifyEnabled;
7770 _cfgCommon.EventNotifyFlag = SettingDialog.EventNotifyFlag;
7771 _cfgCommon.IsMyEventNotifyFlag = SettingDialog.IsMyEventNotifyFlag;
7772 _cfgCommon.ForceEventNotify = SettingDialog.ForceEventNotify;
7773 _cfgCommon.FavEventUnread = SettingDialog.FavEventUnread;
7774 _cfgCommon.TranslateLanguage = SettingDialog.TranslateLanguage;
7775 _cfgCommon.EventSoundFile = SettingDialog.EventSoundFile;
7776 _cfgCommon.AutoShortUrlFirst = SettingDialog.AutoShortUrlFirst;
7777 _cfgCommon.TabIconDisp = SettingDialog.TabIconDisp;
7778 _cfgCommon.ReplyIconState = SettingDialog.ReplyIconState;
7779 _cfgCommon.ReadOwnPost = SettingDialog.ReadOwnPost;
7780 _cfgCommon.GetFav = SettingDialog.GetFav;
7781 _cfgCommon.IsMonospace = SettingDialog.IsMonospace;
7782 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7783 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7785 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7787 _cfgCommon.ReadOldPosts = SettingDialog.ReadOldPosts;
7788 _cfgCommon.BilyUser = SettingDialog.BitlyUser;
7789 _cfgCommon.BitlyPwd = SettingDialog.BitlyPwd;
7790 _cfgCommon.ShowGrid = SettingDialog.ShowGrid;
7791 _cfgCommon.UseAtIdSupplement = SettingDialog.UseAtIdSupplement;
7792 _cfgCommon.UseHashSupplement = SettingDialog.UseHashSupplement;
7793 _cfgCommon.PreviewEnable = SettingDialog.PreviewEnable;
7794 _cfgCommon.Language = SettingDialog.Language;
7796 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7797 switch (_statuses.SortMode)
7799 case IdComparerClass.ComparerMode.Nickname: //ニックネーム
7800 _cfgCommon.SortColumn = 1;
7802 case IdComparerClass.ComparerMode.Data: //本文
7803 _cfgCommon.SortColumn = 2;
7805 case IdComparerClass.ComparerMode.Id: //時刻=発言Id
7806 _cfgCommon.SortColumn = 3;
7808 case IdComparerClass.ComparerMode.Name: //名前
7809 _cfgCommon.SortColumn = 4;
7811 case IdComparerClass.ComparerMode.Source: //Source
7812 _cfgCommon.SortColumn = 7;
7816 _cfgCommon.Nicoms = SettingDialog.Nicoms;
7817 _cfgCommon.HashTags = HashMgr.HashHistories;
7818 if (HashMgr.IsPermanent)
7820 _cfgCommon.HashSelected = HashMgr.UseHash;
7824 _cfgCommon.HashSelected = "";
7826 _cfgCommon.HashIsHead = HashMgr.IsHead;
7827 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7828 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7829 _cfgCommon.TwitterUrl = SettingDialog.TwitterApiUrl;
7830 _cfgCommon.HotkeyEnabled = SettingDialog.HotkeyEnabled;
7831 _cfgCommon.HotkeyModifier = SettingDialog.HotkeyMod;
7832 _cfgCommon.HotkeyKey = SettingDialog.HotkeyKey;
7833 _cfgCommon.HotkeyValue = SettingDialog.HotkeyValue;
7834 _cfgCommon.BlinkNewMentions = SettingDialog.BlinkNewMentions;
7835 if (ToolStripFocusLockMenuItem != null &&
7836 ToolStripFocusLockMenuItem.IsDisposed == false)
7838 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7840 _cfgCommon.UseAdditionalCount = SettingDialog.UseAdditionalCount;
7841 _cfgCommon.MoreCountApi = SettingDialog.MoreCountApi;
7842 _cfgCommon.FirstCountApi = SettingDialog.FirstCountApi;
7843 _cfgCommon.SearchCountApi = SettingDialog.SearchCountApi;
7844 _cfgCommon.FavoritesCountApi = SettingDialog.FavoritesCountApi;
7845 _cfgCommon.UserTimelineCountApi = SettingDialog.UserTimelineCountApi;
7846 _cfgCommon.TrackWord = tw.TrackWord;
7847 _cfgCommon.AllAtReply = tw.AllAtReply;
7848 _cfgCommon.OpenUserTimeline = SettingDialog.OpenUserTimeline;
7849 _cfgCommon.ListCountApi = SettingDialog.ListCountApi;
7850 _cfgCommon.UseImageService = ImageServiceCombo.SelectedIndex;
7851 _cfgCommon.UseImageServiceName = this.ImageService;
7852 _cfgCommon.ListDoubleClickAction = SettingDialog.ListDoubleClickAction;
7853 _cfgCommon.UserAppointUrl = SettingDialog.UserAppointUrl;
7854 _cfgCommon.HideDuplicatedRetweets = SettingDialog.HideDuplicatedRetweets;
7855 _cfgCommon.EnableImgAzyobuziNet = SettingDialog.EnableImgAzyobuziNet;
7856 _cfgCommon.ImgAzyobuziNetDisabledInDM = SettingDialog.ImgAzyobuziNetDisabledInDM;
7857 _cfgCommon.MapThumbnailProvider = SettingDialog.MapThumbnailProvider;
7858 _cfgCommon.MapThumbnailHeight = SettingDialog.MapThumbnailHeight;
7859 _cfgCommon.MapThumbnailWidth = SettingDialog.MapThumbnailWidth;
7860 _cfgCommon.MapThumbnailZoom = SettingDialog.MapThumbnailZoom;
7861 _cfgCommon.IsListsIncludeRts = SettingDialog.IsListStatusesIncludeRts;
7862 _cfgCommon.TabMouseLock = SettingDialog.TabMouseLock;
7863 _cfgCommon.IsRemoveSameEvent = SettingDialog.IsRemoveSameEvent;
7864 _cfgCommon.IsUseNotifyGrowl = SettingDialog.IsNotifyUseGrowl;
7870 private void SaveConfigsLocal()
7872 if (_ignoreConfigSave) return;
7875 _modifySettingLocal = false;
7876 _cfgLocal.FormSize = _mySize;
7877 _cfgLocal.FormLocation = _myLoc;
7878 _cfgLocal.SplitterDistance = _mySpDis;
7879 _cfgLocal.PreviewDistance = _mySpDis3;
7880 _cfgLocal.StatusMultiline = StatusText.Multiline;
7881 _cfgLocal.StatusTextHeight = _mySpDis2;
7882 _cfgLocal.StatusText = SettingDialog.Status;
7884 _cfgLocal.FontUnread = _fntUnread;
7885 _cfgLocal.ColorUnread = _clUnread;
7886 _cfgLocal.FontRead = _fntReaded;
7887 _cfgLocal.ColorRead = _clReaded;
7888 _cfgLocal.FontDetail = _fntDetail;
7889 _cfgLocal.ColorDetail = _clDetail;
7890 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7891 _cfgLocal.ColorDetailLink = _clDetailLink;
7892 _cfgLocal.ColorFav = _clFav;
7893 _cfgLocal.ColorOWL = _clOWL;
7894 _cfgLocal.ColorRetweet = _clRetweet;
7895 _cfgLocal.ColorSelf = _clSelf;
7896 _cfgLocal.ColorAtSelf = _clAtSelf;
7897 _cfgLocal.ColorTarget = _clTarget;
7898 _cfgLocal.ColorAtTarget = _clAtTarget;
7899 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7900 _cfgLocal.ColorAtTo = _clAtTo;
7901 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7902 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7903 _cfgLocal.ColorInputFont = _clInputFont;
7904 _cfgLocal.FontInputFont = _fntInputFont;
7906 _cfgLocal.BrowserPath = SettingDialog.BrowserPath;
7907 _cfgLocal.UseRecommendStatus = SettingDialog.UseRecommendStatus;
7908 _cfgLocal.ProxyType = SettingDialog.SelectedProxyType;
7909 _cfgLocal.ProxyAddress = SettingDialog.ProxyAddress;
7910 _cfgLocal.ProxyPort = SettingDialog.ProxyPort;
7911 _cfgLocal.ProxyUser = SettingDialog.ProxyUser;
7912 _cfgLocal.ProxyPassword = SettingDialog.ProxyPassword;
7913 if (_ignoreConfigSave) return;
7918 private void SaveConfigsTabs()
7920 SettingTabs tabSetting = new SettingTabs();
7921 for (int i = 0; i < ListTab.TabPages.Count; i++)
7923 if (_statuses.Tabs[ListTab.TabPages[i].Text].TabType != MyCommon.TabUsageType.Related) tabSetting.Tabs.Add(_statuses.Tabs[ListTab.TabPages[i].Text]);
7928 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7931 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7932 if (ret != DialogResult.OK)
7935 var match = Twitter.StatusUrlRegex.Match(inputText);
7938 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7939 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7943 var statusId = long.Parse(match.Groups["StatusId"].Value);
7945 var post = this._statuses[statusId];
7950 post = await Task.Run(() =>
7952 PostClass newPost = null;
7954 var err = this.tw.GetStatusApi(false, statusId, ref newPost);
7955 if (!string.IsNullOrEmpty(err))
7956 throw new WebApiException(err);
7961 catch (WebApiException ex)
7963 var message = ex.InnerException.Message;
7964 MessageBox.Show(this, string.Format(Properties.Resources.OpenURL_LoadFailed, message),
7965 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7972 this.OpenRelatedTab(post);
7974 catch (TabException ex)
7976 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7980 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7982 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7983 Properties.Resources.SaveLogMenuItem_ClickText2,
7984 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7985 if (rslt == DialogResult.Cancel) return;
7987 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7988 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7989 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7990 SaveFileDialog1.FilterIndex = 0;
7991 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7992 SaveFileDialog1.RestoreDirectory = true;
7994 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7996 if (!SaveFileDialog1.ValidateNames) return;
7997 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7999 if (rslt == DialogResult.Yes)
8002 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8004 PostClass post = _statuses[_curTab.Text, idx];
8005 string protect = "";
8006 if (post.IsProtect) protect = "Protect";
8007 sw.WriteLine(post.Nickname + "\t" +
8008 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8009 post.CreatedAt.ToString() + "\t" +
8010 post.ScreenName + "\t" +
8011 post.StatusId.ToString() + "\t" +
8012 post.ImageUrl + "\t" +
8013 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8019 foreach (int idx in _curList.SelectedIndices)
8021 PostClass post = _statuses[_curTab.Text, idx];
8022 string protect = "";
8023 if (post.IsProtect) protect = "Protect";
8024 sw.WriteLine(post.Nickname + "\t" +
8025 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8026 post.CreatedAt.ToString() + "\t" +
8027 post.ScreenName + "\t" +
8028 post.StatusId.ToString() + "\t" +
8029 post.ImageUrl + "\t" +
8030 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8036 this.TopMost = SettingDialog.AlwaysTop;
8039 private void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8041 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
8042 if (State == ModifierState.NotFlags) return;
8043 bool KeyRes = CommonKeyDown(e.KeyCode, FocusedControl.PostBrowser, State);
8046 e.IsInputKey = true;
8049 public bool TabRename(ref string tabName)
8052 string newTabText = null;
8053 using (InputTabName inputName = new InputTabName())
8055 inputName.TabName = tabName;
8056 inputName.ShowDialog();
8057 if (inputName.DialogResult == DialogResult.Cancel) return false;
8058 newTabText = inputName.TabName;
8060 this.TopMost = SettingDialog.AlwaysTop;
8061 if (!string.IsNullOrEmpty(newTabText))
8064 for (int i = 0; i < ListTab.TabCount; i++)
8066 if (ListTab.TabPages[i].Text == newTabText)
8068 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8069 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8073 //タブ名のリスト作り直し(デフォルトタブ以外は再作成)
8074 for (int i = 0; i < ListTab.TabCount; i++)
8076 if (ListTab.TabPages[i].Text == tabName)
8078 ListTab.TabPages[i].Text = newTabText;
8081 _statuses.RenameTab(tabName, newTabText);
8083 for (int i = 0; i < ListTab.TabCount; i++)
8085 if (_statuses.IsDistributableTab(ListTab.TabPages[i].Text))
8087 if (ListTab.TabPages[i].Text == tabName)
8089 ListTab.TabPages[i].Text = newTabText;
8093 SaveConfigsCommon();
8095 _rclickTabName = newTabText;
8096 tabName = newTabText;
8105 private void ListTab_MouseClick(object sender, MouseEventArgs e)
8107 if (e.Button == MouseButtons.Middle)
8109 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8111 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8113 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8114 this.SaveConfigsTabs();
8121 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8123 string tn = ListTab.SelectedTab.Text;
8127 private void ListTab_MouseDown(object sender, MouseEventArgs e)
8129 if (SettingDialog.TabMouseLock) return;
8130 Point cpos = new Point(e.X, e.Y);
8131 if (e.Button == MouseButtons.Left)
8133 for (int i = 0; i < ListTab.TabPages.Count; i++)
8135 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8138 _tabMouseDownPoint = e.Location;
8149 private void ListTab_DragEnter(object sender, DragEventArgs e)
8151 if (e.Data.GetDataPresent(typeof(TabPage)))
8152 e.Effect = DragDropEffects.Move;
8154 e.Effect = DragDropEffects.None;
8157 private void ListTab_DragDrop(object sender, DragEventArgs e)
8159 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8164 Point cpos = new Point(e.X, e.Y);
8165 Point spos = ListTab.PointToClient(cpos);
8167 for (i = 0; i < ListTab.TabPages.Count; i++)
8169 Rectangle rect = ListTab.GetTabRect(i);
8170 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8171 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8173 tn = ListTab.TabPages[i].Text;
8174 if (spos.X <= (rect.Left + rect.Right) / 2)
8183 //タブのないところにドロップ->最後尾へ移動
8184 if (string.IsNullOrEmpty(tn))
8186 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8188 i = ListTab.TabPages.Count - 1;
8191 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8192 if (tp.Text == tn) return;
8194 ReOrderTab(tp.Text, tn, bef);
8197 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8200 for (baseIndex = 0; baseIndex < ListTab.TabPages.Count; baseIndex++)
8202 if (ListTab.TabPages[baseIndex].Text == baseTabText) break;
8205 using (ControlTransaction.Layout(this.ListTab))
8208 for (int j = 0; j < ListTab.TabPages.Count; j++)
8210 if (ListTab.TabPages[j].Text == targetTabText)
8212 mTp = ListTab.TabPages[j];
8213 ListTab.TabPages.Remove(mTp);
8214 if (j < baseIndex) baseIndex -= 1;
8218 if (isBeforeBaseTab)
8219 ListTab.TabPages.Insert(baseIndex, mTp);
8221 ListTab.TabPages.Insert(baseIndex + 1, mTp);
8227 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8229 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8230 //isReply:true=@,false=DM
8231 if (!StatusText.Enabled) return;
8232 if (_curList == null) return;
8233 if (_curTab == null) return;
8234 if (!this.ExistCurrentPost) return;
8236 // 複数あてリプライはReplyではなく通常ポスト
8237 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8238 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8239 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8241 if (_curList.SelectedIndices.Count > 0)
8244 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8247 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8250 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8251 StatusText.SelectionStart = StatusText.Text.Length;
8253 _reply_to_id = null;
8254 _reply_to_name = null;
8257 if (string.IsNullOrEmpty(StatusText.Text))
8261 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8262 StatusText.Text = "@" + _curPost.ScreenName + " ";
8263 if (_curPost.RetweetedId != null)
8265 _reply_to_id = _curPost.RetweetedId.Value;
8269 _reply_to_id = _curPost.StatusId;
8271 _reply_to_name = _curPost.ScreenName;
8279 //1件選んでEnter or DoubleClick
8280 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8282 if (_reply_to_id != null && _reply_to_name == _curPost.ScreenName)
8285 if (_curPost.RetweetedId != null)
8287 _reply_to_id = _curPost.RetweetedId.Value;
8291 _reply_to_id = _curPost.StatusId;
8293 _reply_to_name = _curPost.ScreenName;
8297 if (!StatusText.Text.StartsWith("@"))
8300 if (StatusText.Text.StartsWith(". "))
8303 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8304 _reply_to_id = null;
8305 _reply_to_name = null;
8310 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8311 if (_curPost.RetweetedId != null)
8313 _reply_to_id = _curPost.RetweetedId.Value;
8317 _reply_to_id = _curPost.StatusId;
8319 _reply_to_name = _curPost.ScreenName;
8326 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8327 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8328 _reply_to_id = null;
8329 _reply_to_name = null;
8334 //1件選んでCtrl-Rの場合(返信先操作せず)
8335 int sidx = StatusText.SelectionStart;
8336 string id = "@" + _curPost.ScreenName + " ";
8339 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8344 StatusText.Text = StatusText.Text.Insert(sidx, id);
8346 //if (StatusText.Text.StartsWith("@"))
8349 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8350 // sidx += 5 + _curPost.ScreenName.Length;
8355 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8356 // sidx += 3 + _curPost.ScreenName.Length;
8358 StatusText.SelectionStart = sidx;
8361 //_reply_to_name = null;
8369 if (!isAuto && !isReply) return;
8371 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8375 //Enter or DoubleClick
8377 string sTxt = StatusText.Text;
8378 if (!sTxt.StartsWith(". "))
8381 _reply_to_id = null;
8382 _reply_to_name = null;
8384 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8386 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[cnt]];
8387 if (!sTxt.Contains("@" + post.ScreenName + " "))
8389 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8390 //sTxt = "@" + post.ScreenName + " " + sTxt;
8393 StatusText.Text = sTxt;
8398 if (_curList.SelectedIndices.Count > 1)
8403 int sidx = StatusText.SelectionStart;
8404 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8406 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[cnt]];
8407 if (!ids.Contains("@" + post.ScreenName + " ") &&
8408 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8410 ids += "@" + post.ScreenName + " ";
8414 foreach (string nm in post.ReplyToList)
8416 if (!ids.Contains("@" + nm + " ") &&
8417 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8419 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8421 ids += "@" + m.Result("${id}") + " ";
8423 ids += "@" + nm + " ";
8428 if (ids.Length == 0) return;
8429 if (!StatusText.Text.StartsWith(". "))
8431 StatusText.Text = ". " + StatusText.Text;
8433 _reply_to_id = null;
8434 _reply_to_name = null;
8438 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8443 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8445 //if (StatusText.Text.StartsWith("@"))
8447 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8448 // sidx += 2 + ids.Length;
8452 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8453 // sidx += 1 + ids.Length;
8455 StatusText.SelectionStart = sidx;
8461 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8464 int sidx = StatusText.SelectionStart;
8465 PostClass post = _curPost;
8466 if (!ids.Contains("@" + post.ScreenName + " ") &&
8467 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8469 ids += "@" + post.ScreenName + " ";
8471 foreach (string nm in post.ReplyToList)
8473 if (!ids.Contains("@" + nm + " ") &&
8474 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8476 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8478 ids += "@" + m.Result("${id}") + " ";
8480 ids += "@" + nm + " ";
8483 if (!string.IsNullOrEmpty(post.RetweetedBy))
8485 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8486 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8488 ids += "@" + post.RetweetedBy + " ";
8491 if (ids.Length == 0) return;
8492 if (string.IsNullOrEmpty(StatusText.Text))
8495 StatusText.Text = ids;
8496 StatusText.SelectionStart = ids.Length;
8498 if (post.RetweetedId != null)
8500 _reply_to_id = post.RetweetedId.Value;
8504 _reply_to_id = post.StatusId;
8506 _reply_to_name = post.ScreenName;
8512 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8517 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8519 StatusText.SelectionStart = sidx;
8525 StatusText.SelectionStart = StatusText.Text.Length;
8530 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8535 private static int iconCnt = 0;
8536 private static int blinkCnt = 0;
8537 private static bool blink = false;
8538 private static bool idle = false;
8540 private void RefreshTasktrayIcon(bool forceRefresh)
8542 if (_colorize) Colorize();
8543 if (!TimerRefreshIcon.Enabled) return;
8544 //Static usCheckCnt As int = 0
8546 //Static iconDlListTopItem As ListViewItem = null
8548 if (forceRefresh) idle = false;
8550 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8551 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8553 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8555 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8561 //if (usCheckCnt > 300) //1min
8564 // if (!this.IsReceivedUserStream)
8566 // TraceOut("ReconnectUserStream");
8567 // tw.ReconnectUserStream();
8572 foreach (BackgroundWorker bw in this._bw)
8574 if (bw != null && bw.IsBusy)
8589 SaveConfigsAll(true);
8594 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8596 _myStatusError = false;
8600 TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8601 if (SettingDialog.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8603 if (blinkCnt > 0) return;
8605 if (blink || SettingDialog.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8607 NotifyIcon1.Icon = ReplyIcon;
8611 NotifyIcon1.Icon = ReplyIconBlink;
8619 //優先度:エラー→オフライン→アイドル
8623 NotifyIcon1.Icon = NIconAtRed;
8626 if (_myStatusOnline)
8628 NotifyIcon1.Icon = NIconAt;
8632 NotifyIcon1.Icon = NIconAtSmoke;
8636 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
8639 this.RefreshTasktrayIcon(false);
8642 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8644 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8645 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8647 if (ListTab != null && ListTab.SelectedTab != null)
8648 _rclickTabName = ListTab.SelectedTab.Text;
8653 if (_statuses == null) return;
8654 if (_statuses.Tabs == null) return;
8656 TabClass tb = _statuses.Tabs[_rclickTabName];
8657 if (tb == null) return;
8659 NotifyDispMenuItem.Checked = tb.Notify;
8660 this.NotifyTbMenuItem.Checked = tb.Notify;
8662 soundfileListup = true;
8663 SoundFileComboBox.Items.Clear();
8664 this.SoundFileTbComboBox.Items.Clear();
8665 SoundFileComboBox.Items.Add("");
8666 this.SoundFileTbComboBox.Items.Add("");
8667 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8668 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8670 oDir = oDir.GetDirectories("Sounds")[0];
8672 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8674 SoundFileComboBox.Items.Add(oFile.Name);
8675 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8677 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8678 if (idx == -1) idx = 0;
8679 SoundFileComboBox.SelectedIndex = idx;
8680 this.SoundFileTbComboBox.SelectedIndex = idx;
8681 soundfileListup = false;
8682 UreadManageMenuItem.Checked = tb.UnreadManage;
8683 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8685 TabMenuControl(_rclickTabName);
8688 private void TabMenuControl(string tabName)
8690 this.FilterEditMenuItem.Enabled = true;
8691 this.EditRuleTbMenuItem.Enabled = true;
8693 if (_statuses.IsDefaultTab(tabName))
8695 this.ProtectTabMenuItem.Enabled = false;
8696 this.ProtectTbMenuItem.Enabled = false;
8700 this.ProtectTabMenuItem.Enabled = true;
8701 this.ProtectTbMenuItem.Enabled = true;
8704 if (_statuses.IsDefaultTab(tabName) || _statuses.Tabs[tabName].Protected)
8706 this.ProtectTabMenuItem.Checked = true;
8707 this.ProtectTbMenuItem.Checked = true;
8708 this.DeleteTabMenuItem.Enabled = false;
8709 this.DeleteTbMenuItem.Enabled = false;
8713 this.ProtectTabMenuItem.Checked = false;
8714 this.ProtectTbMenuItem.Checked = false;
8715 this.DeleteTabMenuItem.Enabled = true;
8716 this.DeleteTbMenuItem.Enabled = true;
8720 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8722 var checkState = ((ToolStripMenuItem)sender).Checked;
8725 this.ProtectTbMenuItem.Checked = checkState;
8726 this.ProtectTabMenuItem.Checked = checkState;
8729 this.DeleteTabMenuItem.Enabled = !checkState;
8730 this.DeleteTbMenuItem.Enabled = !checkState;
8732 if (string.IsNullOrEmpty(_rclickTabName)) return;
8733 _statuses.Tabs[_rclickTabName].Protected = checkState;
8738 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8740 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8741 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8743 if (string.IsNullOrEmpty(_rclickTabName)) return;
8744 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8749 public void ChangeTabUnreadManage(string tabName, bool isManage)
8752 for (idx = 0; idx < ListTab.TabCount; idx++)
8754 if (ListTab.TabPages[idx].Text == tabName) break;
8757 _statuses.SetTabUnreadManage(tabName, isManage);
8758 if (SettingDialog.TabIconDisp)
8760 if (_statuses.Tabs[tabName].UnreadCount > 0)
8761 ListTab.TabPages[idx].ImageIndex = 0;
8763 ListTab.TabPages[idx].ImageIndex = -1;
8766 if (_curTab.Text == tabName)
8768 this.PurgeListViewItemCache();
8772 SetMainWindowTitle();
8773 SetStatusLabelUrl();
8774 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
8777 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8779 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8780 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8782 if (string.IsNullOrEmpty(_rclickTabName)) return;
8784 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8789 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8791 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8793 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8798 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8800 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8802 RemoveSpecifiedTab(_rclickTabName, true);
8806 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8808 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8809 fltDialog.SetCurrent(_rclickTabName);
8810 fltDialog.ShowDialog(this);
8811 this.TopMost = SettingDialog.AlwaysTop;
8813 this.ApplyPostFilters();
8817 private void AddTabMenuItem_Click(object sender, EventArgs e)
8819 string tabName = null;
8820 MyCommon.TabUsageType tabUsage;
8821 using (InputTabName inputName = new InputTabName())
8823 inputName.TabName = _statuses.GetUniqueTabName();
8824 inputName.IsShowUsage = true;
8825 inputName.ShowDialog();
8826 if (inputName.DialogResult == DialogResult.Cancel) return;
8827 tabName = inputName.TabName;
8828 tabUsage = inputName.Usage;
8830 this.TopMost = SettingDialog.AlwaysTop;
8831 if (!string.IsNullOrEmpty(tabName))
8834 ListElement list = null;
8835 if (tabUsage == MyCommon.TabUsageType.Lists)
8837 using (ListAvailable listAvail = new ListAvailable())
8839 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8840 if (listAvail.SelectedList == null) return;
8841 list = listAvail.SelectedList;
8844 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8846 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8847 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8853 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8855 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8856 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
8857 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8859 if (tabUsage == MyCommon.TabUsageType.Lists)
8861 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8862 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
8863 GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, tabName);
8869 private void TabMenuItem_Click(object sender, EventArgs e)
8872 foreach (int idx in _curList.SelectedIndices)
8876 if (!SelectTab(out tabName)) return;
8878 fltDialog.SetCurrent(tabName);
8879 if (_statuses[_curTab.Text, idx].RetweetedId == null)
8881 fltDialog.AddNewFilter(_statuses[_curTab.Text, idx].ScreenName, _statuses[_curTab.Text, idx].TextFromApi);
8885 fltDialog.AddNewFilter(_statuses[_curTab.Text, idx].RetweetedBy, _statuses[_curTab.Text, idx].TextFromApi);
8887 fltDialog.ShowDialog(this);
8888 this.TopMost = SettingDialog.AlwaysTop;
8891 this.ApplyPostFilters();
8893 if (this.ListTab.SelectedTab != null &&
8894 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8896 _curPost = _statuses[this.ListTab.SelectedTab.Text, ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8900 protected override bool ProcessDialogKey(Keys keyData)
8902 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8903 if ((keyData & Keys.KeyCode) == Keys.Enter)
8905 if (StatusText.Focused)
8907 bool _NewLine = false;
8910 if (SettingDialog.PostCtrlEnter) //Ctrl+Enter投稿時
8912 if (StatusText.Multiline)
8914 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8916 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8920 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8924 else if (SettingDialog.PostShiftEnter) //SHift+Enter投稿時
8926 if (StatusText.Multiline)
8928 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8930 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8934 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8940 if (StatusText.Multiline)
8942 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8944 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8945 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8949 if (((keyData & Keys.Shift) == Keys.Shift) ||
8950 (((keyData & Keys.Control) != Keys.Control) &&
8951 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8957 int pos1 = StatusText.SelectionStart;
8958 if (StatusText.SelectionLength > 0)
8960 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8962 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8963 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8968 PostButton_Click(null, null);
8972 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8973 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8974 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8976 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8981 return base.ProcessDialogKey(keyData);
8984 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8986 MakeReplyOrDirectStatus(false, true, true);
8989 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8994 if (_curList.SelectedIndices.Count == 0) return;
8997 if (!SelectTab(out tabName)) return;
9001 MoveOrCopy(ref mv, ref mk);
9003 List<string> ids = new List<string>();
9004 foreach (int idx in _curList.SelectedIndices)
9006 PostClass post = _statuses[_curTab.Text, idx];
9007 if (!ids.Contains(post.ScreenName))
9009 PostFilterRule fc = new PostFilterRule();
9010 ids.Add(post.ScreenName);
9011 if (post.RetweetedId == null)
9013 fc.FilterName = post.ScreenName;
9017 fc.FilterName = post.RetweetedBy;
9019 fc.UseNameField = true;
9020 fc.MoveMatches = mv;
9021 fc.MarkMatches = mk;
9022 fc.UseRegex = false;
9023 fc.FilterByUrl = false;
9024 _statuses.Tabs[tabName].AddFilter(fc);
9029 List<string> atids = new List<string>();
9030 foreach (string id in ids)
9032 atids.Add("@" + id);
9034 int cnt = AtIdSupl.ItemCount;
9035 AtIdSupl.AddRangeItem(atids.ToArray());
9036 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
9039 this.ApplyPostFilters();
9043 private bool SelectTab(out string tabName)
9050 using (var dialog = new TabsDialog(_statuses))
9052 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9054 var selectedTab = dialog.SelectedTab;
9055 tabName = selectedTab == null ? null : selectedTab.TabName;
9058 ListTab.SelectedTab.Focus();
9060 if (tabName == null)
9062 using (InputTabName inputName = new InputTabName())
9064 inputName.TabName = _statuses.GetUniqueTabName();
9065 inputName.ShowDialog();
9066 if (inputName.DialogResult == DialogResult.Cancel) return false;
9067 tabName = inputName.TabName;
9069 this.TopMost = SettingDialog.AlwaysTop;
9070 if (!string.IsNullOrEmpty(tabName))
9072 if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9074 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9075 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9093 private void MoveOrCopy(ref bool move, ref bool mark)
9097 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9098 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9106 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9107 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9113 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9118 private void CopyURLMenuItem_Click(object sender, EventArgs e)
9123 private void SelectAllMenuItem_Click(object sender, EventArgs e)
9125 if (StatusText.Focused)
9128 StatusText.SelectAll();
9132 // ListView上でのCtrl+A
9133 for (int i = 0; i < _curList.VirtualListSize; i++)
9135 _curList.SelectedIndices.Add(i);
9140 private void MoveMiddle()
9146 if (_curList.SelectedIndices.Count == 0) return;
9148 int idx = _curList.SelectedIndices[0];
9150 _item = _curList.GetItemAt(0, 25);
9156 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9158 idx2 = _curList.VirtualListSize - 1;
9162 idx -= Math.Abs(idx1 - idx2) / 2;
9163 if (idx < 0) idx = 0;
9165 _curList.EnsureVisible(_curList.VirtualListSize - 1);
9166 _curList.EnsureVisible(idx);
9169 private void OpenURLMenuItem_Click(object sender, EventArgs e)
9171 if (PostBrowser.Document.Links.Count > 0)
9173 UrlDialog.ClearUrl();
9175 string openUrlStr = "";
9177 if (PostBrowser.Document.Links.Count == 1)
9182 urlStr = MyCommon.IDNEncode(PostBrowser.Document.Links[0].GetAttribute("href"));
9184 catch (ArgumentException)
9193 if (string.IsNullOrEmpty(urlStr)) return;
9194 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9198 foreach (HtmlElement linkElm in PostBrowser.Document.Links)
9201 string linkText = "";
9205 urlStr = linkElm.GetAttribute("title");
9206 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9207 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9208 linkText = linkElm.InnerText;
9209 if (!linkText.StartsWith("http") && !linkText.StartsWith("#") && !linkText.Contains("."))
9211 linkText = "@" + linkText;
9214 catch (ArgumentException)
9223 if (string.IsNullOrEmpty(urlStr)) continue;
9224 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9228 if (UrlDialog.ShowDialog() == DialogResult.OK)
9230 openUrlStr = UrlDialog.SelectedUrl;
9237 this.TopMost = SettingDialog.AlwaysTop;
9239 if (string.IsNullOrEmpty(openUrlStr)) return;
9241 if (openUrlStr.StartsWith("http://twitter.com/search?q=") ||
9242 openUrlStr.StartsWith("https://twitter.com/search?q="))
9245 string urlStr = Uri.UnescapeDataString(openUrlStr);
9246 string hash = urlStr.Substring(urlStr.IndexOf("#"));
9247 HashSupl.AddItem(hash);
9248 HashMgr.AddHashToHistory(hash.Trim(), false);
9249 AddNewTabForSearch(hash);
9254 Match m = Regex.Match(openUrlStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9255 if (SettingDialog.OpenUserTimeline && m.Success && IsTwitterId(m.Result("${ScreenName}")))
9256 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
9258 OpenUriAsync(openUrlStr);
9264 private void ClearTabMenuItem_Click(object sender, EventArgs e)
9266 if (string.IsNullOrEmpty(_rclickTabName)) return;
9267 ClearTab(_rclickTabName, true);
9270 private void ClearTab(string tabName, bool showWarning)
9274 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9275 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9281 _statuses.ClearTabIds(tabName);
9282 if (ListTab.SelectedTab.Text == tabName)
9285 _anchorFlag = false;
9286 this.PurgeListViewItemCache();
9290 foreach (TabPage tb in ListTab.TabPages)
9292 if (tb.Text == tabName)
9295 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9299 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
9301 SetMainWindowTitle();
9302 SetStatusLabelUrl();
9305 private static long followers = 0;
9307 private void SetMainWindowTitle()
9310 StringBuilder ttl = new StringBuilder(256);
9313 if (SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.None &&
9314 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9315 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9316 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9318 foreach (var tab in _statuses.Tabs.Values)
9320 ur += tab.UnreadCount;
9325 if (SettingDialog.DispUsername) ttl.Append(tw.Username).Append(" - ");
9326 ttl.Append(Application.ProductName);
9328 switch (SettingDialog.DispLatestPost)
9330 case MyCommon.DispTitleEnum.Ver:
9331 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9333 case MyCommon.DispTitleEnum.Post:
9334 if (_history != null && _history.Count > 1)
9335 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9337 case MyCommon.DispTitleEnum.UnreadRepCount:
9338 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9340 case MyCommon.DispTitleEnum.UnreadAllCount:
9341 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9343 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9344 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9346 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9347 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9349 case MyCommon.DispTitleEnum.OwnStatus:
9350 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9351 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9357 this.Text = ttl.ToString();
9359 catch (AccessViolationException)
9361 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9365 private string GetStatusLabelText()
9368 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9369 if (_statuses == null) return "";
9370 TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9371 TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9372 if (tbRep == null || tbDm == null) return "";
9373 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9378 StringBuilder slbl = new StringBuilder(256);
9381 foreach (var tab in _statuses.Tabs.Values)
9383 ur += tab.UnreadCount;
9385 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9387 tur = tab.UnreadCount;
9398 UnreadAtCounter = urat;
9400 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9401 if (SettingDialog.TimelinePeriodInt == 0)
9403 slbl.Append(Properties.Resources.SetStatusLabelText2);
9407 slbl.Append(SettingDialog.TimelinePeriodInt.ToString() + Properties.Resources.SetStatusLabelText3);
9409 return slbl.ToString();
9412 private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9416 if (this.InvokeRequired && !this.IsDisposed)
9418 this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9422 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9423 if (endpointName == "/statuses/home_timeline" || endpointName == null)
9425 this._apiGauge.ApiLimit = MyCommon.TwitterApiInfo.AccessLimit["/statuses/home_timeline"];
9429 catch (ObjectDisposedException)
9433 catch (InvalidOperationException)
9439 private void SetStatusLabelUrl()
9441 StatusLabelUrl.Text = GetStatusLabelText();
9444 public void SetStatusLabel(string text)
9446 StatusLabel.Text = text;
9449 private static StringBuilder ur = new StringBuilder(64);
9451 private void SetNotifyIconText()
9453 // タスクトレイアイコンのツールチップテキスト書き換え
9455 ur.Remove(0, ur.Length);
9456 if (SettingDialog.DispUsername)
9458 ur.Append(tw.Username);
9461 ur.Append(Application.ProductName);
9463 ur.Append("(Debug Build)");
9465 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9468 ur.Append(UnreadCounter);
9470 ur.Append(UnreadAtCounter);
9473 NotifyIcon1.Text = ur.ToString();
9476 internal void CheckReplyTo(string StatusText)
9480 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9482 foreach (Match hm in m)
9484 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9486 hstr += "#" + hm.Result("$3") + " ";
9487 HashSupl.AddItem("#" + hm.Result("$3"));
9490 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9492 hstr += HashMgr.UseHash;
9494 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9496 // 本当にリプライ先指定すべきかどうかの判定
9497 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9499 if (SettingDialog.UseAtIdSupplement)
9501 int bCnt = AtIdSupl.ItemCount;
9502 foreach (Match mid in m)
9504 AtIdSupl.AddItem(mid.Result("${id}"));
9506 if (bCnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
9509 // リプライ先ステータスIDの指定がない場合は指定しない
9510 if (_reply_to_id == null) return;
9512 // リプライ先ユーザー名がない場合も指定しない
9513 if (string.IsNullOrEmpty(_reply_to_name))
9515 _reply_to_id = null;
9520 // 次の条件を満たす場合に in_reply_to_status_id 指定
9521 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9522 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9523 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9527 if (StatusText.StartsWith("@"))
9529 if (StatusText.StartsWith("@" + _reply_to_name)) return;
9533 foreach (Match mid in m)
9535 if (StatusText.Contains("QT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + _reply_to_name) return;
9540 _reply_to_id = null;
9541 _reply_to_name = null;
9545 private void TweenMain_Resize(object sender, EventArgs e)
9547 if (!_initialLayout && SettingDialog.MinimizeToTray && WindowState == FormWindowState.Minimized)
9549 this.Visible = false;
9551 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9553 this.ClientSize = _cfgLocal.FormSize;
9554 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9555 this.DesktopLocation = _cfgLocal.FormLocation;
9556 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9557 if (_cfgLocal.SplitterDistance > this.SplitContainer1.Panel1MinSize &&
9558 _cfgLocal.SplitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9560 this.SplitContainer1.SplitterDistance = _cfgLocal.SplitterDistance; //Splitterの位置設定
9563 StatusText.Multiline = _cfgLocal.StatusMultiline;
9564 if (StatusText.Multiline)
9566 int dis = SplitContainer2.Height - _cfgLocal.StatusTextHeight - SplitContainer2.SplitterWidth;
9567 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9569 SplitContainer2.SplitterDistance = SplitContainer2.Height - _cfgLocal.StatusTextHeight - SplitContainer2.SplitterWidth;
9571 StatusText.Height = _cfgLocal.StatusTextHeight;
9575 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9577 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9580 if (_cfgLocal.PreviewDistance > this.SplitContainer3.Panel1MinSize && _cfgLocal.PreviewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9582 this.SplitContainer3.SplitterDistance = _cfgLocal.PreviewDistance;
9584 _initialLayout = false;
9586 if (this.WindowState != FormWindowState.Minimized)
9588 _formWindowState = this.WindowState;
9592 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9594 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9595 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9596 if (PlaySoundMenuItem.Checked)
9598 SettingDialog.PlaySound = true;
9602 SettingDialog.PlaySound = false;
9604 _modifySettingCommon = true;
9607 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9609 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
9611 _mySpDis = SplitContainer1.SplitterDistance;
9612 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9613 _modifySettingLocal = true;
9617 private void doRepliedStatusOpen()
9619 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9621 if (MyCommon.IsKeyDown(Keys.Shift))
9623 OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9626 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9628 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9629 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9633 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9635 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9636 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9637 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9640 OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9645 private void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9647 doRepliedStatusOpen();
9651 /// UserPicture.Image に設定されている画像を破棄します。
9653 private void ClearUserPicture()
9655 if (this.UserPicture.Image != null)
9657 var oldImage = this.UserPicture.Image;
9658 this.UserPicture.Image = null;
9663 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9665 //発言詳細のアイコン右クリック時のメニュー制御
9666 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9668 string name = _curPost.ImageUrl;
9669 if (name != null && name.Length > 0)
9671 int idx = name.LastIndexOf('/');
9674 name = Path.GetFileName(name.Substring(idx));
9675 if (name.Contains("_normal.") || name.EndsWith("_normal"))
9677 name = name.Replace("_normal", "");
9678 this.IconNameToolStripMenuItem.Text = name;
9679 this.IconNameToolStripMenuItem.Enabled = true;
9683 this.IconNameToolStripMenuItem.Enabled = false;
9684 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9689 this.IconNameToolStripMenuItem.Enabled = false;
9690 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9693 this.ReloadIconToolStripMenuItem.Enabled = true;
9695 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9697 this.SaveIconPictureToolStripMenuItem.Enabled = true;
9701 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9706 this.IconNameToolStripMenuItem.Enabled = false;
9707 this.ReloadIconToolStripMenuItem.Enabled = false;
9708 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9709 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9714 this.IconNameToolStripMenuItem.Enabled = false;
9715 this.ReloadIconToolStripMenuItem.Enabled = false;
9716 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9717 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9719 if (NameLabel.Tag != null)
9721 string id = (string)NameLabel.Tag;
9722 if (id == tw.Username)
9724 FollowToolStripMenuItem.Enabled = false;
9725 UnFollowToolStripMenuItem.Enabled = false;
9726 ShowFriendShipToolStripMenuItem.Enabled = false;
9727 ShowUserStatusToolStripMenuItem.Enabled = true;
9728 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9729 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9730 ListManageUserContextToolStripMenuItem3.Enabled = true;
9734 FollowToolStripMenuItem.Enabled = true;
9735 UnFollowToolStripMenuItem.Enabled = true;
9736 ShowFriendShipToolStripMenuItem.Enabled = true;
9737 ShowUserStatusToolStripMenuItem.Enabled = true;
9738 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9739 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9740 ListManageUserContextToolStripMenuItem3.Enabled = true;
9745 FollowToolStripMenuItem.Enabled = false;
9746 UnFollowToolStripMenuItem.Enabled = false;
9747 ShowFriendShipToolStripMenuItem.Enabled = false;
9748 ShowUserStatusToolStripMenuItem.Enabled = false;
9749 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9750 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9751 ListManageUserContextToolStripMenuItem3.Enabled = false;
9755 private void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9757 if (_curPost == null) return;
9758 string name = _curPost.ImageUrl;
9759 OpenUriAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9762 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9764 if (this._curPost == null) return;
9766 var imageUrl = this._curPost.ImageUrl;
9769 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true);
9771 this.ClearUserPicture();
9772 this.UserPicture.Image = image.Clone();
9776 this.UserPicture.ShowErrorImage();
9781 catch (HttpRequestException) { }
9782 catch (InvalidImageException) { }
9783 catch (TaskCanceledException) { }
9787 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9789 if (_curPost == null) return;
9790 string name = _curPost.ImageUrl;
9791 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
9793 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
9795 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9801 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9803 if (_curPost == null) return;
9804 string name = _curPost.ImageUrl;
9806 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
9808 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9812 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
9814 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
9816 using (Graphics g = Graphics.FromImage(bmp2))
9818 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
9819 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
9821 bmp2.Save(this.SaveFileDialog1.FileName);
9827 //処理中にキャッシュアウトする可能性あり
9832 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9834 this.StatusText.Multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9835 MultiLineMenuItem.Checked = this.StatusText.Multiline;
9836 _modifySettingLocal = true;
9839 private void StatusText_MultilineChanged(object sender, EventArgs e)
9841 if (this.StatusText.Multiline)
9842 this.StatusText.ScrollBars = ScrollBars.Vertical;
9844 this.StatusText.ScrollBars = ScrollBars.None;
9846 _modifySettingLocal = true;
9849 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9852 StatusText.Multiline = MultiLineMenuItem.Checked;
9853 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
9854 if (MultiLineMenuItem.Checked)
9856 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9857 SplitContainer2.SplitterDistance = 0;
9859 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9863 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9865 _modifySettingLocal = true;
9868 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9870 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9871 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9873 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9874 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9875 //Appendix A. Collected ABNF for URI
9876 //http://www.ietf.org/rfc/rfc3986.txt
9880 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9882 if (StatusText.SelectionLength > 0)
9884 string tmp = StatusText.SelectedText;
9885 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9886 if (tmp.StartsWith("http"))
9888 // 文字列が選択されている場合はその文字列について処理
9890 //nico.ms使用、nicovideoにマッチしたら変換
9891 if (SettingDialog.Nicoms && Regex.IsMatch(tmp, nico))
9893 result = nicoms.Shorten(tmp);
9895 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9897 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9900 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9901 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9902 result = resultUri.ToString();
9904 catch (WebApiException e)
9906 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9909 catch (UriFormatException e)
9911 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9920 if (!string.IsNullOrEmpty(result))
9922 urlUndo undotmp = new urlUndo();
9924 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
9925 StatusText.SelectedText = result;
9928 undotmp.Before = tmp;
9929 undotmp.After = result;
9931 if (urlUndoBuffer == null)
9933 urlUndoBuffer = new List<urlUndo>();
9934 UrlUndoToolStripMenuItem.Enabled = true;
9937 urlUndoBuffer.Add(undotmp);
9943 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9944 @"(?<url>(?<protocol>https?://)" +
9945 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9946 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9947 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9948 // 正規表現にマッチしたURL文字列をtinyurl化
9949 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9951 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9952 string tmp = mt.Result("${url}");
9953 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9954 urlUndo undotmp = new urlUndo();
9957 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9959 //nico.ms使用、nicovideoにマッチしたら変換
9960 if (SettingDialog.Nicoms && Regex.IsMatch(tmp, nico))
9962 result = nicoms.Shorten(tmp);
9964 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9966 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9969 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9970 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9971 result = resultUri.ToString();
9973 catch (WebApiException e)
9975 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9978 catch (UriFormatException e)
9980 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9989 if (!string.IsNullOrEmpty(result))
9991 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9992 StatusText.SelectedText = result;
9994 undotmp.Before = mt.Result("${url}");
9995 undotmp.After = result;
9997 if (urlUndoBuffer == null)
9999 urlUndoBuffer = new List<urlUndo>();
10000 UrlUndoToolStripMenuItem.Enabled = true;
10003 urlUndoBuffer.Add(undotmp);
10011 private void doUrlUndo()
10013 if (urlUndoBuffer != null)
10015 string tmp = StatusText.Text;
10016 foreach (urlUndo data in urlUndoBuffer)
10018 tmp = tmp.Replace(data.After, data.Before);
10020 StatusText.Text = tmp;
10021 urlUndoBuffer = null;
10022 UrlUndoToolStripMenuItem.Enabled = false;
10023 StatusText.SelectionStart = 0;
10024 StatusText.SelectionLength = 0;
10028 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10030 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10033 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10035 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10038 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10040 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10043 private async void UxnuMenuItem_Click(object sender, EventArgs e)
10045 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10048 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10050 if (!await UrlConvertAsync(SettingDialog.AutoShortUrlFirst))
10052 MyCommon.UrlConverter svc = SettingDialog.AutoShortUrlFirst;
10053 Random rnd = new Random();
10054 // 前回使用した短縮URLサービス以外を選択する
10057 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10059 while (svc == SettingDialog.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10060 await UrlConvertAsync(svc);
10064 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10069 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10071 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10072 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10073 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10074 _modifySettingCommon = true;
10077 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10079 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10080 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10081 _cfgCommon.ListLock = ListLockMenuItem.Checked;
10082 _modifySettingCommon = true;
10085 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10087 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10088 MenuStrip1.Tag = new Object();
10089 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10092 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10094 if (this.Tag != null) // 設定された戻り先へ遷移
10096 if (this.Tag == this.ListTab.SelectedTab)
10097 ((Control)this.ListTab.SelectedTab.Tag).Select();
10099 ((Control)this.Tag).Select();
10101 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10103 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10105 this.Tag = ListTab.SelectedTab.Tag;
10106 ((Control)this.Tag).Select();
10109 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10110 MenuStrip1.Tag = null;
10113 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10115 DetailsListView lst = (DetailsListView)sender;
10116 if (_cfgLocal == null) return;
10120 _cfgLocal.Width1 = lst.Columns[0].Width;
10121 _cfgLocal.Width3 = lst.Columns[1].Width;
10125 int[] darr = new int[lst.Columns.Count];
10126 for (int i = 0; i < lst.Columns.Count; i++)
10128 darr[lst.Columns[i].DisplayIndex] = i;
10130 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10132 for (int i = 0; i < lst.Columns.Count; i++)
10137 _cfgLocal.DisplayIndex1 = i;
10140 _cfgLocal.DisplayIndex2 = i;
10143 _cfgLocal.DisplayIndex3 = i;
10146 _cfgLocal.DisplayIndex4 = i;
10149 _cfgLocal.DisplayIndex5 = i;
10152 _cfgLocal.DisplayIndex6 = i;
10155 _cfgLocal.DisplayIndex7 = i;
10158 _cfgLocal.DisplayIndex8 = i;
10162 _cfgLocal.Width1 = lst.Columns[0].Width;
10163 _cfgLocal.Width2 = lst.Columns[1].Width;
10164 _cfgLocal.Width3 = lst.Columns[2].Width;
10165 _cfgLocal.Width4 = lst.Columns[3].Width;
10166 _cfgLocal.Width5 = lst.Columns[4].Width;
10167 _cfgLocal.Width6 = lst.Columns[5].Width;
10168 _cfgLocal.Width7 = lst.Columns[6].Width;
10169 _cfgLocal.Width8 = lst.Columns[7].Width;
10171 _modifySettingLocal = true;
10172 _isColumnChanged = true;
10175 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10177 DetailsListView lst = (DetailsListView)sender;
10178 if (_cfgLocal == null) return;
10181 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10183 _cfgLocal.Width1 = lst.Columns[0].Width;
10184 _modifySettingLocal = true;
10185 _isColumnChanged = true;
10187 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10189 _cfgLocal.Width3 = lst.Columns[1].Width;
10190 _modifySettingLocal = true;
10191 _isColumnChanged = true;
10196 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10198 _cfgLocal.Width1 = lst.Columns[0].Width;
10199 _modifySettingLocal = true;
10200 _isColumnChanged = true;
10202 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10204 _cfgLocal.Width2 = lst.Columns[1].Width;
10205 _modifySettingLocal = true;
10206 _isColumnChanged = true;
10208 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10210 _cfgLocal.Width3 = lst.Columns[2].Width;
10211 _modifySettingLocal = true;
10212 _isColumnChanged = true;
10214 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10216 _cfgLocal.Width4 = lst.Columns[3].Width;
10217 _modifySettingLocal = true;
10218 _isColumnChanged = true;
10220 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10222 _cfgLocal.Width5 = lst.Columns[4].Width;
10223 _modifySettingLocal = true;
10224 _isColumnChanged = true;
10226 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10228 _cfgLocal.Width6 = lst.Columns[5].Width;
10229 _modifySettingLocal = true;
10230 _isColumnChanged = true;
10232 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10234 _cfgLocal.Width7 = lst.Columns[6].Width;
10235 _modifySettingLocal = true;
10236 _isColumnChanged = true;
10238 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10240 _cfgLocal.Width8 = lst.Columns[7].Width;
10241 _modifySettingLocal = true;
10242 _isColumnChanged = true;
10245 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10248 // SaveConfigsLocal();
10252 public string WebBrowser_GetSelectionText(ref WebBrowser ComponentInstance)
10254 //発言詳細で「選択文字列をコピー」を行う
10255 //WebBrowserコンポーネントのインスタンスを渡す
10256 Type typ = ComponentInstance.ActiveXInstance.GetType();
10257 object _SelObj = typ.InvokeMember("selection", BindingFlags.GetProperty, null, ComponentInstance.Document.DomDocument, null);
10258 object _objRange = _SelObj.GetType().InvokeMember("createRange", BindingFlags.InvokeMethod, null, _SelObj, null);
10259 return (string)_objRange.GetType().InvokeMember("text", BindingFlags.GetProperty, null, _objRange, null);
10262 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10265 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10268 Clipboard.SetDataObject(_selText, false, 5, 100);
10270 catch (Exception ex)
10272 MessageBox.Show(ex.Message);
10276 private void doSearchToolStrip(string url)
10278 //発言詳細で「選択文字列で検索」(選択文字列取得)
10279 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10281 if (_selText != null)
10283 if (url == Properties.Resources.SearchItem4Url)
10286 AddNewTabForSearch(_selText);
10290 string tmp = string.Format(url, Uri.EscapeUriString(_selText));
10295 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10298 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10301 private void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10303 doSearchToolStrip(Properties.Resources.SearchItem1Url);
10306 private void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10308 doSearchToolStrip(Properties.Resources.SearchItem2Url);
10311 private void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10313 doSearchToolStrip(Properties.Resources.SearchItem4Url);
10316 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10320 MatchCollection mc = Regex.Matches(this.PostBrowser.DocumentText, @"<a[^>]*href=""(?<url>" + this._postBrowserStatusText.Replace(".", @"\.") + @")""[^>]*title=""(?<title>https?://[^""]+)""", RegexOptions.IgnoreCase);
10321 foreach (Match m in mc)
10323 if (m.Groups["url"].Value == this._postBrowserStatusText)
10325 Clipboard.SetDataObject(m.Groups["title"].Value, false, 5, 100);
10331 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10333 //Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10335 catch (Exception ex)
10337 MessageBox.Show(ex.Message);
10341 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10343 // URLコピーの項目の表示/非表示
10344 if (PostBrowser.StatusText.StartsWith("http"))
10346 this._postBrowserStatusText = PostBrowser.StatusText;
10347 string name = GetUserId();
10348 UrlCopyContextMenuItem.Enabled = true;
10351 FollowContextMenuItem.Enabled = true;
10352 RemoveContextMenuItem.Enabled = true;
10353 FriendshipContextMenuItem.Enabled = true;
10354 ShowUserStatusContextMenuItem.Enabled = true;
10355 SearchPostsDetailToolStripMenuItem.Enabled = true;
10356 IdFilterAddMenuItem.Enabled = true;
10357 ListManageUserContextToolStripMenuItem.Enabled = true;
10358 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10362 FollowContextMenuItem.Enabled = false;
10363 RemoveContextMenuItem.Enabled = false;
10364 FriendshipContextMenuItem.Enabled = false;
10365 ShowUserStatusContextMenuItem.Enabled = false;
10366 SearchPostsDetailToolStripMenuItem.Enabled = false;
10367 IdFilterAddMenuItem.Enabled = false;
10368 ListManageUserContextToolStripMenuItem.Enabled = false;
10369 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10372 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10373 UseHashtagMenuItem.Enabled = true;
10375 UseHashtagMenuItem.Enabled = false;
10379 this._postBrowserStatusText = "";
10380 UrlCopyContextMenuItem.Enabled = false;
10381 FollowContextMenuItem.Enabled = false;
10382 RemoveContextMenuItem.Enabled = false;
10383 FriendshipContextMenuItem.Enabled = false;
10384 ShowUserStatusContextMenuItem.Enabled = false;
10385 SearchPostsDetailToolStripMenuItem.Enabled = false;
10386 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10387 UseHashtagMenuItem.Enabled = false;
10388 IdFilterAddMenuItem.Enabled = false;
10389 ListManageUserContextToolStripMenuItem.Enabled = false;
10391 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10392 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10393 if (_selText == null)
10395 SelectionSearchContextMenuItem.Enabled = false;
10396 SelectionCopyContextMenuItem.Enabled = false;
10397 SelectionTranslationToolStripMenuItem.Enabled = false;
10401 SelectionSearchContextMenuItem.Enabled = true;
10402 SelectionCopyContextMenuItem.Enabled = true;
10403 SelectionTranslationToolStripMenuItem.Enabled = true;
10405 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10406 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10407 bool fAllFlag = false;
10408 foreach (Match mu in ma)
10410 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
10416 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10418 if (_curPost == null)
10419 TranslationToolStripMenuItem.Enabled = false;
10421 TranslationToolStripMenuItem.Enabled = true;
10426 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10428 //発言詳細の選択文字列で現在のタブを検索
10429 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10431 if (_selText != null)
10433 var searchOptions = new SearchWordDialog.SearchOptions(
10434 SearchWordDialog.SearchType.Timeline,
10437 caseSensitive: false,
10440 this.SearchDialog.ResultOptions = searchOptions;
10443 searchOptions.Query,
10444 searchOptions.CaseSensitive,
10445 searchOptions.UseRegex,
10446 SEARCHTYPE.NextSearch);
10450 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10452 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10453 _modifySettingLocal = true;
10456 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10458 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10460 SelectMedia_DragDrop(e);
10462 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10464 var url = GetUrlFromDataObject(e.Data);
10467 if (url.Item2 == null)
10468 appendText = url.Item1;
10470 appendText = url.Item2 + " " + url.Item1;
10472 if (this.StatusText.TextLength == 0)
10473 this.StatusText.Text = appendText;
10475 this.StatusText.Text += " " + appendText;
10477 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10479 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10480 if (data != null) StatusText.Text += data;
10485 /// IDataObject から URL とタイトルの対を取得します
10488 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10490 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10491 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10492 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10494 if (data.GetDataPresent("text/x-moz-url"))
10496 // Firefox, Google Chrome で利用可能
10497 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10499 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10501 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10502 if (lines.Length < 2)
10503 throw new ArgumentException("不正な text/x-moz-url フォーマットです", "data");
10505 return new Tuple<string, string>(lines[0], lines[1]);
10508 else if (data.GetDataPresent("IESiteModeToUrl"))
10510 // Internet Exproler 用
10511 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10513 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10515 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10516 if (lines.Length < 2)
10517 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", "data");
10519 return new Tuple<string, string>(lines[0], lines[1]);
10522 else if (data.GetDataPresent("UniformResourceLocatorW"))
10526 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10528 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10529 return new Tuple<string, string>(url, null);
10533 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10536 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10538 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10540 SelectMedia_DragEnter(e);
10544 private void TweenMain_DragOver(object sender, DragEventArgs e)
10546 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10548 SelectMedia_DragOver(e);
10550 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10552 e.Effect = DragDropEffects.Copy;
10554 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10556 e.Effect = DragDropEffects.Copy;
10560 e.Effect = DragDropEffects.None;
10564 public bool IsNetworkAvailable()
10567 nw = MyCommon.IsNetworkAvailable();
10568 _myStatusOnline = nw;
10572 public Task OpenUriAsync(string UriString)
10574 return Task.Run(() =>
10576 string myPath = UriString;
10580 var configBrowserPath = SettingDialog.BrowserPath;
10581 if (!string.IsNullOrEmpty(configBrowserPath))
10583 if (configBrowserPath.StartsWith("\"") && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2) > -1)
10585 int sep = configBrowserPath.IndexOf("\"", 2);
10586 string browserPath = configBrowserPath.Substring(1, sep - 1);
10588 if (sep < configBrowserPath.Length - 1)
10590 arg = configBrowserPath.Substring(sep + 1);
10592 myPath = arg + " " + myPath;
10593 System.Diagnostics.Process.Start(browserPath, myPath);
10597 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10602 System.Diagnostics.Process.Start(myPath);
10607 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10612 private void ListTabSelect(TabPage _tab)
10616 this.PurgeListViewItemCache();
10619 _curList = (DetailsListView)_tab.Tag;
10620 if (_curList.SelectedIndices.Count > 0)
10622 _curItemIndex = _curList.SelectedIndices[0];
10623 _curPost = GetCurTabPost(_curItemIndex);
10627 _curItemIndex = -1;
10631 _anchorPost = null;
10632 _anchorFlag = false;
10636 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10640 for (int i = 0; i < _curList.Columns.Count; i++)
10642 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10647 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10649 ListTabSelect(e.TabPage);
10652 private void SelectListItem(DetailsListView LView, int Index)
10655 Rectangle bnd = new Rectangle();
10657 var item = LView.FocusedItem;
10666 LView.SelectedIndices.Clear();
10668 while (LView.SelectedIndices.Count > 0);
10669 item = LView.Items[Index];
10670 item.Selected = true;
10671 item.Focused = true;
10673 if (flg) LView.Invalidate(bnd);
10676 private void SelectListItem(DetailsListView LView , int[] Index, int[] FocusedIndex)
10679 Rectangle bnd = new Rectangle();
10681 var item = LView.FocusedItem;
10689 if (Index != null && !(Index.Length == 1 && Index[0] == -1))
10693 LView.SelectedIndices.Clear();
10695 while (LView.SelectedIndices.Count > 0);
10696 foreach (int idx in Index)
10698 if (idx > -1 && LView.VirtualListSize > idx)
10700 LView.SelectedIndices.Add(idx);
10701 if (fIdx == -1) fIdx = idx;
10705 if (FocusedIndex[1] > -1 && LView.VirtualListSize > FocusedIndex[1])
10707 LView.SelectionMark = FocusedIndex[1];
10709 if (FocusedIndex[0] > -1 && LView.VirtualListSize > FocusedIndex[0])
10711 LView.Items[FocusedIndex[0]].Focused = true;
10713 else if (fIdx > -1)
10715 LView.Items[fIdx].Focused = true;
10718 if (flg) LView.Invalidate(bnd);
10721 private void RunAsync(GetWorkerArg args)
10723 BackgroundWorker bw = null;
10724 if (args.type != MyCommon.WORKERTYPE.Follower)
10726 for (int i = 0; i < _bw.Length; i++)
10728 if (_bw[i] != null && !_bw[i].IsBusy)
10736 for (int i = 0; i < _bw.Length; i++)
10738 if (_bw[i] == null)
10740 _bw[i] = new BackgroundWorker();
10742 bw.WorkerReportsProgress = true;
10743 bw.WorkerSupportsCancellation = true;
10744 bw.DoWork += GetTimelineWorker_DoWork;
10745 bw.ProgressChanged += GetTimelineWorker_ProgressChanged;
10746 bw.RunWorkerCompleted += GetTimelineWorker_RunWorkerCompleted;
10754 if (_bwFollower == null)
10756 _bwFollower = new BackgroundWorker();
10758 bw.WorkerReportsProgress = true;
10759 bw.WorkerSupportsCancellation = true;
10760 bw.DoWork += GetTimelineWorker_DoWork;
10761 bw.ProgressChanged += GetTimelineWorker_ProgressChanged;
10762 bw.RunWorkerCompleted += GetTimelineWorker_RunWorkerCompleted;
10766 if (_bwFollower.IsBusy == false)
10770 if (bw == null) return;
10772 bw.RunWorkerAsync(args);
10775 private void StartUserStream()
10777 tw.NewPostFromStream += tw_NewPostFromStream;
10778 tw.UserStreamStarted += tw_UserStreamStarted;
10779 tw.UserStreamStopped += tw_UserStreamStopped;
10780 tw.PostDeleted += tw_PostDeleted;
10781 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
10783 MenuItemUserStream.Text = "&UserStream ■";
10784 MenuItemUserStream.Enabled = true;
10785 StopToolStripMenuItem.Text = "&Start";
10786 StopToolStripMenuItem.Enabled = true;
10787 if (SettingDialog.UserstreamStartup) tw.StartUserStream();
10790 private async void TweenMain_Shown(object sender, EventArgs e)
10794 PostBrowser.Url = new Uri("about:blank");
10795 PostBrowser.DocumentText = ""; //発言詳細部初期化
10801 NotifyIcon1.Visible = true;
10803 if (this.IsNetworkAvailable())
10805 this.RefreshMuteUserIdsAsync();
10806 GetTimeline(MyCommon.WORKERTYPE.BlockIds, 0, 0, "");
10807 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, 0, "");
10808 if (SettingDialog.StartupFollowers)
10810 GetTimeline(MyCommon.WORKERTYPE.Follower, 0, 0, "");
10812 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
10814 _waitTimeline = true;
10815 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 1, "");
10817 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 1, "");
10819 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 1, "");
10820 if (SettingDialog.GetFav)
10823 GetTimeline(MyCommon.WORKERTYPE.Favorites, 1, 1, "");
10825 _waitPubSearch = true;
10826 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, ""); //tabname="":全タブ
10827 _waitUserTimeline = true;
10828 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, ""); //tabname="":全タブ
10830 GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, ""); //tabname="":全タブ
10833 while (this.IsInitialRead())
10835 await Task.Delay(5000);
10838 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10840 if (MyCommon._endingFlag)
10844 if (MyCommon._endingFlag) return;
10846 if (ApplicationSettings.VersionInfoUrl != null)
10848 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10849 if (SettingDialog.StartupVersion)
10850 await this.CheckNewVersion(true);
10854 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10855 this.VerUpMenuItem.Enabled = false;
10856 this.VerUpMenuItem.Available = false;
10857 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10861 if (!tw.GetFollowersSuccess && SettingDialog.StartupFollowers)
10862 GetTimeline(MyCommon.WORKERTYPE.Follower, 0, 0, "");
10865 if (!tw.GetNoRetweetSuccess)
10866 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, 0, "");
10869 if (SettingDialog.TwitterConfiguration.PhotoSizeLimit == 0)
10870 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
10872 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10873 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10875 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10876 SettingStripMenuItem_Click(null, null);
10883 TimerTimeline.Enabled = true;
10886 private bool IsInitialRead()
10888 return _waitTimeline || _waitReply || _waitDm || _waitFav || _waitPubSearch || _waitUserTimeline || _waitLists;
10891 private void doGetFollowersMenu()
10893 GetTimeline(MyCommon.WORKERTYPE.Follower, 1, 0, "");
10894 DispSelectedPost(true);
10897 private void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10899 doGetFollowersMenu();
10902 private void doReTweetUnofficial()
10905 if (this.ExistCurrentPost)
10907 if (_curPost.IsDm ||
10908 !StatusText.Enabled) return;
10910 if (_curPost.IsProtect)
10912 MessageBox.Show("Protected.");
10915 string rtdata = _curPost.Text;
10916 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10918 this._reply_to_id = null;
10919 this._reply_to_name = null;
10921 StatusText.Text = "RT @" + _curPost.ScreenName + ": " + rtdata;
10923 StatusText.SelectionStart = 0;
10924 StatusText.Focus();
10928 private void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10930 doReTweetUnofficial();
10933 private void doReTweetOfficial(bool isConfirm)
10936 if (this.ExistCurrentPost)
10938 if (_curPost.IsProtect)
10940 MessageBox.Show("Protected.");
10941 _DoFavRetweetFlags = false;
10944 if (_curList.SelectedIndices.Count > 15)
10946 MessageBox.Show(Properties.Resources.RetweetLimitText);
10947 _DoFavRetweetFlags = false;
10950 else if (_curList.SelectedIndices.Count > 1)
10952 string QuestionText = Properties.Resources.RetweetQuestion2;
10953 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10954 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10956 case DialogResult.Cancel:
10957 case DialogResult.No:
10958 _DoFavRetweetFlags = false;
10964 if (_curPost.IsDm || _curPost.IsMe)
10966 _DoFavRetweetFlags = false;
10969 if (!SettingDialog.RetweetNoConfirm)
10971 string Questiontext = Properties.Resources.RetweetQuestion1;
10972 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10973 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10975 _DoFavRetweetFlags = false;
10980 GetWorkerArg args = new GetWorkerArg();
10981 args.ids = new List<long>();
10982 args.sIds = new List<long>();
10983 args.tName = _curTab.Text;
10984 args.type = MyCommon.WORKERTYPE.Retweet;
10985 foreach (int idx in _curList.SelectedIndices)
10987 PostClass post = GetCurTabPost(idx);
10988 if (!post.IsMe && !post.IsProtect && !post.IsDm) args.ids.Add(post.StatusId);
10994 private void ReTweetOriginalStripMenuItem_Click(object sender, EventArgs e)
10996 doReTweetOfficial(true);
10999 private void FavoritesRetweetOriginal()
11001 if (!this.ExistCurrentPost) return;
11002 _DoFavRetweetFlags = true;
11003 doReTweetOfficial(true);
11004 if (_DoFavRetweetFlags)
11006 _DoFavRetweetFlags = false;
11007 FavoriteChange(true, false);
11011 private void FavoritesRetweetUnofficial()
11013 if (this.ExistCurrentPost && !_curPost.IsDm)
11015 _DoFavRetweetFlags = true;
11016 FavoriteChange(true);
11017 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11019 _DoFavRetweetFlags = false;
11020 doReTweetUnofficial();
11026 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11028 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11029 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11030 /// <returns>復元されたツイート本文</returns>
11031 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11033 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11036 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11038 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11040 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11044 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11046 statusHtml = statusHtml.Replace("<br>", " ");
11048 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11049 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
11050 statusHtml = statusHtml.Replace(" ", " ");
11052 return WebUtility.HtmlDecode(statusHtml);
11055 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11057 if (_curPost != null)
11058 DispSelectedPost(true);
11061 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11063 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11064 DebugModeToolStripMenuItem.Visible = true;
11066 DebugModeToolStripMenuItem.Visible = false;
11069 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11071 SettingDialog.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11074 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11076 ToolStripMenuItemUrlAutoShorten.Checked = SettingDialog.UrlConvertAuto;
11079 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11081 if (TraceOutToolStripMenuItem.Checked)
11082 MyCommon.TraceFlag = true;
11084 MyCommon.TraceFlag = false;
11087 private void TweenMain_Deactivate(object sender, EventArgs e)
11089 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11090 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11093 private void TabRenameMenuItem_Click(object sender, EventArgs e)
11095 if (string.IsNullOrEmpty(_rclickTabName)) return;
11096 TabRename(ref _rclickTabName);
11099 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11101 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11104 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11106 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11110 private void GetApiInfo_Dowork(object sender, DoWorkEventArgs e)
11112 e.Result = tw.GetInfoApi();
11115 private void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11117 StringBuilder tmp = new StringBuilder();
11119 using (FormInfo dlg = new FormInfo(this, Properties.Resources.ApiInfo6, GetApiInfo_Dowork))
11123 var result = (TwitterApiStatus)dlg.Result;
11125 if (result == null)
11127 var accessLevel = result.AccessLevel;
11128 var timelineLimit = result.AccessLimit["/statuses/home_timeline"];
11129 var mediaLimit = result.MediaUploadLimit;
11131 tmp.AppendLine(Properties.Resources.ApiInfo1 + timelineLimit.AccessLimitCount);
11132 tmp.AppendLine(Properties.Resources.ApiInfo2 + timelineLimit.AccessLimitRemain);
11133 tmp.AppendLine(Properties.Resources.ApiInfo3 + timelineLimit.AccessLimitResetDate);
11134 tmp.AppendLine(Properties.Resources.ApiInfo7 + (tw.UserStreamEnabled ? Properties.Resources.Enable : Properties.Resources.Disable));
11137 tmp.AppendLine(Properties.Resources.ApiInfo8 + accessLevel);
11138 SetStatusLabelUrl();
11141 tmp.AppendLine(Properties.Resources.ApiInfo9 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitCount.ToString()));
11142 tmp.AppendLine(Properties.Resources.ApiInfo10 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitRemain.ToString()));
11143 tmp.AppendLine(Properties.Resources.ApiInfo11 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitResetDate.ToString()));
11147 tmp.Append(Properties.Resources.ApiInfo5);
11151 MessageBox.Show(tmp.ToString(), Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11154 private void FollowCommandMenuItem_Click(object sender, EventArgs e)
11157 if (_curPost != null) id = _curPost.ScreenName;
11161 private void FollowCommand_DoWork(object sender, DoWorkEventArgs e)
11163 FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11164 e.Result = arg.tw.PostFollowCommand(arg.id);
11167 private void FollowCommand(string id)
11169 using (InputTabName inputName = new InputTabName())
11171 inputName.FormTitle = "Follow";
11172 inputName.FormDescription = Properties.Resources.FRMessage1;
11173 inputName.TabName = id;
11174 if (inputName.ShowDialog() == DialogResult.OK &&
11175 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11177 FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11179 arg.id = inputName.TabName.Trim();
11180 using (FormInfo _info = new FormInfo(this, Properties.Resources.FollowCommandText1,
11181 FollowCommand_DoWork,
11185 _info.ShowDialog();
11186 string ret = (string)_info.Result;
11187 if (!string.IsNullOrEmpty(ret))
11188 MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11190 MessageBox.Show(Properties.Resources.FRMessage3);
11196 private void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11199 if (_curPost != null) id = _curPost.ScreenName;
11200 RemoveCommand(id, false);
11203 private class FollowRemoveCommandArgs
11209 private void RemoveCommand_DoWork(object sender , DoWorkEventArgs e)
11211 FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11212 e.Result = arg.tw.PostRemoveCommand(arg.id);
11215 private void RemoveCommand(string id, bool skipInput)
11217 FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11222 using (InputTabName inputName = new InputTabName())
11224 inputName.FormTitle = "Unfollow";
11225 inputName.FormDescription = Properties.Resources.FRMessage1;
11226 inputName.TabName = id;
11227 if (inputName.ShowDialog() == DialogResult.OK &&
11228 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11231 arg.id = inputName.TabName.Trim();
11240 using (FormInfo _info = new FormInfo(this, Properties.Resources.RemoveCommandText1,
11241 RemoveCommand_DoWork,
11245 _info.ShowDialog();
11246 string ret = (string)_info.Result;
11247 if (!string.IsNullOrEmpty(ret))
11248 MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11250 MessageBox.Show(Properties.Resources.FRMessage3);
11254 private void FriendshipMenuItem_Click(object sender, EventArgs e)
11257 if (_curPost != null)
11258 id = _curPost.ScreenName;
11260 ShowFriendship(id);
11263 private class ShowFriendshipArgs
11266 public class FriendshipInfo
11268 public string id = "";
11269 public bool isFollowing = false;
11270 public bool isFollowed = false;
11271 public bool isError = false;
11272 public FriendshipInfo(string id)
11277 public List<FriendshipInfo> ids = new List<FriendshipInfo>();
11280 private void ShowFriendship_DoWork(object sender, DoWorkEventArgs e)
11282 ShowFriendshipArgs arg = (ShowFriendshipArgs)e.Argument;
11283 string result = "";
11284 foreach (ShowFriendshipArgs.FriendshipInfo fInfo in arg.ids)
11286 string rt = arg.tw.GetFriendshipInfo(fInfo.id, ref fInfo.isFollowing, ref fInfo.isFollowed);
11287 if (!string.IsNullOrEmpty(rt))
11289 if (string.IsNullOrEmpty(result)) result = rt;
11290 fInfo.isError = true;
11296 private void ShowFriendship(string id)
11298 ShowFriendshipArgs args = new ShowFriendshipArgs();
11300 using (InputTabName inputName = new InputTabName())
11302 inputName.FormTitle = "Show Friendships";
11303 inputName.FormDescription = Properties.Resources.FRMessage1;
11304 inputName.TabName = id;
11305 if (inputName.ShowDialog() == DialogResult.OK &&
11306 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11309 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(inputName.TabName.Trim()));
11310 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11311 ShowFriendship_DoWork,
11315 _info.ShowDialog();
11316 ret = (string)_info.Result;
11318 string result = "";
11319 if (string.IsNullOrEmpty(ret))
11321 if (args.ids[0].isFollowing)
11323 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11327 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11329 if (args.ids[0].isFollowed)
11331 result += Properties.Resources.GetFriendshipInfo3;
11335 result += Properties.Resources.GetFriendshipInfo4;
11337 result = args.ids[0].id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11343 MessageBox.Show(result);
11348 private void ShowFriendship(string[] ids)
11350 foreach (string id in ids)
11353 ShowFriendshipArgs args = new ShowFriendshipArgs();
11355 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(id.Trim()));
11356 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11357 ShowFriendship_DoWork,
11361 _info.ShowDialog();
11362 ret = (string)_info.Result;
11364 string result = "";
11365 ShowFriendshipArgs.FriendshipInfo fInfo = args.ids[0];
11367 if (string.IsNullOrEmpty(ret))
11370 if (fInfo.isFollowing)
11372 ff += Properties.Resources.GetFriendshipInfo1;
11376 ff += Properties.Resources.GetFriendshipInfo2;
11379 ff += System.Environment.NewLine + " ";
11380 if (fInfo.isFollowed)
11382 ff += Properties.Resources.GetFriendshipInfo3;
11386 ff += Properties.Resources.GetFriendshipInfo4;
11388 result += fInfo.id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11389 if (fInfo.isFollowing)
11391 if (MessageBox.Show(
11392 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11393 MessageBoxButtons.YesNo,
11394 MessageBoxIcon.Question,
11395 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11397 RemoveCommand(fInfo.id, true);
11402 MessageBox.Show(result);
11407 MessageBox.Show(ret);
11412 private void OwnStatusMenuItem_Click(object sender, EventArgs e)
11414 doShowUserStatus(tw.Username, false);
11415 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11417 // doShowUserStatus(tw.Username, false);
11421 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11426 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11427 // URLから切り出した文字列を渡す
11429 public bool IsTwitterId(string name)
11431 if (SettingDialog.TwitterConfiguration.NonUsernamePaths == null || SettingDialog.TwitterConfiguration.NonUsernamePaths.Length == 0)
11432 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11434 return !SettingDialog.TwitterConfiguration.NonUsernamePaths.Contains(name.ToLower());
11437 private string GetUserId()
11439 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11440 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11441 return m.Result("${ScreenName}");
11446 private void FollowContextMenuItem_Click(object sender, EventArgs e)
11448 string name = GetUserId();
11449 if (name != null) FollowCommand(name);
11452 private void RemoveContextMenuItem_Click(object sender, EventArgs e)
11454 string name = GetUserId();
11455 if (name != null) RemoveCommand(name, false);
11458 private void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11460 string name = GetUserId();
11461 if (name != null) ShowFriendship(name);
11464 private void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11466 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11467 List<string> ids = new List<string>();
11468 foreach (Match mu in ma)
11470 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11472 ids.Add(mu.Result("${ScreenName}"));
11475 ShowFriendship(ids.ToArray());
11478 private void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11480 string name = GetUserId();
11481 if (name != null) ShowUserStatus(name);
11484 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11486 string name = GetUserId();
11487 if (name != null) AddNewTabForUserTimeline(name);
11490 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11492 string name = GetUserId();
11493 if (name != null) AddNewTabForSearch("@" + name);
11496 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11498 _modifySettingCommon = true;
11501 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11503 _modifySettingCommon = true;
11506 private void doQuote()
11510 if (this.ExistCurrentPost)
11512 if (_curPost.IsDm ||
11513 !StatusText.Enabled) return;
11515 if (_curPost.IsProtect)
11517 MessageBox.Show("Protected.");
11520 string rtdata = _curPost.Text;
11521 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11523 StatusText.Text = " QT @" + _curPost.ScreenName + ": " + rtdata;
11524 if (_curPost.RetweetedId == null)
11526 _reply_to_id = _curPost.StatusId;
11530 _reply_to_id = _curPost.RetweetedId.Value;
11532 _reply_to_name = _curPost.ScreenName;
11534 StatusText.SelectionStart = 0;
11535 StatusText.Focus();
11539 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11544 private void SearchButton_Click(object sender, EventArgs e)
11547 Control pnl = ((Control)sender).Parent;
11548 if (pnl == null) return;
11549 string tbName = pnl.Parent.Text;
11550 TabClass tb = _statuses.Tabs[tbName];
11551 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11552 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11553 ComboBox cmbusline = (ComboBox)pnl.Controls["comboUserline"];
11554 cmb.Text = cmb.Text.Trim();
11555 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11556 bool Quote = false;
11557 StringBuilder buf = new StringBuilder();
11558 char[] c = cmb.Text.ToCharArray();
11559 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11561 if (cnt > cmb.Text.Length - 4)
11563 buf.Append(cmb.Text.Substring(cnt));
11572 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11574 buf.Append(" OR ");
11579 buf.Append(c[cnt]);
11581 cmb.Text = buf.ToString();
11583 tb.SearchWords = cmb.Text;
11584 tb.SearchLang = cmbLang.Text;
11585 if (string.IsNullOrEmpty(cmb.Text))
11587 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11591 if (tb.IsQueryChanged())
11593 int idx = ((ComboBox)pnl.Controls["comboSearch"]).Items.IndexOf(tb.SearchWords);
11594 if (idx > -1) ((ComboBox)pnl.Controls["comboSearch"]).Items.RemoveAt(idx);
11595 ((ComboBox)pnl.Controls["comboSearch"]).Items.Insert(0, tb.SearchWords);
11596 cmb.Text = tb.SearchWords;
11598 DetailsListView lst = (DetailsListView)pnl.Parent.Tag;
11599 this.PurgeListViewItemCache();
11600 lst.VirtualListSize = 0;
11601 _statuses.ClearTabIds(tbName);
11602 SaveConfigsTabs(); //検索条件の保存
11605 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, tbName);
11606 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11609 private void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11615 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11617 if (_statuses.RemovedTab.Count == 0)
11619 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11624 TabClass tb = _statuses.RemovedTab.Pop();
11625 if (tb.TabType == MyCommon.TabUsageType.Related)
11627 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11628 if (relatedTab != null)
11630 // 関連発言なら既存のタブを置き換える
11631 tb.TabName = relatedTab.TabName;
11632 this.ClearTab(tb.TabName, false);
11633 _statuses.Tabs[tb.TabName] = tb;
11634 for (int i = 0; i < ListTab.TabPages.Count; i++)
11636 if (tb.TabName == ListTab.TabPages[i].Text)
11638 ListTab.SelectedIndex = i;
11639 ListTabSelect(ListTab.TabPages[i]);
11646 const string TabName = "Related Tweets";
11647 string renamed = TabName;
11648 for (int i = 2; i <= 100; i++)
11650 if (!_statuses.ContainsTab(renamed)) break;
11651 renamed = TabName + i.ToString();
11653 tb.TabName = renamed;
11654 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11655 _statuses.Tabs.Add(renamed, tb); // 後に
11656 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11657 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
11662 string renamed = tb.TabName;
11663 for (int i = 1; i < int.MaxValue; i++)
11665 if (!_statuses.ContainsTab(renamed)) break;
11666 renamed = tb.TabName + "(" + i.ToString() + ")";
11668 tb.TabName = renamed;
11669 _statuses.Tabs.Add(renamed, tb); // 先に
11670 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11671 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11672 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
11678 private void doMoveToRTHome()
11680 if (_curList.SelectedIndices.Count > 0)
11682 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11683 if (post.RetweetedId != null)
11685 OpenUriAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11690 private void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11695 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11697 string name = GetUserId();
11703 if (_curList.SelectedIndices.Count == 0) return;
11706 if (!SelectTab(out tabName)) return;
11710 MoveOrCopy(ref mv, ref mk);
11712 PostFilterRule fc = new PostFilterRule();
11713 fc.FilterName = name;
11714 fc.UseNameField = true;
11715 fc.MoveMatches = mv;
11716 fc.MarkMatches = mk;
11717 fc.UseRegex = false;
11718 fc.FilterByUrl = false;
11719 _statuses.Tabs[tabName].AddFilter(fc);
11721 this.ApplyPostFilters();
11726 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11730 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11732 if (menuItem.Owner == this.ContextMenuPostBrowser)
11734 user = GetUserId();
11735 if (user == null) return;
11737 else if (this._curPost != null)
11739 user = this._curPost.ScreenName;
11746 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11748 string res = this.tw.GetListsApi();
11750 if (!string.IsNullOrEmpty(res))
11752 MessageBox.Show("Failed to get lists. (" + res + ")");
11757 using (MyLists listSelectForm = new MyLists(user, this.tw))
11759 listSelectForm.ShowDialog(this);
11763 private void SearchControls_Enter(object sender, EventArgs e)
11765 Control pnl = (Control)sender;
11766 foreach (Control ctl in pnl.Controls)
11768 ctl.TabStop = true;
11772 private void SearchControls_Leave(object sender, EventArgs e)
11774 Control pnl = (Control)sender;
11775 foreach (Control ctl in pnl.Controls)
11777 ctl.TabStop = false;
11781 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
11783 if (ListTab.SelectedTab != null)
11785 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
11786 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
11790 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
11792 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
11795 HashMgr.SetPermanentHash("#" + m.Result("${hash}"));
11796 HashStripSplitButton.Text = HashMgr.UseHash;
11797 HashToggleMenuItem.Checked = true;
11798 HashToggleToolStripMenuItem.Checked = true;
11800 _modifySettingCommon = true;
11804 private void StatusLabel_DoubleClick(object sender, EventArgs e)
11806 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
11809 private void HashManageMenuItem_Click(object sender, EventArgs e)
11811 DialogResult rslt = DialogResult.Cancel;
11814 rslt = HashMgr.ShowDialog();
11820 this.TopMost = SettingDialog.AlwaysTop;
11821 if (rslt == DialogResult.Cancel) return;
11822 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11824 HashStripSplitButton.Text = HashMgr.UseHash;
11825 HashToggleMenuItem.Checked = true;
11826 HashToggleToolStripMenuItem.Checked = true;
11830 HashStripSplitButton.Text = "#[-]";
11831 HashToggleMenuItem.Checked = false;
11832 HashToggleToolStripMenuItem.Checked = false;
11834 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
11836 // int sidx = StatusText.SelectionStart;
11837 // string hash = HashMgr.UseHash + " ";
11840 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
11841 // hash = " " + hash;
11843 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
11844 // sidx += hash.Length;
11845 // StatusText.SelectionStart = sidx;
11846 // StatusText.Focus();
11848 _modifySettingCommon = true;
11849 this.StatusText_TextChanged(null, null);
11852 private void HashToggleMenuItem_Click(object sender, EventArgs e)
11854 HashMgr.ToggleHash();
11855 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11857 HashStripSplitButton.Text = HashMgr.UseHash;
11858 HashToggleMenuItem.Checked = true;
11859 HashToggleToolStripMenuItem.Checked = true;
11863 HashStripSplitButton.Text = "#[-]";
11864 HashToggleMenuItem.Checked = false;
11865 HashToggleToolStripMenuItem.Checked = false;
11867 _modifySettingCommon = true;
11868 this.StatusText_TextChanged(null, null);
11871 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
11873 HashToggleMenuItem_Click(null, null);
11876 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
11878 if (ListTab.SelectedTab == null) return;
11879 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
11880 if (!this.ExistCurrentPost)
11882 this.ReplyOpMenuItem.Enabled = false;
11883 this.ReplyAllOpMenuItem.Enabled = false;
11884 this.DmOpMenuItem.Enabled = false;
11885 this.ShowProfMenuItem.Enabled = false;
11886 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
11887 this.ListManageMenuItem.Enabled = false;
11888 this.OpenFavOpMenuItem.Enabled = false;
11889 this.CreateTabRuleOpMenuItem.Enabled = false;
11890 this.CreateIdRuleOpMenuItem.Enabled = false;
11891 this.ReadOpMenuItem.Enabled = false;
11892 this.UnreadOpMenuItem.Enabled = false;
11896 this.ReplyOpMenuItem.Enabled = true;
11897 this.ReplyAllOpMenuItem.Enabled = true;
11898 this.DmOpMenuItem.Enabled = true;
11899 this.ShowProfMenuItem.Enabled = true;
11900 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
11901 this.ListManageMenuItem.Enabled = true;
11902 this.OpenFavOpMenuItem.Enabled = true;
11903 this.CreateTabRuleOpMenuItem.Enabled = true;
11904 this.CreateIdRuleOpMenuItem.Enabled = true;
11905 this.ReadOpMenuItem.Enabled = true;
11906 this.UnreadOpMenuItem.Enabled = true;
11909 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
11911 this.FavOpMenuItem.Enabled = false;
11912 this.UnFavOpMenuItem.Enabled = false;
11913 this.OpenStatusOpMenuItem.Enabled = false;
11914 this.OpenFavotterOpMenuItem.Enabled = false;
11915 this.ShowRelatedStatusesMenuItem2.Enabled = false;
11916 this.RtOpMenuItem.Enabled = false;
11917 this.RtUnOpMenuItem.Enabled = false;
11918 this.QtOpMenuItem.Enabled = false;
11919 this.FavoriteRetweetMenuItem.Enabled = false;
11920 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11921 if (this.ExistCurrentPost && _curPost.IsDm) this.DelOpMenuItem.Enabled = true;
11925 this.FavOpMenuItem.Enabled = true;
11926 this.UnFavOpMenuItem.Enabled = true;
11927 this.OpenStatusOpMenuItem.Enabled = true;
11928 this.OpenFavotterOpMenuItem.Enabled = true;
11929 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
11933 this.RtOpMenuItem.Enabled = false;
11934 this.FavoriteRetweetMenuItem.Enabled = false;
11935 this.DelOpMenuItem.Enabled = true;
11939 this.DelOpMenuItem.Enabled = false;
11940 if (_curPost.IsProtect)
11942 this.RtOpMenuItem.Enabled = false;
11943 this.RtUnOpMenuItem.Enabled = false;
11944 this.QtOpMenuItem.Enabled = false;
11945 this.FavoriteRetweetMenuItem.Enabled = false;
11946 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11950 this.RtOpMenuItem.Enabled = true;
11951 this.RtUnOpMenuItem.Enabled = true;
11952 this.QtOpMenuItem.Enabled = true;
11953 this.FavoriteRetweetMenuItem.Enabled = true;
11954 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11959 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11961 this.RefreshPrevOpMenuItem.Enabled = true;
11965 this.RefreshPrevOpMenuItem.Enabled = false;
11967 if (!this.ExistCurrentPost
11968 || _curPost.InReplyToStatusId == null)
11970 OpenRepSourceOpMenuItem.Enabled = false;
11974 OpenRepSourceOpMenuItem.Enabled = true;
11976 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11978 OpenRterHomeMenuItem.Enabled = false;
11982 OpenRterHomeMenuItem.Enabled = true;
11986 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11988 ContextMenuTabProperty_Opening(sender, null);
11991 public Twitter TwitterInstance
11996 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11998 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
12000 _mySpDis3 = SplitContainer3.SplitterDistance;
12001 _modifySettingLocal = true;
12005 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12007 if (_statuses.RemovedTab.Count == 0)
12009 UndoRemoveTabMenuItem.Enabled = false;
12013 UndoRemoveTabMenuItem.Enabled = true;
12015 if (ListTab.SelectedTab != null)
12017 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12018 PublicSearchQueryMenuItem.Enabled = true;
12020 PublicSearchQueryMenuItem.Enabled = false;
12024 PublicSearchQueryMenuItem.Enabled = false;
12026 if (!this.ExistCurrentPost)
12028 this.CopySTOTMenuItem.Enabled = false;
12029 this.CopyURLMenuItem.Enabled = false;
12030 this.CopyUserIdStripMenuItem.Enabled = false;
12034 this.CopySTOTMenuItem.Enabled = true;
12035 this.CopyURLMenuItem.Enabled = true;
12036 this.CopyUserIdStripMenuItem.Enabled = true;
12037 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12038 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12042 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12044 SetNotifyIconText();
12047 private void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12050 if (_curPost != null)
12052 id = _curPost.ScreenName;
12054 ShowUserStatus(id);
12057 private class GetUserInfoArgs
12061 public TwitterUser user;
12064 private void GetUserInfo_DoWork(object sender, DoWorkEventArgs e)
12066 GetUserInfoArgs args = (GetUserInfoArgs)e.Argument;
12067 e.Result = args.tw.GetUserInfo(args.id, ref args.user);
12070 private void doShowUserStatus(string id, bool ShowInputDialog)
12072 TwitterUser user = null;
12073 GetUserInfoArgs args = new GetUserInfoArgs();
12074 if (ShowInputDialog)
12076 using (InputTabName inputName = new InputTabName())
12078 inputName.FormTitle = "Show UserStatus";
12079 inputName.FormDescription = Properties.Resources.FRMessage1;
12080 inputName.TabName = id;
12081 if (inputName.ShowDialog() == DialogResult.OK &&
12082 !string.IsNullOrEmpty(inputName.TabName.Trim()))
12084 id = inputName.TabName.Trim();
12088 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
12089 GetUserInfo_DoWork,
12093 _info.ShowDialog();
12094 string ret = (string)_info.Result;
12095 if (string.IsNullOrEmpty(ret))
12096 doShowUserStatus(args.user);
12098 MessageBox.Show(ret);
12108 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
12109 GetUserInfo_DoWork,
12113 _info.ShowDialog();
12114 string ret = (string)_info.Result;
12115 if (string.IsNullOrEmpty(ret))
12117 doShowUserStatus(args.user);
12121 MessageBox.Show(ret);
12127 private void doShowUserStatus(TwitterUser user)
12129 using (var userinfo = new UserInfoDialog())
12131 userinfo.Owner = this;
12132 userinfo.DisplayUser = user;
12133 userinfo.ShowDialog(this);
12135 this.BringToFront();
12139 private void ShowUserStatus(string id, bool ShowInputDialog)
12141 doShowUserStatus(id, ShowInputDialog);
12144 private void ShowUserStatus(string id)
12146 doShowUserStatus(id, true);
12149 private void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12151 if (NameLabel.Tag != null)
12153 string id = (string)NameLabel.Tag;
12154 if (id != tw.Username)
12161 private void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12163 if (NameLabel.Tag != null)
12165 string id = (string)NameLabel.Tag;
12166 if (id != tw.Username)
12168 RemoveCommand(id, false);
12173 private void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12175 if (NameLabel.Tag != null)
12177 string id = (string)NameLabel.Tag;
12178 if (id != tw.Username)
12180 ShowFriendship(id);
12185 private void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12187 if (NameLabel.Tag != null)
12189 string id = (string)NameLabel.Tag;
12190 ShowUserStatus(id, false);
12194 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12196 if (NameLabel.Tag != null)
12198 string id = (string)NameLabel.Tag;
12199 AddNewTabForUserTimeline(id);
12203 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12205 if (NameLabel.Tag != null)
12207 string id = (string)NameLabel.Tag;
12208 AddNewTabForSearch("@" + id);
12212 private void ShowProfileMenuItem_Click(object sender, EventArgs e)
12214 if (_curPost != null)
12216 ShowUserStatus(_curPost.ScreenName, false);
12220 private void GetRetweet_DoWork(object sender, DoWorkEventArgs e)
12225 if (_curPost.RetweetedId != null)
12227 statusid = _curPost.RetweetedId.Value;
12231 statusid = _curPost.StatusId;
12233 tw.GetStatus_Retweeted_Count(statusid, ref counter);
12235 e.Result = counter;
12238 private void RtCountMenuItem_Click(object sender, EventArgs e)
12240 if (this.ExistCurrentPost)
12242 using (FormInfo _info = new FormInfo(this, Properties.Resources.RtCountMenuItem_ClickText1,
12243 GetRetweet_DoWork))
12245 int retweet_count = 0;
12248 _info.ShowDialog();
12249 retweet_count = (int)_info.Result;
12250 if (retweet_count < 0)
12252 MessageBox.Show(Properties.Resources.RtCountText2);
12256 MessageBox.Show(retweet_count.ToString() + Properties.Resources.RtCountText1);
12262 private HookGlobalHotkey _hookGlobalHotkey;
12265 this.http = MyCommon.CreateHttpClient();
12266 _hookGlobalHotkey = new HookGlobalHotkey(this);
12268 // この呼び出しは、Windows フォーム デザイナで必要です。
12269 InitializeComponent();
12271 // InitializeComponent() 呼び出しの後で初期化を追加します。
12273 this.SettingDialog.IntervalChanged += this.TimerInterval_Changed;
12274 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12275 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12276 this.gh.NotifyClicked += GrowlHelper_Callback;
12278 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12279 this.ListTab.HandleCreated += (s, e) => Win32Api.SetMinTabWidth((TabControl)s, 40);
12281 this._apiGauge = new ToolStripAPIGauge();
12282 this._apiGauge.BorderSides = ToolStripStatusLabelBorderSides.Right;
12283 this.StatusStrip1.Items.Insert(2, this._apiGauge);
12285 this.ImageSelectedPicture.InitialImage = Properties.Resources.InitialImage;
12287 this.ReplaceAppName();
12290 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12292 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12295 this.Visible = false;
12297 else if (Form.ActiveForm == null)
12299 this.Visible = true;
12300 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12302 this.BringToFront();
12303 this.StatusText.Focus();
12307 private void UserPicture_MouseEnter(object sender, EventArgs e)
12309 this.UserPicture.Cursor = Cursors.Hand;
12312 private void UserPicture_MouseLeave(object sender, EventArgs e)
12314 this.UserPicture.Cursor = Cursors.Default;
12317 private void UserPicture_DoubleClick(object sender, EventArgs e)
12319 if (NameLabel.Tag != null)
12321 OpenUriAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12325 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12327 this.MultiLineMenuItem.PerformClick();
12330 public PostClass CurPost
12332 get { return _curPost; }
12335 public bool IsPreviewEnable
12337 get { return SettingDialog.PreviewEnable; }
12341 private void CreatePictureServices()
12343 if (this.pictureService != null) this.pictureService.Clear();
12344 this.pictureService = null;
12345 this.pictureService = new Dictionary<string, IMultimediaShareService> {
12346 {"TwitPic", new TwitPic(tw)},
12347 {"img.ly", new imgly(tw)},
12348 {"yfrog", new yfrog(tw)},
12349 {"Twitter", new TwitterPhoto(tw)},
12350 {"ついっぷるフォト", new TwipplePhoto(tw)},
12351 {"Imgur", new Imgur(tw)},
12355 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12357 if (ImageSelectionPanel.Visible)
12359 CloseImageSelectionPanel();
12363 OpenImageSelectionPanel();
12364 ImageFromSelectedFile(true);
12365 ImagefilePathText.Focus();
12369 private void OpenImageSelectionPanel()
12371 ImageSelectionPanel.Visible = true;
12372 ImageSelectionPanel.Enabled = true;
12373 TimelinePanel.Visible = false;
12374 TimelinePanel.Enabled = false;
12377 private void CloseImageSelectionPanel()
12379 ImagefilePathText.CausesValidation = false;
12380 TimelinePanel.Visible = true;
12381 TimelinePanel.Enabled = true;
12382 ImageSelectionPanel.Visible = false;
12383 ImageSelectionPanel.Enabled = false;
12384 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12385 ClearImageSelectedPicture();
12386 ImagefilePathText.CausesValidation = true;
12389 private void SelectMedia_DragEnter(DragEventArgs e)
12391 string filename = ((string[])e.Data.GetData(DataFormats.FileDrop, false))[0];
12392 FileInfo fl = new FileInfo(filename);
12393 string ext = fl.Extension;
12395 if (!string.IsNullOrEmpty(this.ImageService) &&
12396 this.pictureService[this.ImageService].CheckValidFilesize(ext, fl.Length))
12398 e.Effect = DragDropEffects.Copy;
12401 foreach (string svc in ImageServiceCombo.Items)
12403 if (!string.IsNullOrEmpty(svc) &&
12404 this.pictureService[svc].CheckValidFilesize(ext, fl.Length))
12406 //ImageServiceCombo.SelectedItem = svc;
12407 e.Effect = DragDropEffects.Copy;
12411 e.Effect = DragDropEffects.None;
12414 private void SelectMedia_DragOver(DragEventArgs e)
12419 private void SelectMedia_DragDrop(DragEventArgs e)
12422 this.BringToFront();
12423 OpenImageSelectionPanel();
12424 ImagefilePathText.Text = ((string[])e.Data.GetData(DataFormats.FileDrop, false))[0];
12425 ImageFromSelectedFile(false);
12426 StatusText.Focus();
12429 private void FilePickButton_Click(object sender, EventArgs e)
12431 if (string.IsNullOrEmpty(this.ImageService)) return;
12432 OpenFileDialog1.Filter = this.pictureService[this.ImageService].GetFileOpenDialogFilter();
12433 OpenFileDialog1.Title = Properties.Resources.PickPictureDialog1;
12434 OpenFileDialog1.FileName = "";
12438 this.AllowDrop = false;
12439 if (OpenFileDialog1.ShowDialog() == DialogResult.Cancel) return;
12443 this.AllowDrop = true;
12446 ImagefilePathText.Text = OpenFileDialog1.FileName;
12447 ImageFromSelectedFile(false);
12450 private void ImagefilePathText_Validating(object sender, CancelEventArgs e)
12452 if (ImageCancelButton.Focused)
12454 ImagefilePathText.CausesValidation = false;
12458 ImageFromSelectedFile(false);
12461 private void ImageFromSelectedFile(bool suppressMsgBox)
12463 this.ClearImageSelectedPicture();
12467 ImagefilePathText.Text = ImagefilePathText.Text.Trim();
12468 if (string.IsNullOrEmpty(ImagefilePathText.Text) || string.IsNullOrEmpty(this.ImageService))
12470 ImagefilePathText.Text = "";
12474 FileInfo fl = new FileInfo(ImagefilePathText.Text);
12475 string ext = fl.Extension;
12476 var imageService = this.pictureService[this.ImageService];
12478 if (!imageService.CheckValidExtension(ext))
12481 ImagefilePathText.Text = "";
12482 if (!suppressMsgBox)
12485 string.Format(Properties.Resources.PostPictureWarn3, this.ImageService, MakeAvailableServiceText(ext, fl.Length), ext),
12486 Properties.Resources.PostPictureWarn4,
12487 MessageBoxButtons.OK,
12488 MessageBoxIcon.Warning);
12493 if (!imageService.CheckValidFilesize(ext, fl.Length))
12496 ImagefilePathText.Text = "";
12497 if (!suppressMsgBox)
12500 string.Format(Properties.Resources.PostPictureWarn5, this.ImageService, MakeAvailableServiceText(ext, fl.Length)),
12501 Properties.Resources.PostPictureWarn4,
12502 MessageBoxButtons.OK,
12503 MessageBoxIcon.Warning);
12508 switch (imageService.GetFileType(ext))
12510 case MyCommon.UploadFileType.Picture:
12511 using (var fs = File.OpenRead(ImagefilePathText.Text))
12513 ImageSelectedPicture.Image = MemoryImage.CopyFromStream(fs);
12515 ImageSelectedPicture.Tag = MyCommon.UploadFileType.Picture;
12517 case MyCommon.UploadFileType.MultiMedia:
12518 ImageSelectedPicture.Tag = MyCommon.UploadFileType.MultiMedia;
12521 ImagefilePathText.Text = "";
12525 catch (FileNotFoundException)
12527 ImagefilePathText.Text = "";
12528 if (!suppressMsgBox) MessageBox.Show("File not found.");
12532 ImagefilePathText.Text = "";
12533 if (!suppressMsgBox) MessageBox.Show("The type of this file is not image.");
12537 private string MakeAvailableServiceText(string ext, long fileSize)
12539 StringBuilder sb = new StringBuilder();
12541 foreach (string svc in ImageServiceCombo.Items)
12543 if (!string.IsNullOrEmpty(svc) &&
12544 this.pictureService[svc].CheckValidFilesize(ext, fileSize))
12546 if (sb.Length > 0) sb.Append(", ");
12550 if (sb.Length == 0)
12551 return Properties.Resources.PostPictureWarn6;
12553 return sb.ToString();
12556 private void ClearImageSelectedPicture()
12558 var oldImage = this.ImageSelectedPicture.Image;
12559 if (oldImage != null)
12561 this.ImageSelectedPicture.Image = null;
12562 oldImage.Dispose();
12565 this.ImageSelectedPicture.Tag = null;
12566 this.ImageSelectedPicture.ShowInitialImage();
12569 private void ImageCancelButton_Click(object sender, EventArgs e)
12571 CloseImageSelectionPanel();
12574 private void ImageSelection_KeyDown(object sender, KeyEventArgs e)
12576 if (e.KeyCode == Keys.Escape)
12578 CloseImageSelectionPanel();
12582 private void ImageSelection_KeyPress(object sender, KeyPressEventArgs e)
12584 if (Convert.ToInt32(e.KeyChar) == 0x1B)
12586 ImagefilePathText.CausesValidation = false;
12591 private void ImageSelection_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
12593 if (e.KeyCode == Keys.Escape)
12595 ImagefilePathText.CausesValidation = false;
12599 private bool TryGetSelectedMedia(out string imageService, out string imagePath)
12601 if (ImageSelectedPicture.Tag != null &&
12602 ImageServiceCombo.SelectedIndex > -1 &&
12603 !string.IsNullOrEmpty(ImagefilePathText.Text))
12605 if (MessageBox.Show(string.Format(Properties.Resources.PostPictureConfirm1, this.ImageService),
12606 Properties.Resources.PostPictureConfirm2,
12607 MessageBoxButtons.OKCancel,
12608 MessageBoxIcon.Question,
12609 MessageBoxDefaultButton.Button1)
12610 == DialogResult.OK)
12612 imageService = ImageServiceCombo.Text;
12613 imagePath = ImagefilePathText.Text;
12614 CloseImageSelectionPanel();
12615 ImagefilePathText.Text = "";
12621 MessageBox.Show(Properties.Resources.PostPictureWarn1, Properties.Resources.PostPictureWarn2);
12624 CloseImageSelectionPanel();
12625 imageService = null;
12630 private void SetImageServiceCombo()
12633 if (ImageServiceCombo.SelectedIndex > -1) svc = ImageServiceCombo.SelectedItem.ToString();
12634 ImageServiceCombo.Items.Clear();
12636 // Add service names to combobox
12637 foreach (var key in pictureService.Keys)
12639 ImageServiceCombo.Items.Add(key);
12642 SelectImageServiceComboItem(svc);
12645 private void SelectImageServiceComboItem(string svc, int? index = null)
12648 if (string.IsNullOrEmpty(svc))
12654 idx = ImageServiceCombo.Items.IndexOf(svc);
12655 if (idx == -1) idx = index ?? 0;
12660 ImageServiceCombo.SelectedIndex = idx;
12662 catch (ArgumentOutOfRangeException)
12664 ImageServiceCombo.SelectedIndex = 0;
12668 private string ImageService
12670 get { return ImageServiceCombo.SelectedItem.ToString(); }
12673 private void ImageServiceCombo_SelectedIndexChanged(object sender, EventArgs e)
12675 if (ImageSelectedPicture.Tag != null && !string.IsNullOrEmpty(this.ImageService))
12679 FileInfo fi = new FileInfo(ImagefilePathText.Text.Trim());
12680 string ext = fi.Extension;
12681 var imageService = this.pictureService[this.ImageService];
12682 if (!imageService.CheckValidFilesize(ext, fi.Length))
12684 ClearImageSelectedPicture();
12685 ImagefilePathText.Text = "";
12690 ClearImageSelectedPicture();
12691 ImagefilePathText.Text = "";
12693 _modifySettingCommon = true;
12694 SaveConfigsAll(true);
12695 if (this.ImageService == "Twitter")
12697 this.StatusText_TextChanged(null, null);
12702 private void ImageSelectionPanel_VisibleChanged(object sender, EventArgs e)
12704 this.StatusText_TextChanged(null, null);
12708 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12710 using (ListManage form = new ListManage(tw))
12712 form.ShowDialog(this);
12716 public bool ModifySettingCommon
12718 set { _modifySettingCommon = value; }
12721 public bool ModifySettingLocal
12723 set { _modifySettingLocal = value; }
12726 public bool ModifySettingAtId
12728 set { _modifySettingAtId = value; }
12731 private void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12733 string link = (string)SourceLinkLabel.Tag;
12734 if (!string.IsNullOrEmpty(link) && e.Button == MouseButtons.Left)
12736 OpenUriAsync(link);
12740 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12742 string link = (string)SourceLinkLabel.Tag;
12743 if (!string.IsNullOrEmpty(link))
12745 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(link);
12749 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12751 SetStatusLabelUrl();
12754 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12756 if (this.ExistCurrentPost && !_curPost.IsDm)
12757 RtCountMenuItem.Enabled = true;
12759 RtCountMenuItem.Enabled = false;
12761 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12762 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12764 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12767 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12772 private void CopyUserId()
12774 if (_curPost == null) return;
12775 string clstr = _curPost.ScreenName;
12778 Clipboard.SetDataObject(clstr, false, 5, 100);
12780 catch (Exception ex)
12782 MessageBox.Show(ex.Message);
12786 private void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e) // Handles ShowRelatedStatusesMenuItem.Click, ShowRelatedStatusesMenuItem2.Click
12788 if (this.ExistCurrentPost && !_curPost.IsDm)
12792 this.OpenRelatedTab(this._curPost);
12794 catch (TabException ex)
12796 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12802 /// 指定されたツイートに対する関連発言タブを開きます
12804 /// <param name="post">表示する対象となるツイート</param>
12805 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12806 private void OpenRelatedTab(PostClass post)
12808 var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12811 if (tabRelated == null)
12813 tabName = this._statuses.MakeTabName("Related Tweets");
12815 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12816 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12818 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12819 tabRelated.UnreadManage = false;
12820 tabRelated.Notify = false;
12824 tabName = tabRelated.TabName;
12827 tabRelated.RelationTargetPost = post;
12828 this.ClearTab(tabName, false);
12830 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12832 var tabPage = this.ListTab.TabPages[i];
12833 if (tabName == tabPage.Text)
12835 this.ListTab.SelectedIndex = i;
12836 this.ListTabSelect(tabPage);
12841 this.GetTimeline(MyCommon.WORKERTYPE.Related, 1, 1, tabName);
12844 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12846 StringBuilder buf = new StringBuilder();
12847 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12848 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12849 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12850 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12851 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12854 private void tw_UserIdChanged()
12856 this._modifySettingCommon = true;
12859 #region "Userstream"
12860 private bool _isActiveUserstream = false;
12862 private void tw_PostDeleted(long id)
12866 if (InvokeRequired && !IsDisposed)
12868 Invoke((Action) (() =>
12870 _statuses.RemovePostReserve(id);
12871 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(id))
12873 this.PurgeListViewItemCache();
12874 ((DetailsListView)_curTab.Tag).Update();
12875 if (_curPost != null && _curPost.StatusId == id) DispSelectedPost(true);
12881 catch (ObjectDisposedException)
12885 catch (InvalidOperationException)
12891 private void tw_NewPostFromStream()
12893 if (SettingDialog.ReadOldPosts)
12895 _statuses.SetRead(); //新着時未読クリア
12898 int rsltAddCount = _statuses.DistributePosts();
12901 DateTime tm = DateTime.Now;
12902 if (_tlTimestamps.ContainsKey(tm))
12904 _tlTimestamps[tm] += rsltAddCount;
12908 _tlTimestamps.Add(tm, rsltAddCount);
12910 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
12911 List<DateTime> keys = new List<DateTime>();
12913 foreach (DateTime key in _tlTimestamps.Keys)
12915 if (key.CompareTo(oneHour) < 0)
12918 _tlCount += _tlTimestamps[key];
12920 foreach (DateTime key in keys)
12922 _tlTimestamps.Remove(key);
12926 //Static DateTime before = Now;
12927 //if (before.Subtract(Now).Seconds > -5) return;
12931 if (SettingDialog.UserstreamPeriodInt > 0) return;
12935 if (InvokeRequired && !IsDisposed)
12937 Invoke(new Action<bool>(RefreshTimeline), true);
12941 catch (ObjectDisposedException)
12945 catch (InvalidOperationException)
12951 private void tw_UserStreamStarted()
12953 this._isActiveUserstream = true;
12956 if (InvokeRequired && !IsDisposed)
12958 Invoke(new MethodInvoker(tw_UserStreamStarted));
12962 catch (ObjectDisposedException)
12966 catch (InvalidOperationException)
12971 MenuItemUserStream.Text = "&UserStream ▶";
12972 MenuItemUserStream.Enabled = true;
12973 StopToolStripMenuItem.Text = "&Stop";
12974 StopToolStripMenuItem.Enabled = true;
12976 StatusLabel.Text = "UserStream Started.";
12979 private void tw_UserStreamStopped()
12981 this._isActiveUserstream = false;
12984 if (InvokeRequired && !IsDisposed)
12986 Invoke(new MethodInvoker(tw_UserStreamStopped));
12990 catch (ObjectDisposedException)
12994 catch (InvalidOperationException)
12999 MenuItemUserStream.Text = "&UserStream ■";
13000 MenuItemUserStream.Enabled = true;
13001 StopToolStripMenuItem.Text = "&Start";
13002 StopToolStripMenuItem.Enabled = true;
13004 StatusLabel.Text = "UserStream Stopped.";
13007 private void tw_UserStreamEventArrived(Twitter.FormattedEvent ev)
13011 if (InvokeRequired && !IsDisposed)
13013 Invoke(new Action<Twitter.FormattedEvent>(tw_UserStreamEventArrived), ev);
13017 catch (ObjectDisposedException)
13021 catch (InvalidOperationException)
13025 StatusLabel.Text = "Event: " + ev.Event;
13026 //if (ev.Event == "favorite")
13028 // NotifyFavorite(ev);
13031 if (ev.Event == "favorite" || ev.Event == "unfavorite")
13033 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
13035 this.PurgeListViewItemCache();
13036 ((DetailsListView)_curTab.Tag).Update();
13038 if (ev.Event == "unfavorite" && ev.Username.ToLower().Equals(tw.Username.ToLower()))
13040 RemovePostFromFavTab(new long[] {ev.Id});
13045 private void NotifyEvent(Twitter.FormattedEvent ev)
13048 if (BalloonRequired(ev))
13050 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
13051 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
13052 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
13053 StringBuilder title = new StringBuilder();
13054 if (SettingDialog.DispUsername)
13056 title.Append(tw.Username);
13057 title.Append(" - ");
13063 title.Append(Application.ProductName);
13064 title.Append(" [");
13065 title.Append(ev.Event.ToUpper());
13066 title.Append("] by ");
13067 if (!string.IsNullOrEmpty(ev.Username))
13069 title.Append(ev.Username.ToString());
13073 //title.Append("");
13076 if (!string.IsNullOrEmpty(ev.Target))
13078 //NotifyIcon1.BalloonTipText = ev.Target;
13083 //NotifyIcon1.BalloonTipText = " ";
13086 //NotifyIcon1.ShowBalloonTip(500);
13087 if (SettingDialog.IsNotifyUseGrowl)
13089 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13090 ev.Id.ToString(), title.ToString(), text);
13094 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
13095 NotifyIcon1.BalloonTipTitle = title.ToString();
13096 NotifyIcon1.BalloonTipText = text;
13097 NotifyIcon1.ShowBalloonTip(500);
13102 string snd = SettingDialog.EventSoundFile;
13103 if (!_initial && SettingDialog.PlaySound && !string.IsNullOrEmpty(snd))
13105 if ((ev.Eventtype & SettingDialog.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13109 string dir = Application.StartupPath;
13110 if (Directory.Exists(Path.Combine(dir, "Sounds")))
13112 dir = Path.Combine(dir, "Sounds");
13114 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13126 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13128 MenuItemUserStream.Enabled = false;
13129 if (StopRefreshAllMenuItem.Checked)
13131 StopRefreshAllMenuItem.Checked = false;
13134 if (this._isActiveUserstream)
13136 tw.StopUserStream();
13140 tw.StartUserStream();
13144 private static string inputTrack = "";
13146 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13148 if (TrackToolStripMenuItem.Checked)
13150 using (InputTabName inputForm = new InputTabName())
13152 inputForm.TabName = inputTrack;
13153 inputForm.FormTitle = "Input track word";
13154 inputForm.FormDescription = "Track word";
13155 if (inputForm.ShowDialog() != DialogResult.OK)
13157 TrackToolStripMenuItem.Checked = false;
13160 inputTrack = inputForm.TabName.Trim();
13162 if (!inputTrack.Equals(tw.TrackWord))
13164 tw.TrackWord = inputTrack;
13165 this._modifySettingCommon = true;
13166 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13167 tw.ReconnectUserStream();
13173 tw.ReconnectUserStream();
13175 this._modifySettingCommon = true;
13178 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13180 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13181 this._modifySettingCommon = true;
13182 tw.ReconnectUserStream();
13185 private void EventViewerMenuItem_Click(object sender, EventArgs e)
13187 if (evtDialog == null || evtDialog.IsDisposed)
13190 evtDialog = new EventViewerDialog();
13191 evtDialog.Owner = this;
13193 Point pos = evtDialog.Location;
13194 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13195 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13196 evtDialog.Location = pos;
13198 evtDialog.EventSource = tw.StoredEvent;
13199 if (!evtDialog.Visible)
13201 evtDialog.Show(this);
13205 evtDialog.Activate();
13207 this.TopMost = this.SettingDialog.AlwaysTop;
13211 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13213 MyCommon._endingFlag = true;
13217 Application.Restart();
13221 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13225 private void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13227 if (!string.IsNullOrEmpty(tw.Username)) OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13230 private void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13232 OpenUriAsync(MyCommon.TwitterUrl + tw.Username);
13235 private async Task doTranslation(string str)
13237 if (string.IsNullOrEmpty(str))
13240 var bing = new Bing(this.http);
13243 var translatedText = await bing.TranslateAsync(str,
13245 langTo: this.SettingDialog.TranslateLanguage);
13247 this.PostBrowser.DocumentText = translatedText;
13249 catch (HttpRequestException e)
13251 this.StatusLabel.Text = "Err:" + e.Message;
13255 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13257 if (!this.ExistCurrentPost)
13260 await this.doTranslation(this._curPost.TextFromApi);
13263 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13265 var text = this.WebBrowser_GetSelectionText(ref this.PostBrowser);
13266 await this.doTranslation(text);
13269 private bool ExistCurrentPost
13273 if (_curPost == null) return false;
13274 if (_curPost.IsDeleted) return false;
13279 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13281 ShowUserTimeline();
13284 public bool FavEventChangeUnread
13286 get { return SettingDialog.FavEventUnread; }
13289 private string GetUserIdFromCurPostOrInput(string caption)
13292 if (_curPost != null)
13294 id = _curPost.ScreenName;
13296 using (InputTabName inputName = new InputTabName())
13298 inputName.FormTitle = caption;
13299 inputName.FormDescription = Properties.Resources.FRMessage1;
13300 inputName.TabName = id;
13301 if (inputName.ShowDialog() == DialogResult.OK &&
13302 !string.IsNullOrEmpty(inputName.TabName.Trim()))
13304 id = inputName.TabName.Trim();
13314 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13316 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13317 if (!string.IsNullOrEmpty(id))
13319 AddNewTabForUserTimeline(id);
13323 private void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13325 string id = GetUserIdFromCurPostOrInput("Show Favstar");
13326 if (!string.IsNullOrEmpty(id))
13328 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13332 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13334 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13337 private void TimelineRefreshEnableChange(bool isEnable)
13341 tw.StartUserStream();
13345 tw.StopUserStream();
13347 TimerTimeline.Enabled = isEnable;
13350 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13352 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13355 private void OpenUserAppointUrl()
13357 if (SettingDialog.UserAppointUrl != null)
13359 if (SettingDialog.UserAppointUrl.Contains("{ID}") || SettingDialog.UserAppointUrl.Contains("{STATUS}"))
13361 if (_curPost != null)
13363 string xUrl = SettingDialog.UserAppointUrl;
13364 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13365 if (_curPost.RetweetedId != null)
13367 xUrl = xUrl.Replace("{STATUS}", _curPost.RetweetedId.ToString());
13371 xUrl = xUrl.Replace("{STATUS}", _curPost.StatusId.ToString());
13373 OpenUriAsync(xUrl);
13378 OpenUriAsync(SettingDialog.UserAppointUrl);
13383 private void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13385 OpenUserAppointUrl();
13388 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13390 string selText = SourceLinkLabel.Text;
13393 Clipboard.SetDataObject(selText, false, 5, 100);
13395 catch (Exception ex)
13397 MessageBox.Show(ex.Message);
13401 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13403 string selText = (string)SourceLinkLabel.Tag;
13406 Clipboard.SetDataObject(selText, false, 5, 100);
13408 catch (Exception ex)
13410 MessageBox.Show(ex.Message);
13414 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13416 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13418 SourceCopyMenuItem.Enabled = false;
13419 SourceUrlCopyMenuItem.Enabled = false;
13423 SourceCopyMenuItem.Enabled = true;
13424 SourceUrlCopyMenuItem.Enabled = true;
13428 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13430 if (Form.ActiveForm == null)
13432 this.BeginInvoke((Action) (() =>
13434 this.Visible = true;
13435 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13437 this.BringToFront();
13438 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13440 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13444 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13450 private void ReplaceAppName()
13452 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13453 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13456 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13458 this.SplitContainer3.Panel2Collapsed = false;
13460 // PreviewDistance が起動のたびに広がっていく問題の回避策
13461 // FixedPanel が Panel2 に設定された状態で Panel2 を開くと、初回だけ SplitterDistance が再計算されておかしくなるため、
13462 // None で開いた後に設定するようにする
13463 if (this.SplitContainer3.FixedPanel == FixedPanel.None)
13464 this.SplitContainer3.FixedPanel = FixedPanel.Panel2;
13467 private void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13469 this.OpenThumbnailPicture(e.Thumbnail);
13472 private void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13474 this.OpenUriAsync(e.ImageUrl);
13477 private void OpenThumbnailPicture(ThumbnailInfo thumbnail)
13479 this.OpenUriAsync(Uri.EscapeUriString(thumbnail.ImageUrl));
13482 private void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13484 this.OpenUriAsync(Twitter.ServiceAvailabilityStatusUrl);
13487 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13489 if (e.KeyCode == Keys.Space)
13491 this.JumpUnreadMenuItem_Click(null, null);
13493 e.SuppressKeyPress = true;
13497 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13499 this.IconSizeNoneToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.IconNone;
13500 this.IconSize16ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon16;
13501 this.IconSize24ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon24;
13502 this.IconSize48ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon48;
13503 this.IconSize48_2ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon48_2;
13505 this.LockListSortOrderToolStripMenuItem.Checked = SettingDialog.SortOrderLock;
13508 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13510 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13513 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13515 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13518 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13520 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13523 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13525 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13528 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13530 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13533 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13535 if (SettingDialog.IconSz == iconSize) return;
13537 var oldIconCol = _iconCol;
13539 SettingDialog.IconSz = iconSize;
13540 ApplyListViewIconSize(iconSize);
13542 if (_iconCol != oldIconCol)
13544 foreach (TabPage tp in ListTab.TabPages)
13546 ResetColumns((DetailsListView)tp.Tag);
13550 if (_curList != null) _curList.Refresh();
13552 _modifySettingCommon = true;
13555 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13557 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13558 if (SettingDialog.SortOrderLock == state) return;
13560 SettingDialog.SortOrderLock = state;
13562 _modifySettingCommon = true;