-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathrpdeltwain.pas
2864 lines (2590 loc) · 90.2 KB
/
rpdeltwain.pas
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{DELPHI IMPLEMENTATION OF TWAIN INTERFACE}
{december 2003®, initially created by Gustavo Daud}
{This is my newest contribution for Delphi comunity, a powerfull}
{implementation of latest Twain features. As you know, twain is }
{the most common library to acquire images from most acquisition}
{devices such as Scanners and Web-Cameras.}
{Twain library is a bit different from other libraries, because}
{most of the hard work can be done by a a single method. Also it}
{automatically changes in the application message loop, which is}
{not a simple task, at least in delphi VCL.}
{It is not 100% sure to to Twain not to be installed in Windows,}
{as it ships with Windows and later and with most of the }
{acquisition device drivers (automatically with their installation)}
{This library dynamically calls the library, avoiding the application}
{hand when it is not present.}
{Also, as in most of my other components, I included a trigger}
{to allow the component to work without the heavy delphi VCL}
{for small final executables. To enable, edit DelphiTwain.inc}
{20/01/2004 - Some updates and bug fixes by Nemeth Peter}
{$INCLUDE rpdeltwain.inc}
unit rpdeltwain;
interface
{Used units}
uses
rptwain, Windows {$IFNDEF DONTUSEVCL}, Classes, SysUtils, Graphics{$ENDIF},
rpdeltwainutils;
const
{Name of the Twain library for 32 bits enviroment}
TWAINLIBRARY = 'TWAIN_32.DLL';
VIRTUALWIN_CLASSNAME = 'DELPHITWAIN_VIRTUALWINDOW';
const
{Error codes}
ERROR_BASE = 300;
ERROR_INT16: TW_INT16 = HIGH(TW_INT16);
type
{From twain}
TW_STR255 = rpTwain.TW_STR255;
{Forward declaration}
TDelphiTwain = class;
{Component kinds}
{$IFDEF DONTUSEVCL} TTwainComponent = TObject;
{$ELSE} TTwainComponent = TComponent; {$ENDIF}
{File formats}
TTwainFormat = (tfTIFF, tfPict, tfBMP, tfXBM, tfJPEG, tfFPX,
tfTIFFMulti, tfPNG, tfSPIFF, tfEXIF, tfUnknown);
{Twain units}
TTwainUnit = (tuInches, tuCentimeters, tuPicas, tuPoints, tuTwips,
tuPixels, tuUnknown);
TTwainUnitSet = set of TTwainUnit;
{Twain pixel flavor}
TTwainPixelFlavor = (tpfChocolate, tpfVanilla, tpfUnknown);
TTwainPixelFlavorSet = set of TTwainPixelFlavor;
{Twain pixel type}
TTwainPixelType = (tbdBw, tbdGray, tbdRgb, tbdPalette, tbdCmy, tbdCmyk,
tbdYuv, tbdYuvk, tbdCieXYZ, tbdUnknown);
TTwainPixelTypeSet = set of TTwainPixelType;
{Twain bit depth}
TTwainBitDepth = array of TW_UINT16;
{Twain resolutions}
TTwainResolution = array of Extended;
{Events}
TOnTwainError = procedure(Sender: TObject; const Index: Integer; ErrorCode,
Additional: Integer) of object;
TOnTwainAcquire = procedure(Sender: TObject; const Index: Integer; Image:
{$IFNDEF DONTUSEVCL}TBitmap{$ELSE}HBitmap{$ENDIF};
var Cancel: Boolean) of object;
TOnAcquireProgress = procedure(Sender: TObject; const Index: Integer;
const Image: HBitmap; const Current, Total: Integer) of object;
TOnSourceNotify = procedure(Sender: TObject; const Index: Integer) of object;
TOnSourceFileTransfer = procedure(Sender: TObject; const Index: Integer;
Filename: TW_STR255; Format: TTwainFormat; var Cancel: Boolean) of object;
{Avaliable twain languages}
TTwainLanguage = ({-1}tlUserLocale, tlDanish, tlDutch, tlInternationalEnglish,
tlFrenchCanadian, tlFinnish, tlFrench, tlGerman, tlIcelandic, tlItalian,
tlNorwegian, tlPortuguese, tlSpanish, tlSwedish, tlUsEnglish,
tlAfrikaans, tlAlbania, tlArabic, tlArabicAlgeria, tlArabicBahrain, {18}
tlArabicEgypt, tlArabicIraq, tlArabJordan, tlArabicKuwait,
tlArabicLebanon, tlArabicLibya, tlArabicMorocco, tlArabicOman,
tlArabicQatar, tlArabicSaudiarabia, tlArabicSyria, tlArabicTunisia,
tlArabicUae, tlArabicYemen, tlBasque, tlByelorussian, tlBulgarian, {35}
tlCatalan, tlChinese, tlChineseHongkong, tlChinesePeoplesRepublic,
tlChineseSingapore, tlChineseSimplified, tlChineseTwain, {42}
tlChineseTraditional, tlCroatia, tlCzech, tlDutchBelgian, {46}
tlEnglishAustralian, tlEnglishCanadian, tlEnglishIreland,
tlEnglishNewZealand, tlEnglishSouthAfrica, tlEnglishUk, {52}
tlEstonian, tlFaeroese, tlFarsi, tlFrenchBelgian, tlFrenchLuxembourg, {57}
tlFrenchSwiss, tlGermanAustrian, tlGermanLuxembourg, tlGermanLiechtenstein,
tlGermanSwiss, tlGreek, tlHebrew, tlHungarian, tlIndonesian, {66}
tlItalianSwiss, tlJapanese, tlKorean, tlKoreanJohab, tlLatvian, {71}
tlLithuanian, tlNorewgianBokmal, tlNorwegianNynorsk, tlPolish, {75}
tlPortugueseBrazil, tlRomanian, tlRussian, tlSerbianLatin,
tlSlovak, tlSlovenian, tlSpanishMexican, tlSpanishModern, tlThai,
tlTurkish, tlUkranian, tlAssamese, tlBengali, tlBihari, tlBodo,
tlDogri, tlGujarati {92}, tlHarayanvi, tlHindi, tlKannada, tlKashmiri,
tlMalayalam, tlMarathi, tlMarwari, tlMeghalayan, tlMizo, tlNaga {102},
tlOrissi, tlPunjabi, tlPushtu, tlSerbianCyrillic, tlSikkimi,
tlSwidishFinland, tlTamil, tlTelugu, tlTripuri, tlUrdu, tlVietnamese);
{Twain supported groups}
TTwainGroups = set of (tgControl, tgImage, tgAudio);
{Transfer mode for twain}
TTwainTransferMode = (ttmFile, ttmNative, ttmMemory);
{rect for LAYOUT; npeter 2004.01.12.}
TTwainRect =
record
Left: double;
Top: double;
Right: double;
Bottom: double;
end;
{Object to handle TW_IDENTITY}
TTwainIdentity = class{$IFNDEF DONTUSEVCL}(TPersistent){$ENDIF}
private
{Structure which should be filled}
Structure: TW_IDENTITY;
{Owner}
fOwner: {$IFNDEF DONTUSEVCL}TComponent{$ELSE}TObject{$ENDIF};
{Returns/sets application language property}
function GetLanguage(): TTwainLanguage;
procedure SetLanguage(const Value: TTwainLanguage);
{Returns/sets text values}
function GetString(const Index: integer): String;
procedure SetString(const Index: Integer; const Value: String);
{Returns/sets avaliable groups}
function GetGroups(): TTwainGroups;
procedure SetGroups(const Value: TTwainGroups);
protected
{$IFNDEF DONTUSEVCL}function GetOwner(): TPersistent; override;{$ENDIF}
public
{Object being created}
{$IFNDEF DONTUSEVCL} constructor Create(AOwner: TComponent);
{$ELSE} constructor Create(AOwner: TObject); {$ENDIF}
{Copy properties from another TTwainIdentity}
{$IFDEF DONTUSEVCL} procedure Assign(Source: TObject); {$ELSE}
procedure Assign(Source: TPersistent); override; {$ENDIF}
published
{Application major version}
property MajorVersion: TW_UINT16 read Structure.Version.MajorNum
write Structure.Version.MajorNum;
{Application minor version}
property MinorVersion: TW_UINT16 read Structure.Version.MinorNum
write Structure.Version.MinorNum;
{Language}
property Language: TTwainLanguage read GetLanguage write SetLanguage;
{Country code}
property CountryCode: word read Structure.Version.Country write
Structure.Version.Country;
{Supported groups}
property Groups: TTwainGroups read GetGroups write SetGroups;
{Text values}
property VersionInfo: String index 0 read GetString write
SetString;
property Manufacturer: String index 1 read GetString write
SetString;
property ProductFamily: String index 2 read GetString write
SetString;
property ProductName: String index 3 read GetString write
SetString;
end;
{Return set for capability retrieving/setting}
TCapabilityRet = (crSuccess, crUnsupported, crBadOperation, crDependencyError,
crLowMemory, crInvalidState, crInvalidContainer);
{Kinds of capability retrieving}
TRetrieveCap = (rcGet, rcGetCurrent, rcGetDefault, rcReset);
{Capability list type}
TGetCapabilityList = array of string;
TSetCapabilityList = array of pointer;
{Source object}
TTwainSource = class(TTwainIdentity)
private
{Holds the item index}
fIndex: Integer;
{Transfer mode for the images}
fTransferMode: TTwainTransferMode;
{Stores if user interface should be shown}
fShowUI: Boolean;
{Stores if the source window is modal}
fModal: Boolean;
{Stores if the source is enabled}
fEnabled: Boolean;
{Stores if the source is loaded}
fLoaded: Boolean;
{Stores the owner}
fOwner: TDelphiTwain;
{Used with property SourceManagerLoaded to test if the source manager}
{is loaded or not.}
function GetSourceManagerLoaded(): Boolean;
{Returns a pointer to the application}
function GetAppInfo(): pTW_IDENTITY;
{Sets if the source is loaded}
procedure SetLoaded(const Value: Boolean);
{Sets if the source is enabled}
procedure SetEnabled(const Value: Boolean);
{Returns a pointer to the source pTW_IDENTITY}
function GetStructure: pTW_IDENTITY;
{Returns a resolution}
function GetResolution(Capability: TW_UINT16; var Return: Extended;
var Values: TTwainResolution; Mode: TRetrieveCap): TCapabilityRet;
protected
{Reads a native image}
procedure ReadNative(Handle: TW_UINT32; var Cancel: Boolean);
{Reads the file image}
procedure ReadFile(Name: TW_STR255; Format: TW_UINT16; var Cancel: Boolean);
{Call event for memory image}
procedure ReadMemory(Image: HBitmap; var Cancel: Boolean);
protected
{Prepare image memory transference}
function PrepareMemXfer(var BitmapHandle: HBitmap;
var PixelType: TW_INT16): TW_UINT16;
{Transfer image memory}
function TransferImageMemory(var ImageHandle: HBitmap;
PixelType: TW_INT16): TW_UINT16;
{Returns a pointer to the TW_IDENTITY for the application}
property AppInfo: pTW_IDENTITY read GetAppInfo;
{Method to transfer the images}
procedure TransferImages();
{Message received in the event loop}
function ProcessMessage(const Msg: TMsg): Boolean;
{Returns if the source manager is loaded}
property SourceManagerLoaded: Boolean read GetSourceManagerLoaded;
{Source configuration methods}
{************************}
protected
{Gets an item and returns it in a string}
procedure GetItem(var Return: String; ItemType: TW_UINT16; Data: Pointer);
{Converts from a result to a TCapabilityRec}
function ResultToCapabilityRec(const Value: TW_UINT16): TCapabilityRet;
{Sets a capability}
function SetCapabilityRec(const Capability, ConType: TW_UINT16;
Data: HGLOBAL): TCapabilityRet;
public
{Returns a capability strucutre}
function GetCapabilityRec(const Capability: TW_UINT16;
var Handle: HGLOBAL; Mode: TRetrieveCap;
var Container: TW_UINT16): TCapabilityRet;
{************************}
{Returns an one value capability}
function GetOneValue(Capability: TW_UINT16;
var ItemType: TW_UINT16; var Value: string;
Mode: TRetrieveCap{$IFDEF DEFAULTPARAM}=rcGet{$ENDIF};
MemHandle: HGLOBAL{$IFDEF DEFAULTPARAM}=0{$ENDIF}): TCapabilityRet;
{Returns an range capability}
function GetRangeValue(Capability: TW_UINT16; var ItemType: TW_UINT16;
var Min, Max, Step, Default, Current: String;
MemHandle: HGLOBAL{$IFDEF DEFAULTPARAM}=0{$ENDIF}): TCapabilityRet;
{Returns an enumeration capability}
function GetEnumerationValue(Capability: TW_UINT16;
var ItemType: TW_UINT16; var List: TGetCapabilityList; var Current,
Default: Integer; Mode: TRetrieveCap{$IFDEF DEFAULTPARAM}=rcGet{$ENDIF};
MemHandle: HGLOBAL{$IFDEF DEFAULTPARAM}=0{$ENDIF}): TCapabilityRet;
{Returns an array capability}
function GetArrayValue(Capability: TW_UINT16; var ItemType: TW_UINT16;
var List: TGetCapabilityList; MemHandle: HGLOBAL
{$IFDEF DEFAULTPARAM}=0{$ENDIF}): TCapabilityRet;
{************************}
{Sets an one value capability}
function SetOneValue(Capability: TW_UINT16; ItemType: TW_UINT16;
Value: Pointer): TCapabilityRet;
{Sets a range capability}
function SetRangeValue(Capability, ItemType: TW_UINT16; Min, Max, Step,
Current: TW_UINT32): TCapabilityRet;
{Sets an enumeration capability}
function SetEnumerationValue(Capability, ItemType: TW_UINT16;
CurrentIndex: TW_UINT32; List: TSetCapabilityList): TCapabilityRet;
{Sets an array capability}
function SetArrayValue(Capability, ItemType: TW_UINT16;
List: TSetCapabilityList): TCapabilityRet;
public
{Setup file transfer}
function SetupFileTransfer(Filename: String; Format: TTwainFormat): Boolean;
protected
{Used with property PendingXfers}
function GetPendingXfers(): TW_INT16;
public
{Set source transfer mode}
function ChangeTransferMode(NewMode: TTwainTransferMode): TCapabilityRet;
{Returns return status information}
function GetReturnStatus(): TW_UINT16;
{Capability setting}
{Set the number of images that the application wants to receive}
function SetCapXferCount(Value: SmallInt): TCapabilityRet;
{Returns the number of images that the source will return}
function GetCapXferCount(var Return: SmallInt;
Mode: TRetrieveCap{$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet;
{Retrieve the unit measure for all quantities}
function GetICapUnits(var Return: TTwainUnit;
var Supported: TTwainUnitSet; Mode: TRetrieveCap
{$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet;
{Set the unit measure}
function SetICapUnits(Value: TTwainUnit): TCapabilityRet;
{npeter 2004.01.12 begin}
function SetImagelayoutFrame(const fLeft,fTop,fRight,
fBottom: double): TCapabilityRet;
function SetIndicators(Value: boolean): TCapabilityRet;
{npeter 2004.01.12 end}
{Retrieve the pixel flavor values}
function GetIPixelFlavor(var Return: TTwainPixelFlavor;
var Supported: TTwainPixelFlavorSet; Mode: TRetrieveCap
{$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet;
{Set the pixel flavor values}
function SetIPixelFlavor(Value: TTwainPixelFlavor): TCapabilityRet;
{Returns bitdepth values}
function GetIBitDepth(var Return: Word;
var Supported: TTwainBitDepth; Mode: TRetrieveCap
{$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet;
{Set current bitdepth value}
function SetIBitDepth(Value: Word): TCapabilityRet;
{Returns pixel type values}
function GetIPixelType(var Return: TTwainPixelType;
var Supported: TTwainPixelTypeSet; Mode: TRetrieveCap
{$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet;
{Set the pixel type value}
function SetIPixelType(Value: TTwainPixelType): TCapabilityRet;
{Returns X and Y resolutions}
function GetIXResolution(var Return: Extended; var Values: TTwainResolution;
Mode: TRetrieveCap {$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet;
function GetIYResolution(var Return: Extended; var Values: TTwainResolution;
Mode: TRetrieveCap {$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet;
{Sets X and X resolutions}
function SetIXResolution(Value: Extended): TCapabilityRet;
function SetIYResolution(Value: Extended): TCapabilityRet;
{Returns physical width and height}
function GetIPhysicalWidth(var Return: Extended; Mode: TRetrieveCap
{$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet;
function GetIPhysicalHeight(var Return: Extended; Mode: TRetrieveCap
{$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet;
{Returns if user interface is controllable}
function GetUIControllable(var Return: Boolean): TCapabilityRet;
{Returns feeder is loaded or not}
function GetFeederLoaded(var Return: Boolean): TCapabilityRet;
{Returns/sets if feeder is enabled}
function GetFeederEnabled(var Return: Boolean): TCapabilityRet;
function SetFeederEnabled(Value: WordBool): TCapabilityRet;
{Returns/sets if auto feed is enabled}
function GetAutofeed(var Return: Boolean): TCapabilityRet;
function SetAutoFeed(Value: WordBool): TCapabilityRet;
{Returns number of pending transfer}
property PendingXfers: TW_INT16 read GetPendingXfers;
public
{Enables the source}
function EnableSource(ShowUI, Modal: Boolean): Boolean;
{Disables the source}
function DisableSource: Boolean;
{Loads the source}
function LoadSource(): Boolean;
{Unloads the source}
function UnloadSource(): Boolean;
{Returns a pointer to the source identity}
property SourceIdentity: pTW_IDENTITY read GetStructure;
{Returns/sets if the source is enabled}
property Enabled: Boolean read fEnabled write SetEnabled;
{Returns/sets if this source is loaded}
property Loaded: Boolean read fLoaded write SetLoaded;
{Object being created/destroyed}
constructor Create(AOwner: TDelphiTwain);
destructor Destroy; override;
{Returns owner}
property Owner: TDelphiTwain read fOwner;
{Source window is modal}
property Modal: Boolean read fModal write fModal;
{Sets if user interface should be shown}
property ShowUI: Boolean read fShowUI write fShowUI;
{Transfer mode for transfering images from the source to}
{the component and finally to the application}
property TransferMode: TTwainTransferMode read fTransferMode
write fTransferMode;
{Returns the item index}
property Index: Integer read fIndex;
{Convert properties from write/read to read only}
{(read description on TTwainIdentity source)}
property MajorVersion: TW_UINT16 read Structure.Version.MajorNum;
property MinorVersion: TW_UINT16 read Structure.Version.MinorNum;
property Language: TTwainLanguage read GetLanguage;
property CountryCode: word read Structure.Version.Country;
property Groups: TTwainGroups read GetGroups;
property VersionInfo: String index 0 read GetString;
property Manufacturer: String index 1 read GetString;
property ProductFamily: String index 2 read GetString;
property ProductName: String index 3 read GetString;
end;
{Component part}
TDelphiTwain = class(TTwainComponent)
private
{Should contain the number of Twain sources loaded}
fSourcesLoaded: Integer;
{Contains if the select source dialog is being displayed}
SelectDialogDisplayed: Boolean;
private
{Event pointer holders}
fOnSourceDisable: TOnSourceNotify;
fOnAcquireCancel: TOnSourceNotify;
fOnTwainAcquire: TOnTwainAcquire;
fOnSourceSetupFileXfer: TOnSourceNotify;
fOnSourceFileTransfer: TOnSourceFileTransfer;
fOnAcquireError: TOnTwainError;
fOnAcquireProgress: TOnAcquireProgress;
private
{Temp variable to allow SourceCount to be displayed in delphi}
{property editor}
fDummySourceCount: integer;
{Contains list of source devices}
DeviceList: TPointerList;
{Contains a pointer to the structure with the application}
{information}
AppInfo: pTW_IDENTITY;
{Holds the object to allow the user to set the application information}
fInfo: TTwainIdentity;
{Holds the handle for the virtual window which will receive}
{twain message notifications}
VirtualWindow: THandle;
{Will hold Twain library handle}
fHandle: HInst;
{Holds if the component has enumerated the devices}
fHasEnumerated: Boolean;
{Holds twain dll procedure handle}
fTwainProc: TDSMEntryProc;
{Holds the transfer mode to be used}
fTransferMode: TTwainTransferMode;
{Contains if the library is loaded}
fLibraryLoaded: Boolean;
{Contains if the source manager was loaded}
fSourceManagerLoaded: Boolean;
{Procedure to load and unload twain library and update property}
procedure SetLibraryLoaded(const Value: Boolean);
{Procedure to load or unloaded the twain source manager}
procedure SetSourceManagerLoaded(const Value: Boolean);
{Updates the application information object}
procedure SetInfo(const Value: TTwainIdentity);
{Returns the number of sources}
function GetSourceCount(): Integer;
{Returns a source from the list}
function GetSource(Index: Integer): TTwainSource;
{Finds a matching source index}
function FindSource(Value: pTW_IDENTITY): Integer;
protected
{Returns the default source}
function GetDefaultSource: Integer;
{Creates the virtual window}
procedure CreateVirtualWindow();
{Clears the list of sources}
procedure ClearDeviceList();
public
{Allows Twain to display a dialog to let the user choose any source}
{and returns the source index in the list}
function SelectSource(): Integer;
{Returns the number of loaded sources}
property SourcesLoaded: Integer read fSourcesLoaded;
{Enumerate the avaliable devices after Source Manager is loaded}
function EnumerateDevices(): Boolean;
{Object being created}
{$IFNDEF DONTUSEVCL}
constructor Create(AOwner: TComponent);override;
{$ELSE}
constructor Create;
{$ENDIF}
{Object being destroyed}
destructor Destroy(); override;
{Loads twain library and returns if it loaded sucessfully}
function LoadLibrary(): Boolean;
{Unloads twain and returns if it unloaded sucessfully}
function UnloadLibrary(): Boolean;
{Loads twain source manager}
function LoadSourceManager(): Boolean;
{Unloads the source manager}
function UnloadSourceManager(forced: boolean): Boolean;
{Returns the application TW_IDENTITY}
property AppIdentity: pTW_IDENTITY read AppInfo;
{Returns Twain library handle}
property Handle: HInst read fHandle;
{Returns a pointer to Twain only procedure}
property TwainProc: TDSMEntryProc read fTwainProc;
{Holds if the component has enumerated the devices}
property HasEnumerated: Boolean read fHasEnumerated;
{Returns a source}
property Source[Index: Integer]: TTwainSource read GetSource;
published
{Events}
{Source being disabled}
property OnSourceDisable: TOnSourceNotify read fOnSourceDisable
write fOnSourceDisable;
{Acquire cancelled}
property OnAcquireCancel: TOnSourceNotify read fOnAcquireCancel
write fOnAcquireCancel;
{Image acquired}
property OnTwainAcquire: TOnTwainAcquire read fOnTwainAcquire
write fOnTwainAcquire;
{User should set information to prepare for the file transfer}
property OnSourceSetupFileXfer: TOnSourceNotify read fOnSourceSetupFileXfer
write fOnSourceSetupFileXfer;
{File transfered}
property OnSourceFileTransfer: TOnSourceFileTransfer read
fOnSourceFileTransfer write fOnSourceFileTransfer;
{Acquire error}
property OnAcquireError: TOnTwainError read fOnAcquireError
write fOnAcquireError;
{Acquire progress, for memory transfers}
property OnAcquireProgress: TOnAcquireProgress read fOnAcquireProgress
write fOnAcquireProgress;
published
{Default transfer mode to be used with sources}
property TransferMode: TTwainTransferMode read fTransferMode
write fTransferMode;
{Returns the number of sources, after Library and Source Manager}
{has being loaded}
property SourceCount: Integer read GetSourceCount write fDummySourceCount;
{User should fill the application information}
property Info: TTwainIdentity read fInfo write SetInfo;
{Loads or unload Twain library}
property LibraryLoaded: Boolean read fLibraryLoaded write SetLibraryLoaded;
{Loads or unloads the source manager}
property SourceManagerLoaded: Boolean read fSourceManagerLoaded write
SetSourceManagerLoaded;
end;
{Puts a string inside a TW_STR255}
function StrToStr255(Value: String): TW_STR255;
{This method returns if Twain is installed in the current machine}
function IsTwainInstalled(): Boolean;
{Called by Delphi to register the component}
procedure Register();
{Returns the size of a twain type}
function TWTypeSize(TypeName: TW_UINT16): Integer;
implementation
{Units used bellow}
uses
Messages;
{Called by Delphi to register the component}
procedure Register();
begin
{$IFNDEF DONTUSEVCL}
RegisterComponents('NP', [TDelphiTwain]);
{$ENDIF}
end;
{Returns the size of a twain type}
function TWTypeSize(TypeName: TW_UINT16): Integer;
begin
{Test the type to return the size}
case TypeName of
TWTY_INT8 : Result := sizeof(TW_INT8);
TWTY_UINT8 : Result := sizeof(TW_UINT8);
TWTY_INT16 : Result := sizeof(TW_INT16);
TWTY_UINT16: Result := sizeof(TW_UINT16);
TWTY_INT32 : Result := sizeof(TW_INT32);
TWTY_UINT32: Result := sizeof(TW_UINT32);
TWTY_FIX32 : Result := sizeof(TW_FIX32);
TWTY_FRAME : Result := sizeof(TW_FRAME);
TWTY_STR32 : Result := sizeof(TW_STR32);
TWTY_STR64 : Result := sizeof(TW_STR64);
TWTY_STR128: Result := sizeof(TW_STR128);
TWTY_STR255: Result := sizeof(TW_STR255);
//npeter: the following types were not implemented
//especially the bool caused problems
TWTY_BOOL: Result := sizeof(TW_BOOL);
TWTY_UNI512: Result := sizeof(TW_UNI512);
TWTY_STR1024: Result := sizeof(TW_STR1024);
else Result := 0;
end {case}
end;
{Puts a string inside a TW_STR255}
function StrToStr255(Value: String): TW_STR255;
begin
{Clean result}
Fillchar(Result, sizeof(TW_STR255), #0);
{If value fits inside the TW_STR255, copy memory}
if Length(Value) <= sizeof(TW_STR255) then
CopyMemory(@Result[0], @Value[1], Length(Value))
else CopyMemory(@Result[0], @Value[1], sizeof(TW_STR255));
end;
{Returns full Twain directory (usually in Windows directory)}
function GetTwainDirectory(): String;
var
i: TDirectoryKind;
Dir: String;
begin
{Searches in all the directories}
FOR i := LOW(TDirectoryKind) TO HIGH(TDirectoryKind) DO
begin
{Directory to search}
Dir := GetCustomDirectory(i);
{Tests if the file exists in this directory}
if FileExists(Dir + TWAINLIBRARY) then
begin
{In case it exists, returns this directory and exit}
{the for loop}
Result := Dir;
Break;
end {if FileExists}
end {FOR i}
end;
{This method returns if Twain is installed in the current machine}
function IsTwainInstalled(): Boolean;
begin
{If GetTwainDirectory function returns an empty string, it means}
{that Twain was not found}
Result := (GetTwainDirectory() <> '');
end;
{ TTwainIdentity object implementation }
{Object being created}
{$IFNDEF DONTUSEVCL} constructor TTwainIdentity.Create(AOwner: TComponent);
{$ELSE} constructor TTwainIdentity.Create(AOwner: TObject); {$ENDIF}
begin
{Allows ancestor to work}
inherited Create;
{Set initial properties}
FillChar(Structure, sizeof(Structure), #0);
Language := tlUserLocale;
CountryCode := 1;
MajorVersion := 1;
VersionInfo := 'Application name';
Structure.ProtocolMajor := TWON_PROTOCOLMAJOR;
Structure.ProtocolMinor := TWON_PROTOCOLMINOR;
Groups := [tgImage, tgControl];
Manufacturer := 'Application manufacturer';
ProductFamily := 'App product family';
ProductName := 'App product name';
fOwner := AOwner; {Copy owner pointer}
end;
{$IFNDEF DONTUSEVCL}
function TTwainIdentity.GetOwner(): TPersistent;
begin
Result := fOwner;
end;
{$ENDIF}
{Sets a text value}
procedure TTwainIdentity.SetString(const Index: Integer;
const Value: String);
var
PropStr: PChar;
begin
{Select and copy pointer}
case Index of
0: PropStr := @Structure.Version.Info[0];
1: PropStr := @Structure.Manufacturer[0];
2: PropStr := @Structure.ProductFamily[0];
else PropStr := @Structure.ProductName[0];
end {case};
{Set value}
Fillchar(PropStr^, sizeof(TW_STR32), #0);
if Length(Value) > sizeof(TW_STR32) then
CopyMemory(PropStr, @Value[1], sizeof(TW_STR32))
else
CopyMemory(PropStr, @Value[1], Length(Value));
end;
{Returns a text value}
function TTwainIdentity.GetString(const Index: Integer): String;
begin
{Test for the required property}
case Index of
0: Result := Structure.Version.Info;
1: Result := Structure.Manufacturer;
2: Result := Structure.ProductFamily;
else Result := Structure.ProductName;
end {case}
end;
{Returns application language property}
function TTwainIdentity.GetLanguage(): TTwainLanguage;
begin
Result := TTwainLanguage(Structure.Version.Language + 1);
end;
{Sets application language property}
procedure TTwainIdentity.SetLanguage(const Value: TTwainLanguage);
begin
{$R-}
Structure.Version.Language := Word(Value) - 1;
{$R+}
end;
{Copy properties from another TTwainIdentity}
{$IFDEF DONTUSEVCL} procedure TTwainIdentity.Assign(Source: TObject);
{$ELSE} procedure TTwainIdentity.Assign(Source: TPersistent); {$ENDIF}
begin
{The source should also be a TTwainIdentity}
if Source is TTwainIdentity then
{Copy properties}
Structure := TTwainIdentity(Source).Structure
else
{$IFNDEF DONTUSEVCL}inherited; {$ENDIF}
end;
{Returns avaliable groups}
function TTwainIdentity.GetGroups(): TTwainGroups;
begin
{Convert from Structure.SupportedGroups to TTwainGroups}
Include(Result, tgControl);
if DG_IMAGE AND Structure.SupportedGroups <> 0 then
Include(Result, tgImage);
if DG_AUDIO AND Structure.SupportedGroups <> 0 then
Include(Result, tgAudio);
end;
{Sets avaliable groups}
procedure TTwainIdentity.SetGroups(const Value: TTwainGroups);
begin
{Convert from TTwainGroups to Structure.SupportedGroups}
Structure.SupportedGroups := DG_CONTROL;
if tgImage in Value then
Structure.SupportedGroups := Structure.SupportedGroups or DG_IMAGE;
if tgAudio in Value then
Structure.SupportedGroups := Structure.SupportedGroups or DG_AUDIO;
end;
{ TDelphiTwain component implementation }
{Loads twain library and returns if it loaded sucessfully}
function TDelphiTwain.LoadLibrary(): Boolean;
var
TwainDirectory: String;
begin
{The library must not be already loaded}
if (not LibraryLoaded) then
begin
Result := FALSE; {Initially returns FALSE}
{Searches for Twain directory}
TwainDirectory := GetTwainDirectory();
{Continue only if twain is installed in an known directory}
if TwainDirectory <> '' then
begin
fHandle := Windows.LoadLibrary(PChar(TwainDirectory + TWAINLIBRARY));
{If the library was sucessfully loaded}
if (fHandle <> INVALID_HANDLE_VALUE) then
begin
{Obtains method handle}
@fTwainProc := GetProcAddress(fHandle, MAKEINTRESOURCE(1));
{Returns TRUE/FALSE if the method was obtained}
Result := (@fTwainProc <> nil);
{If the method was not obtained, also free the library}
if not Result then
begin
{Free the handle and clears the variable}
Windows.FreeLibrary(fHandle);
fHandle := 0;
end {if not Result}
end
else
{If it was not loaded, clears handle value}
fHandle := 0;
end {if TwainDirectory <> ''};
end
else
{If it was already loaded, returns true, since that is}
{what was supposed to happen}
Result := TRUE;
{In case the method was sucessful, updates property}
if Result then fLibraryLoaded := TRUE;
end;
{Unloads twain and returns if it unloaded sucessfully}
function TDelphiTwain.UnloadLibrary(): Boolean;
begin
{The library must not be already unloaded}
if (LibraryLoaded) then
begin
{Unloads the source manager}
SourceManagerLoaded := FALSE;
{Just call windows method to unload}
Result := Windows.FreeLibrary(Handle);
{If it was sucessfull, also clears handle value}
if Result then fHandle := 0;
{Updates property}
fLibraryLoaded := not Result;
end
else
{If it was already unloaded, returns true, since that is}
{what was supposed to happen}
Result := TRUE;
{In case the method was sucessful, updates property}
if Result then fLibraryLoaded := FALSE;
end;
{Enumerate the avaliable devices after Source Manager is loaded}
function TDelphiTwain.EnumerateDevices(): Boolean;
var
NewSource: TTwainSource;
CallRes : TW_UINT16;
begin
{Booth library and source manager must be loaded}
if (LibraryLoaded and SourceManagerLoaded) then
begin
{Clears the preview list of sources}
ClearDeviceList();
{Allocate new identity and tries to enumerate}
NewSource := TTwainSource.Create(Self);
CallRes := TwainProc(AppInfo, nil, DG_CONTROL, DAT_IDENTITY,
MSG_GETFIRST, @NewSource.Structure);
if CallRes = TWRC_SUCCESS then
repeat
{Add this item to the list}
DeviceList.Add(NewSource);
{Allocate memory for the next}
NewSource := TTwainSource.Create(Self);
NewSource.TransferMode := Self.TransferMode;
NewSource.fIndex := DeviceList.Count;
{Try to get the next item}
until TwainProc(AppInfo, nil, DG_CONTROL, DAT_IDENTITY,
MSG_GETNEXT, @NewSource.Structure) <> TWRC_SUCCESS;
{Set that the component has enumerated the devices}
{if everything went correctly}
Result := TRUE;
fHasEnumerated := Result;
{Dispose un-needed source object}
NewSource.Free;
end
else Result := FALSE; {If library and source manager aren't loaded}
end;
{Procedure to load and unload twain library and update property}
procedure TDelphiTwain.SetLibraryLoaded(const Value: Boolean);
begin
{The value must be changing to activate}
if (Value <> fLibraryLoaded) then
begin
{Depending on the parameter load/unload the library and updates}
{property whenever it loaded or unloaded sucessfully}
if Value then LoadLibrary()
else {if not Value then} UnloadLibrary();
end {if (Value <> fLibraryLoaded)}
end;
{Loads twain source manager}
function TDelphiTwain.LoadSourceManager(): Boolean;
begin
{The library must be loaded}
if LibraryLoaded and not SourceManagerLoaded then
{Loads source manager}
Result := (fTwainProc(AppInfo, nil, DG_CONTROL, DAT_PARENT,
MSG_OPENDSM, @VirtualWindow) = TWRC_SUCCESS)
else
{The library is not loaded, thus the source manager could}
{not be loaded}
Result := FALSE or SourceManagerLoaded;
{In case the method was sucessful, updates property}
if Result then fSourceManagerLoaded := TRUE;
end;
{UnLoads twain source manager}
function TDelphiTwain.UnloadSourceManager(forced: boolean): Boolean;
begin
{The library must be loaded}
if LibraryLoaded and SourceManagerLoaded then
begin
{Clears the list of sources}
ClearDeviceList();
{Unload source manager}
if not forced then
Result := (TwainProc(AppInfo, nil, DG_CONTROL, DAT_PARENT, MSG_CLOSEDSM, @VirtualWindow) = TWRC_SUCCESS)
else result:=true;
end
else
{The library is not loaded, meaning that the Source Manager isn't either}
Result := TRUE;
{In case the method was sucessful, updates property}
if Result then fSourceManagerLoaded := FALSE;
end;
{Procedure to load or unloaded the twain source manager}
procedure TDelphiTwain.SetSourceManagerLoaded(const Value: Boolean);
begin
{The library must be loaded to have access to the method}
if LibraryLoaded and (Value <> fSourceManagerLoaded) then
begin
{Load/unload the source manager}
if Value then LoadSourceManager()
else {if not Value then} UnloadSourceManager(false);
end {if LibraryLoaded}
end;
{Clears the list of sources}
procedure TDelphiTwain.ClearDeviceList();
var
i: Integer;
begin
{Deallocate pTW_IDENTITY}
FOR i := 0 TO DeviceList.Count - 1 DO
TTwainSource(DeviceList.Item[i]).Free;
{Clears the list}
DeviceList.Clear;
{Set trigger to tell that it has not enumerated again yet}
fHasEnumerated := FALSE;
end;
{Finds a matching source index}
function TDelphiTwain.FindSource(Value: pTW_IDENTITY): Integer;
var
i : Integer;
begin
Result := -1; {Default result}
{Search for this source in the list}
for i := 0 TO SourceCount - 1 DO
if CompareMem(@Source[i].Structure, pChar(Value), SizeOf(TW_IDENTITY)) then
begin
{Return index and exit}
Result := i;
break;
end; {if CompareMem, for i}
end;
{Allows Twain to display a dialog to let the user choose any source}
{and returns the source index in the list}
function TDelphiTwain.SelectSource: Integer;
var
Identity: TW_IDENTITY;
begin
Result := -1; {Default result}
{Booth library and source manager must be loaded}
if (LibraryLoaded and SourceManagerLoaded and not SelectDialogDisplayed) then
begin
{Don't allow this dialog to be displayed twice}
SelectDialogDisplayed := TRUE;
{Call twain to display the dialog}
if TwainProc(AppInfo, nil, DG_CONTROL, DAT_IDENTITY, MSG_USERSELECT,
@Identity) = TWRC_SUCCESS then
Result := FindSource(@Identity);
{Ended using}
SelectDialogDisplayed := FALSE
end {(LibraryLoaded and SourceManagerLoaded)}
end;
{Returns the number of sources}
function TDelphiTwain.GetSourceCount(): Integer;
begin
{Library and source manager must be loaded}
if (LibraryLoaded and SourceManagerLoaded) then
begin
{Enumerate devices, if needed}
if not HasEnumerated then EnumerateDevices();
{Returns}
Result := DeviceList.Count;
end
{In case library and source manager aren't loaded, returns 0}
else Result := 0
end;
{Returns the default source}
function TDelphiTwain.GetDefaultSource: Integer;
var
Identity: TW_IDENTITY;
begin
{Call twain to display the dialog}