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();
365 // 終了時にRemoveHandlerしておかないとメモリリークする
366 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
367 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
370 private void LoadIcon(ref Icon IconInstance, string FileName)
372 string dir = Application.StartupPath;
373 if (File.Exists(Path.Combine(dir, FileName)))
377 IconInstance = new Icon(Path.Combine(dir, FileName));
385 private void LoadIcons()
389 string dir = Application.StartupPath;
391 NIconAt = Properties.Resources.At;
392 NIconAtRed = Properties.Resources.AtRed;
393 NIconAtSmoke = Properties.Resources.AtSmoke;
394 NIconRefresh[0] = Properties.Resources.Refresh;
395 NIconRefresh[1] = Properties.Resources.Refresh2;
396 NIconRefresh[2] = Properties.Resources.Refresh3;
397 NIconRefresh[3] = Properties.Resources.Refresh4;
398 TabIcon = Properties.Resources.TabIcon;
399 MainIcon = Properties.Resources.MIcon;
400 ReplyIcon = Properties.Resources.Reply;
401 ReplyIconBlink = Properties.Resources.ReplyBlink;
403 if (!Directory.Exists(Path.Combine(dir, "Icons")))
406 LoadIcon(ref NIconAt, "Icons\\At.ico");
409 LoadIcon(ref NIconAtRed, "Icons\\AtRed.ico");
412 LoadIcon(ref NIconAtSmoke, "Icons\\AtSmoke.ico");
415 //アニメーション対応により4種類読み込み
416 LoadIcon(ref NIconRefresh[0], "Icons\\Refresh.ico");
417 LoadIcon(ref NIconRefresh[1], "Icons\\Refresh2.ico");
418 LoadIcon(ref NIconRefresh[2], "Icons\\Refresh3.ico");
419 LoadIcon(ref NIconRefresh[3], "Icons\\Refresh4.ico");
422 LoadIcon(ref TabIcon, "Icons\\Tab.ico");
425 LoadIcon(ref MainIcon, "Icons\\MIcon.ico");
428 LoadIcon(ref ReplyIcon, "Icons\\Reply.ico");
431 LoadIcon(ref ReplyIconBlink, "Icons\\ReplyBlink.ico");
434 private void InitColumns(ListView list, bool startup)
436 ColumnHeader _colHd1 = new ColumnHeader(); //アイコン
437 ColumnHeader _colHd2 = new ColumnHeader(); //ニックネーム
438 ColumnHeader _colHd3 = new ColumnHeader(); //本文
439 ColumnHeader _colHd4 = new ColumnHeader(); //日付
440 ColumnHeader _colHd5 = new ColumnHeader(); //ユーザID
441 ColumnHeader _colHd6 = new ColumnHeader(); //未読
442 ColumnHeader _colHd7 = new ColumnHeader(); //マーク&プロテクト
443 ColumnHeader _colHd8 = new ColumnHeader(); //ソース
447 list.Columns.AddRange(new ColumnHeader[] { _colHd1, _colHd2, _colHd3, _colHd4, _colHd5, _colHd6, _colHd7, _colHd8 });
451 list.Columns.AddRange(new ColumnHeader[] { _colHd1, _colHd3 });
455 _colHd1.Text = ColumnText[0];
457 _colHd2.Text = ColumnText[1];
459 _colHd3.Text = ColumnText[2];
461 _colHd4.Text = ColumnText[3];
463 _colHd5.Text = ColumnText[4];
465 _colHd6.Text = ColumnText[5];
467 _colHd7.Text = ColumnText[6];
469 _colHd8.Text = ColumnText[7];
472 int[] dispOrder = new int[8];
475 for (int i = 0; i < _curList.Columns.Count; i++)
477 for (int j = 0; j < _curList.Columns.Count; j++)
479 if (_curList.Columns[j].DisplayIndex == i)
486 for (int i = 0; i < _curList.Columns.Count; i++)
488 list.Columns[i].Width = _curList.Columns[i].Width;
489 list.Columns[dispOrder[i]].DisplayIndex = i;
496 list.Columns[0].Width = _cfgLocal.Width1;
497 list.Columns[1].Width = _cfgLocal.Width3;
498 list.Columns[0].DisplayIndex = 0;
499 list.Columns[1].DisplayIndex = 1;
503 for (int i = 0; i <= 7; i++)
505 if (_cfgLocal.DisplayIndex1 == i)
507 else if (_cfgLocal.DisplayIndex2 == i)
509 else if (_cfgLocal.DisplayIndex3 == i)
511 else if (_cfgLocal.DisplayIndex4 == i)
513 else if (_cfgLocal.DisplayIndex5 == i)
515 else if (_cfgLocal.DisplayIndex6 == i)
517 else if (_cfgLocal.DisplayIndex7 == i)
519 else if (_cfgLocal.DisplayIndex8 == i)
522 list.Columns[0].Width = _cfgLocal.Width1;
523 list.Columns[1].Width = _cfgLocal.Width2;
524 list.Columns[2].Width = _cfgLocal.Width3;
525 list.Columns[3].Width = _cfgLocal.Width4;
526 list.Columns[4].Width = _cfgLocal.Width5;
527 list.Columns[5].Width = _cfgLocal.Width6;
528 list.Columns[6].Width = _cfgLocal.Width7;
529 list.Columns[7].Width = _cfgLocal.Width8;
530 for (int i = 0; i <= 7; i++)
532 list.Columns[dispOrder[i]].DisplayIndex = i;
538 private void InitColumnText()
541 ColumnText[1] = Properties.Resources.AddNewTabText2;
542 ColumnText[2] = Properties.Resources.AddNewTabText3;
543 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
544 ColumnText[4] = Properties.Resources.AddNewTabText5;
547 ColumnText[7] = "Source";
549 ColumnOrgText[0] = "";
550 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
551 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
552 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
553 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
554 ColumnOrgText[5] = "";
555 ColumnOrgText[6] = "";
556 ColumnOrgText[7] = "Source";
559 switch (_statuses.SortMode)
561 case IdComparerClass.ComparerMode.Nickname: //ニックネーム
564 case IdComparerClass.ComparerMode.Data: //本文
567 case IdComparerClass.ComparerMode.Id: //時刻=発言Id
570 case IdComparerClass.ComparerMode.Name: //名前
573 case IdComparerClass.ComparerMode.Source: //Source
580 if (_statuses.SortOrder == SortOrder.Descending)
582 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
583 ColumnText[2] = ColumnOrgText[2] + "▾";
587 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
588 ColumnText[2] = ColumnOrgText[2] + "▴";
593 if (_statuses.SortOrder == SortOrder.Descending)
595 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
596 ColumnText[c] = ColumnOrgText[c] + "▾";
600 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
601 ColumnText[c] = ColumnOrgText[c] + "▴";
606 private void InitializeTraceFrag()
609 TraceOutToolStripMenuItem.Checked = true;
610 MyCommon.TraceFlag = true;
612 if (!MyCommon.FileVersion.EndsWith("0"))
614 TraceOutToolStripMenuItem.Checked = true;
615 MyCommon.TraceFlag = true;
619 private void TweenMain_Load(object sender, EventArgs e)
621 _ignoreConfigSave = true;
622 this.Visible = false;
624 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
626 SecurityManager = new InternetSecurityManager(PostBrowser);
627 this.PostBrowser.AllowWebBrowserDrop = false; // COMException を回避するため、ActiveX の初期化が終わってから設定する
629 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
630 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
632 if (MyApplication.StartupOptions.ContainsKey("d"))
633 MyCommon.TraceFlag = true;
635 Regex.CacheSize = 100;
637 InitializeTraceFrag();
638 LoadIcons(); // アイコン読み込み
641 _statuses = TabInformations.GetInstance();
644 this.Icon = MainIcon; //メインフォーム(TweenMain)
645 NotifyIcon1.Icon = NIconAt; //タスクトレイ
646 TabImage.Images.Add(TabIcon); //タブ見出し
648 SettingDialog.Owner = this;;
649 SearchDialog.Owner = this;
650 fltDialog.Owner = this;
651 UrlDialog.Owner = this;
653 _history.Add(new PostingStatus());
656 _reply_to_name = null;
658 //<<<<<<<<<設定関連>>>>>>>>>
665 ThumbnailGenerator.InitializeGenerator();
667 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance.Value;
668 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
669 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
671 Thumbnail.Services.TonTwitterCom.InitializeOAuthToken = x =>
672 x.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
673 this.tw.AccessToken, this.tw.AccessTokenSecret, "", "");
676 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
677 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
680 _fntUnread = _cfgLocal.FontUnread;
681 _clUnread = _cfgLocal.ColorUnread;
682 _fntReaded = _cfgLocal.FontRead;
683 _clReaded = _cfgLocal.ColorRead;
684 _clFav = _cfgLocal.ColorFav;
685 _clOWL = _cfgLocal.ColorOWL;
686 _clRetweet = _cfgLocal.ColorRetweet;
687 _fntDetail = _cfgLocal.FontDetail;
688 _clDetail = _cfgLocal.ColorDetail;
689 _clDetailLink = _cfgLocal.ColorDetailLink;
690 _clDetailBackcolor = _cfgLocal.ColorDetailBackcolor;
691 _clSelf = _cfgLocal.ColorSelf;
692 _clAtSelf = _cfgLocal.ColorAtSelf;
693 _clTarget = _cfgLocal.ColorTarget;
694 _clAtTarget = _cfgLocal.ColorAtTarget;
695 _clAtFromTarget = _cfgLocal.ColorAtFromTarget;
696 _clAtTo = _cfgLocal.ColorAtTo;
697 _clListBackcolor = _cfgLocal.ColorListBackcolor;
698 _clInputBackcolor = _cfgLocal.ColorInputBackcolor;
699 _clInputFont = _cfgLocal.ColorInputFont;
700 _fntInputFont = _cfgLocal.FontInputFont;
702 var fontUIGlobal = this._cfgLocal.FontUIGlobal;
703 if (fontUIGlobal != null)
705 OTBaseForm.GlobalFont = fontUIGlobal;
706 this.Font = fontUIGlobal;
709 // StringFormatオブジェクトへの事前設定
710 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
711 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
712 //sf.FormatFlags = StringFormatFlags.LineLimit; //
713 sfTab.Alignment = StringAlignment.Center;
714 sfTab.LineAlignment = StringAlignment.Center;
717 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
718 SettingDialog.TwitterApiUrl = _cfgCommon.TwitterUrl;
721 if (string.IsNullOrEmpty(_cfgCommon.Token)) _cfgCommon.UserName = "";
722 tw.Initialize(_cfgCommon.Token, _cfgCommon.TokenSecret, _cfgCommon.UserName, _cfgCommon.UserId);
724 SettingDialog.UserAccounts = _cfgCommon.UserAccounts;
726 SettingDialog.TimelinePeriodInt = _cfgCommon.TimelinePeriod;
727 SettingDialog.ReplyPeriodInt = _cfgCommon.ReplyPeriod;
728 SettingDialog.DMPeriodInt = _cfgCommon.DMPeriod;
729 SettingDialog.PubSearchPeriodInt = _cfgCommon.PubSearchPeriod;
730 SettingDialog.UserTimelinePeriodInt = _cfgCommon.UserTimelinePeriod;
731 SettingDialog.ListsPeriodInt = _cfgCommon.ListsPeriod;
733 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
735 if (SettingDialog.TimelinePeriodInt < 15 && SettingDialog.TimelinePeriodInt > 0) SettingDialog.TimelinePeriodInt = 15;
736 if (SettingDialog.ReplyPeriodInt < 15 && SettingDialog.ReplyPeriodInt > 0) SettingDialog.ReplyPeriodInt = 15;
737 if (SettingDialog.DMPeriodInt < 15 && SettingDialog.DMPeriodInt > 0) SettingDialog.DMPeriodInt = 15;
738 if (SettingDialog.PubSearchPeriodInt < 30 && SettingDialog.PubSearchPeriodInt > 0) SettingDialog.PubSearchPeriodInt = 30;
739 if (SettingDialog.UserTimelinePeriodInt < 15 && SettingDialog.UserTimelinePeriodInt > 0) SettingDialog.UserTimelinePeriodInt = 15;
740 if (SettingDialog.ListsPeriodInt < 15 && SettingDialog.ListsPeriodInt > 0) SettingDialog.ListsPeriodInt = 15;
743 //起動時読み込み分を既読にするか。trueなら既読として処理
744 SettingDialog.Readed = _cfgCommon.Read;
745 //新着取得時のリストスクロールをするか。trueならスクロールしない
746 ListLockMenuItem.Checked = _cfgCommon.ListLock;
747 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
748 SettingDialog.IconSz = _cfgCommon.IconSize;
750 SettingDialog.Status = _cfgLocal.StatusText;
752 SettingDialog.UnreadManage = _cfgCommon.UnreadManage;
754 SettingDialog.PlaySound = _cfgCommon.PlaySound;
755 PlaySoundMenuItem.Checked = SettingDialog.PlaySound;
756 this.PlaySoundFileMenuItem.Checked = SettingDialog.PlaySound;
757 //片思い表示。trueなら片思い表示する
758 SettingDialog.OneWayLove = _cfgCommon.OneWayLove;
760 SettingDialog.FontUnread = _fntUnread;
761 SettingDialog.ColorUnread = _clUnread;
762 SettingDialog.FontReaded = _fntReaded;
763 SettingDialog.ColorReaded = _clReaded;
764 SettingDialog.ColorFav = _clFav;
765 SettingDialog.ColorOWL = _clOWL;
766 SettingDialog.ColorRetweet = _clRetweet;
767 SettingDialog.FontDetail = _fntDetail;
768 SettingDialog.ColorDetail = _clDetail;
769 SettingDialog.ColorDetailLink = _clDetailLink;
770 SettingDialog.ColorDetailBackcolor = _clDetailBackcolor;
771 SettingDialog.ColorSelf = _clSelf;
772 SettingDialog.ColorAtSelf = _clAtSelf;
773 SettingDialog.ColorTarget = _clTarget;
774 SettingDialog.ColorAtTarget = _clAtTarget;
775 SettingDialog.ColorAtFromTarget = _clAtFromTarget;
776 SettingDialog.ColorAtTo = _clAtTo;
777 SettingDialog.ColorListBackcolor = _clListBackcolor;
778 SettingDialog.ColorInputBackcolor = _clInputBackcolor;
779 SettingDialog.ColorInputFont = _clInputFont;
780 SettingDialog.FontInputFont = _fntInputFont;
782 SettingDialog.NameBalloon = _cfgCommon.NameBalloon;
783 SettingDialog.PostCtrlEnter = _cfgCommon.PostCtrlEnter;
784 SettingDialog.PostShiftEnter = _cfgCommon.PostShiftEnter;
786 SettingDialog.CountApi = _cfgCommon.CountApi;
787 SettingDialog.CountApiReply = _cfgCommon.CountApiReply;
788 if (SettingDialog.CountApi < 20 || SettingDialog.CountApi > 200) SettingDialog.CountApi = 60;
789 if (SettingDialog.CountApiReply < 20 || SettingDialog.CountApiReply > 200) SettingDialog.CountApiReply = 40;
791 SettingDialog.BrowserPath = _cfgLocal.BrowserPath;
792 SettingDialog.PostAndGet = _cfgCommon.PostAndGet;
793 SettingDialog.UseRecommendStatus = _cfgLocal.UseRecommendStatus;
794 SettingDialog.DispUsername = _cfgCommon.DispUsername;
795 SettingDialog.CloseToExit = _cfgCommon.CloseToExit;
796 SettingDialog.MinimizeToTray = _cfgCommon.MinimizeToTray;
797 SettingDialog.DispLatestPost = _cfgCommon.DispLatestPost;
798 SettingDialog.SortOrderLock = _cfgCommon.SortOrderLock;
799 SettingDialog.ViewTabBottom = _cfgCommon.ViewTabBottom;
800 SettingDialog.TinyUrlResolve = _cfgCommon.TinyUrlResolve;
802 SettingDialog.SelectedProxyType = _cfgLocal.ProxyType;
803 SettingDialog.ProxyAddress = _cfgLocal.ProxyAddress;
804 SettingDialog.ProxyPort = _cfgLocal.ProxyPort;
805 SettingDialog.ProxyUser = _cfgLocal.ProxyUser;
806 SettingDialog.ProxyPassword = _cfgLocal.ProxyPassword;
808 SettingDialog.StartupVersion = _cfgCommon.StartupVersion;
809 SettingDialog.StartupFollowers = _cfgCommon.StartupFollowers;
810 SettingDialog.RestrictFavCheck = _cfgCommon.RestrictFavCheck;
811 SettingDialog.AlwaysTop = _cfgCommon.AlwaysTop;
812 SettingDialog.UrlConvertAuto = false;
813 //SettingDialog.UrlConvertAuto = _cfgCommon.UrlConvertAuto;
815 SettingDialog.UseUnreadStyle = _cfgCommon.UseUnreadStyle;
816 SettingDialog.DefaultTimeOut = _cfgCommon.DefaultTimeOut;
817 SettingDialog.RetweetNoConfirm = _cfgCommon.RetweetNoConfirm;
818 SettingDialog.PlaySound = _cfgCommon.PlaySound;
819 SettingDialog.DateTimeFormat = _cfgCommon.DateTimeFormat;
820 SettingDialog.LimitBalloon = _cfgCommon.LimitBalloon;
821 SettingDialog.EventNotifyEnabled = _cfgCommon.EventNotifyEnabled;
822 SettingDialog.EventNotifyFlag = _cfgCommon.EventNotifyFlag;
823 SettingDialog.IsMyEventNotifyFlag = _cfgCommon.IsMyEventNotifyFlag;
824 SettingDialog.ForceEventNotify = _cfgCommon.ForceEventNotify;
825 SettingDialog.FavEventUnread = _cfgCommon.FavEventUnread;
826 SettingDialog.TranslateLanguage = _cfgCommon.TranslateLanguage;
827 SettingDialog.EventSoundFile = _cfgCommon.EventSoundFile;
829 //廃止サービスが選択されていた場合bit.lyへ読み替え
830 if (_cfgCommon.AutoShortUrlFirst < 0)
831 _cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
833 SettingDialog.AutoShortUrlFirst = _cfgCommon.AutoShortUrlFirst;
834 SettingDialog.TabIconDisp = _cfgCommon.TabIconDisp;
835 SettingDialog.ReplyIconState = _cfgCommon.ReplyIconState;
836 SettingDialog.ReadOwnPost = _cfgCommon.ReadOwnPost;
837 SettingDialog.GetFav = _cfgCommon.GetFav;
838 SettingDialog.ReadOldPosts = _cfgCommon.ReadOldPosts;
839 SettingDialog.BitlyUser = _cfgCommon.BilyUser;
840 SettingDialog.BitlyPwd = _cfgCommon.BitlyPwd;
841 SettingDialog.ShowGrid = _cfgCommon.ShowGrid;
842 SettingDialog.Language = _cfgCommon.Language;
843 SettingDialog.UseAtIdSupplement = _cfgCommon.UseAtIdSupplement;
844 SettingDialog.UseHashSupplement = _cfgCommon.UseHashSupplement;
845 SettingDialog.PreviewEnable = _cfgCommon.PreviewEnable;
846 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
848 SettingDialog.IsMonospace = _cfgCommon.IsMonospace;
850 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
851 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
853 //Regex statregex = new Regex("^0*");
854 SettingDialog.RecommendStatusText = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
859 if (DateTime.Now.ToString(SettingDialog.DateTimeFormat).Length == 0)
861 // このブロックは絶対に実行されないはず
862 // 変換が成功した場合にLengthが0にならない
863 SettingDialog.DateTimeFormat = "yyyy/MM/dd H:mm:ss";
866 catch (FormatException)
868 // FormatExceptionが発生したら初期値を設定 (=yyyy/MM/dd H:mm:ssとみなされる)
869 SettingDialog.DateTimeFormat = "yyyy/MM/dd H:mm:ss";
872 SettingDialog.Nicoms = _cfgCommon.Nicoms;
873 SettingDialog.HotkeyEnabled = _cfgCommon.HotkeyEnabled;
874 SettingDialog.HotkeyMod = _cfgCommon.HotkeyModifier;
875 SettingDialog.HotkeyKey = _cfgCommon.HotkeyKey;
876 SettingDialog.HotkeyValue = _cfgCommon.HotkeyValue;
878 SettingDialog.BlinkNewMentions = _cfgCommon.BlinkNewMentions;
880 SettingDialog.UseAdditionalCount = _cfgCommon.UseAdditionalCount;
881 SettingDialog.MoreCountApi = _cfgCommon.MoreCountApi;
882 SettingDialog.FirstCountApi = _cfgCommon.FirstCountApi;
883 SettingDialog.SearchCountApi = _cfgCommon.SearchCountApi;
884 SettingDialog.FavoritesCountApi = _cfgCommon.FavoritesCountApi;
885 SettingDialog.UserTimelineCountApi = _cfgCommon.UserTimelineCountApi;
886 SettingDialog.ListCountApi = _cfgCommon.ListCountApi;
888 SettingDialog.UserstreamStartup = _cfgCommon.UserstreamStartup;
889 SettingDialog.UserstreamPeriodInt = _cfgCommon.UserstreamPeriod;
890 SettingDialog.OpenUserTimeline = _cfgCommon.OpenUserTimeline;
891 SettingDialog.ListDoubleClickAction = _cfgCommon.ListDoubleClickAction;
892 SettingDialog.UserAppointUrl = _cfgCommon.UserAppointUrl;
893 SettingDialog.HideDuplicatedRetweets = _cfgCommon.HideDuplicatedRetweets;
895 SettingDialog.EnableImgAzyobuziNet = _cfgCommon.EnableImgAzyobuziNet;
896 SettingDialog.ImgAzyobuziNetDisabledInDM = _cfgCommon.ImgAzyobuziNetDisabledInDM;
897 SettingDialog.MapThumbnailProvider = _cfgCommon.MapThumbnailProvider;
898 SettingDialog.MapThumbnailHeight = _cfgCommon.MapThumbnailHeight;
899 SettingDialog.MapThumbnailWidth = _cfgCommon.MapThumbnailWidth;
900 SettingDialog.MapThumbnailZoom = _cfgCommon.MapThumbnailZoom;
901 SettingDialog.IsListStatusesIncludeRts = _cfgCommon.IsListsIncludeRts;
902 SettingDialog.TabMouseLock = _cfgCommon.TabMouseLock;
903 SettingDialog.IsRemoveSameEvent = _cfgCommon.IsRemoveSameEvent;
904 SettingDialog.IsNotifyUseGrowl = _cfgCommon.IsUseNotifyGrowl;
907 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
908 HashMgr = new HashtagManage(HashSupl,
909 _cfgCommon.HashTags.ToArray(),
910 _cfgCommon.HashSelected,
911 _cfgCommon.HashIsPermanent,
912 _cfgCommon.HashIsHead,
913 _cfgCommon.HashIsNotAddToAtReply);
914 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
919 this.IconCache = new ImageCache(this.http);
921 bool saveRequired = false;
922 bool firstRun = false;
924 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
925 if (string.IsNullOrEmpty(tw.Username))
929 SettingDialog.ShowInTaskbar = true;
931 //設定せずにキャンセルされた場合はプログラム終了
932 if (SettingDialog.ShowDialog(this) == DialogResult.Cancel)
934 Application.Exit(); //強制終了
937 //設定されたが、依然ユーザー名とパスワードが未設定ならプログラム終了
938 if (string.IsNullOrEmpty(tw.Username))
940 Application.Exit(); //強制終了
943 SettingDialog.ShowInTaskbar = false;
947 _fntUnread = SettingDialog.FontUnread;
948 _clUnread = SettingDialog.ColorUnread;
949 _fntReaded = SettingDialog.FontReaded;
950 _clReaded = SettingDialog.ColorReaded;
951 _clFav = SettingDialog.ColorFav;
952 _clOWL = SettingDialog.ColorOWL;
953 _clRetweet = SettingDialog.ColorRetweet;
954 _fntDetail = SettingDialog.FontDetail;
955 _clDetail = SettingDialog.ColorDetail;
956 _clDetailLink = SettingDialog.ColorDetailLink;
957 _clDetailBackcolor = SettingDialog.ColorDetailBackcolor;
958 _clSelf = SettingDialog.ColorSelf;
959 _clAtSelf = SettingDialog.ColorAtSelf;
960 _clTarget = SettingDialog.ColorTarget;
961 _clAtTarget = SettingDialog.ColorAtTarget;
962 _clAtFromTarget = SettingDialog.ColorAtFromTarget;
963 _clAtTo = SettingDialog.ColorAtTo;
964 _clListBackcolor = SettingDialog.ColorListBackcolor;
965 _clInputBackcolor = SettingDialog.ColorInputBackcolor;
966 _clInputFont = SettingDialog.ColorInputFont;
967 _fntInputFont = SettingDialog.FontInputFont;
969 //他の設定項目は、随時設定画面で保持している値を読み出して使用
972 _brsBackColorMine = new SolidBrush(_clSelf);
973 _brsBackColorAt = new SolidBrush(_clAtSelf);
974 _brsBackColorYou = new SolidBrush(_clTarget);
975 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
976 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
977 _brsBackColorAtTo = new SolidBrush(_clAtTo);
978 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
979 _brsBackColorNone = new SolidBrush(_clListBackcolor);
981 InitDetailHtmlFormat();
983 if (SettingDialog.HotkeyEnabled)
986 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
987 if ((SettingDialog.HotkeyMod & Keys.Alt) == Keys.Alt) modKey = modKey | HookGlobalHotkey.ModKeys.Alt;
988 if ((SettingDialog.HotkeyMod & Keys.Control) == Keys.Control) modKey = modKey | HookGlobalHotkey.ModKeys.Ctrl;
989 if ((SettingDialog.HotkeyMod & Keys.Shift) == Keys.Shift) modKey = modKey | HookGlobalHotkey.ModKeys.Shift;
990 if ((SettingDialog.HotkeyMod & Keys.LWin) == Keys.LWin) modKey = modKey | HookGlobalHotkey.ModKeys.Win;
992 _hookGlobalHotkey.RegisterOriginalHotkey(SettingDialog.HotkeyKey, SettingDialog.HotkeyValue, modKey);
996 HttpConnection.InitializeConnection(SettingDialog.DefaultTimeOut,
997 SettingDialog.SelectedProxyType,
998 SettingDialog.ProxyAddress,
999 SettingDialog.ProxyPort,
1000 SettingDialog.ProxyUser,
1001 SettingDialog.ProxyPassword);
1003 tw.RestrictFavCheck = SettingDialog.RestrictFavCheck;
1004 tw.ReadOwnPost = SettingDialog.ReadOwnPost;
1005 ShortUrl.Instance.DisableExpanding = !SettingDialog.TinyUrlResolve;
1006 ShortUrl.Instance.BitlyId = SettingDialog.BitlyUser;
1007 ShortUrl.Instance.BitlyKey = SettingDialog.BitlyPwd;
1008 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
1009 tw.TrackWord = _cfgCommon.TrackWord;
1010 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
1011 tw.AllAtReply = _cfgCommon.AllAtReply;
1012 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
1015 this.CreatePictureServices();
1016 SetImageServiceCombo();
1017 ImageSelectionPanel.Enabled = false;
1019 SelectImageServiceComboItem(_cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
1022 this.ClientSize = _cfgLocal.FormSize;
1023 _mySize = _cfgLocal.FormSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
1024 _myLoc = _cfgLocal.FormLocation;
1026 if (this.WindowState != FormWindowState.Minimized)
1028 this.DesktopLocation = _cfgLocal.FormLocation;
1029 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
1030 bool outOfScreen = true;
1031 if (Screen.AllScreens.Length == 1) //ハングするとの報告
1033 foreach (Screen scr in Screen.AllScreens)
1035 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
1037 outOfScreen = false;
1043 this.DesktopLocation = new Point(0, 0);
1044 _myLoc = this.DesktopLocation;
1048 this.TopMost = SettingDialog.AlwaysTop;
1049 _mySpDis = _cfgLocal.SplitterDistance;
1050 _mySpDis2 = _cfgLocal.StatusTextHeight;
1051 _mySpDis3 = _cfgLocal.PreviewDistance;
1052 if (_mySpDis3 == -1)
1054 _mySpDis3 = _mySize.Width - 150;
1055 if (_mySpDis3 < 1) _mySpDis3 = 50;
1056 _cfgLocal.PreviewDistance = _mySpDis3;
1058 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
1059 //this.Tween_ClientSizeChanged(this, null);
1060 PlaySoundMenuItem.Checked = SettingDialog.PlaySound;
1061 this.PlaySoundFileMenuItem.Checked = SettingDialog.PlaySound;
1063 StatusText.Font = _fntInputFont;
1064 StatusText.ForeColor = _clInputFont;
1066 // NameLabel のフォントを OTBaseForm.GlobalFont に変更
1067 this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
1069 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
1070 if (SettingDialog.UnreadManage == false)
1072 ReadedStripMenuItem.Enabled = false;
1073 UnreadStripMenuItem.Enabled = false;
1076 if (SettingDialog.IsNotifyUseGrowl) gh.RegisterGrowl();
1079 TimerTimeline.AutoReset = true;
1080 TimerTimeline.SynchronizingObject = this;
1082 TimerTimeline.Interval = 1000;
1083 TimerTimeline.Enabled = true;
1086 TimerRefreshIcon.Interval = 200;
1087 TimerRefreshIcon.Enabled = true;
1090 StatusLabel.Text = "";
1091 StatusLabel.AutoToolTip = false;
1092 StatusLabel.ToolTipText = "";
1094 lblLen.Text = GetRestStatusCount(true, false).ToString();
1096 ////////////////////////////////////////////////////////////////////////////////
1097 _statuses.SortOrder = (SortOrder)_cfgCommon.SortOrder;
1098 IdComparerClass.ComparerMode mode = IdComparerClass.ComparerMode.Id;
1099 switch (_cfgCommon.SortColumn)
1101 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1105 mode = IdComparerClass.ComparerMode.Id; //Idソートに読み替え
1108 mode = IdComparerClass.ComparerMode.Nickname;
1111 mode = IdComparerClass.ComparerMode.Data;
1114 mode = IdComparerClass.ComparerMode.Id;
1117 mode = IdComparerClass.ComparerMode.Name;
1120 mode = IdComparerClass.ComparerMode.Source;
1123 _statuses.SortMode = mode;
1124 ////////////////////////////////////////////////////////////////////////////////
1126 ApplyListViewIconSize(SettingDialog.IconSz);
1128 tw.TinyUrlResolve = SettingDialog.TinyUrlResolve;
1130 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1131 StatusLabelUrl.Text = ""; //画面左下のリンク先URL表示部を初期化
1132 NameLabel.Text = ""; //発言詳細部名前ラベル初期化
1133 DateTimeLabel.Text = ""; //発言詳細部日時ラベル初期化
1134 SourceLinkLabel.Text = ""; //Source部分初期化
1136 //<<<<<<<<タブ関連>>>>>>>
1137 //デフォルトタブの存在チェック、ない場合には追加
1138 if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1141 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1143 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1147 tab.TabType = MyCommon.TabUsageType.Home;
1150 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1153 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1155 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1159 tab.TabType = MyCommon.TabUsageType.Mentions;
1162 if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1165 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1167 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1171 tab.TabType = MyCommon.TabUsageType.DirectMessage;
1174 if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1177 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1179 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1183 tab.TabType = MyCommon.TabUsageType.Favorites;
1186 foreach (var tab in _statuses.Tabs.Values)
1188 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1190 tab.TabType = MyCommon.TabUsageType.UserDefined;
1192 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo)) throw new Exception(Properties.Resources.TweenMain_LoadText1);
1195 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1196 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1197 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1198 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1200 if (SettingDialog.MinimizeToTray == false || this.WindowState != FormWindowState.Minimized)
1202 this.Visible = true;
1204 _curTab = ListTab.SelectedTab;
1206 _curList = (DetailsListView)_curTab.Tag;
1207 SetMainWindowTitle();
1208 SetNotifyIconText();
1210 if (SettingDialog.TabIconDisp)
1212 ListTab.DrawMode = TabDrawMode.Normal;
1216 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1217 ListTab.DrawItem += ListTab_DrawItem;
1218 ListTab.ImageList = null;
1221 _ignoreConfigSave = false;
1222 this.TweenMain_Resize(null, null);
1223 if (saveRequired) SaveConfigsAll(false);
1227 tw.VerifyCredentials();
1228 foreach (UserAccount ua in _cfgCommon.UserAccounts)
1230 if (ua.Username.ToLower() == tw.Username.ToLower())
1232 ua.UserId = tw.UserId;
1237 foreach (UserAccount ua in SettingDialog.UserAccounts)
1239 if (ua.UserId == 0 && ua.Username.ToLower() == tw.Username.ToLower())
1241 ua.UserId = tw.UserId;
1248 // 初回起動時だけ右下のメニューを目立たせる
1249 HashStripSplitButton.ShowDropDown();
1256 private void InitDetailHtmlFormat()
1258 if (SettingDialog.IsMonospace)
1260 detailHtmlFormatHeader = detailHtmlFormatMono1;
1261 detailHtmlFormatFooter = detailHtmlFormatMono7;
1265 detailHtmlFormatHeader = detailHtmlFormat1;
1266 detailHtmlFormatFooter = detailHtmlFormat7;
1268 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();
1269 if (SettingDialog.IsMonospace)
1271 detailHtmlFormatHeader += detailHtmlFormatMono6;
1275 detailHtmlFormatHeader += detailHtmlFormat6;
1279 private void CreatePictureServices()
1281 if (this.pictureService != null) this.pictureService.Clear();
1282 this.pictureService = null;
1283 this.pictureService = new Dictionary<string, IMultimediaShareService> {
1284 {"TwitPic", new TwitPic(tw)},
1285 {"img.ly", new imgly(tw)},
1286 {"yfrog", new yfrog(tw)},
1287 {"Twitter", new TwitterPhoto(tw)},
1288 {"ついっぷるフォト", new TwipplePhoto(tw)},
1289 {"Imgur", new Imgur(tw)},
1293 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1298 txt = ListTab.TabPages[e.Index].Text;
1305 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1306 if (e.State == DrawItemState.Selected)
1308 e.DrawFocusRectangle();
1313 if (_statuses.Tabs[txt].UnreadCount > 0)
1316 fore = System.Drawing.SystemBrushes.ControlText;
1320 fore = System.Drawing.SystemBrushes.ControlText;
1322 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1325 private void LoadConfig()
1327 _cfgCommon = SettingCommon.Load();
1328 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1330 _cfgCommon.UserAccounts = new List<UserAccount>();
1331 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1333 UserAccount account = new UserAccount();
1334 account.Username = _cfgCommon.UserName;
1335 account.UserId = _cfgCommon.UserId;
1336 account.Token = _cfgCommon.Token;
1337 account.TokenSecret = _cfgCommon.TokenSecret;
1339 _cfgCommon.UserAccounts.Add(account);
1342 _cfgLocal = SettingLocal.Load();
1343 List<TabClass> tabs = SettingTabs.Load().Tabs;
1344 foreach (TabClass tb in tabs)
1348 _statuses.Tabs.Add(tb.TabName, tb);
1352 tb.TabName = _statuses.GetUniqueTabName();
1353 _statuses.Tabs.Add(tb.TabName, tb);
1356 if (_statuses.Tabs.Count == 0)
1358 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1359 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1360 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1361 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1365 private void TimerInterval_Changed(object sender, AppendSettingDialog.IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1367 if (!TimerTimeline.Enabled) return;
1371 private AppendSettingDialog.IntervalChangedEventArgs ResetTimers = new AppendSettingDialog.IntervalChangedEventArgs();
1373 private static int homeCounter = 0;
1374 private static int mentionCounter = 0;
1375 private static int dmCounter = 0;
1376 private static int pubSearchCounter = 0;
1377 private static int userTimelineCounter = 0;
1378 private static int listsCounter = 0;
1379 private static int usCounter = 0;
1380 private static int ResumeWait = 0;
1381 private static int refreshFollowers = 0;
1383 private void TimerTimeline_Elapsed(object sender, EventArgs e)
1385 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1386 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1387 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1388 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1389 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1390 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1391 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1392 Interlocked.Increment(ref refreshFollowers);
1395 if (ResetTimers.Timeline || homeCounter <= 0 && SettingDialog.TimelinePeriodInt > 0)
1397 Interlocked.Exchange(ref homeCounter, SettingDialog.TimelinePeriodInt);
1398 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline) GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
1399 ResetTimers.Timeline = false;
1401 if (ResetTimers.Reply || mentionCounter <= 0 && SettingDialog.ReplyPeriodInt > 0)
1403 Interlocked.Exchange(ref mentionCounter, SettingDialog.ReplyPeriodInt);
1404 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply) GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
1405 ResetTimers.Reply = false;
1407 if (ResetTimers.DirectMessage || dmCounter <= 0 && SettingDialog.DMPeriodInt > 0)
1409 Interlocked.Exchange(ref dmCounter, SettingDialog.DMPeriodInt);
1410 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage) GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
1411 ResetTimers.DirectMessage = false;
1413 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && SettingDialog.PubSearchPeriodInt > 0)
1415 Interlocked.Exchange(ref pubSearchCounter, SettingDialog.PubSearchPeriodInt);
1416 if (!ResetTimers.PublicSearch) GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, "");
1417 ResetTimers.PublicSearch = false;
1419 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && SettingDialog.UserTimelinePeriodInt > 0)
1421 Interlocked.Exchange(ref userTimelineCounter, SettingDialog.UserTimelinePeriodInt);
1422 if (!ResetTimers.UserTimeline) GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, "");
1423 ResetTimers.UserTimeline = false;
1425 if (ResetTimers.Lists || listsCounter <= 0 && SettingDialog.ListsPeriodInt > 0)
1427 Interlocked.Exchange(ref listsCounter, SettingDialog.ListsPeriodInt);
1428 if (!ResetTimers.Lists) GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, "");
1429 ResetTimers.Lists = false;
1431 if (ResetTimers.UserStream || usCounter <= 0 && SettingDialog.UserstreamPeriodInt > 0)
1433 Interlocked.Exchange(ref usCounter, SettingDialog.UserstreamPeriodInt);
1434 if (this._isActiveUserstream) RefreshTimeline(true);
1435 ResetTimers.UserStream = false;
1437 if (refreshFollowers > 6 * 3600)
1439 Interlocked.Exchange(ref refreshFollowers, 0);
1440 doGetFollowersMenu();
1441 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, 0, "");
1442 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
1443 if (InvokeRequired && !IsDisposed) this.Invoke(new MethodInvoker(this.TrimPostChain));
1447 Interlocked.Increment(ref ResumeWait);
1448 if (ResumeWait > 30)
1451 Interlocked.Exchange(ref ResumeWait, 0);
1452 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
1453 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
1454 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
1455 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, "");
1456 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, "");
1457 GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, "");
1458 doGetFollowersMenu();
1459 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
1460 if (InvokeRequired && !IsDisposed) this.Invoke(new MethodInvoker(this.TrimPostChain));
1465 private void RefreshTimeline(bool isUserStream)
1467 if (isUserStream) this.RefreshTasktrayIcon(true);
1469 int smode = -1; //-1:制御しない,-2:最新へ,その他:topitem使用
1470 long topId = GetScrollPos(ref smode);
1471 int befCnt = _curList.VirtualListSize;
1474 Dictionary<string, long[]> selId = new Dictionary<string, long[]>();
1475 Dictionary<string, long[]> focusedId = new Dictionary<string, long[]>();
1476 SaveSelectedStatus(selId, focusedId);
1479 int dmCount = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount;
1482 PostClass[] notifyPosts = null;
1483 string soundFile = "";
1485 bool isMention = false;
1486 bool isDelete = false;
1487 addCount = _statuses.SubmitUpdate(ref soundFile, ref notifyPosts, ref isMention, ref isDelete, isUserStream);
1489 if (MyCommon._endingFlag) return;
1494 foreach (TabPage tab in ListTab.TabPages)
1496 DetailsListView lst = (DetailsListView)tab.Tag;
1497 TabClass tabInfo = _statuses.Tabs[tab.Text];
1498 using (ControlTransaction.Update(lst))
1500 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1502 if (lst.Equals(_curList))
1504 this.PurgeListViewItemCache();
1508 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1514 this.SelectListItem(lst,
1515 _statuses.IndexOf(tab.Text, selId[tab.Text]),
1516 _statuses.IndexOf(tab.Text, focusedId[tab.Text]));
1519 if (tabInfo.UnreadCount > 0)
1520 if (SettingDialog.TabIconDisp)
1521 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1523 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
1527 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1536 if (befCnt != _curList.VirtualListSize)
1542 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(0);
1546 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(_curList.VirtualListSize - 1);
1553 if (_curList.VirtualListSize > 0 && _statuses.IndexOf(_curTab.Text, topId) > -1)
1555 _curList.EnsureVisible(_curList.VirtualListSize - 1);
1556 _curList.EnsureVisible(_statuses.IndexOf(_curTab.Text, topId));
1562 catch (Exception ex)
1564 ex.Data["Msg"] = "Ref2";
1570 NotifyNewPosts(notifyPosts,
1573 isMention || dmCount != _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount);
1575 SetMainWindowTitle();
1576 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
1578 HashSupl.AddRangeItem(tw.GetHashList());
1582 private long GetScrollPos(ref int smode)
1585 if (_curList != null && _curTab != null && _curList.VirtualListSize > 0)
1587 if (_statuses.SortMode == IdComparerClass.ComparerMode.Id)
1589 if (_statuses.SortOrder == SortOrder.Ascending)
1592 if (ListLockMenuItem.Checked)
1597 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1602 //最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1604 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1); //一番下
1605 if (_item == null) _item = _curList.Items[_curList.VirtualListSize - 1];
1606 if (_item.Index == _curList.VirtualListSize - 1)
1613 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1621 if (ListLockMenuItem.Checked)
1624 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1629 //最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1632 _item = _curList.GetItemAt(0, 10); //一番上
1633 if (_item == null) _item = _curList.Items[0];
1634 if (_item.Index == 0)
1640 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1649 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1660 private void SaveSelectedStatus(Dictionary<string, long[]> selId, Dictionary<string, long[]> focusedId)
1662 if (MyCommon._endingFlag) return;
1663 foreach (TabPage tab in ListTab.TabPages)
1665 DetailsListView lst = (DetailsListView)tab.Tag;
1666 if (lst.SelectedIndices.Count > 0 && lst.SelectedIndices.Count < 61)
1668 selId.Add(tab.Text, _statuses.GetId(tab.Text, lst.SelectedIndices));
1672 selId.Add(tab.Text, new long[1] {-2});
1675 var fIds = new long[2]; // 0 = focus, 1 = selection mark
1676 var item = lst.FocusedItem;
1677 fIds[0] = (item != null) ? _statuses.GetId(tab.Text, item.Index) : -2;
1678 var mIdx = lst.SelectionMark;
1679 fIds[1] = (mIdx > -1) ? _statuses.GetId(tab.Text, mIdx) : -2;
1680 focusedId.Add(tab.Text, fIds);
1685 private bool BalloonRequired()
1687 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1688 ev.Eventtype = MyCommon.EVENTTYPE.None;
1690 return BalloonRequired(ev);
1693 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1695 return SettingDialog.EventNotifyEnabled && (type & SettingDialog.EventNotifyFlag) != 0 || type == MyCommon.EVENTTYPE.None;
1698 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1700 return (ev.Eventtype & SettingDialog.IsMyEventNotifyFlag) != 0 ? true : !ev.IsMe;
1703 private bool BalloonRequired(Twitter.FormattedEvent ev)
1706 IsEventNotifyAsEventType(ev.Eventtype) && IsMyEventNotityAsEventType(ev) &&
1707 (NewPostPopMenuItem.Checked || (SettingDialog.ForceEventNotify && ev.Eventtype != MyCommon.EVENTTYPE.None)) &&
1711 SettingDialog.LimitBalloon &&
1713 this.WindowState == FormWindowState.Minimized ||
1715 Form.ActiveForm == null
1718 !SettingDialog.LimitBalloon
1721 !Win32Api.IsScreenSaverRunning())
1731 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1733 if (notifyPosts != null &&
1734 notifyPosts.Length > 0 &&
1735 this.SettingDialog.ReadOwnPost &&
1736 notifyPosts.All((post) => { return post.UserId == tw.UserId || post.ScreenName == tw.Username; }))
1742 if (BalloonRequired())
1744 if (notifyPosts != null && notifyPosts.Length > 0)
1746 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1747 if (SettingDialog.IsNotifyUseGrowl)
1749 StringBuilder sb = new StringBuilder();
1753 foreach (PostClass post in notifyPosts)
1755 if (!(notifyPosts.Length > 3))
1761 if (post.IsReply && !post.IsExcludeReply) reply = true;
1762 if (post.IsDm) dm = true;
1763 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1764 switch (SettingDialog.NameBalloon)
1766 case MyCommon.NameBalloonEnum.UserID:
1767 sb.Append(post.ScreenName).Append(" : ");
1769 case MyCommon.NameBalloonEnum.NickName:
1770 sb.Append(post.Nickname).Append(" : ");
1773 sb.Append(post.TextFromApi);
1774 if (notifyPosts.Length > 3)
1776 if (notifyPosts.Last() != post) continue;
1779 StringBuilder title = new StringBuilder();
1780 GrowlHelper.NotifyType nt;
1781 if (SettingDialog.DispUsername)
1783 title.Append(tw.Username);
1784 title.Append(" - ");
1792 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1793 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1794 title.Append(Application.ProductName);
1795 title.Append(" [DM] ");
1796 title.Append(Properties.Resources.RefreshDirectMessageText1);
1798 title.Append(addCount);
1799 title.Append(Properties.Resources.RefreshDirectMessageText2);
1800 nt = GrowlHelper.NotifyType.DirectMessage;
1804 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1805 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1806 title.Append(Application.ProductName);
1807 title.Append(" [Reply!] ");
1808 title.Append(Properties.Resources.RefreshTimelineText1);
1810 title.Append(addCount);
1811 title.Append(Properties.Resources.RefreshTimelineText2);
1812 nt = GrowlHelper.NotifyType.Reply;
1816 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1817 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1818 title.Append(Application.ProductName);
1820 title.Append(Properties.Resources.RefreshTimelineText1);
1822 title.Append(addCount);
1823 title.Append(Properties.Resources.RefreshTimelineText2);
1824 nt = GrowlHelper.NotifyType.Notify;
1826 string bText = sb.ToString();
1827 if (string.IsNullOrEmpty(bText)) return;
1829 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1830 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1835 StringBuilder sb = new StringBuilder();
1838 foreach (PostClass post in notifyPosts)
1840 if (post.IsReply && !post.IsExcludeReply) reply = true;
1841 if (post.IsDm) dm = true;
1842 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1843 switch (SettingDialog.NameBalloon)
1845 case MyCommon.NameBalloonEnum.UserID:
1846 sb.Append(post.ScreenName).Append(" : ");
1848 case MyCommon.NameBalloonEnum.NickName:
1849 sb.Append(post.Nickname).Append(" : ");
1852 sb.Append(post.TextFromApi);
1855 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1856 StringBuilder title = new StringBuilder();
1858 if (SettingDialog.DispUsername)
1860 title.Append(tw.Username);
1861 title.Append(" - ");
1869 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1870 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1871 ntIcon = ToolTipIcon.Warning;
1872 title.Append(Application.ProductName);
1873 title.Append(" [DM] ");
1874 title.Append(Properties.Resources.RefreshDirectMessageText1);
1876 title.Append(addCount);
1877 title.Append(Properties.Resources.RefreshDirectMessageText2);
1881 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1882 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1883 ntIcon = ToolTipIcon.Warning;
1884 title.Append(Application.ProductName);
1885 title.Append(" [Reply!] ");
1886 title.Append(Properties.Resources.RefreshTimelineText1);
1888 title.Append(addCount);
1889 title.Append(Properties.Resources.RefreshTimelineText2);
1893 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1894 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1895 ntIcon = ToolTipIcon.Info;
1896 title.Append(Application.ProductName);
1898 title.Append(Properties.Resources.RefreshTimelineText1);
1900 title.Append(addCount);
1901 title.Append(Properties.Resources.RefreshTimelineText2);
1903 string bText = sb.ToString();
1904 if (string.IsNullOrEmpty(bText)) return;
1905 //NotifyIcon1.BalloonTipText = sb.ToString();
1906 //NotifyIcon1.ShowBalloonTip(500);
1907 NotifyIcon1.BalloonTipTitle = title.ToString();
1908 NotifyIcon1.BalloonTipText = bText;
1909 NotifyIcon1.BalloonTipIcon = ntIcon;
1910 NotifyIcon1.ShowBalloonTip(500);
1916 if (!_initial && SettingDialog.PlaySound && !string.IsNullOrEmpty(soundFile))
1920 string dir = Application.StartupPath;
1921 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1923 dir = Path.Combine(dir, "Sounds");
1925 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1935 //mentions新着時に画面ブリンク
1936 if (!_initial && SettingDialog.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1938 Win32Api.FlashMyWindow(this.Handle, Win32Api.FlashSpecification.FlashTray, 3);
1942 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1944 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1946 _curItemIndex = _curList.SelectedIndices[0];
1947 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1951 _curPost = GetCurTabPost(_curItemIndex);
1953 catch (ArgumentException)
1958 this.PushSelectPostChain();
1960 if (SettingDialog.UnreadManage) _statuses.SetReadAllTab(true, _curTab.Text, _curItemIndex);
1962 ChangeCacheStyleRead(true, _curItemIndex, _curTab); //既読へ(フォント、文字色)
1968 private void ChangeCacheStyleRead(bool Read, int Index, TabPage Tab)
1970 //Read:true=既読 false=未読
1971 //未読管理していなかったら既読として扱う
1972 if (!_statuses.Tabs[_curTab.Text].UnreadManage ||
1973 !SettingDialog.UnreadManage) Read = true;
1976 ListViewItem itm = null;
1977 PostClass post = null;
1979 if (Tab.Equals(this._curTab))
1981 this.TryGetListViewItemCache(Index, out itm, out post);
1984 if (itm == null || post == null)
1986 itm = ((DetailsListView)Tab.Tag).Items[Index];
1987 post = _statuses[Tab.Text, Index];
1990 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)Tab.Tag));
1993 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
2000 Item.SubItems[5].Text = "";
2005 Item.SubItems[5].Text = "★";
2011 else if (Post.RetweetedId != null)
2013 else if (Post.IsOwl && (Post.IsDm || SettingDialog.OneWayLove))
2015 else if (Read || !SettingDialog.UseUnreadStyle)
2020 if (DList == null || Item.Index == -1)
2022 Item.ForeColor = cl;
2023 if (SettingDialog.UseUnreadStyle)
2029 if (SettingDialog.UseUnreadStyle)
2030 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2032 DList.ChangeItemForeColor(Item.Index, cl);
2033 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2037 private void ColorizeList()
2039 //Index:更新対象のListviewItem.Index。Colorを返す。
2040 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2043 _post = _anchorPost;
2047 if (_post == null) return;
2049 var itemColors = new Color[] { };
2052 this.itemCacheLock.EnterReadLock();
2055 if (this._itemCache == null) return;
2058 from i in Enumerable.Range(0, this._itemCache.Length)
2059 select this.JudgeColor(_post, this._postCache[i]);
2061 itemColors = query.ToArray();
2062 itemIndex = _itemCacheIndex;
2064 finally { this.itemCacheLock.ExitReadLock(); }
2066 if (itemIndex < 0) return;
2068 foreach (var backColor in itemColors)
2070 // この処理中に MyList_CacheVirtualItems が呼ばれることがあるため、
2071 // 同一スレッド内での二重ロックを避けるためにロックの外で実行する必要がある
2072 _curList.ChangeItemBackColor(itemIndex++, backColor);
2076 private void ColorizeList(ListViewItem Item, int Index)
2078 //Index:更新対象のListviewItem.Index。Colorを返す。
2079 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2082 _post = _anchorPost;
2086 PostClass tPost = GetCurTabPost(Index);
2088 if (_post == null) return;
2090 if (Item.Index == -1)
2091 Item.BackColor = JudgeColor(_post, tPost);
2093 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2096 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2099 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2102 else if (TargetPost.IsMe)
2105 else if (TargetPost.IsReply)
2108 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLower()))
2110 cl = _clAtFromTarget;
2111 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLower()))
2114 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2119 cl = _clListBackcolor;
2124 private async void PostButton_Click(object sender, EventArgs e)
2126 if (StatusText.Text.Trim().Length == 0)
2128 if (!ImageSelectionPanel.Enabled)
2135 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2137 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2139 MessageBoxButtons.YesNoCancel,
2140 MessageBoxIcon.Question);
2143 case DialogResult.Yes:
2144 doReTweetOfficial(false);
2145 StatusText.Text = "";
2147 case DialogResult.Cancel:
2152 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
2154 if (SettingDialog.Nicoms)
2156 StatusText.SelectionStart = StatusText.Text.Length;
2157 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2159 //if (SettingDialog.UrlConvertAuto)
2161 // StatusText.SelectionStart = StatusText.Text.Length;
2162 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2164 //else if (SettingDialog.Nicoms)
2166 // StatusText.SelectionStart = StatusText.Text.Length;
2167 // UrlConvert(UrlConverter.Nicoms);
2169 StatusText.SelectionStart = StatusText.Text.Length;
2170 GetWorkerArg args = new GetWorkerArg();
2173 args.type = MyCommon.WORKERTYPE.PostMessage;
2174 CheckReplyTo(StatusText.Text);
2177 int adjustCount = 0;
2178 string tmpStatus = StatusText.Text.Trim();
2179 if (ToolStripMenuItemApiCommandEvasion.Checked)
2182 if (Regex.IsMatch(tmpStatus,
2183 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2184 RegexOptions.IgnoreCase)
2185 && tmpStatus.EndsWith(" .") == false) adjustCount += 2;
2188 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2191 adjustCount += Regex.Matches(tmpStatus, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+").Count;
2194 bool isCutOff = false;
2195 bool isRemoveFooter = MyCommon.IsKeyDown(Keys.Shift);
2196 if (StatusText.Multiline && !SettingDialog.PostCtrlEnter)
2198 //複数行でEnter投稿の場合、Ctrlも押されていたらフッタ付加しない
2199 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2201 if (SettingDialog.PostShiftEnter)
2203 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2205 if (!isRemoveFooter && (StatusText.Text.Contains("RT @") || StatusText.Text.Contains("QT @")))
2207 isRemoveFooter = true;
2209 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2211 if (MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
2214 //if (!SettingDialog.UrlConvertAuto) UrlConvertAutoToolStripMenuItem_Click(null, null);
2215 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2217 isRemoveFooter = true;
2228 if (StatusText.Text.StartsWith("D ") || StatusText.Text.StartsWith("d "))
2236 if (HashMgr.IsNotAddToAtReply)
2238 if (!string.IsNullOrEmpty(HashMgr.UseHash) && _reply_to_id == null && string.IsNullOrEmpty(_reply_to_name))
2241 header = HashMgr.UseHash + " ";
2243 footer = " " + HashMgr.UseHash;
2248 if (!string.IsNullOrEmpty(HashMgr.UseHash))
2251 header = HashMgr.UseHash + " ";
2253 footer = " " + HashMgr.UseHash;
2256 if (!isRemoveFooter)
2258 if (SettingDialog.UseRecommendStatus)
2260 footer += SettingDialog.RecommendStatusText;
2262 // テキストボックスに入力されている文字列を使用する
2263 footer += " " + SettingDialog.Status.Trim();
2266 args.status.status = header + StatusText.Text + footer;
2268 if (ToolStripMenuItemApiCommandEvasion.Checked)
2271 if (Regex.IsMatch(args.status.status,
2272 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2273 RegexOptions.IgnoreCase)
2274 && args.status.status.EndsWith(" .") == false) args.status.status += " .";
2277 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2280 Match mc2 = Regex.Match(args.status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+");
2281 if (mc2.Success) args.status.status = Regex.Replace(args.status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
2284 if (IdeographicSpaceToSpaceToolStripMenuItem.Checked)
2286 // 文中の全角スペースを半角スペース1個にする
2287 args.status.status = args.status.status.Replace(" ", " ");
2290 if (isCutOff && args.status.status.Length > 140)
2292 args.status.status = args.status.status.Substring(0, 140);
2293 string AtId = @"(@|@)[a-z0-9_/]+$";
2294 string HashTag = @"(^|[^0-9A-Z&\/\?]+)(#|#)([0-9A-Z_]*[A-Z_]+)$";
2295 string Url = @"https?:\/\/[a-z0-9!\*'\(\);:&=\+\$\/%#\[\]\-_\.,~?]+$"; //簡易判定
2296 string pattern = string.Format("({0})|({1})|({2})", AtId, HashTag, Url);
2297 Match mc = Regex.Match(args.status.status, pattern, RegexOptions.IgnoreCase);
2300 //さらに@ID、ハッシュタグ、URLと推測される文字列をカットする
2301 args.status.status = args.status.status.Substring(0, 140 - mc.Value.Length);
2303 if (MessageBox.Show(args.status.status, "Post or Cancel?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return;
2306 args.status.inReplyToId = _reply_to_id;
2307 args.status.inReplyToName = _reply_to_name;
2308 if (ImageSelectionPanel.Visible)
2311 if (!TryGetSelectedMedia(out args.status.imageService, out args.status.imagePath))
2317 _reply_to_id = null;
2318 _reply_to_name = null;
2319 StatusText.Text = "";
2320 _history.Add(new PostingStatus());
2321 _hisIdx = _history.Count - 1;
2322 if (!ToolStripFocusLockMenuItem.Checked)
2323 ((Control)ListTab.SelectedTab.Tag).Focus();
2324 urlUndoBuffer = null;
2325 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2328 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2330 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeUriString(StatusText.Text.Substring(7)));
2331 await this.OpenUriAsync(tmp);
2335 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2337 MyCommon._endingFlag = true;
2341 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2343 if (!SettingDialog.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2345 //_endingFlag=false:フォームの×ボタン
2347 this.Visible = false;
2351 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2352 _ignoreConfigSave = true;
2353 MyCommon._endingFlag = true;
2354 TimerTimeline.Enabled = false;
2355 TimerRefreshIcon.Enabled = false;
2359 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2361 this.Visible = true;
2362 if (this.WindowState == FormWindowState.Minimized)
2364 this.WindowState = FormWindowState.Normal;
2367 this.BringToFront();
2370 private static int errorCount = 0;
2372 private static bool CheckAccountValid()
2374 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2380 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2389 private void GetTimelineWorker_DoWork(object sender, DoWorkEventArgs e)
2391 BackgroundWorker bw = (BackgroundWorker)sender;
2392 if (bw.CancellationPending || MyCommon._endingFlag)
2398 Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
2400 MyApplication.InitCulture();
2403 GetWorkerResult rslt = new GetWorkerResult();
2405 bool read = !SettingDialog.UnreadManage;
2406 if (_initial && SettingDialog.UnreadManage) read = SettingDialog.Readed;
2408 GetWorkerArg args = (GetWorkerArg)e.Argument;
2410 if (!CheckAccountValid())
2412 rslt.retMsg = "Auth error. Check your account";
2413 rslt.type = MyCommon.WORKERTYPE.ErrorState; //エラー表示のみ行ない、後処理キャンセル
2414 rslt.tName = args.tName;
2419 bw.ReportProgress(0, ""); //Notifyアイコンアニメーション開始
2423 case MyCommon.WORKERTYPE.Timeline:
2424 case MyCommon.WORKERTYPE.Reply:
2425 bw.ReportProgress(50, MakeStatusMessage(args, false));
2426 ret = tw.GetTimelineApi(read, args.type, args.page == -1, _initial);
2428 if (string.IsNullOrEmpty(ret) && args.type == MyCommon.WORKERTYPE.Timeline && SettingDialog.ReadOldPosts)
2429 _statuses.SetRead();
2431 rslt.addCount = _statuses.DistributePosts();
2433 case MyCommon.WORKERTYPE.DirectMessegeRcv: //送信分もまとめて取得
2434 bw.ReportProgress(50, MakeStatusMessage(args, false));
2435 ret = tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, args.page == -1);
2436 if (string.IsNullOrEmpty(ret)) ret = tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, args.page == -1);
2437 rslt.addCount = _statuses.DistributePosts();
2440 case MyCommon.WORKERTYPE.FavAdd:
2444 if (_statuses.Tabs.TryGetValue(args.tName, out tab))
2446 for (int i = 0; i <= args.ids.Count - 1; i++)
2448 var post = tab.Posts[args.ids[i]];
2451 bw.ReportProgress(50, MakeStatusMessage(args, false));
2454 if (post.RetweetedId == null)
2455 ret = tw.PostFavAdd(post.StatusId);
2457 ret = tw.PostFavAdd(post.RetweetedId.Value);
2459 if (ret.Length == 0)
2461 args.sIds.Add(post.StatusId);
2462 post.IsFav = true; //リスト再描画必要
2463 _favTimestamps.Add(DateTime.Now);
2464 if (string.IsNullOrEmpty(post.RelTabName))
2466 //検索,リストUserTimeline.Relatedタブからのfavは、favタブへ追加せず。それ以外は追加
2467 _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).Add(post.StatusId, post.IsRead, false);
2471 //検索,リスト,UserTimeline.Relatedタブからのfavで、TLでも取得済みならfav反映
2472 if (_statuses.ContainsKey(post.StatusId))
2474 PostClass postTl = _statuses[post.StatusId];
2475 postTl.IsFav = true;
2476 _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).Add(postTl.StatusId, postTl.IsRead, false);
2479 //検索,リスト,UserTimeline,Relatedの各タブに反映
2480 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch | MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.UserTimeline | MyCommon.TabUsageType.Related))
2482 if (tb.Contains(post.StatusId)) tb.Posts[post.StatusId].IsFav = true;
2488 rslt.sIds = args.sIds;
2492 case MyCommon.WORKERTYPE.FavRemove:
2496 if (_statuses.Tabs.TryGetValue(args.tName, out tab))
2498 for (int i = 0; i <= args.ids.Count - 1; i++)
2500 var post = tab.Posts[args.ids[i]];
2503 bw.ReportProgress(50, MakeStatusMessage(args, false));
2506 if (post.RetweetedId == null)
2507 ret = tw.PostFavRemove(post.StatusId);
2509 ret = tw.PostFavRemove(post.RetweetedId.Value);
2511 if (ret.Length == 0)
2513 args.sIds.Add(post.StatusId);
2514 post.IsFav = false; //リスト再描画必要
2515 if (_statuses.ContainsKey(post.StatusId)) _statuses[post.StatusId].IsFav = false;
2516 //検索,リスト,UserTimeline,Relatedの各タブに反映
2517 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch | MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.UserTimeline | MyCommon.TabUsageType.Related))
2519 if (tb.Contains(post.StatusId)) tb.Posts[post.StatusId].IsFav = false;
2525 rslt.sIds = args.sIds;
2529 case MyCommon.WORKERTYPE.PostMessage:
2530 bw.ReportProgress(200);
2531 if (string.IsNullOrEmpty(args.status.imagePath))
2533 ret = tw.PostStatus(args.status.status, args.status.inReplyToId);
2537 ret = this.pictureService[args.status.imageService].Upload(ref args.status.imagePath,
2538 ref args.status.status,
2539 args.status.inReplyToId);
2541 bw.ReportProgress(300);
2542 rslt.status = args.status;
2544 case MyCommon.WORKERTYPE.Retweet:
2545 bw.ReportProgress(200);
2546 for (int i = 0; i <= args.ids.Count - 1; i++)
2548 ret = tw.PostRetweet(args.ids[i], read);
2550 bw.ReportProgress(300);
2552 case MyCommon.WORKERTYPE.Follower:
2553 bw.ReportProgress(50, Properties.Resources.UpdateFollowersMenuItem1_ClickText1);
2556 tw.RefreshFollowerIds();
2558 catch (WebApiException ex) { ret = ex.Message; }
2560 case MyCommon.WORKERTYPE.NoRetweetIds:
2563 tw.RefreshNoRetweetIds();
2565 catch (WebApiException ex) { ret = ex.Message; }
2567 case MyCommon.WORKERTYPE.Configuration:
2570 this.SettingDialog.TwitterConfiguration = tw.ConfigurationApi();
2572 catch (WebApiException ex) { ret = ex.Message; }
2574 case MyCommon.WORKERTYPE.Favorites:
2575 bw.ReportProgress(50, MakeStatusMessage(args, false));
2576 ret = tw.GetFavoritesApi(read, args.type, args.page == -1);
2577 rslt.addCount = _statuses.DistributePosts();
2579 case MyCommon.WORKERTYPE.PublicSearch:
2580 bw.ReportProgress(50, MakeStatusMessage(args, false));
2581 if (string.IsNullOrEmpty(args.tName))
2583 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
2585 //if (!string.IsNullOrEmpty(tb.SearchWords)) ret = tw.GetPhoenixSearch(read, tb, false);
2586 if (!string.IsNullOrEmpty(tb.SearchWords)) ret = tw.GetSearch(read, tb, false);
2591 TabClass tb = _statuses.GetTabByName(args.tName);
2594 //ret = tw.GetPhoenixSearch(read, tb, false);
2595 ret = tw.GetSearch(read, tb, false);
2596 if (string.IsNullOrEmpty(ret) && args.page == -1)
2598 //ret = tw.GetPhoenixSearch(read, tb, true)
2599 ret = tw.GetSearch(read, tb, true);
2604 rslt.addCount = _statuses.DistributePosts();
2606 case MyCommon.WORKERTYPE.UserTimeline:
2607 bw.ReportProgress(50, MakeStatusMessage(args, false));
2609 if (SettingDialog.UseAdditionalCount) count = SettingDialog.UserTimelineCountApi;
2610 if (string.IsNullOrEmpty(args.tName))
2612 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
2614 if (!string.IsNullOrEmpty(tb.User)) ret = tw.GetUserTimelineApi(read, count, tb.User, tb, false);
2619 TabClass tb = _statuses.GetTabByName(args.tName);
2622 ret = tw.GetUserTimelineApi(read, count, tb.User, tb, args.page == -1);
2626 rslt.addCount = _statuses.DistributePosts();
2628 case MyCommon.WORKERTYPE.List:
2629 bw.ReportProgress(50, MakeStatusMessage(args, false));
2630 if (string.IsNullOrEmpty(args.tName))
2633 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists))
2635 if (tb.ListInfo != null && tb.ListInfo.Id != 0) ret = tw.GetListStatus(read, tb, false, _initial);
2641 TabClass tb = _statuses.GetTabByName(args.tName);
2644 ret = tw.GetListStatus(read, tb, args.page == -1, _initial);
2648 rslt.addCount = _statuses.DistributePosts();
2651 case MyCommon.WORKERTYPE.Related:
2653 bw.ReportProgress(50, MakeStatusMessage(args, false));
2654 TabClass tab = _statuses.GetTabByName(args.tName);
2655 ret = tw.GetRelatedResult(read, tab);
2656 rslt.addCount = _statuses.DistributePosts();
2660 case MyCommon.WORKERTYPE.BlockIds:
2661 bw.ReportProgress(50, Properties.Resources.UpdateBlockUserText1);
2664 tw.RefreshBlockIds();
2666 catch (WebApiException ex) { ret = ex.Message; }
2670 if (bw.CancellationPending)
2677 if (args.type == MyCommon.WORKERTYPE.FavAdd)
2679 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2680 for (int i = _favTimestamps.Count - 1; i >= 0; i--)
2682 if (_favTimestamps[i].CompareTo(oneHour) < 0)
2684 _favTimestamps.RemoveAt(i);
2688 if (args.type == MyCommon.WORKERTYPE.Timeline && !_initial)
2692 DateTime tm = DateTime.Now;
2693 if (_tlTimestamps.ContainsKey(tm))
2694 _tlTimestamps[tm] += rslt.addCount;
2696 _tlTimestamps.Add(tm, rslt.addCount);
2698 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2699 List<DateTime> keys = new List<DateTime>();
2701 foreach (DateTime key in _tlTimestamps.Keys)
2703 if (key.CompareTo(oneHour) < 0)
2709 _tlCount += _tlTimestamps[key];
2712 foreach (DateTime key in keys)
2714 _tlTimestamps.Remove(key);
2721 bw.ReportProgress(100, MakeStatusMessage(args, true)); //ステータス書き換え、Notifyアイコンアニメーション開始
2724 rslt.type = args.type;
2725 rslt.tName = args.tName;
2726 if (args.type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
2727 args.type == MyCommon.WORKERTYPE.DirectMessegeSnt ||
2728 args.type == MyCommon.WORKERTYPE.Reply ||
2729 args.type == MyCommon.WORKERTYPE.Timeline ||
2730 args.type == MyCommon.WORKERTYPE.Favorites)
2732 rslt.page = args.page - 1; //値が正しいか後でチェック。10ページ毎の継続確認
2738 private string MakeStatusMessage(GetWorkerArg AsyncArg, bool Finish)
2744 switch (AsyncArg.type)
2746 case MyCommon.WORKERTYPE.Timeline:
2747 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2749 case MyCommon.WORKERTYPE.Reply:
2750 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2752 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2753 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2755 case MyCommon.WORKERTYPE.FavAdd:
2756 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15 + AsyncArg.page.ToString() + "/" + AsyncArg.ids.Count.ToString() +
2757 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText16 + (AsyncArg.page - AsyncArg.sIds.Count - 1).ToString();
2759 case MyCommon.WORKERTYPE.FavRemove:
2760 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17 + AsyncArg.page.ToString() + "/" + AsyncArg.ids.Count.ToString() +
2761 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText18 + (AsyncArg.page - AsyncArg.sIds.Count - 1).ToString();
2763 case MyCommon.WORKERTYPE.Favorites:
2764 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19;
2766 case MyCommon.WORKERTYPE.PublicSearch:
2767 smsg = "Search refreshing...";
2769 case MyCommon.WORKERTYPE.List:
2770 smsg = "List refreshing...";
2772 case MyCommon.WORKERTYPE.Related:
2773 smsg = "Related refreshing...";
2775 case MyCommon.WORKERTYPE.UserTimeline:
2776 smsg = "UserTimeline refreshing...";
2783 switch (AsyncArg.type)
2785 case MyCommon.WORKERTYPE.Timeline:
2786 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1;
2788 case MyCommon.WORKERTYPE.Reply:
2789 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9;
2791 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2792 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11;
2794 case MyCommon.WORKERTYPE.DirectMessegeSnt:
2795 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText13;
2797 case MyCommon.WORKERTYPE.FavAdd:
2800 case MyCommon.WORKERTYPE.FavRemove:
2803 case MyCommon.WORKERTYPE.Favorites:
2804 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20;
2806 case MyCommon.WORKERTYPE.Follower:
2807 smsg = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2809 case MyCommon.WORKERTYPE.NoRetweetIds:
2810 smsg = "NoRetweetIds refreshed";
2812 case MyCommon.WORKERTYPE.Configuration:
2815 case MyCommon.WORKERTYPE.PublicSearch:
2816 smsg = "Search refreshed";
2818 case MyCommon.WORKERTYPE.List:
2819 smsg = "List refreshed";
2821 case MyCommon.WORKERTYPE.Related:
2822 smsg = "Related refreshed";
2824 case MyCommon.WORKERTYPE.UserTimeline:
2825 smsg = "UserTimeline refreshed";
2827 case MyCommon.WORKERTYPE.BlockIds:
2828 smsg = Properties.Resources.UpdateBlockUserText3;
2835 private void GetTimelineWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
2837 if (MyCommon._endingFlag) return;
2838 if (e.ProgressPercentage > 100)
2841 if (e.ProgressPercentage == 200) //開始
2842 StatusLabel.Text = "Posting...";
2843 if (e.ProgressPercentage == 300) //終了
2844 StatusLabel.Text = Properties.Resources.PostWorker_RunWorkerCompletedText4;
2848 string smsg = (string)e.UserState;
2849 if (smsg.Length > 0) StatusLabel.Text = smsg;
2853 private void GetTimelineWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
2855 if (MyCommon._endingFlag || e.Cancelled) return; //キャンセル
2857 if (e.Error != null)
2859 _myStatusError = true;
2860 _waitTimeline = false;
2864 _waitPubSearch = false;
2865 _waitUserTimeline = false;
2867 throw new Exception("BackgroundWorker Exception", e.Error);
2870 GetWorkerResult rslt = (GetWorkerResult)e.Result;
2873 if (rslt.retMsg.Length > 0)
2875 _myStatusError = true;
2876 StatusLabel.Text = rslt.retMsg;
2879 if (rslt.type == MyCommon.WORKERTYPE.ErrorState) return;
2881 if (rslt.type == MyCommon.WORKERTYPE.FavRemove)
2883 this.RemovePostFromFavTab(rslt.sIds.ToArray());
2887 //bool busy = false;
2888 //foreach (BackgroundWorker bw in _bw)
2890 // if (bw != null && bw.IsBusy)
2896 //if (!busy) RefreshTimeline(); //background処理なければ、リスト反映
2897 if (rslt.type == MyCommon.WORKERTYPE.Timeline ||
2898 rslt.type == MyCommon.WORKERTYPE.Reply ||
2899 rslt.type == MyCommon.WORKERTYPE.List ||
2900 rslt.type == MyCommon.WORKERTYPE.PublicSearch ||
2901 rslt.type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
2902 rslt.type == MyCommon.WORKERTYPE.DirectMessegeSnt ||
2903 rslt.type == MyCommon.WORKERTYPE.Favorites ||
2904 rslt.type == MyCommon.WORKERTYPE.Follower ||
2905 rslt.type == MyCommon.WORKERTYPE.NoRetweetIds ||
2906 rslt.type == MyCommon.WORKERTYPE.FavAdd ||
2907 rslt.type == MyCommon.WORKERTYPE.FavRemove ||
2908 rslt.type == MyCommon.WORKERTYPE.Related ||
2909 rslt.type == MyCommon.WORKERTYPE.UserTimeline ||
2910 rslt.type == MyCommon.WORKERTYPE.BlockIds ||
2911 rslt.type == MyCommon.WORKERTYPE.Configuration)
2913 RefreshTimeline(false); //リスト反映
2918 case MyCommon.WORKERTYPE.Timeline:
2919 _waitTimeline = false;
2922 // //API使用時の取得調整は別途考える(カウント調整?)
2925 case MyCommon.WORKERTYPE.Reply:
2927 if (rslt.newDM && !_initial)
2929 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
2932 case MyCommon.WORKERTYPE.Favorites:
2935 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2938 case MyCommon.WORKERTYPE.FavAdd:
2939 case MyCommon.WORKERTYPE.FavRemove:
2940 if (_curList != null && _curTab != null)
2942 using (ControlTransaction.Update(this._curList))
2944 if (rslt.type == MyCommon.WORKERTYPE.FavRemove && _statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.Favorites)
2950 for (int i = 0; i <= rslt.sIds.Count - 1; i++)
2952 if (_curTab.Text.Equals(rslt.tName))
2954 int idx = _statuses.Tabs[rslt.tName].IndexOf(rslt.sIds[i]);
2957 PostClass post = null;
2958 TabClass tb = _statuses.Tabs[rslt.tName];
2961 if (tb.TabType == MyCommon.TabUsageType.Lists || tb.TabType == MyCommon.TabUsageType.PublicSearch)
2963 post = tb.Posts[rslt.sIds[i]];
2967 post = _statuses[rslt.sIds[i]];
2969 ChangeCacheStyleRead(post.IsRead, idx, _curTab);
2971 if (idx == _curItemIndex) DispSelectedPost(true); //選択アイテム再表示
2979 case MyCommon.WORKERTYPE.PostMessage:
2980 if (string.IsNullOrEmpty(rslt.retMsg) ||
2981 rslt.retMsg.StartsWith("OK:") ||
2982 rslt.retMsg == "Warn:Status is a duplicate.")
2984 _postTimestamps.Add(DateTime.Now);
2985 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2986 for (int i = _postTimestamps.Count - 1; i >= 0; i--)
2988 if (_postTimestamps[i].CompareTo(oneHour) < 0)
2990 _postTimestamps.RemoveAt(i);
2994 if (!HashMgr.IsPermanent && !string.IsNullOrEmpty(HashMgr.UseHash))
2996 HashMgr.ClearHashtag();
2997 this.HashStripSplitButton.Text = "#[-]";
2998 this.HashToggleMenuItem.Checked = false;
2999 this.HashToggleToolStripMenuItem.Checked = false;
3001 SetMainWindowTitle();
3009 retry = MessageBox.Show(string.Format("{0} ---> [ " + rslt.retMsg + " ]" + Environment.NewLine + "\"" + rslt.status.status + "\"" + Environment.NewLine + "{1}",
3010 Properties.Resources.StatusUpdateFailed1,
3011 Properties.Resources.StatusUpdateFailed2),
3012 "Failed to update status",
3013 MessageBoxButtons.RetryCancel,
3014 MessageBoxIcon.Question);
3018 retry = DialogResult.Abort;
3020 if (retry == DialogResult.Retry)
3022 GetWorkerArg args = new GetWorkerArg();
3025 args.type = MyCommon.WORKERTYPE.PostMessage;
3026 args.status = rslt.status;
3031 if (ToolStripFocusLockMenuItem.Checked)
3033 //連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3034 StatusText_Enter(StatusText, new EventArgs());
3038 if (rslt.retMsg.Length == 0 && SettingDialog.PostAndGet)
3040 if (_isActiveUserstream)
3042 RefreshTimeline(true);
3046 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3050 case MyCommon.WORKERTYPE.Retweet:
3051 if (rslt.retMsg.Length == 0)
3053 _postTimestamps.Add(DateTime.Now);
3054 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
3055 for (int i = _postTimestamps.Count - 1; i >= 0; i--)
3057 if (_postTimestamps[i].CompareTo(oneHour) < 0)
3059 _postTimestamps.RemoveAt(i);
3062 if (!_isActiveUserstream && SettingDialog.PostAndGet) GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3065 case MyCommon.WORKERTYPE.Follower:
3066 //_waitFollower = false;
3067 this.PurgeListViewItemCache();
3068 if (_curList != null) _curList.Refresh();
3070 case MyCommon.WORKERTYPE.NoRetweetIds:
3072 case MyCommon.WORKERTYPE.Configuration:
3073 //_waitFollower = false
3074 if (SettingDialog.TwitterConfiguration.PhotoSizeLimit != 0)
3076 pictureService["Twitter"].Configuration("MaxUploadFilesize", SettingDialog.TwitterConfiguration.PhotoSizeLimit);
3078 this.PurgeListViewItemCache();
3079 if (_curList != null) _curList.Refresh();
3081 case MyCommon.WORKERTYPE.PublicSearch:
3082 _waitPubSearch = false;
3084 case MyCommon.WORKERTYPE.UserTimeline:
3085 _waitUserTimeline = false;
3087 case MyCommon.WORKERTYPE.List:
3090 case MyCommon.WORKERTYPE.Related:
3091 TabClass tab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
3092 if (tab != null && tab.RelationTargetPost != null && tab.Contains(tab.RelationTargetPost.StatusId))
3094 foreach (TabPage tp in ListTab.TabPages)
3096 if (tp.Text == tab.TabName)
3098 ((DetailsListView)tp.Tag).SelectedIndices.Add(tab.IndexOf(tab.RelationTargetPost.StatusId));
3099 ((DetailsListView)tp.Tag).Items[tab.IndexOf(tab.RelationTargetPost.StatusId)].Focused = true;
3108 private void RemovePostFromFavTab(Int64[] ids)
3110 string favTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).TabName;
3112 if (_curTab.Text.Equals(favTabName))
3114 if (_curList.FocusedItem != null)
3115 fidx = _curList.FocusedItem.Index;
3116 else if (_curList.TopItem != null)
3117 fidx = _curList.TopItem.Index;
3122 foreach (long i in ids)
3126 _statuses.RemoveFavPost(i);
3133 if (_curTab != null && _curTab.Text.Equals(favTabName))
3135 this.PurgeListViewItemCache();
3137 //_curItemIndex = -1;
3139 foreach (TabPage tp in ListTab.TabPages)
3141 if (tp.Text == favTabName)
3143 ((DetailsListView)tp.Tag).VirtualListSize = _statuses.Tabs[favTabName].AllCount;
3147 if (_curTab.Text.Equals(favTabName))
3151 _curList.SelectedIndices.Clear();
3153 while (_curList.SelectedIndices.Count > 0);
3155 if (_statuses.Tabs[favTabName].AllCount > 0)
3157 if (_statuses.Tabs[favTabName].AllCount - 1 > fidx && fidx > -1)
3159 _curList.SelectedIndices.Add(fidx);
3163 _curList.SelectedIndices.Add(_statuses.Tabs[favTabName].AllCount - 1);
3165 if (_curList.SelectedIndices.Count > 0)
3167 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3168 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3174 private static Dictionary<MyCommon.WORKERTYPE, DateTime> lastTime = new Dictionary<MyCommon.WORKERTYPE, DateTime>();
3176 private void GetTimeline(MyCommon.WORKERTYPE WkType, int fromPage, int toPage, string tabName)
3178 if (!this.IsNetworkAvailable()) return;
3181 GetWorkerArg args = new GetWorkerArg();
3182 args.page = fromPage;
3183 args.endPage = toPage;
3185 args.tName = tabName;
3187 if (!lastTime.ContainsKey(WkType)) lastTime.Add(WkType, new DateTime());
3188 double period = DateTime.Now.Subtract(lastTime[WkType]).TotalSeconds;
3189 if (period > 1 || period < -1)
3191 lastTime[WkType] = DateTime.Now;
3195 //Timeline取得モードの場合はReplyも同時に取得
3196 //if (!SettingDialog.UseAPI &&
3198 // WkType == MyCommon.WORKERTYPE.Timeline &&
3199 // SettingDialog.CheckReply)
3201 // //TimerReply.Enabled = false;
3202 // _mentionCounter = SettingDialog.ReplyPeriodInt;
3203 // GetWorkerArg _args = new GetWorkerArg();
3204 // _args.page = fromPage;
3205 // _args.endPage = toPage;
3206 // _args.type = MyCommon.WORKERTYPE.Reply;
3211 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3213 if (e.Button == MouseButtons.Left)
3215 this.Visible = true;
3216 if (this.WindowState == FormWindowState.Minimized)
3218 this.WindowState = _formWindowState;
3221 this.BringToFront();
3225 private void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3227 switch (SettingDialog.ListDoubleClickAction)
3230 MakeReplyOrDirectStatus();
3233 FavoriteChange(true);
3236 if (_curPost != null)
3237 ShowUserStatus(_curPost.ScreenName, false);
3243 ShowRelatedStatusesMenuItem_Click(null, null);
3246 MoveToHomeToolStripMenuItem_Click(null, null);
3249 StatusOpenMenuItem_Click(null, null);
3257 private void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3259 FavoriteChange(true);
3262 private void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3264 FavoriteChange(false);
3268 private void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3270 FavoritesRetweetOriginal();
3273 private void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3275 FavoritesRetweetUnofficial();
3278 private void FavoriteChange(bool FavAdd , bool multiFavoriteChangeDialogEnable = true)
3280 //trueでFavAdd,falseでFavRemove
3281 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3282 || !this.ExistCurrentPost) return;
3285 if (_curList.SelectedIndices.Count > 250 && FavAdd)
3287 MessageBox.Show(Properties.Resources.FavoriteLimitCountText);
3288 _DoFavRetweetFlags = false;
3291 else if (multiFavoriteChangeDialogEnable && _curList.SelectedIndices.Count > 1)
3295 string QuestionText = Properties.Resources.FavAddToolStripMenuItem_ClickText1;
3296 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText3;
3297 if (MessageBox.Show(QuestionText, Properties.Resources.FavAddToolStripMenuItem_ClickText2,
3298 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3300 _DoFavRetweetFlags = false;
3306 if (MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1, Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3307 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3314 GetWorkerArg args = new GetWorkerArg();
3315 args.ids = new List<long>();
3316 args.sIds = new List<long>();
3317 args.tName = _curTab.Text;
3320 args.type = MyCommon.WORKERTYPE.FavAdd;
3324 args.type = MyCommon.WORKERTYPE.FavRemove;
3326 foreach (int idx in _curList.SelectedIndices)
3328 PostClass post = GetCurTabPost(idx);
3331 if (!post.IsFav) args.ids.Add(post.StatusId);
3335 if (post.IsFav) args.ids.Add(post.StatusId);
3338 if (args.ids.Count == 0)
3341 StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3343 StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3351 private PostClass GetCurTabPost(int Index)
3353 this.itemCacheLock.EnterReadLock();
3356 if (_postCache != null && Index >= _itemCacheIndex && Index < _itemCacheIndex + _postCache.Length)
3357 return _postCache[Index - _itemCacheIndex];
3359 finally { this.itemCacheLock.ExitReadLock(); }
3361 return _statuses[_curTab.Text, Index];
3365 private void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3367 if (_curList.SelectedIndices.Count > 0)
3368 OpenUriAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3369 else if (_curList.SelectedIndices.Count == 0)
3370 OpenUriAsync(MyCommon.TwitterUrl);
3373 private void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3375 if (_curList.SelectedIndices.Count > 0)
3376 OpenUriAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3379 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3381 if ((!_initialLayout) && this.Visible)
3383 if (this.WindowState == FormWindowState.Normal)
3385 _mySize = this.ClientSize;
3386 _mySpDis = this.SplitContainer1.SplitterDistance;
3387 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3388 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3389 _modifySettingLocal = true;
3394 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3396 if (SettingDialog.SortOrderLock) return;
3397 IdComparerClass.ComparerMode mode = IdComparerClass.ComparerMode.Id;
3400 mode = IdComparerClass.ComparerMode.Id;
3408 case 6: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
3412 mode = IdComparerClass.ComparerMode.Nickname;
3415 mode = IdComparerClass.ComparerMode.Data;
3418 mode = IdComparerClass.ComparerMode.Id;
3421 mode = IdComparerClass.ComparerMode.Name;
3424 mode = IdComparerClass.ComparerMode.Source;
3428 _statuses.ToggleSortOrder(mode);
3431 DetailsListView list = (DetailsListView)sender;
3434 list.Columns[0].Text = ColumnOrgText[0];
3435 list.Columns[1].Text = ColumnText[2];
3439 for (int i = 0; i <= 7; i++)
3441 list.Columns[i].Text = ColumnOrgText[i];
3443 list.Columns[e.Column].Text = ColumnText[e.Column];
3446 this.PurgeListViewItemCache();
3448 if (_statuses.Tabs[_curTab.Text].AllCount > 0 && _curPost != null)
3450 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_curPost.StatusId);
3453 SelectListItem(_curList, idx);
3454 _curList.EnsureVisible(idx);
3458 _modifySettingCommon = true;
3461 private void TweenMain_LocationChanged(object sender, EventArgs e)
3463 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3465 _myLoc = this.DesktopLocation;
3466 _modifySettingLocal = true;
3470 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3472 if (ListTab.SelectedTab == null) return;
3473 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3474 if (!this.ExistCurrentPost)
3476 ReplyStripMenuItem.Enabled = false;
3477 ReplyAllStripMenuItem.Enabled = false;
3478 DMStripMenuItem.Enabled = false;
3479 ShowProfileMenuItem.Enabled = false;
3480 ShowUserTimelineContextMenuItem.Enabled = false;
3481 ListManageUserContextToolStripMenuItem2.Enabled = false;
3482 MoveToFavToolStripMenuItem.Enabled = false;
3483 TabMenuItem.Enabled = false;
3484 IDRuleMenuItem.Enabled = false;
3485 ReadedStripMenuItem.Enabled = false;
3486 UnreadStripMenuItem.Enabled = false;
3490 ShowProfileMenuItem.Enabled = true;
3491 ListManageUserContextToolStripMenuItem2.Enabled = true;
3492 ReplyStripMenuItem.Enabled = true;
3493 ReplyAllStripMenuItem.Enabled = true;
3494 DMStripMenuItem.Enabled = true;
3495 ShowUserTimelineContextMenuItem.Enabled = true;
3496 MoveToFavToolStripMenuItem.Enabled = true;
3497 TabMenuItem.Enabled = true;
3498 IDRuleMenuItem.Enabled = true;
3499 ReadedStripMenuItem.Enabled = true;
3500 UnreadStripMenuItem.Enabled = true;
3502 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3503 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3505 FavAddToolStripMenuItem.Enabled = false;
3506 FavRemoveToolStripMenuItem.Enabled = false;
3507 StatusOpenMenuItem.Enabled = false;
3508 FavorareMenuItem.Enabled = false;
3509 ShowRelatedStatusesMenuItem.Enabled = false;
3511 ReTweetStripMenuItem.Enabled = false;
3512 ReTweetOriginalStripMenuItem.Enabled = false;
3513 QuoteStripMenuItem.Enabled = false;
3514 FavoriteRetweetContextMenu.Enabled = false;
3515 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3516 if (this.ExistCurrentPost && _curPost.IsDm)
3517 DeleteStripMenuItem.Enabled = true;
3519 DeleteStripMenuItem.Enabled = false;
3523 FavAddToolStripMenuItem.Enabled = true;
3524 FavRemoveToolStripMenuItem.Enabled = true;
3525 StatusOpenMenuItem.Enabled = true;
3526 FavorareMenuItem.Enabled = true;
3527 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3531 ReTweetOriginalStripMenuItem.Enabled = false;
3532 FavoriteRetweetContextMenu.Enabled = false;
3533 if (string.IsNullOrEmpty(_curPost.RetweetedBy))
3535 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3539 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3541 DeleteStripMenuItem.Enabled = true;
3545 if (string.IsNullOrEmpty(_curPost.RetweetedBy))
3547 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3551 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3553 DeleteStripMenuItem.Enabled = false;
3554 if (_curPost.IsProtect)
3556 ReTweetOriginalStripMenuItem.Enabled = false;
3557 ReTweetStripMenuItem.Enabled = false;
3558 QuoteStripMenuItem.Enabled = false;
3559 FavoriteRetweetContextMenu.Enabled = false;
3560 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3564 ReTweetOriginalStripMenuItem.Enabled = true;
3565 ReTweetStripMenuItem.Enabled = true;
3566 QuoteStripMenuItem.Enabled = true;
3567 FavoriteRetweetContextMenu.Enabled = true;
3568 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3572 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3574 // RefreshMoreStripMenuItem.Enabled = true;
3578 // RefreshMoreStripMenuItem.Enabled = false;
3580 if (!this.ExistCurrentPost
3581 || _curPost.InReplyToStatusId == null)
3583 RepliedStatusOpenMenuItem.Enabled = false;
3587 RepliedStatusOpenMenuItem.Enabled = true;
3589 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3591 MoveToRTHomeMenuItem.Enabled = false;
3595 MoveToRTHomeMenuItem.Enabled = true;
3599 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3601 MakeReplyOrDirectStatus(false, true);
3604 private void DMStripMenuItem_Click(object sender, EventArgs e)
3606 MakeReplyOrDirectStatus(false, false);
3609 private void doStatusDelete()
3611 if (_curTab == null || _curList == null) return;
3612 if (_statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
3614 bool myPost = false;
3615 foreach (int idx in _curList.SelectedIndices)
3617 if (GetCurTabPost(idx).IsMe ||
3618 GetCurTabPost(idx).RetweetedBy.ToLower() == tw.Username.ToLower())
3624 if (!myPost) return;
3628 if (_curList.SelectedIndices.Count == 0)
3632 string tmp = string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine);
3634 if (MessageBox.Show(tmp, Properties.Resources.DeleteStripMenuItem_ClickText2,
3635 MessageBoxButtons.OKCancel,
3636 MessageBoxIcon.Question) == DialogResult.Cancel) return;
3639 if (_curList.FocusedItem != null)
3640 fidx = _curList.FocusedItem.Index;
3641 else if (_curList.TopItem != null)
3642 fidx = _curList.TopItem.Index;
3648 this.Cursor = Cursors.WaitCursor;
3651 foreach (long Id in _statuses.GetId(_curTab.Text, _curList.SelectedIndices))
3654 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)
3656 rtn = tw.RemoveDirectMessage(Id, _statuses[Id]);
3660 if (_statuses[Id].IsMe || _statuses[Id].RetweetedBy.ToLower() == tw.Username.ToLower())
3661 rtn = tw.RemoveStatus(Id);
3672 _statuses.RemovePost(Id);
3677 StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; //失敗
3679 StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; //成功
3681 this.PurgeListViewItemCache();
3684 foreach (TabPage tb in ListTab.TabPages)
3686 ((DetailsListView)tb.Tag).VirtualListSize = _statuses.Tabs[tb.Text].AllCount;
3687 if (_curTab.Equals(tb))
3691 _curList.SelectedIndices.Clear();
3693 while (_curList.SelectedIndices.Count > 0);
3695 if (_statuses.Tabs[tb.Text].AllCount > 0)
3697 if (_statuses.Tabs[tb.Text].AllCount - 1 > fidx && fidx > -1)
3698 _curList.SelectedIndices.Add(fidx);
3700 _curList.SelectedIndices.Add(_statuses.Tabs[tb.Text].AllCount - 1);
3702 if (_curList.SelectedIndices.Count > 0)
3704 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3705 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3709 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3711 if (SettingDialog.TabIconDisp)
3713 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3717 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3721 this.Cursor = Cursors.Default;
3725 private void DeleteStripMenuItem_Click(object sender, EventArgs e)
3730 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3732 using (ControlTransaction.Update(this._curList))
3734 if (SettingDialog.UnreadManage)
3736 foreach (int idx in _curList.SelectedIndices)
3738 _statuses.SetReadAllTab(true, _curTab.Text, idx);
3741 foreach (int idx in _curList.SelectedIndices)
3743 ChangeCacheStyleRead(true, idx, _curTab);
3747 foreach (TabPage tb in ListTab.TabPages)
3749 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3751 if (SettingDialog.TabIconDisp)
3753 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3757 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3760 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3762 using (ControlTransaction.Update(this._curList))
3764 if (SettingDialog.UnreadManage)
3766 foreach (int idx in _curList.SelectedIndices)
3768 _statuses.SetReadAllTab(false, _curTab.Text, idx);
3771 foreach (int idx in _curList.SelectedIndices)
3773 ChangeCacheStyleRead(false, idx, _curTab);
3777 foreach (TabPage tb in ListTab.TabPages)
3779 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3781 if (SettingDialog.TabIconDisp)
3783 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3787 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3790 private void RefreshStripMenuItem_Click(object sender, EventArgs e)
3795 private void DoRefresh()
3797 if (_curTab != null)
3799 switch (_statuses.Tabs[_curTab.Text].TabType)
3801 case MyCommon.TabUsageType.Mentions:
3802 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
3804 case MyCommon.TabUsageType.DirectMessage:
3805 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
3807 case MyCommon.TabUsageType.Favorites:
3808 GetTimeline(MyCommon.WORKERTYPE.Favorites, 1, 0, "");
3810 //case MyCommon.TabUsageType.Profile:
3812 case MyCommon.TabUsageType.PublicSearch:
3814 TabClass tb = _statuses.Tabs[_curTab.Text];
3815 if (string.IsNullOrEmpty(tb.SearchWords)) return;
3816 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, _curTab.Text);
3818 case MyCommon.TabUsageType.UserTimeline:
3819 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, _curTab.Text);
3821 case MyCommon.TabUsageType.Lists:
3823 TabClass tab = _statuses.Tabs[_curTab.Text];
3824 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
3825 GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, _curTab.Text);
3828 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3834 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3838 private void DoRefreshMore()
3841 if (_curTab != null)
3843 switch (_statuses.Tabs[_curTab.Text].TabType)
3845 case MyCommon.TabUsageType.Mentions:
3846 GetTimeline(MyCommon.WORKERTYPE.Reply, -1, 0, "");
3848 case MyCommon.TabUsageType.DirectMessage:
3849 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, -1, 0, "");
3851 case MyCommon.TabUsageType.Favorites:
3852 GetTimeline(MyCommon.WORKERTYPE.Favorites, -1, 0, "");
3854 case MyCommon.TabUsageType.Profile:
3857 case MyCommon.TabUsageType.PublicSearch:
3859 TabClass tb = _statuses.Tabs[_curTab.Text];
3860 if (string.IsNullOrEmpty(tb.SearchWords)) return;
3861 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, -1, 0, _curTab.Text);
3863 case MyCommon.TabUsageType.UserTimeline:
3864 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, -1, 0, _curTab.Text);
3866 case MyCommon.TabUsageType.Lists:
3868 TabClass tab = _statuses.Tabs[_curTab.Text];
3869 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
3870 GetTimeline(MyCommon.WORKERTYPE.List, -1, 0, _curTab.Text);
3873 GetTimeline(MyCommon.WORKERTYPE.Timeline, -1, 0, "");
3879 GetTimeline(MyCommon.WORKERTYPE.Timeline, -1, 0, "");
3883 private void SettingStripMenuItem_Click(object sender, EventArgs e)
3885 DialogResult result;
3886 string uid = tw.Username.ToLower();
3887 var oldIconSz = SettingDialog.IconSz;
3891 result = SettingDialog.ShowDialog(this);
3898 if (result == DialogResult.OK)
3902 tw.TinyUrlResolve = SettingDialog.TinyUrlResolve;
3903 tw.RestrictFavCheck = SettingDialog.RestrictFavCheck;
3904 tw.ReadOwnPost = SettingDialog.ReadOwnPost;
3905 ShortUrl.Instance.DisableExpanding = !SettingDialog.TinyUrlResolve;
3906 ShortUrl.Instance.BitlyId = SettingDialog.BitlyUser;
3907 ShortUrl.Instance.BitlyKey = SettingDialog.BitlyPwd;
3908 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
3910 HttpConnection.InitializeConnection(SettingDialog.DefaultTimeOut,
3911 SettingDialog.SelectedProxyType,
3912 SettingDialog.ProxyAddress,
3913 SettingDialog.ProxyPort,
3914 SettingDialog.ProxyUser,
3915 SettingDialog.ProxyPassword);
3916 this.CreatePictureServices();
3920 if (SettingDialog.TabIconDisp)
3922 ListTab.DrawItem -= ListTab_DrawItem;
3923 ListTab.DrawMode = TabDrawMode.Normal;
3924 ListTab.ImageList = this.TabImage;
3928 ListTab.DrawItem -= ListTab_DrawItem;
3929 ListTab.DrawItem += ListTab_DrawItem;
3930 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3931 ListTab.ImageList = null;
3934 catch (Exception ex)
3936 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3937 ex.Data["IsTerminatePermission"] = false;
3943 if (!SettingDialog.UnreadManage)
3945 ReadedStripMenuItem.Enabled = false;
3946 UnreadStripMenuItem.Enabled = false;
3947 if (SettingDialog.TabIconDisp)
3949 foreach (TabPage myTab in ListTab.TabPages)
3951 myTab.ImageIndex = -1;
3957 ReadedStripMenuItem.Enabled = true;
3958 UnreadStripMenuItem.Enabled = true;
3961 catch (Exception ex)
3963 ex.Data["Instance"] = "ListTab(UnreadManage)";
3964 ex.Data["IsTerminatePermission"] = false;
3971 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance.Value;
3972 imgazyobizinet.Enabled = this.SettingDialog.EnableImgAzyobuziNet;
3973 imgazyobizinet.DisabledInDM = this.SettingDialog.ImgAzyobuziNetDisabledInDM;
3975 PlaySoundMenuItem.Checked = SettingDialog.PlaySound;
3976 this.PlaySoundFileMenuItem.Checked = SettingDialog.PlaySound;
3977 _fntUnread = SettingDialog.FontUnread;
3978 _clUnread = SettingDialog.ColorUnread;
3979 _fntReaded = SettingDialog.FontReaded;
3980 _clReaded = SettingDialog.ColorReaded;
3981 _clFav = SettingDialog.ColorFav;
3982 _clOWL = SettingDialog.ColorOWL;
3983 _clRetweet = SettingDialog.ColorRetweet;
3984 _fntDetail = SettingDialog.FontDetail;
3985 _clDetail = SettingDialog.ColorDetail;
3986 _clDetailLink = SettingDialog.ColorDetailLink;
3987 _clDetailBackcolor = SettingDialog.ColorDetailBackcolor;
3988 _clSelf = SettingDialog.ColorSelf;
3989 _clAtSelf = SettingDialog.ColorAtSelf;
3990 _clTarget = SettingDialog.ColorTarget;
3991 _clAtTarget = SettingDialog.ColorAtTarget;
3992 _clAtFromTarget = SettingDialog.ColorAtFromTarget;
3993 _clAtTo = SettingDialog.ColorAtTo;
3994 _clListBackcolor = SettingDialog.ColorListBackcolor;
3995 _clInputBackcolor = SettingDialog.ColorInputBackcolor;
3996 _clInputFont = SettingDialog.ColorInputFont;
3997 _fntInputFont = SettingDialog.FontInputFont;
3998 _brsBackColorMine.Dispose();
3999 _brsBackColorAt.Dispose();
4000 _brsBackColorYou.Dispose();
4001 _brsBackColorAtYou.Dispose();
4002 _brsBackColorAtFromTarget.Dispose();
4003 _brsBackColorAtTo.Dispose();
4004 _brsBackColorNone.Dispose();
4005 _brsBackColorMine = new SolidBrush(_clSelf);
4006 _brsBackColorAt = new SolidBrush(_clAtSelf);
4007 _brsBackColorYou = new SolidBrush(_clTarget);
4008 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4009 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4010 _brsBackColorAtTo = new SolidBrush(_clAtTo);
4011 _brsBackColorNone = new SolidBrush(_clListBackcolor);
4015 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4016 StatusText.Font = _fntInputFont;
4017 StatusText.ForeColor = _clInputFont;
4019 catch (Exception ex)
4021 MessageBox.Show(ex.Message);
4026 InitDetailHtmlFormat();
4028 catch (Exception ex)
4030 ex.Data["Instance"] = "Font";
4031 ex.Data["IsTerminatePermission"] = false;
4037 _statuses.SetUnreadManage(SettingDialog.UnreadManage);
4039 catch (Exception ex)
4041 ex.Data["Instance"] = "_statuses";
4042 ex.Data["IsTerminatePermission"] = false;
4048 foreach (TabPage tb in ListTab.TabPages)
4050 if (SettingDialog.TabIconDisp)
4052 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4059 catch (Exception ex)
4061 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4062 ex.Data["IsTerminatePermission"] = false;
4068 var oldIconCol = _iconCol;
4070 if (SettingDialog.IconSz != oldIconSz)
4071 ApplyListViewIconSize(SettingDialog.IconSz);
4073 foreach (TabPage tp in ListTab.TabPages)
4075 DetailsListView lst = (DetailsListView)tp.Tag;
4077 using (ControlTransaction.Update(lst))
4079 lst.GridLines = SettingDialog.ShowGrid;
4080 lst.Font = _fntReaded;
4081 lst.BackColor = _clListBackcolor;
4083 if (_iconCol != oldIconCol)
4088 catch (Exception ex)
4090 ex.Data["Instance"] = "ListView(IconSize)";
4091 ex.Data["IsTerminatePermission"] = false;
4095 SetMainWindowTitle();
4096 SetNotifyIconText();
4098 this.PurgeListViewItemCache();
4099 if (_curList != null) _curList.Refresh();
4102 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4103 if (SettingDialog.HotkeyEnabled)
4105 ///グローバルホットキーの登録。設定で変更可能にするかも
4106 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4107 if ((SettingDialog.HotkeyMod & Keys.Alt) == Keys.Alt) modKey = modKey | HookGlobalHotkey.ModKeys.Alt;
4108 if ((SettingDialog.HotkeyMod & Keys.Control) == Keys.Control) modKey = modKey | HookGlobalHotkey.ModKeys.Ctrl;
4109 if ((SettingDialog.HotkeyMod & Keys.Shift) == Keys.Shift) modKey = modKey | HookGlobalHotkey.ModKeys.Shift;
4110 if ((SettingDialog.HotkeyMod & Keys.LWin) == Keys.LWin) modKey = modKey | HookGlobalHotkey.ModKeys.Win;
4112 _hookGlobalHotkey.RegisterOriginalHotkey(SettingDialog.HotkeyKey, SettingDialog.HotkeyValue, modKey);
4115 if (uid != tw.Username) this.doGetFollowersMenu();
4117 SetImageServiceCombo();
4118 if (SettingDialog.IsNotifyUseGrowl) gh.RegisterGrowl();
4121 StatusText_TextChanged(null, null);
4129 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4131 this.TopMost = SettingDialog.AlwaysTop;
4132 SaveConfigsAll(false);
4138 private void SetTabAlignment()
4140 ListTab.Alignment = (SettingDialog.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top);
4143 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4149 case MyCommon.IconSizes.IconNone:
4152 case MyCommon.IconSizes.Icon16:
4155 case MyCommon.IconSizes.Icon24:
4158 case MyCommon.IconSizes.Icon48:
4161 case MyCommon.IconSizes.Icon48_2:
4169 // ディスプレイの DPI 設定を考慮したサイズを設定する
4170 _listViewImageList.ImageSize = new Size(
4172 (int)Math.Ceiling(this._iconSz * this.currentScaleFactor.Height));
4176 _listViewImageList.ImageSize = new Size(1, 1);
4180 private void ResetColumns(DetailsListView list)
4182 using (ControlTransaction.Update(list))
4183 using (ControlTransaction.Layout(list, false))
4186 list.ColumnClick -= MyList_ColumnClick;
4187 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4188 list.ColumnReordered -= MyList_ColumnReordered;
4189 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4191 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4192 list.Columns.Clear();
4193 cols.ForEach(col => col.Dispose());
4196 InitColumns(list, true);
4198 list.ColumnClick += MyList_ColumnClick;
4199 list.DrawColumnHeader += MyList_DrawColumnHeader;
4200 list.ColumnReordered += MyList_ColumnReordered;
4201 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4205 private void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4207 if (e.Url.AbsoluteUri != "about:blank")
4210 OpenUriAsync(e.Url.OriginalString);
4214 private void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4216 if (e.Url.Scheme == "data")
4218 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4220 else if (e.Url.AbsoluteUri != "about:blank")
4224 if (e.Url.AbsoluteUri.StartsWith("http://twitter.com/search?q=%23") ||
4225 e.Url.AbsoluteUri.StartsWith("https://twitter.com/search?q=%23"))
4228 string urlStr = Uri.UnescapeDataString(e.Url.AbsoluteUri);
4229 int i = urlStr.IndexOf('#');
4230 if (i == -1) return;
4232 string hash = urlStr.Substring(i);
4233 HashSupl.AddItem(hash);
4234 HashMgr.AddHashToHistory(hash.Trim(), false);
4235 AddNewTabForSearch(hash);
4240 Match m = Regex.Match(e.Url.AbsoluteUri, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
4241 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
4243 // Ctrlを押しながらリンクをクリックした場合は設定と逆の動作をする
4244 if (SettingDialog.OpenUserTimeline)
4246 if (MyCommon.IsKeyDown(Keys.Control))
4247 OpenUriAsync(e.Url.OriginalString);
4249 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4253 if (MyCommon.IsKeyDown(Keys.Control))
4254 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4256 OpenUriAsync(e.Url.OriginalString);
4261 OpenUriAsync(e.Url.OriginalString);
4267 public void AddNewTabForSearch(string searchWord)
4269 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4270 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4272 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4274 foreach (TabPage tp in ListTab.TabPages)
4276 if (tb.TabName == tp.Text)
4278 ListTab.SelectedTab = tp;
4285 string tabName = searchWord;
4286 for (int i = 0; i <= 100; i++)
4288 if (_statuses.ContainsTab(tabName))
4294 _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4295 AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4297 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4299 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4300 cmb.Items.Add(searchWord);
4301 cmb.Text = searchWord;
4304 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4307 private void ShowUserTimeline()
4309 if (!this.ExistCurrentPost) return;
4310 AddNewTabForUserTimeline(_curPost.ScreenName);
4313 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4315 if (e.KeyCode == Keys.Escape)
4317 TabPage relTp = ListTab.SelectedTab;
4318 RemoveSpecifiedTab(relTp.Text, false);
4320 e.SuppressKeyPress = true;
4324 public void AddNewTabForUserTimeline(string user)
4326 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4327 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4329 if (tb.User == user)
4331 foreach (TabPage tp in ListTab.TabPages)
4333 if (tb.TabName == tp.Text)
4335 ListTab.SelectedTab = tp;
4342 string tabName = "user:" + user;
4343 while (_statuses.ContainsTab(tabName))
4348 _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4349 _statuses.Tabs[tabName].User = user;
4350 AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4352 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4356 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, tabName);
4359 public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4362 foreach (TabPage tb in ListTab.TabPages)
4364 if (tb.Text == tabName) return false;
4368 if (tabName == Properties.Resources.AddNewTabText1) return false;
4373 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4374 tabType == MyCommon.TabUsageType.Favorites ||
4375 tabType == MyCommon.TabUsageType.Home ||
4376 tabType == MyCommon.TabUsageType.Mentions ||
4377 tabType == MyCommon.TabUsageType.Related)
4379 if (_statuses.GetTabByType(tabType) != null) return false;
4383 TabPage _tabPage = new TabPage();
4384 DetailsListView _listCustom = new DetailsListView();
4386 int cnt = ListTab.TabPages.Count;
4388 ///ToDo:Create and set controls follow tabtypes
4390 using (ControlTransaction.Update(_listCustom))
4391 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4392 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4393 using (ControlTransaction.Layout(this.SplitContainer1, false))
4394 using (ControlTransaction.Layout(this.ListTab, false))
4395 using (ControlTransaction.Layout(this))
4396 using (ControlTransaction.Layout(_tabPage, false))
4400 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4402 label = new Label();
4403 label.Dock = DockStyle.Top;
4404 label.Name = "labelUser";
4405 if (tabType == MyCommon.TabUsageType.Lists)
4407 label.Text = listInfo.ToString();
4411 label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4413 label.TextAlign = ContentAlignment.MiddleLeft;
4414 using (ComboBox tmpComboBox = new ComboBox())
4416 label.Height = tmpComboBox.Height;
4418 _tabPage.Controls.Add(label);
4423 if (tabType == MyCommon.TabUsageType.PublicSearch)
4427 Label lbl = new Label();
4428 ComboBox cmb = new ComboBox();
4429 Button btn = new Button();
4430 ComboBox cmbLang = new ComboBox();
4432 pnl.SuspendLayout();
4434 pnl.Controls.Add(cmb);
4435 pnl.Controls.Add(cmbLang);
4436 pnl.Controls.Add(btn);
4437 pnl.Controls.Add(lbl);
4438 pnl.Name = "panelSearch";
4439 pnl.Dock = DockStyle.Top;
4440 pnl.Height = cmb.Height;
4441 pnl.Enter += SearchControls_Enter;
4442 pnl.Leave += SearchControls_Leave;
4445 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4446 cmb.Dock = DockStyle.Fill;
4447 cmb.Name = "comboSearch";
4448 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4449 cmb.ImeMode = ImeMode.NoControl;
4450 cmb.TabStop = false;
4451 cmb.AutoCompleteMode = AutoCompleteMode.None;
4452 cmb.KeyDown += SearchComboBox_KeyDown;
4454 if (_statuses.ContainsTab(tabName))
4456 cmb.Items.Add(_statuses.Tabs[tabName].SearchWords);
4457 cmb.Text = _statuses.Tabs[tabName].SearchWords;
4461 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4462 cmbLang.Dock = DockStyle.Right;
4464 cmbLang.Name = "comboLang";
4465 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4466 cmbLang.TabStop = false;
4467 cmbLang.Items.Add("");
4468 cmbLang.Items.Add("ja");
4469 cmbLang.Items.Add("en");
4470 cmbLang.Items.Add("ar");
4471 cmbLang.Items.Add("da");
4472 cmbLang.Items.Add("nl");
4473 cmbLang.Items.Add("fa");
4474 cmbLang.Items.Add("fi");
4475 cmbLang.Items.Add("fr");
4476 cmbLang.Items.Add("de");
4477 cmbLang.Items.Add("hu");
4478 cmbLang.Items.Add("is");
4479 cmbLang.Items.Add("it");
4480 cmbLang.Items.Add("no");
4481 cmbLang.Items.Add("pl");
4482 cmbLang.Items.Add("pt");
4483 cmbLang.Items.Add("ru");
4484 cmbLang.Items.Add("es");
4485 cmbLang.Items.Add("sv");
4486 cmbLang.Items.Add("th");
4487 if (_statuses.ContainsTab(tabName)) cmbLang.Text = _statuses.Tabs[tabName].SearchLang;
4489 lbl.Text = "Search(C-S-f)";
4490 lbl.Name = "label1";
4491 lbl.Dock = DockStyle.Left;
4493 lbl.Height = cmb.Height;
4494 lbl.TextAlign = ContentAlignment.MiddleLeft;
4496 btn.Text = "Search";
4497 btn.Name = "buttonSearch";
4498 btn.UseVisualStyleBackColor = true;
4499 btn.Dock = DockStyle.Right;
4500 btn.TabStop = false;
4501 btn.Click += SearchButton_Click;
4504 this.ListTab.Controls.Add(_tabPage);
4505 _tabPage.Controls.Add(_listCustom);
4507 if (tabType == MyCommon.TabUsageType.PublicSearch) _tabPage.Controls.Add(pnl);
4508 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists) _tabPage.Controls.Add(label);
4510 _tabPage.Location = new Point(4, 4);
4511 _tabPage.Name = "CTab" + cnt.ToString();
4512 _tabPage.Size = new Size(380, 260);
4513 _tabPage.TabIndex = 2 + cnt;
4514 _tabPage.Text = tabName;
4515 _tabPage.UseVisualStyleBackColor = true;
4517 _listCustom.AllowColumnReorder = true;
4518 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4519 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4520 _listCustom.Dock = DockStyle.Fill;
4521 _listCustom.FullRowSelect = true;
4522 _listCustom.HideSelection = false;
4523 _listCustom.Location = new Point(0, 0);
4524 _listCustom.Margin = new Padding(0);
4525 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4526 _listCustom.ShowItemToolTips = true;
4527 _listCustom.Size = new Size(380, 260);
4528 _listCustom.UseCompatibleStateImageBehavior = false;
4529 _listCustom.View = View.Details;
4530 _listCustom.OwnerDraw = true;
4531 _listCustom.VirtualMode = true;
4532 _listCustom.Font = _fntReaded;
4533 _listCustom.BackColor = _clListBackcolor;
4535 _listCustom.GridLines = SettingDialog.ShowGrid;
4536 _listCustom.AllowDrop = true;
4538 _listCustom.SmallImageList = _listViewImageList;
4540 InitColumns(_listCustom, startup);
4542 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4543 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4544 _listCustom.ColumnClick += MyList_ColumnClick;
4545 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4546 _listCustom.DragDrop += TweenMain_DragDrop;
4547 _listCustom.DragEnter += TweenMain_DragEnter;
4548 _listCustom.DragOver += TweenMain_DragOver;
4549 _listCustom.DrawItem += MyList_DrawItem;
4550 _listCustom.MouseClick += MyList_MouseClick;
4551 _listCustom.ColumnReordered += MyList_ColumnReordered;
4552 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4553 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4554 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4555 _listCustom.DrawSubItem += MyList_DrawSubItem;
4556 _listCustom.HScrolled += MyList_HScrolled;
4558 if (tabType == MyCommon.TabUsageType.PublicSearch) pnl.ResumeLayout(false);
4561 _tabPage.Tag = _listCustom;
4565 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4567 if (_statuses.IsDefaultTab(TabName) || _statuses.Tabs[TabName].Protected) return false;
4571 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4572 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4573 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4579 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault<TabPage>(tp => tp.Text == TabName);
4580 if (_tabPage == null) return false;
4582 SetListProperty(); //他のタブに列幅等を反映
4584 MyCommon.TabUsageType tabType = _statuses.Tabs[TabName].TabType;
4587 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4588 _tabPage.Tag = null;
4590 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4591 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4592 using (ControlTransaction.Layout(this.SplitContainer1, false))
4593 using (ControlTransaction.Layout(this.ListTab, false))
4594 using (ControlTransaction.Layout(this))
4595 using (ControlTransaction.Layout(_tabPage, false))
4597 if (this.ListTab.SelectedTab == _tabPage)
4599 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4600 this._beforeSelectedTab = null;
4602 this.ListTab.Controls.Remove(_tabPage);
4605 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4607 using (Control label = _tabPage.Controls["labelUser"])
4609 _tabPage.Controls.Remove(label);
4612 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4614 using (Control pnl = _tabPage.Controls["panelSearch"])
4616 pnl.Enter -= SearchControls_Enter;
4617 pnl.Leave -= SearchControls_Leave;
4618 _tabPage.Controls.Remove(pnl);
4620 foreach (Control ctrl in pnl.Controls)
4622 if (ctrl.Name == "buttonSearch")
4624 ctrl.Click -= SearchButton_Click;
4626 else if (ctrl.Name == "comboSearch")
4628 ctrl.KeyDown -= SearchComboBox_KeyDown;
4630 pnl.Controls.Remove(ctrl);
4636 _tabPage.Controls.Remove(_listCustom);
4638 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4639 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4640 _listCustom.ColumnClick -= MyList_ColumnClick;
4641 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4642 _listCustom.DragDrop -= TweenMain_DragDrop;
4643 _listCustom.DragEnter -= TweenMain_DragEnter;
4644 _listCustom.DragOver -= TweenMain_DragOver;
4645 _listCustom.DrawItem -= MyList_DrawItem;
4646 _listCustom.MouseClick -= MyList_MouseClick;
4647 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4648 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4649 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4650 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4651 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4652 _listCustom.HScrolled -= MyList_HScrolled;
4654 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4655 _listCustom.Columns.Clear();
4656 cols.ForEach(col => col.Dispose());
4659 _listCustom.ContextMenuStrip = null;
4660 _listCustom.ColumnHeaderContextMenuStrip = null;
4661 _listCustom.Font = null;
4663 _listCustom.SmallImageList = null;
4664 _listCustom.ListViewItemSorter = null;
4667 if (_curTab.Equals(_tabPage))
4674 this.PurgeListViewItemCache();
4678 _listCustom.Dispose();
4679 _statuses.RemoveTab(TabName);
4681 foreach (TabPage tp in ListTab.TabPages)
4683 DetailsListView lst = (DetailsListView)tp.Tag;
4684 var count = _statuses.Tabs[tp.Text].AllCount;
4685 if (lst.VirtualListSize != count)
4687 lst.VirtualListSize = count;
4694 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4696 this.PurgeListViewItemCache();
4697 _beforeSelectedTab = e.TabPage;
4700 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4704 if (!SettingDialog.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4707 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4708 if (!dragEnableRectangle.Contains(e.Location))
4710 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4711 tn = ListTab.SelectedTab.Text;
4714 if (string.IsNullOrEmpty(tn)) return;
4716 foreach (TabPage tb in ListTab.TabPages)
4720 ListTab.DoDragDrop(tb, DragDropEffects.All);
4730 Point cpos = new Point(e.X, e.Y);
4731 for (int i = 0; i < ListTab.TabPages.Count; i++)
4733 Rectangle rect = ListTab.GetTabRect(i);
4734 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4735 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4737 _rclickTabName = ListTab.TabPages[i].Text;
4743 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4745 //_curList.Refresh();
4747 SetMainWindowTitle();
4748 SetStatusLabelUrl();
4749 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4750 TabMenuControl(ListTab.SelectedTab.Text);
4751 this.PushSelectPostChain();
4754 private void SetListProperty()
4756 //削除などで見つからない場合は処理せず
4757 if (_curList == null) return;
4758 if (!_isColumnChanged) return;
4760 int[] dispOrder = new int[_curList.Columns.Count];
4761 for (int i = 0; i < _curList.Columns.Count; i++)
4763 for (int j = 0; j < _curList.Columns.Count; j++)
4765 if (_curList.Columns[j].DisplayIndex == i)
4774 foreach (TabPage tb in ListTab.TabPages)
4776 if (!tb.Equals(_curTab))
4778 if (tb.Tag != null && tb.Controls.Count > 0)
4780 DetailsListView lst = (DetailsListView)tb.Tag;
4781 for (int i = 0; i < lst.Columns.Count; i++)
4783 lst.Columns[dispOrder[i]].DisplayIndex = i;
4784 lst.Columns[i].Width = _curList.Columns[i].Width;
4790 _isColumnChanged = false;
4793 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
4797 if (PostBrowser.StatusText.StartsWith("http") || PostBrowser.StatusText.StartsWith("ftp")
4798 || PostBrowser.StatusText.StartsWith("data"))
4800 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4802 if (string.IsNullOrEmpty(PostBrowser.StatusText))
4804 SetStatusLabelUrl();
4812 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4814 if (e.KeyChar == '@')
4816 if (!SettingDialog.UseAtIdSupplement) return;
4818 int cnt = AtIdSupl.ItemCount;
4819 ShowSuplDialog(StatusText, AtIdSupl);
4820 if (cnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
4823 else if (e.KeyChar == '#')
4825 if (!SettingDialog.UseHashSupplement) return;
4826 ShowSuplDialog(StatusText, HashSupl);
4831 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4833 ShowSuplDialog(owner, dialog, 0, "");
4836 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4838 ShowSuplDialog(owner, dialog, offset, "");
4841 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4843 dialog.StartsWith = startswith;
4850 dialog.ShowDialog();
4852 this.TopMost = SettingDialog.AlwaysTop;
4853 int selStart = owner.SelectionStart;
4856 if (dialog.DialogResult == DialogResult.OK)
4858 if (!string.IsNullOrEmpty(dialog.inputText))
4862 fHalf = owner.Text.Substring(0, selStart - offset);
4864 if (selStart < owner.Text.Length)
4866 eHalf = owner.Text.Substring(selStart);
4868 owner.Text = fHalf + dialog.inputText + eHalf;
4869 owner.SelectionStart = selStart + dialog.inputText.Length;
4876 fHalf = owner.Text.Substring(0, selStart);
4878 if (selStart < owner.Text.Length)
4880 eHalf = owner.Text.Substring(selStart);
4882 owner.Text = fHalf + eHalf;
4885 owner.SelectionStart = selStart;
4891 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4894 if (!e.Alt && !e.Control && !e.Shift)
4896 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4898 bool isSpace = false;
4899 foreach (char c in StatusText.Text.ToCharArray())
4901 if (c == ' ' || c == ' ')
4914 StatusText.Text = "";
4915 JumpUnreadMenuItem_Click(null, null);
4919 this.StatusText_TextChanged(null, null);
4922 private void StatusText_TextChanged(object sender, EventArgs e)
4925 int pLen = GetRestStatusCount(true, false);
4926 lblLen.Text = pLen.ToString();
4929 StatusText.ForeColor = Color.Red;
4933 StatusText.ForeColor = _clInputFont;
4935 if (string.IsNullOrEmpty(StatusText.Text))
4937 _reply_to_id = null;
4938 _reply_to_name = null;
4942 private int GetRestStatusCount(bool isAuto, bool isAddFooter)
4945 var statusText = this.StatusText.Text;
4946 statusText = statusText.Replace("\r\n", "\n");
4948 int pLen = 140 - statusText.Length;
4949 if (this.NotifyIcon1 == null || !this.NotifyIcon1.Visible) return pLen;
4950 if ((isAuto && !MyCommon.IsKeyDown(Keys.Control) && SettingDialog.PostShiftEnter) ||
4951 (isAuto && !MyCommon.IsKeyDown(Keys.Shift) && !SettingDialog.PostShiftEnter) ||
4952 (!isAuto && isAddFooter))
4954 if (SettingDialog.UseRecommendStatus)
4955 pLen -= SettingDialog.RecommendStatusText.Length;
4956 else if (SettingDialog.Status.Length > 0)
4957 pLen -= SettingDialog.Status.Length + 1;
4959 if (!string.IsNullOrEmpty(HashMgr.UseHash))
4961 pLen -= HashMgr.UseHash.Length + 1;
4963 //foreach (Match m in Regex.Matches(statusText, "https?:\/\/[-_.!~*//()a-zA-Z0-9;\/?:\@&=+\$,%#^]+"))
4965 // pLen += m.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4967 foreach (Match m in Regex.Matches(statusText, Twitter.rgUrl, RegexOptions.IgnoreCase))
4969 string before = m.Result("${before}");
4970 string url = m.Result("${url}");
4971 string protocol = m.Result("${protocol}");
4972 string domain = m.Result("${domain}");
4973 string path = m.Result("${path}");
4974 if (protocol.Length == 0)
4976 if (Regex.IsMatch(before, Twitter.url_invalid_without_protocol_preceding_chars))
4981 bool last_url_invalid_match = false;
4982 string lasturl = null;
4983 foreach (Match mm in Regex.Matches(domain, Twitter.url_valid_ascii_domain, RegexOptions.IgnoreCase))
4985 lasturl = mm.ToString();
4986 last_url_invalid_match = Regex.IsMatch(lasturl, Twitter.url_invalid_short_domain, RegexOptions.IgnoreCase);
4987 if (!last_url_invalid_match)
4989 pLen += lasturl.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4993 if (path.Length != 0)
4995 if (last_url_invalid_match)
4997 pLen += lasturl.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4999 pLen += path.Length;
5004 int shortUrlLength = protocol == "https://"
5005 ? SettingDialog.TwitterConfiguration.ShortUrlLengthHttps
5006 : SettingDialog.TwitterConfiguration.ShortUrlLength;
5008 pLen += url.Length - shortUrlLength;
5011 //if (m.Result("${url}").Length > SettingDialog.TwitterConfiguration.ShortUrlLength)
5013 // pLen += m.Result("${url}").Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
5016 if (ImageSelectionPanel.Visible && ImageSelectedPicture.Tag != null && !string.IsNullOrEmpty(this.ImageService))
5018 pLen -= SettingDialog.TwitterConfiguration.CharactersReservedPerMedia;
5023 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5025 this.itemCacheLock.EnterUpgradeableReadLock();
5028 if (_curList.Equals(sender))
5030 if (_itemCache != null &&
5031 e.StartIndex >= _itemCacheIndex &&
5032 e.EndIndex < _itemCacheIndex + _itemCache.Length)
5034 //If the newly requested cache is a subset of the old cache,
5035 //no need to rebuild everything, so do nothing.
5039 //Now we need to rebuild the cache.
5040 CreateCache(e.StartIndex, e.EndIndex);
5043 finally { this.itemCacheLock.ExitUpgradeableReadLock(); }
5046 private async void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5048 ListViewItem item = null;
5049 PostClass cacheItemPost = null;
5051 if (_curList.Equals(sender))
5052 this.TryGetListViewItemCache(e.ItemIndex, out item, out cacheItemPost);
5056 //A cache miss, so create a new ListViewItem and pass it back.
5057 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5060 item = this.CreateItem(tb, _statuses[tb.Text, e.ItemIndex], e.ItemIndex);
5065 string[] sitem = {"", "", "", "", "", "", "", ""};
5066 item = new ImageListViewItem(sitem);
5070 // e.Item に値をセットする前に await しないこと
5073 await ((ImageListViewItem)item).GetImageAsync();
5076 private void CreateCache(int StartIndex, int EndIndex)
5078 this.itemCacheLock.EnterWriteLock();
5081 //キャッシュ要求(要求範囲±30を作成)
5083 if (StartIndex < 0) StartIndex = 0;
5085 if (EndIndex >= _statuses.Tabs[_curTab.Text].AllCount) EndIndex = _statuses.Tabs[_curTab.Text].AllCount - 1;
5086 _postCache = _statuses[_curTab.Text, StartIndex, EndIndex]; //配列で取得
5087 _itemCacheIndex = StartIndex;
5089 _itemCache = new ListViewItem[0] {};
5090 Array.Resize(ref _itemCache, _postCache.Length);
5092 for (int i = 0; i < _postCache.Length; i++)
5094 _itemCache[i] = CreateItem(_curTab, _postCache[i], StartIndex + i);
5099 //キャッシュ要求が実データとずれるため(イベントの遅延?)
5101 _itemCacheIndex = -1;
5104 finally { this.itemCacheLock.ExitWriteLock(); }
5108 /// DetailsListView のための ListViewItem のキャッシュを消去する
5110 private void PurgeListViewItemCache()
5112 this.itemCacheLock.EnterWriteLock();
5115 this._itemCache = null;
5116 this._itemCacheIndex = -1;
5117 this._postCache = null;
5119 finally { this.itemCacheLock.ExitWriteLock(); }
5122 private bool TryGetListViewItemCache(int index, out ListViewItem item, out PostClass post)
5124 this.itemCacheLock.EnterReadLock();
5127 if (this._itemCache != null && index >= this._itemCacheIndex && index < this._itemCacheIndex + this._itemCache.Length)
5129 item = this._itemCache[index - _itemCacheIndex];
5130 post = this._postCache[index - _itemCacheIndex];
5134 finally { this.itemCacheLock.ExitReadLock(); }
5141 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5143 StringBuilder mk = new StringBuilder();
5144 //if (Post.IsDeleted) mk.Append("×");
5145 //if (Post.IsMark) mk.Append("♪");
5146 //if (Post.IsProtect) mk.Append("Ю");
5147 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5148 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5149 ImageListViewItem itm;
5150 if (Post.RetweetedId == null)
5152 string[] sitem= {"",
5154 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5155 Post.CreatedAt.ToString(SettingDialog.DateTimeFormat),
5160 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5164 string[] sitem = {"",
5166 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5167 Post.CreatedAt.ToString(SettingDialog.DateTimeFormat),
5168 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5172 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5174 itm.StateImageIndex = Post.StateIndex;
5176 bool read = Post.IsRead;
5177 //未読管理していなかったら既読として扱う
5178 if (!_statuses.Tabs[Tab.Text].UnreadManage || !SettingDialog.UnreadManage) read = true;
5179 ChangeItemStyleRead(read, itm, Post, null);
5180 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5185 /// 全てのタブの振り分けルールを反映し直します
5187 private void ApplyPostFilters()
5191 this.Cursor = Cursors.WaitCursor;
5193 this.PurgeListViewItemCache();
5194 this._curPost = null;
5195 this._curItemIndex = -1;
5196 this._statuses.FilterAll();
5198 foreach (TabPage tabPage in this.ListTab.TabPages)
5200 var tab = this._statuses.Tabs[tabPage.Text];
5202 var listview = (DetailsListView)tabPage.Tag;
5203 listview.VirtualListSize = tab.AllCount;
5205 if (this.SettingDialog.TabIconDisp)
5207 if (tab.UnreadCount > 0)
5208 tabPage.ImageIndex = 0;
5210 tabPage.ImageIndex = -1;
5214 if (!this.SettingDialog.TabIconDisp)
5215 this.ListTab.Refresh();
5219 this.Cursor = Cursors.Default;
5223 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5225 e.DrawDefault = true;
5228 private void MyList_HScrolled(object sender, EventArgs e)
5230 DetailsListView listView = (DetailsListView)sender;
5234 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5236 if (e.State == 0) return;
5237 e.DrawDefault = false;
5238 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5240 SolidBrush brs2 = null;
5242 if (e.Item.BackColor == _clSelf)
5243 brs2 = _brsBackColorMine;
5244 else if (e.Item.BackColor == _clAtSelf)
5245 brs2 = _brsBackColorAt;
5246 else if (e.Item.BackColor == _clTarget)
5247 brs2 = _brsBackColorYou;
5248 else if (e.Item.BackColor == _clAtTarget)
5249 brs2 = _brsBackColorAtYou;
5250 else if (e.Item.BackColor == _clAtFromTarget)
5251 brs2 = _brsBackColorAtFromTarget;
5252 else if (e.Item.BackColor == _clAtTo)
5253 brs2 = _brsBackColorAtTo;
5255 brs2 = _brsBackColorNone;
5257 e.Graphics.FillRectangle(brs2, e.Bounds);
5262 if (((Control)sender).Focused)
5263 e.Graphics.FillRectangle(_brsHighLight, e.Bounds);
5265 e.Graphics.FillRectangle(_brsDeactiveSelection, e.Bounds);
5267 if ((e.State & ListViewItemStates.Focused) == ListViewItemStates.Focused) e.DrawFocusRectangle();
5268 this.DrawListViewItemIcon(e);
5271 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5273 if (e.ItemState == 0) return;
5275 if (e.ColumnIndex > 0)
5278 RectangleF rct = e.Bounds;
5279 rct.Width = e.Header.Width;
5282 rct.Y += e.Item.Font.Height;
5283 rct.Height -= e.Item.Font.Height;
5287 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, e.Item.Font.Height, out heightDiff));
5289 //if (heightDiff > e.Item.Font.Height * 0.7)
5291 // rct.Height += e.Item.Font.Height;
5292 // drawLineCount += 1;
5295 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5296 if (!_iconCol && drawLineCount <= 1)
5298 //rct.Inflate(0, heightDiff / -2);
5299 //rct.Height += e.Item.Font.Height / 2;
5301 else if (heightDiff < e.Item.Font.Height * 0.7)
5303 //最終行が70%以上欠けていたら、最終行は表示しない
5304 //rct.Height = (float)((e.Item.Font.Height * drawLineCount) + (e.Item.Font.Height / 2));
5305 rct.Height = (e.Item.Font.Height * drawLineCount) - 1;
5312 //if (!_iconCol && drawLineCount > 1)
5314 // rct.Y += e.Item.Font.Height * 0.2;
5315 // if (heightDiff >= e.Item.Font.Height * 0.8) rct.Height -= e.Item.Font.Height * 0.2;
5320 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5321 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5326 RectangleF rctB = e.Bounds;
5327 rctB.Width = e.Header.Width;
5328 rctB.Height = e.Item.Font.Height;
5330 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5332 TextRenderer.DrawText(e.Graphics,
5333 e.Item.SubItems[2].Text,
5335 Rectangle.Round(rct),
5337 TextFormatFlags.WordBreak |
5338 TextFormatFlags.EndEllipsis |
5339 TextFormatFlags.GlyphOverhangPadding |
5340 TextFormatFlags.NoPrefix);
5341 TextRenderer.DrawText(e.Graphics,
5342 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 + "]",
5344 Rectangle.Round(rctB),
5346 TextFormatFlags.SingleLine |
5347 TextFormatFlags.EndEllipsis |
5348 TextFormatFlags.GlyphOverhangPadding |
5349 TextFormatFlags.NoPrefix);
5352 else if (drawLineCount == 1)
5354 TextRenderer.DrawText(e.Graphics,
5357 Rectangle.Round(rct),
5359 TextFormatFlags.SingleLine |
5360 TextFormatFlags.EndEllipsis |
5361 TextFormatFlags.GlyphOverhangPadding |
5362 TextFormatFlags.NoPrefix |
5363 TextFormatFlags.VerticalCenter);
5367 TextRenderer.DrawText(e.Graphics,
5370 Rectangle.Round(rct),
5372 TextFormatFlags.WordBreak |
5373 TextFormatFlags.EndEllipsis |
5374 TextFormatFlags.GlyphOverhangPadding |
5375 TextFormatFlags.NoPrefix);
5377 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5382 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5384 ImageListViewItem item = (ImageListViewItem)e.Item;
5386 //e.Bounds.Leftが常に0を指すから自前で計算
5387 Rectangle itemRect = item.Bounds;
5388 itemRect.Width = e.Item.ListView.Columns[0].Width;
5390 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5392 if (clm.DisplayIndex < e.Item.ListView.Columns[0].DisplayIndex)
5393 itemRect.X += clm.Width;
5396 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5397 var realIconSize = new SizeF(this._iconSz * this.currentScaleFactor.Width, this._iconSz * this.currentScaleFactor.Height).ToSize();
5398 var realStateSize = new SizeF(16 * this.currentScaleFactor.Width, 16 * this.currentScaleFactor.Height).ToSize();
5401 Rectangle stateRect;
5402 if (item.Image != null)
5404 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5405 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5406 stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5410 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5411 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5412 stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5415 var img = item.Image;
5416 if (img != null && iconRect.Width > 0)
5418 e.Graphics.FillRectangle(Brushes.White, iconRect);
5419 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5422 e.Graphics.DrawImage(img.Image, iconRect);
5424 catch (ArgumentException)
5426 item.RefreshImageAsync();
5430 if (item.StateImageIndex > -1)
5432 if (stateRect.Width > 0)
5434 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5435 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5436 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateImageIndex], stateRect);
5441 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5443 base.ScaleControl(factor, specified);
5445 const int baseDpi = 96;
5447 // デザイン時の DPI (96dpi) との比を更新する
5448 this.currentScaleFactor = new SizeF(
5449 this.CurrentAutoScaleDimensions.Width / baseDpi,
5450 this.CurrentAutoScaleDimensions.Height / baseDpi);
5453 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5455 // ImageListViewItem item = (ImageListViewItem)e.Item;
5456 // if (item.StateImageIndex > -1)
5458 // ////e.Bounds.Leftが常に0を指すから自前で計算
5459 // //Rectangle itemRect = item.Bounds;
5460 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5462 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5464 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5466 // // itemRect.X += clm.Width;
5470 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5471 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5473 // if (rct.Width > 0)
5475 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5476 // //e.Graphics.FillRectangle(Brushes.White, rct);
5477 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5478 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5483 private void DoTabSearch(string _word,
5493 if (_curList.VirtualListSize == 0)
5495 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5498 if (_curList.SelectedIndices.Count > 0)
5500 cidx = _curList.SelectedIndices[0];
5502 toIdx = _curList.VirtualListSize;
5506 case SEARCHTYPE.DialogSearch: //ダイアログからの検索
5507 if (_curList.SelectedIndices.Count > 0)
5508 cidx = _curList.SelectedIndices[0];
5512 case SEARCHTYPE.NextSearch: //次を検索
5513 if (_curList.SelectedIndices.Count > 0)
5515 cidx = _curList.SelectedIndices[0] + 1;
5516 if (cidx > toIdx) cidx = toIdx;
5523 case SEARCHTYPE.PrevSearch: //前を検索
5524 if (_curList.SelectedIndices.Count > 0)
5526 cidx = _curList.SelectedIndices[0] - 1;
5527 if (cidx < 0) cidx = 0;
5538 RegexOptions regOpt = RegexOptions.None;
5539 StringComparison fndOpt = StringComparison.Ordinal;
5542 regOpt = RegexOptions.IgnoreCase;
5543 fndOpt = StringComparison.OrdinalIgnoreCase;
5554 _search = new Regex(_word, regOpt);
5555 for (int idx = cidx; idx != toIdx; idx += stp)
5560 post = _statuses[_curTab.Text, idx];
5566 if (_search.IsMatch(post.Nickname)
5567 || _search.IsMatch(post.TextFromApi)
5568 || _search.IsMatch(post.ScreenName))
5570 SelectListItem(_curList, idx);
5571 _curList.EnsureVisible(idx);
5576 catch (ArgumentException)
5578 MessageBox.Show(Properties.Resources.DoTabSearchText1, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
5585 for (int idx = cidx; idx != toIdx; idx += stp)
5590 post = _statuses[_curTab.Text, idx];
5596 if (post.Nickname.IndexOf(_word, fndOpt) > -1
5597 || post.TextFromApi.IndexOf(_word, fndOpt) > -1
5598 || post.ScreenName.IndexOf(_word, fndOpt) > -1)
5600 SelectListItem(_curList, idx);
5601 _curList.EnsureVisible(idx);
5611 case SEARCHTYPE.DialogSearch:
5612 case SEARCHTYPE.NextSearch:
5616 case SEARCHTYPE.PrevSearch:
5618 cidx = _curList.VirtualListSize - 1;
5625 catch (ArgumentOutOfRangeException)
5628 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5631 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5634 this.ShowSearchDialog();
5637 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5639 var previousSearch = this.SearchDialog.ResultOptions;
5640 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5642 this.SearchDialog.Reset();
5643 this.ShowSearchDialog();
5649 previousSearch.Query,
5650 previousSearch.CaseSensitive,
5651 previousSearch.UseRegex,
5652 SEARCHTYPE.NextSearch);
5655 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5657 var previousSearch = this.SearchDialog.ResultOptions;
5658 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5660 this.SearchDialog.Reset();
5661 this.ShowSearchDialog();
5667 previousSearch.Query,
5668 previousSearch.CaseSensitive,
5669 previousSearch.UseRegex,
5670 SEARCHTYPE.PrevSearch);
5674 /// 検索ダイアログを表示し、検索を実行します
5676 private void ShowSearchDialog()
5678 // Recentタブの検索時以外では「新規タブに表示」ボタンを無効化する
5679 if (this._statuses.Tabs[this._curTab.Text].TabType == MyCommon.TabUsageType.Home)
5680 this.SearchDialog.DisableNewTabButton = false;
5682 this.SearchDialog.DisableNewTabButton = true;
5684 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5686 this.TopMost = this.SettingDialog.AlwaysTop;
5689 this.TopMost = this.SettingDialog.AlwaysTop;
5691 var searchOptions = this.SearchDialog.ResultOptions;
5692 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5694 if (searchOptions.NewTab)
5696 var tabName = searchOptions.Query;
5700 tabName = this._statuses.MakeTabName(tabName);
5702 catch (TabException ex)
5704 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5707 this.AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined);
5708 this._statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null);
5710 var filter = new PostFilterRule
5712 FilterBody = new[] { searchOptions.Query },
5713 UseRegex = searchOptions.UseRegex,
5714 CaseSensitive = searchOptions.CaseSensitive,
5716 this._statuses.Tabs[tabName].AddFilter(filter);
5718 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5719 .First(x => x.Text == tabName);
5721 this.ListTab.SelectedTab = tabPage;
5722 this.ListTabSelect(tabPage);
5724 this.ApplyPostFilters();
5725 this.SaveConfigsTabs();
5730 searchOptions.Query,
5731 searchOptions.CaseSensitive,
5732 searchOptions.UseRegex,
5733 SEARCHTYPE.DialogSearch);
5736 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5738 this.AddNewTabForSearch(searchOptions.Query);
5742 private void AboutMenuItem_Click(object sender, EventArgs e)
5744 using (TweenAboutBox about = new TweenAboutBox())
5746 about.ShowDialog(this);
5748 this.TopMost = SettingDialog.AlwaysTop;
5751 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5753 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5755 DetailsListView lst = null;
5757 if (ImageSelectionPanel.Enabled)
5761 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5764 idx = _statuses.GetOldestUnreadIndex(ListTab.TabPages[i].Text);
5767 ListTab.SelectedIndex = i;
5768 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5769 //_curTab = ListTab.TabPages[i];
5774 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5775 if (idx == -1 && bgnIdx > 0)
5777 for (int i = 0; i < bgnIdx; i++)
5779 idx = _statuses.GetOldestUnreadIndex(ListTab.TabPages[i].Text);
5782 ListTab.SelectedIndex = i;
5783 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5784 //_curTab = ListTab.TabPages[i];
5790 //全部調べたが未読見つからず→先頭タブの最新発言へ
5793 ListTab.SelectedIndex = 0;
5794 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5795 //_curTab = ListTab.TabPages[0];
5796 if (_statuses.SortOrder == SortOrder.Ascending)
5797 idx = lst.VirtualListSize - 1;
5802 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5804 SelectListItem(lst, idx);
5805 if (_statuses.SortMode == IdComparerClass.ComparerMode.Id)
5807 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5808 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5814 lst.EnsureVisible(idx);
5819 lst.EnsureVisible(idx);
5825 private void StatusOpenMenuItem_Click(object sender, EventArgs e)
5827 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5829 var post = _statuses[_curTab.Text, _curList.SelectedIndices[0]];
5830 OpenUriAsync(MyCommon.GetStatusUrl(post));
5834 private void FavorareMenuItem_Click(object sender, EventArgs e)
5836 if (_curList.SelectedIndices.Count > 0)
5838 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[0]];
5839 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5843 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5845 await this.CheckNewVersion(false);
5848 private void RunTweenUp()
5850 ProcessStartInfo pinfo = new ProcessStartInfo();
5851 pinfo.UseShellExecute = true;
5852 pinfo.WorkingDirectory = MyCommon.settingPath;
5853 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5854 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5857 Process.Start(pinfo);
5861 MessageBox.Show("Failed to execute TweenUp3.exe.");
5865 public class VersionInfo
5867 public Version Version { get; set; }
5868 public Uri DownloadUri { get; set; }
5869 public string ReleaseNote { get; set; }
5873 /// OpenTween の最新バージョンの情報を取得します
5875 public async Task<VersionInfo> GetVersionInfoAsync()
5877 var http = MyCommon.CreateHttpClient();
5879 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5880 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5882 var responseText = await http.GetStringAsync(versionInfoUrl)
5883 .ConfigureAwait(false);
5885 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5886 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5888 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5889 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5891 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5893 return new VersionInfo
5895 Version = Version.Parse(msgHeader[0]),
5896 DownloadUri = new Uri(msgHeader[1]),
5897 ReleaseNote = msgBody,
5901 private async Task CheckNewVersion(bool startup = false)
5903 if (ApplicationSettings.VersionInfoUrl == null)
5904 return; // 更新チェック無効化
5908 var versionInfo = await this.GetVersionInfoAsync();
5910 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5915 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5916 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5917 msgtext = MyCommon.ReplaceAppName(msgtext);
5919 MessageBox.Show(msgtext,
5920 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5921 MessageBoxButtons.OK, MessageBoxIcon.Information);
5926 using (var dialog = new UpdateDialog())
5928 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5929 MyCommon.GetReadableVersion(versionInfo.Version));
5930 dialog.DetailsText = versionInfo.ReleaseNote;
5932 if (dialog.ShowDialog(this) == DialogResult.Yes)
5934 await this.OpenUriAsync(versionInfo.DownloadUri.OriginalString);
5940 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5943 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5944 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5945 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5950 private void Colorize()
5954 //件数関連の場合、タイトル即時書き換え
5955 if (SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.None &&
5956 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5957 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5958 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5960 SetMainWindowTitle();
5962 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
5963 foreach (TabPage tb in ListTab.TabPages)
5965 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5967 if (SettingDialog.TabIconDisp)
5969 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5973 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
5976 public string createDetailHtml(string orgdata)
5978 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5981 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
5983 if (sender.Equals(displayItem))
5985 this.ClearUserPicture();
5987 var img = displayItem.Image;
5991 img = await img.CloneAsync();
5993 UserPicture.Image = img;
5997 UserPicture.ShowErrorImage();
6002 private void DispSelectedPost()
6004 DispSelectedPost(false);
6007 private static PostClass displaypost = new PostClass();
6010 /// サムネイルの表示処理を表すタスク
6012 private Task thumbnailTask = null;
6015 /// サムネイル表示に使用する CancellationToken の生成元
6017 private CancellationTokenSource thumbnailTokenSource = null;
6019 private void DispSelectedPost(bool forceupdate)
6021 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6024 if (!forceupdate && _curPost.Equals(displaypost))
6027 displaypost = _curPost;
6028 if (displayItem != null)
6030 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6033 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6034 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6036 string dTxt = createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6039 SourceLinkLabel.Tag = null;
6040 SourceLinkLabel.Text = "";
6044 Match mc = Regex.Match(_curPost.SourceHtml, "<a href=\"(?<sourceurl>.+?)\"");
6047 string src = mc.Groups["sourceurl"].Value;
6048 SourceLinkLabel.Tag = mc.Groups["sourceurl"].Value;
6049 mc = Regex.Match(src, "^https?://");
6052 src = src.Insert(0, "https://twitter.com");
6054 SourceLinkLabel.Tag = src;
6058 SourceLinkLabel.Tag = null;
6060 if (string.IsNullOrEmpty(_curPost.Source))
6062 SourceLinkLabel.Text = "";
6063 //SourceLinkLabel.Visible = false;
6067 SourceLinkLabel.Text = _curPost.Source;
6068 //SourceLinkLabel.Visible = true;
6071 SourceLinkLabel.TabStop = false;
6073 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && !_curPost.IsOwl)
6075 NameLabel.Text = "DM TO -> ";
6077 else if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)
6079 NameLabel.Text = "DM FROM <- ";
6083 NameLabel.Text = "";
6085 NameLabel.Text += _curPost.ScreenName + "/" + _curPost.Nickname;
6086 NameLabel.Tag = _curPost.ScreenName;
6087 if (!string.IsNullOrEmpty(_curPost.RetweetedBy))
6089 NameLabel.Text += " (RT:" + _curPost.RetweetedBy + ")";
6092 this.ClearUserPicture();
6094 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6096 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6099 UserPicture.Image = image != null ? image.Clone() : null;
6103 UserPicture.ShowErrorImage();
6107 NameLabel.ForeColor = System.Drawing.SystemColors.ControlText;
6108 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6109 if (_curPost.IsOwl && (SettingDialog.OneWayLove || _statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)) NameLabel.ForeColor = _clOWL;
6110 if (_curPost.RetweetedId != null) NameLabel.ForeColor = _clRetweet;
6111 if (_curPost.IsFav) NameLabel.ForeColor = _clFav;
6113 if (DumpPostClassToolStripMenuItem.Checked)
6115 StringBuilder sb = new StringBuilder(512);
6117 sb.Append("-----Start PostClass Dump<br>");
6118 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
6119 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6120 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
6121 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
6122 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
6123 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
6124 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
6125 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
6126 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
6127 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
6128 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
6129 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
6130 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
6131 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
6132 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
6134 foreach (string nm in _curPost.ReplyToList)
6136 sb.AppendFormat("ReplyToList : {0}<br>", nm);
6139 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
6140 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
6141 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
6142 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
6143 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
6144 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
6145 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
6146 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
6147 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
6148 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
6149 sb.AppendFormat("SearchTabName : {0}<br>", _curPost.RelTabName);
6150 sb.Append("-----End PostClass Dump<br>");
6152 PostBrowser.Visible = false;
6153 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6154 PostBrowser.Visible = true;
6160 if (PostBrowser.DocumentText != dTxt)
6162 PostBrowser.Visible = false;
6163 PostBrowser.DocumentText = dTxt;
6165 this.SplitContainer3.Panel2Collapsed = true;
6167 if (this.IsPreviewEnable)
6169 if (this.thumbnailTokenSource != null)
6171 var oldTokenSource = this.thumbnailTokenSource;
6172 oldTokenSource.Cancel();
6173 this.thumbnailTask.ContinueWith(_ => oldTokenSource.Dispose());
6176 this.thumbnailTokenSource = new CancellationTokenSource();
6178 var token = this.thumbnailTokenSource.Token;
6179 this.thumbnailTask = this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token);
6183 catch (System.Runtime.InteropServices.COMException)
6187 catch (UriFormatException)
6189 PostBrowser.DocumentText = dTxt;
6193 PostBrowser.Visible = true;
6198 private void MatomeMenuItem_Click(object sender, EventArgs e)
6200 OpenApplicationWebsite();
6203 private void OpenApplicationWebsite()
6205 OpenUriAsync(ApplicationSettings.WebsiteUrl);
6208 private void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6210 OpenUriAsync(ApplicationSettings.ShortcutKeyUrl);
6213 private void ListTab_KeyDown(object sender, KeyEventArgs e)
6215 if (ListTab.SelectedTab != null)
6217 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6219 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6220 if (pnl.Controls["comboSearch"].Focused ||
6221 pnl.Controls["comboLang"].Focused ||
6222 pnl.Controls["buttonSearch"].Focused) return;
6224 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
6225 if (State == ModifierState.NotFlags) return;
6226 if (State != ModifierState.None) _anchorFlag = false;
6227 if (CommonKeyDown(e.KeyCode, FocusedControl.ListTab, State))
6230 e.SuppressKeyPress = true;
6235 private ModifierState GetModifierState(bool sControl, bool sShift, bool sAlt)
6237 ModifierState state = ModifierState.None;
6238 if (sControl) state = state | ModifierState.Ctrl;
6239 if (sShift) state = state | ModifierState.Shift;
6240 if (sAlt) state = state | ModifierState.Alt;
6245 private enum ModifierState
6257 //PostBrowser = 102,
6261 private enum FocusedControl : int
6269 private bool CommonKeyDown(Keys KeyCode, FocusedControl Focused, ModifierState Modifier)
6271 //リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6272 if (Focused == FocusedControl.ListTab)
6274 if (Modifier == (ModifierState.Ctrl | ModifierState.Shift) ||
6275 Modifier == ModifierState.Ctrl ||
6276 Modifier == ModifierState.None ||
6277 Modifier == ModifierState.Shift)
6279 if (KeyCode == Keys.J)
6281 SendKeys.Send("{DOWN}");
6284 else if (KeyCode == Keys.K)
6286 SendKeys.Send("{UP}");
6290 if (Modifier == ModifierState.Shift ||
6291 Modifier == ModifierState.None)
6293 if (KeyCode == Keys.F)
6295 SendKeys.Send("{PGDN}");
6298 else if (KeyCode == Keys.B)
6300 SendKeys.Send("{PGUP}");
6309 case ModifierState.None:
6314 OpenApplicationWebsite();
6317 MenuItemSearchNext_Click(null, null);
6323 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
6326 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
6329 if (Focused != FocusedControl.StatusText)
6335 case Keys.ProcessKey:
6336 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6337 JumpUnreadMenuItem_Click(null, null);
6340 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6341 ShowRelatedStatusesMenuItem_Click(null, null);
6345 if (Focused == FocusedControl.ListTab)
6358 case Keys.OemPeriod:
6362 if (this.StatusText.Enabled) this.StatusText.Focus();
6365 MakeReplyOrDirectStatus();
6372 _anchorFlag = false;
6392 // ] in_reply_to参照元へ戻る
6393 GoInReplyToPostTree();
6396 // [ in_reply_toへジャンプ
6397 GoBackInReplyToPostTree();
6400 if (ListTab.SelectedTab != null)
6402 MyCommon.TabUsageType tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6403 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch)
6405 TabPage relTp = ListTab.SelectedTab;
6406 RemoveSpecifiedTab(relTp.Text, false);
6414 else if (Focused == FocusedControl.PostBrowser)
6421 //スクロールを発生させるため、true を返す
6426 case ModifierState.Ctrl:
6431 MakeReplyOrDirectStatus(false, true);
6437 MakeReplyOrDirectStatus(false, false);
6440 FavoriteChange(true);
6443 doRepliedStatusOpen();
6449 ReadedStripMenuItem_Click(null, null);
6452 HashManageMenuItem_Click(null, null);
6455 UrlConvertAutoToolStripMenuItem_Click(null, null);
6458 if (Focused != FocusedControl.PostBrowser)
6460 MultiLineMenuItem_Click(null, null);
6465 MenuItemSubSearch_Click(null, null);
6472 MoveToHomeToolStripMenuItem_Click(null, null);
6476 MoveToFavToolStripMenuItem_Click(null, null);
6480 StatusOpenMenuItem_Click(null, null);
6484 OpenURLMenuItem_Click(null, null);
6488 if (Focused == FocusedControl.ListTab)
6495 return false; //スルーする
6513 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6514 int tabNo = KeyCode - Keys.D1;
6515 if (ListTab.TabPages.Count < tabNo)
6517 ListTab.SelectedIndex = tabNo;
6518 ListTabSelect(ListTab.TabPages[tabNo]);
6521 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
6522 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
6526 else if (Focused == FocusedControl.StatusText)
6532 StatusText.SelectAll();
6536 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6538 _history[_hisIdx] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
6540 if (KeyCode == Keys.Up)
6543 if (_hisIdx < 0) _hisIdx = 0;
6548 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6550 StatusText.Text = _history[_hisIdx].status;
6551 _reply_to_id = _history[_hisIdx].inReplyToId;
6552 _reply_to_name = _history[_hisIdx].inReplyToName;
6553 StatusText.SelectionStart = StatusText.Text.Length;
6557 if (ListTab.SelectedIndex == 0)
6559 ListTab.SelectedIndex = ListTab.TabCount - 1;
6563 ListTab.SelectedIndex -= 1;
6569 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6571 ListTab.SelectedIndex = 0;
6575 ListTab.SelectedIndex += 1;
6583 //フォーカスPostBrowserもしくは関係なし
6587 PostBrowser.Document.ExecCommand("SelectAll", false, null);
6591 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
6592 if (!string.IsNullOrEmpty(_selText))
6596 Clipboard.SetDataObject(_selText, false, 5, 100);
6598 catch (Exception ex)
6600 MessageBox.Show(ex.Message);
6605 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6606 MultiLineMenuItem_Click(null, null);
6611 case ModifierState.Shift:
6616 MenuItemSearchPrev_Click(null, null);
6622 GetTimeline(MyCommon.WORKERTYPE.Reply, -1, 0, "");
6625 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, -1, 0, "");
6629 if (Focused != FocusedControl.StatusText)
6631 if (KeyCode == Keys.R)
6638 if (Focused == FocusedControl.ListTab)
6658 GoBackInReplyToPostTree(true, false);
6661 GoBackInReplyToPostTree(true, true);
6665 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6670 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6674 this.GoBackSelectPostChain();
6679 case ModifierState.Alt:
6683 doReTweetOfficial(true);
6686 if (_curPost != null)
6688 doShowUserStatus(_curPost.ScreenName, false);
6693 ScrollDownPostBrowser(false);
6696 ScrollDownPostBrowser(true);
6699 PageDownPostBrowser(false);
6702 PageDownPostBrowser(true);
6705 if (Focused == FocusedControl.ListTab)
6707 // 別タブの同じ書き込みへ(ALT+←/→)
6708 if (KeyCode == Keys.Right)
6710 GoSamePostToAnotherTab(false);
6713 else if (KeyCode == Keys.Left)
6715 GoSamePostToAnotherTab(true);
6720 case ModifierState.Ctrl | ModifierState.Shift:
6724 MakeReplyOrDirectStatus(false, true, true);
6730 if (ListTab.SelectedTab != null)
6732 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6734 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
6740 FavoriteChange(false);
6743 UnreadStripMenuItem_Click(null, null);
6746 HashToggleMenuItem_Click(null, null);
6749 ImageSelectMenuItem_Click(null, null);
6755 FavorareMenuItem_Click(null, null);
6758 if (Focused == FocusedControl.StatusText)
6764 if (_curList != null && _curList.VirtualListSize != 0 &&
6765 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6767 idx = _curList.SelectedIndices[0] - 1;
6768 SelectListItem(_curList, idx);
6769 _curList.EnsureVisible(idx);
6774 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6775 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6777 idx = _curList.SelectedIndices[0] + 1;
6778 SelectListItem(_curList, idx);
6779 _curList.EnsureVisible(idx);
6784 if (StatusText.SelectionStart > 0)
6786 int endidx = StatusText.SelectionStart - 1;
6787 string startstr = "";
6788 bool pressed = false;
6789 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6791 char c = StatusText.Text[i];
6792 if (Char.IsLetterOrDigit(c) || c == '_')
6799 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6800 int cnt = AtIdSupl.ItemCount;
6801 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6802 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
6807 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6808 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6820 else if (Focused == FocusedControl.ListTab)
6822 DetailsListView lst = (DetailsListView)ListTab.SelectedTab.Tag;
6834 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6835 int colNo = KeyCode - Keys.D1;
6836 if (lst.Columns.Count < colNo) return false;
6837 col = lst.Columns.Cast<ColumnHeader>().Where((x) => { return x.DisplayIndex == colNo; }).FirstOrDefault();
6838 if (col == null) return false;
6839 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
6842 col = lst.Columns.Cast<ColumnHeader>().OrderByDescending((x) => { return x.DisplayIndex; }).First();
6843 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
6848 case ModifierState.Ctrl | ModifierState.Alt:
6849 if (KeyCode == Keys.S)
6851 FavoritesRetweetOriginal();
6854 else if (KeyCode == Keys.R)
6856 FavoritesRetweetUnofficial();
6859 else if (KeyCode == Keys.H)
6861 OpenUserAppointUrl();
6865 case ModifierState.Alt | ModifierState.Shift:
6866 if (Focused == FocusedControl.PostBrowser)
6868 if (KeyCode == Keys.R)
6869 doReTweetUnofficial();
6870 else if (KeyCode == Keys.C)
6877 if (!this.ExistCurrentPost) return false;
6878 doTranslation(_curPost.TextFromApi);
6881 doReTweetUnofficial();
6887 this.tweetThumbnail1.ScrollUp();
6890 this.tweetThumbnail1.ScrollDown();
6893 if (Focused == FocusedControl.ListTab && KeyCode == Keys.Enter)
6895 if (!this.SplitContainer3.Panel2Collapsed)
6897 OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail);
6907 private void ScrollDownPostBrowser(bool forward)
6909 var doc = PostBrowser.Document;
6910 if (doc == null) return;
6912 var tags = doc.GetElementsByTagName("html");
6916 tags[0].ScrollTop += SettingDialog.FontDetail.Height;
6918 tags[0].ScrollTop -= SettingDialog.FontDetail.Height;
6922 private void PageDownPostBrowser(bool forward)
6924 var doc = PostBrowser.Document;
6925 if (doc == null) return;
6927 var tags = doc.GetElementsByTagName("html");
6931 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - SettingDialog.FontDetail.Height;
6933 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - SettingDialog.FontDetail.Height;
6937 private void GoNextTab(bool forward)
6939 int idx = ListTab.SelectedIndex;
6943 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6948 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6950 ListTab.SelectedIndex = idx;
6951 ListTabSelect(ListTab.TabPages[idx]);
6954 private void CopyStot()
6957 StringBuilder sb = new StringBuilder();
6958 bool IsProtected = false;
6960 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6961 foreach (int idx in _curList.SelectedIndices)
6963 PostClass post = _statuses[_curTab.Text, idx];
6969 if (post.IsDeleted) continue;
6972 if (post.RetweetedId != null)
6973 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6975 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6979 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6984 MessageBox.Show(Properties.Resources.CopyStotText1);
6988 clstr = sb.ToString();
6991 Clipboard.SetDataObject(clstr, false, 5, 100);
6993 catch (Exception ex)
6995 MessageBox.Show(ex.Message);
7000 private void CopyIdUri()
7003 StringBuilder sb = new StringBuilder();
7004 if (this._curTab == null) return;
7005 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7006 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7007 foreach (int idx in _curList.SelectedIndices)
7009 var post = _statuses[_curTab.Text, idx];
7010 sb.Append(MyCommon.GetStatusUrl(post));
7011 sb.Append(Environment.NewLine);
7015 clstr = sb.ToString();
7018 Clipboard.SetDataObject(clstr, false, 5, 100);
7020 catch (Exception ex)
7022 MessageBox.Show(ex.Message);
7027 private void GoFav(bool forward)
7029 if (_curList.VirtualListSize == 0) return;
7036 if (_curList.SelectedIndices.Count == 0)
7042 fIdx = _curList.SelectedIndices[0] + 1;
7043 if (fIdx > _curList.VirtualListSize - 1) return;
7045 toIdx = _curList.VirtualListSize;
7050 if (_curList.SelectedIndices.Count == 0)
7052 fIdx = _curList.VirtualListSize - 1;
7056 fIdx = _curList.SelectedIndices[0] - 1;
7057 if (fIdx < 0) return;
7063 for (int idx = fIdx; idx != toIdx; idx += stp)
7065 if (_statuses[_curTab.Text, idx].IsFav)
7067 SelectListItem(_curList, idx);
7068 _curList.EnsureVisible(idx);
7074 private void GoSamePostToAnotherTab(bool left)
7076 if (_curList.VirtualListSize == 0) return;
7082 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7083 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7085 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7090 if (ListTab.SelectedIndex == 0)
7096 fIdx = ListTab.SelectedIndex - 1;
7104 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7110 fIdx = ListTab.SelectedIndex + 1;
7112 toIdx = ListTab.TabCount;
7117 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7119 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7120 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7122 if (_statuses[ListTab.TabPages[tabidx].Text, idx].StatusId == targetId)
7124 ListTab.SelectedIndex = tabidx;
7125 ListTabSelect(ListTab.TabPages[tabidx]);
7126 SelectListItem(_curList, idx);
7127 _curList.EnsureVisible(idx);
7136 private void GoPost(bool forward)
7138 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7145 fIdx = _curList.SelectedIndices[0] + 1;
7146 if (fIdx > _curList.VirtualListSize - 1) return;
7147 toIdx = _curList.VirtualListSize;
7152 fIdx = _curList.SelectedIndices[0] - 1;
7153 if (fIdx < 0) return;
7159 if (_curPost.RetweetedId == null)
7161 name = _curPost.ScreenName;
7165 name = _curPost.RetweetedBy;
7167 for (int idx = fIdx; idx != toIdx; idx += stp)
7169 if (_statuses[_curTab.Text, idx].RetweetedId == null)
7171 if (_statuses[_curTab.Text, idx].ScreenName == name)
7173 SelectListItem(_curList, idx);
7174 _curList.EnsureVisible(idx);
7180 if (_statuses[_curTab.Text, idx].RetweetedBy == name)
7182 SelectListItem(_curList, idx);
7183 _curList.EnsureVisible(idx);
7190 private void GoRelPost(bool forward)
7192 if (_curList.SelectedIndices.Count == 0) return;
7199 fIdx = _curList.SelectedIndices[0] + 1;
7200 if (fIdx > _curList.VirtualListSize - 1) return;
7201 toIdx = _curList.VirtualListSize;
7206 fIdx = _curList.SelectedIndices[0] - 1;
7207 if (fIdx < 0) return;
7214 if (_curPost == null) return;
7215 _anchorPost = _curPost;
7220 if (_anchorPost == null) return;
7223 for (int idx = fIdx; idx != toIdx; idx += stp)
7225 PostClass post = _statuses[_curTab.Text, idx];
7226 if (post.ScreenName == _anchorPost.ScreenName ||
7227 post.RetweetedBy == _anchorPost.ScreenName ||
7228 post.ScreenName == _anchorPost.RetweetedBy ||
7229 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7230 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLower()) ||
7231 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLower()) ||
7232 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLower()) ||
7233 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLower()))
7235 SelectListItem(_curList, idx);
7236 _curList.EnsureVisible(idx);
7242 private void GoAnchor()
7244 if (_anchorPost == null) return;
7245 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7246 if (idx == -1) return;
7248 SelectListItem(_curList, idx);
7249 _curList.EnsureVisible(idx);
7252 private void GoTopEnd(bool GoTop)
7259 _item = _curList.GetItemAt(0, 25);
7267 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7269 idx = _curList.VirtualListSize - 1;
7273 SelectListItem(_curList, idx);
7276 private void GoMiddle()
7283 _item = _curList.GetItemAt(0, 0);
7293 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7296 idx2 = _curList.VirtualListSize - 1;
7302 idx3 = (idx1 + idx2) / 2;
7304 SelectListItem(_curList, idx3);
7307 private void GoLast()
7309 if (_curList.VirtualListSize == 0) return;
7311 if (_statuses.SortOrder == SortOrder.Ascending)
7313 SelectListItem(_curList, _curList.VirtualListSize - 1);
7314 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7318 SelectListItem(_curList, 0);
7319 _curList.EnsureVisible(0);
7323 private void MoveTop()
7325 if (_curList.SelectedIndices.Count == 0) return;
7326 int idx = _curList.SelectedIndices[0];
7327 if (_statuses.SortOrder == SortOrder.Ascending)
7329 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7333 _curList.EnsureVisible(0);
7335 _curList.EnsureVisible(idx);
7338 private void GoInReplyToPostTree()
7340 if (_curPost == null) return;
7342 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7344 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7346 PostClass post = null;
7347 string r = tw.GetStatusApi(false, _curPost.StatusId, ref post);
7348 if (string.IsNullOrEmpty(r) && post != null)
7350 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7351 _curPost.InReplyToUser = post.InReplyToUser;
7352 _curPost.IsReply = post.IsReply;
7353 this.PurgeListViewItemCache();
7354 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7358 this.StatusLabel.Text = r;
7362 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7364 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7366 replyChains = new Stack<ReplyChain>();
7368 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7371 string inReplyToTabName;
7372 long inReplyToId = _curPost.InReplyToStatusId.Value;
7373 string inReplyToUser = _curPost.InReplyToUser;
7374 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7376 var inReplyToPosts = from tab in _statuses.Tabs.Values
7377 orderby tab != curTabClass
7378 from post in tab.Posts.Values
7379 where post.StatusId == inReplyToId
7380 let index = tab.IndexOf(post.StatusId)
7382 select new {Tab = tab, Index = index};
7386 var inReplyPost = inReplyToPosts.First();
7387 inReplyToTabName = inReplyPost.Tab.TabName;
7388 inReplyToIndex = inReplyPost.Index;
7390 catch (InvalidOperationException)
7392 PostClass post = null;
7393 string r = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value, ref post);
7394 if (string.IsNullOrEmpty(r) && post != null)
7397 _statuses.AddPost(post);
7398 _statuses.DistributePosts();
7399 //_statuses.SubmitUpdate(null, null, null, false);
7400 this.RefreshTimeline(false);
7403 var inReplyPost = inReplyToPosts.First();
7404 inReplyToTabName = inReplyPost.Tab.TabName;
7405 inReplyToIndex = inReplyPost.Index;
7407 catch (InvalidOperationException)
7409 OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7415 this.StatusLabel.Text = r;
7416 OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7421 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7422 DetailsListView listView = (DetailsListView)tabPage.Tag;
7424 if (_curTab != tabPage)
7426 this.ListTab.SelectTab(tabPage);
7429 this.SelectListItem(listView, inReplyToIndex);
7430 listView.EnsureVisible(inReplyToIndex);
7433 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7435 if (_curPost == null) return;
7437 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7438 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7442 if (_curPost.InReplyToStatusId != null)
7444 var posts = from t in _statuses.Tabs
7445 from p in t.Value.Posts
7446 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7447 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7449 orderby isForward ? indexOf : indexOf * -1
7450 orderby t.Value != curTabClass
7451 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7454 var postList = posts.ToList();
7455 for (int i = postList.Count - 1; i >= 0; i--)
7458 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7460 postList.RemoveAt(index);
7463 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7464 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7465 if (post == null) post = postList.First();
7466 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7467 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7468 SelectListItem(listView, post.Index);
7469 listView.EnsureVisible(post.Index);
7471 catch (InvalidOperationException)
7479 if (replyChains == null || replyChains.Count < 1)
7481 var posts = from t in _statuses.Tabs
7482 from p in t.Value.Posts
7483 where p.Value.InReplyToStatusId == _curPost.StatusId
7484 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7487 orderby t.Value != curTabClass
7488 select new {Tab = t.Value, Index = indexOf};
7491 var post = posts.First();
7492 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7493 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7494 SelectListItem(listView, post.Index);
7495 listView.EnsureVisible(post.Index);
7497 catch (InvalidOperationException)
7504 ReplyChain chainHead = replyChains.Pop();
7505 if (chainHead.InReplyToId == _curPost.StatusId)
7507 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7516 ListTab.SelectTab(chainHead.OriginalTab);
7522 SelectListItem(_curList, idx);
7523 _curList.EnsureVisible(idx);
7529 this.GoBackInReplyToPostTree(parallel);
7535 private void GoBackSelectPostChain()
7539 this.selectPostChains.Pop();
7540 Tuple<TabPage, PostClass> tabPostPair = this.selectPostChains.Pop();
7541 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) return;
7542 this.ListTab.SelectedTab = tabPostPair.Item1;
7543 if (tabPostPair.Item2 != null && this._statuses.Tabs[this._curTab.Text].IndexOf(tabPostPair.Item2.StatusId) > -1)
7545 this.SelectListItem(this._curList, this._statuses.Tabs[this._curTab.Text].IndexOf(tabPostPair.Item2.StatusId));
7546 this._curList.EnsureVisible(this._statuses.Tabs[this._curTab.Text].IndexOf(tabPostPair.Item2.StatusId));
7549 catch (InvalidOperationException)
7554 private void PushSelectPostChain()
7556 if (this.selectPostChains.Count == 0 || (this.selectPostChains.Peek().Item1.Text != this._curTab.Text || this._curPost != this.selectPostChains.Peek().Item2))
7558 this.selectPostChains.Push(Tuple.Create(this._curTab, _curPost));
7562 private void TrimPostChain()
7564 if (this.selectPostChains.Count < 2000) return;
7565 Stack<Tuple<TabPage, PostClass>> p = new Stack<Tuple<TabPage, PostClass>>();
7566 for (int i = 0; i < 2000; i++)
7568 p.Push(this.selectPostChains.Pop());
7570 this.selectPostChains.Clear();
7571 for (int i = 0; i < 2000; i++)
7573 this.selectPostChains.Push(p.Pop());
7577 private bool GoStatus(long statusId)
7579 if (statusId == 0) return false;
7580 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7582 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7584 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7585 ListTab.SelectedIndex = tabidx;
7586 ListTabSelect(ListTab.TabPages[tabidx]);
7587 SelectListItem(_curList, idx);
7588 _curList.EnsureVisible(idx);
7595 private bool GoDirectMessage(long statusId)
7597 if (statusId == 0) return false;
7598 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7600 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7602 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7603 ListTab.SelectedIndex = tabidx;
7604 ListTabSelect(ListTab.TabPages[tabidx]);
7605 SelectListItem(_curList, idx);
7606 _curList.EnsureVisible(idx);
7613 private void MyList_MouseClick(object sender, MouseEventArgs e)
7615 _anchorFlag = false;
7618 private void StatusText_Enter(object sender, EventArgs e)
7620 // フォーカスの戻り先を StatusText に設定
7621 this.Tag = StatusText;
7622 StatusText.BackColor = _clInputBackcolor;
7625 public Color InputBackColor
7627 get { return _clInputBackcolor; }
7628 set { _clInputBackcolor = value; }
7631 private void StatusText_Leave(object sender, EventArgs e)
7633 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7634 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7635 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7638 private void StatusText_KeyDown(object sender, KeyEventArgs e)
7640 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
7641 if (State == ModifierState.NotFlags) return;
7642 if (CommonKeyDown(e.KeyCode, FocusedControl.StatusText, State))
7645 e.SuppressKeyPress = true;
7648 this.StatusText_TextChanged(null, null);
7651 private void SaveConfigsAll(bool ifModified)
7655 SaveConfigsCommon();
7662 if (_modifySettingCommon) SaveConfigsCommon();
7663 if (_modifySettingLocal) SaveConfigsLocal();
7664 if (_modifySettingAtId) SaveConfigsAtId();
7668 private void SaveConfigsAtId()
7670 if (_ignoreConfigSave || !SettingDialog.UseAtIdSupplement && AtIdSupl == null) return;
7672 _modifySettingAtId = false;
7673 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7677 private void SaveConfigsCommon()
7679 if (_ignoreConfigSave) return;
7681 _modifySettingCommon = false;
7684 _cfgCommon.UserName = tw.Username;
7685 _cfgCommon.UserId = tw.UserId;
7686 _cfgCommon.Password = tw.Password;
7687 _cfgCommon.Token = tw.AccessToken;
7688 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7689 _cfgCommon.UserAccounts = SettingDialog.UserAccounts;
7690 _cfgCommon.UserstreamStartup = SettingDialog.UserstreamStartup;
7691 _cfgCommon.UserstreamPeriod = SettingDialog.UserstreamPeriodInt;
7692 _cfgCommon.TimelinePeriod = SettingDialog.TimelinePeriodInt;
7693 _cfgCommon.ReplyPeriod = SettingDialog.ReplyPeriodInt;
7694 _cfgCommon.DMPeriod = SettingDialog.DMPeriodInt;
7695 _cfgCommon.PubSearchPeriod = SettingDialog.PubSearchPeriodInt;
7696 _cfgCommon.ListsPeriod = SettingDialog.ListsPeriodInt;
7697 _cfgCommon.UserTimelinePeriod = SettingDialog.UserTimelinePeriodInt;
7698 _cfgCommon.Read = SettingDialog.Readed;
7699 _cfgCommon.IconSize = SettingDialog.IconSz;
7700 _cfgCommon.UnreadManage = SettingDialog.UnreadManage;
7701 _cfgCommon.PlaySound = SettingDialog.PlaySound;
7702 _cfgCommon.OneWayLove = SettingDialog.OneWayLove;
7704 _cfgCommon.NameBalloon = SettingDialog.NameBalloon;
7705 _cfgCommon.PostCtrlEnter = SettingDialog.PostCtrlEnter;
7706 _cfgCommon.PostShiftEnter = SettingDialog.PostShiftEnter;
7707 _cfgCommon.CountApi = SettingDialog.CountApi;
7708 _cfgCommon.CountApiReply = SettingDialog.CountApiReply;
7709 _cfgCommon.PostAndGet = SettingDialog.PostAndGet;
7710 _cfgCommon.DispUsername = SettingDialog.DispUsername;
7711 _cfgCommon.MinimizeToTray = SettingDialog.MinimizeToTray;
7712 _cfgCommon.CloseToExit = SettingDialog.CloseToExit;
7713 _cfgCommon.DispLatestPost = SettingDialog.DispLatestPost;
7714 _cfgCommon.SortOrderLock = SettingDialog.SortOrderLock;
7715 _cfgCommon.ViewTabBottom = SettingDialog.ViewTabBottom;
7716 _cfgCommon.TinyUrlResolve = SettingDialog.TinyUrlResolve;
7717 _cfgCommon.StartupVersion = SettingDialog.StartupVersion;
7718 _cfgCommon.StartupFollowers = SettingDialog.StartupFollowers;
7719 _cfgCommon.RestrictFavCheck = SettingDialog.RestrictFavCheck;
7720 _cfgCommon.AlwaysTop = SettingDialog.AlwaysTop;
7721 _cfgCommon.UrlConvertAuto = SettingDialog.UrlConvertAuto;
7722 _cfgCommon.UseUnreadStyle = SettingDialog.UseUnreadStyle;
7723 _cfgCommon.DateTimeFormat = SettingDialog.DateTimeFormat;
7724 _cfgCommon.DefaultTimeOut = SettingDialog.DefaultTimeOut;
7725 _cfgCommon.RetweetNoConfirm = SettingDialog.RetweetNoConfirm;
7726 _cfgCommon.LimitBalloon = SettingDialog.LimitBalloon;
7727 _cfgCommon.EventNotifyEnabled = SettingDialog.EventNotifyEnabled;
7728 _cfgCommon.EventNotifyFlag = SettingDialog.EventNotifyFlag;
7729 _cfgCommon.IsMyEventNotifyFlag = SettingDialog.IsMyEventNotifyFlag;
7730 _cfgCommon.ForceEventNotify = SettingDialog.ForceEventNotify;
7731 _cfgCommon.FavEventUnread = SettingDialog.FavEventUnread;
7732 _cfgCommon.TranslateLanguage = SettingDialog.TranslateLanguage;
7733 _cfgCommon.EventSoundFile = SettingDialog.EventSoundFile;
7734 _cfgCommon.AutoShortUrlFirst = SettingDialog.AutoShortUrlFirst;
7735 _cfgCommon.TabIconDisp = SettingDialog.TabIconDisp;
7736 _cfgCommon.ReplyIconState = SettingDialog.ReplyIconState;
7737 _cfgCommon.ReadOwnPost = SettingDialog.ReadOwnPost;
7738 _cfgCommon.GetFav = SettingDialog.GetFav;
7739 _cfgCommon.IsMonospace = SettingDialog.IsMonospace;
7740 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7741 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7743 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7745 _cfgCommon.ReadOldPosts = SettingDialog.ReadOldPosts;
7746 _cfgCommon.BilyUser = SettingDialog.BitlyUser;
7747 _cfgCommon.BitlyPwd = SettingDialog.BitlyPwd;
7748 _cfgCommon.ShowGrid = SettingDialog.ShowGrid;
7749 _cfgCommon.UseAtIdSupplement = SettingDialog.UseAtIdSupplement;
7750 _cfgCommon.UseHashSupplement = SettingDialog.UseHashSupplement;
7751 _cfgCommon.PreviewEnable = SettingDialog.PreviewEnable;
7752 _cfgCommon.Language = SettingDialog.Language;
7754 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7755 switch (_statuses.SortMode)
7757 case IdComparerClass.ComparerMode.Nickname: //ニックネーム
7758 _cfgCommon.SortColumn = 1;
7760 case IdComparerClass.ComparerMode.Data: //本文
7761 _cfgCommon.SortColumn = 2;
7763 case IdComparerClass.ComparerMode.Id: //時刻=発言Id
7764 _cfgCommon.SortColumn = 3;
7766 case IdComparerClass.ComparerMode.Name: //名前
7767 _cfgCommon.SortColumn = 4;
7769 case IdComparerClass.ComparerMode.Source: //Source
7770 _cfgCommon.SortColumn = 7;
7774 _cfgCommon.Nicoms = SettingDialog.Nicoms;
7775 _cfgCommon.HashTags = HashMgr.HashHistories;
7776 if (HashMgr.IsPermanent)
7778 _cfgCommon.HashSelected = HashMgr.UseHash;
7782 _cfgCommon.HashSelected = "";
7784 _cfgCommon.HashIsHead = HashMgr.IsHead;
7785 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7786 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7787 _cfgCommon.TwitterUrl = SettingDialog.TwitterApiUrl;
7788 _cfgCommon.HotkeyEnabled = SettingDialog.HotkeyEnabled;
7789 _cfgCommon.HotkeyModifier = SettingDialog.HotkeyMod;
7790 _cfgCommon.HotkeyKey = SettingDialog.HotkeyKey;
7791 _cfgCommon.HotkeyValue = SettingDialog.HotkeyValue;
7792 _cfgCommon.BlinkNewMentions = SettingDialog.BlinkNewMentions;
7793 if (ToolStripFocusLockMenuItem != null &&
7794 ToolStripFocusLockMenuItem.IsDisposed == false)
7796 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7798 _cfgCommon.UseAdditionalCount = SettingDialog.UseAdditionalCount;
7799 _cfgCommon.MoreCountApi = SettingDialog.MoreCountApi;
7800 _cfgCommon.FirstCountApi = SettingDialog.FirstCountApi;
7801 _cfgCommon.SearchCountApi = SettingDialog.SearchCountApi;
7802 _cfgCommon.FavoritesCountApi = SettingDialog.FavoritesCountApi;
7803 _cfgCommon.UserTimelineCountApi = SettingDialog.UserTimelineCountApi;
7804 _cfgCommon.TrackWord = tw.TrackWord;
7805 _cfgCommon.AllAtReply = tw.AllAtReply;
7806 _cfgCommon.OpenUserTimeline = SettingDialog.OpenUserTimeline;
7807 _cfgCommon.ListCountApi = SettingDialog.ListCountApi;
7808 _cfgCommon.UseImageService = ImageServiceCombo.SelectedIndex;
7809 _cfgCommon.UseImageServiceName = this.ImageService;
7810 _cfgCommon.ListDoubleClickAction = SettingDialog.ListDoubleClickAction;
7811 _cfgCommon.UserAppointUrl = SettingDialog.UserAppointUrl;
7812 _cfgCommon.HideDuplicatedRetweets = SettingDialog.HideDuplicatedRetweets;
7813 _cfgCommon.EnableImgAzyobuziNet = SettingDialog.EnableImgAzyobuziNet;
7814 _cfgCommon.ImgAzyobuziNetDisabledInDM = SettingDialog.ImgAzyobuziNetDisabledInDM;
7815 _cfgCommon.MapThumbnailProvider = SettingDialog.MapThumbnailProvider;
7816 _cfgCommon.MapThumbnailHeight = SettingDialog.MapThumbnailHeight;
7817 _cfgCommon.MapThumbnailWidth = SettingDialog.MapThumbnailWidth;
7818 _cfgCommon.MapThumbnailZoom = SettingDialog.MapThumbnailZoom;
7819 _cfgCommon.IsListsIncludeRts = SettingDialog.IsListStatusesIncludeRts;
7820 _cfgCommon.TabMouseLock = SettingDialog.TabMouseLock;
7821 _cfgCommon.IsRemoveSameEvent = SettingDialog.IsRemoveSameEvent;
7822 _cfgCommon.IsUseNotifyGrowl = SettingDialog.IsNotifyUseGrowl;
7828 private void SaveConfigsLocal()
7830 if (_ignoreConfigSave) return;
7833 _modifySettingLocal = false;
7834 _cfgLocal.FormSize = _mySize;
7835 _cfgLocal.FormLocation = _myLoc;
7836 _cfgLocal.SplitterDistance = _mySpDis;
7837 _cfgLocal.PreviewDistance = _mySpDis3;
7838 _cfgLocal.StatusMultiline = StatusText.Multiline;
7839 _cfgLocal.StatusTextHeight = _mySpDis2;
7840 _cfgLocal.StatusText = SettingDialog.Status;
7842 _cfgLocal.FontUnread = _fntUnread;
7843 _cfgLocal.ColorUnread = _clUnread;
7844 _cfgLocal.FontRead = _fntReaded;
7845 _cfgLocal.ColorRead = _clReaded;
7846 _cfgLocal.FontDetail = _fntDetail;
7847 _cfgLocal.ColorDetail = _clDetail;
7848 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7849 _cfgLocal.ColorDetailLink = _clDetailLink;
7850 _cfgLocal.ColorFav = _clFav;
7851 _cfgLocal.ColorOWL = _clOWL;
7852 _cfgLocal.ColorRetweet = _clRetweet;
7853 _cfgLocal.ColorSelf = _clSelf;
7854 _cfgLocal.ColorAtSelf = _clAtSelf;
7855 _cfgLocal.ColorTarget = _clTarget;
7856 _cfgLocal.ColorAtTarget = _clAtTarget;
7857 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7858 _cfgLocal.ColorAtTo = _clAtTo;
7859 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7860 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7861 _cfgLocal.ColorInputFont = _clInputFont;
7862 _cfgLocal.FontInputFont = _fntInputFont;
7864 _cfgLocal.BrowserPath = SettingDialog.BrowserPath;
7865 _cfgLocal.UseRecommendStatus = SettingDialog.UseRecommendStatus;
7866 _cfgLocal.ProxyType = SettingDialog.SelectedProxyType;
7867 _cfgLocal.ProxyAddress = SettingDialog.ProxyAddress;
7868 _cfgLocal.ProxyPort = SettingDialog.ProxyPort;
7869 _cfgLocal.ProxyUser = SettingDialog.ProxyUser;
7870 _cfgLocal.ProxyPassword = SettingDialog.ProxyPassword;
7871 if (_ignoreConfigSave) return;
7876 private void SaveConfigsTabs()
7878 SettingTabs tabSetting = new SettingTabs();
7879 for (int i = 0; i < ListTab.TabPages.Count; i++)
7881 if (_statuses.Tabs[ListTab.TabPages[i].Text].TabType != MyCommon.TabUsageType.Related) tabSetting.Tabs.Add(_statuses.Tabs[ListTab.TabPages[i].Text]);
7886 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7889 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7890 if (ret != DialogResult.OK)
7893 var match = Twitter.StatusUrlRegex.Match(inputText);
7896 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7897 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7901 var statusId = long.Parse(match.Groups["StatusId"].Value);
7903 var post = this._statuses[statusId];
7908 post = await Task.Run(() =>
7910 PostClass newPost = null;
7912 var err = this.tw.GetStatusApi(false, statusId, ref newPost);
7913 if (!string.IsNullOrEmpty(err))
7914 throw new WebApiException(err);
7919 catch (WebApiException ex)
7921 var message = ex.InnerException.Message;
7922 MessageBox.Show(this, string.Format(Properties.Resources.OpenURL_LoadFailed, message),
7923 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7930 this.OpenRelatedTab(post);
7932 catch (TabException ex)
7934 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7938 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7940 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7941 Properties.Resources.SaveLogMenuItem_ClickText2,
7942 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7943 if (rslt == DialogResult.Cancel) return;
7945 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7946 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7947 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7948 SaveFileDialog1.FilterIndex = 0;
7949 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7950 SaveFileDialog1.RestoreDirectory = true;
7952 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7954 if (!SaveFileDialog1.ValidateNames) return;
7955 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7957 if (rslt == DialogResult.Yes)
7960 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7962 PostClass post = _statuses[_curTab.Text, idx];
7963 string protect = "";
7964 if (post.IsProtect) protect = "Protect";
7965 sw.WriteLine(post.Nickname + "\t" +
7966 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7967 post.CreatedAt.ToString() + "\t" +
7968 post.ScreenName + "\t" +
7969 post.StatusId.ToString() + "\t" +
7970 post.ImageUrl + "\t" +
7971 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7977 foreach (int idx in _curList.SelectedIndices)
7979 PostClass post = _statuses[_curTab.Text, idx];
7980 string protect = "";
7981 if (post.IsProtect) protect = "Protect";
7982 sw.WriteLine(post.Nickname + "\t" +
7983 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7984 post.CreatedAt.ToString() + "\t" +
7985 post.ScreenName + "\t" +
7986 post.StatusId.ToString() + "\t" +
7987 post.ImageUrl + "\t" +
7988 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7994 this.TopMost = SettingDialog.AlwaysTop;
7997 private void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
7999 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
8000 if (State == ModifierState.NotFlags) return;
8001 bool KeyRes = CommonKeyDown(e.KeyCode, FocusedControl.PostBrowser, State);
8004 e.IsInputKey = true;
8007 public bool TabRename(ref string tabName)
8010 string newTabText = null;
8011 using (InputTabName inputName = new InputTabName())
8013 inputName.TabName = tabName;
8014 inputName.ShowDialog();
8015 if (inputName.DialogResult == DialogResult.Cancel) return false;
8016 newTabText = inputName.TabName;
8018 this.TopMost = SettingDialog.AlwaysTop;
8019 if (!string.IsNullOrEmpty(newTabText))
8022 for (int i = 0; i < ListTab.TabCount; i++)
8024 if (ListTab.TabPages[i].Text == newTabText)
8026 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8027 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8031 //タブ名のリスト作り直し(デフォルトタブ以外は再作成)
8032 for (int i = 0; i < ListTab.TabCount; i++)
8034 if (ListTab.TabPages[i].Text == tabName)
8036 ListTab.TabPages[i].Text = newTabText;
8039 _statuses.RenameTab(tabName, newTabText);
8041 for (int i = 0; i < ListTab.TabCount; i++)
8043 if (_statuses.IsDistributableTab(ListTab.TabPages[i].Text))
8045 if (ListTab.TabPages[i].Text == tabName)
8047 ListTab.TabPages[i].Text = newTabText;
8051 SaveConfigsCommon();
8053 _rclickTabName = newTabText;
8054 tabName = newTabText;
8063 private void ListTab_MouseClick(object sender, MouseEventArgs e)
8065 if (e.Button == MouseButtons.Middle)
8067 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8069 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8071 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8072 this.SaveConfigsTabs();
8079 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8081 string tn = ListTab.SelectedTab.Text;
8085 private void ListTab_MouseDown(object sender, MouseEventArgs e)
8087 if (SettingDialog.TabMouseLock) return;
8088 Point cpos = new Point(e.X, e.Y);
8089 if (e.Button == MouseButtons.Left)
8091 for (int i = 0; i < ListTab.TabPages.Count; i++)
8093 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8096 _tabMouseDownPoint = e.Location;
8107 private void ListTab_DragEnter(object sender, DragEventArgs e)
8109 if (e.Data.GetDataPresent(typeof(TabPage)))
8110 e.Effect = DragDropEffects.Move;
8112 e.Effect = DragDropEffects.None;
8115 private void ListTab_DragDrop(object sender, DragEventArgs e)
8117 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8122 Point cpos = new Point(e.X, e.Y);
8123 Point spos = ListTab.PointToClient(cpos);
8125 for (i = 0; i < ListTab.TabPages.Count; i++)
8127 Rectangle rect = ListTab.GetTabRect(i);
8128 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8129 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8131 tn = ListTab.TabPages[i].Text;
8132 if (spos.X <= (rect.Left + rect.Right) / 2)
8141 //タブのないところにドロップ->最後尾へ移動
8142 if (string.IsNullOrEmpty(tn))
8144 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8146 i = ListTab.TabPages.Count - 1;
8149 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8150 if (tp.Text == tn) return;
8152 ReOrderTab(tp.Text, tn, bef);
8155 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8158 for (baseIndex = 0; baseIndex < ListTab.TabPages.Count; baseIndex++)
8160 if (ListTab.TabPages[baseIndex].Text == baseTabText) break;
8163 using (ControlTransaction.Layout(this.ListTab))
8166 for (int j = 0; j < ListTab.TabPages.Count; j++)
8168 if (ListTab.TabPages[j].Text == targetTabText)
8170 mTp = ListTab.TabPages[j];
8171 ListTab.TabPages.Remove(mTp);
8172 if (j < baseIndex) baseIndex -= 1;
8176 if (isBeforeBaseTab)
8177 ListTab.TabPages.Insert(baseIndex, mTp);
8179 ListTab.TabPages.Insert(baseIndex + 1, mTp);
8185 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8187 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8188 //isReply:true=@,false=DM
8189 if (!StatusText.Enabled) return;
8190 if (_curList == null) return;
8191 if (_curTab == null) return;
8192 if (!this.ExistCurrentPost) return;
8194 // 複数あてリプライはReplyではなく通常ポスト
8195 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8196 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8197 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8199 if (_curList.SelectedIndices.Count > 0)
8202 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8205 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8208 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8209 StatusText.SelectionStart = StatusText.Text.Length;
8211 _reply_to_id = null;
8212 _reply_to_name = null;
8215 if (string.IsNullOrEmpty(StatusText.Text))
8219 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8220 StatusText.Text = "@" + _curPost.ScreenName + " ";
8221 if (_curPost.RetweetedId != null)
8223 _reply_to_id = _curPost.RetweetedId.Value;
8227 _reply_to_id = _curPost.StatusId;
8229 _reply_to_name = _curPost.ScreenName;
8237 //1件選んでEnter or DoubleClick
8238 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8240 if (_reply_to_id != null && _reply_to_name == _curPost.ScreenName)
8243 if (_curPost.RetweetedId != null)
8245 _reply_to_id = _curPost.RetweetedId.Value;
8249 _reply_to_id = _curPost.StatusId;
8251 _reply_to_name = _curPost.ScreenName;
8255 if (!StatusText.Text.StartsWith("@"))
8258 if (StatusText.Text.StartsWith(". "))
8261 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8262 _reply_to_id = null;
8263 _reply_to_name = null;
8268 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8269 if (_curPost.RetweetedId != null)
8271 _reply_to_id = _curPost.RetweetedId.Value;
8275 _reply_to_id = _curPost.StatusId;
8277 _reply_to_name = _curPost.ScreenName;
8284 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8285 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8286 _reply_to_id = null;
8287 _reply_to_name = null;
8292 //1件選んでCtrl-Rの場合(返信先操作せず)
8293 int sidx = StatusText.SelectionStart;
8294 string id = "@" + _curPost.ScreenName + " ";
8297 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8302 StatusText.Text = StatusText.Text.Insert(sidx, id);
8304 //if (StatusText.Text.StartsWith("@"))
8307 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8308 // sidx += 5 + _curPost.ScreenName.Length;
8313 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8314 // sidx += 3 + _curPost.ScreenName.Length;
8316 StatusText.SelectionStart = sidx;
8319 //_reply_to_name = null;
8327 if (!isAuto && !isReply) return;
8329 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8333 //Enter or DoubleClick
8335 string sTxt = StatusText.Text;
8336 if (!sTxt.StartsWith(". "))
8339 _reply_to_id = null;
8340 _reply_to_name = null;
8342 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8344 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[cnt]];
8345 if (!sTxt.Contains("@" + post.ScreenName + " "))
8347 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8348 //sTxt = "@" + post.ScreenName + " " + sTxt;
8351 StatusText.Text = sTxt;
8356 if (_curList.SelectedIndices.Count > 1)
8361 int sidx = StatusText.SelectionStart;
8362 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8364 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[cnt]];
8365 if (!ids.Contains("@" + post.ScreenName + " ") &&
8366 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8368 ids += "@" + post.ScreenName + " ";
8372 foreach (string nm in post.ReplyToList)
8374 if (!ids.Contains("@" + nm + " ") &&
8375 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8377 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8379 ids += "@" + m.Result("${id}") + " ";
8381 ids += "@" + nm + " ";
8386 if (ids.Length == 0) return;
8387 if (!StatusText.Text.StartsWith(". "))
8389 StatusText.Text = ". " + StatusText.Text;
8391 _reply_to_id = null;
8392 _reply_to_name = null;
8396 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8401 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8403 //if (StatusText.Text.StartsWith("@"))
8405 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8406 // sidx += 2 + ids.Length;
8410 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8411 // sidx += 1 + ids.Length;
8413 StatusText.SelectionStart = sidx;
8419 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8422 int sidx = StatusText.SelectionStart;
8423 PostClass post = _curPost;
8424 if (!ids.Contains("@" + post.ScreenName + " ") &&
8425 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8427 ids += "@" + post.ScreenName + " ";
8429 foreach (string nm in post.ReplyToList)
8431 if (!ids.Contains("@" + nm + " ") &&
8432 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8434 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8436 ids += "@" + m.Result("${id}") + " ";
8438 ids += "@" + nm + " ";
8441 if (!string.IsNullOrEmpty(post.RetweetedBy))
8443 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8444 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8446 ids += "@" + post.RetweetedBy + " ";
8449 if (ids.Length == 0) return;
8450 if (string.IsNullOrEmpty(StatusText.Text))
8453 StatusText.Text = ids;
8454 StatusText.SelectionStart = ids.Length;
8456 if (post.RetweetedId != null)
8458 _reply_to_id = post.RetweetedId.Value;
8462 _reply_to_id = post.StatusId;
8464 _reply_to_name = post.ScreenName;
8470 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8475 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8477 StatusText.SelectionStart = sidx;
8483 StatusText.SelectionStart = StatusText.Text.Length;
8488 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8493 private static int iconCnt = 0;
8494 private static int blinkCnt = 0;
8495 private static bool blink = false;
8496 private static bool idle = false;
8498 private void RefreshTasktrayIcon(bool forceRefresh)
8500 if (_colorize) Colorize();
8501 if (!TimerRefreshIcon.Enabled) return;
8502 //Static usCheckCnt As int = 0
8504 //Static iconDlListTopItem As ListViewItem = null
8506 if (forceRefresh) idle = false;
8508 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8509 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8511 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8513 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8519 //if (usCheckCnt > 300) //1min
8522 // if (!this.IsReceivedUserStream)
8524 // TraceOut("ReconnectUserStream");
8525 // tw.ReconnectUserStream();
8530 foreach (BackgroundWorker bw in this._bw)
8532 if (bw != null && bw.IsBusy)
8547 SaveConfigsAll(true);
8552 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8554 _myStatusError = false;
8558 TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8559 if (SettingDialog.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8561 if (blinkCnt > 0) return;
8563 if (blink || SettingDialog.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8565 NotifyIcon1.Icon = ReplyIcon;
8569 NotifyIcon1.Icon = ReplyIconBlink;
8577 //優先度:エラー→オフライン→アイドル
8581 NotifyIcon1.Icon = NIconAtRed;
8584 if (_myStatusOnline)
8586 NotifyIcon1.Icon = NIconAt;
8590 NotifyIcon1.Icon = NIconAtSmoke;
8594 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
8597 this.RefreshTasktrayIcon(false);
8600 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8602 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8603 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8605 if (ListTab != null && ListTab.SelectedTab != null)
8606 _rclickTabName = ListTab.SelectedTab.Text;
8611 if (_statuses == null) return;
8612 if (_statuses.Tabs == null) return;
8614 TabClass tb = _statuses.Tabs[_rclickTabName];
8615 if (tb == null) return;
8617 NotifyDispMenuItem.Checked = tb.Notify;
8618 this.NotifyTbMenuItem.Checked = tb.Notify;
8620 soundfileListup = true;
8621 SoundFileComboBox.Items.Clear();
8622 this.SoundFileTbComboBox.Items.Clear();
8623 SoundFileComboBox.Items.Add("");
8624 this.SoundFileTbComboBox.Items.Add("");
8625 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8626 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8628 oDir = oDir.GetDirectories("Sounds")[0];
8630 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8632 SoundFileComboBox.Items.Add(oFile.Name);
8633 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8635 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8636 if (idx == -1) idx = 0;
8637 SoundFileComboBox.SelectedIndex = idx;
8638 this.SoundFileTbComboBox.SelectedIndex = idx;
8639 soundfileListup = false;
8640 UreadManageMenuItem.Checked = tb.UnreadManage;
8641 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8643 TabMenuControl(_rclickTabName);
8646 private void TabMenuControl(string tabName)
8648 this.FilterEditMenuItem.Enabled = true;
8649 this.EditRuleTbMenuItem.Enabled = true;
8651 if (_statuses.IsDefaultTab(tabName))
8653 this.ProtectTabMenuItem.Enabled = false;
8654 this.ProtectTbMenuItem.Enabled = false;
8658 this.ProtectTabMenuItem.Enabled = true;
8659 this.ProtectTbMenuItem.Enabled = true;
8662 if (_statuses.IsDefaultTab(tabName) || _statuses.Tabs[tabName].Protected)
8664 this.ProtectTabMenuItem.Checked = true;
8665 this.ProtectTbMenuItem.Checked = true;
8666 this.DeleteTabMenuItem.Enabled = false;
8667 this.DeleteTbMenuItem.Enabled = false;
8671 this.ProtectTabMenuItem.Checked = false;
8672 this.ProtectTbMenuItem.Checked = false;
8673 this.DeleteTabMenuItem.Enabled = true;
8674 this.DeleteTbMenuItem.Enabled = true;
8678 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8680 var checkState = ((ToolStripMenuItem)sender).Checked;
8683 this.ProtectTbMenuItem.Checked = checkState;
8684 this.ProtectTabMenuItem.Checked = checkState;
8687 this.DeleteTabMenuItem.Enabled = !checkState;
8688 this.DeleteTbMenuItem.Enabled = !checkState;
8690 if (string.IsNullOrEmpty(_rclickTabName)) return;
8691 _statuses.Tabs[_rclickTabName].Protected = checkState;
8696 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8698 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8699 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8701 if (string.IsNullOrEmpty(_rclickTabName)) return;
8702 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8707 public void ChangeTabUnreadManage(string tabName, bool isManage)
8710 for (idx = 0; idx < ListTab.TabCount; idx++)
8712 if (ListTab.TabPages[idx].Text == tabName) break;
8715 _statuses.SetTabUnreadManage(tabName, isManage);
8716 if (SettingDialog.TabIconDisp)
8718 if (_statuses.Tabs[tabName].UnreadCount > 0)
8719 ListTab.TabPages[idx].ImageIndex = 0;
8721 ListTab.TabPages[idx].ImageIndex = -1;
8724 if (_curTab.Text == tabName)
8726 this.PurgeListViewItemCache();
8730 SetMainWindowTitle();
8731 SetStatusLabelUrl();
8732 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
8735 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8737 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8738 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8740 if (string.IsNullOrEmpty(_rclickTabName)) return;
8742 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8747 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8749 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8751 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8756 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8758 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8760 RemoveSpecifiedTab(_rclickTabName, true);
8764 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8766 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8767 fltDialog.SetCurrent(_rclickTabName);
8768 fltDialog.ShowDialog(this);
8769 this.TopMost = SettingDialog.AlwaysTop;
8771 this.ApplyPostFilters();
8775 private void AddTabMenuItem_Click(object sender, EventArgs e)
8777 string tabName = null;
8778 MyCommon.TabUsageType tabUsage;
8779 using (InputTabName inputName = new InputTabName())
8781 inputName.TabName = _statuses.GetUniqueTabName();
8782 inputName.IsShowUsage = true;
8783 inputName.ShowDialog();
8784 if (inputName.DialogResult == DialogResult.Cancel) return;
8785 tabName = inputName.TabName;
8786 tabUsage = inputName.Usage;
8788 this.TopMost = SettingDialog.AlwaysTop;
8789 if (!string.IsNullOrEmpty(tabName))
8792 ListElement list = null;
8793 if (tabUsage == MyCommon.TabUsageType.Lists)
8795 using (ListAvailable listAvail = new ListAvailable())
8797 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8798 if (listAvail.SelectedList == null) return;
8799 list = listAvail.SelectedList;
8802 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8804 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8805 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8811 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8813 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8814 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
8815 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8817 if (tabUsage == MyCommon.TabUsageType.Lists)
8819 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8820 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
8821 GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, tabName);
8827 private void TabMenuItem_Click(object sender, EventArgs e)
8830 foreach (int idx in _curList.SelectedIndices)
8834 if (!SelectTab(out tabName)) return;
8836 fltDialog.SetCurrent(tabName);
8837 if (_statuses[_curTab.Text, idx].RetweetedId == null)
8839 fltDialog.AddNewFilter(_statuses[_curTab.Text, idx].ScreenName, _statuses[_curTab.Text, idx].TextFromApi);
8843 fltDialog.AddNewFilter(_statuses[_curTab.Text, idx].RetweetedBy, _statuses[_curTab.Text, idx].TextFromApi);
8845 fltDialog.ShowDialog(this);
8846 this.TopMost = SettingDialog.AlwaysTop;
8849 this.ApplyPostFilters();
8851 if (this.ListTab.SelectedTab != null &&
8852 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8854 _curPost = _statuses[this.ListTab.SelectedTab.Text, ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8858 protected override bool ProcessDialogKey(Keys keyData)
8860 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8861 if ((keyData & Keys.KeyCode) == Keys.Enter)
8863 if (StatusText.Focused)
8865 bool _NewLine = false;
8868 if (SettingDialog.PostCtrlEnter) //Ctrl+Enter投稿時
8870 if (StatusText.Multiline)
8872 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8874 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8878 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8882 else if (SettingDialog.PostShiftEnter) //SHift+Enter投稿時
8884 if (StatusText.Multiline)
8886 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8888 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8892 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8898 if (StatusText.Multiline)
8900 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8902 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8903 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8907 if (((keyData & Keys.Shift) == Keys.Shift) ||
8908 (((keyData & Keys.Control) != Keys.Control) &&
8909 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8915 int pos1 = StatusText.SelectionStart;
8916 if (StatusText.SelectionLength > 0)
8918 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8920 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8921 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8926 PostButton_Click(null, null);
8930 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8931 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8932 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8934 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8939 return base.ProcessDialogKey(keyData);
8942 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8944 MakeReplyOrDirectStatus(false, true, true);
8947 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8952 if (_curList.SelectedIndices.Count == 0) return;
8955 if (!SelectTab(out tabName)) return;
8959 MoveOrCopy(ref mv, ref mk);
8961 List<string> ids = new List<string>();
8962 foreach (int idx in _curList.SelectedIndices)
8964 PostClass post = _statuses[_curTab.Text, idx];
8965 if (!ids.Contains(post.ScreenName))
8967 PostFilterRule fc = new PostFilterRule();
8968 ids.Add(post.ScreenName);
8969 if (post.RetweetedId == null)
8971 fc.FilterName = post.ScreenName;
8975 fc.FilterName = post.RetweetedBy;
8977 fc.UseNameField = true;
8978 fc.MoveMatches = mv;
8979 fc.MarkMatches = mk;
8980 fc.UseRegex = false;
8981 fc.FilterByUrl = false;
8982 _statuses.Tabs[tabName].AddFilter(fc);
8987 List<string> atids = new List<string>();
8988 foreach (string id in ids)
8990 atids.Add("@" + id);
8992 int cnt = AtIdSupl.ItemCount;
8993 AtIdSupl.AddRangeItem(atids.ToArray());
8994 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
8997 this.ApplyPostFilters();
9001 private bool SelectTab(out string tabName)
9008 using (var dialog = new TabsDialog(_statuses))
9010 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9012 var selectedTab = dialog.SelectedTab;
9013 tabName = selectedTab == null ? null : selectedTab.TabName;
9016 ListTab.SelectedTab.Focus();
9018 if (tabName == null)
9020 using (InputTabName inputName = new InputTabName())
9022 inputName.TabName = _statuses.GetUniqueTabName();
9023 inputName.ShowDialog();
9024 if (inputName.DialogResult == DialogResult.Cancel) return false;
9025 tabName = inputName.TabName;
9027 this.TopMost = SettingDialog.AlwaysTop;
9028 if (!string.IsNullOrEmpty(tabName))
9030 if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9032 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9033 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9051 private void MoveOrCopy(ref bool move, ref bool mark)
9055 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9056 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9064 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9065 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9071 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9076 private void CopyURLMenuItem_Click(object sender, EventArgs e)
9081 private void SelectAllMenuItem_Click(object sender, EventArgs e)
9083 if (StatusText.Focused)
9086 StatusText.SelectAll();
9090 // ListView上でのCtrl+A
9091 for (int i = 0; i < _curList.VirtualListSize; i++)
9093 _curList.SelectedIndices.Add(i);
9098 private void MoveMiddle()
9104 if (_curList.SelectedIndices.Count == 0) return;
9106 int idx = _curList.SelectedIndices[0];
9108 _item = _curList.GetItemAt(0, 25);
9114 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9116 idx2 = _curList.VirtualListSize - 1;
9120 idx -= Math.Abs(idx1 - idx2) / 2;
9121 if (idx < 0) idx = 0;
9123 _curList.EnsureVisible(_curList.VirtualListSize - 1);
9124 _curList.EnsureVisible(idx);
9127 private void OpenURLMenuItem_Click(object sender, EventArgs e)
9129 if (PostBrowser.Document.Links.Count > 0)
9131 UrlDialog.ClearUrl();
9133 string openUrlStr = "";
9135 if (PostBrowser.Document.Links.Count == 1)
9140 urlStr = MyCommon.IDNEncode(PostBrowser.Document.Links[0].GetAttribute("href"));
9142 catch (ArgumentException)
9151 if (string.IsNullOrEmpty(urlStr)) return;
9152 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9156 foreach (HtmlElement linkElm in PostBrowser.Document.Links)
9159 string linkText = "";
9163 urlStr = linkElm.GetAttribute("title");
9164 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9165 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9166 linkText = linkElm.InnerText;
9167 if (!linkText.StartsWith("http") && !linkText.StartsWith("#") && !linkText.Contains("."))
9169 linkText = "@" + linkText;
9172 catch (ArgumentException)
9181 if (string.IsNullOrEmpty(urlStr)) continue;
9182 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9186 if (UrlDialog.ShowDialog() == DialogResult.OK)
9188 openUrlStr = UrlDialog.SelectedUrl;
9195 this.TopMost = SettingDialog.AlwaysTop;
9197 if (string.IsNullOrEmpty(openUrlStr)) return;
9199 if (openUrlStr.StartsWith("http://twitter.com/search?q=") ||
9200 openUrlStr.StartsWith("https://twitter.com/search?q="))
9203 string urlStr = Uri.UnescapeDataString(openUrlStr);
9204 string hash = urlStr.Substring(urlStr.IndexOf("#"));
9205 HashSupl.AddItem(hash);
9206 HashMgr.AddHashToHistory(hash.Trim(), false);
9207 AddNewTabForSearch(hash);
9212 Match m = Regex.Match(openUrlStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9213 if (SettingDialog.OpenUserTimeline && m.Success && IsTwitterId(m.Result("${ScreenName}")))
9214 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
9216 OpenUriAsync(openUrlStr);
9222 private void ClearTabMenuItem_Click(object sender, EventArgs e)
9224 if (string.IsNullOrEmpty(_rclickTabName)) return;
9225 ClearTab(_rclickTabName, true);
9228 private void ClearTab(string tabName, bool showWarning)
9232 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9233 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9239 _statuses.ClearTabIds(tabName);
9240 if (ListTab.SelectedTab.Text == tabName)
9243 _anchorFlag = false;
9244 this.PurgeListViewItemCache();
9248 foreach (TabPage tb in ListTab.TabPages)
9250 if (tb.Text == tabName)
9253 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9257 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
9259 SetMainWindowTitle();
9260 SetStatusLabelUrl();
9263 private static long followers = 0;
9265 private void SetMainWindowTitle()
9268 StringBuilder ttl = new StringBuilder(256);
9271 if (SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.None &&
9272 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9273 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9274 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9276 foreach (var tab in _statuses.Tabs.Values)
9278 ur += tab.UnreadCount;
9283 if (SettingDialog.DispUsername) ttl.Append(tw.Username).Append(" - ");
9284 ttl.Append(Application.ProductName);
9286 switch (SettingDialog.DispLatestPost)
9288 case MyCommon.DispTitleEnum.Ver:
9289 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9291 case MyCommon.DispTitleEnum.Post:
9292 if (_history != null && _history.Count > 1)
9293 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9295 case MyCommon.DispTitleEnum.UnreadRepCount:
9296 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9298 case MyCommon.DispTitleEnum.UnreadAllCount:
9299 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9301 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9302 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9304 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9305 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9307 case MyCommon.DispTitleEnum.OwnStatus:
9308 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9309 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9315 this.Text = ttl.ToString();
9317 catch (AccessViolationException)
9319 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9323 private string GetStatusLabelText()
9326 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9327 if (_statuses == null) return "";
9328 TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9329 TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9330 if (tbRep == null || tbDm == null) return "";
9331 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9336 StringBuilder slbl = new StringBuilder(256);
9339 foreach (var tab in _statuses.Tabs.Values)
9341 ur += tab.UnreadCount;
9343 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9345 tur = tab.UnreadCount;
9356 UnreadAtCounter = urat;
9358 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9359 if (SettingDialog.TimelinePeriodInt == 0)
9361 slbl.Append(Properties.Resources.SetStatusLabelText2);
9365 slbl.Append(SettingDialog.TimelinePeriodInt.ToString() + Properties.Resources.SetStatusLabelText3);
9367 return slbl.ToString();
9370 private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9374 if (this.InvokeRequired && !this.IsDisposed)
9376 this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9380 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9381 if (endpointName == "/statuses/home_timeline" || endpointName == null)
9383 this._apiGauge.ApiLimit = MyCommon.TwitterApiInfo.AccessLimit["/statuses/home_timeline"];
9387 catch (ObjectDisposedException)
9391 catch (InvalidOperationException)
9397 private void SetStatusLabelUrl()
9399 StatusLabelUrl.Text = GetStatusLabelText();
9402 public void SetStatusLabel(string text)
9404 StatusLabel.Text = text;
9407 private static StringBuilder ur = new StringBuilder(64);
9409 private void SetNotifyIconText()
9411 // タスクトレイアイコンのツールチップテキスト書き換え
9413 ur.Remove(0, ur.Length);
9414 if (SettingDialog.DispUsername)
9416 ur.Append(tw.Username);
9419 ur.Append(Application.ProductName);
9421 ur.Append("(Debug Build)");
9423 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9426 ur.Append(UnreadCounter);
9428 ur.Append(UnreadAtCounter);
9431 NotifyIcon1.Text = ur.ToString();
9434 internal void CheckReplyTo(string StatusText)
9438 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9440 foreach (Match hm in m)
9442 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9444 hstr += "#" + hm.Result("$3") + " ";
9445 HashSupl.AddItem("#" + hm.Result("$3"));
9448 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9450 hstr += HashMgr.UseHash;
9452 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9454 // 本当にリプライ先指定すべきかどうかの判定
9455 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9457 if (SettingDialog.UseAtIdSupplement)
9459 int bCnt = AtIdSupl.ItemCount;
9460 foreach (Match mid in m)
9462 AtIdSupl.AddItem(mid.Result("${id}"));
9464 if (bCnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
9467 // リプライ先ステータスIDの指定がない場合は指定しない
9468 if (_reply_to_id == null) return;
9470 // リプライ先ユーザー名がない場合も指定しない
9471 if (string.IsNullOrEmpty(_reply_to_name))
9473 _reply_to_id = null;
9478 // 次の条件を満たす場合に in_reply_to_status_id 指定
9479 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9480 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9481 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9485 if (StatusText.StartsWith("@"))
9487 if (StatusText.StartsWith("@" + _reply_to_name)) return;
9491 foreach (Match mid in m)
9493 if (StatusText.Contains("QT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + _reply_to_name) return;
9498 _reply_to_id = null;
9499 _reply_to_name = null;
9503 private void TweenMain_Resize(object sender, EventArgs e)
9505 if (!_initialLayout && SettingDialog.MinimizeToTray && WindowState == FormWindowState.Minimized)
9507 this.Visible = false;
9509 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9511 this.ClientSize = _cfgLocal.FormSize;
9512 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9513 this.DesktopLocation = _cfgLocal.FormLocation;
9514 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9515 if (_cfgLocal.SplitterDistance > this.SplitContainer1.Panel1MinSize &&
9516 _cfgLocal.SplitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9518 this.SplitContainer1.SplitterDistance = _cfgLocal.SplitterDistance; //Splitterの位置設定
9521 StatusText.Multiline = _cfgLocal.StatusMultiline;
9522 if (StatusText.Multiline)
9524 int dis = SplitContainer2.Height - _cfgLocal.StatusTextHeight - SplitContainer2.SplitterWidth;
9525 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9527 SplitContainer2.SplitterDistance = SplitContainer2.Height - _cfgLocal.StatusTextHeight - SplitContainer2.SplitterWidth;
9529 StatusText.Height = _cfgLocal.StatusTextHeight;
9533 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9535 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9538 if (_cfgLocal.PreviewDistance > this.SplitContainer3.Panel1MinSize && _cfgLocal.PreviewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9540 this.SplitContainer3.SplitterDistance = _cfgLocal.PreviewDistance;
9542 _initialLayout = false;
9544 if (this.WindowState != FormWindowState.Minimized)
9546 _formWindowState = this.WindowState;
9550 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9552 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9553 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9554 if (PlaySoundMenuItem.Checked)
9556 SettingDialog.PlaySound = true;
9560 SettingDialog.PlaySound = false;
9562 _modifySettingCommon = true;
9565 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9567 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
9569 _mySpDis = SplitContainer1.SplitterDistance;
9570 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9571 _modifySettingLocal = true;
9575 private void doRepliedStatusOpen()
9577 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9579 if (MyCommon.IsKeyDown(Keys.Shift))
9581 OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9584 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9586 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9587 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9591 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9593 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9594 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9595 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9598 OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9603 private void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9605 doRepliedStatusOpen();
9609 /// UserPicture.Image に設定されている画像を破棄します。
9611 private void ClearUserPicture()
9613 if (this.UserPicture.Image != null)
9615 var oldImage = this.UserPicture.Image;
9616 this.UserPicture.Image = null;
9621 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9623 //発言詳細のアイコン右クリック時のメニュー制御
9624 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9626 string name = _curPost.ImageUrl;
9627 if (name != null && name.Length > 0)
9629 int idx = name.LastIndexOf('/');
9632 name = Path.GetFileName(name.Substring(idx));
9633 if (name.Contains("_normal.") || name.EndsWith("_normal"))
9635 name = name.Replace("_normal", "");
9636 this.IconNameToolStripMenuItem.Text = name;
9637 this.IconNameToolStripMenuItem.Enabled = true;
9641 this.IconNameToolStripMenuItem.Enabled = false;
9642 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9647 this.IconNameToolStripMenuItem.Enabled = false;
9648 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9651 this.ReloadIconToolStripMenuItem.Enabled = true;
9653 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9655 this.SaveIconPictureToolStripMenuItem.Enabled = true;
9659 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9664 this.IconNameToolStripMenuItem.Enabled = false;
9665 this.ReloadIconToolStripMenuItem.Enabled = false;
9666 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9667 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9672 this.IconNameToolStripMenuItem.Enabled = false;
9673 this.ReloadIconToolStripMenuItem.Enabled = false;
9674 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9675 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9677 if (NameLabel.Tag != null)
9679 string id = (string)NameLabel.Tag;
9680 if (id == tw.Username)
9682 FollowToolStripMenuItem.Enabled = false;
9683 UnFollowToolStripMenuItem.Enabled = false;
9684 ShowFriendShipToolStripMenuItem.Enabled = false;
9685 ShowUserStatusToolStripMenuItem.Enabled = true;
9686 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9687 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9688 ListManageUserContextToolStripMenuItem3.Enabled = true;
9692 FollowToolStripMenuItem.Enabled = true;
9693 UnFollowToolStripMenuItem.Enabled = true;
9694 ShowFriendShipToolStripMenuItem.Enabled = true;
9695 ShowUserStatusToolStripMenuItem.Enabled = true;
9696 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9697 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9698 ListManageUserContextToolStripMenuItem3.Enabled = true;
9703 FollowToolStripMenuItem.Enabled = false;
9704 UnFollowToolStripMenuItem.Enabled = false;
9705 ShowFriendShipToolStripMenuItem.Enabled = false;
9706 ShowUserStatusToolStripMenuItem.Enabled = false;
9707 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9708 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9709 ListManageUserContextToolStripMenuItem3.Enabled = false;
9713 private void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9715 if (_curPost == null) return;
9716 string name = _curPost.ImageUrl;
9717 OpenUriAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9720 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9722 if (this._curPost == null) return;
9724 var imageUrl = this._curPost.ImageUrl;
9727 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true);
9729 this.ClearUserPicture();
9730 this.UserPicture.Image = image.Clone();
9734 this.UserPicture.ShowErrorImage();
9739 catch (HttpRequestException) { }
9740 catch (InvalidImageException) { }
9741 catch (TaskCanceledException) { }
9745 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9747 if (_curPost == null) return;
9748 string name = _curPost.ImageUrl;
9749 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
9751 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
9753 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9759 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9761 if (_curPost == null) return;
9762 string name = _curPost.ImageUrl;
9764 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
9766 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9770 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
9772 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
9774 using (Graphics g = Graphics.FromImage(bmp2))
9776 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
9777 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
9779 bmp2.Save(this.SaveFileDialog1.FileName);
9785 //処理中にキャッシュアウトする可能性あり
9790 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9792 this.StatusText.Multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9793 MultiLineMenuItem.Checked = this.StatusText.Multiline;
9794 _modifySettingLocal = true;
9797 private void StatusText_MultilineChanged(object sender, EventArgs e)
9799 if (this.StatusText.Multiline)
9800 this.StatusText.ScrollBars = ScrollBars.Vertical;
9802 this.StatusText.ScrollBars = ScrollBars.None;
9804 _modifySettingLocal = true;
9807 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9810 StatusText.Multiline = MultiLineMenuItem.Checked;
9811 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
9812 if (MultiLineMenuItem.Checked)
9814 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9815 SplitContainer2.SplitterDistance = 0;
9817 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9821 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9823 _modifySettingLocal = true;
9826 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9828 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9829 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9831 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9832 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9833 //Appendix A. Collected ABNF for URI
9834 //http://www.ietf.org/rfc/rfc3986.txt
9838 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9840 if (StatusText.SelectionLength > 0)
9842 string tmp = StatusText.SelectedText;
9843 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9844 if (tmp.StartsWith("http"))
9846 // 文字列が選択されている場合はその文字列について処理
9848 //nico.ms使用、nicovideoにマッチしたら変換
9849 if (SettingDialog.Nicoms && Regex.IsMatch(tmp, nico))
9851 result = nicoms.Shorten(tmp);
9853 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9855 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9858 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9859 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9860 result = resultUri.ToString();
9862 catch (WebApiException e)
9864 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9867 catch (UriFormatException e)
9869 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9878 if (!string.IsNullOrEmpty(result))
9880 urlUndo undotmp = new urlUndo();
9882 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
9883 StatusText.SelectedText = result;
9886 undotmp.Before = tmp;
9887 undotmp.After = result;
9889 if (urlUndoBuffer == null)
9891 urlUndoBuffer = new List<urlUndo>();
9892 UrlUndoToolStripMenuItem.Enabled = true;
9895 urlUndoBuffer.Add(undotmp);
9901 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9902 @"(?<url>(?<protocol>https?://)" +
9903 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9904 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9905 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9906 // 正規表現にマッチしたURL文字列をtinyurl化
9907 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9909 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9910 string tmp = mt.Result("${url}");
9911 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9912 urlUndo undotmp = new urlUndo();
9915 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9917 //nico.ms使用、nicovideoにマッチしたら変換
9918 if (SettingDialog.Nicoms && Regex.IsMatch(tmp, nico))
9920 result = nicoms.Shorten(tmp);
9922 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9924 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9927 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9928 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9929 result = resultUri.ToString();
9931 catch (WebApiException e)
9933 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9936 catch (UriFormatException e)
9938 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9947 if (!string.IsNullOrEmpty(result))
9949 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9950 StatusText.SelectedText = result;
9952 undotmp.Before = mt.Result("${url}");
9953 undotmp.After = result;
9955 if (urlUndoBuffer == null)
9957 urlUndoBuffer = new List<urlUndo>();
9958 UrlUndoToolStripMenuItem.Enabled = true;
9961 urlUndoBuffer.Add(undotmp);
9969 private void doUrlUndo()
9971 if (urlUndoBuffer != null)
9973 string tmp = StatusText.Text;
9974 foreach (urlUndo data in urlUndoBuffer)
9976 tmp = tmp.Replace(data.After, data.Before);
9978 StatusText.Text = tmp;
9979 urlUndoBuffer = null;
9980 UrlUndoToolStripMenuItem.Enabled = false;
9981 StatusText.SelectionStart = 0;
9982 StatusText.SelectionLength = 0;
9986 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9988 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9991 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9993 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9996 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9998 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10001 private async void UxnuMenuItem_Click(object sender, EventArgs e)
10003 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10006 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10008 if (!await UrlConvertAsync(SettingDialog.AutoShortUrlFirst))
10010 MyCommon.UrlConverter svc = SettingDialog.AutoShortUrlFirst;
10011 Random rnd = new Random();
10012 // 前回使用した短縮URLサービス以外を選択する
10015 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10017 while (svc == SettingDialog.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10018 await UrlConvertAsync(svc);
10022 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10027 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10029 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10030 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10031 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10032 _modifySettingCommon = true;
10035 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10037 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10038 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10039 _cfgCommon.ListLock = ListLockMenuItem.Checked;
10040 _modifySettingCommon = true;
10043 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10045 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10046 MenuStrip1.Tag = new Object();
10047 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10050 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10052 if (this.Tag != null) // 設定された戻り先へ遷移
10054 if (this.Tag == this.ListTab.SelectedTab)
10055 ((Control)this.ListTab.SelectedTab.Tag).Select();
10057 ((Control)this.Tag).Select();
10059 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10061 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10063 this.Tag = ListTab.SelectedTab.Tag;
10064 ((Control)this.Tag).Select();
10067 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10068 MenuStrip1.Tag = null;
10071 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10073 DetailsListView lst = (DetailsListView)sender;
10074 if (_cfgLocal == null) return;
10078 _cfgLocal.Width1 = lst.Columns[0].Width;
10079 _cfgLocal.Width3 = lst.Columns[1].Width;
10083 int[] darr = new int[lst.Columns.Count];
10084 for (int i = 0; i < lst.Columns.Count; i++)
10086 darr[lst.Columns[i].DisplayIndex] = i;
10088 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10090 for (int i = 0; i < lst.Columns.Count; i++)
10095 _cfgLocal.DisplayIndex1 = i;
10098 _cfgLocal.DisplayIndex2 = i;
10101 _cfgLocal.DisplayIndex3 = i;
10104 _cfgLocal.DisplayIndex4 = i;
10107 _cfgLocal.DisplayIndex5 = i;
10110 _cfgLocal.DisplayIndex6 = i;
10113 _cfgLocal.DisplayIndex7 = i;
10116 _cfgLocal.DisplayIndex8 = i;
10120 _cfgLocal.Width1 = lst.Columns[0].Width;
10121 _cfgLocal.Width2 = lst.Columns[1].Width;
10122 _cfgLocal.Width3 = lst.Columns[2].Width;
10123 _cfgLocal.Width4 = lst.Columns[3].Width;
10124 _cfgLocal.Width5 = lst.Columns[4].Width;
10125 _cfgLocal.Width6 = lst.Columns[5].Width;
10126 _cfgLocal.Width7 = lst.Columns[6].Width;
10127 _cfgLocal.Width8 = lst.Columns[7].Width;
10129 _modifySettingLocal = true;
10130 _isColumnChanged = true;
10133 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10135 DetailsListView lst = (DetailsListView)sender;
10136 if (_cfgLocal == null) return;
10139 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10141 _cfgLocal.Width1 = lst.Columns[0].Width;
10142 _modifySettingLocal = true;
10143 _isColumnChanged = true;
10145 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10147 _cfgLocal.Width3 = lst.Columns[1].Width;
10148 _modifySettingLocal = true;
10149 _isColumnChanged = true;
10154 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10156 _cfgLocal.Width1 = lst.Columns[0].Width;
10157 _modifySettingLocal = true;
10158 _isColumnChanged = true;
10160 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10162 _cfgLocal.Width2 = lst.Columns[1].Width;
10163 _modifySettingLocal = true;
10164 _isColumnChanged = true;
10166 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10168 _cfgLocal.Width3 = lst.Columns[2].Width;
10169 _modifySettingLocal = true;
10170 _isColumnChanged = true;
10172 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10174 _cfgLocal.Width4 = lst.Columns[3].Width;
10175 _modifySettingLocal = true;
10176 _isColumnChanged = true;
10178 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10180 _cfgLocal.Width5 = lst.Columns[4].Width;
10181 _modifySettingLocal = true;
10182 _isColumnChanged = true;
10184 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10186 _cfgLocal.Width6 = lst.Columns[5].Width;
10187 _modifySettingLocal = true;
10188 _isColumnChanged = true;
10190 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10192 _cfgLocal.Width7 = lst.Columns[6].Width;
10193 _modifySettingLocal = true;
10194 _isColumnChanged = true;
10196 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10198 _cfgLocal.Width8 = lst.Columns[7].Width;
10199 _modifySettingLocal = true;
10200 _isColumnChanged = true;
10203 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10206 // SaveConfigsLocal();
10210 public string WebBrowser_GetSelectionText(ref WebBrowser ComponentInstance)
10212 //発言詳細で「選択文字列をコピー」を行う
10213 //WebBrowserコンポーネントのインスタンスを渡す
10214 Type typ = ComponentInstance.ActiveXInstance.GetType();
10215 object _SelObj = typ.InvokeMember("selection", BindingFlags.GetProperty, null, ComponentInstance.Document.DomDocument, null);
10216 object _objRange = _SelObj.GetType().InvokeMember("createRange", BindingFlags.InvokeMethod, null, _SelObj, null);
10217 return (string)_objRange.GetType().InvokeMember("text", BindingFlags.GetProperty, null, _objRange, null);
10220 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10223 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10226 Clipboard.SetDataObject(_selText, false, 5, 100);
10228 catch (Exception ex)
10230 MessageBox.Show(ex.Message);
10234 private void doSearchToolStrip(string url)
10236 //発言詳細で「選択文字列で検索」(選択文字列取得)
10237 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10239 if (_selText != null)
10241 if (url == Properties.Resources.SearchItem4Url)
10244 AddNewTabForSearch(_selText);
10248 string tmp = string.Format(url, Uri.EscapeUriString(_selText));
10253 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10256 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10259 private void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10261 doSearchToolStrip(Properties.Resources.SearchItem1Url);
10264 private void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10266 doSearchToolStrip(Properties.Resources.SearchItem2Url);
10269 private void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10271 doSearchToolStrip(Properties.Resources.SearchItem4Url);
10274 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10278 MatchCollection mc = Regex.Matches(this.PostBrowser.DocumentText, @"<a[^>]*href=""(?<url>" + this._postBrowserStatusText.Replace(".", @"\.") + @")""[^>]*title=""(?<title>https?://[^""]+)""", RegexOptions.IgnoreCase);
10279 foreach (Match m in mc)
10281 if (m.Groups["url"].Value == this._postBrowserStatusText)
10283 Clipboard.SetDataObject(m.Groups["title"].Value, false, 5, 100);
10289 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10291 //Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10293 catch (Exception ex)
10295 MessageBox.Show(ex.Message);
10299 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10301 // URLコピーの項目の表示/非表示
10302 if (PostBrowser.StatusText.StartsWith("http"))
10304 this._postBrowserStatusText = PostBrowser.StatusText;
10305 string name = GetUserId();
10306 UrlCopyContextMenuItem.Enabled = true;
10309 FollowContextMenuItem.Enabled = true;
10310 RemoveContextMenuItem.Enabled = true;
10311 FriendshipContextMenuItem.Enabled = true;
10312 ShowUserStatusContextMenuItem.Enabled = true;
10313 SearchPostsDetailToolStripMenuItem.Enabled = true;
10314 IdFilterAddMenuItem.Enabled = true;
10315 ListManageUserContextToolStripMenuItem.Enabled = true;
10316 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10320 FollowContextMenuItem.Enabled = false;
10321 RemoveContextMenuItem.Enabled = false;
10322 FriendshipContextMenuItem.Enabled = false;
10323 ShowUserStatusContextMenuItem.Enabled = false;
10324 SearchPostsDetailToolStripMenuItem.Enabled = false;
10325 IdFilterAddMenuItem.Enabled = false;
10326 ListManageUserContextToolStripMenuItem.Enabled = false;
10327 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10330 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10331 UseHashtagMenuItem.Enabled = true;
10333 UseHashtagMenuItem.Enabled = false;
10337 this._postBrowserStatusText = "";
10338 UrlCopyContextMenuItem.Enabled = false;
10339 FollowContextMenuItem.Enabled = false;
10340 RemoveContextMenuItem.Enabled = false;
10341 FriendshipContextMenuItem.Enabled = false;
10342 ShowUserStatusContextMenuItem.Enabled = false;
10343 SearchPostsDetailToolStripMenuItem.Enabled = false;
10344 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10345 UseHashtagMenuItem.Enabled = false;
10346 IdFilterAddMenuItem.Enabled = false;
10347 ListManageUserContextToolStripMenuItem.Enabled = false;
10349 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10350 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10351 if (_selText == null)
10353 SelectionSearchContextMenuItem.Enabled = false;
10354 SelectionCopyContextMenuItem.Enabled = false;
10355 SelectionTranslationToolStripMenuItem.Enabled = false;
10359 SelectionSearchContextMenuItem.Enabled = true;
10360 SelectionCopyContextMenuItem.Enabled = true;
10361 SelectionTranslationToolStripMenuItem.Enabled = true;
10363 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10364 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10365 bool fAllFlag = false;
10366 foreach (Match mu in ma)
10368 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
10374 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10376 if (_curPost == null)
10377 TranslationToolStripMenuItem.Enabled = false;
10379 TranslationToolStripMenuItem.Enabled = true;
10384 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10386 //発言詳細の選択文字列で現在のタブを検索
10387 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10389 if (_selText != null)
10391 var searchOptions = new SearchWordDialog.SearchOptions(
10392 SearchWordDialog.SearchType.Timeline,
10395 caseSensitive: false,
10398 this.SearchDialog.ResultOptions = searchOptions;
10401 searchOptions.Query,
10402 searchOptions.CaseSensitive,
10403 searchOptions.UseRegex,
10404 SEARCHTYPE.NextSearch);
10408 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10410 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10411 _modifySettingLocal = true;
10414 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10416 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10418 SelectMedia_DragDrop(e);
10420 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10422 var url = GetUrlFromDataObject(e.Data);
10425 if (url.Item2 == null)
10426 appendText = url.Item1;
10428 appendText = url.Item2 + " " + url.Item1;
10430 if (this.StatusText.TextLength == 0)
10431 this.StatusText.Text = appendText;
10433 this.StatusText.Text += " " + appendText;
10435 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10437 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10438 if (data != null) StatusText.Text += data;
10443 /// IDataObject から URL とタイトルの対を取得します
10446 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10448 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10449 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10450 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10452 if (data.GetDataPresent("text/x-moz-url"))
10454 // Firefox, Google Chrome で利用可能
10455 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10457 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10459 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10460 if (lines.Length < 2)
10461 throw new ArgumentException("不正な text/x-moz-url フォーマットです", "data");
10463 return new Tuple<string, string>(lines[0], lines[1]);
10466 else if (data.GetDataPresent("IESiteModeToUrl"))
10468 // Internet Exproler 用
10469 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10471 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10473 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10474 if (lines.Length < 2)
10475 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", "data");
10477 return new Tuple<string, string>(lines[0], lines[1]);
10480 else if (data.GetDataPresent("UniformResourceLocatorW"))
10484 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10486 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10487 return new Tuple<string, string>(url, null);
10491 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10494 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10496 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10498 SelectMedia_DragEnter(e);
10502 private void TweenMain_DragOver(object sender, DragEventArgs e)
10504 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10506 SelectMedia_DragOver(e);
10508 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10510 e.Effect = DragDropEffects.Copy;
10512 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10514 e.Effect = DragDropEffects.Copy;
10518 e.Effect = DragDropEffects.None;
10522 public bool IsNetworkAvailable()
10525 nw = MyCommon.IsNetworkAvailable();
10526 _myStatusOnline = nw;
10530 public Task OpenUriAsync(string UriString)
10532 return Task.Run(() =>
10534 string myPath = UriString;
10538 var configBrowserPath = SettingDialog.BrowserPath;
10539 if (!string.IsNullOrEmpty(configBrowserPath))
10541 if (configBrowserPath.StartsWith("\"") && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2) > -1)
10543 int sep = configBrowserPath.IndexOf("\"", 2);
10544 string browserPath = configBrowserPath.Substring(1, sep - 1);
10546 if (sep < configBrowserPath.Length - 1)
10548 arg = configBrowserPath.Substring(sep + 1);
10550 myPath = arg + " " + myPath;
10551 System.Diagnostics.Process.Start(browserPath, myPath);
10555 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10560 System.Diagnostics.Process.Start(myPath);
10565 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10570 private void ListTabSelect(TabPage _tab)
10574 this.PurgeListViewItemCache();
10577 _curList = (DetailsListView)_tab.Tag;
10578 if (_curList.SelectedIndices.Count > 0)
10580 _curItemIndex = _curList.SelectedIndices[0];
10581 _curPost = GetCurTabPost(_curItemIndex);
10585 _curItemIndex = -1;
10589 _anchorPost = null;
10590 _anchorFlag = false;
10594 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10598 for (int i = 0; i < _curList.Columns.Count; i++)
10600 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10605 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10607 ListTabSelect(e.TabPage);
10610 private void SelectListItem(DetailsListView LView, int Index)
10613 Rectangle bnd = new Rectangle();
10615 var item = LView.FocusedItem;
10624 LView.SelectedIndices.Clear();
10626 while (LView.SelectedIndices.Count > 0);
10627 item = LView.Items[Index];
10628 item.Selected = true;
10629 item.Focused = true;
10631 if (flg) LView.Invalidate(bnd);
10634 private void SelectListItem(DetailsListView LView , int[] Index, int[] FocusedIndex)
10637 Rectangle bnd = new Rectangle();
10639 var item = LView.FocusedItem;
10647 if (Index != null && !(Index.Length == 1 && Index[0] == -1))
10651 LView.SelectedIndices.Clear();
10653 while (LView.SelectedIndices.Count > 0);
10654 foreach (int idx in Index)
10656 if (idx > -1 && LView.VirtualListSize > idx)
10658 LView.SelectedIndices.Add(idx);
10659 if (fIdx == -1) fIdx = idx;
10663 if (FocusedIndex[1] > -1 && LView.VirtualListSize > FocusedIndex[1])
10665 LView.SelectionMark = FocusedIndex[1];
10667 if (FocusedIndex[0] > -1 && LView.VirtualListSize > FocusedIndex[0])
10669 LView.Items[FocusedIndex[0]].Focused = true;
10671 else if (fIdx > -1)
10673 LView.Items[fIdx].Focused = true;
10676 if (flg) LView.Invalidate(bnd);
10679 private void RunAsync(GetWorkerArg args)
10681 BackgroundWorker bw = null;
10682 if (args.type != MyCommon.WORKERTYPE.Follower)
10684 for (int i = 0; i < _bw.Length; i++)
10686 if (_bw[i] != null && !_bw[i].IsBusy)
10694 for (int i = 0; i < _bw.Length; i++)
10696 if (_bw[i] == null)
10698 _bw[i] = new BackgroundWorker();
10700 bw.WorkerReportsProgress = true;
10701 bw.WorkerSupportsCancellation = true;
10702 bw.DoWork += GetTimelineWorker_DoWork;
10703 bw.ProgressChanged += GetTimelineWorker_ProgressChanged;
10704 bw.RunWorkerCompleted += GetTimelineWorker_RunWorkerCompleted;
10712 if (_bwFollower == null)
10714 _bwFollower = new BackgroundWorker();
10716 bw.WorkerReportsProgress = true;
10717 bw.WorkerSupportsCancellation = true;
10718 bw.DoWork += GetTimelineWorker_DoWork;
10719 bw.ProgressChanged += GetTimelineWorker_ProgressChanged;
10720 bw.RunWorkerCompleted += GetTimelineWorker_RunWorkerCompleted;
10724 if (_bwFollower.IsBusy == false)
10728 if (bw == null) return;
10730 bw.RunWorkerAsync(args);
10733 private void StartUserStream()
10735 tw.NewPostFromStream += tw_NewPostFromStream;
10736 tw.UserStreamStarted += tw_UserStreamStarted;
10737 tw.UserStreamStopped += tw_UserStreamStopped;
10738 tw.PostDeleted += tw_PostDeleted;
10739 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
10741 MenuItemUserStream.Text = "&UserStream ■";
10742 MenuItemUserStream.Enabled = true;
10743 StopToolStripMenuItem.Text = "&Start";
10744 StopToolStripMenuItem.Enabled = true;
10745 if (SettingDialog.UserstreamStartup) tw.StartUserStream();
10748 private async void TweenMain_Shown(object sender, EventArgs e)
10752 PostBrowser.Url = new Uri("about:blank");
10753 PostBrowser.DocumentText = ""; //発言詳細部初期化
10759 NotifyIcon1.Visible = true;
10761 if (this.IsNetworkAvailable())
10763 GetTimeline(MyCommon.WORKERTYPE.BlockIds, 0, 0, "");
10764 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, 0, "");
10765 if (SettingDialog.StartupFollowers)
10767 GetTimeline(MyCommon.WORKERTYPE.Follower, 0, 0, "");
10769 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
10771 _waitTimeline = true;
10772 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 1, "");
10774 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 1, "");
10776 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 1, "");
10777 if (SettingDialog.GetFav)
10780 GetTimeline(MyCommon.WORKERTYPE.Favorites, 1, 1, "");
10782 _waitPubSearch = true;
10783 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, ""); //tabname="":全タブ
10784 _waitUserTimeline = true;
10785 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, ""); //tabname="":全タブ
10787 GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, ""); //tabname="":全タブ
10790 while (this.IsInitialRead())
10792 await Task.Delay(5000);
10795 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10797 if (MyCommon._endingFlag)
10801 if (MyCommon._endingFlag) return;
10803 if (ApplicationSettings.VersionInfoUrl != null)
10805 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10806 if (SettingDialog.StartupVersion)
10807 await this.CheckNewVersion(true);
10811 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10812 this.VerUpMenuItem.Enabled = false;
10813 this.VerUpMenuItem.Available = false;
10814 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10818 if (!tw.GetFollowersSuccess && SettingDialog.StartupFollowers)
10819 GetTimeline(MyCommon.WORKERTYPE.Follower, 0, 0, "");
10822 if (!tw.GetNoRetweetSuccess)
10823 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, 0, "");
10826 if (SettingDialog.TwitterConfiguration.PhotoSizeLimit == 0)
10827 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
10829 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10830 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10832 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10833 SettingStripMenuItem_Click(null, null);
10840 TimerTimeline.Enabled = true;
10843 private bool IsInitialRead()
10845 return _waitTimeline || _waitReply || _waitDm || _waitFav || _waitPubSearch || _waitUserTimeline || _waitLists;
10848 private void doGetFollowersMenu()
10850 GetTimeline(MyCommon.WORKERTYPE.Follower, 1, 0, "");
10851 DispSelectedPost(true);
10854 private void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10856 doGetFollowersMenu();
10859 private void doReTweetUnofficial()
10862 if (this.ExistCurrentPost)
10864 if (_curPost.IsDm ||
10865 !StatusText.Enabled) return;
10867 if (_curPost.IsProtect)
10869 MessageBox.Show("Protected.");
10872 string rtdata = _curPost.Text;
10873 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10875 this._reply_to_id = null;
10876 this._reply_to_name = null;
10878 StatusText.Text = "RT @" + _curPost.ScreenName + ": " + rtdata;
10880 StatusText.SelectionStart = 0;
10881 StatusText.Focus();
10885 private void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10887 doReTweetUnofficial();
10890 private void doReTweetOfficial(bool isConfirm)
10893 if (this.ExistCurrentPost)
10895 if (_curPost.IsProtect)
10897 MessageBox.Show("Protected.");
10898 _DoFavRetweetFlags = false;
10901 if (_curList.SelectedIndices.Count > 15)
10903 MessageBox.Show(Properties.Resources.RetweetLimitText);
10904 _DoFavRetweetFlags = false;
10907 else if (_curList.SelectedIndices.Count > 1)
10909 string QuestionText = Properties.Resources.RetweetQuestion2;
10910 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10911 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10913 case DialogResult.Cancel:
10914 case DialogResult.No:
10915 _DoFavRetweetFlags = false;
10921 if (_curPost.IsDm || _curPost.IsMe)
10923 _DoFavRetweetFlags = false;
10926 if (!SettingDialog.RetweetNoConfirm)
10928 string Questiontext = Properties.Resources.RetweetQuestion1;
10929 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10930 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10932 _DoFavRetweetFlags = false;
10937 GetWorkerArg args = new GetWorkerArg();
10938 args.ids = new List<long>();
10939 args.sIds = new List<long>();
10940 args.tName = _curTab.Text;
10941 args.type = MyCommon.WORKERTYPE.Retweet;
10942 foreach (int idx in _curList.SelectedIndices)
10944 PostClass post = GetCurTabPost(idx);
10945 if (!post.IsMe && !post.IsProtect && !post.IsDm) args.ids.Add(post.StatusId);
10951 private void ReTweetOriginalStripMenuItem_Click(object sender, EventArgs e)
10953 doReTweetOfficial(true);
10956 private void FavoritesRetweetOriginal()
10958 if (!this.ExistCurrentPost) return;
10959 _DoFavRetweetFlags = true;
10960 doReTweetOfficial(true);
10961 if (_DoFavRetweetFlags)
10963 _DoFavRetweetFlags = false;
10964 FavoriteChange(true, false);
10968 private void FavoritesRetweetUnofficial()
10970 if (this.ExistCurrentPost && !_curPost.IsDm)
10972 _DoFavRetweetFlags = true;
10973 FavoriteChange(true);
10974 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10976 _DoFavRetweetFlags = false;
10977 doReTweetUnofficial();
10983 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10985 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10986 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10987 /// <returns>復元されたツイート本文</returns>
10988 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10990 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10993 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10995 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10997 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11001 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11003 statusHtml = statusHtml.Replace("<br>", " ");
11005 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11006 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
11007 statusHtml = statusHtml.Replace(" ", " ");
11009 return WebUtility.HtmlDecode(statusHtml);
11012 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11014 if (_curPost != null)
11015 DispSelectedPost(true);
11018 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11020 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11021 DebugModeToolStripMenuItem.Visible = true;
11023 DebugModeToolStripMenuItem.Visible = false;
11026 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11028 SettingDialog.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11031 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11033 ToolStripMenuItemUrlAutoShorten.Checked = SettingDialog.UrlConvertAuto;
11036 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11038 if (TraceOutToolStripMenuItem.Checked)
11039 MyCommon.TraceFlag = true;
11041 MyCommon.TraceFlag = false;
11044 private void TweenMain_Deactivate(object sender, EventArgs e)
11046 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11047 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11050 private void TabRenameMenuItem_Click(object sender, EventArgs e)
11052 if (string.IsNullOrEmpty(_rclickTabName)) return;
11053 TabRename(ref _rclickTabName);
11056 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11058 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11061 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11063 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11067 private void GetApiInfo_Dowork(object sender, DoWorkEventArgs e)
11069 e.Result = tw.GetInfoApi();
11072 private void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11074 StringBuilder tmp = new StringBuilder();
11076 using (FormInfo dlg = new FormInfo(this, Properties.Resources.ApiInfo6, GetApiInfo_Dowork))
11080 var result = (TwitterApiStatus)dlg.Result;
11082 if (result == null)
11084 var accessLevel = result.AccessLevel;
11085 var timelineLimit = result.AccessLimit["/statuses/home_timeline"];
11086 var mediaLimit = result.MediaUploadLimit;
11088 tmp.AppendLine(Properties.Resources.ApiInfo1 + timelineLimit.AccessLimitCount);
11089 tmp.AppendLine(Properties.Resources.ApiInfo2 + timelineLimit.AccessLimitRemain);
11090 tmp.AppendLine(Properties.Resources.ApiInfo3 + timelineLimit.AccessLimitResetDate);
11091 tmp.AppendLine(Properties.Resources.ApiInfo7 + (tw.UserStreamEnabled ? Properties.Resources.Enable : Properties.Resources.Disable));
11094 tmp.AppendLine(Properties.Resources.ApiInfo8 + accessLevel);
11095 SetStatusLabelUrl();
11098 tmp.AppendLine(Properties.Resources.ApiInfo9 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitCount.ToString()));
11099 tmp.AppendLine(Properties.Resources.ApiInfo10 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitRemain.ToString()));
11100 tmp.AppendLine(Properties.Resources.ApiInfo11 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitResetDate.ToString()));
11104 tmp.Append(Properties.Resources.ApiInfo5);
11108 MessageBox.Show(tmp.ToString(), Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11111 private void FollowCommandMenuItem_Click(object sender, EventArgs e)
11114 if (_curPost != null) id = _curPost.ScreenName;
11118 private void FollowCommand_DoWork(object sender, DoWorkEventArgs e)
11120 FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11121 e.Result = arg.tw.PostFollowCommand(arg.id);
11124 private void FollowCommand(string id)
11126 using (InputTabName inputName = new InputTabName())
11128 inputName.FormTitle = "Follow";
11129 inputName.FormDescription = Properties.Resources.FRMessage1;
11130 inputName.TabName = id;
11131 if (inputName.ShowDialog() == DialogResult.OK &&
11132 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11134 FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11136 arg.id = inputName.TabName.Trim();
11137 using (FormInfo _info = new FormInfo(this, Properties.Resources.FollowCommandText1,
11138 FollowCommand_DoWork,
11142 _info.ShowDialog();
11143 string ret = (string)_info.Result;
11144 if (!string.IsNullOrEmpty(ret))
11145 MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11147 MessageBox.Show(Properties.Resources.FRMessage3);
11153 private void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11156 if (_curPost != null) id = _curPost.ScreenName;
11157 RemoveCommand(id, false);
11160 private class FollowRemoveCommandArgs
11166 private void RemoveCommand_DoWork(object sender , DoWorkEventArgs e)
11168 FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11169 e.Result = arg.tw.PostRemoveCommand(arg.id);
11172 private void RemoveCommand(string id, bool skipInput)
11174 FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11179 using (InputTabName inputName = new InputTabName())
11181 inputName.FormTitle = "Unfollow";
11182 inputName.FormDescription = Properties.Resources.FRMessage1;
11183 inputName.TabName = id;
11184 if (inputName.ShowDialog() == DialogResult.OK &&
11185 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11188 arg.id = inputName.TabName.Trim();
11197 using (FormInfo _info = new FormInfo(this, Properties.Resources.RemoveCommandText1,
11198 RemoveCommand_DoWork,
11202 _info.ShowDialog();
11203 string ret = (string)_info.Result;
11204 if (!string.IsNullOrEmpty(ret))
11205 MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11207 MessageBox.Show(Properties.Resources.FRMessage3);
11211 private void FriendshipMenuItem_Click(object sender, EventArgs e)
11214 if (_curPost != null)
11215 id = _curPost.ScreenName;
11217 ShowFriendship(id);
11220 private class ShowFriendshipArgs
11223 public class FriendshipInfo
11225 public string id = "";
11226 public bool isFollowing = false;
11227 public bool isFollowed = false;
11228 public bool isError = false;
11229 public FriendshipInfo(string id)
11234 public List<FriendshipInfo> ids = new List<FriendshipInfo>();
11237 private void ShowFriendship_DoWork(object sender, DoWorkEventArgs e)
11239 ShowFriendshipArgs arg = (ShowFriendshipArgs)e.Argument;
11240 string result = "";
11241 foreach (ShowFriendshipArgs.FriendshipInfo fInfo in arg.ids)
11243 string rt = arg.tw.GetFriendshipInfo(fInfo.id, ref fInfo.isFollowing, ref fInfo.isFollowed);
11244 if (!string.IsNullOrEmpty(rt))
11246 if (string.IsNullOrEmpty(result)) result = rt;
11247 fInfo.isError = true;
11253 private void ShowFriendship(string id)
11255 ShowFriendshipArgs args = new ShowFriendshipArgs();
11257 using (InputTabName inputName = new InputTabName())
11259 inputName.FormTitle = "Show Friendships";
11260 inputName.FormDescription = Properties.Resources.FRMessage1;
11261 inputName.TabName = id;
11262 if (inputName.ShowDialog() == DialogResult.OK &&
11263 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11266 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(inputName.TabName.Trim()));
11267 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11268 ShowFriendship_DoWork,
11272 _info.ShowDialog();
11273 ret = (string)_info.Result;
11275 string result = "";
11276 if (string.IsNullOrEmpty(ret))
11278 if (args.ids[0].isFollowing)
11280 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11284 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11286 if (args.ids[0].isFollowed)
11288 result += Properties.Resources.GetFriendshipInfo3;
11292 result += Properties.Resources.GetFriendshipInfo4;
11294 result = args.ids[0].id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11300 MessageBox.Show(result);
11305 private void ShowFriendship(string[] ids)
11307 foreach (string id in ids)
11310 ShowFriendshipArgs args = new ShowFriendshipArgs();
11312 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(id.Trim()));
11313 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11314 ShowFriendship_DoWork,
11318 _info.ShowDialog();
11319 ret = (string)_info.Result;
11321 string result = "";
11322 ShowFriendshipArgs.FriendshipInfo fInfo = args.ids[0];
11324 if (string.IsNullOrEmpty(ret))
11327 if (fInfo.isFollowing)
11329 ff += Properties.Resources.GetFriendshipInfo1;
11333 ff += Properties.Resources.GetFriendshipInfo2;
11336 ff += System.Environment.NewLine + " ";
11337 if (fInfo.isFollowed)
11339 ff += Properties.Resources.GetFriendshipInfo3;
11343 ff += Properties.Resources.GetFriendshipInfo4;
11345 result += fInfo.id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11346 if (fInfo.isFollowing)
11348 if (MessageBox.Show(
11349 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11350 MessageBoxButtons.YesNo,
11351 MessageBoxIcon.Question,
11352 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11354 RemoveCommand(fInfo.id, true);
11359 MessageBox.Show(result);
11364 MessageBox.Show(ret);
11369 private void OwnStatusMenuItem_Click(object sender, EventArgs e)
11371 doShowUserStatus(tw.Username, false);
11372 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11374 // doShowUserStatus(tw.Username, false);
11378 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11383 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11384 // URLから切り出した文字列を渡す
11386 public bool IsTwitterId(string name)
11388 if (SettingDialog.TwitterConfiguration.NonUsernamePaths == null || SettingDialog.TwitterConfiguration.NonUsernamePaths.Length == 0)
11389 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11391 return !SettingDialog.TwitterConfiguration.NonUsernamePaths.Contains(name.ToLower());
11394 private string GetUserId()
11396 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11397 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11398 return m.Result("${ScreenName}");
11403 private void FollowContextMenuItem_Click(object sender, EventArgs e)
11405 string name = GetUserId();
11406 if (name != null) FollowCommand(name);
11409 private void RemoveContextMenuItem_Click(object sender, EventArgs e)
11411 string name = GetUserId();
11412 if (name != null) RemoveCommand(name, false);
11415 private void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11417 string name = GetUserId();
11418 if (name != null) ShowFriendship(name);
11421 private void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11423 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11424 List<string> ids = new List<string>();
11425 foreach (Match mu in ma)
11427 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11429 ids.Add(mu.Result("${ScreenName}"));
11432 ShowFriendship(ids.ToArray());
11435 private void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11437 string name = GetUserId();
11438 if (name != null) ShowUserStatus(name);
11441 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11443 string name = GetUserId();
11444 if (name != null) AddNewTabForUserTimeline(name);
11447 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11449 string name = GetUserId();
11450 if (name != null) AddNewTabForSearch("@" + name);
11453 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11455 _modifySettingCommon = true;
11458 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11460 _modifySettingCommon = true;
11463 private void doQuote()
11467 if (this.ExistCurrentPost)
11469 if (_curPost.IsDm ||
11470 !StatusText.Enabled) return;
11472 if (_curPost.IsProtect)
11474 MessageBox.Show("Protected.");
11477 string rtdata = _curPost.Text;
11478 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11480 StatusText.Text = " QT @" + _curPost.ScreenName + ": " + rtdata;
11481 if (_curPost.RetweetedId == null)
11483 _reply_to_id = _curPost.StatusId;
11487 _reply_to_id = _curPost.RetweetedId.Value;
11489 _reply_to_name = _curPost.ScreenName;
11491 StatusText.SelectionStart = 0;
11492 StatusText.Focus();
11496 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11501 private void SearchButton_Click(object sender, EventArgs e)
11504 Control pnl = ((Control)sender).Parent;
11505 if (pnl == null) return;
11506 string tbName = pnl.Parent.Text;
11507 TabClass tb = _statuses.Tabs[tbName];
11508 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11509 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11510 ComboBox cmbusline = (ComboBox)pnl.Controls["comboUserline"];
11511 cmb.Text = cmb.Text.Trim();
11512 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11513 bool Quote = false;
11514 StringBuilder buf = new StringBuilder();
11515 char[] c = cmb.Text.ToCharArray();
11516 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11518 if (cnt > cmb.Text.Length - 4)
11520 buf.Append(cmb.Text.Substring(cnt));
11529 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11531 buf.Append(" OR ");
11536 buf.Append(c[cnt]);
11538 cmb.Text = buf.ToString();
11540 tb.SearchWords = cmb.Text;
11541 tb.SearchLang = cmbLang.Text;
11542 if (string.IsNullOrEmpty(cmb.Text))
11544 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11548 if (tb.IsQueryChanged())
11550 int idx = ((ComboBox)pnl.Controls["comboSearch"]).Items.IndexOf(tb.SearchWords);
11551 if (idx > -1) ((ComboBox)pnl.Controls["comboSearch"]).Items.RemoveAt(idx);
11552 ((ComboBox)pnl.Controls["comboSearch"]).Items.Insert(0, tb.SearchWords);
11553 cmb.Text = tb.SearchWords;
11555 DetailsListView lst = (DetailsListView)pnl.Parent.Tag;
11556 this.PurgeListViewItemCache();
11557 lst.VirtualListSize = 0;
11558 _statuses.ClearTabIds(tbName);
11559 SaveConfigsTabs(); //検索条件の保存
11562 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, tbName);
11563 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11566 private void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11572 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11574 if (_statuses.RemovedTab.Count == 0)
11576 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11581 TabClass tb = _statuses.RemovedTab.Pop();
11582 if (tb.TabType == MyCommon.TabUsageType.Related)
11584 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11585 if (relatedTab != null)
11587 // 関連発言なら既存のタブを置き換える
11588 tb.TabName = relatedTab.TabName;
11589 this.ClearTab(tb.TabName, false);
11590 _statuses.Tabs[tb.TabName] = tb;
11591 for (int i = 0; i < ListTab.TabPages.Count; i++)
11593 if (tb.TabName == ListTab.TabPages[i].Text)
11595 ListTab.SelectedIndex = i;
11596 ListTabSelect(ListTab.TabPages[i]);
11603 const string TabName = "Related Tweets";
11604 string renamed = TabName;
11605 for (int i = 2; i <= 100; i++)
11607 if (!_statuses.ContainsTab(renamed)) break;
11608 renamed = TabName + i.ToString();
11610 tb.TabName = renamed;
11611 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11612 _statuses.Tabs.Add(renamed, tb); // 後に
11613 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11614 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
11619 string renamed = tb.TabName;
11620 for (int i = 1; i < int.MaxValue; i++)
11622 if (!_statuses.ContainsTab(renamed)) break;
11623 renamed = tb.TabName + "(" + i.ToString() + ")";
11625 tb.TabName = renamed;
11626 _statuses.Tabs.Add(renamed, tb); // 先に
11627 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11628 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11629 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
11635 private void doMoveToRTHome()
11637 if (_curList.SelectedIndices.Count > 0)
11639 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11640 if (post.RetweetedId != null)
11642 OpenUriAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11647 private void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11652 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11654 string name = GetUserId();
11660 if (_curList.SelectedIndices.Count == 0) return;
11663 if (!SelectTab(out tabName)) return;
11667 MoveOrCopy(ref mv, ref mk);
11669 PostFilterRule fc = new PostFilterRule();
11670 fc.FilterName = name;
11671 fc.UseNameField = true;
11672 fc.MoveMatches = mv;
11673 fc.MarkMatches = mk;
11674 fc.UseRegex = false;
11675 fc.FilterByUrl = false;
11676 _statuses.Tabs[tabName].AddFilter(fc);
11678 this.ApplyPostFilters();
11683 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11687 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11689 if (menuItem.Owner == this.ContextMenuPostBrowser)
11691 user = GetUserId();
11692 if (user == null) return;
11694 else if (this._curPost != null)
11696 user = this._curPost.ScreenName;
11703 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11705 string res = this.tw.GetListsApi();
11707 if (!string.IsNullOrEmpty(res))
11709 MessageBox.Show("Failed to get lists. (" + res + ")");
11714 using (MyLists listSelectForm = new MyLists(user, this.tw))
11716 listSelectForm.ShowDialog(this);
11720 private void SearchControls_Enter(object sender, EventArgs e)
11722 Control pnl = (Control)sender;
11723 foreach (Control ctl in pnl.Controls)
11725 ctl.TabStop = true;
11729 private void SearchControls_Leave(object sender, EventArgs e)
11731 Control pnl = (Control)sender;
11732 foreach (Control ctl in pnl.Controls)
11734 ctl.TabStop = false;
11738 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
11740 if (ListTab.SelectedTab != null)
11742 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
11743 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
11747 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
11749 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
11752 HashMgr.SetPermanentHash("#" + m.Result("${hash}"));
11753 HashStripSplitButton.Text = HashMgr.UseHash;
11754 HashToggleMenuItem.Checked = true;
11755 HashToggleToolStripMenuItem.Checked = true;
11757 _modifySettingCommon = true;
11761 private void StatusLabel_DoubleClick(object sender, EventArgs e)
11763 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
11766 private void HashManageMenuItem_Click(object sender, EventArgs e)
11768 DialogResult rslt = DialogResult.Cancel;
11771 rslt = HashMgr.ShowDialog();
11777 this.TopMost = SettingDialog.AlwaysTop;
11778 if (rslt == DialogResult.Cancel) return;
11779 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11781 HashStripSplitButton.Text = HashMgr.UseHash;
11782 HashToggleMenuItem.Checked = true;
11783 HashToggleToolStripMenuItem.Checked = true;
11787 HashStripSplitButton.Text = "#[-]";
11788 HashToggleMenuItem.Checked = false;
11789 HashToggleToolStripMenuItem.Checked = false;
11791 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
11793 // int sidx = StatusText.SelectionStart;
11794 // string hash = HashMgr.UseHash + " ";
11797 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
11798 // hash = " " + hash;
11800 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
11801 // sidx += hash.Length;
11802 // StatusText.SelectionStart = sidx;
11803 // StatusText.Focus();
11805 _modifySettingCommon = true;
11806 this.StatusText_TextChanged(null, null);
11809 private void HashToggleMenuItem_Click(object sender, EventArgs e)
11811 HashMgr.ToggleHash();
11812 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11814 HashStripSplitButton.Text = HashMgr.UseHash;
11815 HashToggleMenuItem.Checked = true;
11816 HashToggleToolStripMenuItem.Checked = true;
11820 HashStripSplitButton.Text = "#[-]";
11821 HashToggleMenuItem.Checked = false;
11822 HashToggleToolStripMenuItem.Checked = false;
11824 _modifySettingCommon = true;
11825 this.StatusText_TextChanged(null, null);
11828 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
11830 HashToggleMenuItem_Click(null, null);
11833 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
11835 if (ListTab.SelectedTab == null) return;
11836 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
11837 if (!this.ExistCurrentPost)
11839 this.ReplyOpMenuItem.Enabled = false;
11840 this.ReplyAllOpMenuItem.Enabled = false;
11841 this.DmOpMenuItem.Enabled = false;
11842 this.ShowProfMenuItem.Enabled = false;
11843 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
11844 this.ListManageMenuItem.Enabled = false;
11845 this.OpenFavOpMenuItem.Enabled = false;
11846 this.CreateTabRuleOpMenuItem.Enabled = false;
11847 this.CreateIdRuleOpMenuItem.Enabled = false;
11848 this.ReadOpMenuItem.Enabled = false;
11849 this.UnreadOpMenuItem.Enabled = false;
11853 this.ReplyOpMenuItem.Enabled = true;
11854 this.ReplyAllOpMenuItem.Enabled = true;
11855 this.DmOpMenuItem.Enabled = true;
11856 this.ShowProfMenuItem.Enabled = true;
11857 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
11858 this.ListManageMenuItem.Enabled = true;
11859 this.OpenFavOpMenuItem.Enabled = true;
11860 this.CreateTabRuleOpMenuItem.Enabled = true;
11861 this.CreateIdRuleOpMenuItem.Enabled = true;
11862 this.ReadOpMenuItem.Enabled = true;
11863 this.UnreadOpMenuItem.Enabled = true;
11866 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
11868 this.FavOpMenuItem.Enabled = false;
11869 this.UnFavOpMenuItem.Enabled = false;
11870 this.OpenStatusOpMenuItem.Enabled = false;
11871 this.OpenFavotterOpMenuItem.Enabled = false;
11872 this.ShowRelatedStatusesMenuItem2.Enabled = false;
11873 this.RtOpMenuItem.Enabled = false;
11874 this.RtUnOpMenuItem.Enabled = false;
11875 this.QtOpMenuItem.Enabled = false;
11876 this.FavoriteRetweetMenuItem.Enabled = false;
11877 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11878 if (this.ExistCurrentPost && _curPost.IsDm) this.DelOpMenuItem.Enabled = true;
11882 this.FavOpMenuItem.Enabled = true;
11883 this.UnFavOpMenuItem.Enabled = true;
11884 this.OpenStatusOpMenuItem.Enabled = true;
11885 this.OpenFavotterOpMenuItem.Enabled = true;
11886 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
11890 this.RtOpMenuItem.Enabled = false;
11891 this.FavoriteRetweetMenuItem.Enabled = false;
11892 this.DelOpMenuItem.Enabled = true;
11896 this.DelOpMenuItem.Enabled = false;
11897 if (_curPost.IsProtect)
11899 this.RtOpMenuItem.Enabled = false;
11900 this.RtUnOpMenuItem.Enabled = false;
11901 this.QtOpMenuItem.Enabled = false;
11902 this.FavoriteRetweetMenuItem.Enabled = false;
11903 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11907 this.RtOpMenuItem.Enabled = true;
11908 this.RtUnOpMenuItem.Enabled = true;
11909 this.QtOpMenuItem.Enabled = true;
11910 this.FavoriteRetweetMenuItem.Enabled = true;
11911 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11916 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11918 this.RefreshPrevOpMenuItem.Enabled = true;
11922 this.RefreshPrevOpMenuItem.Enabled = false;
11924 if (!this.ExistCurrentPost
11925 || _curPost.InReplyToStatusId == null)
11927 OpenRepSourceOpMenuItem.Enabled = false;
11931 OpenRepSourceOpMenuItem.Enabled = true;
11933 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11935 OpenRterHomeMenuItem.Enabled = false;
11939 OpenRterHomeMenuItem.Enabled = true;
11943 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11945 ContextMenuTabProperty_Opening(sender, null);
11948 public Twitter TwitterInstance
11953 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11955 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
11957 _mySpDis3 = SplitContainer3.SplitterDistance;
11958 _modifySettingLocal = true;
11962 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11964 if (_statuses.RemovedTab.Count == 0)
11966 UndoRemoveTabMenuItem.Enabled = false;
11970 UndoRemoveTabMenuItem.Enabled = true;
11972 if (ListTab.SelectedTab != null)
11974 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11975 PublicSearchQueryMenuItem.Enabled = true;
11977 PublicSearchQueryMenuItem.Enabled = false;
11981 PublicSearchQueryMenuItem.Enabled = false;
11983 if (!this.ExistCurrentPost)
11985 this.CopySTOTMenuItem.Enabled = false;
11986 this.CopyURLMenuItem.Enabled = false;
11987 this.CopyUserIdStripMenuItem.Enabled = false;
11991 this.CopySTOTMenuItem.Enabled = true;
11992 this.CopyURLMenuItem.Enabled = true;
11993 this.CopyUserIdStripMenuItem.Enabled = true;
11994 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11995 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11999 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12001 SetNotifyIconText();
12004 private void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12007 if (_curPost != null)
12009 id = _curPost.ScreenName;
12011 ShowUserStatus(id);
12014 private class GetUserInfoArgs
12018 public TwitterDataModel.User user;
12021 private void GetUserInfo_DoWork(object sender, DoWorkEventArgs e)
12023 GetUserInfoArgs args = (GetUserInfoArgs)e.Argument;
12024 e.Result = args.tw.GetUserInfo(args.id, ref args.user);
12027 private void doShowUserStatus(string id, bool ShowInputDialog)
12029 TwitterDataModel.User user = null;
12030 GetUserInfoArgs args = new GetUserInfoArgs();
12031 if (ShowInputDialog)
12033 using (InputTabName inputName = new InputTabName())
12035 inputName.FormTitle = "Show UserStatus";
12036 inputName.FormDescription = Properties.Resources.FRMessage1;
12037 inputName.TabName = id;
12038 if (inputName.ShowDialog() == DialogResult.OK &&
12039 !string.IsNullOrEmpty(inputName.TabName.Trim()))
12041 id = inputName.TabName.Trim();
12045 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
12046 GetUserInfo_DoWork,
12050 _info.ShowDialog();
12051 string ret = (string)_info.Result;
12052 if (string.IsNullOrEmpty(ret))
12053 doShowUserStatus(args.user);
12055 MessageBox.Show(ret);
12065 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
12066 GetUserInfo_DoWork,
12070 _info.ShowDialog();
12071 string ret = (string)_info.Result;
12072 if (string.IsNullOrEmpty(ret))
12074 doShowUserStatus(args.user);
12078 MessageBox.Show(ret);
12084 private void doShowUserStatus(TwitterDataModel.User user)
12086 using (ShowUserInfo userinfo = new ShowUserInfo())
12088 userinfo.Owner = this;
12089 userinfo.User = user;
12090 userinfo.ShowDialog(this);
12092 this.BringToFront();
12096 private void ShowUserStatus(string id, bool ShowInputDialog)
12098 doShowUserStatus(id, ShowInputDialog);
12101 private void ShowUserStatus(string id)
12103 doShowUserStatus(id, true);
12106 private void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12108 if (NameLabel.Tag != null)
12110 string id = (string)NameLabel.Tag;
12111 if (id != tw.Username)
12118 private void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12120 if (NameLabel.Tag != null)
12122 string id = (string)NameLabel.Tag;
12123 if (id != tw.Username)
12125 RemoveCommand(id, false);
12130 private void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12132 if (NameLabel.Tag != null)
12134 string id = (string)NameLabel.Tag;
12135 if (id != tw.Username)
12137 ShowFriendship(id);
12142 private void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12144 if (NameLabel.Tag != null)
12146 string id = (string)NameLabel.Tag;
12147 ShowUserStatus(id, false);
12151 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12153 if (NameLabel.Tag != null)
12155 string id = (string)NameLabel.Tag;
12156 AddNewTabForUserTimeline(id);
12160 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12162 if (NameLabel.Tag != null)
12164 string id = (string)NameLabel.Tag;
12165 AddNewTabForSearch("@" + id);
12169 private void ShowProfileMenuItem_Click(object sender, EventArgs e)
12171 if (_curPost != null)
12173 ShowUserStatus(_curPost.ScreenName, false);
12177 private void GetRetweet_DoWork(object sender, DoWorkEventArgs e)
12182 if (_curPost.RetweetedId != null)
12184 statusid = _curPost.RetweetedId.Value;
12188 statusid = _curPost.StatusId;
12190 tw.GetStatus_Retweeted_Count(statusid, ref counter);
12192 e.Result = counter;
12195 private void RtCountMenuItem_Click(object sender, EventArgs e)
12197 if (this.ExistCurrentPost)
12199 using (FormInfo _info = new FormInfo(this, Properties.Resources.RtCountMenuItem_ClickText1,
12200 GetRetweet_DoWork))
12202 int retweet_count = 0;
12205 _info.ShowDialog();
12206 retweet_count = (int)_info.Result;
12207 if (retweet_count < 0)
12209 MessageBox.Show(Properties.Resources.RtCountText2);
12213 MessageBox.Show(retweet_count.ToString() + Properties.Resources.RtCountText1);
12219 private HookGlobalHotkey _hookGlobalHotkey;
12222 this.http = MyCommon.CreateHttpClient();
12223 _hookGlobalHotkey = new HookGlobalHotkey(this);
12225 // この呼び出しは、Windows フォーム デザイナで必要です。
12226 InitializeComponent();
12228 // InitializeComponent() 呼び出しの後で初期化を追加します。
12230 this.SettingDialog.IntervalChanged += this.TimerInterval_Changed;
12231 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12232 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12233 this.gh.NotifyClicked += GrowlHelper_Callback;
12235 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12236 this.ListTab.HandleCreated += (s, e) => Win32Api.SetMinTabWidth((TabControl)s, 40);
12238 this._apiGauge = new ToolStripAPIGauge();
12239 this._apiGauge.BorderSides = ToolStripStatusLabelBorderSides.Right;
12240 this.StatusStrip1.Items.Insert(2, this._apiGauge);
12242 this.ReplaceAppName();
12245 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12247 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12250 this.Visible = false;
12252 else if (Form.ActiveForm == null)
12254 this.Visible = true;
12255 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12257 this.BringToFront();
12258 this.StatusText.Focus();
12262 private void UserPicture_MouseEnter(object sender, EventArgs e)
12264 this.UserPicture.Cursor = Cursors.Hand;
12267 private void UserPicture_MouseLeave(object sender, EventArgs e)
12269 this.UserPicture.Cursor = Cursors.Default;
12272 private void UserPicture_DoubleClick(object sender, EventArgs e)
12274 if (NameLabel.Tag != null)
12276 OpenUriAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12280 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12282 this.MultiLineMenuItem.PerformClick();
12285 public PostClass CurPost
12287 get { return _curPost; }
12290 public bool IsPreviewEnable
12292 get { return SettingDialog.PreviewEnable; }
12296 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12298 if (ImageSelectionPanel.Visible)
12300 CloseImageSelectionPanel();
12304 OpenImageSelectionPanel();
12305 ImageFromSelectedFile(true);
12306 ImagefilePathText.Focus();
12310 private void OpenImageSelectionPanel()
12312 ImageSelectionPanel.Visible = true;
12313 ImageSelectionPanel.Enabled = true;
12314 TimelinePanel.Visible = false;
12315 TimelinePanel.Enabled = false;
12318 private void CloseImageSelectionPanel()
12320 ImagefilePathText.CausesValidation = false;
12321 TimelinePanel.Visible = true;
12322 TimelinePanel.Enabled = true;
12323 ImageSelectionPanel.Visible = false;
12324 ImageSelectionPanel.Enabled = false;
12325 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12326 ClearImageSelectedPicture(false);
12327 ImagefilePathText.CausesValidation = true;
12330 private void SelectMedia_DragEnter(DragEventArgs e)
12332 string filename = ((string[])e.Data.GetData(DataFormats.FileDrop, false))[0];
12333 FileInfo fl = new FileInfo(filename);
12334 string ext = fl.Extension;
12336 if (!string.IsNullOrEmpty(this.ImageService) &&
12337 this.pictureService[this.ImageService].CheckValidFilesize(ext, fl.Length))
12339 e.Effect = DragDropEffects.Copy;
12342 foreach (string svc in ImageServiceCombo.Items)
12344 if (!string.IsNullOrEmpty(svc) &&
12345 this.pictureService[svc].CheckValidFilesize(ext, fl.Length))
12347 //ImageServiceCombo.SelectedItem = svc;
12348 e.Effect = DragDropEffects.Copy;
12352 e.Effect = DragDropEffects.None;
12355 private void SelectMedia_DragOver(DragEventArgs e)
12360 private void SelectMedia_DragDrop(DragEventArgs e)
12363 this.BringToFront();
12364 OpenImageSelectionPanel();
12365 ImagefilePathText.Text = ((string[])e.Data.GetData(DataFormats.FileDrop, false))[0];
12366 ImageFromSelectedFile(false);
12367 StatusText.Focus();
12370 private void FilePickButton_Click(object sender, EventArgs e)
12372 if (string.IsNullOrEmpty(this.ImageService)) return;
12373 OpenFileDialog1.Filter = this.pictureService[this.ImageService].GetFileOpenDialogFilter();
12374 OpenFileDialog1.Title = Properties.Resources.PickPictureDialog1;
12375 OpenFileDialog1.FileName = "";
12379 this.AllowDrop = false;
12380 if (OpenFileDialog1.ShowDialog() == DialogResult.Cancel) return;
12384 this.AllowDrop = true;
12387 ImagefilePathText.Text = OpenFileDialog1.FileName;
12388 ImageFromSelectedFile(false);
12391 private void ImagefilePathText_Validating(object sender, CancelEventArgs e)
12393 if (ImageCancelButton.Focused)
12395 ImagefilePathText.CausesValidation = false;
12399 ImageFromSelectedFile(false);
12402 private void ImageFromSelectedFile(bool suppressMsgBox)
12406 ClearImageSelectedPicture(true);
12408 ImagefilePathText.Text = ImagefilePathText.Text.Trim();
12409 if (string.IsNullOrEmpty(ImagefilePathText.Text) || string.IsNullOrEmpty(this.ImageService))
12411 ImagefilePathText.Text = "";
12415 FileInfo fl = new FileInfo(ImagefilePathText.Text);
12416 string ext = fl.Extension;
12417 var imageService = this.pictureService[this.ImageService];
12419 if (!imageService.CheckValidExtension(ext))
12422 ImagefilePathText.Text = "";
12423 if (!suppressMsgBox)
12426 string.Format(Properties.Resources.PostPictureWarn3, this.ImageService, MakeAvailableServiceText(ext, fl.Length), ext),
12427 Properties.Resources.PostPictureWarn4,
12428 MessageBoxButtons.OK,
12429 MessageBoxIcon.Warning);
12434 if (!imageService.CheckValidFilesize(ext, fl.Length))
12437 ImagefilePathText.Text = "";
12438 if (!suppressMsgBox)
12441 string.Format(Properties.Resources.PostPictureWarn5, this.ImageService, MakeAvailableServiceText(ext, fl.Length)),
12442 Properties.Resources.PostPictureWarn4,
12443 MessageBoxButtons.OK,
12444 MessageBoxIcon.Warning);
12449 switch (imageService.GetFileType(ext))
12451 case MyCommon.UploadFileType.Invalid:
12452 ImagefilePathText.Text = "";
12454 case MyCommon.UploadFileType.Picture:
12456 using (FileStream fs = new FileStream(ImagefilePathText.Text, FileMode.Open, FileAccess.Read))
12458 img = Image.FromStream(fs);
12460 ImageSelectedPicture.Image = (new HttpVarious()).CheckValidImage(
12464 ImageSelectedPicture.Tag = MyCommon.UploadFileType.Picture;
12466 case MyCommon.UploadFileType.MultiMedia:
12467 ImageSelectedPicture.Image = Properties.Resources.MultiMediaImage;
12468 ImageSelectedPicture.Tag = MyCommon.UploadFileType.MultiMedia;
12471 ImagefilePathText.Text = "";
12475 catch (FileNotFoundException)
12477 ClearImageSelectedPicture(true);
12478 ImagefilePathText.Text = "";
12479 if (!suppressMsgBox) MessageBox.Show("File not found.");
12483 ClearImageSelectedPicture(true);
12484 ImagefilePathText.Text = "";
12485 if (!suppressMsgBox) MessageBox.Show("The type of this file is not image.");
12489 private string MakeAvailableServiceText(string ext, long fileSize)
12491 StringBuilder sb = new StringBuilder();
12493 foreach (string svc in ImageServiceCombo.Items)
12495 if (!string.IsNullOrEmpty(svc) &&
12496 this.pictureService[svc].CheckValidFilesize(ext, fileSize))
12498 if (sb.Length > 0) sb.Append(", ");
12502 if (sb.Length == 0)
12503 return Properties.Resources.PostPictureWarn6;
12505 return sb.ToString();
12508 private void ClearImageSelectedPicture(bool invalidate)
12510 Image oldImage = null;
12511 if (this.ImageSelectedPicture.Image != null)
12513 if (this.ImageSelectedPicture.Image != ImageSelectedPicture.InitialImage &&
12514 this.ImageSelectedPicture.Image != Properties.Resources.MultiMediaImage)
12516 oldImage = this.ImageSelectedPicture.Image;
12521 this.ImageSelectedPicture.Image = ImageSelectedPicture.InitialImage;
12522 this.ImageSelectedPicture.Tag = MyCommon.UploadFileType.Invalid;
12526 this.ImageSelectedPicture.Image = null;
12527 this.ImageSelectedPicture.Tag = null;
12529 if (oldImage != null) oldImage.Dispose();
12532 private void ImageCancelButton_Click(object sender, EventArgs e)
12534 CloseImageSelectionPanel();
12537 private void ImageSelection_KeyDown(object sender, KeyEventArgs e)
12539 if (e.KeyCode == Keys.Escape)
12541 CloseImageSelectionPanel();
12545 private void ImageSelection_KeyPress(object sender, KeyPressEventArgs e)
12547 if (Convert.ToInt32(e.KeyChar) == 0x1B)
12549 ImagefilePathText.CausesValidation = false;
12554 private void ImageSelection_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
12556 if (e.KeyCode == Keys.Escape)
12558 ImagefilePathText.CausesValidation = false;
12562 private bool TryGetSelectedMedia(out string imageService, out string imagePath)
12564 if (ImageSelectedPicture.Image != ImageSelectedPicture.InitialImage &&
12565 ImageServiceCombo.SelectedIndex > -1 &&
12566 !string.IsNullOrEmpty(ImagefilePathText.Text))
12568 if (MessageBox.Show(string.Format(Properties.Resources.PostPictureConfirm1, this.ImageService),
12569 Properties.Resources.PostPictureConfirm2,
12570 MessageBoxButtons.OKCancel,
12571 MessageBoxIcon.Question,
12572 MessageBoxDefaultButton.Button1)
12573 == DialogResult.OK)
12575 imageService = ImageServiceCombo.Text;
12576 imagePath = ImagefilePathText.Text;
12577 CloseImageSelectionPanel();
12578 ImagefilePathText.Text = "";
12584 MessageBox.Show(Properties.Resources.PostPictureWarn1, Properties.Resources.PostPictureWarn2);
12587 CloseImageSelectionPanel();
12588 imageService = null;
12593 private void SetImageServiceCombo()
12596 if (ImageServiceCombo.SelectedIndex > -1) svc = ImageServiceCombo.SelectedItem.ToString();
12597 ImageServiceCombo.Items.Clear();
12599 // Add service names to combobox
12600 foreach (var key in pictureService.Keys)
12602 ImageServiceCombo.Items.Add(key);
12605 SelectImageServiceComboItem(svc);
12608 private void SelectImageServiceComboItem(string svc, int? index = null)
12611 if (string.IsNullOrEmpty(svc))
12617 idx = ImageServiceCombo.Items.IndexOf(svc);
12618 if (idx == -1) idx = index ?? 0;
12623 ImageServiceCombo.SelectedIndex = idx;
12625 catch (ArgumentOutOfRangeException)
12627 ImageServiceCombo.SelectedIndex = 0;
12631 private string ImageService
12633 get { return ImageServiceCombo.SelectedItem.ToString(); }
12636 private void ImageServiceCombo_SelectedIndexChanged(object sender, EventArgs e)
12638 if (ImageSelectedPicture.Tag != null && !string.IsNullOrEmpty(this.ImageService))
12642 FileInfo fi = new FileInfo(ImagefilePathText.Text.Trim());
12643 string ext = fi.Extension;
12644 var imageService = this.pictureService[this.ImageService];
12645 if (!imageService.CheckValidFilesize(ext, fi.Length))
12647 ClearImageSelectedPicture(true);
12648 ImagefilePathText.Text = "";
12653 ClearImageSelectedPicture(true);
12654 ImagefilePathText.Text = "";
12656 _modifySettingCommon = true;
12657 SaveConfigsAll(true);
12658 if (this.ImageService == "Twitter")
12660 this.StatusText_TextChanged(null, null);
12665 private void ImageSelectionPanel_VisibleChanged(object sender, EventArgs e)
12667 this.StatusText_TextChanged(null, null);
12671 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12673 using (ListManage form = new ListManage(tw))
12675 form.ShowDialog(this);
12679 public bool ModifySettingCommon
12681 set { _modifySettingCommon = value; }
12684 public bool ModifySettingLocal
12686 set { _modifySettingLocal = value; }
12689 public bool ModifySettingAtId
12691 set { _modifySettingAtId = value; }
12694 private void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12696 string link = (string)SourceLinkLabel.Tag;
12697 if (!string.IsNullOrEmpty(link) && e.Button == MouseButtons.Left)
12699 OpenUriAsync(link);
12703 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12705 string link = (string)SourceLinkLabel.Tag;
12706 if (!string.IsNullOrEmpty(link))
12708 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(link);
12712 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12714 SetStatusLabelUrl();
12717 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12719 if (this.ExistCurrentPost && !_curPost.IsDm)
12720 RtCountMenuItem.Enabled = true;
12722 RtCountMenuItem.Enabled = false;
12724 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12725 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12727 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12730 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12735 private void CopyUserId()
12737 if (_curPost == null) return;
12738 string clstr = _curPost.ScreenName;
12741 Clipboard.SetDataObject(clstr, false, 5, 100);
12743 catch (Exception ex)
12745 MessageBox.Show(ex.Message);
12749 private void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e) // Handles ShowRelatedStatusesMenuItem.Click, ShowRelatedStatusesMenuItem2.Click
12751 if (this.ExistCurrentPost && !_curPost.IsDm)
12755 this.OpenRelatedTab(this._curPost);
12757 catch (TabException ex)
12759 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12765 /// 指定されたツイートに対する関連発言タブを開きます
12767 /// <param name="post">表示する対象となるツイート</param>
12768 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12769 private void OpenRelatedTab(PostClass post)
12771 var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12774 if (tabRelated == null)
12776 tabName = this._statuses.MakeTabName("Related Tweets");
12778 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12779 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12781 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12782 tabRelated.UnreadManage = false;
12783 tabRelated.Notify = false;
12787 tabName = tabRelated.TabName;
12790 tabRelated.RelationTargetPost = post;
12791 this.ClearTab(tabName, false);
12793 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12795 var tabPage = this.ListTab.TabPages[i];
12796 if (tabName == tabPage.Text)
12798 this.ListTab.SelectedIndex = i;
12799 this.ListTabSelect(tabPage);
12804 this.GetTimeline(MyCommon.WORKERTYPE.Related, 1, 1, tabName);
12807 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12809 StringBuilder buf = new StringBuilder();
12810 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12811 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12812 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12813 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12814 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12817 private void tw_UserIdChanged()
12819 this._modifySettingCommon = true;
12822 #region "Userstream"
12823 private bool _isActiveUserstream = false;
12825 private void tw_PostDeleted(long id)
12829 if (InvokeRequired && !IsDisposed)
12831 Invoke((Action) (() =>
12833 _statuses.RemovePostReserve(id);
12834 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(id))
12836 this.PurgeListViewItemCache();
12837 ((DetailsListView)_curTab.Tag).Update();
12838 if (_curPost != null && _curPost.StatusId == id) DispSelectedPost(true);
12844 catch (ObjectDisposedException)
12848 catch (InvalidOperationException)
12854 private void tw_NewPostFromStream()
12856 if (SettingDialog.ReadOldPosts)
12858 _statuses.SetRead(); //新着時未読クリア
12861 int rsltAddCount = _statuses.DistributePosts();
12864 DateTime tm = DateTime.Now;
12865 if (_tlTimestamps.ContainsKey(tm))
12867 _tlTimestamps[tm] += rsltAddCount;
12871 _tlTimestamps.Add(tm, rsltAddCount);
12873 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
12874 List<DateTime> keys = new List<DateTime>();
12876 foreach (DateTime key in _tlTimestamps.Keys)
12878 if (key.CompareTo(oneHour) < 0)
12881 _tlCount += _tlTimestamps[key];
12883 foreach (DateTime key in keys)
12885 _tlTimestamps.Remove(key);
12889 //Static DateTime before = Now;
12890 //if (before.Subtract(Now).Seconds > -5) return;
12894 if (SettingDialog.UserstreamPeriodInt > 0) return;
12898 if (InvokeRequired && !IsDisposed)
12900 Invoke(new Action<bool>(RefreshTimeline), true);
12904 catch (ObjectDisposedException)
12908 catch (InvalidOperationException)
12914 private void tw_UserStreamStarted()
12916 this._isActiveUserstream = true;
12919 if (InvokeRequired && !IsDisposed)
12921 Invoke(new MethodInvoker(tw_UserStreamStarted));
12925 catch (ObjectDisposedException)
12929 catch (InvalidOperationException)
12934 MenuItemUserStream.Text = "&UserStream ▶";
12935 MenuItemUserStream.Enabled = true;
12936 StopToolStripMenuItem.Text = "&Stop";
12937 StopToolStripMenuItem.Enabled = true;
12939 StatusLabel.Text = "UserStream Started.";
12942 private void tw_UserStreamStopped()
12944 this._isActiveUserstream = false;
12947 if (InvokeRequired && !IsDisposed)
12949 Invoke(new MethodInvoker(tw_UserStreamStopped));
12953 catch (ObjectDisposedException)
12957 catch (InvalidOperationException)
12962 MenuItemUserStream.Text = "&UserStream ■";
12963 MenuItemUserStream.Enabled = true;
12964 StopToolStripMenuItem.Text = "&Start";
12965 StopToolStripMenuItem.Enabled = true;
12967 StatusLabel.Text = "UserStream Stopped.";
12970 private void tw_UserStreamEventArrived(Twitter.FormattedEvent ev)
12974 if (InvokeRequired && !IsDisposed)
12976 Invoke(new Action<Twitter.FormattedEvent>(tw_UserStreamEventArrived), ev);
12980 catch (ObjectDisposedException)
12984 catch (InvalidOperationException)
12988 StatusLabel.Text = "Event: " + ev.Event;
12989 //if (ev.Event == "favorite")
12991 // NotifyFavorite(ev);
12994 if (ev.Event == "favorite" || ev.Event == "unfavorite")
12996 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12998 this.PurgeListViewItemCache();
12999 ((DetailsListView)_curTab.Tag).Update();
13001 if (ev.Event == "unfavorite" && ev.Username.ToLower().Equals(tw.Username.ToLower()))
13003 RemovePostFromFavTab(new long[] {ev.Id});
13008 private void NotifyEvent(Twitter.FormattedEvent ev)
13011 if (BalloonRequired(ev))
13013 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
13014 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
13015 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
13016 StringBuilder title = new StringBuilder();
13017 if (SettingDialog.DispUsername)
13019 title.Append(tw.Username);
13020 title.Append(" - ");
13026 title.Append(Application.ProductName);
13027 title.Append(" [");
13028 title.Append(ev.Event.ToUpper());
13029 title.Append("] by ");
13030 if (!string.IsNullOrEmpty(ev.Username))
13032 title.Append(ev.Username.ToString());
13036 //title.Append("");
13039 if (!string.IsNullOrEmpty(ev.Target))
13041 //NotifyIcon1.BalloonTipText = ev.Target;
13046 //NotifyIcon1.BalloonTipText = " ";
13049 //NotifyIcon1.ShowBalloonTip(500);
13050 if (SettingDialog.IsNotifyUseGrowl)
13052 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13053 ev.Id.ToString(), title.ToString(), text);
13057 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
13058 NotifyIcon1.BalloonTipTitle = title.ToString();
13059 NotifyIcon1.BalloonTipText = text;
13060 NotifyIcon1.ShowBalloonTip(500);
13065 string snd = SettingDialog.EventSoundFile;
13066 if (!_initial && SettingDialog.PlaySound && !string.IsNullOrEmpty(snd))
13068 if ((ev.Eventtype & SettingDialog.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13072 string dir = Application.StartupPath;
13073 if (Directory.Exists(Path.Combine(dir, "Sounds")))
13075 dir = Path.Combine(dir, "Sounds");
13077 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13089 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13091 MenuItemUserStream.Enabled = false;
13092 if (StopRefreshAllMenuItem.Checked)
13094 StopRefreshAllMenuItem.Checked = false;
13097 if (this._isActiveUserstream)
13099 tw.StopUserStream();
13103 tw.StartUserStream();
13107 private static string inputTrack = "";
13109 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13111 if (TrackToolStripMenuItem.Checked)
13113 using (InputTabName inputForm = new InputTabName())
13115 inputForm.TabName = inputTrack;
13116 inputForm.FormTitle = "Input track word";
13117 inputForm.FormDescription = "Track word";
13118 if (inputForm.ShowDialog() != DialogResult.OK)
13120 TrackToolStripMenuItem.Checked = false;
13123 inputTrack = inputForm.TabName.Trim();
13125 if (!inputTrack.Equals(tw.TrackWord))
13127 tw.TrackWord = inputTrack;
13128 this._modifySettingCommon = true;
13129 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13130 tw.ReconnectUserStream();
13136 tw.ReconnectUserStream();
13138 this._modifySettingCommon = true;
13141 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13143 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13144 this._modifySettingCommon = true;
13145 tw.ReconnectUserStream();
13148 private void EventViewerMenuItem_Click(object sender, EventArgs e)
13150 if (evtDialog == null || evtDialog.IsDisposed)
13153 evtDialog = new EventViewerDialog();
13154 evtDialog.Owner = this;
13156 Point pos = evtDialog.Location;
13157 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13158 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13159 evtDialog.Location = pos;
13161 evtDialog.EventSource = tw.StoredEvent;
13162 if (!evtDialog.Visible)
13164 evtDialog.Show(this);
13168 evtDialog.Activate();
13170 this.TopMost = this.SettingDialog.AlwaysTop;
13174 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13176 MyCommon._endingFlag = true;
13180 Application.Restart();
13184 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13188 private void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13190 if (!string.IsNullOrEmpty(tw.Username)) OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13193 private void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13195 OpenUriAsync(MyCommon.TwitterUrl + tw.Username);
13198 private async Task doTranslation(string str)
13200 if (string.IsNullOrEmpty(str))
13203 var bing = new Bing(this.http);
13206 var translatedText = await bing.TranslateAsync(str,
13208 langTo: this.SettingDialog.TranslateLanguage);
13210 this.PostBrowser.DocumentText = translatedText;
13212 catch (HttpRequestException e)
13214 this.StatusLabel.Text = "Err:" + e.Message;
13218 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13220 if (!this.ExistCurrentPost)
13223 await this.doTranslation(this._curPost.TextFromApi);
13226 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13228 var text = this.WebBrowser_GetSelectionText(ref this.PostBrowser);
13229 await this.doTranslation(text);
13232 private bool ExistCurrentPost
13236 if (_curPost == null) return false;
13237 if (_curPost.IsDeleted) return false;
13242 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13244 ShowUserTimeline();
13247 public bool FavEventChangeUnread
13249 get { return SettingDialog.FavEventUnread; }
13252 private string GetUserIdFromCurPostOrInput(string caption)
13255 if (_curPost != null)
13257 id = _curPost.ScreenName;
13259 using (InputTabName inputName = new InputTabName())
13261 inputName.FormTitle = caption;
13262 inputName.FormDescription = Properties.Resources.FRMessage1;
13263 inputName.TabName = id;
13264 if (inputName.ShowDialog() == DialogResult.OK &&
13265 !string.IsNullOrEmpty(inputName.TabName.Trim()))
13267 id = inputName.TabName.Trim();
13277 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13279 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13280 if (!string.IsNullOrEmpty(id))
13282 AddNewTabForUserTimeline(id);
13286 private void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13288 string id = GetUserIdFromCurPostOrInput("Show Favstar");
13289 if (!string.IsNullOrEmpty(id))
13291 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13295 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13297 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13300 private void TimelineRefreshEnableChange(bool isEnable)
13304 tw.StartUserStream();
13308 tw.StopUserStream();
13310 TimerTimeline.Enabled = isEnable;
13313 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13315 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13318 private void OpenUserAppointUrl()
13320 if (SettingDialog.UserAppointUrl != null)
13322 if (SettingDialog.UserAppointUrl.Contains("{ID}") || SettingDialog.UserAppointUrl.Contains("{STATUS}"))
13324 if (_curPost != null)
13326 string xUrl = SettingDialog.UserAppointUrl;
13327 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13328 if (_curPost.RetweetedId != null)
13330 xUrl = xUrl.Replace("{STATUS}", _curPost.RetweetedId.ToString());
13334 xUrl = xUrl.Replace("{STATUS}", _curPost.StatusId.ToString());
13336 OpenUriAsync(xUrl);
13341 OpenUriAsync(SettingDialog.UserAppointUrl);
13346 private void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13348 OpenUserAppointUrl();
13351 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13353 string selText = SourceLinkLabel.Text;
13356 Clipboard.SetDataObject(selText, false, 5, 100);
13358 catch (Exception ex)
13360 MessageBox.Show(ex.Message);
13364 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13366 string selText = (string)SourceLinkLabel.Tag;
13369 Clipboard.SetDataObject(selText, false, 5, 100);
13371 catch (Exception ex)
13373 MessageBox.Show(ex.Message);
13377 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13379 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13381 SourceCopyMenuItem.Enabled = false;
13382 SourceUrlCopyMenuItem.Enabled = false;
13386 SourceCopyMenuItem.Enabled = true;
13387 SourceUrlCopyMenuItem.Enabled = true;
13391 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13393 if (Form.ActiveForm == null)
13395 this.BeginInvoke((Action) (() =>
13397 this.Visible = true;
13398 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13400 this.BringToFront();
13401 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13403 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13407 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13413 private void ReplaceAppName()
13415 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13416 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13419 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13421 this.SplitContainer3.Panel2Collapsed = false;
13423 // PreviewDistance が起動のたびに広がっていく問題の回避策
13424 // FixedPanel が Panel2 に設定された状態で Panel2 を開くと、初回だけ SplitterDistance が再計算されておかしくなるため、
13425 // None で開いた後に設定するようにする
13426 if (this.SplitContainer3.FixedPanel == FixedPanel.None)
13427 this.SplitContainer3.FixedPanel = FixedPanel.Panel2;
13430 private void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13432 this.OpenThumbnailPicture(e.Thumbnail);
13435 private void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13437 this.OpenUriAsync(e.ImageUrl);
13440 private void OpenThumbnailPicture(ThumbnailInfo thumbnail)
13442 this.OpenUriAsync(Uri.EscapeUriString(thumbnail.ImageUrl));
13445 private void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13447 this.OpenUriAsync(Twitter.ServiceAvailabilityStatusUrl);
13450 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13452 if (e.KeyCode == Keys.Space)
13454 this.JumpUnreadMenuItem_Click(null, null);
13456 e.SuppressKeyPress = true;
13460 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13462 this.IconSizeNoneToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.IconNone;
13463 this.IconSize16ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon16;
13464 this.IconSize24ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon24;
13465 this.IconSize48ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon48;
13466 this.IconSize48_2ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon48_2;
13468 this.LockListSortOrderToolStripMenuItem.Checked = SettingDialog.SortOrderLock;
13471 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13473 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13476 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13478 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13481 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13483 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13486 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13488 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13491 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13493 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13496 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13498 if (SettingDialog.IconSz == iconSize) return;
13500 var oldIconCol = _iconCol;
13502 SettingDialog.IconSz = iconSize;
13503 ApplyListViewIconSize(iconSize);
13505 if (_iconCol != oldIconCol)
13507 foreach (TabPage tp in ListTab.TabPages)
13509 ResetColumns((DetailsListView)tp.Tag);
13513 if (_curList != null) _curList.Refresh();
13515 _modifySettingCommon = true;
13518 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13520 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13521 if (SettingDialog.SortOrderLock == state) return;
13523 SettingDialog.SortOrderLock = state;
13525 _modifySettingCommon = true;