Skip to content

Commit

Permalink
Fix console cancellation
Browse files Browse the repository at this point in the history
  • Loading branch information
cyanfish committed Sep 2, 2024
1 parent e0eada5 commit 70eb676
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 6 deletions.
26 changes: 20 additions & 6 deletions NAPS2.Lib/Automation/AutomatedScanning.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ internal class AutomatedScanning

private readonly ConsoleOutput _output;
private readonly AutomatedScanningOptions _options;
private readonly CancellationTokenSource _cts = new();
private PdfEncryption _parsedEncryptConfigOption = null!;
private List<List<ProcessedImage>> _scanList = null!;
private int _pagesScanned;
Expand Down Expand Up @@ -78,6 +79,15 @@ private void OutputVerbose(string value, params object[] args)

public async Task Execute()
{
Console.CancelKeyPress += (_, e) =>
{
if (!_cts.IsCancellationRequested)
{
Console.WriteLine(ConsoleResources.Cancelling);
_cts.Cancel();
e.Cancel = true;
}
};
bool hasUnexpectedException = false;
try
{
Expand Down Expand Up @@ -115,6 +125,8 @@ public async Task Execute()
await ImportImages();
}

if (_cts.IsCancellationRequested) return;

ConfigureOcr();

if (_options.Number > 0)
Expand All @@ -130,6 +142,8 @@ public async Task Execute()
await PerformScan(profile);
}

if (_cts.IsCancellationRequested) return;

ReorderScannedImages();

if (_options.OutputPath != null)
Expand Down Expand Up @@ -245,9 +259,7 @@ private async Task ListDevices()
};
await SetProfileOverrides(profile);

var cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, _) => cts.Cancel();
await foreach (var device in _scanPerformer.GetDevices(profile, cts.Token))
await foreach (var device in _scanPerformer.GetDevices(profile, _cts.Token))
{
_output.Writer.WriteLine(device.Name);
}
Expand Down Expand Up @@ -332,7 +344,7 @@ private async Task ImportImages()
PatchTOnly = true
}
};
await foreach (var image in _fileImporter.Import(actualPath, importParams))
await foreach (var image in _fileImporter.Import(actualPath, importParams, _cts.Token))
{
scan.Add(PostProcessImportedImage(image));
}
Expand Down Expand Up @@ -443,7 +455,7 @@ private async Task EmailScannedImages()
}

OutputVerbose(ConsoleResources.SendingEmail);
if (await _emailProviderFactory.Default.SendEmail(message))
if (await _emailProviderFactory.Default.SendEmail(message, _cts.Token))
{
OutputVerbose(ConsoleResources.EmailSent);
}
Expand Down Expand Up @@ -590,6 +602,7 @@ private async Task DoExportToImageFiles(string outputPath)
foreach (var scan in _scanList)
{
var op = _operationFactory.Create<SaveImagesOperation>();
_cts.Token.Register(op.Cancel);
int i = -1;
op.StatusChanged += (sender, args) =>
{
Expand Down Expand Up @@ -673,6 +686,7 @@ private async Task<bool> DoExportToPdf(string path, bool email)
foreach (var fileContents in _scanList)
{
var op = _operationFactory.Create<SavePdfOperation>();
_cts.Token.Register(op.Cancel);
int i = -1;
op.StatusChanged += (sender, args) =>
{
Expand Down Expand Up @@ -731,7 +745,7 @@ private async Task PerformScan(ScanProfile profile)
DetectPatchT = _options.SplitPatchT,
OcrParams = _ocrParams
};
await foreach (var image in _scanPerformer.PerformScan(profile, scanParams))
await foreach (var image in _scanPerformer.PerformScan(profile, scanParams, cancelToken: _cts.Token))
{
ReceiveScannedImage(image);
}
Expand Down
9 changes: 9 additions & 0 deletions NAPS2.Lib/Lang/ConsoleResources/ConsoleResources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions NAPS2.Lib/Lang/ConsoleResources/ConsoleResources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -263,4 +263,7 @@ Use the "--importpassword" option.</value>
<data name="DriverRequired" xml:space="preserve">
<value>The --driver option must be set to use the --device or --listdevices option. Possible values: {0}</value>
</data>
<data name="Cancelling" xml:space="preserve">
<value>Cancelling... Press Ctrl+C again to terminate.</value>
</data>
</root>
3 changes: 3 additions & 0 deletions NAPS2.Sdk/Scan/Internal/Twain/RemoteTwainController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ public async Task StartScan(ScanOptions options, ITwainEvents twainEvents, Cance
// We need to report cancellation so that TwainImageProcessor doesn't return a partial image
_scanningContext.Logger.LogDebug("NAPS2.TW - Sending cancel event");
twainEvents.TransferCanceled(new TwainTransferCanceled());
// We also want to wait until the worker closes so we guarantee the parent process doesn't die before the
// TWAIN process has a chance to clean up
await workerContext.Stop();
}
}

Expand Down

0 comments on commit 70eb676

Please sign in to comment.