summaryrefslogtreecommitdiffstats
path: root/src/gui/painting/qcolorspace.cpp
blob: 7a1d34a4083117f1612ef10637ae35060a842ce1 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
// Copyright (C) 2020 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qcolorspace.h"
#include "qcolorspace_p.h"

#include "qcolortransform.h"
#include "qcolorclut_p.h"
#include "qcolormatrix_p.h"
#include "qcolortransferfunction_p.h"
#include "qcolortransform_p.h"
#include "qicc_p.h"

#include <qatomic.h>
#include <qmath.h>
#include <qtransform.h>

#include <qdebug.h>

QT_BEGIN_NAMESPACE

Q_CONSTINIT QBasicMutex QColorSpacePrivate::s_lutWriteLock;

Q_CONSTINIT static QAtomicPointer<QColorSpacePrivate> s_predefinedColorspacePrivates[QColorSpace::ProPhotoRgb] = {};
static void cleanupPredefinedColorspaces()
{
    for (QAtomicPointer<QColorSpacePrivate> &ptr : s_predefinedColorspacePrivates) {
        QColorSpacePrivate *prv = ptr.fetchAndStoreAcquire(nullptr);
        if (prv && !prv->ref.deref())
            delete prv;
    }
}

Q_DESTRUCTOR_FUNCTION(cleanupPredefinedColorspaces)

QColorSpacePrimaries::QColorSpacePrimaries(QColorSpace::Primaries primaries)
{
    switch (primaries) {
    case QColorSpace::Primaries::SRgb:
        redPoint   = QPointF(0.640, 0.330);
        greenPoint = QPointF(0.300, 0.600);
        bluePoint  = QPointF(0.150, 0.060);
        whitePoint = QColorVector::D65Chromaticity();
        break;
    case QColorSpace::Primaries::DciP3D65:
        redPoint   = QPointF(0.680, 0.320);
        greenPoint = QPointF(0.265, 0.690);
        bluePoint  = QPointF(0.150, 0.060);
        whitePoint = QColorVector::D65Chromaticity();
        break;
    case QColorSpace::Primaries::AdobeRgb:
        redPoint   = QPointF(0.640, 0.330);
        greenPoint = QPointF(0.210, 0.710);
        bluePoint  = QPointF(0.150, 0.060);
        whitePoint = QColorVector::D65Chromaticity();
        break;
    case QColorSpace::Primaries::ProPhotoRgb:
        redPoint   = QPointF(0.7347, 0.2653);
        greenPoint = QPointF(0.1596, 0.8404);
        bluePoint  = QPointF(0.0366, 0.0001);
        whitePoint = QColorVector::D50Chromaticity();
        break;
    default:
        Q_UNREACHABLE();
    }
}

bool QColorSpacePrimaries::areValid() const
{
    if (!QColorVector::isValidChromaticity(redPoint))
        return false;
    if (!QColorVector::isValidChromaticity(greenPoint))
        return false;
    if (!QColorVector::isValidChromaticity(bluePoint))
        return false;
    if (!QColorVector::isValidChromaticity(whitePoint))
        return false;
    return true;
}

QColorMatrix QColorSpacePrimaries::toXyzMatrix() const
{
    // This converts to XYZ in some undefined scale.
    QColorMatrix toXyz = { QColorVector::fromXYChromaticity(redPoint),
                           QColorVector::fromXYChromaticity(greenPoint),
                           QColorVector::fromXYChromaticity(bluePoint) };

    // Since the white point should be (1.0, 1.0, 1.0) in the
    // input, we can figure out the scale by using the
    // inverse conversion on the white point.
    const auto wXyz = QColorVector::fromXYChromaticity(whitePoint);
    QColorVector whiteScale = toXyz.inverted().map(wXyz);

    // Now we have scaled conversion to XYZ relative to the given whitepoint
    toXyz = toXyz * QColorMatrix::fromScale(whiteScale);

    return toXyz;
}

QColorSpacePrivate::QColorSpacePrivate()
{
}

QColorSpacePrivate::QColorSpacePrivate(QColorSpace::NamedColorSpace namedColorSpace)
        : namedColorSpace(namedColorSpace)
        , colorModel(QColorSpace::ColorModel::Rgb)
{
    switch (namedColorSpace) {
    case QColorSpace::SRgb:
        primaries = QColorSpace::Primaries::SRgb;
        transferFunction = QColorSpace::TransferFunction::SRgb;
        description = QStringLiteral("sRGB");
        break;
    case QColorSpace::SRgbLinear:
        primaries = QColorSpace::Primaries::SRgb;
        transferFunction = QColorSpace::TransferFunction::Linear;
        description = QStringLiteral("Linear sRGB");
        break;
    case QColorSpace::AdobeRgb:
        primaries = QColorSpace::Primaries::AdobeRgb;
        transferFunction = QColorSpace::TransferFunction::Gamma;
        gamma = 2.19921875f; // Not quite 2.2, see https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf
        description = QStringLiteral("Adobe RGB");
        break;
    case QColorSpace::DisplayP3:
        primaries = QColorSpace::Primaries::DciP3D65;
        transferFunction = QColorSpace::TransferFunction::SRgb;
        description = QStringLiteral("Display P3");
        break;
    case QColorSpace::ProPhotoRgb:
        primaries = QColorSpace::Primaries::ProPhotoRgb;
        transferFunction = QColorSpace::TransferFunction::ProPhotoRgb;
        description = QStringLiteral("ProPhoto RGB");
        break;
    default:
        Q_UNREACHABLE();
    }
    initialize();
}

QColorSpacePrivate::QColorSpacePrivate(QColorSpace::Primaries primaries, QColorSpace::TransferFunction transferFunction, float gamma)
        : primaries(primaries)
        , transferFunction(transferFunction)
        , colorModel(QColorSpace::ColorModel::Rgb)
        , gamma(gamma)
{
    identifyColorSpace();
    initialize();
}

QColorSpacePrivate::QColorSpacePrivate(const QColorSpacePrimaries &primaries,
                                       QColorSpace::TransferFunction transferFunction,
                                       float gamma)
        : primaries(QColorSpace::Primaries::Custom)
        , transferFunction(transferFunction)
        , colorModel(QColorSpace::ColorModel::Rgb)
        , gamma(gamma)
        , whitePoint(QColorVector::fromXYChromaticity(primaries.whitePoint))
{
    Q_ASSERT(primaries.areValid());
    toXyz = primaries.toXyzMatrix();
    chad = QColorMatrix::chromaticAdaptation(whitePoint);
    toXyz = chad * toXyz;

    identifyColorSpace();
    setTransferFunction();
}

