1/*
2 * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
8 *     * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *     * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 *     * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31#include "config.h"
32#include "ICOImageDecoder.h"
33
34#include <algorithm>
35
36#include "BMPImageReader.h"
37#include "PNGImageDecoder.h"
38#include <wtf/PassOwnPtr.h>
39
40namespace WebCore {
41
42// Number of bits in .ICO/.CUR used to store the directory and its entries,
43// respectively (doesn't match sizeof values for member structs since we omit
44// some fields).
45static const size_t sizeOfDirectory = 6;
46static const size_t sizeOfDirEntry = 16;
47
48ICOImageDecoder::ICOImageDecoder(ImageSource::AlphaOption alphaOption,
49                                 ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
50    : ImageDecoder(alphaOption, gammaAndColorProfileOption)
51    , m_decodedOffset(0)
52{
53}
54
55ICOImageDecoder::~ICOImageDecoder()
56{
57}
58
59void ICOImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
60{
61    if (failed())
62        return;
63
64    ImageDecoder::setData(data, allDataReceived);
65
66    for (BMPReaders::iterator i(m_bmpReaders.begin()); i != m_bmpReaders.end(); ++i) {
67        if (*i)
68            (*i)->setData(data);
69    }
70    for (size_t i = 0; i < m_pngDecoders.size(); ++i)
71        setDataForPNGDecoderAtIndex(i);
72}
73
74bool ICOImageDecoder::isSizeAvailable()
75{
76    if (!ImageDecoder::isSizeAvailable())
77        decode(0, true);
78
79    return ImageDecoder::isSizeAvailable();
80}
81
82IntSize ICOImageDecoder::size() const
83{
84    return m_frameSize.isEmpty() ? ImageDecoder::size() : m_frameSize;
85}
86
87IntSize ICOImageDecoder::frameSizeAtIndex(size_t index) const
88{
89    return (index && (index < m_dirEntries.size())) ? m_dirEntries[index].m_size : size();
90}
91
92bool ICOImageDecoder::setSize(unsigned width, unsigned height)
93{
94    // The size calculated inside the BMPImageReader had better match the one in
95    // the icon directory.
96    return m_frameSize.isEmpty() ? ImageDecoder::setSize(width, height) : ((IntSize(width, height) == m_frameSize) || setFailed());
97}
98
99size_t ICOImageDecoder::frameCount()
100{
101    decode(0, true);
102    if (m_frameBufferCache.isEmpty()) {
103        m_frameBufferCache.resize(m_dirEntries.size());
104        for (size_t i = 0; i < m_dirEntries.size(); ++i)
105            m_frameBufferCache[i].setPremultiplyAlpha(m_premultiplyAlpha);
106    }
107    // CAUTION: We must not resize m_frameBufferCache again after this, as
108    // decodeAtIndex() may give a BMPImageReader a pointer to one of the
109    // entries.
110    return m_frameBufferCache.size();
111}
112
113ImageFrame* ICOImageDecoder::frameBufferAtIndex(size_t index)
114{
115    // Ensure |index| is valid.
116    if (index >= frameCount())
117        return 0;
118
119    ImageFrame* buffer = &m_frameBufferCache[index];
120    if (buffer->status() != ImageFrame::FrameComplete)
121        decode(index, false);
122    return buffer;
123}
124
125bool ICOImageDecoder::setFailed()
126{
127    m_bmpReaders.clear();
128    m_pngDecoders.clear();
129    return ImageDecoder::setFailed();
130}
131
132bool ICOImageDecoder::hotSpot(IntPoint& hotSpot) const
133{
134    // When unspecified, the default frame is always frame 0. This is consistent with
135    // BitmapImage where currentFrame() starts at 0 and only increases when animation is
136    // requested.
137    return hotSpotAtIndex(0, hotSpot);
138}
139
140bool ICOImageDecoder::hotSpotAtIndex(size_t index, IntPoint& hotSpot) const
141{
142    if (index >= m_dirEntries.size() || m_fileType != CURSOR)
143        return false;
144
145    hotSpot = m_dirEntries[index].m_hotSpot;
146    return true;
147}
148
149
150// static
151bool ICOImageDecoder::compareEntries(const IconDirectoryEntry& a, const IconDirectoryEntry& b)
152{
153    // Larger icons are better.  After that, higher bit-depth icons are better.
154    const int aEntryArea = a.m_size.width() * a.m_size.height();
155    const int bEntryArea = b.m_size.width() * b.m_size.height();
156    return (aEntryArea == bEntryArea) ? (a.m_bitCount > b.m_bitCount) : (aEntryArea > bEntryArea);
157}
158
159void ICOImageDecoder::setDataForPNGDecoderAtIndex(size_t index)
160{
161    if (!m_pngDecoders[index])
162        return;
163
164    const IconDirectoryEntry& dirEntry = m_dirEntries[index];
165    // Copy out PNG data to a separate vector and send to the PNG decoder.
166    // FIXME: Save this copy by making the PNG decoder able to take an
167    // optional offset.
168    RefPtr<SharedBuffer> pngData(SharedBuffer::create(&m_data->data()[dirEntry.m_imageOffset], m_data->size() - dirEntry.m_imageOffset));
169    m_pngDecoders[index]->setData(pngData.get(), isAllDataReceived());
170}
171
172void ICOImageDecoder::decode(size_t index, bool onlySize)
173{
174    if (failed())
175        return;
176
177    // If we couldn't decode the image but we've received all the data, decoding
178    // has failed.
179    if ((!decodeDirectory() || (!onlySize && !decodeAtIndex(index))) && isAllDataReceived())
180        setFailed();
181    // If we're done decoding this frame, we don't need the BMPImageReader or
182    // PNGImageDecoder anymore.  (If we failed, these have already been
183    // cleared.)
184    else if ((m_frameBufferCache.size() > index) && (m_frameBufferCache[index].status() == ImageFrame::FrameComplete)) {
185        m_bmpReaders[index].clear();
186        m_pngDecoders[index].clear();
187    }
188}
189
190bool ICOImageDecoder::decodeDirectory()
191{
192    // Read and process directory.
193    if ((m_decodedOffset < sizeOfDirectory) && !processDirectory())
194        return false;
195
196    // Read and process directory entries.
197    return (m_decodedOffset >= (sizeOfDirectory + (m_dirEntries.size() * sizeOfDirEntry))) || processDirectoryEntries();
198}
199
200bool ICOImageDecoder::decodeAtIndex(size_t index)
201{
202    ASSERT_WITH_SECURITY_IMPLICATION(index < m_dirEntries.size());
203    const IconDirectoryEntry& dirEntry = m_dirEntries[index];
204    const ImageType imageType = imageTypeAtIndex(index);
205    if (imageType == Unknown)
206        return false; // Not enough data to determine image type yet.
207
208    if (imageType == BMP) {
209        if (!m_bmpReaders[index]) {
210            // We need to have already sized m_frameBufferCache before this, and
211            // we must not resize it again later (see caution in frameCount()).
212            ASSERT(m_frameBufferCache.size() == m_dirEntries.size());
213            m_bmpReaders[index] = adoptPtr(new BMPImageReader(this, dirEntry.m_imageOffset, 0, true));
214            m_bmpReaders[index]->setData(m_data.get());
215            m_bmpReaders[index]->setBuffer(&m_frameBufferCache[index]);
216        }
217        m_frameSize = dirEntry.m_size;
218        bool result = m_bmpReaders[index]->decodeBMP(false);
219        m_frameSize = IntSize();
220        return result;
221    }
222
223    if (!m_pngDecoders[index]) {
224        m_pngDecoders[index] = adoptPtr(
225            new PNGImageDecoder(m_premultiplyAlpha ? ImageSource::AlphaPremultiplied : ImageSource::AlphaNotPremultiplied,
226                                m_ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied));
227        setDataForPNGDecoderAtIndex(index);
228    }
229    // Fail if the size the PNGImageDecoder calculated does not match the size
230    // in the directory.
231    if (m_pngDecoders[index]->isSizeAvailable() && (m_pngDecoders[index]->size() != dirEntry.m_size))
232        return setFailed();
233    m_frameBufferCache[index] = *m_pngDecoders[index]->frameBufferAtIndex(0);
234    return !m_pngDecoders[index]->failed() || setFailed();
235}
236
237bool ICOImageDecoder::processDirectory()
238{
239    // Read directory.
240    ASSERT(!m_decodedOffset);
241    if (m_data->size() < sizeOfDirectory)
242        return false;
243    const uint16_t fileType = readUint16(2);
244    const uint16_t idCount = readUint16(4);
245    m_decodedOffset = sizeOfDirectory;
246
247    // See if this is an icon filetype we understand, and make sure we have at
248    // least one entry in the directory.
249    if (((fileType != ICON) && (fileType != CURSOR)) || (!idCount))
250        return setFailed();
251
252    m_fileType = static_cast<FileType>(fileType);
253
254    // Enlarge member vectors to hold all the entries.
255    m_dirEntries.resize(idCount);
256    m_bmpReaders.resize(idCount);
257    m_pngDecoders.resize(idCount);
258    return true;
259}
260
261bool ICOImageDecoder::processDirectoryEntries()
262{
263    // Read directory entries.
264    ASSERT(m_decodedOffset == sizeOfDirectory);
265    if ((m_decodedOffset > m_data->size()) || ((m_data->size() - m_decodedOffset) < (m_dirEntries.size() * sizeOfDirEntry)))
266        return false;
267    for (IconDirectoryEntries::iterator i(m_dirEntries.begin()); i != m_dirEntries.end(); ++i)
268        *i = readDirectoryEntry();  // Updates m_decodedOffset.
269
270    // Make sure the specified image offsets are past the end of the directory
271    // entries.
272    for (IconDirectoryEntries::iterator i(m_dirEntries.begin()); i != m_dirEntries.end(); ++i) {
273        if (i->m_imageOffset < m_decodedOffset)
274            return setFailed();
275    }
276
277    // Arrange frames in decreasing quality order.
278    std::sort(m_dirEntries.begin(), m_dirEntries.end(), compareEntries);
279
280    // The image size is the size of the largest entry.
281    const IconDirectoryEntry& dirEntry = m_dirEntries.first();
282    // Technically, this next call shouldn't be able to fail, since the width
283    // and height here are each <= 256, and |m_frameSize| is empty.
284    return setSize(dirEntry.m_size.width(), dirEntry.m_size.height());
285}
286
287ICOImageDecoder::IconDirectoryEntry ICOImageDecoder::readDirectoryEntry()
288{
289    // Read icon data.
290    // The casts to uint8_t in the next few lines are because that's the on-disk
291    // type of the width and height values.  Storing them in ints (instead of
292    // matching uint8_ts) is so we can record dimensions of size 256 (which is
293    // what a zero byte really means).
294    int width = static_cast<uint8_t>(m_data->data()[m_decodedOffset]);
295    if (!width)
296        width = 256;
297    int height = static_cast<uint8_t>(m_data->data()[m_decodedOffset + 1]);
298    if (!height)
299        height = 256;
300    IconDirectoryEntry entry;
301    entry.m_size = IntSize(width, height);
302    if (m_fileType == CURSOR) {
303        entry.m_bitCount = 0;
304        entry.m_hotSpot = IntPoint(readUint16(4), readUint16(6));
305    } else {
306        entry.m_bitCount = readUint16(6);
307        entry.m_hotSpot = IntPoint();
308    }
309    entry.m_imageOffset = readUint32(12);
310
311    // Some icons don't have a bit depth, only a color count.  Convert the
312    // color count to the minimum necessary bit depth.  It doesn't matter if
313    // this isn't quite what the bitmap info header says later, as we only use
314    // this value to determine which icon entry is best.
315    if (!entry.m_bitCount) {
316        int colorCount = static_cast<uint8_t>(m_data->data()[m_decodedOffset + 2]);
317        if (!colorCount)
318            colorCount = 256;  // Vague in the spec, needed by real-world icons.
319        for (--colorCount; colorCount; colorCount >>= 1)
320            ++entry.m_bitCount;
321    }
322
323    m_decodedOffset += sizeOfDirEntry;
324    return entry;
325}
326
327ICOImageDecoder::ImageType ICOImageDecoder::imageTypeAtIndex(size_t index)
328{
329    // Check if this entry is a BMP or a PNG; we need 4 bytes to check the magic
330    // number.
331    ASSERT_WITH_SECURITY_IMPLICATION(index < m_dirEntries.size());
332    const uint32_t imageOffset = m_dirEntries[index].m_imageOffset;
333    if ((imageOffset > m_data->size()) || ((m_data->size() - imageOffset) < 4))
334        return Unknown;
335    return strncmp(&m_data->data()[imageOffset], "\x89PNG", 4) ? BMP : PNG;
336}
337
338}
339