naps2/NAPS2.Sdk/ImportExport/DirectImportOperation.cs
2019-03-19 15:00:49 -04:00

73 lines
2.4 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Google.Protobuf;
using NAPS2.Lang.Resources;
using NAPS2.Logging;
using NAPS2.Operation;
using NAPS2.Images;
using NAPS2.Images.Storage;
using NAPS2.Images.Transforms;
using NAPS2.Serialization;
namespace NAPS2.ImportExport
{
public class DirectImportOperation : OperationBase
{
private readonly ImageRenderer imageRenderer;
public DirectImportOperation(ImageRenderer imageRenderer)
{
this.imageRenderer = imageRenderer;
AllowCancel = true;
AllowBackground = true;
}
public bool Start(DirectImageTransfer data, bool copy, Action<ScannedImage> imageCallback)
{
ProgressTitle = copy ? MiscResources.CopyProgress : MiscResources.ImportProgress;
Status = new OperationStatus
{
StatusText = copy ? MiscResources.Copying : MiscResources.Importing,
MaxProgress = data.SerializedImages.Count
};
RunAsync(async () =>
{
Exception error = null;
foreach (var serializedImageBytes in data.SerializedImages)
{
try
{
var serializedImage = new SerializedImage();
serializedImage.MergeFrom(serializedImageBytes);
ScannedImage img = SerializedImageHelper.Deserialize(serializedImage, new SerializedImageHelper.DeserializeOptions());
// TODO: Don't bother, here, in recovery, etc.
img.SetThumbnail(Transform.Perform(await imageRenderer.Render(img), new ThumbnailTransform()));
imageCallback(img);
Status.CurrentProgress++;
InvokeStatusChanged();
if (CancelToken.IsCancellationRequested)
{
break;
}
}
catch (Exception ex)
{
error = ex;
}
}
if (error != null)
{
Log.ErrorException(string.Format(MiscResources.ImportErrorCouldNot, "<data>"), error);
}
return true;
});
return true;
}
}
}