forked from chrisrolliston/CCR.Clipboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCCR.Clipboard.Win.pas
2453 lines (2237 loc) · 80.6 KB
/
CCR.Clipboard.Win.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
{**************************************************************************************}
{ }
{ CCR.Clipboard - Windows backend }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 2.0 }
{ (the "License"); you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at https://www.mozilla.org/MPL/2.0 }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT }
{ WARRANTY OF ANY KIND, either express or implied. See the License for the specific }
{ language governing rights and limitations under the License. }
{ }
{ The Initial Developer of the Original Code is Chris Rolliston. Portions created by }
{ Chris Rolliston are Copyright (C) 2012-15 Chris Rolliston. All Rights Reserved. }
{ }
{**************************************************************************************}
unit CCR.Clipboard.Win;
interface
{$IFDEF MSWINDOWS}
uses
WinApi.Windows, WinApi.ShlObj, WinApi.ActiveX, System.Win.ComObj, System.Types,
System.SysUtils, System.Classes, System.Generics.Collections, System.Generics.Defaults,
CCR.Clipboard.Consts, CCR.Clipboard;
type
TClipboardFormatHelper = record helper for TClipboardFormat
strict private
function GetHandle: TClipFormat; inline;
public
property Handle: TClipFormat read GetHandle;
class function Wrap(const Value: TClipFormat): TClipboardFormat; static; inline;
end;
{$IF CompilerVersion > 28}
IStream = interface(IUnknown) //redefined for compatibility
['{0000000C-0000-0000-C000-000000000046}']
function Read(pv: Pointer; cb: LongInt; pcbRead: PLongInt): HRESULT; stdcall;
function Write(pv: Pointer; cb: LongInt; pcbWritten: PLongInt): HRESULT; stdcall;
function Seek(dlibMove: Int64; dwOrigin: DWORD; out libNewPosition: Int64): HRESULT; stdcall;
function SetSize(libNewSize: Int64): HRESULT; stdcall;
function CopyTo(stm: IStream; cb: Int64; out cbRead: Int64; out cbWritten: Int64): HRESULT; stdcall;
function Commit(grfCommitFlags: DWORD): HRESULT; stdcall;
function Revert: HRESULT; stdcall;
function LockRegion(libOffset: Int64; cb: Int64; dwLockType: DWORD): HRESULT; stdcall;
function UnlockRegion(libOffset: Int64; cb: Int64; dwLockType: DWORD): HRESULT; stdcall;
function Stat(out statstg: TStatStg; grfStatFlag: DWORD): HRESULT; stdcall;
function Clone(out stm: IStream): HRESULT; stdcall;
end;
{$IFEND}
{ TStream adaptor for IStream; provided since stock one is in a VCL unit }
TOleStreamWrapper = class(TStream)
private
FStream: IStream;
public
constructor Create(const AStream: IStream);
function Read(var Buffer; Count: LongInt): LongInt; override;
function Write(const Buffer; Count: LongInt): LongInt; override;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
end;
{ The following interface can be queried for from the IClipboardDropInfo instances
returned by TClipboard.RegisterDropTarget }
IWinClipboardDropInfo = interface(IClipboardDropInfo)
['{DE6743E9-4038-454D-B949-4B5DC4309873}']
procedure SetEffect(Effect: DWORD);
end;
{ Friendlier interface for building up a IDataObject; is implemented by both a class
that acts on an arbitrary IDataObject + our own IDataObject implementation }
TGetDataObjectDataEvent = reference to procedure (
AllocResourceInMedium: Boolean; var Medium: TStgMedium);
IDataObjectBuilder = interface
['{036C4A89-146B-4A9D-9459-A52C8E100566}']
procedure AddFormat(const Format: TClipboardFormat; Index: LongInt;
var StgMediumToOwn: TStgMedium); overload;
procedure AddFormat(const Format: TClipboardFormat; Index: LongInt;
PreferredTymed: LongInt; const OnGetData: TGetDataObjectDataEvent;
FallbackTymed: LongInt = TYMED_NULL; const OnGetDataFallback: TGetDataObjectDataEvent = nil); overload;
procedure AddFormat(const Format: TClipboardFormat; Index: LongInt;
const OnGetData: TFunc<TBytes>); overload;
procedure AddFormat(const Format: TClipboardFormat; Index: LongInt;
const OnGetData: TProc<TStream>); overload;
function GetEmpty: Boolean;
property Empty: Boolean read GetEmpty;
end;
TDataObjectBuilderBase = class(TInterfacedObject)
protected
procedure AddFormat(const Format: TClipboardFormat; Index: LongInt;
PreferredTymed: LongInt; const OnGetData: TGetDataObjectDataEvent;
FallbackTymed: LongInt; const OnGetDataFallback: TGetDataObjectDataEvent); overload; virtual; abstract;
procedure AddFormat(const Format: TClipboardFormat; Index: LongInt;
const OnGetData: TFunc<TBytes>); overload;
procedure AddFormat(const Format: TClipboardFormat; Index: LongInt;
const OnGetData: TProc<TStream>); overload;
end;
TDataObjectBuilder = class(TDataObjectBuilderBase, IDataObjectBuilder)
strict private
FDataObject: IDataObject;
protected
procedure AddFormat(const Format: TClipboardFormat; Index: LongInt;
var StgMediumToOwn: TStgMedium); overload;
procedure AddFormat(const Format: TClipboardFormat; Index: LongInt;
PreferredTymed: LongInt; const OnGetData: TGetDataObjectDataEvent;
FallbackTymed: LongInt; const OnGetDataFallback: TGetDataObjectDataEvent); override;
function GetDataObject: IDataObject;
function GetEmpty: Boolean;
public
constructor Create(const ADataObject: IDataObject);
end;
{ Our own IDataObject implementation; is pretty complete, in particular it has a substantive
not dummy SetData implementation (needed for drag and drop). Nonetheless, from Delphi code
the idea is to build instances up via the IDataObjectBuilder interface instead. }
IClipboardDataObject = interface(IDataObject)
['{CE708417-23A8-4EA3-8674-4321D743FC94}']
function GetIsOleClipboard: Boolean;
procedure SetIsOleClipboard(Value: Boolean);
property IsOleClipboard: Boolean read GetIsOleClipboard write SetIsOleClipboard;
end;
TDataObject = class(TDataObjectBuilderBase, IDataObject, IDataObjectBuilder, IClipboardDataObject)
private type
TOutputKind = (okAllocResourceInMedium, okGetInPlace, okQueryOnly);
strict private type
TSource = class
strict private
FDataRetrievedCount: Integer;
FFormatEtc: TFormatEtc;
FFallbackTymed: LongInt;
FStgMedium: TStgMedium;
FOnGetData, FOnGetDataFallback: TGetDataObjectDataEvent;
procedure ReleaseStgMedium;
public
constructor Create(const ClipFormat: TClipFormat; Index: LongInt);
destructor Destroy; override;
procedure Assign(PreferredTymed: LongInt; const OnGetData: TGetDataObjectDataEvent;
FallbackTymed: LongInt; const OnGetDataFallback: TGetDataObjectDataEvent); overload;
procedure Assign(const StgMediumToOwn: TStgMedium); overload;
function DoGetData(const WantedFormat: TFormatEtc; var Medium: TStgMedium;
OutputKind: TOutputKind): HRESULT;
property DataRetrievedCount: Integer read FDataRetrievedCount;
property Aspect: LongInt read FFormatEtc.dwAspect;
property ClipFormat: TClipFormat read FFormatEtc.cfFormat;
property FormatEtc: TFormatEtc read FFormatEtc;
property Index: LongInt read FFormatEtc.lindex;
property PreferredTymed: LongInt read FFormatEtc.tymed;
property FallbackTymed: LongInt read FFallbackTymed;
end;
protected type
TEnumFormatEtc = class(TInterfacedObject, IEnumFormatEtc)
strict private
FNextIndex: Integer;
FSource: TDataObject;
protected
function Next(celt: Longint; out elt;
pceltFetched: PLongint): HRESULT; stdcall;
function Skip(celt: Longint): HRESULT; stdcall;
function Reset: HRESULT; stdcall;
function Clone(out Enum: IEnumFormatEtc): HRESULT; stdcall;
public
constructor Create(const ASource: TDataObject; AStartAt: Integer = 0);
destructor Destroy; override;
end;
strict private
FSources: TList<TSource>;
function FindOrAddSource(const ClipFormat: TClipFormat; Index: Integer): TSource;
function DoGetData(const FormatEtc: TFormatEtc; var Medium: TStgMedium;
OutputKind: TOutputKind): HRESULT; overload;
function GetFormatCount: Integer;
function GetFormatEtc(Index: Integer): TFormatEtc;
protected
{ IDataObjectBuilder }
procedure AddFormat(Format: TClipFormat; Index: LongInt; var StgMediumToOwn: TStgMedium); overload;
procedure AddFormat(const Format: TClipboardFormat; Index: LongInt;
var StgMediumToOwn: TStgMedium); overload;
procedure AddFormat(const Format: TClipboardFormat; Index: LongInt;
PreferredTymed: LongInt; const OnGetData: TGetDataObjectDataEvent;
FallbackTymed: LongInt; const OnGetDataFallback: TGetDataObjectDataEvent); override;
function GetDataObject: IDataObject;
function GetEmpty: Boolean;
{ IDataObject }
function GetData(const formatetcIn: TFormatEtc; out medium: TStgMedium): HRESULT; stdcall;
function GetDataHere(const formatetc: TFormatEtc; out medium: TStgMedium): HRESULT; stdcall;
function QueryGetData(const formatetc: TFormatEtc): HRESULT; stdcall;
function GetCanonicalFormatEtc(const formatetc: TFormatEtc;
out formatetcOut: TFormatEtc): HRESULT; stdcall;
function SetData(const formatetc: TFormatEtc; var medium: TStgMedium; fRelease: BOOL): HRESULT; stdcall;
function EnumFormatEtc(dwDirection: LongInt; out enumFormatEtc: IEnumFormatEtc): HRESULT; stdcall;
function DAdvise(const formatetc: TFormatEtc; advf: LongInt;
const advSink: IAdviseSink; out dwConnection: LongInt): HRESULT; stdcall;
function DUnadvise(dwConnection: LongInt): HRESULT; stdcall;
function EnumDAdvise(out enumAdvise: IEnumStatData): HRESULT; stdcall;
{ IClipboardDataObject }
function HaveAllFormatsBeenRetrieved: Boolean;
function GetIsOleClipboard: Boolean;
procedure SetIsOleClipboard(Value: Boolean);
public
constructor Create;
destructor Destroy; override;
property FormatCount: Integer read GetFormatCount;
property FormatEtcs[Index: Integer]: TFormatEtc read GetFormatEtc;
end;
{ TDataObjectDestroyNotifier wraps an existing IDataObject purely to call a user-provided
method on destruction. Needed because can't open the classic and OLE clipboards at the
same time, so when the latter needs to be read the classic clipboard is closed but
re-opened once the OLE clipboard has been finished with (goes out of scope/nil'ed) }
TDataObjectDestroyNotifier = class(TInterfacedObject, IDataObject)
strict private
FSource: IDataObject;
FOnDestroy: TNotifyEvent;
protected
function GetData(const formatetcIn: TFormatEtc; out medium: TStgMedium): HRESULT; stdcall;
function GetDataHere(const formatetc: TFormatEtc; out medium: TStgMedium): HRESULT; stdcall;
function QueryGetData(const formatetc: TFormatEtc): HRESULT; stdcall;
function GetCanonicalFormatEtc(const formatetc: TFormatEtc;
out formatetcOut: TFormatEtc): HRESULT; stdcall;
function SetData(const formatetc: TFormatEtc; var medium: TStgMedium; fRelease: BOOL): HRESULT; stdcall;
function EnumFormatEtc(dwDirection: LongInt; out enumFormatEtc: IEnumFormatEtc): HRESULT; stdcall;
function DAdvise(const formatetc: TFormatEtc; advf: LongInt;
const advSink: IAdviseSink; out dwConnection: LongInt): HRESULT; stdcall;
function DUnadvise(dwConnection: LongInt): HRESULT; stdcall;
function EnumDAdvise(out enumAdvise: IEnumStatData): HRESULT; stdcall;
public
constructor Create(const ASource: IDataObject; const OnDestroy: TNotifyEvent);
procedure BeforeDestruction; override;
end;
{ IWinClipboardCore is queried for by the VCL and FMX/Win TClipboard class helpers in
order to implement GetAsHandle, SetAsHandle and EnumDataObject methods on TClipboard.
Simply exposing the IDataObject as a property would risk a reference being held onto
and so preventing use of the classic clipboard functions. }
TEnumDataObjectCallback = reference to procedure (const DataObject: IDataObject;
const FormatEtc: TFormatEtc; var LookForMore: Boolean);
IWinClipboardCore = interface
['{DC1DB577-7255-4772-9A7D-C2FB0944F0EF}']
function DoGetAsHandle(Format: TClipboardFormat): THandle;
procedure DoSetAsHandle(Format: TClipboardFormat; Value: THandle); overload;
procedure DoSetAsHandleDelayed(Format: TClipboardFormat; ValueGetter: TFunc<THandle>); overload;
procedure EnumDataObject(const Callback: TEnumDataObjectCallback);
end;
TDummyChangeCountBehaviour = (dbIncrementing, dbFixed);
TWinClipboardCore = class(TClipboard.TCore, IWinClipboardCore, TClipboard.IDelayedRendering,
TClipboard.IReadWriteBytes, TClipboard.IReadWriteStream, TClipboard.IReadWriteFileNames,
TClipboard.IReadWriteURL, TClipboard.IReadWriteVirtualFile)
strict private type
TVirtualFileInfo = class
Details: TVirtualFileDetails;
Renderer: TProc<TStream>;
end;
strict private class var
FLegacyFormatToClassMap: TDictionary<TClipboardFormat, TClass>;
FOEMEncoding: TEncoding;
FChangeListenerWnd: HWND;
FRegisteredListenerWndClass: Boolean;
class constructor InitializeClass;
class destructor FinalizeClass;
strict private
FCustomDataObjectToWrap: IDataObject;
FDataObjectBuilder: IDataObjectBuilder;
FDummyChangeCountBehaviour: TDummyChangeCountBehaviour;
FFilesToWrite: TList<TFunc<TFileName>>;
FStgMediumsToRelease: TList<TStgMedium>;
FSysDataObjectToRead: Pointer; //weak ref for us plebs who don't have [Weak]
FVirtualFilesToWrite: TObjectList<TVirtualFileInfo>;
procedure StgMediumsToReleaseNotify(Sender: TObject; const Item: TStgMedium;
Action: TCollectionNotification);
procedure SysDataObjectToReadDestroy(Sender: TObject);
function DoGetStrings(const Format: TClipboardFormat; const Encoding: TEncoding): TArray<string>;
procedure DoSetString(const Format: TClipboardFormat; const Encoding: TEncoding;
const Renderer: TFunc<string>);
function DoReadFileNames(out FileNames: TArray<string>; ReturnCountOnly: Boolean = False): Integer;
procedure DoReadVirtualFiles(DescriptorsOnly: Boolean; const Callback: TEnumVirtualFilesStreamCallback);
procedure AssignFilesToWrite;
procedure AssignVirtualFilesToWrite;
class function ListenerWndProc(Wnd: HWND; Msg: UINT;
wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; static;
private class var
cfFileContents, cfAnsiFileName, cfUnicodeFileName: TClipboardFormat;
private
ChangeNotificationCallback: TThreadMethod;
strict protected
constructor Create(const AOwner: TClipboard); overload; override;
function GetDataObjectToRead: IDataObject;
property CustomDataObjectToWrap: IDataObject read FCustomDataObjectToWrap;
property DataObjectBuilder: IDataObjectBuilder read FDataObjectBuilder;
{ TClipboard.TCore }
function GetChangeCount: TClipboardChangeCount; override;
function SupportsChangeNotifications: Boolean; override;
procedure EnableChangeNotifications(const Callback: TThreadMethod); override;
procedure DisableChangeNotifications; override;
function WrapsSystemClipboard: Boolean; override;
function GetFormats: TArray<TClipboardFormat>; override;
function HasFormat(Format: TClipboardFormat): Boolean; override;
function HasFormat(const Formats: array of TClipboardFormat; var Matched: TClipboardFormat): Boolean; override;
function DoOpen: Boolean; override;
procedure DoClose; override;
procedure DoClear; override;
function HasPlainText: Boolean; override;
function ReadPlainText: TArray<string>; override;
procedure WritePlainText(const Renderer: TFunc<string>; PreferDelayed: Boolean); override;
{ IWinClipboardCore }
function DoGetAsHandle(Format: TClipboardFormat): THandle;
procedure DoSetAsHandle(Format: TClipboardFormat; Value: THandle); overload;
procedure DoSetAsHandleDelayed(Format: TClipboardFormat; ValueGetter: TFunc<THandle>); overload;
procedure EnumDataObject(const Callback: TEnumDataObjectCallback);
{ TClipboard.IDelayedRendering }
function HasOutstandingPromisesToOS: Boolean;
procedure ResolveOutstandingPromisesToOS(IsExplicitlyRequested: Boolean);
procedure CancelOutstandingPromisesToOS;
{ TClipboard.IReadWriteBytes }
function ReadBytes(const Format: TClipboardFormat): TBytes;
procedure WriteBytes(const Format: TClipboardFormat;
const Renderer: TFunc<TBytes>; PreferDelayed: Boolean = True);
{ TClipboard.IReadWriteStream }
function ReadStream(const Format: TClipboardFormat; const Dest: TStream): Boolean;
procedure WriteStream(const Format: TClipboardFormat;
const Renderer: TProc<TStream>; PreferDelayed: Boolean);
{ TClipboard.IReadWriteFileNames }
function HasFile: Boolean;
function ReadFileNames: TArray<string>;
procedure WriteFileName(const Renderer: TFunc<TFileName>; PreferDelayed: Boolean);
{ TClipboard.IReadWriteURL }
function ReadURLs: TArray<string>;
procedure WriteURL(const Renderer: TFunc<string>; PreferDelayed: Boolean);
{ TClipboard.IReadWriteVirtualFile }
function ReadVirtualFileDescriptors: TArray<string>;
procedure ReadVirtualFiles(const Callback: TEnumVirtualFilesStreamCallback);
procedure SaveVirtualFiles(const Callback: TSaveVirtualFilesCallback);
procedure WriteVirtualFile(const Details: TVirtualFileDetails;
const Renderer: TProc<TStream>; PreferDelayed: Boolean);
protected
class procedure InitializeFormats(StdFormatValues: TClipboard.TStdFormatValues;
var CustomFormatsSupported: Boolean); override;
class function GetFormatName(const Format: TClipboardFormat): string; override;
class function IsCompatibleVirtualFileDescriptor(const Descriptor: string;
const SupportedFileExts: TArray<string>): Boolean; override;
public
class function RegisterFormat(const Name: string): TClipboardFormat; override;
public
class function CreateClipboardForDataObject(const DataObject: IDataObject;
DummyChangeCountBehaviour: TDummyChangeCountBehaviour): TClipboard;
constructor Create(const AOwner: TClipboard; const DataObjectToWrap: IDataObject;
DummyChangeCountBehaviour: TDummyChangeCountBehaviour); reintroduce; overload;
procedure BeforeDestruction; override;
destructor Destroy; override;
class property OEMEncoding: TEncoding read FOEMEncoding;
{ For support of legacy HasFormat(cfPicture) syntax - preferred is HasFormatFor(TPicture).
Implemented here not in TClipboard to discourage use. }
class property LegacyFormatToClassMap: TDictionary<TClipboardFormat, TClass> read FLegacyFormatToClassMap;
end;
TWinClipboardCoreClass = class of TWinClipboardCore;
IOleDragHelper = interface
['{5CD06C04-474A-4D49-AB47-365CD6B692F5}']
function GetClipboard: TClipboard;
function GetMousePos: TPoint;
procedure SetBitmap(const Value: HBITMAP; TransparentColor: TColorRef = 0);
procedure SetOffset(const Value: TPoint);
function Execute: Boolean;
property Clipboard: TClipboard read GetClipboard;
property MousePos: TPoint read GetMousePos;
end;
TOleDragHelper = class(TDataObjectDestroyNotifier, IDropSource, IOleDragHelper)
strict private
FAutoOffset: Boolean;
FBitmap: HBITMAP;
FClipboard: TClipboard;
FEffect: LongInt;
FMousePos, FOffset: TPoint;
FTransparentColor: TColorRef;
protected
{ IDropSource }
function QueryContinueDrag(fEscapePressed: BOOL; grfKeyState: LongInt): HRESULT; stdcall;
function GiveFeedback(dwEffect: LongInt): HRESULT; stdcall;
{ IOleDragHelper }
function GetClipboard: TClipboard;
function GetMousePos: TPoint;
procedure SetBitmap(const Value: HBITMAP; TransparentColor: TColorRef = 0);
procedure SetOffset(const Value: TPoint);
function Execute: Boolean;
public
constructor Create;
destructor Destroy; override;
end;
function cfBitmap: TClipboardFormat; inline;
function cfMetafilePict: TClipboardFormat; inline;
function cfSYLK: TClipboardFormat; inline;
function cfDIF: TClipboardFormat; inline;
function cfAnsiText: TClipboardFormat; inline;
function cfOemText: TClipboardFormat; inline;
function cfUnicodeText: TClipboardFormat; inline;
function cfDIB: TClipboardFormat; inline;
function cfPalette: TClipboardFormat; inline;
function cfPenData: TClipboardFormat; inline;
function cfRiff: TClipboardFormat; inline;
function cfWave: TClipboardFormat; inline;
function cfEnhMetafile: TClipboardFormat; inline;
function cfHDROP: TClipboardFormat; inline;
function cfLocale: TClipboardFormat; inline;
function cfDIBv5: TClipboardFormat; inline;
function cfDspText: TClipboardFormat; inline;
function cfDspBitmap: TClipboardFormat; inline;
function cfDspMetafilePict: TClipboardFormat; inline;
function cfDspEnhMetafile: TClipboardFormat; inline;
function cfFileContents: TClipboardFormat; inline;
function cfAnsiFileName: TClipboardFormat; inline;
function cfUnicodeFileName: TClipboardFormat; inline;
function cfDataObject: TClipboardFormat; inline;
{$ENDIF}
implementation
{$IFDEF MSWINDOWS}
uses
WinApi.Messages, WinApi.RichEdit, WinApi.ShellApi,
System.StrUtils, System.Math, System.RTLConsts;
function GetPriorityClipboardFormat(const paFormatPriorityList;
cFormats: Integer): Integer; stdcall; external user32;
function TClipboardFormatHelper.GetHandle: TClipFormat;
begin
Result := TClipFormat(NativeUInt(Self));
end;
class function TClipboardFormatHelper.Wrap(const Value: TClipFormat): TClipboardFormat;
begin
NativeUInt(Result) := Value;
end;
function cfBitmap: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_BITMAP);
end;
function cfMetafilePict: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_METAFILEPICT);
end;
function cfSYLK: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_SYLK);
end;
function cfDIF: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_DIF);
end;
function cfAnsiText: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_TEXT);
end;
function cfOemText: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_OEMTEXT);
end;
function cfUnicodeText: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_UNICODETEXT);
end;
function cfDIB: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_DIB);
end;
function cfPalette: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_PALETTE);
end;
function cfPenData: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_PENDATA);
end;
function cfRiff: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_RIFF);
end;
function cfWave: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_WAVE);
end;
function cfEnhMetafile: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_ENHMETAFILE);
end;
function cfHDROP: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_HDROP);
end;
function cfLocale: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_LOCALE);
end;
function cfDIBv5: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_DIBV5);
end;
function cfDspText: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_DSPTEXT);
end;
function cfDspBitmap: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_DSPBITMAP);
end;
function cfDspMetafilePict: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_DSPMETAFILEPICT);
end;
function cfDspEnhMetafile: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap(CF_DSPENHMETAFILE);
end;
function cfFileContents: TClipboardFormat;
begin
Result := TWinClipboardCore.cfFileContents;
end;
function cfAnsiFileName: TClipboardFormat;
begin
Result := TWinClipboardCore.cfAnsiFileName;
end;
function cfUnicodeFileName: TClipboardFormat;
begin
Result := TWinClipboardCore.cfUnicodeFileName;
end;
function cfDataObject: TClipboardFormat;
begin
Result := TClipboardFormat.Wrap($C009);
end;
procedure Win32Check(RetVal: BOOL);
begin
if not RetVal then RaiseLastOSError;
end;
function CreateBytesFromHGLOBAL(const Global: HGLOBAL): TBytes;
var
Ptr: PByte;
begin
if Global = 0 then
Exit(nil);
Ptr := GlobalLock(Global);
try
SetLength(Result, GlobalSize(Global));
if Result <> nil then Move(Ptr^, Result[0], Length(Result));
finally
GlobalUnlock(Global);
end;
end;
procedure InitMediumHGlobal(NeededSize: SIZE_T; AllocResourceInMedium: Boolean; var Medium: TStgMedium);
begin
if AllocResourceInMedium then
Medium.hGlobal := GlobalAlloc(GMEM_MOVEABLE or GMEM_DDESHARE or GMEM_ZEROINIT, NeededSize)
else if GlobalSize(Medium.hGlobal) < NeededSize then
OleError(E_OUTOFMEMORY); //MSDN docs say not to realloc
if Medium.hGlobal = 0 then RaiseLastOSError;
end;
procedure InitAndAssignMediumHGlobal(const Buffer; BufferSize: NativeInt;
AllocResourceInMedium: Boolean; var Medium: TStgMedium); overload;
var
Ptr: Pointer;
begin
InitMediumHGlobal(BufferSize, AllocResourceInMedium, Medium);
Ptr := GlobalLock(Medium.hGlobal);
try
Move(Buffer, Ptr^, BufferSize)
finally
GlobalUnlock(Medium.hGlobal);
end;
end;
procedure InitAndAssignMediumHGlobal(const SourceToCopy: HGLOBAL;
AllocResourceInMedium: Boolean; var Medium: TStgMedium); overload;
var
SourcePtr, DestPtr: Pointer;
Size: Integer;
begin
Size := GlobalSize(SourceToCopy);
InitMediumHGlobal(Size, AllocResourceInMedium, Medium);
SourcePtr := GlobalLock(SourceToCopy);
DestPtr := GlobalLock(Medium.hGlobal);
try
Move(SourcePtr^, DestPtr^, Size)
finally
GlobalUnlock(Medium.hGlobal);
GlobalUnlock(SourceToCopy);
end;
end;
function GetStgMediumFromStgMedium(const Source: TStgMedium; var Dest: TStgMedium;
OutputKind: TDataObject.TOutputKind): HRESULT;
var
Pos: Int64;
PictToCopyPtr: PMetafilePict;
NewPict: TMetafilePict;
begin
{ While this isn't a full 'TStgMedium copy' implementation, in the case of
OutputKind = okGetInPlace, the only valid medium types *ever* to
request per the MSDN docs are TYMED_HGLOBAL, TYMED_FILE, TYMED_ISTREAM and
TYMED_ISTORAGE. }
try
case OutputKind of
okQueryOnly: Exit(S_OK);
okGetInPlace:
begin
if Dest.tymed <> Source.tymed then Exit(DV_E_TYMED);
Dest.unkForRelease := nil;
end;
okAllocResourceInMedium:
begin
Dest.tymed := Source.tymed;
Dest.unkForRelease := nil;
end;
end;
case Source.tymed of
TYMED_HGLOBAL:
begin
InitAndAssignMediumHGlobal(Source.hGlobal, OutputKind = okAllocResourceInMedium, Dest);
Exit(S_OK);
end;
TYMED_ISTREAM:
begin
if OutputKind = okAllocResourceInMedium then
begin
IStream(Source.stm).Seek(0, STREAM_SEEK_END, Pos);
IStream(Dest.stm) := IStream(Source.stm);
Exit(S_OK);
end;
if Dest.stm = nil then Exit(DV_E_STGMEDIUM);
IStream(Source.stm).Seek(0, STREAM_SEEK_SET, Pos);
Result := IStream(Source.stm).CopyTo(IStream(Dest.stm),
High(Int64), PInt64(nil)^, PInt64(nil)^);
Exit;
end;
TYMED_GDI:
begin
if OutputKind <> okAllocResourceInMedium then Exit(DV_E_TYMED);
Dest.hBitmap := CopyImage(Source.hBitmap, IMAGE_BITMAP, 0, 0, 0);
if Dest.hBitmap = 0 then
Exit(HResultFromWin32(GetLastError))
else
Exit(S_OK);
end;
TYMED_ENHMF:
begin
if OutputKind <> okAllocResourceInMedium then Exit(DV_E_TYMED);
Dest.hEnhMetaFile := CopyEnhMetaFile(Source.hEnhMetaFile, nil);
if Dest.hEnhMetaFile = 0 then
Exit(HResultFromWin32(GetLastError))
else
Exit(S_OK);
end;
TYMED_MFPICT:
begin
if OutputKind <> okAllocResourceInMedium then Exit(DV_E_TYMED);
PictToCopyPtr := GlobalLock(Source.hMetaFilePict);
try
NewPict := PictToCopyPtr^;
NewPict.hMF := CopyMetaFile(NewPict.hMF, nil);
if NewPict.hMF = 0 then
Exit(HResultFromWin32(GetLastError))
else
Exit(S_OK);
finally
GlobalUnlock(Source.hMetaFilePict);
end;
InitAndAssignMediumHGlobal(NewPict, SizeOf(NewPict), True, Dest);
Exit(S_OK);
end;
else
Exit(DV_E_TYMED);
end;
except
on E: EOleSysError do
Result := E.ErrorCode
else
Result := E_UNEXPECTED;
end;
end;
//procedure GetBitmapFromMetafilePict(const Source: HGLOBAL; Dest: TBitmap);
//var
// BitmapInfo: TBitmapInfo;
// Bytes: TBytes;
// EnhMetafile: HENHMETAFILE;
// EnhHeader: TEnhMetaHeader;
// ScreenDC, MemDC: HDC;
// MemBitmap, PrevBitmap: HBITMAP;
// Pict: PMetafilePict;
// MapData: TBitmapData;
//begin
// Pict := GlobalLock(Source);
// try
// SetLength(Bytes, GetMetaFileBitsEx(Pict.hMF, 0, nil));
// GetMetaFileBitsEx(Pict.hMF, Length(Bytes), Bytes);
// EnhMetafile := 0;
// ScreenDC := GetDC(0);
// try
// EnhMetafile := SetWinMetaFileBits(Length(Bytes), @Bytes[0], ScreenDC, Pict^);
// GetEnhMetaFileHeader(EnhMetafile, SizeOf(EnhHeader), @EnhHeader);
// MemDC := CreateCompatibleDC(ScreenDC);
// if MemDC = 0 then RaiseLastOSError;
// MemBitmap := CreateCompatibleBitmap(MemDC,
// EnhHeader.rclBounds.Width + 1, EnhHeader.rclBounds.Height + 1);
// if MemBitmap = 0 then RaiseLastOSError;
// PrevBitmap := SelectObject(MemDC, MemBitmap);
// if not PlayEnhMetaFile(MemDC, EnhMetafile, EnhHeader.rclBounds) then
// RaiseLastOSError;
// Dest.SetSize(EnhHeader.rclBounds.Width + 1, EnhHeader.rclBounds.Height + 1);
// Dest.Clear(TAlphaColors.Null);
// Dest.Map(TMapAccess.Write, MapData);
// try
// GetDIBits(MemDC, MemBitmap, 0, MapData.Height, MapData.Data, BitmapInfo, DIB_RGB_COLORS);
// finally
// Dest.Unmap(MapData);
// end;
// SelectObject(MemDC, PrevBitmap);
// DeleteObject(MemBitmap);
// DeleteDC(MemDC);
// finally
// if EnhMetafile <> 0 then DeleteEnhMetaFile(EnhMetafile);
// ReleaseDC(0, ScreenDC);
// end;
// finally
// GlobalUnlock(Source);
// end;
//end;
{ IDataObject helpers }
function GetFormatCountInDataObject(const DataObject: IDataObject): Integer;
var
Enumerator: IEnumFORMATETC;
FormatEtc: TFormatEtc;
begin
OleCheck(DataObject.EnumFormatEtc(DATADIR_GET, Enumerator));
OleCheck(Enumerator.Reset);
Result := 0;
while Enumerator.Next(1, FormatEtc, nil) = S_OK do
if FormatEtc.dwAspect = DVASPECT_CONTENT then
Inc(Result);
end;
function GetFormatsInDataObject(const DataObject: IDataObject): TArray<TClipboardFormat>;
var
Count: Integer;
Enumerator: IEnumFORMATETC;
FormatEtc: TFormatEtc;
begin
OleCheck(DataObject.EnumFormatEtc(DATADIR_GET, Enumerator));
OleCheck(Enumerator.Reset);
Count := 0;
while Enumerator.Next(1, FormatEtc, nil) = S_OK do
if FormatEtc.dwAspect = DVASPECT_CONTENT then
begin
if Length(Result) = Count then
SetLength(Result, Count + 16);
Result[Count] := TClipboardFormat.Wrap(FormatEtc.cfFormat);
Inc(Count);
end;
SetLength(Result, Count);
end;
function HasFormatInDataObject(const DataObject: IDataObject;
const Format: TClipboardFormat): Boolean; overload;
var
Etc: TFormatEtc;
begin
Etc.cfFormat := Format.Handle;
Etc.ptd := nil;
Etc.dwAspect := DVASPECT_CONTENT;
Etc.lindex := -1;
case Format.Handle of
CF_BITMAP: Etc.tymed := TYMED_GDI;
CF_METAFILEPICT: Etc.tymed := TYMED_MFPICT;
CF_ENHMETAFILE: Etc.tymed := TYMED_ENHMF;
else Etc.tymed := TYMED_HGLOBAL;
end;
Result := (DataObject.QueryGetData(Etc) = S_OK);
if not Result and (Etc.tymed = TYMED_HGLOBAL) then
begin
Etc.tymed := TYMED_ISTREAM;
Result := (DataObject.QueryGetData(Etc) = S_OK);
end;
end;
function HasFormatInDataObject(const DataObject: IDataObject;
const Formats: array of TClipboardFormat; var Matched: TClipboardFormat): Boolean; overload;
var
I: Integer;
begin
for I := Low(Formats) to High(Formats) do
if HasFormatInDataObject(DataObject, Formats[I]) then
begin
Matched := Formats[I];
Exit(True);
end;
Result := False;
end;
function GetBytesInDataObject(const DataObject: IDataObject; Format: TClipboardFormat;
Index: Integer = -1): TBytes;
var
Etc: TFormatEtc;
Medium: TStgMedium;
begin
Result := nil;
Etc.cfFormat := Format.Handle;
Etc.ptd := nil;
Etc.dwAspect := DVASPECT_CONTENT;
Etc.lindex := Index;
Etc.tymed := TYMED_HGLOBAL;
if DataObject.GetData(Etc, Medium) <> S_OK then Exit;
try
Result := CreateBytesFromHGLOBAL(Medium.hGlobal)
finally
ReleaseStgMedium(Medium);
end;
end;
{ TOleStreamWrapper }
constructor TOleStreamWrapper.Create(const AStream: IStream);
begin
inherited Create;
FStream := AStream;
end;
function TOleStreamWrapper.Read(var Buffer; Count: LongInt): LongInt;
begin
OleCheck(FStream.Read(@Buffer, Count, @Result));
end;
function TOleStreamWrapper.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
OleCheck(FStream.Seek(Offset, Ord(Origin), Result));
end;
function TOleStreamWrapper.Write(const Buffer; Count: LongInt): LongInt;
begin
OleCheck(FStream.Write(@Buffer, Count, @Result));
end;
{ TDataObjectBuilderBase }
procedure TDataObjectBuilderBase.AddFormat(const Format: TClipboardFormat; Index: LongInt;
const OnGetData: TFunc<TBytes>);
begin
AddFormat(Format, Index,
TYMED_HGLOBAL,
procedure (AllocResourceInMedium: Boolean; var Medium: TStgMedium)
var
Data: TBytes;
Ptr: PByte;
begin
Data := OnGetData;
InitMediumHGlobal(Length(Data), AllocResourceInMedium, Medium);
if Data = nil then Exit;
Ptr := GlobalLock(Medium.hGlobal);
try
Move(Data[0], Ptr^, Length(Data));
finally
GlobalUnlock(Medium.hGlobal);
end;
end,
TYMED_ISTREAM,
procedure (AllocResourceInMedium: Boolean; var Medium: TStgMedium)
var
Data: TBytes;
begin
Data := OnGetData;
if AllocResourceInMedium then
IStream(Medium.stm) := TStreamAdapter.Create(TBytesStream.Create(Data), soOwned) as IStream
else
IStream(Medium.stm).Write(Data, Length(Data), nil);
end
);
end;
procedure TDataObjectBuilderBase.AddFormat(const Format: TClipboardFormat; Index: LongInt;
const OnGetData: TProc<TStream>);
begin
AddFormat(Format, Index,
TYMED_ISTREAM,
procedure (AllocResourceInMedium: Boolean; var Medium: TStgMedium)
var
Stream: TStream;
begin
if AllocResourceInMedium then
begin
Stream := TMemoryStream.Create;
try
OnGetData(Stream);
IStream(Medium.stm) := TStreamAdapter.Create(Stream, soOwned) as IStream;
except
Stream.Free;
raise;
end;
end
else
begin
Stream := TOleStreamWrapper.Create(IStream(Medium.stm));
try
OnGetData(Stream);
finally
Stream.Free;
end;
end;
end,
TYMED_HGLOBAL,
procedure (AllocResourceInMedium: Boolean; var Medium: TStgMedium)
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
OnGetData(Stream);
InitAndAssignMediumHGlobal(Stream.Memory^, Stream.Size, AllocResourceInMedium, Medium);
finally
Stream.Free;
end;
end
);
end;
{ TDataObjectBuilder }
constructor TDataObjectBuilder.Create(const ADataObject: IDataObject);
begin
inherited Create;
FDataObject := ADataObject;
end;
procedure TDataObjectBuilder.AddFormat(const Format: TClipboardFormat; Index: LongInt;
var StgMediumToOwn: TStgMedium);
var
Etc: TFormatEtc;
Result: HRESULT;
begin
Etc.cfFormat := Format.Handle;
Etc.ptd := nil;
Etc.dwAspect := DVASPECT_CONTENT;
Etc.lindex := Index;
Etc.tymed := StgMediumToOwn.tymed;
Result := FDataObject.SetData(Etc, StgMediumToOwn, True);
if Result <> S_OK then
ReleaseStgMedium(StgMediumToOwn);
OleCheck(Result);
end;
procedure TDataObjectBuilder.AddFormat(const Format: TClipboardFormat; Index: LongInt;
PreferredTymed: LongInt; const OnGetData: TGetDataObjectDataEvent;
FallbackTymed: LongInt; const OnGetDataFallback: TGetDataObjectDataEvent);
var
Etc: TFormatEtc;
Medium: TStgMedium;
Result: HRESULT;
begin