QColorSpacePrivate::QColorSpacePrivate(const QPointF &whitePoint,
                                       QColorSpace::TransferFunction transferFunction,
                                       float gamma)
        : primaries(QColorSpace::Primaries::Custom)
        , transferFunction(transferFunction)
        , colorModel(QColorSpace::ColorModel::Gray)
        , gamma(gamma)
        , whitePoint(QColorVector::fromXYChromaticity(whitePoint))
{
    chad = QColorMatrix::chromaticAdaptation(this->whitePoint);
    toXyz = chad;
    setTransferFunction();
}

QColorSpacePrivate::QColorSpacePrivate(const QPointF &whitePoint, const QList<uint16_t> &transferFunctionTable)
      : primaries(QColorSpace::Primaries::Custom)
      , transferFunction(QColorSpace::TransferFunction::Custom)
      , colorModel(QColorSpace::ColorModel::Gray)
      , gamma(0)
      , whitePoint(QColorVector::fromXYChromaticity(whitePoint))
{
    chad = QColorMatrix::chromaticAdaptation(this->whitePoint);
    toXyz = chad;
    setTransferFunctionTable(transferFunctionTable);
    setTransferFunction();
}

QColorSpacePrivate::QColorSpacePrivate(QColorSpace::Primaries primaries, const QList<uint16_t> &transferFunctionTable)
        : primaries(primaries)
        , transferFunction(QColorSpace::TransferFunction::Custom)
        , colorModel(QColorSpace::ColorModel::Rgb)
        , gamma(0)
{
    setTransferFunctionTable(transferFunctionTable);
    identifyColorSpace();
    initialize();
}

QColorSpacePrivate::QColorSpacePrivate(const QColorSpacePrimaries &primaries, const QList<uint16_t> &transferFunctionTable)
        : primaries(QColorSpace::Primaries::Custom)
        , transferFunction(QColorSpace::TransferFunction::Custom)
        , colorModel(QColorSpace::ColorModel::Rgb)
        , gamma(0)
        , whitePoint(QColorVector::fromXYChromaticity(primaries.whitePoint))
{
    Q_ASSERT(primaries.areValid());
    toXyz = primaries.toXyzMatrix();
    chad = QColorMatrix::chromaticAdaptation(whitePoint);
    toXyz = chad * toXyz;
    setTransferFunctionTable(transferFunctionTable);
    identifyColorSpace();
    initialize();
}

QColorSpacePrivate::QColorSpacePrivate(const QColorSpacePrimaries &primaries,
                                       const QList<uint16_t> &redTransferFunctionTable,
                                       const QList<uint16_t> &greenTransferFunctionTable,
                                       const QList<uint16_t> &blueTransferFunctionTable)
        : primaries(QColorSpace::Primaries::Custom)
        , transferFunction(QColorSpace::TransferFunction::Custom)
        , colorModel(QColorSpace::ColorModel::Rgb)
        , gamma(0)
{
    Q_ASSERT(primaries.areValid());
    toXyz = primaries.toXyzMatrix();
    whitePoint = QColorVector::fromXYChromaticity(primaries.whitePoint);
    chad = QColorMatrix::chromaticAdaptation(whitePoint);
    toXyz = chad * toXyz;
    setTransferFunctionTables(redTransferFunctionTable,
                              greenTransferFunctionTable,
                              blueTransferFunctionTable);
    identifyColorSpace();
}

void QColorSpacePrivate::identifyColorSpace()
{
    switch (primaries) {
    case QColorSpace::Primaries::SRgb:
        if (transferFunction == QColorSpace::TransferFunction::SRgb) {
            namedColorSpace = QColorSpace::SRgb;
            if (description.isEmpty())
                description = QStringLiteral("sRGB");
            return;
        }
        if (transferFunction == QColorSpace::TransferFunction::Linear) {
            namedColorSpace = QColorSpace::SRgbLinear;
            if (description.isEmpty())
                description = QStringLiteral("Linear sRGB");
            return;
        }
        break;
    case QColorSpace::Primaries::AdobeRgb:
        if (transferFunction == QColorSpace::TransferFunction::Gamma) {
            if (qAbs(gamma - 2.19921875f) < (1/1024.0f)) {
                namedColorSpace = QColorSpace::AdobeRgb;
                if (description.isEmpty())
                    description = QStringLiteral("Adobe RGB");
                return;
            }
        }
        break;
    case QColorSpace::Primaries::DciP3D65:
        if (transferFunction == QColorSpace::TransferFunction::SRgb) {
            namedColorSpace = QColorSpace::DisplayP3;
            if (description.isEmpty())
                description = QStringLiteral("Display P3");
            return;
        }
        break;
    case QColorSpace::Primaries::ProPhotoRgb:
        if (transferFunction == QColorSpace::TransferFunction::ProPhotoRgb) {
            namedColorSpace = QColorSpace::ProPhotoRgb;
            if (description.isEmpty())
                description = QStringLiteral("ProPhoto RGB");
            return;
        }
        if (transferFunction == QColorSpace::TransferFunction::Gamma) {
            // ProPhoto RGB's curve is effectively gamma 1.8 for 8bit precision.
            if (qAbs(gamma - 1.8f) < (1/1024.0f)) {
                namedColorSpace = QColorSpace::ProPhotoRgb;
                if (description.isEmpty())
                    description = QStringLiteral("ProPhoto RGB");
                return;
            }
        }
        break;
    default:
        break;
    }

    namedColorSpace = Unknown;
}

void QColorSpacePrivate::initialize()
{
    setToXyzMatrix();
    setTransferFunction();
}

void QColorSpacePrivate::setToXyzMatrix()
{
    if (primaries == QColorSpace::Primaries::Custom) {
        toXyz = QColorMatrix();
        whitePoint = QColorVector::D50();
        return;
    }
    QColorSpacePrimaries colorSpacePrimaries(primaries);
    toXyz = colorSpacePrimaries.toXyzMatrix();
    whitePoint = QColorVector::fromXYChromaticity(colorSpacePrimaries.whitePoint);
    chad = QColorMatrix::chromaticAdaptation(whitePoint);
    toXyz = chad * toXyz;
}

