-
-
Notifications
You must be signed in to change notification settings - Fork 131
/
FMX.Skia.Canvas.pas
4043 lines (3688 loc) · 135 KB
/
FMX.Skia.Canvas.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
{************************************************************************}
{ }
{ Skia4Delphi }
{ }
{ Copyright (c) 2021-2024 Skia4Delphi Project. }
{ }
{ Use of this source code is governed by the MIT license that can be }
{ found in the LICENSE file. }
{ }
{************************************************************************}
unit FMX.Skia.Canvas;
interface
{$SCOPEDENUMS ON}
{$IF (CompilerVersion < 35) or ((CompilerVersion = 35) and not DECLARED(RTLVersion111))}
{$DEFINE MODULATE_CANVAS}
{$ENDIF}
uses
{ Delphi }
FMX.Graphics,
FMX.TextLayout,
FMX.Types,
System.Classes,
System.Generics.Defaults,
System.Math.Vectors,
System.Messaging,
System.SysUtils,
System.Types,
System.UITypes,
{ Skia }
System.Skia;
type
ESkCanvas = class(Exception);
EGrCanvas = class(ESkCanvas);
{ ISkCanvasWrapper }
/// <summary>
/// Wrapper for encapsulating a <c>ISkCanvas</c> in a <c>TCanvas</c>.
/// Numerous Skia features return the <c>ISkCanvas</c>, and with the
/// assistance of this wrapper, any class can be transformed into a
/// <c>TCanvas</c>. This enables the utilization of highly useful functions,
/// such as <b>PaintTo</b> of <c>TControl</c>.
/// </summary>
ISkCanvasWrapper = interface
['{C9CDCC18-9C92-4F45-98FE-E3F5E60A397D}']
function CanvasBegin(const ACanvas: TCanvas): ISkCanvas;
procedure CanvasEnd;
function GetCanvasHeight: Integer;
function GetCanvasScale: Single;
function GetCanvasWidth: Integer;
property CanvasHeight: Integer read GetCanvasHeight;
property CanvasScale: Single read GetCanvasScale;
property CanvasWidth: Integer read GetCanvasWidth;
end;
{ TSkCanvasCustom }
TSkCanvasCustom = class(TCanvas{$IFDEF MODULATE_CANVAS}, IModulateCanvas{$ENDIF})
strict private type
TSaveState = class(TCanvasSaveState)
strict protected
procedure AssignTo(ADest: TPersistent); override;
public
procedure Assign(ASource: TPersistent); override;
end;
strict protected type
TBrushData = record
Brush: TBrush;
Paint: ISkPaint;
BitmapMapped: Boolean;
BitmapData: TBitmapData;
end;
{$IFDEF MODULATE_CANVAS}
strict private
FModulateColor: TAlphaColor;
function GetModulateColor: TAlphaColor;
procedure SetModulateColor(const AColor: TAlphaColor);
{$ENDIF}
strict private
FCanvas: ISkCanvas;
FContextHandle: THandle;
procedure BeginPaint(const ARect: TRectF; const AOpacity: Single; var ABrushData: TBrushData);
strict protected
FAntiAlias: Boolean;
FWrapper: ISkCanvasWrapper;
constructor CreateFromPrinter(const APrinter: TAbstractPrinter); override;
// Since FMX effects use TContext3D, on systems using OpenGLES it makes the
// current context the context it created, and does not revert to the old
// one after it has finished its task.
procedure BeforeRestore; virtual;
function BeginCanvas(const AContextHandle: THandle): ISkCanvas; virtual;
function BeginPaintWithBrush(const ABrush: TBrush; const ARect: TRectF; const AOpacity: Single; out ABrushData: TBrushData): TSkPaint;
function BeginPaintWithStrokeBrush(const ABrush: TStrokeBrush; const ARect: TRectF; const AOpacity: Single; out ABrushData: TBrushData): TSkPaint;
function CreateSaveState: TCanvasSaveState; override;
function DoBeginScene({$IF CompilerVersion < 35}const {$ENDIF}AClipRects: PClipRects = nil; AContextHandle: THandle = 0): Boolean; override; final;
{$IF CompilerVersion >= 35}
procedure DoClear(const AColor: TAlphaColor); override;
procedure DoClearRect(const ARect: TRectF; const AColor: TAlphaColor = 0); override;
{$ENDIF}
procedure DoDrawBitmap(const ABitmap: TBitmap; const ASrcRect, ADestRect: TRectF; const AOpacity: Single; const AHighSpeed: Boolean); override;
procedure DoDrawEllipse(const ARect: TRectF; const AOpacity: Single; const ABrush: TStrokeBrush); override;
procedure DoDrawLine(const APoint1, APoint2: TPointF; const AOpacity: Single; const ABrush: TStrokeBrush); override;
procedure DoDrawPath(const APath: TPathData; const AOpacity: Single; const ABrush: TStrokeBrush); override;
procedure DoDrawRect(const ARect: TRectF; const AOpacity: Single; const ABrush: TStrokeBrush); override;
procedure DoEndScene; override; final;
procedure DoFillEllipse(const ARect: TRectF; const AOpacity: Single; const ABrush: TBrush); override;
procedure DoFillPath(const APath: TPathData; const AOpacity: Single; const ABrush: TBrush); override;
procedure DoFillRect(const ARect: TRectF; const AOpacity: Single; const ABrush: TBrush); override;
{$IF CompilerVersion >= 30}
procedure DoSetMatrix(const AMatrix: TMatrix); override;
{$ENDIF}
procedure EndCanvas(const AContextHandle: THandle); virtual;
procedure EndPaint(var ABrushData: TBrushData);
function GetCachedImage(const ABitmap: TBitmap): TSkImage; virtual;
function GetCanvasScale: Single; override;
function GetSamplingOptions(const AHighSpeed: Boolean = False): TSkSamplingOptions; inline;
procedure Resized; virtual;
function SupportsCachedImage: Boolean; virtual;
class procedure DoFinalizeBitmap(var ABitmapHandle: THandle); override;
class function DoInitializeBitmap(const AWidth, AHeight: Integer; const AScale: Single; var APixelFormat: TPixelFormat): THandle; override;
class function DoMapBitmap(const ABitmapHandle: THandle; const AAccess: TMapAccess; var ABitmapData: TBitmapData): Boolean; override;
class procedure DoUnmapBitmap(const ABitmapHandle: THandle; var ABitmapData: TBitmapData); override;
public
constructor Wrap(const AWrapper: ISkCanvasWrapper);
destructor Destroy; override;
procedure AfterConstruction; override;
{$IF CompilerVersion < 35}
procedure Clear(const AColor: TAlphaColor); override;
procedure ClearRect(const ARect: TRectF; const AColor: TAlphaColor = 0); override;
{$ENDIF}
procedure ExcludeClipRect(const ARect: TRectF); override;
procedure IntersectClipRect(const ARect: TRectF); override;
function LoadFontFromStream(const AStream: TStream): Boolean; override;
function PtInPath(const APoint: TPointF; const APath: TPathData): Boolean; override;
{$IF CompilerVersion < 30}
procedure SetMatrix(const AMatrix: TMatrix); override;
{$ENDIF}
property Canvas: ISkCanvas read FCanvas;
procedure SetSize(const AWidth, AHeight: Integer); override; final;
class function GetCanvasStyle: TCanvasStyles; override;
class function QualityToSamplingOptions(const AQuality: TCanvasQuality; const AHighSpeed: Boolean = False): TSkSamplingOptions;
end;
TSkCanvasCustomClass = class of TSkCanvasCustom;
{ TSkBitmapHandle }
TSkBitmapHandle = class
private
FPixels: Pointer;
strict private
FHeight: Integer;
FPixelFormat: TPixelFormat;
FWidth: Integer;
public
constructor Create(const AWidth, AHeight: Integer; const APixelFormat: TPixelFormat);
destructor Destroy; override;
property Height: Integer read FHeight;
property PixelFormat: TPixelFormat read FPixelFormat;
property Pixels: Pointer read FPixels;
property Width: Integer read FWidth;
end;
{ TSkCanvasBase }
TSkCanvasBase = class abstract(TSkCanvasCustom)
strict private
FBitmapSurface: ISkSurface;
FSurface: TSkSurface;
strict protected
{$IFDEF MSWINDOWS}
constructor CreateFromWindow(const AParent: TWindowHandle; const AWidth, AHeight: Integer; const AQuality: TCanvasQuality = TCanvasQuality.SystemDefault); override;
{$ENDIF}
function BeginCanvas(const AContextHandle: THandle): ISkCanvas; override;
procedure EndCanvas(const AContextHandle: THandle); override;
function GetSurfaceFromWindow(const AContextHandle: THandle): TSkSurface; virtual; abstract;
{$IFDEF MSWINDOWS}
procedure Resized; override;
{$ENDIF}
procedure SwapBuffers(const AContextHandle: THandle); virtual;
class function CreateBitmap(const AWidth, AHeight: Integer; const APixelFormat: TPixelFormat): TSkBitmapHandle; virtual;
class procedure DoFinalizeBitmap(var ABitmapHandle: THandle); override;
class function DoInitializeBitmap(const AWidth, AHeight: Integer; const AScale: Single; var APixelFormat: TPixelFormat): THandle; override;
class function DoMapBitmap(const ABitmapHandle: THandle; const AAccess: TMapAccess; var ABitmapData: TBitmapData): Boolean; override;
class procedure DoUnmapBitmap(const ABitmapHandle: THandle; var ABitmapData: TBitmapData); override;
end;
TSkCanvasBaseClass = class of TSkCanvasBase;
TGrBeforeSharedContextDestructionMessage = class(TMessage);
{ IGrSharedContext }
/// <summary>
/// GPU shared context for utilization among multiple threads and windows.
/// </summary>
/// <remarks>
/// This is designed to be created once per application after the first
/// canvas is created from a window by the main thread. Prior to its
/// destruction, the main thread will send the message
/// <c>TGrBeforeSharedContextDestructionMessage</c>, at this point, all
/// shared context resources should be released, and it is recommended to
/// release all Skia-related resources as well.
/// </remarks>
IGrSharedContext = interface
['{8C8A3BD1-43AC-4872-B254-F38630F81395}']
procedure BeginContext;
procedure EndContext;
function GetGrDirectContext: TGrDirectContext;
function GetTextureColorType: TSkColorType;
function GetTextureOrigin: TGrSurfaceOrigin;
// Currently, this function is only significant when using an OpenGL
// backend, as it updates the current context of the thread to the shared
// context when working with multiple contexts.
procedure RefreshContext;
/// <summary>Direct access to the shared GPU context.</summary>
/// <remarks>
/// This property can only be used between the <b>BeginContext</b> and
/// <b>EndContext</b> call.
/// </remarks>
property GrDirectContext: TGrDirectContext read GetGrDirectContext;
/// <summary>Color type for use in texture creation.</summary>
property TextureColorType: TSkColorType read GetTextureColorType;
/// <summary>Surface origin for use in texture creation.</summary>
property TextureOrigin: TGrSurfaceOrigin read GetTextureOrigin;
end;
TGrBitmapHandle = class;
{ TGrSharedContext }
TGrSharedContext = class abstract(TInterfacedObject, IGrSharedContext)
strict private
function GetGrDirectContext: TGrDirectContext;
strict protected
FGrDirectContext: IGrDirectContext;
procedure BeginContext; virtual;
procedure DestroyContext; virtual;
procedure EndContext; virtual;
function GetTextureColorType: TSkColorType; virtual; abstract;
function GetTextureOrigin: TGrSurfaceOrigin; virtual; abstract;
procedure RefreshContext; virtual;
public
constructor Create;
destructor Destroy; override;
procedure FinalizeTextureCache(const ABitmap: TGrBitmapHandle); virtual;
procedure InitializeTextureCache(const ABitmap: TGrBitmapHandle); virtual;
property GrDirectContext: IGrDirectContext read FGrDirectContext;
end;
{ TGrBitmapHandle }
TGrBitmapHandle = class(TSkBitmapHandle)
private
FSharedContext: IGrSharedContext;
strict private
FCache: ISkImage;
public
property Cache: ISkImage read FCache write FCache;
property SharedContext: IGrSharedContext read FSharedContext;
end;
/// <summary>
/// To be used in conjunction with the <c>ISkCanvasWrapper</c>, indicating
/// the use of the shared context (e.g. when drawing on textures).
/// </summary>
/// <remarks>
/// Utilize the <b>DefaultSkiaRenderCanvasClass</b> function to obtain the
/// default registered Skia canvas class, and subsequently call the
/// <b>Wrap</b> function.
/// </remarks>
IGrCanvasWrapper = interface
['{D3381B1A-06FD-4DB2-A09A-330D49BD34A7}']
end;
{ TGrCanvas }
TGrCanvas = class abstract(TSkCanvasBase)
strict private class var
FInitialized: Boolean;
FSharedContext: IGrSharedContext;
strict protected
FGrDirectContext: IGrDirectContext;
constructor CreateFromWindow(const AParent: TWindowHandle; const AWidth, AHeight: Integer; const AQuality: TCanvasQuality = TCanvasQuality.SystemDefault); override;
function BeginCanvas(const AContextHandle: THandle): ISkCanvas; override;
function CreateSharedContext: IGrSharedContext; virtual; abstract;
procedure EndCanvas(const AContextHandle: THandle); override;
function GetCachedImage(const ABitmap: TBitmap): TSkImage; override; final;
function SupportsCachedImage: Boolean; override;
class function CreateBitmap(const AWidth, AHeight: Integer; const APixelFormat: TPixelFormat): TSkBitmapHandle; override;
class function DoMapBitmap(const ABitmapHandle: THandle; const AAccess: TMapAccess; var ABitmapData: TBitmapData): Boolean; override;
class procedure DoFinalizeBitmap(var ABitmapHandle: THandle); override;
public
/// <summary>Direct access to the GPU context.</summary>
/// <remarks>
/// This property can only be used between the <b>BeginScene</b> and
// <b>EndScene</b> call.
/// </remarks>
property GrDirectContext: IGrDirectContext read FGrDirectContext;
/// <summary>
/// Indicates in a thread-safe manner whether the shared context has been
/// initialized.
/// </summary>
/// <remarks>
/// The shared context is initialized once a canvas is created from a
/// window via the main thread. If initialized, the <b>SharedContext</b>
/// property is accessible and not nil.
/// </remarks>
class property Initialized: Boolean read FInitialized;
/// <summary>
/// Shared context for utilization across multiple windows and/or threads.
/// </summary>
/// <remarks>
/// If the shared context has not been initialized, the property will
/// return nil. To check the initialization status, use the
/// <b>Initialized</b> property.
/// </remarks>
class property SharedContext: IGrSharedContext read FSharedContext;
end;
TGrCanvasClass = class of TGrCanvas;
{ TSkTextLayout }
TSkTextLayout = class(TTextLayout)
{$REGION ' - Workaround RSP-36975'}
// - -------------------------------------------------------------------------
// - WORKAROUND
// - -------------------------------------------------------------------------
// -
// - Description:
// - This code is a workaround intended to fix a bug involving the
// - TContextMetal.DoCopyToBits.
// -
// - Bug report:
// - https://quality.embarcadero.com/browse/RSP-36975
// -
// - -------------------------------------------------------------------------
{$IF (CompilerVersion < 35) or ((CompilerVersion = 35) and NOT DECLARED(RTLVersion113))}
strict private type
TRSP36975Workaround = record
strict private
FIgnoreNeedUpdate: Boolean;
public
procedure Apply(const ATextLayout: TTextLayout); inline;
property IgnoreNeedUpdate: Boolean read FIgnoreNeedUpdate;
end;
{$ENDIF}
// - -------------------------------------------------------------------------
{$ENDREGION}
{$REGION ' - Workaround RSP-38480'}
// - -------------------------------------------------------------------------
// - WORKAROUND
// - -------------------------------------------------------------------------
// -
// - Description:
// - This code is a workaround intended to fix a bug involving the
// - TContextMetal.DoCopyToBits.
// -
// - Bug report:
// - https://quality.embarcadero.com/browse/RSP-38480
// -
// - -------------------------------------------------------------------------
{$IF (CompilerVersion < 35) or ((CompilerVersion = 35) and NOT DECLARED(RTLVersion112))}
strict private type
TRSP38480Workaround = record
class procedure Apply(var AText: string); static; inline;
end;
{$ENDIF}
// - -------------------------------------------------------------------------
{$ENDREGION}
strict private type
TParagraph = record
Bounds: TRectF;
Index: Integer;
Offset: TPointF;
Paragraph: ISkParagraph;
Range: TTextRange;
end;
TGraphemesMap = record
strict private
FCharIndexInGrapheme: TBytes;
FText: string;
function CreateGraphemesMapping(const AText: string): TBytes;
procedure SetText(const AText: string); inline;
public
procedure FindNextGraphemeBoundary(var AIndex: Integer); inline;
procedure FindPreviousGraphemeBoundary(var AIndex: Integer); inline;
property Text: string read FText write SetText;
end;
strict private class var
FAttributesRangeComparer: IComparer<TTextAttributedRange>;
FParagraphTextRangeComparer: IComparer<TParagraph>;
private
class procedure Initialize;
strict private
FColor: TAlphaColor;
FGraphemesMap: TGraphemesMap;
FMaxLines: Integer;
FOpacity: Single;
FParagraphs: TArray<TParagraph>;
{$IF DECLARED(TRSP36975Workaround))}
FRSP36975Workaround: TRSP36975Workaround;
{$ENDIF}
FTextRect: TRectF;
function GetParagraphsInRange(const APos, ALength: Integer): TArray<TParagraph>;
function NeedHorizontalAlignment: Boolean;
procedure SetMaxLines(AValue: Integer);
procedure UpdateParagraph;
class constructor Create;
strict protected
procedure DoDrawLayout(const ACanvas: TCanvas); overload; override;
procedure DoDrawLayout(const ACanvas: ISkCanvas); reintroduce; overload;
function DoPositionAtPoint(const APoint: TPointF): Integer; override;
function DoRegionForRange(const ARange: TTextRange): TRegion; override;
procedure DoRenderLayout; override;
function GetTextHeight: Single; override;
function GetTextRect: TRectF; override;
function GetTextWidth: Single; override;
public
constructor Create(const ACanvas: TCanvas = nil); override;
destructor Destroy; override;
procedure ConvertToPath(const APath: TPathData); override;
procedure RenderLayout(const ACanvas: ISkCanvas); overload;
/// <summary>
/// Max lines allowed in text. When zero (default) it is unlimited.
/// </summary>
property MaxLines: Integer read FMaxLines write SetMaxLines;
end;
/// <summary>Get the registered default Skia canvas class.</summary>
/// <returns>
/// Nil if the Skia canvas class has not been registered or if Skia has not
// been selected as the default canvas; otherwise it returns the registered
/// Skia canvas class.
/// </returns>
function DefaultSkiaRenderCanvasClass: TSkCanvasBaseClass;
procedure RegisterSkiaRenderCanvas(const ACanvasClass: TSkCanvasBaseClass; const APriority: Boolean; const AIsSupportedFunc: TFunc<Boolean> = nil);
const
CanvasQualitySampleCount: array[TCanvasQuality] of Integer = (2, 1, 4);
resourcestring
SVWEBPImages = 'WebP Images';
SVWBMPImages = 'WBMP Images';
SVRawCanon = 'Raw Canon';
SVRawDNG = 'Raw Adobe DNG Digital Negative';
SVRawNikon = 'Raw Nikon';
SVRawORF = 'Raw Olympus ORF';
SVRawPanasonic = 'Raw Panasonic';
SVRawPEF = 'Raw Pentax PEF';
SVRawRAF = 'Raw Fujifilm RAF';
SVRawSony = 'Raw Sony';
SVRawSRW = 'Raw Samsung SRW';
implementation
{$IF CompilerVersion >= 36}
{$DEFINE SKIA_ANIMATED_CODEC}
{$DEFINE SKIA_FILTER}
{$DEFINE SKIA_PRINTER}
{$DEFINE SKIA_VULKAN}
{$ENDIF}
{$IF DEFINED(LINUX) or (DEFINED(MACOS) and NOT DEFINED(IOS)) or DEFINED(MSWINDOWS)}
{$DEFINE SKIA_RASTER}
{$ENDIF}
uses
{ Delphi }
FMX.Consts,
FMX.Forms,
FMX.Platform,
FMX.Printer,
FMX.Surfaces,
{$IF DEFINED(LINUX)}
FMUX.Api,
{$ELSEIF DEFINED(MACOS) and NOT DEFINED(IOS)}
Macapi.CocoaTypes,
Macapi.CoreGraphics,
{$ELSEIF DEFINED(MSWINDOWS)}
FMX.Platform.Win,
Winapi.Windows,
{$ENDIF}
System.Generics.Collections,
System.IOUtils,
System.Math,
System.UIConsts,
{ Workarounds }
{$IF DEFINED(MACOS)}
FMX.Context.Metal,
FMX.Types3D,
FMX.Utils,
Macapi.Metal,
Macapi.MetalKit,
Posix.SysMman,
Posix.Unistd,
System.Rtti,
{$IFDEF IOS}
FMX.Context.GLES,
FMX.Controls,
FMX.Helpers.iOS,
FMX.MediaLibrary,
FMX.MediaLibrary.IOS,
iOSapi.AssetsLibrary,
iOSapi.CocoaTypes,
iOSapi.CoreGraphics,
iOSapi.Foundation,
iOSapi.OpenGLES,
iOSapi.UIKit,
Macapi.Helpers,
Macapi.ObjectiveC,
{$ENDIF}
{$ELSEIF DEFINED(ANDROID)}
FMX.Context.GLES,
FMX.Types3D,
FMX.Utils,
Androidapi.Gles2,
Posix.SysMman,
Posix.Unistd,
System.Rtti,
{$ENDIF}
{ Skia }
FMX.Skia,
{$IFDEF SKIA_ANIMATED_CODEC}
FMX.Skia.AnimatedCodec,
{$ENDIF}
{$IFDEF SKIA_FILTER}
FMX.Skia.Filter,
{$ENDIF}
{$IFDEF SKIA_PRINTER}
FMX.Skia.Printer,
{$ENDIF}
{$IFDEF SKIA_VULKAN}
FMX.Skia.Canvas.Vulkan,
{$ENDIF}
FMX.Skia.Canvas.GL,
FMX.Skia.Canvas.Metal,
System.Skia.API;
{$REGION ' - Workaround RSP-36957'}
// - ---------------------------------------------------------------------------
// - WORKAROUND
// - ---------------------------------------------------------------------------
// -
// - Description:
// - This code is a workaround intended to fix a bug involving the
// - TCustomContextOpenGL.DoCopyToBits.
// -
// - Bug report:
// - https://quality.embarcadero.com/browse/RSP-36957
// -
// - ---------------------------------------------------------------------------
{$IF (CompilerVersion < 35) or ((CompilerVersion = 35) and not DECLARED(RTLVersion112))}
{$IF DEFINED(ANDROID) or DEFINED(IOS)}
type
{ TRSP36957Workaround }
TRSP36957Workaround = record
private type
{$RTTI EXPLICIT METHODS([vcProtected])}
TContextOpenGLPatch = class(TCustomContextOpenGL)
protected
procedure DoCopyToBits(const Bits: Pointer; const Pitch: Integer; const ARect: TRect); override;
end;
{$RTTI METHODS([vcPublic, vcPublished])}
public
class procedure Apply; static;
end;
{ TRSP36957Workaround }
class procedure TRSP36957Workaround.Apply;
function HookVMT(const AVMTEntry, ATargetAddress: Pointer): Boolean;
var
LOriginEnd: Pointer;
LOriginStart: Pointer;
LPageSize: Integer;
LTargetEnd: Pointer;
LTargetStart: Pointer;
begin
LPageSize := sysconf(_SC_PAGESIZE);
LOriginStart := Pointer(NativeUInt(AVMTEntry) and not (LPageSize - 1));
LOriginEnd := Pointer((NativeUInt(AVMTEntry) + SizeOf(Pointer) + Cardinal(LPageSize) - 1) and not (LPageSize - 1));
LTargetStart := Pointer(NativeUInt(ATargetAddress) and not (LPageSize - 1));
LTargetEnd := Pointer((NativeUInt(ATargetAddress) + SizeOf(Pointer) + Cardinal(LPageSize) - 1) and not (LPageSize - 1));
Result := (mprotect(LOriginStart, PByte(LOriginEnd) - PByte(LOriginStart), PROT_READ or PROT_WRITE) = 0) and (mprotect(LTargetStart, PByte(LTargetEnd) - PByte(LTargetStart), PROT_READ or PROT_WRITE) = 0);
if Result then
PPointer(AVMTEntry)^ := PPointer(ATargetAddress)^;
end;
function TryGetVMT(const AClass: TClass; const AMethodName: string; out AVMT: Integer): Boolean;
var
LRttiContext: TRttiContext;
LRttiMethod: TRttiMethod;
begin
LRttiContext := TRttiContext.Create;
try
LRttiMethod := LRttiContext.GetType(AClass).AsInstance.GetMethod(AMethodName);
Result := Assigned(LRttiMethod);
if Result then
AVMT := LRttiMethod.VirtualIndex * SizeOf(Pointer);
finally
LRttiContext.Free;
end;
end;
var
LVMT: Integer;
begin
if TContextManager.DefaultContextClass.InheritsFrom(TCustomContextOpenGL) and TryGetVMT(TContextOpenGLPatch, 'DoCopyToBits', LVMT) then
HookVMT(PByte(TContextManager.DefaultContextClass) + LVMT, PByte(TContextOpenGLPatch) + LVMT);
end;
{ TRSP36957Workaround.TContextOpenGLPatch }
procedure TRSP36957Workaround.TContextOpenGLPatch.DoCopyToBits(
const Bits: Pointer; const Pitch: Integer; const ARect: TRect);
var
I: Integer;
OldFBO: GLuint;
BitmapBuffer: PAlphaColorArray;
BitmapBufferLen: Integer;
Rect: TRect;
begin
if Valid then
begin
BitmapBufferLen := Width * Height * 4;
GetMem(BitmapBuffer, BitmapBufferLen);
try
if FFrameBuf <> 0 then
begin
glGetIntegerv(GL_FRAMEBUFFER_BINDING, @OldFBO);
glBindFramebuffer(GL_FRAMEBUFFER, FFrameBuf);
end;
glReadPixels(0, 0, Width, Height, GL_RGBA, GL_UNSIGNED_BYTE, BitmapBuffer);
Rect := TRect.Intersect(ARect, TRect.Create(0, 0, Width, Height));
for I := Rect.Top to Rect.Bottom - 1 do
Move(BitmapBuffer[(Height - 1 - I) * Width + Rect.Left], PAlphaColorArray(Bits)[I * (Pitch div 4) + Rect.Left],
Rect.Width * 4);
if FFrameBuf <> 0 then
glBindFramebuffer(GL_FRAMEBUFFER, OldFBO);
finally
FreeMem(BitmapBuffer);
end;
{$IF CompilerVersion < 34}
if GLHasAnyErrors then
RaiseContextExceptionFmt(@SErrorInContextMethod, ['DoCopyBits']);
{$ELSE}
TGlesDiagnostic.RaiseIfHasError(@SErrorInContextMethod, ['DoCopyBits']);
{$ENDIF}
end;
end;
{$ENDIF}
{$ENDIF}
// - ---------------------------------------------------------------------------
{$ENDREGION}
{$REGION ' - Workaround RSP-37147'}
// - ---------------------------------------------------------------------------
// - WORKAROUND
// - ---------------------------------------------------------------------------
// -
// - Description:
// - This code is a workaround intended to fix a bug involving the
// - TContextMetal.DoCopyToBits.
// -
// - Bug report:
// - https://quality.embarcadero.com/browse/RSP-37147
// -
// - ---------------------------------------------------------------------------
{$IF (CompilerVersion < 35) or ((CompilerVersion = 35) and not DECLARED(RTLVersion112))}
{$IFDEF MACOS}
type
{ TRSP37147Workaround }
TRSP37147Workaround = record
private type
{$RTTI EXPLICIT METHODS([vcProtected])}
TContextMetalPatch = class(TCustomContextMetal)
protected
FPipelineStateConfiguration: TPipelineStateConfiguration;
FDepthStencilStateConfiguration: TDepthStencilStateConfiguration;
FCommandQueue: MTLCommandQueue;
FCommandBuffer: MTLCommandBuffer;
FRenderPassDescriptor: MTLRenderPassDescriptor;
FRenderCommandEncoder: MTLRenderCommandEncoder;
FCurrentDrawable: CAMetalDrawable;
FOnScreenTexture: MTLTexture;
FStencilReferenceValue: LongWord;
FSampleCount: NSUInteger;
procedure DoCopyToBits(const Bits: Pointer; const Pitch: Integer; const ARect: TRect); override;
end;
{$RTTI METHODS([vcPublic, vcPublished])}
public
class procedure Apply; static;
end;
{ TRSP37147Workaround }
class procedure TRSP37147Workaround.Apply;
function HookVMT(const AVMTEntry, ATargetAddress: Pointer): Boolean;
var
LOriginEnd: Pointer;
LOriginStart: Pointer;
LPageSize: Integer;
LTargetEnd: Pointer;
LTargetStart: Pointer;
begin
LPageSize := sysconf(_SC_PAGESIZE);
LOriginStart := Pointer(NativeUInt(AVMTEntry) and not (LPageSize - 1));
LOriginEnd := Pointer((NativeUInt(AVMTEntry) + SizeOf(Pointer) + Cardinal(LPageSize) - 1) and not (LPageSize - 1));
LTargetStart := Pointer(NativeUInt(ATargetAddress) and not (LPageSize - 1));
LTargetEnd := Pointer((NativeUInt(ATargetAddress) + SizeOf(Pointer) + Cardinal(LPageSize) - 1) and not (LPageSize - 1));
Result := (mprotect(LOriginStart, PByte(LOriginEnd) - PByte(LOriginStart), PROT_READ or PROT_WRITE) = 0) and (mprotect(LTargetStart, PByte(LTargetEnd) - PByte(LTargetStart), PROT_READ or PROT_WRITE) = 0);
if Result then
PPointer(AVMTEntry)^ := PPointer(ATargetAddress)^;
end;
function TryGetVMT(const AClass: TClass; const AMethodName: string; out AVMT: Integer): Boolean;
var
LRttiContext: TRttiContext;
LRttiMethod: TRttiMethod;
begin
LRttiContext := TRttiContext.Create;
try
LRttiMethod := LRttiContext.GetType(AClass).AsInstance.GetMethod(AMethodName);
Result := Assigned(LRttiMethod);
if Result then
AVMT := LRttiMethod.VirtualIndex * SizeOf(Pointer);
finally
LRttiContext.Free;
end;
end;
var
LVMT: Integer;
begin
if TContextManager.DefaultContextClass.InheritsFrom(TCustomContextMetal) and TryGetVMT(TContextMetalPatch, 'DoCopyToBits', LVMT) then
HookVMT(PByte(TContextManager.DefaultContextClass) + LVMT, PByte(TContextMetalPatch) + LVMT);
end;
{ TRSP37147Workaround.TContextMetalPatch }
procedure TRSP37147Workaround.TContextMetalPatch.DoCopyToBits(
const Bits: Pointer; const Pitch: Integer; const ARect: TRect);
function CreateRegion(const ARect: TRect; const AScale: Single): MTLRegion;
begin
if SameValue(AScale, 1, TEpsilon.Scale) then
begin
Result.origin.x := ARect.left;
Result.origin.y := ARect.top;
Result.size.width := ARect.Width;
Result.size.height := ARect.Height;
end
else
begin
Result.origin.x := Round(ARect.Left * Scale);
Result.origin.y := Round(ARect.Top * Scale);
Result.size.width := Round(ARect.Width * Scale);
Result.size.height := Round(ARect.Height * Scale);
end;
Result.origin.z := 0;
Result.size.depth := 1;
end;
procedure SynchronizeResources(const ATexture: MTLTexture);
var
CommandBuffer: MTLCommandBuffer;
LBlitCommandEncoder: MTLBlitCommandEncoder;
begin
CommandBuffer := FCommandQueue.CommandBuffer;
if CommandBuffer = nil then
Exit;
LBlitCommandEncoder := CommandBuffer.blitCommandEncoder;
LBlitCommandEncoder.synchronizeResource(ATexture);
LBlitCommandEncoder.endEncoding;
CommandBuffer.commit;
CommandBuffer.waitUntilCompleted;
end;
var
LCopyRect: TRect;
LTexture: MTLTexture;
LRegion: MTLRegion;
begin
LTexture := nil;
if FCommandBuffer <> nil then
FCommandBuffer.waitUntilCompleted;
LCopyRect := TRect.Intersect(ARect, TRect.Create(0, 0, Width, Height));
if Texture <> nil then
begin
LTexture := TMTLTexture.Wrap(Pointer(Texture.Handle));
LRegion := CreateRegion(LCopyRect, 1);
end
else if FOnScreenTexture <> nil then
begin
LTexture := FOnScreenTexture;
LRegion := CreateRegion(LCopyRect, Scale);
end;
if LTexture <> nil then
begin
// Synchronizing a Managed Resource between GPU and CPU
if LTexture.storageMode = MTLStorageModeManaged then
SynchronizeResources(LTexture);
// Get texture data
LTexture.getBytesBytesPerRowFromRegionMipmapLevel(
Bits, // pixelBytes: Pointer;
Pitch, // bytesPerRow: NSUInteger;
LRegion, // fromRegion: MTLRegion;
0); // mipmapLevel: NSUInteger
end;
end;
{$ENDIF}
{$ENDIF}
// - ---------------------------------------------------------------------------
{$ENDREGION}
{$REGION ' - Workaround RSP-37660'}
// - ---------------------------------------------------------------------------
// - WORKAROUND
// - ---------------------------------------------------------------------------
// -
// - Description:
// - The functions BitmapToUIImage and UIImageToBitmap of unit FMX.Helpers.iOS
// - are ignoring the PixelFormat of bitmaps. This issue generates wrong
// - colors in several parts of the code, and this workaround will fix some
// - important services that use these functions: IFMXTakenImageService,
// - IFMXCameraService, IFMXPhotoLibrary and IFMXShareSheetActionsService.
// -
// - Bug report:
// - https://quality.embarcadero.com/browse/RSP-37651
// - https://quality.embarcadero.com/browse/RSP-37660
// -
// - ---------------------------------------------------------------------------
{$IF (CompilerVersion < 35) or ((CompilerVersion = 35) and not DECLARED(RTLVersion112))}
{$IFDEF IOS}
type
{ TRSP37660Workaround }
TRSP37660Workaround = record
private type
TImageDelegate = class;
TImageManagerCocoa = class;
TSaveImageRequest = class
private
[Weak] FImageManager: TImageManagerCocoa;
FImage: UIImage;
FOnCompletion: TWriteImageCompletionEvent;
procedure PerformResultOfSavingPhoto(assetURL: NSURL; error: NSError);
public
constructor Create(const AImageManager: TImageManagerCocoa; const AImage: UIImage; const AHandler: TWriteImageCompletionEvent);
procedure Save;
end;
TImageManagerCocoa = class(TInterfacedObject, IFMXTakenImageService, IFMXCameraService, IFMXPhotoLibrary)
private
FImageDelegate: TImageDelegate;
FImagePicker: UIImagePickerController;
FSaveImageRequests: TList<TSaveImageRequest>;
protected
procedure TakeImage(const AControl: TControl; const ASourceType: UIImagePickerControllerSourceType);
procedure SaveImageToSavedPhotosAlbum(const AImage: UIImage; const AOnResult: TWriteImageCompletionEvent = nil);
public
constructor Create;
destructor Destroy; override;
class function IsAvailableSourceType(const ASourceType: UIImagePickerControllerSourceType): Boolean;
{ IFMXTakenImage }
procedure TakeImageFromLibrary(const AControl: TControl; const ARequiredResolution: TSize; const AEditable: Boolean;
const AOnDidFinishTaking: TOnDidFinishTaking; const AOnDidCancelTaking: TOnDidCancelTaking); overload;
procedure TakeImageFromLibrary(const AControl: TControl; const AParams: TParamsPhotoQuery); overload;
{ IFMXPhotoLibrary }
procedure AddImageToSavedPhotosAlbum(const ABitmap: TBitmap; const AWriteImageCompletionEvent: TWriteImageCompletionEvent = nil);
{ IFMXCameraService }
procedure TakePhoto(const AControl: TControl; const ARequiredResolution: TSize; const AEditable: Boolean;
const AOnDidFinishTaking: TOnDidFinishTaking; const AOnDidCancelTaking: TOnDidCancelTaking); overload;
procedure TakePhoto(const AControl: TControl; const AParams: TParamsPhotoQuery); overload;
end;
TImageDelegate = class(TOCLocal, UIImagePickerControllerDelegate)
private
[Weak] FImageManager: TImageManagerCocoa;
FParams: TParamsPhotoQuery;
protected
procedure DoDidFinishTaking(const AImage: TBitmap);
procedure DoDidCancelTaking;
procedure HidePicker(const APicker: UIImagePickerController);
function GetAngleOfImageOrientation(const AImage: UIImage): Single;
public
constructor Create(const AImageManager: TImageManagerCocoa);
property Params: TParamsPhotoQuery read FParams write FParams;
{ UIImagePickerControllerDelegate }
procedure imagePickerController(picker: UIImagePickerController; didFinishPickingImage: UIImage; editingInfo: NSDictionary); overload; cdecl;
procedure imagePickerController(picker: UIImagePickerController; didFinishPickingMediaWithInfo: NSDictionary); overload; cdecl;
procedure imagePickerControllerDidCancel(picker: UIImagePickerController); cdecl;
end;
TShareService = class(TInterfacedObject, IFMXShareSheetActionsService)
private
FActivityViewController: UIActivityViewController;
FActivityItems: NSMutableArray;
FPopoverController: UIPopoverController;
public
constructor Create;
destructor Destroy; override;
procedure ReleaseOldSharingController;
{ IFMXShareSheetActionsService }
procedure Share(const AControl: TControl; const AText: string; const ABitmap: TBitmap);
end;
private
class procedure SetPixelFormatRGBA(const ABitmap: TBitmap); static;
public
class procedure Apply; static;
end;
{ TRSP37660Workaround }
class procedure TRSP37660Workaround.Apply;
var
LImageManager: TImageManagerCocoa;
begin
TPlatformServices.Current.RemovePlatformService(IFMXShareSheetActionsService);
TPlatformServices.Current.RemovePlatformService(IFMXPhotoLibrary);
TPlatformServices.Current.RemovePlatformService(IFMXTakenImageService);
TPlatformServices.Current.RemovePlatformService(IFMXCameraService);
LImageManager := TImageManagerCocoa.Create;
if TImageManagerCocoa.IsAvailableSourceType(UIImagePickerControllerSourceTypeCamera) then
TPlatformServices.Current.AddPlatformService(IFMXCameraService, LImageManager);
if TImageManagerCocoa.IsAvailableSourceType(UIImagePickerControllerSourceTypeSavedPhotosAlbum) then
TPlatformServices.Current.AddPlatformService(IFMXTakenImageService, LImageManager);
TPlatformServices.Current.AddPlatformService(IFMXPhotoLibrary, LImageManager);
if TOSVersion.Check(6, 0) then
TPlatformServices.Current.AddPlatformService(IFMXShareSheetActionsService, IInterface(TShareService.Create));
end;
class procedure TRSP37660Workaround.SetPixelFormatRGBA(const ABitmap: TBitmap);
var
LBitmapData: TBitmapData;
begin
if (ABitmap <> nil) and (not ABitmap.IsEmpty) and ABitmap.Map(TMapAccess.ReadWrite, LBitmapData) then
begin
try
ChangePixelFormat(LBitmapData.Data, LBitmapData.Data, (LBitmapData.Pitch * LBitmapData.Height) div LBitmapData.BytesPerPixel,
LBitmapData.PixelFormat, TPixelFormat.RGBA);
finally
ABitmap.Unmap(LBitmapData);
end;
end;
end;
{ TRSP37660Workaround.TSaveImageRequest }
constructor TRSP37660Workaround.TSaveImageRequest.Create(
const AImageManager: TImageManagerCocoa; const AImage: UIImage;
const AHandler: TWriteImageCompletionEvent);
begin
if AImageManager = nil then
raise EArgumentNilException.CreateFmt(SWrongParameter, ['AImageManager']);
if AImage = nil then
raise EArgumentNilException.CreateFmt(SWrongParameter, ['AImage']);
FImageManager := AImageManager;
FImage := AImage;
FOnCompletion := AHandler;
end;
procedure TRSP37660Workaround.TSaveImageRequest.PerformResultOfSavingPhoto(