-
-
Notifications
You must be signed in to change notification settings - Fork 445
Expand file tree
/
Copy pathTwainScanRunner.cs
More file actions
445 lines (408 loc) · 17.2 KB
/
Copy pathTwainScanRunner.cs
File metadata and controls
445 lines (408 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#if !MAC
using System.Threading;
using Google.Protobuf;
using Microsoft.Extensions.Logging;
using NAPS2.Remoting.Worker;
using NAPS2.Scan.Exceptions;
using NTwain;
using NTwain.Data;
namespace NAPS2.Scan.Internal.Twain;
/// <summary>
/// Interfaces with the native NTwain TwainSession to perform an actual scan. The raw scanned data is propagated via the
/// ITwainEvents interface. This logic involves quite a bit of complicated state management related to the Twain spec.
/// https://twain.org/wp-content/uploads/2015/05/TWAIN-2.3-Specification.pdf
/// </summary>
internal class TwainScanRunner
{
private readonly ILogger _logger;
private readonly TwainDsm _dsm;
private readonly ScanOptions _options;
private readonly CancellationToken _cancelToken;
private readonly ITwainEvents _twainEvents;
private readonly TwainHandleManager _handleManager;
private readonly TwainSession _session;
private readonly TaskCompletionSource<bool> _tcs;
private readonly TaskCompletionSource<bool> _sourceDisabledTcs;
private DataSource? _source;
public TwainScanRunner(ILogger logger, TWIdentity twainAppId, TwainDsm dsm, ScanOptions options,
CancellationToken cancelToken, ITwainEvents twainEvents)
{
_logger = logger;
_dsm = dsm;
_options = options;
_cancelToken = cancelToken;
_twainEvents = twainEvents;
_handleManager = TwainHandleManager.Factory();
PlatformInfo.Current.PreferNewDSM = dsm != TwainDsm.Old;
_logger.LogDebug($"Using TWAIN DSM: {PlatformInfo.Current.ExpectedDsmPath}");
_session = new TwainSession(twainAppId);
_session.TransferReady += TransferReady;
_session.DataTransferred += DataTransferred;
_session.TransferCanceled += TransferCanceled;
_session.TransferError += TransferError;
_session.SourceDisabled += SourceDisabled;
_session.StateChanged += StateChanged;
_tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_sourceDisabledTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
}
public Task Run()
{
_handleManager.Invoker.InvokeDispatch(Init);
return _tcs.Task;
}
private void Init()
{
try
{
_logger.LogDebug("NAPS2.TW - Opening session");
bool useNativeUi = _options.UseNativeUI || _options.TwainOptions.ShowProgress;
var rc = _session.Open(_handleManager.CreateMessageLoopHook(_options.DialogParent, useNativeUi));
if (rc != ReturnCode.Success)
{
throw new DeviceException($"TWAIN session open error: {rc}");
}
_logger.LogDebug("NAPS2.TW - Finding source");
_source = _session.FirstOrDefault(x => x.Name == _options.Device!.ID);
if (_source == null)
{
throw new DeviceNotFoundException();
}
_logger.LogDebug("NAPS2.TW - Opening source");
_logger.LogDebug(
"NAPS2.TW - Name: {Name}; Manu: {Manu}; Family: {Family}; Version: {Version}; Protocol: {Protocol}",
_source.Name, _source.Manufacturer, _source.ProductFamily, _source.Version, _source.ProtocolVersion);
rc = _source.Open();
if (rc != ReturnCode.Success)
{
throw GetExceptionForStatus(_session.GetStatus());
}
_logger.LogDebug("NAPS2.TW - Configuring source");
ConfigureSource(_source);
_logger.LogDebug("NAPS2.TW - Enabling source");
var ui = _options.UseNativeUI ? SourceEnableMode.ShowUI : SourceEnableMode.NoUI;
var enableHandle = _handleManager.GetEnableHandle(_options.DialogParent, useNativeUi);
// Note that according to the twain spec, on Windows it is recommended to set the modal parameter to false
rc = _source.Enable(ui, false, enableHandle);
if (rc != ReturnCode.Success)
{
throw GetExceptionForStatus(_source.GetStatus());
}
_cancelToken.Register(() => _handleManager.Invoker.Invoke(FinishWithCancellation));
_sourceDisabledTcs.Task.ContinueWith(_ => _handleManager.Invoker.Invoke(FinishWithCompletion))
.AssertNoAwait();
}
catch (Exception ex)
{
FinishWithError(ex);
}
}
private void FinishWithCancellation()
{
_logger.LogDebug("NAPS2.TW - Finishing with cancellation");
if (_session.State != 5)
{
// If we're in state 6 or 7, this will abort the ongoing transfer via ForceStepDown.
// If we're in state 4 or lower, then we're not transferring and this will just clean up the source/session.
UnloadTwain();
_tcs.TrySetResult(false);
}
else
{
// If we're in state 5, we can just wait for the TransferReady event and "naturally" cancel the transfer.
// (Or if we're in state 5 in the process of finishing all transfers, then we don't need to cancel anyway.)
// This will result in FinishWithCompletion being called when the source disables itself.
// The alternative of calling ForceStepDown from state 5 seems to produce an error message from the scanner.
_logger.LogDebug("NAPS2.TW - Will cancel via TransferReady");
}
}
private void FinishWithError(Exception ex)
{
_logger.LogDebug(ex, "NAPS2.TW - Finishing with error");
// If we're in state 5 or higher, we'll call ForceStepDown, which could potentially produce additional errors,
// but what alternative is there?
// If we're in state 4 or lower, this will just clean up the source/session.
UnloadTwain();
_tcs.TrySetException(ex);
}
private void FinishWithCompletion()
{
_logger.LogDebug("NAPS2.TW - Finishing with completion");
// At this point we should be in state 4 and this will clean up the source/session.
UnloadTwain();
_tcs.TrySetResult(true);
}
private void UnloadTwain()
{
try
{
if (_session.State > 4)
{
// If a transfer is initialized or in progress, this will abort it and also clean up the source/session.
_session.ForceStepDown(2);
return;
}
// If a transfer isn't in progress, we just clean up the source/session as needed.
if (_session.State == 4)
{
_source!.Close();
}
if (_session.State >= 3)
{
_session.Close();
}
}
finally
{
_handleManager.Dispose();
}
}
private void StateChanged(object? sender, EventArgs e)
{
_logger.LogDebug($"NAPS2.TW - StateChanged (to {_session.State})");
}
private void SourceDisabled(object? sender, EventArgs e)
{
_logger.LogDebug("NAPS2.TW - SourceDisabled");
_sourceDisabledTcs.TrySetResult(true);
}
private void TransferCanceled(object? sender, TransferCanceledEventArgs e)
{
_logger.LogDebug("NAPS2.TW - TransferCanceled");
_twainEvents.TransferCanceled(new TwainTransferCanceled());
}
private void TransferError(object? sender, TransferErrorEventArgs e)
{
_logger.LogDebug("NAPS2.TW - TransferError");
FinishWithError(e.Exception ?? GetExceptionForStatus(e.SourceStatus));
}
private Exception GetExceptionForStatus(TWStatus status)
{
switch (status.ConditionCode)
{
case ConditionCode.OperationError:
// This means the scanner has already shown the user an error message, so we don't need to show another.
// TODO: The spec says that if CAP_INDICATORS is false with NO_UI, we should still display the error to
// the user, but with my test scanners that seems unnecessary so for now I'm not showing the error
// regardless.
return new AlreadyHandledDriverException();
case ConditionCode.PaperJam:
return new DevicePaperJamException();
case ConditionCode.CheckDeviceOnline when _session.State <= 3:
return new DeviceOfflineException();
case ConditionCode.CheckDeviceOnline when _session.State >= 4:
return new DeviceCommunicationException();
default:
return new DeviceException($"TWAIN error: {status.ConditionCode}");
}
}
private void DataTransferred(object? sender, DataTransferredEventArgs e)
{
_logger.LogDebug("NAPS2.TW - DataTransferred");
try
{
if (_options.TwainOptions.TransferMode == TwainTransferMode.Memory && e.MemoryData == null)
{
_logger.LogDebug("NAPS2.TW - Expected memory transfer, but got native transfer?");
}
if (e.MemoryData != null)
{
_twainEvents.MemoryBufferTransferred(ToMemoryBuffer(e.MemoryData, e.MemoryInfo));
}
else
{
_twainEvents.NativeImageTransferred(new TwainNativeImage
{
Buffer = ByteString.FromStream(e.GetNativeImageStream())
});
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending TWAIN data transfer event");
}
}
private void TransferReady(object? sender, TransferReadyEventArgs e)
{
_logger.LogDebug("NAPS2.TW - TransferReady");
try
{
var pageStart = new TwainPageStart();
if (_options.TwainOptions.TransferMode == TwainTransferMode.Memory)
{
pageStart.ImageData = ToImageData(e.PendingImageInfo);
}
_twainEvents.PageStart(pageStart);
if (_cancelToken.IsCancellationRequested)
{
e.CancelAll = true;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending TWAIN transfer ready event");
}
}
private TwainMemoryBuffer ToMemoryBuffer(byte[] buffer, TWImageMemXfer memInfo)
{
return new TwainMemoryBuffer
{
Buffer = ByteString.CopyFrom(buffer),
Columns = (int) memInfo.Columns,
Rows = (int) memInfo.Rows,
XOffset = (int) memInfo.XOffset,
YOffset = (int) memInfo.YOffset,
BytesPerRow = (int) memInfo.BytesPerRow
};
}
private static TwainImageData ToImageData(TWImageInfo imageInfo)
{
var imageData = new TwainImageData
{
Width = imageInfo.ImageWidth,
Height = imageInfo.ImageLength,
BitsPerPixel = imageInfo.BitsPerPixel,
SamplesPerPixel = imageInfo.SamplesPerPixel,
PixelType = (int) imageInfo.PixelType,
XRes = imageInfo.XResolution,
YRes = imageInfo.YResolution
};
imageData.BitsPerSample.AddRange(imageInfo.BitsPerSample.Select(x => (int) x));
return imageData;
}
private void ConfigureSource(DataSource source)
{
// Transfer Mode
if (_options.TwainOptions.TransferMode == TwainTransferMode.Default)
{
if (source.Manufacturer.Contains("Kyocera", StringComparison.InvariantCultureIgnoreCase) &&
(source.ProductFamily.Contains("Ecosys", StringComparison.InvariantCultureIgnoreCase) ||
source.Name.Contains("Ecosys", StringComparison.InvariantCultureIgnoreCase)))
{
_logger.LogDebug("Detected Kyocera Ecosys scanner. Defaulting to Native transfer mode.");
_options.TwainOptions.TransferMode = TwainTransferMode.Native;
}
else
{
_logger.LogDebug("Defaulting to Memory transfer mode.");
_options.TwainOptions.TransferMode = TwainTransferMode.Memory;
}
}
if (_options.TwainOptions.TransferMode == TwainTransferMode.Memory)
{
_logger.LogDebug("Transfer mode: Memory");
source.Capabilities.ICapXferMech.SetValue(XferMech.Memory);
}
else
{
_logger.LogDebug("Transfer mode: Native");
}
if (_options.UseNativeUI)
{
return;
}
// Progress UI
if (!_options.TwainOptions.ShowProgress)
{
source.Capabilities.CapIndicators.SetValue(BoolType.False);
}
// Paper Source
switch (_options.PaperSource)
{
case PaperSource.Auto:
if (source.Capabilities.CapFeederEnabled.IsSupported)
{
source.Capabilities.CapFeederEnabled.SetValue(BoolType.True);
}
if (source.Capabilities.CapAutomaticSenseMedium.IsSupported)
{
source.Capabilities.CapAutomaticSenseMedium.SetValue(BoolType.True);
}
else
{
// Only set if CAP_AUTOMATICSENSEMEDIUM is unsupported (https://epson.com/Support/wa00954e?pg=6#:~:text=CAP_AUTOMATICSENSEMEDIUM,to%20CAP_FEEDERENABLED%20dynamically.)
// CAP_FEEDERLOADED is depending on CAP_FEEDERENABLED being set to TRUE (https://epson.com/Support/wa00954e?pg=6#:~:text=TWCC_BADCAP.-,CAP_FEEDERLOADED,TRUE.,-CAP_FEEDPAGE)
if (!source.Capabilities.CapFeederLoaded.IsSupported || source.Capabilities.CapFeederLoaded.GetCurrent() == BoolType.False)
{
source.Capabilities.CapFeederEnabled.SetValue(BoolType.False);
}
source.Capabilities.CapDuplexEnabled.SetValue(BoolType.False);
}
break;
case PaperSource.Flatbed:
source.Capabilities.CapFeederEnabled.SetValue(BoolType.False);
source.Capabilities.CapDuplexEnabled.SetValue(BoolType.False);
break;
case PaperSource.Feeder:
source.Capabilities.CapFeederEnabled.SetValue(BoolType.True);
source.Capabilities.CapDuplexEnabled.SetValue(BoolType.False);
break;
case PaperSource.Duplex:
source.Capabilities.CapFeederEnabled.SetValue(BoolType.True);
source.Capabilities.CapDuplexEnabled.SetValue(BoolType.True);
break;
}
// Bit Depth
switch (_options.BitDepth)
{
case BitDepth.Color:
source.Capabilities.ICapPixelType.SetValue(PixelType.RGB);
source.Capabilities.ICapBitDepth.SetValue(24);
break;
case BitDepth.Grayscale:
source.Capabilities.ICapPixelType.SetValue(PixelType.Gray);
source.Capabilities.ICapBitDepth.SetValue(8);
break;
case BitDepth.BlackAndWhite:
source.Capabilities.ICapPixelType.SetValue(PixelType.BlackWhite);
source.Capabilities.ICapBitDepth.SetValue(1);
break;
}
// Page Size, Horizontal Align
float pageWidth = _options.PageSize!.WidthInThousandthsOfAnInch / 1000.0f;
float pageHeight = _options.PageSize.HeightInThousandthsOfAnInch / 1000.0f;
var pageMaxWidthFixed = source.Capabilities.ICapPhysicalWidth.GetCurrent();
float pageMaxWidth = pageMaxWidthFixed.Whole + (pageMaxWidthFixed.Fraction / (float) UInt16.MaxValue);
float horizontalOffset = 0.0f;
if (_options.PageAlign == HorizontalAlign.Center)
horizontalOffset = (pageMaxWidth - pageWidth) / 2;
else if (_options.PageAlign == HorizontalAlign.Left)
horizontalOffset = (pageMaxWidth - pageWidth);
source.Capabilities.ICapUnits.SetValue(Unit.Inches);
source.DGImage.ImageLayout.Get(out TWImageLayout imageLayout);
imageLayout.Frame = new TWFrame
{
Left = horizontalOffset,
Right = horizontalOffset + pageWidth,
Top = 0,
Bottom = pageHeight
};
source.DGImage.ImageLayout.Set(imageLayout);
// Brightness, Contrast
// Conveniently, the range of values used in settings (-1000 to +1000) is the same range TWAIN supports
if (!_options.BrightnessContrastAfterScan)
{
source.Capabilities.ICapBrightness.SetValue(_options.Brightness);
source.Capabilities.ICapContrast.SetValue(_options.Contrast);
}
// Resolution
SetClosest(source.Capabilities.ICapXResolution, _options.Dpi);
SetClosest(source.Capabilities.ICapYResolution, _options.Dpi);
}
private void SetClosest(ICapWrapper<TWFix32> cap, int value)
{
if (!cap.CanGet)
{
cap.SetValue(value);
return;
}
var possibleValues = cap.GetValues().ToList();
if (possibleValues.Count == 0)
{
cap.SetValue(value);
return;
}
var closest = possibleValues.OrderBy(v => Math.Abs(v - value)).First();
cap.SetValue(closest);
}
}
#endif