void QColorSpacePrivate::setTransferFunctionTable(const QList<uint16_t> &transferFunctionTable)
{
    QColorTransferTable table(transferFunctionTable.size(), transferFunctionTable);
    if (!table.isEmpty() && !table.checkValidity()) {
        qWarning() << "Invalid transfer function table given to QColorSpace";
        trc[0].m_type = QColorTrc::Type::Uninitialized;
        return;
    }
    transferFunction = QColorSpace::TransferFunction::Custom;
    QColorTransferFunction curve;
    if (table.asColorTransferFunction(&curve)) {
        // Table recognized as a specific curve
        if (curve.isIdentity()) {
            transferFunction = QColorSpace::TransferFunction::Linear;
            gamma = 1.0f;
        } else if (curve.isSRgb()) {
            transferFunction = QColorSpace::TransferFunction::SRgb;
        }
        trc[0].m_type = QColorTrc::Type::Function;
        trc[0].m_fun = curve;
    } else {
        trc[0].m_type = QColorTrc::Type::Table;
        trc[0].m_table = table;
    }
}

void QColorSpacePrivate::setTransferFunctionTables(const QList<uint16_t> &redTransferFunctionTable,
                                                   const QList<uint16_t> &greenTransferFunctionTable,
                                                   const QList<uint16_t> &blueTransferFunctionTable)
{
    QColorTransferTable redTable(redTransferFunctionTable.size(), redTransferFunctionTable);
    QColorTransferTable greenTable(greenTransferFunctionTable.size(), greenTransferFunctionTable);
    QColorTransferTable blueTable(blueTransferFunctionTable.size(), blueTransferFunctionTable);
    if (!redTable.isEmpty() && !greenTable.isEmpty() && !blueTable.isEmpty() &&
        !redTable.checkValidity() && !greenTable.checkValidity() && !blueTable.checkValidity()) {
        qWarning() << "Invalid transfer function table given to QColorSpace";
        trc[0].m_type = QColorTrc::Type::Uninitialized;
        trc[1].m_type = QColorTrc::Type::Uninitialized;
        trc[2].m_type = QColorTrc::Type::Uninitialized;
        return;
    }
    transferFunction = QColorSpace::TransferFunction::Custom;
    QColorTransferFunction curve;
    if (redTable.asColorTransferFunction(&curve)) {
        trc[0].m_type = QColorTrc::Type::Function;
        trc[0].m_fun = curve;
    } else {
        trc[0].m_type = QColorTrc::Type::Table;
        trc[0].m_table = redTable;
    }
    if (greenTable.asColorTransferFunction(&curve)) {
        trc[1].m_type = QColorTrc::Type::Function;
        trc[1].m_fun = curve;
    } else {
        trc[1].m_type = QColorTrc::Type::Table;
        trc[1].m_table = greenTable;
    }
    if (blueTable.asColorTransferFunction(&curve)) {
        trc[2].m_type = QColorTrc::Type::Function;
        trc[2].m_fun = curve;
    } else {
        trc[2].m_type = QColorTrc::Type::Table;
        trc[2].m_table = blueTable;
    }
    lut.generated.storeRelease(0);
}

void QColorSpacePrivate::setTransferFunction()
{
    switch (transferFunction) {
    case QColorSpace::TransferFunction::Linear:
        trc[0].m_type = QColorTrc::Type::Function;
        trc[0].m_fun = QColorTransferFunction();
        if (qFuzzyIsNull(gamma))
            gamma = 1.0f;
        break;
    case QColorSpace::TransferFunction::Gamma:
        trc[0].m_type = QColorTrc::Type::Function;
        trc[0].m_fun = QColorTransferFunction::fromGamma(gamma);
        break;
    case QColorSpace::TransferFunction::SRgb:
        trc[0].m_type = QColorTrc::Type::Function;
        trc[0].m_fun = QColorTransferFunction::fromSRgb();
        if (qFuzzyIsNull(gamma))
            gamma = 2.31f;
        break;
    case QColorSpace::TransferFunction::ProPhotoRgb:
        trc[0].m_type = QColorTrc::Type::Function;
        trc[0].m_fun = QColorTransferFunction::fromProPhotoRgb();
        if (qFuzzyIsNull(gamma))
            gamma = 1.8f;
        break;
    case QColorSpace::TransferFunction::Custom:
        break;
    default:
        Q_UNREACHABLE();
        break;
    }
    trc[1] = trc[0];
    trc[2] = trc[0];
    lut.generated.storeRelease(0);
}

QColorTransform QColorSpacePrivate::transformationToColorSpace(const QColorSpacePrivate *out) const
{
    Q_ASSERT(out);
    QColorTransform combined;
    auto ptr = new QColorTransformPrivate;
    combined.d = ptr;
    ptr->colorSpaceIn = this;
    ptr->colorSpaceOut = out;
    if (isThreeComponentMatrix())
        ptr->colorMatrix = toXyz;
    else
        ptr->colorMatrix = QColorMatrix::identity();
    if (out->isThreeComponentMatrix())
        ptr->colorMatrix = out->toXyz.inverted() * ptr->colorMatrix;
    if (ptr->isIdentity())
        return QColorTransform();
    return combined;
}

QColorTransform QColorSpacePrivate::transformationToXYZ() const
{
    QColorTransform transform;
    auto ptr = new QColorTransformPrivate;
    transform.d = ptr;
    ptr->colorSpaceIn = this;
    ptr->colorSpaceOut = this;
    // Convert to XYZ relative to our white point, not the regular D50 white point.
    if (isThreeComponentMatrix())
        ptr->colorMatrix = QColorMatrix::chromaticAdaptation(whitePoint).inverted() * toXyz;
    else
        ptr->colorMatrix = QColorMatrix::identity();
    return transform;
}

bool QColorSpacePrivate::isThreeComponentMatrix() const
{
    return transformModel == QColorSpace::TransformModel::ThreeComponentMatrix;
}

void QColorSpacePrivate::clearElementListProcessingForEdit()
{
    Q_ASSERT(transformModel == QColorSpace::TransformModel::ElementListProcessing);
    Q_ASSERT(primaries == QColorSpace::Primaries::Custom);
    Q_ASSERT(transferFunction == QColorSpace::TransferFunction::Custom);

    transformModel = QColorSpace::TransformModel::ThreeComponentMatrix;
    colorModel = QColorSpace::ColorModel::Rgb;
    isPcsLab = false;
    mAB.clear();
    mBA.clear();
}

