OSDN Git Service

プロフィール画面へのD&Dによるアイコン変更時に確認ダイアログを表示するように変更
[opentween/open-tween.git] / OpenTween / ImageCache.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2013 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.Linq;
25 using System.Text;
26 using System.Threading.Tasks;
27 using System.Net;
28 using System.Threading;
29 using System.Xml.Serialization;
30 using System.Net.Http;
31 using OpenTween.Connection;
32
33 namespace OpenTween
34 {
35     public class ImageCache : IDisposable
36     {
37         /// <summary>
38         /// キャッシュとして URL と取得した画像を対に保持する辞書
39         /// </summary>
40         internal LRUCacheDictionary<string, Task<MemoryImage>> innerDictionary;
41
42         /// <summary>
43         /// 非同期タスクをキャンセルするためのトークンのもと
44         /// </summary>
45         private CancellationTokenSource cancelTokenSource;
46
47         /// <summary>
48         /// innerDictionary の排他制御のためのロックオブジェクト
49         /// </summary>
50         private object lockObject = new object();
51
52         /// <summary>
53         /// オブジェクトが破棄された否か
54         /// </summary>
55         private bool disposed = false;
56
57         public ImageCache()
58         {
59             this.innerDictionary = new LRUCacheDictionary<string, Task<MemoryImage>>(trimLimit: 300, autoTrimCount: 100);
60             this.innerDictionary.CacheRemoved += (s, e) => {
61                 // まだ参照されている場合もあるのでDisposeはファイナライザ任せ
62                 this.CacheRemoveCount++;
63             };
64
65             this.cancelTokenSource = new CancellationTokenSource();
66         }
67
68         /// <summary>
69         /// 保持しているキャッシュの件数
70         /// </summary>
71         public long CacheCount
72         {
73             get { return this.innerDictionary.Count; }
74         }
75
76         /// <summary>
77         /// 破棄されたキャッシュの件数
78         /// </summary>
79         public int CacheRemoveCount { get; private set; }
80
81         /// <summary>
82         /// 指定された URL にある画像を非同期に取得するメソッド
83         /// </summary>
84         /// <param name="address">取得先の URL</param>
85         /// <param name="force">キャッシュを使用せずに取得する場合は true</param>
86         /// <returns>非同期に画像を取得するタスク</returns>
87         public Task<MemoryImage> DownloadImageAsync(string address, bool force = false)
88         {
89             var cancelToken = this.cancelTokenSource.Token;
90
91             return Task.Run(() =>
92             {
93                 Task<MemoryImage> cachedImageTask = null;
94                 lock (this.lockObject)
95                 {
96                     innerDictionary.TryGetValue(address, out cachedImageTask);
97
98                     if (cachedImageTask != null)
99                     {
100                         if (force)
101                         {
102                             this.innerDictionary.Remove(address);
103
104                             if (cachedImageTask.Status == TaskStatus.RanToCompletion)
105                                 cachedImageTask.Result.Dispose();
106
107                             cachedImageTask.Dispose();
108                             cachedImageTask = null;
109                         }
110                         else
111                             return cachedImageTask;
112                     }
113
114                     cancelToken.ThrowIfCancellationRequested();
115
116                     var imageTask = this.FetchImageAsync(address, cancelToken);
117                     this.innerDictionary[address] = imageTask;
118
119                     return imageTask;
120                 }
121             }, cancelToken);
122         }
123
124         private async Task<MemoryImage> FetchImageAsync(string uri, CancellationToken cancelToken)
125         {
126             using (var response = await Networking.Http.GetAsync(uri, cancelToken).ConfigureAwait(false))
127             {
128                 response.EnsureSuccessStatusCode();
129
130                 using (var imageStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
131                 {
132                     return await MemoryImage.CopyFromStreamAsync(imageStream)
133                         .ConfigureAwait(false);
134                 }
135             }
136         }
137
138         public MemoryImage TryGetFromCache(string address)
139         {
140             lock (this.lockObject)
141             {
142                 Task<MemoryImage> imageTask;
143                 if (!this.innerDictionary.TryGetValue(address, out imageTask) ||
144                     imageTask.Status != TaskStatus.RanToCompletion)
145                     return null;
146
147                 return imageTask.Result;
148             }
149         }
150
151         public void CancelAsync()
152         {
153             lock (this.lockObject)
154             {
155                 var oldTokenSource = this.cancelTokenSource;
156                 this.cancelTokenSource = new CancellationTokenSource();
157
158                 oldTokenSource.Cancel();
159                 oldTokenSource.Dispose();
160             }
161         }
162
163         protected virtual void Dispose(bool disposing)
164         {
165             if (this.disposed) return;
166
167             if (disposing)
168             {
169                 this.CancelAsync();
170
171                 lock (this.lockObject)
172                 {
173                     foreach (var item in this.innerDictionary)
174                     {
175                         var task = item.Value;
176                         if (task.Status == TaskStatus.RanToCompletion && task.Result != null)
177                             task.Result.Dispose();
178                     }
179
180                     this.innerDictionary.Clear();
181                     this.cancelTokenSource.Dispose();
182                 }
183             }
184
185             this.disposed = true;
186         }
187
188         public void Dispose()
189         {
190             this.Dispose(true);
191             GC.SuppressFinalize(this);
192         }
193
194         ~ImageCache()
195         {
196             this.Dispose(false);
197         }
198     }
199 }