OSDN Git Service

using var を使用する
[opentween/open-tween.git] / OpenTween / Extensions.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2015 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
3 // All rights reserved.
4 //
5 // This file is part of OpenTween.
6 //
7 // This program is free software; you can redistribute it and/or modify it
8 // under the terms of the GNU General Public License as published by the Free
9 // Software Foundation; either version 3 of the License, or (at your option)
10 // any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 // for more details.
16 //
17 // You should have received a copy of the GNU General Public License along
18 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
19 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
20 // Boston, MA 02110-1301, USA.
21
22 using System;
23 using System.Collections.Generic;
24 using System.Globalization;
25 using System.Linq;
26 using System.Text;
27 using System.Threading;
28 using System.Threading.Tasks;
29 using System.Windows.Forms;
30
31 namespace OpenTween
32 {
33     internal static class Extensions
34     {
35         /// <summary>
36         /// WebBrowserで選択中のテキストを取得します
37         /// </summary>
38         public static string GetSelectedText(this WebBrowser webBrowser)
39         {
40             dynamic document = webBrowser.Document.DomDocument;
41             dynamic textRange = document.selection.createRange();
42             string selectedText = textRange.text;
43
44             return selectedText;
45         }
46
47         public static ReadLockTransaction BeginReadTransaction(this ReaderWriterLockSlim lockObj)
48             => new ReadLockTransaction(lockObj);
49
50         public static WriteLockTransaction BeginWriteTransaction(this ReaderWriterLockSlim lockObj)
51             => new WriteLockTransaction(lockObj);
52
53         public static UpgradeableReadLockTransaction BeginUpgradeableReadTransaction(this ReaderWriterLockSlim lockObj)
54             => new UpgradeableReadLockTransaction(lockObj);
55
56         /// <summary>
57         /// 一方のカルチャがもう一方のカルチャを内包するかを判断します
58         /// </summary>
59         public static bool Contains(this CultureInfo @this, CultureInfo that)
60         {
61             if (@this.Equals(that))
62                 return true;
63
64             // InvariantCulture の親カルチャは InvariantCulture 自身であるため、false になったら打ち切る
65             if (!that.Parent.Equals(that))
66                 return Contains(@this, that.Parent);
67
68             return false;
69         }
70
71         public static IEnumerable<(T Value, int Index)> WithIndex<T>(this IEnumerable<T> enumerable)
72         {
73             var i = 0;
74             foreach (var value in enumerable)
75                 yield return (value, i++);
76         }
77
78         public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp, out TKey key, out TValue value)
79         {
80             key = kvp.Key;
81             value = kvp.Value;
82         }
83
84         /// <summary>
85         /// 文字列をコードポイント単位に分割して返します
86         /// </summary>
87         public static IEnumerable<int> ToCodepoints(this string s)
88         {
89             if (s == null)
90                 throw new ArgumentNullException(nameof(s));
91
92             IEnumerable<int> GetEnumerable(string input)
93             {
94                 var i = 0;
95                 var length = input.Length;
96                 while (i < length)
97                 {
98                     if (char.IsSurrogatePair(input, i))
99                     {
100                         yield return char.ConvertToUtf32(input, i);
101                         i += 2;
102                     }
103                     else
104                     {
105                         yield return input[i];
106                         i++;
107                     }
108                 }
109             }
110
111             return GetEnumerable(s);
112         }
113
114         /// <summary>
115         /// 指定された部分文字列のコードポイント単位での文字数を返す
116         /// </summary>
117         /// <param name="s">文字列</param>
118         /// <param name="start">開始位置</param>
119         /// <param name="end">終了位置</param>
120         public static int GetCodepointCount(this string s, int start, int end)
121         {
122             if (s == null)
123                 throw new ArgumentNullException(nameof(s));
124             if (start < 0 || start > s.Length)
125                 throw new ArgumentOutOfRangeException(nameof(start));
126             if (end < 0 || end > s.Length)
127                 throw new ArgumentOutOfRangeException(nameof(end));
128             if (start > end)
129                 throw new ArgumentOutOfRangeException(nameof(start));
130
131             var count = 0;
132             for (var i = start; i < end; i += char.IsSurrogatePair(s, i) ? 2 : 1)
133                 count++;
134
135             return count;
136         }
137
138         public static Task ForEachAsync<T>(this IObservable<T> observable, Action<T> subscriber)
139             => ForEachAsync(observable, value => { subscriber(value); return Task.CompletedTask; });
140
141         public static Task ForEachAsync<T>(this IObservable<T> observable, Func<T, Task> subscriber)
142             => ForEachAsync(observable, subscriber, CancellationToken.None);
143
144         public static Task ForEachAsync<T>(this IObservable<T> observable, Action<T> subscriber, CancellationToken cancellationToken)
145             => ForEachAsync(observable, value => { subscriber(value); return Task.CompletedTask; }, cancellationToken);
146
147         public static async Task ForEachAsync<T>(this IObservable<T> observable, Func<T, Task> subscriber, CancellationToken cancellationToken)
148         {
149             var observer = new ForEachObserver<T>(subscriber);
150             using var unsubscriber = observable.Subscribe(observer);
151
152             using (cancellationToken.Register(() => unsubscriber.Dispose()))
153                 await observer.Task.ConfigureAwait(false);
154         }
155
156         private class ForEachObserver<T> : IObserver<T>
157         {
158             private readonly Func<T, Task> subscriber;
159             private readonly TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
160
161             public Task Task
162                 => this.tcs.Task;
163
164             public ForEachObserver(Func<T, Task> subscriber)
165                 => this.subscriber = subscriber;
166
167             public async void OnNext(T value)
168             {
169                 try
170                 {
171                     await this.subscriber(value);
172                 }
173                 catch (Exception ex)
174                 {
175                     this.tcs.TrySetException(ex);
176                 }
177             }
178
179             public void OnCompleted()
180                 => this.tcs.TrySetResult(1);
181
182             public void OnError(Exception error)
183                 => this.tcs.TrySetException(error);
184         }
185     }
186 }