/*!
    \class QColorSpace
    \brief The QColorSpace class provides a color space abstraction.
    \since 5.14

    \ingroup painting
    \ingroup appearance
    \inmodule QtGui

    Color values can be interpreted in different ways, and based on the interpretation
    can live in different spaces. We call this \e {color spaces}.

    QColorSpace provides access to creating several predefined color spaces and
    can generate QColorTransforms for converting colors from one color space to
    another.

    QColorSpace can also represent color spaces defined by ICC profiles or embedded
    in images, that do not otherwise fit the predefined color spaces.

    A color space can generally speaking be conceived as a combination of set of primary
    colors and a transfer function. The primaries defines the axes of the color space, and
    the transfer function how values are mapped on the axes.
    The primaries are for ColorModel::Rgb color spaces defined by three primary colors that
    represent exactly how red, green, and blue look in this particular color space, and a white
    color that represents where and how bright pure white is. For grayscale color spaces, only
    a single white primary is needed. The range of colors expressible by the primary colors is
    called the gamut, and a color space that can represent a wider range of colors is also
    known as a wide-gamut color space.

    The transfer function or gamma curve determines how each component in the
    color space is encoded. These are used because human perception does not operate
    linearly, and the transfer functions try to ensure that colors will seem evenly
    spaced to human eyes.
*/


/*!
    \enum QColorSpace::NamedColorSpace

    Predefined color spaces.

    \value SRgb The sRGB color space, which Qt operates in by default. It is a close approximation
    of how most classic monitors operate, and a mode most software and hardware support.
    \l{http://www.color.org/chardata/rgb/srgb.xalter}{ICC registration of sRGB}.
    \value SRgbLinear The sRGB color space with linear gamma. Useful for gamma-corrected blending.
    \value AdobeRgb The Adobe RGB color space is a classic wide-gamut color space, using a gamma of 2.2.
    \l{http://www.color.org/chardata/rgb/adobergb.xalter}{ICC registration of Adobe RGB (1998)}
    \value DisplayP3 A color-space using the primaries of DCI-P3, but with the whitepoint and transfer
    function of sRGB. Common in modern wide-gamut screens.
    \l{http://www.color.org/chardata/rgb/DCIP3.xalter}{ICC registration of DCI-P3}
    \value ProPhotoRgb The Pro Photo RGB color space, also known as ROMM RGB is a very wide gamut color space.
    \l{http://www.color.org/chardata/rgb/rommrgb.xalter}{ICC registration of ROMM RGB}
*/

/*!
    \enum QColorSpace::Primaries

    Predefined sets of primary colors.

    \value Custom The primaries are undefined or does not match any predefined sets.
    \value SRgb The sRGB primaries
    \value AdobeRgb The Adobe RGB primaries
    \value DciP3D65 The DCI-P3 primaries with the D65 whitepoint
    \value ProPhotoRgb The ProPhoto RGB primaries with the D50 whitepoint
*/

/*!
    \enum QColorSpace::TransferFunction

    Predefined transfer functions or gamma curves.

    \value Custom The custom or null transfer function
    \value Linear The linear transfer functions
    \value Gamma A transfer function that is a real gamma curve based on the value of gamma()
    \value SRgb The sRGB transfer function, composed of linear and gamma parts
    \value ProPhotoRgb The ProPhoto RGB transfer function, composed of linear and gamma parts
*/

/*!
    \enum QColorSpace::TransformModel
    \since 6.8

    Defines the processing model used for color space transforms.

    \value ThreeComponentMatrix The transform consist of a matrix calculated from primaries and set of transfer functions
    for each color channel. This is very fast and used by all predefined color spaces. Any color space on this form is
    reversible and always both valid sources and targets.
    \value ElementListProcessing The transforms are one or two lists of processing elements that can do many things,
    each list only process either to the connection color space or from it. This is very flexible, but rather
    slow, and can only be set by reading ICC profiles (See  \l fromIccProfile()). Since the two lists are
    separate a color space on this form can be a valid source, but not necessarily also a valid target. When changing
    either primaries or transfer function on a color space on this type it will reset to an empty ThreeComponentMatrix form.
*/

/*!
    \enum QColorSpace::ColorModel
    \since 6.8

    Defines the color model used by the color space data.

    \value Undefined No color model
    \value Rgb An RGB color model with red, green, and blue colors. Can apply to RGB and grayscale data.
    \value Gray A gray scale color model. Can only apply to grayscale data.
    \value Cmyk Can only represent color data defined with cyan, magenta, yellow, and black colors.
    In effect only QImage::Format_CMYK32. Note Cmyk color spaces will be TransformModel::ElementListProcessing.
*/

/*!
    \fn QColorSpace::QColorSpace()

    Creates a new colorspace object that represents an undefined and invalid colorspace.
 */

/*!
    Creates a new colorspace object that represents a \a namedColorSpace.
 */
QColorSpace::QColorSpace(NamedColorSpace namedColorSpace)
{
    if (namedColorSpace < QColorSpace::SRgb || namedColorSpace > QColorSpace::ProPhotoRgb) {
        qWarning() << "QColorSpace attempted constructed from invalid QColorSpace::NamedColorSpace: " << int(namedColorSpace);
        return;
    }
    // The defined namespaces start at 1:
    auto &atomicRef = s_predefinedColorspacePrivates[static_cast<int>(namedColorSpace) - 1];
    QColorSpacePrivate *cspriv = atomicRef.loadAcquire();
    if (!cspriv) {
        auto *tmp = new QColorSpacePrivate(namedColorSpace);
        tmp->ref.ref();
        if (atomicRef.testAndSetOrdered(nullptr, tmp, cspriv))
            cspriv = tmp;
        else
            delete tmp;
    }
    d_ptr = cspriv;
    Q_ASSERT(isValid());
}

/*!
    Creates a custom color space with the primaries \a primaries, using the transfer function \a transferFunction and
    optionally \a gamma.
 */
QColorSpace::QColorSpace(QColorSpace::Primaries primaries, QColorSpace::TransferFunction transferFunction, float gamma)
        : d_ptr(new QColorSpacePrivate(primaries, transferFunction, gamma))
{
}

/*!
    Creates a custom color space with the primaries \a primaries, using a gamma transfer function of
    \a gamma.
 */
QColorSpace::QColorSpace(QColorSpace::Primaries primaries, float gamma)
        : d_ptr(new QColorSpacePrivate(primaries, TransferFunction::Gamma, gamma))
{
}

/*!
    Creates a custom color space with the primaries \a gamut, using a custom transfer function
    described by \a transferFunctionTable.

    The table should contain at least 2 values, and contain an monotonically increasing list
    of values from 0 to 65535.

    \since 6.1
 */
QColorSpace::QColorSpace(QColorSpace::Primaries gamut, const QList<uint16_t> &transferFunctionTable)
    : d_ptr(new QColorSpacePrivate(gamut, transferFunctionTable))
{
}

/*!
    Creates a custom grayscale color space with the white point \a whitePoint, using the transfer function \a transferFunction and
    optionally \a gamma.

    \since 6.8
*/
QColorSpace::QColorSpace(const QPointF &whitePoint, TransferFunction transferFunction, float gamma)
    : d_ptr(new QColorSpacePrivate(whitePoint, transferFunction, gamma))
{
}

