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 "platform/image-decoders/ico/ICOImageDecoder.h"
33
34#include <algorithm>
35
36#include "platform/PlatformInstrumentation.h"
37#include "platform/image-decoders/png/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    size_t maxDecodedBytes)
51    : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes)
52    , m_decodedOffset(0)
53{
54}
55
56ICOImageDecoder::~ICOImageDecoder()
57{
58}
59
60void ICOImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
61{
62    if (failed())
63        return;
64
65    ImageDecoder::setData(data, allDataReceived);
66
67    for (BMPReaders::iterator i(m_bmpReaders.begin()); i != m_bmpReaders.end(); ++i) {
68        if (*i)
69            (*i)->setData(data);
70    }
71    for (size_t i = 0; i < m_pngDecoders.size(); ++i)
72        setDataForPNGDecoderAtIndex(i);
73}
74
75bool ICOImageDecoder::isSizeAvailable()
76{
77    if (!ImageDecoder::isSizeAvailable())
78        decode(0, true);
79
80    return ImageDecoder::isSizeAvailable();
81}
82
83IntSize ICOImageDecoder::size() const
84{
85    return m_frameSize.isEmpty() ? ImageDecoder::size() : m_frameSize;
86}
87
88IntSize ICOImageDecoder::frameSizeAtIndex(size_t index) const
89{
90    return (index && (index < m_dirEntries.size())) ? m_dirEntries[index].m_size : size();
91}
92
93bool ICOImageDecoder::setSize(unsigned width, unsigned height)
94{
95    // The size calculated inside the BMPImageReader had better match the one in
96    // the icon directory.
97    return m_frameSize.isEmpty() ? ImageDecoder::setSize(width, height) : ((IntSize(width, height) == m_frameSize) || setFailed());
98}
99
100size_t ICOImageDecoder::frameCount()
101{
102    decode(0, true);
103    if (m_frameBufferCache.isEmpty()) {
104        m_frameBufferCache.resize(m_dirEntries.size());
105        for (size_t i = 0; i < m_dirEntries.size(); ++i) {
106            m_frameBufferCache[i].setPremultiplyAlpha(m_premultiplyAlpha);
107            m_frameBufferCache[i].setRequiredPreviousFrameIndex(kNotFound);
108        }
109    }
110    // CAUTION: We must not resize m_frameBufferCache again after this, as
111    // decodeAtIndex() may give a BMPImageReader a pointer to one of the
112    // entries.
113    return m_frameBufferCache.size();
114}
115
116ImageFrame* ICOImageDecoder::frameBufferAtIndex(size_t index)
117{
118    // Ensure |index| is valid.
119    if (index >= frameCount())
120        return 0;
121
122    ImageFrame* buffer = &m_frameBufferCache[index];
123    if (buffer->status() != ImageFrame::FrameComplete) {
124        PlatformInstrumentation::willDecodeImage("ICO");
125        decode(index, false);
126        PlatformInstrumentation::didDecodeImage();
127    }
128    return buffer;
129}
130
131bool ICOImageDecoder::setFailed()
132{
133    m_bmpReaders.clear();
134    m_pngDecoders.clear();
135    return ImageDecoder::setFailed();
136}
137
138bool ICOImageDecoder::hotSpot(IntPoint& hotSpot) const
139{
140    // When unspecified, the default frame is always frame 0. This is consistent with
141    // BitmapImage where currentFrame() starts at 0 and only increases when animation is
142    // requested.
143    return hotSpotAtIndex(0, hotSpot);
144}
145
146bool ICOImageDecoder::hotSpotAtIndex(size_t index, IntPoint& hotSpot) const
147{
148    if (index >= m_dirEntries.size() || m_fileType != CURSOR)
149        return false;
150
151    hotSpot = m_dirEntries[index].m_hotSpot;
152    return true;
153}
154
155
156// static
157bool ICOImageDecoder::compareEntries(const IconDirectoryEntry& a, const IconDirectoryEntry& b)
158{
159    // Larger icons are better.  After that, higher bit-depth icons are better.
160    const int aEntryArea = a.m_size.width() * a.m_size.height();
161    const int bEntryArea = b.m_size.width() * b.m_size.height();
162    return (aEntryArea == bEntryArea) ? (a.m_bitCount > b.m_bitCount) : (aEntryArea > bEntryArea);
163}
164
165void ICOImageDecoder::setDataForPNGDecoderAtIndex(size_t index)
166{
167    if (!m_pngDecoders[index])
168        return;
169
170    const IconDirectoryEntry& dirEntry = m_dirEntries[index];
171    // Copy out PNG data to a separate vector and send to the PNG decoder.
172    // FIXME: Save this copy by making the PNG decoder able to take an
173    // optional offset.
174    RefPtr<SharedBuffer> pngData(SharedBuffer::create(&m_data->data()[dirEntry.m_imageOffset], m_data->size() - dirEntry.m_imageOffset));
175    m_pngDecoders[index]->setData(pngData.get(), isAllDataReceived());
176}
177
178void ICOImageDecoder::decode(size_t index, bool onlySize)
179{
180    if (failed())
181        return;
182
183    // If we couldn't decode the image but we've received all the data, decoding
184    // has failed.
185    if ((!decodeDirectory() || (!onlySize && !decodeAtIndex(index))) && isAllDataReceived())
186        setFailed();
187    // If we're done decoding this frame, we don't need the BMPImageReader or
188    // PNGImageDecoder anymore.  (If we failed, these have already been
189    // cleared.)
190    else if ((m_frameBufferCache.size() > index) && (m_frameBufferCache[index].status() == ImageFrame::FrameComplete)) {
191        m_bmpReaders[index].clear();
192        m_pngDecoders[index].clear();
193    }
194}
195
196bool ICOImageDecoder::decodeDirectory()
197{
198    // Read and process directory.
199    if ((m_decodedOffset < sizeOfDirectory) && !processDirectory())
200        return false;
201
202    // Read and process directory entries.
203    return (m_decodedOffset >= (sizeOfDirectory + (m_dirEntries.size() * sizeOfDirEntry))) || processDirectoryEntries();
204}
205
206bool ICOImageDecoder::decodeAtIndex(size_t index)
207{
208    ASSERT_WITH_SECURITY_IMPLICATION(index < m_dirEntries.size());
209    const IconDirectoryEntry& dirEntry = m_dirEntries[index];
210    const ImageType imageType = imageTypeAtIndex(index);
211    if (imageType == Unknown)
212        return false; // Not enough data to determine image type yet.
213
214    if (imageType == BMP) {
215        if (!m_bmpReaders[index]) {
216            // We need to have already sized m_frameBufferCache before this, and
217            // we must not resize it again later (see caution in frameCount()).
218            ASSERT(m_frameBufferCache.size() == m_dirEntries.size());
219            m_bmpReaders[index] = adoptPtr(new BMPImageReader(this, dirEntry.m_imageOffset, 0, true));
220            m_bmpReaders[index]->setData(m_data.get());
221            m_bmpReaders[index]->setBuffer(&m_frameBufferCache[index]);
222        }
223        m_frameSize = dirEntry.m_size;
224        bool result = m_bmpReaders[index]->decodeBMP(false);
225        m_frameSize = IntSize();
226        return result;
227    }
228
229    if (!m_pngDecoders[index]) {
230        m_pngDecoders[index] = adoptPtr(
231            new PNGImageDecoder(m_premultiplyAlpha ? ImageSource::AlphaPremultiplied : ImageSource::AlphaNotPremultiplied,
232                m_ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied, m_maxDecodedBytes));
233        setDataForPNGDecoderAtIndex(index);
234    }
235    // Fail if the size the PNGImageDecoder calculated does not match the size
236    // in the directory.
237    if (m_pngDecoders[index]->isSizeAvailable() && (m_pngDecoders[index]->size() != dirEntry.m_size))
238        return setFailed();
239    m_frameBufferCache[index] = *m_pngDecoders[index]->frameBufferAtIndex(0);
240    m_frameBufferCache[index].setPremultiplyAlpha(m_premultiplyAlpha);
241    m_frameBufferCache[index].setRequiredPreviousFrameIndex(kNotFound);
242    return !m_pngDecoders[index]->failed() || setFailed();
243}
244
245bool ICOImageDecoder::processDirectory()
246{
247    // Read directory.
248    ASSERT(!m_decodedOffset);
249    if (m_data->size() < sizeOfDirectory)
250        return false;
251    const uint16_t fileType = readUint16(2);
252    const uint16_t idCount = readUint16(4);
253    m_decodedOffset = sizeOfDirectory;
254
255    // See if this is an icon filetype we understand, and make sure we have at
256    // least one entry in the directory.
257    if (((fileType != ICON) && (fileType != CURSOR)) || (!idCount))
258        return setFailed();
259
260    m_fileType = static_cast<FileType>(fileType);
261
262    // Enlarge member vectors to hold all the entries.
263    m_dirEntries.resize(idCount);
264    m_bmpReaders.resize(idCount);
265    m_pngDecoders.resize(idCount);
266    return true;
267}
268
269bool ICOImageDecoder::processDirectoryEntries()
270{
271    // Read directory entries.
272    ASSERT(m_decodedOffset == sizeOfDirectory);
273    if ((m_decodedOffset > m_data->size()) || ((m_data->size() - m_decodedOffset) < (m_dirEntries.size() * sizeOfDirEntry)))
274        return false;
275    for (IconDirectoryEntries::iterator i(m_dirEntries.begin()); i != m_dirEntries.end(); ++i)
276        *i = readDirectoryEntry();  // Updates m_decodedOffset.
277
278    // Make sure the specified image offsets are past the end of the directory
279    // entries.
280    for (IconDirectoryEntries::iterator i(m_dirEntries.begin()); i != m_dirEntries.end(); ++i) {
281        if (i->m_imageOffset < m_decodedOffset)
282            return setFailed();
283    }
284
285    // Arrange frames in decreasing quality order.
286    std::sort(m_dirEntries.begin(), m_dirEntries.end(), compareEntries);
287
288    // The image size is the size of the largest entry.
289    const IconDirectoryEntry& dirEntry = m_dirEntries.first();
290    // Technically, this next call shouldn't be able to fail, since the width
291    // and height here are each <= 256, and |m_frameSize| is empty.
292    return setSize(dirEntry.m_size.width(), dirEntry.m_size.height());
293}
294
295ICOImageDecoder::IconDirectoryEntry ICOImageDecoder::readDirectoryEntry()
296{
297    // Read icon data.
298    // The casts to uint8_t in the next few lines are because that's the on-disk
299    // type of the width and height values.  Storing them in ints (instead of
300    // matching uint8_ts) is so we can record dimensions of size 256 (which is
301    // what a zero byte really means).
302    int width = static_cast<uint8_t>(m_data->data()[m_decodedOffset]);
303    if (!width)
304        width = 256;
305    int height = static_cast<uint8_t>(m_data->data()[m_decodedOffset + 1]);
306    if (!height)
307        height = 256;
308    IconDirectoryEntry entry;
309    entry.m_size = IntSize(width, height);
310    if (m_fileType == CURSOR) {
311        entry.m_bitCount = 0;
312        entry.m_hotSpot = IntPoint(readUint16(4), readUint16(6));
313    } else {
314        entry.m_bitCount = readUint16(6);
315        entry.m_hotSpot = IntPoint();
316    }
317    entry.m_imageOffset = readUint32(12);
318
319    // Some icons don't have a bit depth, only a color count.  Convert the
320    // color count to the minimum necessary bit depth.  It doesn't matter if
321    // this isn't quite what the bitmap info header says later, as we only use
322    // this value to determine which icon entry is best.
323    if (!entry.m_bitCount) {
324        int colorCount = static_cast<uint8_t>(m_data->data()[m_decodedOffset + 2]);
325        if (!colorCount)
326            colorCount = 256;  // Vague in the spec, needed by real-world icons.
327        for (--colorCount; colorCount; colorCount >>= 1)
328            ++entry.m_bitCount;
329    }
330
331    m_decodedOffset += sizeOfDirEntry;
332    return entry;
333}
334
335ICOImageDecoder::ImageType ICOImageDecoder::imageTypeAtIndex(size_t index)
336{
337    // Check if this entry is a BMP or a PNG; we need 4 bytes to check the magic
338    // number.
339    ASSERT_WITH_SECURITY_IMPLICATION(index < m_dirEntries.size());
340    const uint32_t imageOffset = m_dirEntries[index].m_imageOffset;
341    if ((imageOffset > m_data->size()) || ((m_data->size() - imageOffset) < 4))
342        return Unknown;
343    return strncmp(&m_data->data()[imageOffset], "\x89PNG", 4) ? BMP : PNG;
344}
345
346}
347