OSDN Git Service

TweenMain.ListTab.SelectedTabへの参照をCurrentTabPageに置き換える
[opentween/open-tween.git] / OpenTween / EventViewerDialog.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 //           (c) 2008-2011 Moz (@syo68k)
4 //           (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 //           (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 //           (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 //           (c) 2011-2012 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
9 // 
10 // This file is part of OpenTween.
11 // 
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
15 // any later version.
16 // 
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
20 // for more details. 
21 // 
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
26
27 using System;
28 using System.Collections.Generic;
29 using System.ComponentModel;
30 using System.Data;
31 using System.Diagnostics.CodeAnalysis;
32 using System.Drawing;
33 using System.Linq;
34 using System.Text;
35 using System.Windows.Forms;
36 using System.Text.RegularExpressions;
37 using System.IO;
38 using System.Globalization;
39 using OpenTween.Setting;
40 using System.Threading.Tasks;
41
42 namespace OpenTween
43 {
44     public partial class EventViewerDialog : OTBaseForm
45     {
46         public List<Twitter.FormattedEvent> EventSource { get; set; }
47
48         private Twitter.FormattedEvent[] _filterdEventSource;
49
50         private ListViewItem[] _ItemCache = null;
51         private int _itemCacheIndex;
52
53         private TabPage _curTab = null;
54
55         public EventViewerDialog()
56         {
57             InitializeComponent();
58
59             // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
60             this.TabEventType.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
61         }
62
63         protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
64         {
65             base.ScaleControl(factor, specified);
66             ScaleChildControl(this.EventList, factor);
67         }
68
69         private void OK_Button_Click(object sender, EventArgs e)
70         {
71             this.DialogResult = DialogResult.OK;
72             this.Close();
73         }
74
75         private void Cancel_Button_Click(object sender, EventArgs e)
76         {
77             this.DialogResult = DialogResult.Cancel;
78             this.Close();
79         }
80
81         private ListViewItem CreateListViewItem(Twitter.FormattedEvent source)
82         {
83             string[] s = { source.CreatedAt.ToLocalTimeString(), source.Event.ToUpper(CultureInfo.CurrentCulture), source.Username, source.Target };
84             return new ListViewItem(s);
85         }
86
87         private void EventViewerDialog_Shown(object sender, EventArgs e)
88         {
89             // タブ初期化
90             foreach (var tabPage in CreateTabsFromUserStreamsEvent())
91             {
92                 TabEventType.TabPages.Add(tabPage);
93             }
94
95             EventList.BeginUpdate();
96             _curTab = TabEventType.SelectedTab;
97             CreateFilterdEventSource();
98             EventList.EndUpdate();
99             this.TopMost = SettingManager.Common.AlwaysTop;
100         }
101
102         private async void EventList_DoubleClick(object sender, EventArgs e)
103             => await this.OpenEventStatusOrUser();
104
105         private async void EventList_KeyDown(object sender, KeyEventArgs e)
106         {
107             if (e.KeyData == Keys.Enter)
108                 await this.OpenEventStatusOrUser();
109         }
110
111         private async Task OpenEventStatusOrUser()
112         {
113             if (this.EventList.SelectedIndices.Count == 0)
114                 return;
115
116             var tweenMain = (TweenMain)this.Owner;
117             var selectedEvent = this._filterdEventSource[this.EventList.SelectedIndices[0]];
118             if (selectedEvent != null)
119             {
120                 if (selectedEvent.Id != 0)
121                     await tweenMain.OpenRelatedTab(selectedEvent.Id);
122                 else
123                     await tweenMain.OpenUriAsync(new Uri("https://twitter.com/" + selectedEvent.Username));
124             }
125         }
126
127         private MyCommon.EVENTTYPE ParseEventTypeFromTag()
128             => (MyCommon.EVENTTYPE)Enum.Parse(typeof(MyCommon.EVENTTYPE), _curTab.Tag.ToString());
129
130         private bool IsFilterMatch(Twitter.FormattedEvent x)
131         {
132             if (!CheckBoxFilter.Checked || string.IsNullOrEmpty(TextBoxKeyword.Text))
133             {
134                 return true;
135             }
136             else
137             {
138                 if (CheckRegex.Checked)
139                 {
140                     try
141                     {
142                         Regex rx = new Regex(TextBoxKeyword.Text);
143                         return rx.Match(x.Username).Success || rx.Match(x.Target).Success;
144                     }
145                     catch (Exception ex)
146                     {
147                         MessageBox.Show(Properties.Resources.ButtonOK_ClickText3 + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
148                         return false;
149                     }
150                 }
151                 else
152                 {
153                     return x.Username.Contains(TextBoxKeyword.Text) || x.Target.Contains(TextBoxKeyword.Text);
154                 }
155             }
156         }
157
158         private void CreateFilterdEventSource()
159         {
160             if (EventSource != null && EventSource.Count > 0)
161             {
162                 _filterdEventSource = EventSource.FindAll((x) => !(CheckExcludeMyEvent.Checked && x.IsMe) &&
163                                                                  (x.Eventtype & ParseEventTypeFromTag()) != 0 &&
164                                                                  IsFilterMatch(x)).ToArray();
165                 _ItemCache = null;
166                 EventList.VirtualListSize = _filterdEventSource.Count();
167                 StatusLabelCount.Text = string.Format("{0} / {1}", _filterdEventSource.Count(), EventSource.Count());
168             }
169             else
170             {
171                 StatusLabelCount.Text = "0 / 0";
172             }
173         }
174
175         private void CheckExcludeMyEvent_CheckedChanged(object sender, EventArgs e)
176             => this.CreateFilterdEventSource();
177
178         private void ButtonRefresh_Click(object sender, EventArgs e)
179             => this.CreateFilterdEventSource();
180
181         private void TabEventType_SelectedIndexChanged(object sender, EventArgs e)
182             => this.CreateFilterdEventSource();
183
184         private void TabEventType_Selecting(object sender, TabControlCancelEventArgs e)
185         {
186             _curTab = e.TabPage;
187             if (!e.TabPage.Controls.Contains(EventList))
188             {
189                 e.TabPage.Controls.Add(EventList);
190             }
191         }
192
193         private void TextBoxKeyword_KeyPress(object sender, KeyPressEventArgs e)
194         {
195             if (e.KeyChar == (char)Keys.Enter)
196             {
197                 CreateFilterdEventSource();
198                 e.Handled = true;
199             }
200         }
201
202         private void EventList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
203         {
204             if (_ItemCache != null && e.ItemIndex >= _itemCacheIndex && e.ItemIndex < _itemCacheIndex + _ItemCache.Length)
205             {
206                 //キャッシュヒット
207                 e.Item = _ItemCache[e.ItemIndex - _itemCacheIndex];
208             }
209             else
210             {
211                 //キャッシュミス
212                 e.Item = CreateListViewItem(_filterdEventSource[e.ItemIndex]);
213             }
214         }
215
216         private void EventList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
217             => this.CreateCache(e.StartIndex, e.EndIndex);
218
219         private void CreateCache(int StartIndex, int EndIndex)
220         {
221             //キャッシュ要求(要求範囲±30を作成)
222             StartIndex -= 30;
223             if (StartIndex < 0) StartIndex = 0;
224             EndIndex += 30;
225             if (EndIndex > _filterdEventSource.Count() - 1)
226             {
227                 EndIndex = _filterdEventSource.Count() - 1;
228             }
229             _ItemCache = new ListViewItem[] { };
230             Array.Resize(ref _ItemCache, EndIndex - StartIndex + 1);
231             _itemCacheIndex = StartIndex;
232             for (int i = 0; i < _ItemCache.Length; i++)
233             {
234                 _ItemCache[i] = CreateListViewItem(_filterdEventSource[StartIndex + i]);
235             }
236         }
237
238         private void SaveLogButton_Click(object sender, EventArgs e)
239         {
240             DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText5, Environment.NewLine),
241                     Properties.Resources.SaveLogMenuItem_ClickText2,
242                     MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
243             switch (rslt)
244             {
245                 case DialogResult.Yes:
246                     SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Events{_curTab.Tag}{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
247                     break;
248                 case DialogResult.No:
249                     SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Events{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
250                     break;
251                 default:
252                     return;
253             }
254
255             SaveFileDialog1.InitialDirectory = Application.StartupPath;
256             SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
257             SaveFileDialog1.FilterIndex = 0;
258             SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
259             SaveFileDialog1.RestoreDirectory = true;
260
261             if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
262             {
263                 if (!SaveFileDialog1.ValidateNames) return;
264                 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
265                 {
266                     switch (rslt)
267                     {
268                         case DialogResult.Yes:
269                             SaveEventLog(_filterdEventSource.ToList(), sw);
270                             break;
271                         case DialogResult.No:
272                             SaveEventLog(EventSource, sw);
273                             break;
274                         default:
275                             //
276                             break;
277                     }
278                 }
279             }
280             this.TopMost = SettingManager.Common.AlwaysTop;
281         }
282
283         private void SaveEventLog(List<Twitter.FormattedEvent> source, StreamWriter sw)
284         {
285             foreach (Twitter.FormattedEvent _event in source)
286             {
287                 sw.WriteLine(_event.Eventtype + "\t" +
288                              "\"" + _event.CreatedAt.ToLocalTimeString() + "\"\t" +
289                              _event.Event + "\t" +
290                              _event.Username + "\t" +
291                              _event.Target + "\t" +
292                              _event.Id);
293             }
294         }
295
296         [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
297         private static IEnumerable<TabPage> CreateTabsFromUserStreamsEvent()
298         {
299             return Enum.GetNames(typeof(MyCommon.EVENTTYPE))
300                        .Where(e => e != "None" && e != "All")
301                        .Select(e => new TabPage(e)
302                        {
303                            // Name = "TabPage" + e,
304                            Tag = e,
305                            UseVisualStyleBackColor = true,
306                            AccessibleRole = AccessibleRole.PageTab,
307                        });
308         }
309     }
310 }