/*!
    Creates a custom grayscale color space with white point \a whitePoint, and using the custom transfer function described by
    \a transferFunctionTable.

    \since 6.8
*/
QColorSpace::QColorSpace(const QPointF &whitePoint, const QList<uint16_t> &transferFunctionTable)
    : d_ptr(new QColorSpacePrivate(whitePoint, transferFunctionTable))
{
}

/*!
    Creates a custom colorspace with a primaries based on the chromaticities of the primary colors \a whitePoint,
    \a redPoint, \a greenPoint and \a bluePoint, and using the transfer function \a transferFunction and optionally \a gamma.
 */
QColorSpace::QColorSpace(const QPointF &whitePoint, const QPointF &redPoint,
                         const QPointF &greenPoint, const QPointF &bluePoint,
                         QColorSpace::TransferFunction transferFunction, float gamma)
{
    QColorSpacePrimaries primaries(whitePoint, redPoint, greenPoint, bluePoint);
    if (!primaries.areValid()) {
        qWarning() << "QColorSpace attempted constructed from invalid primaries:" << whitePoint << redPoint << greenPoint << bluePoint;
        return;
    }
    d_ptr = new QColorSpacePrivate(primaries, transferFunction, gamma);
}

/*!
    Creates a custom color space with primaries based on the chromaticities of the primary colors \a whitePoint,
    \a redPoint, \a greenPoint and \a bluePoint, and using the custom transfer function described by
    \a transferFunctionTable.

    \since 6.1
 */
QColorSpace::QColorSpace(const QPointF &whitePoint, const QPointF &redPoint,
                         const QPointF &greenPoint, const QPointF &bluePoint,
                         const QList<uint16_t> &transferFunctionTable)
    : d_ptr(new QColorSpacePrivate({whitePoint, redPoint, greenPoint, bluePoint}, transferFunctionTable))
{
}

/*!
    Creates a custom color space with primaries based on the chromaticities of the primary colors \a whitePoint,
    \a redPoint, \a greenPoint and \a bluePoint, and using the custom transfer functions described by
    \a redTransferFunctionTable, \a greenTransferFunctionTable, and \a blueTransferFunctionTable.

    \since 6.1
 */
QColorSpace::QColorSpace(const QPointF &whitePoint, const QPointF &redPoint,
                         const QPointF &greenPoint, const QPointF &bluePoint,
                         const QList<uint16_t> &redTransferFunctionTable,
                         const QList<uint16_t> &greenTransferFunctionTable,
                         const QList<uint16_t> &blueTransferFunctionTable)
    : d_ptr(new QColorSpacePrivate({whitePoint, redPoint, greenPoint, bluePoint},
                                   redTransferFunctionTable,
                                   greenTransferFunctionTable,
                                   blueTransferFunctionTable))
{
}

QColorSpace::~QColorSpace() = default;

QT_DEFINE_QESDP_SPECIALIZATION_DTOR(QColorSpacePrivate)

QColorSpace::QColorSpace(const QColorSpace &colorSpace) noexcept = default;

/*! \fn void QColorSpace::swap(QColorSpace &other)

    Swaps color space \a other with this color space. This operation is very fast and
    never fails.
*/

/*!
    Returns the predefined primaries of the color space
    or \c primaries::Custom if it doesn't match any of them.
*/
QColorSpace::Primaries QColorSpace::primaries() const noexcept
{
    if (Q_UNLIKELY(!d_ptr))
        return QColorSpace::Primaries::Custom;
    return d_ptr->primaries;
}

/*!
    Returns the predefined transfer function of the color space
    or \c TransferFunction::Custom if it doesn't match any of them.

    \sa gamma(), setTransferFunction(), withTransferFunction()
*/
QColorSpace::TransferFunction QColorSpace::transferFunction() const noexcept
{
    if (Q_UNLIKELY(!d_ptr))
        return QColorSpace::TransferFunction::Custom;
    return d_ptr->transferFunction;
}

/*!
    Returns the gamma value of color spaces with \c TransferFunction::Gamma,
    an approximate gamma value for other predefined color spaces, or
    0.0 if no approximate gamma is known.

    \sa transferFunction()
*/
float QColorSpace::gamma() const noexcept
{
    if (Q_UNLIKELY(!d_ptr))
        return 0.0f;
    return d_ptr->gamma;
}

/*!
    Sets the transfer function to \a transferFunction and \a gamma.

    \sa transferFunction(), gamma(), withTransferFunction()
*/
void QColorSpace::setTransferFunction(QColorSpace::TransferFunction transferFunction, float gamma)
{
    if (transferFunction == TransferFunction::Custom)
        return;
    if (!d_ptr) {
        d_ptr = new QColorSpacePrivate(Primaries::Custom, transferFunction, gamma);
        return;
    }
    if (d_ptr->transferFunction == transferFunction && d_ptr->gamma == gamma)
        return;
    detach();
    if (d_ptr->transformModel == TransformModel::ElementListProcessing)
        d_ptr->clearElementListProcessingForEdit();
    d_ptr->iccProfile = {};
    d_ptr->description = QString();
    d_ptr->transferFunction = transferFunction;
    d_ptr->gamma = gamma;
    d_ptr->identifyColorSpace();
    d_ptr->setTransferFunction();
}

/*!
    Sets the transfer function to \a transferFunctionTable.

    \since 6.1
    \sa withTransferFunction()
*/
void QColorSpace::setTransferFunction(const QList<uint16_t> &transferFunctionTable)
{
    if (!d_ptr) {
        d_ptr = new QColorSpacePrivate(Primaries::Custom, transferFunctionTable);
        d_ptr->ref.ref();
        return;
    }
    detach();
    if (d_ptr->transformModel == TransformModel::ElementListProcessing)
        d_ptr->clearElementListProcessingForEdit();
    d_ptr->iccProfile = {};
    d_ptr->description = QString();
    d_ptr->setTransferFunctionTable(transferFunctionTable);
    d_ptr->gamma = 0;
    d_ptr->identifyColorSpace();
    d_ptr->setTransferFunction();
}

