2 * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
20 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
22 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 #include "core/html/ImageDocument.h"
28 #include "HTMLNames.h"
29 #include "bindings/v8/ExceptionStatePlaceholder.h"
30 #include "core/dom/RawDataDocumentParser.h"
31 #include "core/events/EventListener.h"
32 #include "core/events/MouseEvent.h"
33 #include "core/events/ThreadLocalEventNames.h"
34 #include "core/fetch/ImageResource.h"
35 #include "core/html/HTMLBodyElement.h"
36 #include "core/html/HTMLHeadElement.h"
37 #include "core/html/HTMLHtmlElement.h"
38 #include "core/html/HTMLImageElement.h"
39 #include "core/html/HTMLMetaElement.h"
40 #include "core/loader/DocumentLoader.h"
41 #include "core/loader/FrameLoader.h"
42 #include "core/loader/FrameLoaderClient.h"
43 #include "core/frame/Frame.h"
44 #include "core/frame/FrameView.h"
45 #include "core/frame/Settings.h"
46 #include "wtf/text/StringBuilder.h"
52 using namespace HTMLNames;
54 class ImageEventListener : public EventListener {
56 static PassRefPtr<ImageEventListener> create(ImageDocument* document) { return adoptRef(new ImageEventListener(document)); }
57 static const ImageEventListener* cast(const EventListener* listener)
59 return listener->type() == ImageEventListenerType
60 ? static_cast<const ImageEventListener*>(listener)
64 virtual bool operator==(const EventListener& other);
67 ImageEventListener(ImageDocument* document)
68 : EventListener(ImageEventListenerType)
73 virtual void handleEvent(ExecutionContext*, Event*);
78 class ImageDocumentParser : public RawDataDocumentParser {
80 static PassRefPtr<ImageDocumentParser> create(ImageDocument* document)
82 return adoptRef(new ImageDocumentParser(document));
85 ImageDocument* document() const
87 return toImageDocument(RawDataDocumentParser::document());
91 ImageDocumentParser(ImageDocument* document)
92 : RawDataDocumentParser(document)
96 virtual void appendBytes(const char*, size_t) OVERRIDE;
97 virtual void finish();
102 static float pageZoomFactor(const Document* document)
104 Frame* frame = document->frame();
105 return frame ? frame->pageZoomFactor() : 1;
108 static String imageTitle(const String& filename, const IntSize& size)
110 StringBuilder result;
111 result.append(filename);
113 // FIXME: Localize numbers. Safari/OSX shows localized numbers with group
114 // separaters. For example, "1,920x1,080".
115 result.append(String::number(size.width()));
116 result.append(static_cast<UChar>(0xD7)); // U+00D7 (multiplication sign)
117 result.append(String::number(size.height()));
119 return result.toString();
122 void ImageDocumentParser::appendBytes(const char* data, size_t length)
127 Frame* frame = document()->frame();
128 Settings* settings = frame->settings();
129 if (!frame->loader().client()->allowImage(!settings || settings->imagesEnabled(), document()->url()))
132 document()->cachedImage()->appendData(data, length);
133 document()->imageUpdated();
136 void ImageDocumentParser::finish()
138 if (!isStopped() && document()->imageElement()) {
139 ImageResource* cachedImage = document()->cachedImage();
140 cachedImage->finish();
141 cachedImage->setResponse(document()->frame()->loader().documentLoader()->response());
143 // Report the natural image size in the page title, regardless of zoom level.
144 // At a zoom level of 1 the image is guaranteed to have an integer size.
145 IntSize size = flooredIntSize(cachedImage->imageSizeForRenderer(document()->imageElement()->renderer(), 1.0f));
147 // Compute the title, we use the decoded filename of the resource, falling
148 // back on the (decoded) hostname if there is no path.
149 String fileName = decodeURLEscapeSequences(document()->url().lastPathComponent());
150 if (fileName.isEmpty())
151 fileName = document()->url().host();
152 document()->setTitle(imageTitle(fileName, size));
155 document()->imageUpdated();
158 document()->finishedParsing();
163 ImageDocument::ImageDocument(const DocumentInit& initializer)
164 : HTMLDocument(initializer, ImageDocumentClass)
166 , m_imageSizeIsKnown(false)
167 , m_didShrinkImage(false)
168 , m_shouldShrinkImage(shouldShrinkToFit())
170 setCompatibilityMode(QuirksMode);
171 lockCompatibilityMode();
174 PassRefPtr<DocumentParser> ImageDocument::createParser()
176 return ImageDocumentParser::create(this);
179 void ImageDocument::createDocumentStructure()
181 RefPtr<HTMLHtmlElement> rootElement = HTMLHtmlElement::create(*this);
182 appendChild(rootElement);
183 rootElement->insertedByParser();
186 frame()->loader().dispatchDocumentElementAvailable();
188 RefPtr<HTMLHeadElement> head = HTMLHeadElement::create(*this);
189 RefPtr<HTMLMetaElement> meta = HTMLMetaElement::create(*this);
190 meta->setAttribute(nameAttr, "viewport");
191 meta->setAttribute(contentAttr, "width=device-width, minimum-scale=0.1");
192 head->appendChild(meta);
194 RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(*this);
195 body->setAttribute(styleAttr, "margin: 0px;");
197 m_imageElement = HTMLImageElement::create(*this);
198 m_imageElement->setAttribute(styleAttr, "-webkit-user-select: none");
199 m_imageElement->setLoadManually(true);
200 m_imageElement->setSrc(url().string());
201 body->appendChild(m_imageElement.get());
203 if (shouldShrinkToFit()) {
204 // Add event listeners
205 RefPtr<EventListener> listener = ImageEventListener::create(this);
206 if (DOMWindow* domWindow = this->domWindow())
207 domWindow->addEventListener("resize", listener, false);
208 m_imageElement->addEventListener("click", listener.release(), false);
211 rootElement->appendChild(head);
212 rootElement->appendChild(body);
215 float ImageDocument::scale() const
217 if (!m_imageElement || m_imageElement->document() != this)
220 FrameView* view = frame()->view();
224 LayoutSize imageSize = m_imageElement->cachedImage()->imageSizeForRenderer(m_imageElement->renderer(), pageZoomFactor(this));
225 LayoutSize windowSize = LayoutSize(view->width(), view->height());
227 float widthScale = (float)windowSize.width() / imageSize.width();
228 float heightScale = (float)windowSize.height() / imageSize.height();
230 return min(widthScale, heightScale);
233 void ImageDocument::resizeImageToFit()
235 if (!m_imageElement || m_imageElement->document() != this || pageZoomFactor(this) > 1)
238 LayoutSize imageSize = m_imageElement->cachedImage()->imageSizeForRenderer(m_imageElement->renderer(), pageZoomFactor(this));
240 float scale = this->scale();
241 m_imageElement->setWidth(static_cast<int>(imageSize.width() * scale));
242 m_imageElement->setHeight(static_cast<int>(imageSize.height() * scale));
244 m_imageElement->setInlineStyleProperty(CSSPropertyCursor, CSSValueWebkitZoomIn);
247 void ImageDocument::imageClicked(int x, int y)
249 if (!m_imageSizeIsKnown || imageFitsInWindow())
252 m_shouldShrinkImage = !m_shouldShrinkImage;
254 if (m_shouldShrinkImage)
261 float scale = this->scale();
263 int scrollX = static_cast<int>(x / scale - (float)frame()->view()->width() / 2);
264 int scrollY = static_cast<int>(y / scale - (float)frame()->view()->height() / 2);
266 frame()->view()->setScrollPosition(IntPoint(scrollX, scrollY));
270 void ImageDocument::imageUpdated()
272 ASSERT(m_imageElement);
274 if (m_imageSizeIsKnown)
277 if (m_imageElement->cachedImage()->imageSizeForRenderer(m_imageElement->renderer(), pageZoomFactor(this)).isEmpty())
280 m_imageSizeIsKnown = true;
282 if (shouldShrinkToFit()) {
283 // Force resizing of the image
288 void ImageDocument::restoreImageSize()
290 if (!m_imageElement || !m_imageSizeIsKnown || m_imageElement->document() != this || pageZoomFactor(this) < 1)
293 LayoutSize imageSize = m_imageElement->cachedImage()->imageSizeForRenderer(m_imageElement->renderer(), 1.0f);
294 m_imageElement->setWidth(imageSize.width());
295 m_imageElement->setHeight(imageSize.height());
297 if (imageFitsInWindow())
298 m_imageElement->removeInlineStyleProperty(CSSPropertyCursor);
300 m_imageElement->setInlineStyleProperty(CSSPropertyCursor, CSSValueWebkitZoomOut);
302 m_didShrinkImage = false;
305 bool ImageDocument::imageFitsInWindow() const
307 if (!m_imageElement || m_imageElement->document() != this)
310 FrameView* view = frame()->view();
314 LayoutSize imageSize = m_imageElement->cachedImage()->imageSizeForRenderer(m_imageElement->renderer(), pageZoomFactor(this));
315 LayoutSize windowSize = LayoutSize(view->width(), view->height());
317 return imageSize.width() <= windowSize.width() && imageSize.height() <= windowSize.height();
320 void ImageDocument::windowSizeChanged()
322 if (!m_imageElement || !m_imageSizeIsKnown || m_imageElement->document() != this)
325 bool fitsInWindow = imageFitsInWindow();
327 // If the image has been explicitly zoomed in, restore the cursor if the image fits
328 // and set it to a zoom out cursor if the image doesn't fit
329 if (!m_shouldShrinkImage) {
331 m_imageElement->removeInlineStyleProperty(CSSPropertyCursor);
333 m_imageElement->setInlineStyleProperty(CSSPropertyCursor, CSSValueWebkitZoomOut);
337 if (m_didShrinkImage) {
338 // If the window has been resized so that the image fits, restore the image size
339 // otherwise update the restored image size.
345 // If the image isn't resized but needs to be, then resize it.
348 m_didShrinkImage = true;
353 ImageResource* ImageDocument::cachedImage()
356 createDocumentStructure();
358 return m_imageElement->cachedImage();
361 bool ImageDocument::shouldShrinkToFit() const
363 return frame()->settings()->shrinksStandaloneImagesToFit() && frame()->isMainFrame();
366 void ImageDocument::dispose()
369 HTMLDocument::dispose();
374 void ImageEventListener::handleEvent(ExecutionContext*, Event* event)
376 if (event->type() == EventTypeNames::resize)
377 m_doc->windowSizeChanged();
378 else if (event->type() == EventTypeNames::click && event->isMouseEvent()) {
379 MouseEvent* mouseEvent = toMouseEvent(event);
380 m_doc->imageClicked(mouseEvent->x(), mouseEvent->y());
384 bool ImageEventListener::operator==(const EventListener& listener)
386 if (const ImageEventListener* imageEventListener = ImageEventListener::cast(&listener))
387 return m_doc == imageEventListener->m_doc;