2021-12-17 23:18:20 +03:00
|
|
|
|
namespace NAPS2.Images;
|
2021-12-17 22:59:54 +03:00
|
|
|
|
|
2022-06-27 00:12:32 +03:00
|
|
|
|
// TODO: Add a method or something for IAsyncEnumerable, conditionally compiling for .NET 5+
|
2021-12-17 22:59:54 +03:00
|
|
|
|
public abstract class ScannedImageSource
|
2018-09-05 23:26:04 +03:00
|
|
|
|
{
|
2021-12-17 22:59:54 +03:00
|
|
|
|
public static ScannedImageSource Empty => new EmptySource();
|
2019-05-04 02:25:05 +03:00
|
|
|
|
|
2022-06-09 05:54:08 +03:00
|
|
|
|
public abstract Task<ProcessedImage?> Next();
|
2019-05-04 02:25:05 +03:00
|
|
|
|
|
2022-06-09 05:54:08 +03:00
|
|
|
|
public async Task<List<ProcessedImage>> ToList()
|
2021-12-17 22:59:54 +03:00
|
|
|
|
{
|
2022-06-09 05:54:08 +03:00
|
|
|
|
var list = new List<ProcessedImage>();
|
2021-12-17 22:59:54 +03:00
|
|
|
|
try
|
2018-09-05 23:26:04 +03:00
|
|
|
|
{
|
2021-12-17 22:59:54 +03:00
|
|
|
|
await ForEach(image => list.Add(image));
|
2018-09-05 23:26:04 +03:00
|
|
|
|
}
|
2021-12-17 22:59:54 +03:00
|
|
|
|
catch (Exception)
|
2018-09-05 23:26:04 +03:00
|
|
|
|
{
|
2021-12-17 22:59:54 +03:00
|
|
|
|
// TODO: If we ever allow multiple enumeration, this will need to be rethought
|
|
|
|
|
foreach (var image in list)
|
2018-09-05 23:26:04 +03:00
|
|
|
|
{
|
2021-12-17 22:59:54 +03:00
|
|
|
|
image.Dispose();
|
2018-12-04 04:12:20 +03:00
|
|
|
|
}
|
2021-12-17 22:59:54 +03:00
|
|
|
|
|
|
|
|
|
throw;
|
2018-12-04 04:12:20 +03:00
|
|
|
|
}
|
|
|
|
|
|
2021-12-17 22:59:54 +03:00
|
|
|
|
return list;
|
|
|
|
|
}
|
|
|
|
|
|
2022-06-09 05:54:08 +03:00
|
|
|
|
public async Task ForEach(Action<ProcessedImage> action)
|
2021-12-17 22:59:54 +03:00
|
|
|
|
{
|
2022-06-09 05:54:08 +03:00
|
|
|
|
ProcessedImage? image;
|
2021-12-17 22:59:54 +03:00
|
|
|
|
while ((image = await Next()) != null)
|
2018-12-04 04:12:20 +03:00
|
|
|
|
{
|
2021-12-17 22:59:54 +03:00
|
|
|
|
action(image);
|
2018-09-05 23:26:04 +03:00
|
|
|
|
}
|
2021-12-17 22:59:54 +03:00
|
|
|
|
}
|
2019-05-04 02:25:05 +03:00
|
|
|
|
|
2022-06-09 05:54:08 +03:00
|
|
|
|
public async Task ForEach(Func<ProcessedImage, Task> action)
|
2021-12-17 22:59:54 +03:00
|
|
|
|
{
|
2022-06-09 05:54:08 +03:00
|
|
|
|
ProcessedImage? image;
|
2021-12-17 22:59:54 +03:00
|
|
|
|
while ((image = await Next()) != null)
|
2019-05-04 02:25:05 +03:00
|
|
|
|
{
|
2021-12-17 22:59:54 +03:00
|
|
|
|
await action(image);
|
2019-05-04 02:25:05 +03:00
|
|
|
|
}
|
2018-09-05 23:26:04 +03:00
|
|
|
|
}
|
2021-12-17 22:59:54 +03:00
|
|
|
|
|
|
|
|
|
private class EmptySource : ScannedImageSource
|
|
|
|
|
{
|
2022-06-09 05:54:08 +03:00
|
|
|
|
public override Task<ProcessedImage?> Next() => Task.FromResult<ProcessedImage?>(null);
|
2021-12-17 22:59:54 +03:00
|
|
|
|
}
|
|
|
|
|
}
|