/*!
    Sets the transfer functions to \a redTransferFunctionTable,
    \a greenTransferFunctionTable and \a blueTransferFunctionTable.

    \since 6.1
    \sa withTransferFunctions()
*/
void QColorSpace::setTransferFunctions(const QList<uint16_t> &redTransferFunctionTable,
                                       const QList<uint16_t> &greenTransferFunctionTable,
                                       const QList<uint16_t> &blueTransferFunctionTable)
{
    if (!d_ptr) {
        d_ptr = new QColorSpacePrivate();
        d_ptr->setTransferFunctionTables(redTransferFunctionTable,
                                         greenTransferFunctionTable,
                                         blueTransferFunctionTable);
        d_ptr->ref.ref();
        return;
    }
    detach();
    if (d_ptr->transformModel == TransformModel::ElementListProcessing)
        d_ptr->clearElementListProcessingForEdit();
    d_ptr->iccProfile = {};
    d_ptr->description = QString();
    d_ptr->setTransferFunctionTables(redTransferFunctionTable,
                                     greenTransferFunctionTable,
                                     blueTransferFunctionTable);
    d_ptr->gamma = 0;
    d_ptr->identifyColorSpace();
}

/*!
    Returns a copy of this color space, except using the transfer function
    \a transferFunction and \a gamma.

    \sa transferFunction(), gamma(), setTransferFunction()
*/
QColorSpace QColorSpace::withTransferFunction(QColorSpace::TransferFunction transferFunction, float gamma) const
{
    if (!isValid() || transferFunction == TransferFunction::Custom)
        return *this;
    if (d_ptr->transferFunction == transferFunction && d_ptr->gamma == gamma)
        return *this;
    QColorSpace out(*this);
    out.setTransferFunction(transferFunction, gamma);
    return out;
}

/*!
    Returns a copy of this color space, except using the transfer function
    described by \a transferFunctionTable.

    \since 6.1
    \sa transferFunction(), setTransferFunction()
*/
QColorSpace QColorSpace::withTransferFunction(const QList<uint16_t> &transferFunctionTable) const
{
    if (!isValid())
        return *this;
    QColorSpace out(*this);
    out.setTransferFunction(transferFunctionTable);
    return out;
}

/*!
    Returns a copy of this color space, except using the transfer functions
    described by \a redTransferFunctionTable, \a greenTransferFunctionTable and
    \a blueTransferFunctionTable.

    \since 6.1
    \sa setTransferFunctions()
*/
QColorSpace QColorSpace::withTransferFunctions(const QList<uint16_t> &redTransferFunctionTable,
                                               const QList<uint16_t> &greenTransferFunctionTable,
                                               const QList<uint16_t> &blueTransferFunctionTable) const
{
    if (!isValid())
        return *this;
    QColorSpace out(*this);
    out.setTransferFunctions(redTransferFunctionTable, greenTransferFunctionTable, blueTransferFunctionTable);
    return out;
}

/*!
    Sets the primaries to those of the \a primariesId set.

    \sa primaries()
*/
void QColorSpace::setPrimaries(QColorSpace::Primaries primariesId)
{
    if (primariesId == Primaries::Custom)
        return;
    if (!d_ptr) {
        d_ptr = new QColorSpacePrivate(primariesId, TransferFunction::Custom, 0.0f);
        return;
    }
    if (d_ptr->primaries == primariesId)
        return;
    detach();
    if (d_ptr->transformModel == TransformModel::ElementListProcessing)
        d_ptr->clearElementListProcessingForEdit();
    d_ptr->iccProfile = {};
    d_ptr->description = QString();
    d_ptr->primaries = primariesId;
    d_ptr->colorModel = QColorSpace::ColorModel::Rgb;
    d_ptr->identifyColorSpace();
    d_ptr->setToXyzMatrix();
}

/*!
    Set primaries to the chromaticities of \a whitePoint, \a redPoint, \a greenPoint
    and \a bluePoint.

    \sa primaries()
*/
void QColorSpace::setPrimaries(const QPointF &whitePoint, const QPointF &redPoint,
                               const QPointF &greenPoint, const QPointF &bluePoint)
{
    QColorSpacePrimaries primaries(whitePoint, redPoint, greenPoint, bluePoint);
    if (!primaries.areValid())
        return;
    if (!d_ptr) {
        d_ptr = new QColorSpacePrivate(primaries, TransferFunction::Custom, 0.0f);
        return;
    }
    QColorMatrix toXyz = primaries.toXyzMatrix();
    QColorMatrix chad = QColorMatrix::chromaticAdaptation(QColorVector::fromXYChromaticity(whitePoint));
    toXyz = chad * toXyz;
    if (QColorVector::fromXYChromaticity(primaries.whitePoint) == d_ptr->whitePoint
        && toXyz == d_ptr->toXyz && chad == d_ptr->chad)
        return;
    detach();
    if (d_ptr->transformModel == TransformModel::ElementListProcessing)
        d_ptr->clearElementListProcessingForEdit();
    d_ptr->iccProfile = {};
    d_ptr->description = QString();
    d_ptr->primaries = QColorSpace::Primaries::Custom;
    d_ptr->colorModel = QColorSpace::ColorModel::Rgb;
    d_ptr->toXyz = toXyz;
    d_ptr->chad = chad;
    d_ptr->whitePoint = QColorVector::fromXYChromaticity(primaries.whitePoint);
    d_ptr->identifyColorSpace();
}

/*!
    Returns the white point used for this color space. Returns a null QPointF if not defined.

    \since 6.8
*/
QPointF QColorSpace::whitePoint() const
{
    if (Q_UNLIKELY(!d_ptr))
        return QPointF();
    return d_ptr->whitePoint.toChromaticity();
}

/*!
    Sets the white point to used for this color space to \a whitePoint.

    \since 6.8
*/
void QColorSpace::setWhitePoint(const QPointF &whitePoint)
{
    if (Q_UNLIKELY(!d_ptr)) {
        d_ptr = new QColorSpacePrivate(whitePoint, TransferFunction::Custom, 0.0f);
        return;
    }
    if (QColorVector::fromXYChromaticity(whitePoint) == d_ptr->whitePoint)
        return;
    detach();
    if (d_ptr->transformModel == TransformModel::ElementListProcessing)
        d_ptr->clearElementListProcessingForEdit();
    d_ptr->iccProfile = {};
    d_ptr->description = QString();
    d_ptr->primaries = QColorSpace::Primaries::Custom;
    // An RGB color model stays RGB, a gray stays gray, but an undefined one can now be considered gray
    if (d_ptr->colorModel == QColorSpace::ColorModel::Undefined)
        d_ptr->colorModel = QColorSpace::ColorModel::Gray;
    QColorVector wXyz(QColorVector::fromXYChromaticity(whitePoint));
    if (d_ptr->transformModel == QColorSpace::TransformModel::ThreeComponentMatrix) {
        if (d_ptr->colorModel == QColorSpace::ColorModel::Rgb) {
            // Rescale toXyz to new whitepoint
            QColorMatrix rawToXyz = d_ptr->chad.inverted() * d_ptr->toXyz;
            QColorVector whiteScale = rawToXyz.inverted().map(wXyz);
            rawToXyz = rawToXyz * QColorMatrix::fromScale(whiteScale);
            d_ptr->chad = QColorMatrix::chromaticAdaptation(wXyz);
            d_ptr->toXyz = d_ptr->chad * rawToXyz;
        } else if (d_ptr->colorModel == QColorSpace::ColorModel::Gray) {
            d_ptr->chad = d_ptr->toXyz = QColorMatrix::chromaticAdaptation(wXyz);
        }
    }
    d_ptr->whitePoint = wXyz;
    d_ptr->identifyColorSpace();
}

