-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathCCR.Clipboard.Apple.pas
1860 lines (1679 loc) · 62.9 KB
/
CCR.Clipboard.Apple.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 - OS X and iOS backends. In same unit for convenience of client code. }
{ }
{ 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.Apple;
interface
{$IFDEF NEXTGEN}
{$LEGACYIFEND ON}
{$ENDIF}
{$IFDEF MACOS}
uses
{$IFDEF IOS} {$IF RTLVersion < 27}{$Message Fatal 'TClipboard for iOS requires XE6 or later'}{$IFEND}
iOSapi.CocoaTypes, iOSapi.CoreGraphics, iOSapi.Foundation, iOSapi.UIKit,
{$ELSE}
MacApi.CocoaTypes, MacApi.CoreGraphics, MacApi.Foundation, MacApi.AppKit,
{$ENDIF}
System.Math, System.SysUtils, System.Classes, System.Generics.Collections, System.UITypes,
Posix.Dlfcn, Posix.UniStd, MacApi.ObjCRuntime, MacApi.ObjectiveC, MacApi.CoreFoundation,
CCR.Clipboard.Consts, CCR.Clipboard, CCR.Clipboard.Apple.Helpers;
type
TAppleClipboardCore = class(TClipboard.TCore)
strict private class var
FRegisteredTypes: CFMutableSetRef;
class constructor InitializeClass;
class destructor FinalizeClass;
strict protected class var
FFindClipboard: TClipboard;
class function SameFormat(const Format1, Format2: TClipboardFormat): Boolean; override;
//for notification of RegisterFormat calls with a name not registered before
class procedure NewFormatRegistered(const Name: string; const Format: TClipboardFormat); virtual;
private
class function RegisterFormatInternal(const TypeRef: CFStringRef): TClipboardFormat; overload;
class function RegisterFormatInternal(const TypeLiteral: MarshaledAString): TClipboardFormat; overload; inline;
class property FindClipboard: TClipboard read FFindClipboard;
protected class var
cfAppleICNS, cfColor, cfPDF, cfTGA: TClipboardFormat;
protected
class procedure InitializeFormats(StdFormatValues: TClipboard.TStdFormatValues;
var CustomFormatsSupported: Boolean); override;
class function IsCompatibleVirtualFileDescriptor(const Descriptor: string;
const SupportedFileExtsOrUTIs: TArray<string>): Boolean; override;
class function GetFormatName(const Format: TClipboardFormat): string; override;
class function GetFormatDescription(const Format: TClipboardFormat): string; override;
class function RegisterFormat(const TypeRef: CFStringRef; TakeOwnership: Boolean): TClipboardFormat; reintroduce; overload;
class function RegisterFormat(const Name: string): TClipboardFormat; overload; override;
strict protected
function GetNSURLs: NSArray; virtual; abstract;
protected
function ReadFileNames: TArray<string>;
function ReadURLs: TArray<string>;
end;
TClipboardFormatHelper = record helper for TClipboardFormat
strict private
function GetHandle: CFStringRef; inline;
public
class function Wrap(const PredefinedType: CFStringRef): TClipboardFormat; overload; static; inline;
class function Wrap(const PredefinedType: NSString): TClipboardFormat; overload; static; inline;
class function Wrap(const UTI: string): TClipboardFormat; overload; static; inline;
function IsUTI: Boolean; inline;
function ToNSString: NSString; inline;
property Handle: CFStringRef read GetHandle;
end;
function cfAppleICNS: TClipboardFormat; inline;
function cfColor: TClipboardFormat; inline;
function cfPDF: TClipboardFormat; inline;
function cfTGA: TClipboardFormat; inline;
function ClipboardFormatsToNSArray(const AFormats: array of TClipboardFormat): NSArray;
function NSArrayToClipboardFormats(const Types: NSArray): TArray<TClipboardFormat>;
function FindClipboard: TClipboard; inline;
{$IFDEF iOS}
type
IiOSClipboardCore = interface
['{CCF96610-2292-480E-A733-68BC2746E700}']
procedure AssignNSObject(const Format: TClipboardFormat; const ObjID: Pointer);
function GetPasteboard: UIPasteboard;
property Pasteboard: UIPasteboard read GetPasteboard;
end;
TiOSClipboardCore = class(TAppleClipboardCore, IiOSClipboardCore, TClipboard.IReadWriteBytes,
TClipboard.IReadWriteFileNames, TClipboard.IReadWriteURL, TClipboard.IMultipleFormatSets)
strict private
FChangeListener: NSObject;
FCurrentItem: NSMutableDictionary;
FCustomPasteboard: UIPasteboard;
FToAdd: NSMutableArray;
FOnNotifyChanges: TProc;
function GetPasteboard: UIPasteboard; inline;
procedure NeedItem(const NewIfHasFormat: array of TClipboardFormat);
procedure AssignNSObject(const Format: TClipboardFormat; const ObjID: Pointer);
strict protected
class function ConformingFormat(const FormatToTest, BaseFormat: TClipboardFormat): Boolean; override;
class procedure InitializeFormats(StdFormatValues: TClipboard.TStdFormatValues;
var CustomFormatsSupported: Boolean); override;
function GetNSURLs: NSArray; override;
property OnNotifyChanges: TProc read FOnNotifyChanges;
{ TClipboard.TCore }
function GetChangeCount: TClipboardChangeCount; override;
function SupportsChangeNotifications: Boolean; override;
procedure EnableChangeNotifications(const Callback: TThreadMethod); override;
procedure DisableChangeNotifications; override;
function WrapsSystemClipboard: Boolean; override;
procedure DoClear; override;
function DoOpen: Boolean; override;
procedure DoClose; 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 ReadPlainText: TArray<string>; override;
procedure WritePlainText(const Renderer: TFunc<string>; PreferDelayed: Boolean); override;
{ TClipboard.IMultipleFormatSets }
procedure NewFormatSet;
procedure EnumBytes(const Format: TClipboardFormat; const Callback: TGetBytesCallback);
procedure EnumFormatSets(const Callback: TEnumFormatSetsCallback);
{ TClipboard.IReadWriteBytes }
function ReadBytes(const Format: TClipboardFormat): TBytes;
procedure WriteBytes(const Format: TClipboardFormat;
const Renderer: TFunc<TBytes>; PreferDelayed: Boolean); overload;
{ TClipboard.IReadWriteFileNames }
procedure WriteFileName(const Renderer: TFunc<TFileName>; PreferDelayed: Boolean);
{ TClipboard.IReadWriteURL }
procedure WriteURL(const Renderer: TFunc<string>; PreferDelayed: Boolean);
public
class function CreateClipboardForPasteboard(const Pasteboard: UIPasteboard): TClipboard;
constructor Create(const AOwner: TClipboard; const ACustomPasteboard: UIPasteboard); reintroduce; overload;
destructor Destroy; override;
property Pasteboard: UIPasteboard read GetPasteboard;
end;
TiOSClipboardCoreClass = class of TiOSClipboardCore;
{$ELSE}
type
TGetPasteboardDataEvent = reference to procedure (const NSType: NSString;
const DestItem: NSPasteboardItem);
{$M+}
IPasteboardItemDataProvider = interface(NSPasteboardItemDataProvider)
['{8EA66AE3-A7D1-4139-951E-B4EFBC1089F2}']
{ standard NSPasteboardItemDataProvider }
procedure pasteboard(pasteboard: NSPasteboard; item: NSPasteboardItem; provideDataForType: CFStringRef); cdecl;
procedure pasteboardFinishedWithDataProvider(Sender: Pointer); cdecl;
{ internal }
function count: Integer; cdecl;
function types: NSArray; cdecl;
function hasType(PBType: CFStringRef): Boolean; cdecl;
function hasOutstandingPromises: Boolean; cdecl;
procedure clearContents; cdecl;
procedure resolvePromises(Item: NSPasteboardItem; forceAnyVirtualFile: Boolean); cdecl;
end;
TPasteboardItemDataProvider = class(TOCLocal, NSPasteboardItemDataProvider, IPasteboardItemDataProvider)
strict private type
TSource = class
strict private
FFormat: TClipboardFormat;
FOnGetData: TGetPasteboardDataEvent;
public
constructor Create(const Format: TClipboardFormat; const OnGetData: TGetPasteboardDataEvent);
property Format: TClipboardFormat read FFormat;
property GetData: TGetPasteboardDataEvent read FOnGetData;
end;
strict private
FToUpload: TObjectList<TSource>;
private
procedure AddFormat(const Format: TClipboardFormat; const OnGetData: TGetPasteboardDataEvent);
public
constructor Create; overload;
constructor Create(const Format: TClipboardFormat; const OnGetData: TGetPasteboardDataEvent); overload;
destructor Destroy; override;
{ NSPasteboardItemDataProvider }
procedure pasteboard(pasteboard: NSPasteboard; item: NSPasteboardItem;
provideDataForType: CFStringRef); cdecl;
procedure pasteboardFinishedWithDataProvider(Sender: Pointer); cdecl;
{ IPasteboardItemDataProvider }
function count: Integer; cdecl;
function types: NSArray; cdecl;
function hasType(PBType: CFStringRef): Boolean; cdecl;
function hasOutstandingPromises: Boolean; cdecl;
procedure clearContents; cdecl;
procedure resolvePromises(Item: NSPasteboardItem; forceAnyVirtualFile: Boolean); cdecl;
end;
{$M-}
IMacClipboardCore = interface
['{44B2B2E1-1F2F-429D-A9CB-118F4252302F}']
procedure AssignNSObject(const ObjID: Pointer);
function GetPasteboard: NSPasteboard;
property Pasteboard: NSPasteboard read GetPasteboard;
end;
TMacClipboardCore = class(TAppleClipboardCore, IMacClipboardCore, TClipboard.IReadWriteBytes,
TClipboard.IReadWriteFileNames, TClipboard.IReadWriteURL, TClipboard.IReadWriteVirtualFile,
TClipboard.IMultipleFormatSets, TClipboard.IDelayedRendering)
strict private class var
FAllClipboardTypeKinds: ICFMutableArray; //workaround for class destructors called after variable already nil'ed
FDragClipboard, FFontClipboard, FRulerClipboard: TClipboard;
class destructor FinalizeClass;
class function GetAllClipboardTypeKinds: NSMutableArray; static;
strict private
FChangeNotifyCallback: TThreadMethod;
FCustomPasteboard: NSPasteboard;
FCurrentProvider: TPasteboardItemDataProvider;
FLastChangeCount: NSInteger;
FProviders: TList<IPasteboardItemDataProvider>;
FProvidedItems: array of NSPasteboardItem;
FNSObjectIDsToUpload: TList<Pointer>;
FTimer: CFRunLoopTimerRef;
class procedure CheckForChangesTimer(timer: CFRunLoopTimerRef; info: Pointer); cdecl; static;
procedure CheckForChanges;
procedure AddFormat(const Format: TClipboardFormat;
const OnGetData: TGetPasteboardDataEvent);
procedure NSObjectIDsToUploadNotify(Sender: TObject; const Item: Pointer;
Action: TCollectionNotification);
procedure DoEnumVirtualFiles(DescriptorsOnly: Boolean; const Callback: TSaveVirtualFilesCallback);
private class var
cfRTFD, cfTabularText, cfFont, cfRuler, cfSound, cfMultipleTextSelection,
cfFindPanelSearchOptions, cfFileURLPromise, cfFilePromiseContent: TClipboardFormat;
class property DragClipboard: TClipboard read FDragClipboard;
class property FontClipboard: TClipboard read FFontClipboard;
class property RulerClipboard: TClipboard read FRulerClipboard;
strict protected
class function ConformingFormat(const FormatToTest, BaseFormat: TClipboardFormat): Boolean; override;
class procedure InitializeFormats(StdFormatValues: TClipboard.TStdFormatValues;
var CustomFormatsSupported: Boolean); override;
class procedure NewFormatRegistered(const Name: string; const Format: TClipboardFormat); override;
function GetNSURLs: NSArray; override;
{ IMacClipboardCore }
procedure AssignNSObject(const ObjID: Pointer);
function GetPasteboard: NSPasteboard;
{ TClipboard.TCore }
constructor Create(const AOwner: TClipboard); overload; override;
function SupportsChangeNotifications: Boolean; override;
procedure EnableChangeNotifications(const Callback: TThreadMethod); override;
procedure DisableChangeNotifications; override;
function GetChangeCount: TClipboardChangeCount; 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 ReadPlainText: TArray<string>; override;
procedure WritePlainText(const Renderer: TFunc<string>; PreferDelayed: Boolean); override;
{ 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); overload;
{ TClipboard.IReadWriteFileNames }
procedure WriteFileName(const Renderer: TFunc<TFileName>; PreferDelayed: Boolean);
{ TClipboard.IReadWriteURL }
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);
{ TClipboard.IMultipleFormatSets }
procedure NewFormatSet;
procedure EnumBytes(const Format: TClipboardFormat; const Callback: TGetBytesCallback);
procedure EnumFormatSets(const Callback: TEnumFormatSetsCallback);
public
constructor Create(const AOwner: TClipboard; const ACustomPasteboard: NSPasteboard); reintroduce; overload;
destructor Destroy; override;
property Pasteboard: NSPasteboard read GetPasteboard;
class property AllClipboardTypeKinds: NSMutableArray read GetAllClipboardTypeKinds;
end;
function LoadNSObjectsFromPasteboard(const Pasteboard: NSPasteboard; const NSClass: NSObjectClass): NSArray; overload;
function LoadNSObjectsFromPasteboard(const Pasteboard: NSPasteboard;
const NSClasses: array of NSObjectClass; const Options: NSDictionary = nil): NSArray; overload;
function DragClipboard: TClipboard; inline;
function FontClipboard: TClipboard; inline;
function RulerClipboard: TClipboard; inline;
function cfRTFD: TClipboardFormat; inline;
function cfTabularText: TClipboardFormat; inline;
function cfFont: TClipboardFormat; inline;
function cfRuler: TClipboardFormat; inline;
function cfSound: TClipboardFormat; inline;
function cfMultipleTextSelection: TClipboardFormat; inline;
function cfFindPanelSearchOptions: TClipboardFormat; inline;
function cfFileURLPromise: TClipboardFormat; inline;
function cfFilePromiseContent: TClipboardFormat; inline;
{$ENDIF}
{$ENDIF}
implementation
{$IFDEF MACOS}
uses
System.RTLConsts, System.IOUtils;
function ClipboardFormatsToNSArray(const AFormats: array of TClipboardFormat): NSArray;
begin
Result := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@AFormats[0], Length(AFormats)));
end;
function NSArrayToClipboardFormats(const Types: NSArray): TArray<TClipboardFormat>;
var
I: Integer;
begin
if Types = nil then Exit(nil);
SetLength(Result, Types.count);
{ can't just copy the CFStringRefs directly because caller may wish to hold
onto the array -> retain counts }
for I := 0 to High(Result) do
Result[I] := TAppleClipboardCore.RegisterFormat(Types.objectAtIndex(I), False)
end;
function cfAppleICNS: TClipboardFormat;
begin
Result := TAppleClipboardCore.cfAppleICNS;
end;
function cfColor: TClipboardFormat;
begin
Result := TAppleClipboardCore.cfColor;
end;
function cfPDF: TClipboardFormat;
begin
Result := TAppleClipboardCore.cfPDF;
end;
function cfTGA: TClipboardFormat;
begin
Result := TAppleClipboardCore.cfTGA;
end;
function FindClipboard: TClipboard;
begin
Result := TAppleClipboardCore.FindClipboard;
end;
{ TAppleClipboardCore }
function SetCompareFunc(Str1, Str2: Pointer): Boolean; cdecl;
begin
Result := CFStringCompare(Str1, Str2, kCFCompareCaseInsensitive) = 0;
end;
class constructor TAppleClipboardCore.InitializeClass;
var
Callbacks: CFSetCallBacks;
begin
Callbacks := kCFTypeSetCallBacks;
Callbacks.equal := SetCompareFunc;
FRegisteredTypes := CFSetCreateMutable(nil, 0, @Callbacks);
end;
class destructor TAppleClipboardCore.FinalizeClass;
begin
CFReleaseAndNil(FRegisteredTypes);
FFindClipboard.Free;
end;
function CFStringContains(const StrToSearch, StrToFind: CFStringRef): Boolean; inline;
begin
Result := (CFStringFind(StrToSearch, StrToFind, 0).length > 0);
end;
class function TAppleClipboardCore.SameFormat(const Format1, Format2: TClipboardFormat): Boolean;
begin
if (Format1.Handle = nil) or (Format2.Handle = nil) then Exit(False);
Result := UTTypeEqual(Format1.Handle, Format2.Handle);
if not Result and not Format1.IsUTI and not Format2.IsUTI then
Result := (CFStringCompare(Format1.Handle, Format2.Handle,
kCFCompareCaseInsensitive) = kCFCompareEqualTo);
end;
class procedure TAppleClipboardCore.NewFormatRegistered(const Name: string; const Format: TClipboardFormat);
begin
end;
class procedure TAppleClipboardCore.InitializeFormats(
StdFormatValues: TClipboard.TStdFormatValues; var CustomFormatsSupported: Boolean);
begin
StdFormatValues.cfUTF8Text := RegisterFormatInternal(kUTTypeUTF8PlainText);
StdFormatValues.cfUnicodeText := RegisterFormatInternal(kUTTypeUTF16PlainText);
StdFormatValues.cfRTF := RegisterFormatInternal(kUTTypeRTF);
StdFormatValues.cfGIF := RegisterFormatInternal(kUTTypeGIF);
StdFormatValues.cfJPEG := RegisterFormatInternal(kUTTypeJPEG);
StdFormatValues.cfPNG := RegisterFormatInternal(kUTTypePNG);
StdFormatValues.cfTIFF := RegisterFormatInternal(kUTTypeTIFF);
StdFormatValues.cfFileName := RegisterFormatInternal(kUTTypeFileURL);
StdFormatValues.cfURL := RegisterFormatInternal(kUTTypeURL);
//use UTI format rather than generic defaults taken from the VCL
StdFormatValues.cfComponent := RegisterFormatInternal('com.embarcadero.dfm');
StdFormatValues.cfComponents := RegisterFormatInternal('com.embarcadero.dfms');
cfAppleICNS := RegisterFormatInternal(kUTTypeAppleICNS);
cfPDF := RegisterFormatInternal(kUTTypePDF);
cfTGA := RegisterFormatInternal('com.truevision.tga-image');
CustomFormatsSupported := True;
end;
class function TAppleClipboardCore.IsCompatibleVirtualFileDescriptor(const Descriptor: string;
const SupportedFileExtsOrUTIs: TArray<string>): Boolean;
var
Ext: string;
InUTI, BaseUTI: CFStringRef;
begin
BaseUTI := nil;
InUTI := CFStringCreateWithString(Descriptor);
try
for Ext in SupportedFileExtsOrUTIs do
begin
CFReleaseAndNil(BaseUTI);
if PChar(Ext)^ = '.' then
BaseUTI := CFStringCreateUTIForFileExt(Ext)
else
BaseUTI := CFStringCreateWithString(Ext);
Result := UTTypeConformsTo(InUTI, BaseUTI);
if Result then Exit;
end;
finally
CFReleaseAndNil(InUTI);
end;
Result := False;
end;
class function TAppleClipboardCore.GetFormatName(const Format: TClipboardFormat): string;
begin
Result := CFStringGetValue(CFStringRef(Format));
end;
class function TAppleClipboardCore.GetFormatDescription(const Format: TClipboardFormat): string;
begin
Result := CFStringGetValue(UTTypeCopyDescription(CFStringRef(Format)));
end;
class function TAppleClipboardCore.RegisterFormatInternal(const TypeRef: CFStringRef): TClipboardFormat;
begin
CFSetAddValue(FRegisteredTypes, TypeRef);
Result := TClipboardFormat.Wrap(TypeRef);
end;
class function TAppleClipboardCore.RegisterFormatInternal(const TypeLiteral: MarshaledAString): TClipboardFormat;
begin
Result := RegisterFormatInternal(__CFStringMakeConstantString(TypeLiteral));
end;
class function TAppleClipboardCore.RegisterFormat(const TypeRef: CFStringRef;
TakeOwnership: Boolean): TClipboardFormat;
begin
try
if CFSetGetValueIfPresent(CFSetRef(FRegisteredTypes), TypeRef, @Result) then
Exit;
Result := RegisterFormatInternal(TypeRef);
finally
if TakeOwnership then CFRelease(TypeRef);
end;
NewFormatRegistered(CFStringGetValue(TypeRef), Result);
end;
class function TAppleClipboardCore.RegisterFormat(const Name: string): TClipboardFormat;
begin
Result := RegisterFormat(CFStringCreateWithString(Name), True);
end;
function TAppleClipboardCore.ReadFileNames: TArray<string>;
var
NSArr: NSArray;
URL: NSURL;
Count, I: Integer;
begin
NSArr := GetNSURLs;
if NSArr = nil then Exit(nil);
SetLength(Result, NSArr.count);
Count := 0;
for I := 0 to High(Result) do
begin
URL := TNSURL.Wrap(NSArr.objectAtIndex(I));
if URL.isFileURL then
begin
Result[Count] := NSStringGetValue(URL.path); //!!!may need to switch to using CFURLCopyFileSystemPath
Inc(Count);
end;
end;
SetLength(Result, Count);
end;
function TAppleClipboardCore.ReadURLs: TArray<string>;
var
I: Integer;
NSArr: NSArray;
begin
NSArr := GetNSURLs;
if NSArr = nil then Exit(nil);
SetLength(Result, NSArr.count);
for I := 0 to High(Result) do
Result[I] := NSStringGetValue(TNSURL.Wrap(NSArr.objectAtIndex(I)).absoluteString);
end;
{ TClipboardFormatHelper }
class function TClipboardFormatHelper.Wrap(const PredefinedType: CFStringRef): TClipboardFormat;
begin
Result := TClipboardFormat(PredefinedType);
end;
class function TClipboardFormatHelper.Wrap(const PredefinedType: NSString): TClipboardFormat;
begin
Result := TClipboardFormat((PredefinedType as ILocalObject).GetObjectID);
end;
class function TClipboardFormatHelper.Wrap(const UTI: string): TClipboardFormat;
begin
Result := TAppleClipboardCore.RegisterFormat(UTI);
end;
function TClipboardFormatHelper.GetHandle: CFStringRef;
begin
Result := CFStringRef(Self);
end;
function TClipboardFormatHelper.IsUTI: Boolean;
begin
Result := IsValidUTIString(Handle);
end;
function TClipboardFormatHelper.ToNSString: NSString;
begin
Result := TNSString.Wrap(Handle);
end;
{$IFDEF iOS}
type
{$M+}
IChangeListener = interface(IObjectiveC)
['{7F7F54AE-FECD-4F2A-AEBA-4E2F167CD46F}']
procedure pasteboardChanged(notification: Pointer); cdecl;
end;
TChangeListener = class(TOCLocal, IChangeListener)
strict private
FCallback: TProc;
public
constructor Create(const Callback: TProc);
procedure pasteboardChanged(notification: Pointer); cdecl;
end;
{$M-}
constructor TChangeListener.Create(const Callback: TProc);
begin
inherited Create;
FCallback := Callback;
end;
procedure TChangeListener.pasteboardChanged(notification: Pointer);
begin
FCallback();
end;
{ TiOSClipboardCore }
type
TAdditionalClipboard = class(TClipboard)
public
constructor Create(const MinCoreClass: TiOSClipboardCoreClass;
const Pasteboard: UIPasteboard);
end;
constructor TAdditionalClipboard.Create(const MinCoreClass: TiOSClipboardCoreClass;
const Pasteboard: UIPasteboard);
var
LClass: TiOSClipboardCoreClass;
begin
LClass := TiOSClipboardCoreClass(GetSuitableCoreClass(TiOSClipboardCore));
inherited Create(LClass.Create(Self, Pasteboard));
end;
class function TiOSClipboardCore.CreateClipboardForPasteboard(const Pasteboard: UIPasteboard): TClipboard;
begin
Result := TAdditionalClipboard.Create(Self, Pasteboard);
end;
class function TiOSClipboardCore.ConformingFormat(const FormatToTest, BaseFormat: TClipboardFormat): Boolean;
begin
if (FormatToTest.Handle = nil) or (BaseFormat.Handle = nil) then
Result := False
else
if FormatToTest.IsUTI then
if BaseFormat.IsUTI then
Result := UTTypeConformsTo(FormatToTest.Handle, BaseFormat.Handle)
else
Result := False
else
if BaseFormat.IsUTI then
Result := False
else
Result := SameFormat(FormatToTest, BaseFormat);
end;
{$IF NOT DECLARED(UIPasteboardNameFind)}
const
UIKitFwk = '/System/Library/Frameworks/UIKit.framework/UIKit';
function UIPasteboardNameFind: NSString;
begin
Result := CocoaNSStringConst(UIKitFwk, 'UIPasteboardNameFind');
end;
function UIPasteboardChangedNotification: NSString;
begin
Result := CocoaNSStringConst(UIKitFwk, 'UIPasteboardChangedNotification');
end;
{$IFEND}
class procedure TiOSClipboardCore.InitializeFormats(
StdFormatValues: TClipboard.TStdFormatValues; var CustomFormatsSupported: Boolean);
begin
inherited;
cfColor := RegisterFormatInternal('com.apple.uikit.color');
FFindClipboard := CreateClipboardForPasteboard(
TUIPasteboard.Wrap(TUIPasteboard.OCClass.pasteboardWithName(UIPasteboardNameFind, False)));
end;
constructor TiOSClipboardCore.Create(const AOwner: TClipboard; const ACustomPasteboard: UIPasteboard);
begin
if ACustomPasteboard = nil then
raise EArgumentNilException.CreateRes(@SArgumentNil);
Create(AOwner);
FCustomPasteboard := ACustomPasteboard;
FCustomPasteboard.retain;
end;
destructor TiOSClipboardCore.Destroy;
begin
if FCustomPasteboard <> nil then FCustomPasteboard.release;
inherited;
end;
function TiOSClipboardCore.GetChangeCount: TClipboardChangeCount;
begin
Result := TClipboardChangeCount(Pasteboard.changeCount);
end;
function TiOSClipboardCore.WrapsSystemClipboard: Boolean;
begin
Result := (FCustomPasteboard = nil);
end;
function TiOSClipboardCore.SupportsChangeNotifications: Boolean;
begin
Result := True;
end;
procedure TiOSClipboardCore.EnableChangeNotifications(const Callback: TThreadMethod);
var
NotifyCentre: NSNotificationCenter;
begin
FOnNotifyChanges := Callback;
//god the Objective-C bridge syntax is horrible...
FChangeListener := TNSObject.Wrap(TChangeListener.Create(Callback).GetObjectID);
NotifyCentre := TNSNotificationCenter.Wrap(TNSNotificationCenter.OCClass.defaultCenter);
NotifyCentre.addObserver((FChangeListener as ILocalObject).GetObjectID,
sel_getUid('pasteboardChanged:'),
(UIPasteboardChangedNotification as ILocalObject).GetObjectID,
(Pasteboard as ILocalObject).GetObjectID);
end;
procedure TiOSClipboardCore.DisableChangeNotifications;
begin
FOnNotifyChanges := nil;
TNSNotificationCenter.Wrap(TNSNotificationCenter.OCClass.defaultCenter).removeObserver(
(FChangeListener as ILocalObject).GetObjectID);
FChangeListener.release;
FChangeListener := nil;
end;
function TiOSClipboardCore.GetPasteboard: UIPasteboard;
begin
if FCustomPasteboard = nil then
Result := TUIPasteboard.Wrap(TUIPasteboard.OCClass.generalPasteboard)
else
Result := FCustomPasteboard;
end;
function TiOSClipboardCore.DoOpen: Boolean;
begin
FToAdd := TNSMutableArray.Wrap(CFArrayCreateMutable(nil, 4, nil));
Result := True;
end;
procedure TiOSClipboardCore.DoClear;
begin
Pasteboard.setItems(nil);
FToAdd.removeAllObjects;
FCurrentItem := nil;
end;
procedure TiOSClipboardCore.DoClose;
begin
try
if FToAdd.count <> 0 then Pasteboard.setItems(FToAdd);
finally
FCurrentItem := nil;
FToAdd.release;
FToAdd := nil;
end;
end;
{ reading }
function TiOSClipboardCore.GetNSURLs: NSArray;
begin
Result := Pasteboard.URLs;
end;
function TiOSClipboardCore.ReadBytes(const Format: TClipboardFormat): TBytes;
begin
Result := NSDataToBytes(Pasteboard.dataForPasteboardType(Format.ToNSString));
end;
procedure TiOSClipboardCore.EnumBytes(const Format: TClipboardFormat;
const Callback: TGetBytesCallback);
var
ContinueEnum: Boolean;
Pasteboard: UIPasteboard;
I: Integer;
Values: NSArray;
begin
ContinueEnum := True;
Pasteboard := GetPasteboard;
Values := Pasteboard.dataForPasteboardType(Format.ToNSString, nil);
if Values <> nil then
for I := 0 to Values.count - 1 do
begin
Callback(NSDataToBytes(TNSData.Wrap(Values.objectAtIndex(I))), ContinueEnum);
if not ContinueEnum then Exit;
end;
end;
procedure TiOSClipboardCore.EnumFormatSets(const Callback: TEnumFormatSetsCallback);
var
LookForMore: Boolean;
GetFormatBytes: TFunc<TClipboardFormat, TBytes>;
I: NSUInteger;
Items: NSArray;
Pasteboard: UIPasteboard;
begin
LookForMore := True;
Pasteboard := GetPasteboard;
Items := Pasteboard.pasteboardTypesForItemSet(nil);
if Items = nil then Exit;
GetFormatBytes :=
function (ClipFormat: TClipboardFormat): TBytes
var
DataArr: NSArray;
begin
DataArr := Pasteboard.dataForPasteboardType(ClipFormat.ToNSString,
TNSIndexSet.Wrap(TNSIndexSet.OCClass.indexSetWithIndex(I)));
if (DataArr = nil) or (DataArr.count = 0) then
Result := nil
else
Result := NSDataToBytes(TNSData.Wrap(DataArr.objectAtIndex(0)));
end;
for I := 0 to Items.count - 1 do
begin
Callback(NSArrayToClipboardFormats(TNSArray.Wrap(Items.objectAtIndex(I))),
GetFormatBytes, LookForMore);
if not LookForMore then Break;
end;
GetFormatBytes := nil;
end;
function NSArrayToStrings(const ArrRef: CFArrayRef): TArray<string>; overload;
var
I: Integer;
begin
SetLength(Result, CFArrayGetCount(ArrRef));
for I := 0 to High(Result) do
Result[I] := CFStringGetValue(CFArrayGetValueAtIndex(ArrRef, I));
end;
function NSArrayToStrings(const Arr: NSArray): TArray<string>; overload;
begin
Result := NSArrayToStrings((Arr as ILocalObject).GetObjectID)
end;
function TiOSClipboardCore.ReadPlainText: TArray<string>;
begin
Result := NSArrayToStrings(GetPasteboard.strings);
end;
function TiOSClipboardCore.GetFormats: TArray<TClipboardFormat>;
procedure CanonizeResult;
var
I: Integer;
begin
for I := Low(Result) to High(Result) do
Result[I] := RegisterFormat(Result[I].Handle, False);
end;
var
Dicts: array of CFDictionaryRef;
FormatSet: Pointer;
KeyCount: Integer;
Keys: array of CFStringRef;
I, J: NSUInteger;
Items: NSArray;
Range: NSRange;
SetCallbacks: CFSetCallBacks;
begin
{ UIPasteboard.pasteboardTypes is documented to only return the first item's types.
Which is a pain... }
Items := Pasteboard.items;
Range.location := 0;
Range.length := Items.count;
if Range.length = 0 then Exit(nil);
SetLength(Dicts, Range.length);
Items.getObjects(Dicts, Range);
//if there's only one dictionary then output its keys to Result and exit
if Range.length = 1 then
begin
SetLength(Result, CFDictionaryGetCount(Dicts[0]));
CFDictionaryGetKeysAndValues(Dicts[0], Result, nil);
CanonizeResult;
Exit;
end;
//otherwise build up a set of keys
SetCallbacks := kCFTypeSetCallBacks;
FormatSet := CFSetCreateMutable(nil, 0, @SetCallbacks);
for I := 0 to Range.length - 1 do
begin
KeyCount := CFDictionaryGetCount(Dicts[I]);
if Length(Keys) < KeyCount then
begin
Keys := nil;
SetLength(Keys, KeyCount);
end;
CFDictionaryGetKeysAndValues(Dicts[I], Keys, nil);
for J := 0 to KeyCount - 1 do
CFSetAddValue(FormatSet, Keys[J]);
end;
//get the combined list
SetLength(Result, CFSetGetCount(FormatSet));
CFSetGetValues(FormatSet, Result);
CanonizeResult;
end;
function TiOSClipboardCore.HasFormat(Format: TClipboardFormat): Boolean;
begin
Result := Pasteboard.containsPasteboardTypes(ClipboardFormatsToNSArray([Format]), nil)
end;
function TiOSClipboardCore.HasFormat(const Formats: array of TClipboardFormat;
var Matched: TClipboardFormat): Boolean;
var
DictRef: CFDictionaryRef;
Key, Possible: TClipboardFormat;
Keys: array of TClipboardFormat;
Indices: NSIndexSet;
Pasteboard: UIPasteboard;
begin
Pasteboard := GetPasteboard;
Indices := Pasteboard.itemSetWithPasteboardTypes(ClipboardFormatsToNSArray(Formats));
if (Indices = nil) or (Indices.count = 0) then Exit(False);
DictRef := Pasteboard.items.objectAtIndex(Indices.firstIndex);
SetLength(Keys, CFDictionaryGetCount(DictRef));
CFDictionaryGetKeysAndValues(DictRef, Keys, nil);
for Key in Keys do
for Possible in Formats do
if Key = Possible then
begin
Matched := Possible;
Result := True;
Exit;
end;
Result := False;
end;
{ writing }
procedure TiOSClipboardCore.NeedItem(const NewIfHasFormat: array of TClipboardFormat);
var
F: TClipboardFormat;
ID: Pointer;
begin
if FCurrentItem <> nil then
begin
for F in NewIfHasFormat do
if FCurrentItem.objectForKey(CFStringRef(F)) <> nil then
begin
FCurrentItem := nil;
Break;
end;
if FCurrentItem <> nil then Exit;
end;
ID := TNSMutableDictionary.OCClass.dictionaryWithCapacity(Min(1, Length(NewIfHasFormat)));
FToAdd.addObject(ID);
FCurrentItem := TNSMutableDictionary.Wrap(ID);
end;
procedure TiOSClipboardCore.NewFormatSet;
begin
FCurrentItem := nil;
end;
procedure TiOSClipboardCore.AssignNSObject(const Format: TClipboardFormat; const ObjID: Pointer);
begin
NeedItem([Format]);
FCurrentItem.setObject(ObjID, CFStringRef(Format));
end;
procedure TiOSClipboardCore.WriteBytes(const Format: TClipboardFormat;
const Renderer: TFunc<TBytes>; PreferDelayed: Boolean);
var
Bytes: TBytes;
begin
Bytes := Renderer;
AssignNSObject(Format, TNSData.OCClass.dataWithBytes(Bytes, Length(Bytes)));
end;
procedure TiOSClipboardCore.WriteFileName(const Renderer: TFunc<TFileName>; PreferDelayed: Boolean);
begin
AssignNSObject(cfFileName, TNSURL.OCClass.fileURLWithPath(StrToNSString(Renderer)));
end;
procedure TiOSClipboardCore.WritePlainText(const Renderer: TFunc<string>; PreferDelayed: Boolean);
var
S: string;
begin
S := Renderer;
AssignNSObject(cfUTF8Text, TNSString.OCClass.stringWithCharacters(PChar(S), Length(S)));
end;
procedure TiOSClipboardCore.WriteURL(const Renderer: TFunc<string>; PreferDelayed: Boolean);
begin
AssignNSObject(cfURL, TNSURL.OCClass.URLWithString(StrToNSString(Renderer)));
end;
{$ELSE}
function MakeFileURLPromiseFunc(const Pasteboard: NSPasteboard;
const Details: TVirtualFileDetails; const RenderProc: TProc<TStream>): TGetPasteboardDataEvent;
var
LDetails: TVirtualFileDetails;
begin
LDetails := Details;
Result :=
procedure (const NSType: NSString; const Item: NSPasteboardItem)
var
CBoard: PasteboardRef;
DestPath, DestName, DestExt, FullName: string;
CFStr: CFStringRef;
I: Integer;
Stream: TFileStream;
URL: CFURLRef;
begin
CBoard := nil;
OSStatusCheck(PasteboardCreate((Pasteboard.name as ILocalObject).GetObjectID, CBoard));
try
OSStatusCheck(PasteboardSynchronize(CBoard));
{ Allow for the paste location not being set to support ResolveOutstandingPromisesToOS }
if PasteboardCopyPasteLocation(CBoard, URL) <> 0 then
URL := nil;
CFStr := nil;
try
if URL = nil then
DestPath := IncludeTrailingPathDelimiter(TPath.GetTempPath)
else
begin
{ Path returned from Finder will be a 'file ref' rather than a POSIX-style path;
CFURLCopyFileSystemPath will convert accordingly }
CFStr := CFURLCopyFileSystemPath(URL, kCFURLPOSIXPathStyle);
DestPath := IncludeTrailingPathDelimiter(CFStringGetValue(CFStr));
CFReleaseAndNil(CFStr);
end;
DestName := ChangeFileExt(ExtractFileName(LDetails.FileName), '');
DestExt := ExtractFileExt(LDetails.FileName);