Krita Source Code Documentation
Loading...
Searching...
No Matches
psd_layer_record.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2009 Boudewijn Rempt <boud@valdyas.org>
3 * SPDX-FileCopyrightText: 2021 L. E. Segovia <amy@amyspark.me>
4 *
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 */
7#include "psd_layer_record.h"
8
9#include <QtEndian>
10
11#include <KoColor.h>
12#include <QBuffer>
13#include <QDataStream>
14#include <QIODevice>
15
16#include "kis_iterator_ng.h"
17#include <algorithm>
18#include <kis_debug.h>
19#include <kis_node.h>
20#include <kis_paint_layer.h>
21
22#include "compression.h"
23#include "psd.h"
24#include "psd_header.h"
25#include "psd_utils.h"
26
27#include <KoColorSpace.h>
28#include <KoColorSpaceMaths.h>
30#include <KoColorSpaceTraits.h>
31
32#include <KoPathShape.h>
33#include <KoPathSegment.h>
34#include <KoPathPoint.h>
35
39
40#include "psd_pixel_utils.h"
41#include <kundo2command.h>
42
43// Just for pretty debug messages
44QString channelIdToChannelType(int channelId, psd_color_mode colormode)
45{
46 switch (channelId) {
47 case -3:
48 return "Real User Supplied Layer Mask (when both a user mask and a vector mask are present";
49 case -2:
50 return "User Supplied Layer Mask";
51 case -1:
52 return "Transparency mask";
53 case 0:
54 switch (colormode) {
55 case Bitmap:
56 case Indexed:
57 return QString("bitmap or indexed: %1").arg(channelId);
58 case Grayscale:
59 case Gray16:
60 return "gray";
61 case RGB:
62 case RGB48:
63 return "red";
64 case Lab:
65 case Lab48:
66 return "L";
67 case CMYK:
68 case CMYK64:
69 return "cyan";
70 case MultiChannel:
72 return QString("multichannel channel %1").arg(channelId);
73 case DuoTone:
74 case Duotone16:
75 return QString("duotone channel %1").arg(channelId);
76 default:
77 return QString("unknown: %1").arg(channelId);
78 };
79 case 1:
80 switch (colormode) {
81 case Bitmap:
82 case Indexed:
83 return QString("WARNING bitmap or indexed: %1").arg(channelId);
84 case Grayscale:
85 case Gray16:
86 return QString("WARNING: %1").arg(channelId);
87 case RGB:
88 case RGB48:
89 return "green";
90 case Lab:
91 case Lab48:
92 return "a";
93 case CMYK:
94 case CMYK64:
95 return "Magenta";
96 case MultiChannel:
98 return QString("multichannel channel %1").arg(channelId);
99 case DuoTone:
100 case Duotone16:
101 return QString("duotone channel %1").arg(channelId);
102 default:
103 return QString("unknown: %1").arg(channelId);
104 };
105 case 2:
106 switch (colormode) {
107 case Bitmap:
108 case Indexed:
109 return QString("WARNING bitmap or indexed: %1").arg(channelId);
110 case Grayscale:
111 case Gray16:
112 return QString("WARNING: %1").arg(channelId);
113 case RGB:
114 case RGB48:
115 return "blue";
116 case Lab:
117 case Lab48:
118 return "b";
119 case CMYK:
120 case CMYK64:
121 return "yellow";
122 case MultiChannel:
123 case DeepMultichannel:
124 return QString("multichannel channel %1").arg(channelId);
125 case DuoTone:
126 case Duotone16:
127 return QString("duotone channel %1").arg(channelId);
128 default:
129 return QString("unknown: %1").arg(channelId);
130 };
131 case 3:
132 switch (colormode) {
133 case Bitmap:
134 case Indexed:
135 return QString("WARNING bitmap or indexed: %1").arg(channelId);
136 case Grayscale:
137 case Gray16:
138 return QString("WARNING: %1").arg(channelId);
139 case RGB:
140 case RGB48:
141 return QString("alpha: %1").arg(channelId);
142 case Lab:
143 case Lab48:
144 return QString("alpha: %1").arg(channelId);
145 case CMYK:
146 case CMYK64:
147 return "Key";
148 case MultiChannel:
149 case DeepMultichannel:
150 return QString("multichannel channel %1").arg(channelId);
151 case DuoTone:
152 case Duotone16:
153 return QString("duotone channel %1").arg(channelId);
154 default:
155 return QString("unknown: %1").arg(channelId);
156 };
157 default:
158 return QString("unknown: %1").arg(channelId);
159 };
160}
161
163 : infoBlocks(header)
164 , m_header(header)
165{
166}
167
168bool PSDLayerRecord::read(QIODevice &io)
169{
170 switch (m_header.byteOrder) {
172 return readImpl<psd_byte_order::psdLittleEndian>(io);
173 default:
174 return readImpl(io);
175 }
176}
177
178template<psd_byte_order byteOrder>
179bool PSDLayerRecord::readImpl(QIODevice &io)
180{
181 dbgFile << "Going to read layer record. Pos:" << io.pos();
182
183 if (!psdread<byteOrder>(io, top) || !psdread<byteOrder>(io, left) || !psdread<byteOrder>(io, bottom) || !psdread<byteOrder>(io, right)
184 || !psdread<byteOrder>(io, nChannels)) {
185 error = "could not read layer record";
186 return false;
187 }
188
189 dbgFile << "\ttop" << top << "left" << left << "bottom" << bottom << "right" << right << "number of channels" << nChannels;
190
191 Q_ASSERT(top <= bottom);
192 Q_ASSERT(left <= right);
193 Q_ASSERT(nChannels > 0);
194
195 if (nChannels < 1) {
196 error = QString("Not enough channels. Got: %1").arg(nChannels);
197 return false;
198 }
199
200 if (nChannels > MAX_CHANNELS) {
201 error = QString("Too many channels. Got: %1").arg(nChannels);
202 return false;
203 }
204
205 for (int i = 0; i < nChannels; ++i) {
206 if (io.atEnd()) {
207 error = "Could not read enough data for channels";
208 return false;
209 }
210
211 ChannelInfo *info = new ChannelInfo;
212
213 if (!psdread<byteOrder>(io, info->channelId)) {
214 error = "could not read channel id";
215 delete info;
216 return false;
217 }
218 bool r;
219 if (m_header.version == 1) {
220 quint32 channelDataLength;
221 r = psdread<byteOrder>(io, channelDataLength);
222 info->channelDataLength = (quint64)channelDataLength;
223 } else {
224 r = psdread<byteOrder>(io, info->channelDataLength);
225 }
226 if (!r) {
227 error = "Could not read length for channel data";
228 delete info;
229 return false;
230 }
231
232 dbgFile << "\tchannel" << i << "id" << channelIdToChannelType(info->channelId, m_header.colormode) << "length" << info->channelDataLength << "start"
233 << info->channelDataStart << "offset" << info->channelOffset << "channelInfoPosition" << info->channelInfoPosition;
234
235 channelInfoRecords << info;
236 }
237
238 if (!psd_read_blendmode<byteOrder>(io, blendModeKey)) {
239 error = QString("Could not read blend mode key. Got: %1").arg(blendModeKey);
240 return false;
241 }
242
243 dbgFile << "\tBlend mode" << blendModeKey << "pos" << io.pos();
244
245 if (!psdread<byteOrder>(io, opacity)) {
246 error = "Could not read opacity";
247 return false;
248 }
249
250 dbgFile << "\tOpacity" << opacity << io.pos();
251
252 if (!psdread<byteOrder>(io, clipping)) {
253 error = "Could not read clipping";
254 return false;
255 }
256
257 dbgFile << "\tclipping" << clipping << io.pos();
258
259 quint8 flags;
260 if (!psdread<byteOrder>(io, flags)) {
261 error = "Could not read flags";
262 return false;
263 }
264 dbgFile << "\tflags" << flags << io.pos();
265
266 transparencyProtected = flags & 1 ? true : false;
267
268 dbgFile << "\ttransparency protected" << transparencyProtected;
269
270 visible = flags & 2 ? false : true;
271
272 dbgFile << "\tvisible" << visible;
273
274 if (flags & 8) {
275 irrelevant = flags & 16 ? true : false;
276 } else {
277 irrelevant = false;
278 }
279
280 dbgFile << "\tirrelevant" << irrelevant;
281
282 dbgFile << "\tfiller at " << io.pos();
283
284 quint8 filler;
285 if (!psdread<byteOrder>(io, filler) || filler != 0) {
286 error = "Could not read padding";
287 return false;
288 }
289
290 dbgFile << "\tGoing to read extra data length" << io.pos();
291
292 quint32 extraDataLength;
293 if (!psdread<byteOrder>(io, extraDataLength) || io.bytesAvailable() < extraDataLength) {
294 error = QString("Could not read extra layer data: %1 at pos %2").arg(extraDataLength).arg(io.pos());
295 return false;
296 }
297
298 dbgFile << "\tExtra data length" << extraDataLength;
299
300 if (extraDataLength > 0) {
301 dbgFile << "Going to read extra data field. Bytes available: " << io.bytesAvailable() << "pos" << io.pos();
302
303 // See https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_22582
304 quint32 layerMaskLength = 1; // invalid...
305 if (!psdread<byteOrder>(io, layerMaskLength) || io.bytesAvailable() < layerMaskLength) {
306 error = QString("Could not read layer mask length: %1").arg(layerMaskLength);
307 return false;
308 }
309
310 layerMask = {};
311
312 if (layerMaskLength == 0) {
313 dbgFile << "\tNo layer mask/adjustment layer data. pos" << io.pos();
314 } else {
315 dbgFile << "\tReading layer mask/adjustment layer data. Length of block:" << layerMaskLength << "pos"
316 << io.pos();
317
318 if (!psdread<byteOrder>(io, layerMask.top) || !psdread<byteOrder>(io, layerMask.left)
319 || !psdread<byteOrder>(io, layerMask.bottom) || !psdread<byteOrder>(io, layerMask.right)
320 || !psdread<byteOrder>(io, layerMask.defaultColor) || !psdread<byteOrder>(io, flags)) {
321 error = "could not read common records of layer mask";
322 return false;
323 }
324
325 layerMask.positionedRelativeToLayer = (flags & 1) != 0;
326 layerMask.disabled = (flags & 2) != 0;
327 layerMask.invertLayerMaskWhenBlending = (flags & 4) != 0;
328 const bool hasMaskParameters = (flags & 8) != 0;
329
330 dbgFile << "\tLayer mask info (original): position relative" << layerMask.positionedRelativeToLayer
331 << ", disabled" << layerMask.disabled << ", invert" << layerMask.invertLayerMaskWhenBlending
332 << ", needs to read mask parameters" << hasMaskParameters;
333
334 if (layerMaskLength == 20) {
335 quint16 padding = 0;
336 if (!psdread<byteOrder>(io, padding)) {
337 error = "Could not read layer mask padding";
338 return false;
339 }
340 } else {
341 quint32 remainingBlockLength = layerMaskLength - 18;
342
343 dbgFile << "\tReading selective records from layer mask info. Remaining block length"
344 << remainingBlockLength;
345
346 if (hasMaskParameters) {
347 if (!psdread<byteOrder>(io, flags)) {
348 error = "could not read mask parameters";
349 return false;
350 }
351
352 remainingBlockLength -= 1;
353
354 dbgFile << "\t\tMask parameters" << QString::number(flags, 2) << ". Remaining block length"
355 << remainingBlockLength;
356
357 if (flags & 1) {
358 quint8 dummy = 0;
359 if (!psdread<byteOrder>(io, dummy)) {
360 error = "could not read user mask density";
361 return false;
362 }
363 remainingBlockLength -= sizeof(dummy);
364 }
365
366 if (flags & 2) {
367 double dummy = 0;
368 if (!psdread<byteOrder>(io, dummy)) {
369 error = "could not read user mask feather";
370 return false;
371 }
372 remainingBlockLength -= sizeof(dummy);
373 }
374
375 if (flags & 4) {
376 quint8 dummy = 0;
377 if (!psdread<byteOrder>(io, dummy)) {
378 error = "could not read vector mask density";
379 return false;
380 }
381 remainingBlockLength -= sizeof(dummy);
382 }
383
384 if (flags & 8) {
385 double dummy = 0;
386 if (!psdread<byteOrder>(io, dummy)) {
387 error = "could not read vector mask feather";
388 return false;
389 }
390 remainingBlockLength -= sizeof(dummy);
391 }
392 }
393
394 if (remainingBlockLength >= 1) {
395 if (!psdread<byteOrder>(io, flags)) {
396 error = "could not read 'real' mask record";
397 return false;
398 }
399
400 layerMask.positionedRelativeToLayer = (flags & 1) != 0;
401 layerMask.disabled = (flags & 2) != 0;
402 layerMask.invertLayerMaskWhenBlending = (flags & 4) != 0;
403 const bool hasMaskParameters = (flags & 8) != 0;
404
405 dbgFile << "\t\tLayer mask info (real): position relative" << layerMask.positionedRelativeToLayer
406 << ", disabled" << layerMask.disabled << ", invert" << layerMask.invertLayerMaskWhenBlending
407 << ", needs to read mask parameters" << hasMaskParameters;
408
409 remainingBlockLength -= 1;
410
411 dbgFile << "\t\tRemaining block length" << remainingBlockLength;
412 }
413
414 if (remainingBlockLength >= 1) {
415 if (!psdread<byteOrder>(io, layerMask.defaultColor)) {
416 error = "could not read 'real' default color";
417 return false;
418 }
419 remainingBlockLength -= 1;
420 dbgFile << "\t\tRead 'real' default color. Remaining block length" << remainingBlockLength;
421 }
422
423 if (remainingBlockLength >= 16) {
424 if (!psdread<byteOrder>(io, layerMask.top) || !psdread<byteOrder>(io, layerMask.left)
425 || !psdread<byteOrder>(io, layerMask.bottom) || !psdread<byteOrder>(io, layerMask.right)) {
426 error = "could not read 'real' mask rectangle";
427 return false;
428 }
429 remainingBlockLength -= 16;
430 dbgFile << "\t\tRead 'real' mask rectangle. Remaining block length" << remainingBlockLength;
431 }
432 }
433 }
434
435 // layer blending thingies
436 quint32 blendingDataLength = 0;
437 if (!psdread<byteOrder>(io, blendingDataLength) || io.bytesAvailable() < blendingDataLength) {
438 error = "Could not read extra blending data.";
439 return false;
440 }
441
442 quint32 blendingNchannels = blendingDataLength > 0 ? (blendingDataLength - 8) / 4 / 2 : 0;
443
444 dbgFile << "\tNumber of blending channels:" << blendingNchannels;
445
446 if (blendingDataLength > 0) {
447 if (blendingDataLength > 0) {
448 if (!psdread<byteOrder>(io, blendingRanges.compositeGrayRange.first.blackValues[0])
449 || !psdread<byteOrder>(io, blendingRanges.compositeGrayRange.first.blackValues[1])
450 || !psdread<byteOrder>(io, blendingRanges.compositeGrayRange.first.whiteValues[0])
451 || !psdread<byteOrder>(io, blendingRanges.compositeGrayRange.first.whiteValues[1])) {
452 error = "Could not read blending black/white values";
453 return false;
454 }
455 }
456 blendingDataLength -= 4;
457
458 if (blendingDataLength > 0) {
459 if (!psdread<byteOrder>(io, blendingRanges.compositeGrayRange.second.blackValues[0])
460 || !psdread<byteOrder>(io, blendingRanges.compositeGrayRange.second.blackValues[1])
461 || !psdread<byteOrder>(io, blendingRanges.compositeGrayRange.second.whiteValues[0])
462 || !psdread<byteOrder>(io, blendingRanges.compositeGrayRange.second.whiteValues[1])) {
463 error = "Could not read blending black/white values";
464 return false;
465 }
466 }
467 blendingDataLength -= 4;
468
469 dbgFile << "\tBlending ranges:";
470 dbgFile << "\t\tcomposite gray (source) :" << blendingRanges.compositeGrayRange.first;
471 dbgFile << "\t\tcomposite gray (dest):" << blendingRanges.compositeGrayRange.second;
472
473 for (quint32 i = 0; i < blendingNchannels; ++i) {
476 if (!psdread<byteOrder>(io, src.blackValues[0]) || !psdread<byteOrder>(io, src.blackValues[1]) || !psdread<byteOrder>(io, src.whiteValues[0])
477 || !psdread<byteOrder>(io, src.whiteValues[1]) || !psdread<byteOrder>(io, dst.blackValues[0]) || !psdread<byteOrder>(io, dst.blackValues[1])
478 || !psdread<byteOrder>(io, dst.whiteValues[0]) || !psdread<byteOrder>(io, dst.whiteValues[1])) {
479 error = QString("could not read src/dst range for channel %1").arg(i);
480 return false;
481 }
482 dbgFile << "\t\tread range " << src << "to" << dst << "for channel" << i;
483 blendingRanges.sourceDestinationRanges << qMakePair(src, dst);
484 }
485 }
486
487 dbgFile << "\tGoing to read layer name at" << io.pos();
488 quint8 layerNameLength;
489 if (!psdread<byteOrder>(io, layerNameLength)) {
490 error = "Could not read layer name length";
491 return false;
492 }
493
494 dbgFile << "\tlayer name length unpadded" << layerNameLength << "pos" << io.pos();
495 layerNameLength = ((layerNameLength + 1 + 3) & ~0x03) - 1;
496
497 dbgFile << "\tlayer name length padded" << layerNameLength << "pos" << io.pos();
498 // XXX: This should use psdread_pascalstring
499 layerName = io.read(layerNameLength);
500 dbgFile << "\tlayer name" << layerName << io.pos();
501
502 dbgFile << "\tAbout to read additional info blocks at" << io.pos();
503
504 if (!infoBlocks.read(io)) {
506 return false;
507 }
508
509 if (infoBlocks.keys.contains("luni") && !infoBlocks.unicodeLayerName.isEmpty()) {
511 }
512
513 if (infoBlocks.keys.contains("lspf")) {
515 }
517
518 // Paint Tool SAI blend mode handling. It sets tsly to 0,
519 // the layer opacity to 255 and iOpa to the actual opacity.
520 if (infoBlocks.keys.contains("tsly") && infoBlocks.keys.contains("iOpa") && infoBlocks.transparencyShapesLayer == 0) {
522 saiBlendMode = true;
523 }
524 }
525
526 return valid();
527}
528
529void PSDLayerRecord::write(QIODevice &io,
530 KisPaintDeviceSP layerContentDevice,
531 KisNodeSP onlyTransparencyMask,
532 const QRect &maskRect,
533 psd_section_type sectionType,
534 const QDomDocument &stylesXmlDoc,
535 bool useLfxsLayerStyleFormat)
536{
537 switch (m_header.byteOrder) {
539 return writeImpl<psd_byte_order::psdLittleEndian>(io,
540 layerContentDevice,
541 onlyTransparencyMask,
542 maskRect,
543 sectionType,
544 stylesXmlDoc,
545 useLfxsLayerStyleFormat);
546 default:
547 return writeImpl(io, layerContentDevice, onlyTransparencyMask, maskRect, sectionType, stylesXmlDoc, useLfxsLayerStyleFormat);
548 }
549}
550
551template<psd_byte_order byteOrder>
552void PSDLayerRecord::writeImpl(QIODevice &io,
553 KisPaintDeviceSP layerContentDevice,
554 KisNodeSP onlyTransparencyMask,
555 const QRect &maskRect,
556 psd_section_type sectionType,
557 const QDomDocument &stylesXmlDoc,
558 bool useLfxsLayerStyleFormat)
559{
560 dbgFile << "writing layer info record"
561 << "at" << io.pos();
562
563 m_layerContentDevice = layerContentDevice;
564 m_onlyTransparencyMask = onlyTransparencyMask;
566
567 dbgFile << "saving layer record for " << layerName << "at pos" << io.pos();
568 dbgFile << "\ttop" << top << "left" << left << "bottom" << bottom << "right" << right << "number of channels" << nChannels;
569 Q_ASSERT(left <= right);
570 Q_ASSERT(top <= bottom);
571 Q_ASSERT(nChannels > 0);
572
573 try {
574 {
575 const QRect layerRect(left, top, right - left, bottom - top);
576 KisAslWriterUtils::writeRect<byteOrder>(layerRect, io);
577 }
578
579 {
580 quint16 realNumberOfChannels = nChannels + bool(m_onlyTransparencyMask);
581 SAFE_WRITE_EX(byteOrder, io, realNumberOfChannels);
582 }
583
584 Q_FOREACH (ChannelInfo *channel, channelInfoRecords) {
585 SAFE_WRITE_EX(byteOrder, io, (quint16)channel->channelId);
586
587 channel->channelInfoPosition = static_cast<int>(io.pos());
588
589 // to be filled in when we know how big channel block is
590 const quint32 fakeChannelSize = 0;
591 SAFE_WRITE_EX(byteOrder, io, fakeChannelSize);
592 }
593
595 const quint16 userSuppliedMaskChannelId = -2;
596 SAFE_WRITE_EX(byteOrder, io, userSuppliedMaskChannelId);
597
599
600 const quint32 fakeTransparencyMaskSize = 0;
601 SAFE_WRITE_EX(byteOrder, io, fakeTransparencyMaskSize);
602 }
603
604 // blend mode
605 dbgFile << ppVar(blendModeKey) << ppVar(io.pos());
606
607 KisAslWriterUtils::writeFixedString<byteOrder>("8BIM", io);
608 KisAslWriterUtils::writeFixedString<byteOrder>(blendModeKey, io);
609
610 // For Paint Tool SAI blend modes, the regular layer
611 // opacity is set to 255 and the real opacity is in the
612 // iOpa block instead.
613 SAFE_WRITE_EX(byteOrder, io, saiBlendMode ? quint8(255) : opacity);
614 SAFE_WRITE_EX(byteOrder, io, clipping); // unused
615
616 // visibility and protection
617 quint8 flags = 0;
619 flags |= 1;
620 if (!visible)
621 flags |= 2;
622 flags |= (1 << 3);
623 if (irrelevant) {
624 flags |= (1 << 4);
625 }
626
627 SAFE_WRITE_EX(byteOrder, io, flags);
628
629 {
630 quint8 padding = 0;
631 SAFE_WRITE_EX(byteOrder, io, padding);
632 }
633
634 {
635 // extra fields with their own length tag
637
639 {
640 const quint32 layerMaskDataSize = 20; // support simple case only
641 SAFE_WRITE_EX(byteOrder, io, layerMaskDataSize);
642 }
643
644 KisAslWriterUtils::writeRect<byteOrder>(m_onlyTransparencyMaskRect, io);
645
646 {
647 // NOTE: in PSD the default color of the mask is stored in 1 byte value!
648 // Even when the mask is actually 16/32 bit! I have no idea how it is
649 // actually treated in this case.
651 const quint8 defaultPixel = *m_onlyTransparencyMask->paintDevice()->defaultPixel().data();
652 SAFE_WRITE_EX(byteOrder, io, defaultPixel);
653 }
654
655 {
656 quint8 maskFlags = 0; // nothing serious
657 if (!vectorMask.path.subPaths.isEmpty()) {
658 maskFlags |= 8; // bit 3 = indicates that the user mask actually came from rendering other data
659 }
660 SAFE_WRITE_EX(byteOrder, io, maskFlags);
661
662 const quint16 padding = 0; // 2-byte padding
663 SAFE_WRITE_EX(byteOrder, io, padding);
664 }
665 } else {
666 const quint32 nullLayerMaskDataSize = 0;
667 SAFE_WRITE_EX(byteOrder, io, nullLayerMaskDataSize);
668 }
669
670 {
671 // blending ranges are not implemented yet
672 const quint32 nullBlendingRangesSize = 0;
673 SAFE_WRITE_EX(byteOrder, io, nullBlendingRangesSize);
674 }
675
676 // layer name: Pascal string, padded to a multiple of 4 bytes.
677 psdwrite_pascalstring<byteOrder>(io, layerName, 4);
678
679 PsdAdditionalLayerInfoBlock additionalInfoBlock(m_header);
680
681 // write 'luni' data block
682 additionalInfoBlock.writeLuniBlockEx(io, layerName);
683
684 additionalInfoBlock.writeLspfBlockEx(io, userLocked);
685 additionalInfoBlock.writeLclrBlockEx(io, psdLabelColor(labelColor));
686
687 // write 'lsct' data block
688 if (sectionType != psd_other) {
689 additionalInfoBlock.writeLsctBlockEx(io, sectionType, isPassThrough, blendModeKey);
690 }
691
692 // write 'lfx2' data block
693 if (!stylesXmlDoc.isNull()) {
694 additionalInfoBlock.writeLfx2BlockEx(io, stylesXmlDoc, useLfxsLayerStyleFormat);
695 }
696
697 // write SoCo, GdFl, PtFl data blocks.
698 if (!fillConfig.isNull()) {
699 additionalInfoBlock.writeFillLayerBlockEx(io, fillConfig, fillType);
700 }
701
702 // write 'vmsk' data block
703 if (!vectorMask.path.subPaths.isEmpty()) {
704 additionalInfoBlock.writeVmskBlockEx(io, vectorMask);
705 }
706
707 // write 'tysh' data block
708 if (!textShape.engineData.isEmpty()) {
709 additionalInfoBlock.writeTypeToolBlockEx(io, textShape);
710 }
711
712 // write 'vstk' data block
713 if (!vectorStroke.isNull()) {
714 additionalInfoBlock.writeVectorStrokeDataEx(io, vectorStroke);
715 }
716
717 if (!vectorOriginationData.isNull()) {
719 }
720
721 // write 'tsly' and 'iOpa' data blocks
722 if (saiBlendMode) {
723 additionalInfoBlock.writeSaiBlendBlockEx(io, opacity);
724 }
725 }
728 }
729}
730
732{
733 KisPaintDeviceSP result = dev;
734
735 if (m_header.channelDepth == 16) {
736 result = new KisPaintDevice(*dev);
737 result->convertTo(KoColorSpaceRegistry::instance()->alpha16());
738 } else if (m_header.channelDepth == 32) {
739 result = new KisPaintDevice(*dev);
740 result->convertTo(KoColorSpaceRegistry::instance()->alpha32f());
741 }
742 return result;
743}
744
745quint16 PSDLayerRecord::psdLabelColor(int colorLabelIndex)
746{
747 quint16 color = 0;
748 switch (colorLabelIndex) {
749 case 0: // none
750 color = 0;
751 break;
752 case 1: // Blue
753 color = 5;
754 break;
755 case 2: // Green
756 color = 4;
757 break;
758 case 3: // Yellow
759 color = 3;
760 break;
761 case 4: // Orange
762 color = 2;
763 break;
764 case 5: // Brown, don't save.
765 color = 0;
766 break;
767 case 6: // Red
768 color = 1;
769 break;
770 case 7: // Purple
771 color = 6;
772 break;
773 case 8: // Grey
774 color = 7;
775 break;
776 default:
777 color = 0;
778 }
779 return color;
780}
781
783{
784 int color = 0;
785 switch (labelColor) {
786 case 0:
787 color = 0;
788 break;
789 case 1: // red
790 color = 6;
791 break;
792 case 2: // Orange
793 color = 4;
794 break;
795 case 3: // Yellow
796 color = 3;
797 break;
798 case 4: // Green
799 color = 2;
800 break;
801 case 5: // Blue
802 color = 1;
803 break;
804 case 6: // Purple
805 color = 7;
806 break;
807 case 7: // Grey
808 color = 8;
809 break;
810 default:
811 color = 0;
812 }
813 return color;
814}
815
816template<psd_byte_order byteOrder>
818{
821
822 QByteArray buffer(static_cast<int>(device->pixelSize()) * m_onlyTransparencyMaskRect.width() * m_onlyTransparencyMaskRect.height(), 0);
823 device->readBytes((quint8 *)buffer.data(), m_onlyTransparencyMaskRect);
824
826 (quint8 *)buffer.data(),
827 static_cast<int>(device->pixelSize()),
830 -1,
831 true,
832 byteOrder);
833 }
834}
835
836void PSDLayerRecord::writePixelData(QIODevice &io, psd_compression_type compressionType)
837{
838 try {
839 switch (m_header.byteOrder) {
841 writePixelDataImpl<psd_byte_order::psdLittleEndian>(io, compressionType);
842 break;
843 default:
844 writePixelDataImpl(io, compressionType);
845 break;
846 }
849 }
850}
851
852template<psd_byte_order byteOrder>
854{
855 dbgFile << "writing pixel data for layer" << layerName << "at" << io.pos();
856
858 const QRect rc(left, top, right - left, bottom - top);
859
860 if (rc.isEmpty()) {
861 dbgFile << "Layer is empty! Writing placeholder information.";
862
863 for (int i = 0; i < nChannels; i++) {
864 const ChannelInfo *channelInfo = channelInfoRecords[i];
865 KisAslWriterUtils::OffsetStreamPusher<quint32, byteOrder> channelBlockSizeExternalTag(io, 0, channelInfo->channelInfoPosition);
866 SAFE_WRITE_EX(byteOrder, io, static_cast<quint16>(psd_compression_type::Uncompressed));
867 }
868
869 writeTransparencyMaskPixelData<byteOrder>(io);
870
871 return;
872 }
873
874 // now write all the channels in display order
875 dbgFile << "layer" << layerName;
876
877 const int channelSize = m_header.channelDepth / 8;
878 const psd_color_mode colorMode = m_header.colormode;
879
881 Q_FOREACH (const ChannelInfo *channelInfo, channelInfoRecords) {
882 writingInfoList << PsdPixelUtils::ChannelWritingInfo(channelInfo->channelId, channelInfo->channelInfoPosition);
883 }
884
885 PsdPixelUtils::writePixelDataCommon(io, dev, rc, colorMode, channelSize, true, true, writingInfoList, compressionType, byteOrder);
886 writeTransparencyMaskPixelData<byteOrder>(io);
887}
888
890{
891 // XXX: check validity!
892 return true;
893}
894
896{
897 dbgFile << "Reading pixel data for layer" << layerName << "pos" << io.pos();
898
899 const int channelSize = m_header.channelDepth / 8;
900 const QRect layerRect = QRect(left, top, right - left, bottom - top);
901
902 try {
903 // WARNING: Pixel data is ALWAYS in big endian!!!
906 device->clear();
907 error = e.what();
908 return false;
909 }
910
911 return true;
912}
913
915{
916 QRect result;
917
918 if (channel->channelId < -1) {
920 } else {
921 result = QRect(left, top, right - left, bottom - top);
922 }
923
924 return result;
925}
926
927bool PSDLayerRecord::readMask(QIODevice &io, KisPaintDeviceSP dev, ChannelInfo *channelInfo)
928{
929 KIS_ASSERT_RECOVER(channelInfo->channelId < -1)
930 {
931 return false;
932 }
933
934 dbgFile << "Going to read" << channelIdToChannelType(channelInfo->channelId, m_header.colormode) << "mask";
935
936 QRect maskRect = channelRect(channelInfo);
937 if (maskRect.isEmpty()) {
938 dbgFile << "Empty Channel";
939 return true;
940 }
941
942 // the device must be a pixel selection
943 KIS_ASSERT_RECOVER(dev->pixelSize() == 1)
944 {
945 return false;
946 }
947
949
950 const int pixelSize = m_header.channelDepth == 16 ? 2 : m_header.channelDepth == 32 ? 4 : 1;
951
952 QVector<ChannelInfo *> infoRecords;
953 infoRecords << channelInfo;
954 PsdPixelUtils::readAlphaMaskChannels(io, dev, pixelSize, maskRect, infoRecords);
955
956 return true;
957}
958
959KoPathShape *PSDLayerRecord::constructPathShape(psd_path path, double shapeWidth, double shapeHeight)
960{
961 KoPathShape *shape = new KoPathShape();
962
963 // psd paths are stored normalized.
964 QTransform tf = QTransform::fromScale(shapeWidth, shapeHeight);
965
966 QString nodeTypes;
967 Q_FOREACH(psd_path_sub_path subPath, path.subPaths) {
968 for (int i = 0; i < subPath.nodes.size(); i++) {
969 psd_path_node node = subPath.nodes.at(i);
970 if (i == 0) {
971 shape->moveTo(tf.map(node.node));
972 } else {
973 psd_path_node previousNode = subPath.nodes.at(i-1);
974 if (previousNode.node == previousNode.control2 && node.node == node.control1) {
975 shape->lineTo(tf.map(node.node));
976 } else {
977 shape->curveTo(tf.map(previousNode.control2), tf.map(node.control1), tf.map(node.node));
978 }
979 }
980 if (node.isSmooth) {
981 nodeTypes.append("s");
982 } else {
983 nodeTypes.append("c");
984 }
985 }
986 if (subPath.isClosed) {
987 psd_path_node lastNode = subPath.nodes.last();
988 psd_path_node firstNode = subPath.nodes.first();
989 if (lastNode.node == lastNode.control2 && firstNode.node == firstNode.control1) {
990 shape->lineTo(tf.map(firstNode.node));
991 } else {
992 shape->curveTo(tf.map(lastNode.control2), tf.map(firstNode.control1), tf.map(firstNode.node));
993 }
994 shape->closeMerge();
995 }
996
997 }
998 if (shape->pointCount() > 0) {
999 shape->loadNodeTypes(nodeTypes);
1000 }
1001
1002 return shape;
1003}
1004
1005void PSDLayerRecord::addPathShapeToPSDPath(psd_path &path, KoPathShape *shape, double shapeWidth, double shapeHeight)
1006{
1007 QTransform tf = QTransform::fromScale(shapeWidth, shapeHeight).inverted();
1008 tf = shape->absoluteTransformation()*tf;
1009
1010
1011 for (int i = 0; i < shape->subpathCount(); i++) {
1012 psd_path_sub_path subPath;
1013 subPath.isClosed = shape->isClosedSubpath(i);
1014 while(subPath.nodes.size() < shape->subpathPointCount(i)) {
1015 const KoPathPoint *point = shape->pointByIndex(KoPathPointIndex(i, subPath.nodes.size()));
1016 psd_path_node node;
1017 node.node = tf.map(point->point());
1018 node.control1 = point->activeControlPoint1()? tf.map(point->controlPoint1()): node.node;
1019 node.control2 = point->activeControlPoint2()? tf.map(point->controlPoint2()): node.node;
1020
1021 node.isSmooth = (point->properties().testFlag(KoPathPoint::IsSmooth)
1022 || point->properties().testFlag(KoPathPoint::IsSymmetric));
1023 subPath.nodes.append(node);
1024 }
1025
1026 path.subPaths.append(subPath);
1027 }
1028}
1029
1030QDebug operator<<(QDebug dbg, const PSDLayerRecord &layer)
1031{
1032#ifndef NODEBUG
1033 dbg.nospace() << "valid: " << const_cast<PSDLayerRecord *>(&layer)->valid();
1034 dbg.nospace() << ", name: " << layer.layerName;
1035 dbg.nospace() << ", top: " << layer.top;
1036 dbg.nospace() << ", left:" << layer.left;
1037 dbg.nospace() << ", bottom: " << layer.bottom;
1038 dbg.nospace() << ", right: " << layer.right;
1039 dbg.nospace() << ", number of channels: " << layer.nChannels;
1040 dbg.nospace() << ", blendModeKey: " << layer.blendModeKey;
1041 dbg.nospace() << ", opacity: " << layer.opacity;
1042 dbg.nospace() << ", clipping: " << layer.clipping;
1043 dbg.nospace() << ", transparency protected: " << layer.transparencyProtected;
1044 dbg.nospace() << ", visible: " << layer.visible;
1045 dbg.nospace() << ", irrelevant: " << layer.irrelevant;
1046 dbg.nospace() << ", locked: " << layer.userLocked << "\n";
1047 Q_FOREACH (const ChannelInfo *channel, layer.channelInfoRecords) {
1048 dbg.space() << channel;
1049 }
1050#endif
1051 return dbg.nospace();
1052}
1053
1054QDebug operator<<(QDebug dbg, const ChannelInfo &channel)
1055{
1056#ifndef NODEBUG
1057 dbg.nospace() << "\tChannel type" << channel.channelId << "size: " << channel.channelDataLength << "compression type" << channel.compressionType << "\n";
1058#endif
1059 return dbg.nospace();
1060}
QPair< int, int > KoPathPointIndex
Definition KoPathShape.h:28
quint32 pixelSize() const
virtual void clear()
void setDefaultPixel(const KoColor &defPixel)
const KoColorSpace * colorSpace() const
KoColor defaultPixel() const
void convertTo(const KoColorSpace *dstColorSpace, KoColorConversionTransformation::Intent renderingIntent=KoColorConversionTransformation::internalRenderingIntent(), KoColorConversionTransformation::ConversionFlags conversionFlags=KoColorConversionTransformation::internalConversionFlags(), KUndo2Command *parentCommand=nullptr, KoUpdater *progressUpdater=nullptr)
void readBytes(quint8 *data, qint32 x, qint32 y, qint32 w, qint32 h) const
quint8 * data()
Definition KoColor.h:144
A KoPathPoint represents a point in a path.
PointProperties properties
QPointF point
QPointF controlPoint1
@ IsSmooth
it is smooth, both control points on a line through the point
Definition KoPathPoint.h:41
@ IsSymmetric
it is symmetric, like smooth but control points have same distance to point
Definition KoPathPoint.h:42
bool activeControlPoint1
bool activeControlPoint2
QPointF controlPoint2
The position of a path point within a path shape.
Definition KoPathShape.h:63
int subpathPointCount(int subpathIndex) const
Returns the number of points in a subpath.
bool isClosedSubpath(int subpathIndex) const
Checks if a subpath is closed.
KoPathPoint * lineTo(const QPointF &p)
Adds a new line segment.
void closeMerge()
Closes the current subpath.
KoPathPoint * moveTo(const QPointF &p)
Starts a new Subpath.
int pointCount() const
Returns the number of points in the path.
KoPathPoint * curveTo(const QPointF &c1, const QPointF &c2, const QPointF &p)
Adds a new cubic Bezier curve segment.
int subpathCount() const
Returns the number of subpaths in the path.
void loadNodeTypes(const QString &nodeTypes)
Loads node types.
KoPathPoint * pointByIndex(const KoPathPointIndex &pointIndex) const
Returns the path point specified by a path point index.
QTransform absoluteTransformation() const
Definition KoShape.cpp:330
psd_color_mode colormode
Definition psd_header.h:48
quint16 channelDepth
Definition psd_header.h:47
quint16 version
Definition psd_header.h:43
psd_byte_order byteOrder
Definition psd_header.h:49
bool readImpl(QIODevice &io)
PSDLayerRecord(const PSDHeader &header)
PsdAdditionalLayerInfoBlock infoBlocks
qint64 m_transparencyMaskSizeOffset
KisPaintDeviceSP convertMaskDeviceIfNeeded(KisPaintDeviceSP dev)
QRect m_onlyTransparencyMaskRect
psd_fill_type fillType
void writePixelData(QIODevice &io, psd_compression_type compressionType)
void writeTransparencyMaskPixelData(QIODevice &io)
psd_vector_mask vectorMask
psd_layer_type_shape textShape
bool readPixelData(QIODevice &io, KisPaintDeviceSP device)
void writePixelDataImpl(QIODevice &io, psd_compression_type compressionType)
QDomDocument vectorOriginationData
const PSDHeader m_header
KisPaintDeviceSP m_layerContentDevice
quint16 psdLabelColor(int colorLabelIndex)
LayerBlendingRanges blendingRanges
QVector< ChannelInfo * > channelInfoRecords
QRect channelRect(ChannelInfo *channel) const
QDomDocument vectorStroke
void write(QIODevice &io, KisPaintDeviceSP layerContentDevice, KisNodeSP onlyTransparencyMask, const QRect &maskRect, psd_section_type sectionType, const QDomDocument &stylesXmlDoc, bool useLfxsLayerStyleFormat)
KoPathShape * constructPathShape(psd_path path, double shapeWidth, double shapeHeight)
constructPathShape create a KoPathshape based on a psd_path struct, used in vector masks and path res...
void addPathShapeToPSDPath(psd_path &path, KoPathShape *shape, double shapeWidth, double shapeHeight)
addPathShapeToPSDPath add all KoPathShape subpaths to the given psd_path struct.
int kritaColorLabelIndex(quint16 labelColor)
QDomDocument fillConfig
KisNodeSP m_onlyTransparencyMask
LayerMaskData layerMask
void writeImpl(QIODevice &io, KisPaintDeviceSP layerContentDevice, KisNodeSP onlyTransparencyMask, const QRect &maskRect, psd_section_type sectionType, const QDomDocument &stylesXmlDoc, bool useLfxsLayerStyleFormat)
bool read(QIODevice &io)
bool readMask(QIODevice &io, KisPaintDeviceSP dev, ChannelInfo *channel)
The PsdAdditionalLayerInfoBlock class implements the Additional Layer Information block.
void writeLfx2BlockEx(QIODevice &io, const QDomDocument &stylesXmlDoc, bool useLfxsLayerStyleFormat)
void writeFillLayerBlockEx(QIODevice &io, const QDomDocument &fillConfig, psd_fill_type type)
void writeVmskBlockEx(QIODevice &io, psd_vector_mask mask)
void writeVectorOriginationDataEx(QIODevice &io, const QDomDocument &vectorOrigination)
void writeLspfBlockEx(QIODevice &io, const bool lock)
void writeLsctBlockEx(QIODevice &io, psd_section_type sectionType, bool isPassThrough, const QString &blendModeKey)
void writeVectorStrokeDataEx(QIODevice &io, const QDomDocument &vectorStroke)
void writeLuniBlockEx(QIODevice &io, const QString &layerName)
void writeSaiBlendBlockEx(QIODevice &io, quint8 opacity)
void writeLclrBlockEx(QIODevice &io, const quint16 &labelColor)
void writeTypeToolBlockEx(QIODevice &io, psd_layer_type_shape typeTool)
#define SAFE_WRITE_EX(byteOrder, device, varname)
#define KIS_ASSERT_RECOVER(cond)
Definition kis_assert.h:55
#define KIS_ASSERT_RECOVER_NOOP(cond)
Definition kis_assert.h:97
#define PREPEND_METHOD(msg)
Definition kis_debug.h:180
#define ppVar(var)
Definition kis_debug.h:163
#define dbgFile
Definition kis_debug.h:57
void writePixelDataCommon(QIODevice &io, KisPaintDeviceSP dev, const QRect &rc, psd_color_mode colorMode, int channelSize, bool alphaFirst, const bool writeCompressionType, QVector< ChannelWritingInfo > &writingInfoList, psd_compression_type compressionType, psd_byte_order byteOrder)
void readChannels(QIODevice &io, KisPaintDeviceSP device, psd_color_mode colorMode, int channelSize, const QRect &layerRect, QVector< ChannelInfo * > infoRecords, psd_byte_order byteOrder)
void writeChannelDataRLE(QIODevice &io, const quint8 *plane, const int channelSize, const QRect &rc, const qint64 sizeFieldOffset, const qint64 rleBlockOffset, const bool writeCompressionType, psd_byte_order byteOrder)
void readAlphaMaskChannels(QIODevice &io, KisPaintDeviceSP device, int channelSize, const QRect &layerRect, QVector< ChannelInfo * > infoRecords, psd_byte_order byteOrder)
psd_compression_type
Definition psd.h:39
@ Uncompressed
Definition psd.h:40
psd_section_type
Definition psd.h:144
@ psd_other
Definition psd.h:144
const int MAX_CHANNELS
Definition psd.h:27
psd_color_mode
Definition psd.h:50
@ CMYK64
Definition psd.h:62
@ Lab
Definition psd.h:58
@ RGB
Definition psd.h:54
@ DuoTone
Definition psd.h:57
@ RGB48
Definition psd.h:60
@ Duotone16
Definition psd.h:64
@ CMYK
Definition psd.h:55
@ Gray16
Definition psd.h:59
@ Indexed
Definition psd.h:53
@ MultiChannel
Definition psd.h:56
@ DeepMultichannel
Definition psd.h:63
@ Grayscale
Definition psd.h:52
@ Bitmap
Definition psd.h:51
@ Lab48
Definition psd.h:61
QString channelIdToChannelType(int channelId, psd_color_mode colormode)
QDebug operator<<(QDebug dbg, const PSDLayerRecord &layer)
psd_compression_type compressionType
quint64 channelDataLength
quint64 channelDataStart
virtual KisPaintDeviceSP paintDevice() const =0
static KoColorSpaceRegistry * instance()
QVector< QPair< LayerBlendingRange, LayerBlendingRange > > sourceDestinationRanges
QPair< LayerBlendingRange, LayerBlendingRange > compositeGrayRange
QList< psd_path_sub_path > subPaths