/*!
    Returns the transfrom processing model used for this color space.

    \since 6.8
*/
QColorSpace::TransformModel QColorSpace::transformModel() const noexcept
{
    if (Q_UNLIKELY(!d_ptr))
        return QColorSpace::TransformModel::ThreeComponentMatrix;
    return d_ptr->transformModel;
}

/*!
    Returns the color model this color space can represent

    \since 6.8
*/
QColorSpace::ColorModel QColorSpace::colorModel() const noexcept
{
    if (Q_UNLIKELY(!d_ptr))
        return QColorSpace::ColorModel::Undefined;
    return d_ptr->colorModel;
}

/*!
    \internal
*/
void QColorSpace::detach()
{
    if (d_ptr)
        d_ptr.detach();
    else
        d_ptr = new QColorSpacePrivate;
}

/*!
    Returns an ICC profile representing the color space.

    If the color space was generated from an ICC profile, that profile
    is returned, otherwise one is generated.

    \note Even invalid color spaces may return the ICC profile if they
    were generated from one, to allow applications to implement wider
    support themselves.

    \sa fromIccProfile()
*/
QByteArray QColorSpace::iccProfile() const
{
    if (Q_UNLIKELY(!d_ptr))
        return QByteArray();
    if (!d_ptr->iccProfile.isEmpty())
        return d_ptr->iccProfile;
    if (!isValid())
        return QByteArray();
    return QIcc::toIccProfile(*this);
}

/*!
    Creates a QColorSpace from ICC profile \a iccProfile.

    \note Not all ICC profiles are supported. QColorSpace only supports
    RGB or Gray ICC profiles.

    If the ICC profile is not supported an invalid QColorSpace is returned
    where you can still read the original ICC profile using iccProfile().

    \sa iccProfile()
*/
QColorSpace QColorSpace::fromIccProfile(const QByteArray &iccProfile)
{
    QColorSpace colorSpace;
    if (QIcc::fromIccProfile(iccProfile, &colorSpace))
        return colorSpace;
    colorSpace.detach();
    colorSpace.d_ptr->iccProfile = iccProfile;
    return colorSpace;
}

/*!
    Returns \c true if the color space is valid. For a color space with \c TransformModel::ThreeComponentMatrix
    that means both primaries and transfer functions set, and implies isValidTarget().
    For a color space with \c TransformModel::ElementListProcessing it means it has a valid source transform, to
    check if it also a valid target color space use isValidTarget().

    \sa isValidTarget()
*/
bool QColorSpace::isValid() const noexcept
{
    if (!d_ptr)
        return false;
    return d_ptr->isValid();
}

/*!
    \since 6.8

    Returns \c true if the color space is a valid target color space.
*/
bool QColorSpace::isValidTarget() const noexcept
{
    if (!d_ptr)
        return false;
    if (!d_ptr->isThreeComponentMatrix())
        return !d_ptr->mBA.isEmpty();
    return d_ptr->isValid();
}

/*!
    \internal
*/
bool QColorSpacePrivate::isValid() const noexcept
{
    if (!isThreeComponentMatrix())
        return !mAB.isEmpty();
    if (!toXyz.isValid())
        return false;
    if (colorModel == QColorSpace::ColorModel::Gray) {
        if (!trc[0].isValid())
            return false;
    } else {
        if (!trc[0].isValid() || !trc[1].isValid() || !trc[2].isValid())
            return false;
    }
    return true;
}

/*!
    \fn bool QColorSpace::operator==(const QColorSpace &colorSpace1, const QColorSpace &colorSpace2)

    Returns \c true if colorspace \a colorSpace1 is equal to colorspace \a colorSpace2;
    otherwise returns \c false
*/

/*!
    \fn bool QColorSpace::operator!=(const QColorSpace &colorSpace1, const QColorSpace &colorSpace2)

    Returns \c true if colorspace \a colorSpace1 is not equal to colorspace \a colorSpace2;
    otherwise returns \c false
*/

static bool compareElement(const QColorSpacePrivate::TransferElement &element,
                           const QColorSpacePrivate::TransferElement &other)
{
    return element.trc[0] == other.trc[0]
        && element.trc[1] == other.trc[1]
        && element.trc[2] == other.trc[2]
        && element.trc[3] == other.trc[3];
}

static bool compareElement(const QColorMatrix &element,
                           const QColorMatrix &other)
{
    return element == other;
}

static bool compareElement(const QColorVector &element,
                           const QColorVector &other)
{
    return element == other;
}

static bool compareElement(const QColorCLUT &element,
                           const QColorCLUT &other)
{
    if (element.gridPointsX != other.gridPointsX)
        return false;
    if (element.gridPointsY != other.gridPointsY)
        return false;
    if (element.gridPointsZ != other.gridPointsZ)
        return false;
    if (element.gridPointsW != other.gridPointsW)
        return false;
    if (element.table.size() != other.table.size())
        return false;
    for (qsizetype i = 0; i < element.table.size(); ++i) {
        if (element.table[i] != other.table[i])
            return false;
    }
    return true;
}

template<typename T>
static bool compareElements(const T &element, const QColorSpacePrivate::Element &other)
{
    return compareElement(element, std::get<T>(other));
}

/*!
    \internal
*/
bool QColorSpace::equals(const QColorSpace &other) const
{
    if (d_ptr == other.d_ptr)
        return true;
    if (!d_ptr)
        return false;
    return d_ptr->equals(other.d_ptr.constData());
}

/*!
    \internal
*/
bool QColorSpacePrivate::equals(const QColorSpacePrivate *other) const
{
    if (!other)
        return false;

    if (namedColorSpace && other->namedColorSpace)
        return namedColorSpace == other->namedColorSpace;

    const bool valid1 = isValid();
    const bool valid2 = other->isValid();
    if (valid1 != valid2)
        return false;
    if (!valid1 && !valid2) {
        if (!iccProfile.isEmpty() || !other->iccProfile.isEmpty())
            return iccProfile == other->iccProfile;
        return false;
    }

    // At this point one or both color spaces are unknown, and must be compared in detail instead

    if (transformModel != other->transformModel)
        return false;

    if (!isThreeComponentMatrix()) {
        if (isPcsLab != other->isPcsLab)
            return false;
        if (colorModel != other->colorModel)
            return false;
        if (mAB.count() != other->mAB.count())
            return false;
        if (mBA.count() != other->mBA.count())
            return false;

        // Compare element types
        for (qsizetype i = 0; i < mAB.count(); ++i) {
            if (mAB[i].index() != other->mAB[i].index())
                return false;
        }
        for (qsizetype i = 0; i < mBA.count(); ++i) {
            if (mBA[i].index() != other->mBA[i].index())
                return false;
        }

        // Compare element contents
        for (qsizetype i = 0; i < mAB.count(); ++i) {
            if (!std::visit([&](auto &&elm) { return compareElements(elm, other->mAB[i]); }, mAB[i]))
                return false;
        }
        for (qsizetype i = 0; i < mBA.count(); ++i) {
            if (!std::visit([&](auto &&elm) { return compareElements(elm, other->mBA[i]); }, mBA[i]))
                return false;
        }

        return true;
    }

    if (primaries != QColorSpace::Primaries::Custom && other->primaries != QColorSpace::Primaries::Custom) {
        if (primaries != other->primaries)
            return false;
    } else {
        if (toXyz != other->toXyz)
            return false;
    }

    if (transferFunction != QColorSpace::TransferFunction::Custom && other->transferFunction != QColorSpace::TransferFunction::Custom) {
        if (transferFunction != other->transferFunction)
            return false;
        if (transferFunction == QColorSpace::TransferFunction::Gamma)
            return (qAbs(gamma - other->gamma) <= (1.0f / 512.0f));
        return true;
    }

    if (trc[0] != other->trc[0] ||
        trc[1] != other->trc[1] ||
        trc[2] != other->trc[2])
        return false;

    return true;
}

/*!
    Generates and returns a color space transformation from this color space to
    \a colorspace.
*/
QColorTransform QColorSpace::transformationToColorSpace(const QColorSpace &colorspace) const
{
    if (!isValid())
        return QColorTransform();

    if (*this == colorspace)
        return QColorTransform();
    if (!colorspace.isValidTarget()) {
        qWarning() << "QColorSpace::transformationToColorSpace: colorspace not a valid target";
        return QColorTransform();
    }

    return d_ptr->transformationToColorSpace(colorspace.d_ptr.get());
}

/*!
    Returns the color space as a QVariant.
    \since 5.15
*/
QColorSpace::operator QVariant() const
{
    return QVariant::fromValue(*this);
}

/*!
    Returns the name or short description. If a description hasn't been given
    in setDescription(), the original name of the profile is returned if the
    profile is unmodified, a guessed name is returned if the profile has been
    recognized as a known color space, otherwise an empty string is returned.

    \since 6.2
*/
QString QColorSpace::description() const noexcept
{
    if (d_ptr)
        return d_ptr->userDescription.isEmpty() ? d_ptr->description : d_ptr->userDescription;
    return QString();
}

/*!
    Sets the name or short description of the color space to \a description.

    If set to empty description() will return original or guessed descriptions
    instead.

    \since 6.2
*/
void QColorSpace::setDescription(const QString &description)
{
    detach();
    d_ptr->iccProfile = {};
    d_ptr->userDescription = description;
}

/*****************************************************************************
  QColorSpace stream functions
 *****************************************************************************/
#if !defined(QT_NO_DATASTREAM)
/*!
    \fn QDataStream &operator<<(QDataStream &stream, const QColorSpace &colorSpace)
    \relates QColorSpace

    Writes the given \a colorSpace to the given \a stream as an ICC profile.

    \sa QColorSpace::iccProfile(), {Serializing Qt Data Types}
*/

QDataStream &operator<<(QDataStream &s, const QColorSpace &image)
{
    s << image.iccProfile();
    return s;
}

/*!
    \fn QDataStream &operator>>(QDataStream &stream, QColorSpace &colorSpace)
    \relates QColorSpace

    Reads a color space from the given \a stream and stores it in the given
    \a colorSpace.

    \sa QColorSpace::fromIccProfile(), {Serializing Qt Data Types}
*/

QDataStream &operator>>(QDataStream &s, QColorSpace &colorSpace)
{
    QByteArray iccProfile;
    s >> iccProfile;
    colorSpace = QColorSpace::fromIccProfile(iccProfile);
    return s;
}
#endif // QT_NO_DATASTREAM

#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QColorSpacePrivate::TransferElement &)
{
    return dbg << ":Transfer";
}
QDebug operator<<(QDebug dbg, const QColorMatrix &)
{
    return dbg << ":Matrix";
}
QDebug operator<<(QDebug dbg, const QColorVector &)
{
    return dbg << ":Offset";
}
QDebug operator<<(QDebug dbg, const QColorCLUT &)
{
    return dbg << ":CLUT";
}
QDebug operator<<(QDebug dbg, const QList<QColorSpacePrivate::Element> &elements)
{
    for (auto &&element : elements)
        std::visit([&](auto &&elm) { dbg << elm; }, element);
    return dbg;
}
QDebug operator<<(QDebug dbg, const QColorSpace &colorSpace)
{
    QDebugStateSaver saver(dbg);
    dbg.nospace();
    dbg << "QColorSpace(";
    if (colorSpace.d_ptr) {
        if (colorSpace.d_ptr->namedColorSpace)
            dbg << colorSpace.d_ptr->namedColorSpace << ", ";
        if (!colorSpace.isValid()) {
            dbg << "Invalid";
            if (!colorSpace.d_ptr->iccProfile.isEmpty())
                dbg << " with profile data";
        } else if (colorSpace.d_ptr->isThreeComponentMatrix()) {
            dbg << colorSpace.primaries() << ", " << colorSpace.transferFunction();
            dbg << ", gamma=" << colorSpace.gamma();
        } else {
            if (colorSpace.d_ptr->isPcsLab)
                dbg << "PCSLab, ";
            else
                dbg << "PCSXYZ, ";
            dbg << "A2B" << colorSpace.d_ptr->mAB;
            if (!colorSpace.d_ptr->mBA.isEmpty())
                dbg << ", B2A" << colorSpace.d_ptr->mBA;
        }
    }
    dbg << ')';
    return dbg;
}
#endif

QT_END_NAMESPACE

#include "moc_qcolorspace.cpp"