示例#1
0
TEST(ImageResourceTest, CancelOnDetach) {
  KURL testURL(ParsedURLString, "http://www.test.com/cancelTest.html");
  ScopedRegisteredURL scopedRegisteredURL(testURL);

  ResourceFetcher* fetcher =
      ResourceFetcher::create(ImageResourceTestMockFetchContext::create());

  // Emulate starting a real load.
  ImageResource* cachedImage = ImageResource::create(ResourceRequest(testURL));
  cachedImage->setIdentifier(createUniqueIdentifier());

  fetcher->startLoad(cachedImage);
  memoryCache()->add(cachedImage);

  Persistent<MockImageResourceClient> client =
      new MockImageResourceClient(cachedImage);
  EXPECT_EQ(Resource::Pending, cachedImage->getStatus());

  // The load should still be alive, but a timer should be started to cancel the
  // load inside removeClient().
  client->removeAsClient();
  EXPECT_EQ(Resource::Pending, cachedImage->getStatus());
  EXPECT_TRUE(memoryCache()->resourceForURL(testURL));

  // Trigger the cancel timer, ensure the load was cancelled and the resource
  // was evicted from the cache.
  blink::testing::runPendingTasks();
  EXPECT_EQ(Resource::LoadError, cachedImage->getStatus());
  EXPECT_FALSE(memoryCache()->resourceForURL(testURL));
}
void ImageDocumentParser::finish()
{
    if (!isStopped() && document()->imageElement() && document()->cachedImage()) {
        ImageResource* cachedImage = document()->cachedImage();
        cachedImage->finish();
        cachedImage->setResponse(document()->frame()->loader().documentLoader()->response());

        // Report the natural image size in the page title, regardless of zoom level.
        // At a zoom level of 1 the image is guaranteed to have an integer size.
        IntSize size = flooredIntSize(cachedImage->imageSizeForLayoutObject(document()->imageElement()->layoutObject(), 1.0f));
        if (size.width()) {
            // Compute the title, we use the decoded filename of the resource, falling
            // back on the (decoded) hostname if there is no path.
            String fileName = decodeURLEscapeSequences(document()->url().lastPathComponent());
            if (fileName.isEmpty())
                fileName = document()->url().host();
            document()->setTitle(imageTitle(fileName, size));
        }

        document()->imageUpdated();
    }

    if (document())
        document()->finishedParsing();
}
void PaintChatWindow::on_pushButtonClear_clicked()
{
    //käse tut ned, vermutlich wegen gleichen timestamps
    /*
    // not the best way to reset the image, because it causes the entire image to be transmitted
    // first overwrite with black
    ui->paintWidget->fillImage(Qt::black);
    updateImage();
    // then with white
    ui->paintWidget->fillImage(Qt::white);
    updateImage();
    */

    // andere Lösung:
    // sendet viele bytes, weil resource unkomprimiert ist
    // tut nicht, vielleicht zu große items?

    ui->paintWidget->fillImage(Qt::white);
    ImageResource res;
    res.fromQImage(ui->paintWidget->getImage());
    paintChatService->init(peerId,res);
    paintChatService->sendInit(peerId,res);


}
示例#4
0
bool HTMLImageElement::wouldTaintOrigin(SecurityOrigin* destinationSecurityOrigin) const
{
    ImageResource* image = cachedImage();
    if (!image)
        return false;
    return !image->isAccessAllowed(destinationSecurityOrigin);
}
示例#5
0
void ImageLoader::setImageWithoutConsideringPendingLoadEvent(ImageResource* newImage)
{
    ASSERT(m_failedLoadURL.isEmpty());
    ImageResource* oldImage = m_image.get();
    if (newImage != oldImage) {
        sourceImageChanged();
        m_image = newImage;
        if (m_hasPendingBeforeLoadEvent) {
            beforeLoadEventSender().cancelEvent(this);
            m_hasPendingBeforeLoadEvent = false;
        }
        if (m_hasPendingLoadEvent) {
            loadEventSender().cancelEvent(this);
            m_hasPendingLoadEvent = false;
        }
        if (m_hasPendingErrorEvent) {
            errorEventSender().cancelEvent(this);
            m_hasPendingErrorEvent = false;
        }
        m_imageComplete = true;
        if (newImage)
            newImage->addClient(this);
        if (oldImage)
            oldImage->removeClient(this);
    }

    if (RenderImageResource* imageResource = renderImageResource())
        imageResource->resetAnimation();
}
示例#6
0
void ImageLoader::setImageWithoutConsideringPendingLoadEvent(
    ImageResource* newImage) {
    DCHECK(m_failedLoadURL.isEmpty());
    ImageResource* oldImage = m_image.get();
    if (newImage != oldImage) {
        m_image = newImage;
        if (m_hasPendingLoadEvent) {
            loadEventSender().cancelEvent(this);
            m_hasPendingLoadEvent = false;
        }
        if (m_hasPendingErrorEvent) {
            errorEventSender().cancelEvent(this);
            m_hasPendingErrorEvent = false;
        }
        m_imageComplete = true;
        if (newImage) {
            newImage->addObserver(this);
        }
        if (oldImage) {
            oldImage->removeObserver(this);
        }
    }

    if (LayoutImageResource* imageResource = layoutImageResource())
        imageResource->resetAnimation();
}
示例#7
0
PassRefPtr<AnimatableValue> AnimatableImage::interpolateTo(const AnimatableValue* value, double fraction) const
{
    if (fraction <= 0 || fraction >= 1)
        return defaultInterpolateTo(this, value, fraction);
    RefPtr<CSSValue> fromValue = toCSSValue();
    // FIXME: Once cross-fade works on generated image types, remove this check.
    if (fromValue->isImageGeneratorValue())
        return defaultInterpolateTo(this, value, fraction);
    if (!fromValue->isImageValue() && !fromValue->isImageGeneratorValue()) {
        if (!m_image->isImageResource())
            return defaultInterpolateTo(this, value, fraction);
        ImageResource* resource = static_cast<ImageResource*>(m_image->data());
        fromValue = CSSImageValue::create(resource->url(), m_image.get());
    }
    const AnimatableImage* image = toAnimatableImage(value);
    RefPtr<CSSValue> toValue = image->toCSSValue();
    // FIXME: Once cross-fade works on generated image types, remove this check.
    if (toValue->isImageGeneratorValue())
        return defaultInterpolateTo(this, value, fraction);
    if (!toValue->isImageValue() && !toValue->isImageGeneratorValue()) {
        if (!image->m_image->isImageResource())
            return defaultInterpolateTo(this, value, fraction);
        ImageResource* resource = static_cast<ImageResource*>(image->m_image->data());
        toValue = CSSImageValue::create(resource->url(), image->m_image.get());
    }
    RefPtr<CSSCrossfadeValue> crossfadeValue = CSSCrossfadeValue::create(fromValue, toValue);
    crossfadeValue->setPercentage(CSSPrimitiveValue::create(fraction, CSSPrimitiveValue::CSS_NUMBER));
    return create(StyleGeneratedImage::create(crossfadeValue.get()).get());
}
void ImageDocumentParser::finish()
{
    if (!isStopped() && document()->imageElement() && document()->cachedImage()) {
        ImageResource* cachedImage = document()->cachedImage();
        DocumentLoader* loader = document()->loader();
        cachedImage->setResponse(loader->response());
        cachedImage->setLoadFinishTime(loader->timing().responseEnd());
        cachedImage->finish();

        // Report the natural image size in the page title, regardless of zoom level.
        // At a zoom level of 1 the image is guaranteed to have an integer size.
        IntSize size = flooredIntSize(cachedImage->imageSizeForLayoutObject(document()->imageElement()->layoutObject(), 1.0f));
        if (size.width()) {
            // Compute the title, we use the decoded filename of the resource, falling
            // back on the (decoded) hostname if there is no path.
            String fileName = decodeURLEscapeSequences(document()->url().lastPathComponent());
            if (fileName.isEmpty())
                fileName = document()->url().host();
            document()->setTitle(imageTitle(fileName, size));
        }

        document()->imageUpdated();
    }

    // TODO(esprehn): These null checks on Document don't make sense, document()
    // will ASSERT if it was null. Do these want to check isDetached() ?
    if (document())
        document()->finishedParsing();
}
TEST(ImageResourceTest, CancelOnDetach)
{
    KURL testURL(ParsedURLString, "http://www.test.com/cancelTest.html");
    URLTestHelpers::registerMockedURLLoad(testURL, "cancelTest.html", "text/html");

    ResourceFetcher* fetcher = ResourceFetcher::create(ImageResourceTestMockFetchContext::create());

    // Emulate starting a real load.
    ImageResource* cachedImage = ImageResource::create(ResourceRequest(testURL));
    cachedImage->setIdentifier(createUniqueIdentifier());

    fetcher->startLoad(cachedImage);
    memoryCache()->add(cachedImage);

    Persistent<MockImageResourceClient> client = new MockImageResourceClient(cachedImage);
    EXPECT_EQ(Resource::Pending, cachedImage->getStatus());

    // The load should still be alive, but a timer should be started to cancel the load inside removeClient().
    client->removeAsClient();
    EXPECT_EQ(Resource::Pending, cachedImage->getStatus());
    EXPECT_NE(reinterpret_cast<Resource*>(0), memoryCache()->resourceForURL(testURL));

    // Trigger the cancel timer, ensure the load was cancelled and the resource was evicted from the cache.
    blink::testing::runPendingTasks();
    EXPECT_EQ(Resource::LoadError, cachedImage->getStatus());
    EXPECT_EQ(reinterpret_cast<Resource*>(0), memoryCache()->resourceForURL(testURL));

    Platform::current()->getURLLoaderMockFactory()->unregisterURL(testURL);
}
示例#10
0
FloatSize HTMLImageElement::elementSize() const
{
    ImageResource* image = cachedImage();
    if (!image)
        return FloatSize();

    return FloatSize(image->imageSizeForLayoutObject(layoutObject(), 1.0f));
}
static bool containerSizeIsSetForLayoutObject(ImageResource& cachedImage, const LayoutObject* layoutObject)
{
    const Image* image = cachedImage.image();
    // If a container size has been specified for this layoutObject, then
    // imageForLayoutObject() will return the SVGImageForContainer while image()
    // will return the underlying SVGImage.
    return !image->isSVGImage() || image != cachedImage.imageForLayoutObject(layoutObject);
}
示例#12
0
FloatSize HTMLImageElement::sourceSize() const
{
    ImageResource* image = cachedImage();
    if (!image)
        return FloatSize();
    LayoutSize size;
    size = image->imageSizeForRenderer(renderer(), 1.0f); // FIXME: Not sure about this.

    return size;
}
RenderBox* RenderImage::embeddedContentBox() const
{
    if (!m_imageResource)
        return 0;

    ImageResource* cachedImage = m_imageResource->cachedImage();
    if (cachedImage && cachedImage->image() && cachedImage->image()->isSVGImage())
        return static_cast<SVGImage*>(cachedImage->image())->embeddedContentBox();

    return 0;
}
示例#14
0
	/**
	 * Returns an image resource.
	 *
	 * @param fileName The filename of the image.
	 *
	 * @return The image.
	 *
	 * @throw ResourceNotLoadedExcpetion
	*/
	ImageResource* ResourceManager::image(std::string fileName) {
		std::string id = ImageResource::createID(fileName);
		if (!hasResource(id)) {
			ImageResource* res = ImageResource::open(fileName);
			insertResource(res->getName(), res);
			
			return res;
		} else {
			return static_cast<ImageResource*>(getResource(id));
		}
	}
void LayoutSVGImage::updateImageContainerSize()
{
    ImageResource* cachedImage = m_imageResource->cachedImage();
    if (!cachedImage || !cachedImage->usesImageContainerSize())
        return;
    FloatSize imageViewportSize = computeImageViewportSize(*cachedImage);
    if (LayoutSize(imageViewportSize) != m_imageResource->imageSize(styleRef().effectiveZoom())
            || !containerSizeIsSetForLayoutObject(*cachedImage, this)) {
        m_imageResource->setContainerSizeForLayoutObject(roundedIntSize(imageViewportSize));
    }
}
示例#16
0
LayoutBox* LayoutImage::embeddedContentBox() const
{
    if (!m_imageResource)
        return nullptr;

    ImageResource* cachedImage = m_imageResource->cachedImage();
    if (cachedImage && cachedImage->image() && cachedImage->image()->isSVGImage())
        return toSVGImage(cachedImage->image())->embeddedContentBox();

    return nullptr;
}
示例#17
0
bool checkShapeImageOrigin(Document& document, ImageResource& imageResource)
{
    if (imageResource.isAccessAllowed(document.securityOrigin()))
        return true;

    const KURL& url = imageResource.url();
    String urlString = url.isNull() ? "''" : url.elidedString();
    document.addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Unsafe attempt to load URL " + urlString + ".");

    return false;
}
示例#18
0
FloatSize HTMLImageElement::defaultDestinationSize() const
{
    ImageResource* image = cachedImage();
    if (!image)
        return FloatSize();
    LayoutSize size;
    size = image->imageSizeForLayoutObject(layoutObject(), 1.0f);
    if (layoutObject() && layoutObject()->isLayoutImage() && image->image() && !image->image()->hasRelativeWidth())
        size.scale(toLayoutImage(layoutObject())->imageDevicePixelRatio());
    return FloatSize(size);
}
示例#19
0
FloatSize HTMLImageElement::defaultDestinationSize() const
{
    ImageResource* image = cachedImage();
    if (!image)
        return FloatSize();
    LayoutSize size;
    size = image->imageSizeForRenderer(renderer(), 1.0f); // FIXME: Not sure about this.
    if (renderer() && renderer()->isRenderImage() && image->image() && !image->image()->hasRelativeWidth())
        size.scale(toRenderImage(renderer())->imageDevicePixelRatio());
    return size;
}
void PaintChatWindow::updateImage(){
    if(paintChatService->receivedInit(peerId)){
        ui->paintWidget->fillImage(Qt::white);
        ImageResource res;
        res.fromQImage(ui->paintWidget->getImage());
        paintChatService->init(peerId,res);
    }else{
        ImageResource res;
        res.fromQImage(ui->paintWidget->getImage());
        ui->paintWidget->setImage(paintChatService->update(peerId,res).toQImage());
    }
}
示例#21
0
void HTMLImageLoader::notifyFinished(Resource*)
{
    ImageResource* cachedImage = image();

    RefPtr<Element> element = this->element();
    ImageLoader::notifyFinished(cachedImage);

    bool loadError = cachedImage->errorOccurred() || cachedImage->response().httpStatusCode() >= 400;

    if (loadError && element->hasTagName(HTMLNames::objectTag))
        toHTMLObjectElement(element)->renderFallbackContent();
}
示例#22
0
void ImageLoader::updateFromElement(UpdateFromElementBehavior updateBehavior,
                                    ReferrerPolicy referrerPolicy) {
    AtomicString imageSourceURL = m_element->imageSourceURL();
    m_suppressErrorEvents = (updateBehavior == UpdateSizeChanged);

    if (updateBehavior == UpdateIgnorePreviousError)
        clearFailedLoadURL();

    if (!m_failedLoadURL.isEmpty() && imageSourceURL == m_failedLoadURL)
        return;

    // Prevent the creation of a ResourceLoader (and therefore a network request)
    // for ImageDocument loads. In this case, the image contents have already been
    // requested as a main resource and ImageDocumentParser will take care of
    // funneling the main resource bytes into m_image, so just create an
    // ImageResource to be populated later.
    if (m_loadingImageDocument && updateBehavior != UpdateForcedReload) {
        setImage(
            ImageResource::create(imageSourceToKURL(m_element->imageSourceURL())));
        m_image->setStatus(Resource::Pending);
        return;
    }

    // If we have a pending task, we have to clear it -- either we're now loading
    // immediately, or we need to reset the task's state.
    if (m_pendingTask) {
        m_pendingTask->clearLoader();
        m_pendingTask.reset();
    }

    KURL url = imageSourceToKURL(imageSourceURL);
    if (shouldLoadImmediately(url)) {
        doUpdateFromElement(DoNotBypassMainWorldCSP, updateBehavior, url,
                            referrerPolicy);
        return;
    }
    // Allow the idiom "img.src=''; img.src='.." to clear down the image before an
    // asynchronous load completes.
    if (imageSourceURL.isEmpty()) {
        ImageResource* image = m_image.get();
        if (image) {
            image->removeObserver(this);
        }
        m_image = nullptr;
    }

    // Don't load images for inactive documents. We don't want to slow down the
    // raw HTML parsing case by loading images we don't intend to display.
    Document& document = m_element->document();
    if (document.isActive())
        enqueueImageLoadingMicroTask(updateBehavior, referrerPolicy);
}
示例#23
0
ImageResource *ResourceManager::requestImage(const QString &path)
{
    QUrl url = resolve(path);

    ImageResource *image = find<ImageResource>(url);
    if (!image) {
        image = new ImageResource(url, this);
        mResources.insert(url, image);
        mResourceListModel->addResource(image);
    }

    image->incRef();
    return image;
}
示例#24
0
	/**
	 * Returns an image resource. The image will be scaled and rotated.
	 *
	 * @param fileName The filename of the image.
	 * @param width The width of the image.
	 * @param height The height of the image.
	 * @param keepRatio True if to keep the aspect ratio of the original image.
	 *        It is possible that the width or height of the image will be less than the given values.
	 * @param angle The angle of the rotation (in degrees).
	 *
	 * @return The image.
	 *
	 * @throw ResourceNotLoadedExcpetion
	*/
	ImageResource* ResourceManager::image(std::string fileName, int width,
	                                      int height, bool keepRatio, int angle) {
		std::string id = ImageResource::createID(fileName, width, height, keepRatio, angle);
		if (!hasResource(id)) {
			ImageResource* res = image(fileName);
			ImageResource* scaled = res->scaleAndRotate(width, height, keepRatio, angle);
			free(res);
			insertResource(scaled->getName(), scaled);
			
			return scaled;
		} else {
			return static_cast<ImageResource*>(getResource(id));
		}
	}
示例#25
0
TEST(ImageResourceTest, SVGImage) {
  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo");
  ImageResource* imageResource = ImageResource::create(ResourceRequest(url));
  Persistent<MockImageResourceClient> client =
      new MockImageResourceClient(imageResource);

  receiveResponse(imageResource, url, "image/svg+xml", svgImage());

  EXPECT_FALSE(imageResource->errorOccurred());
  ASSERT_TRUE(imageResource->hasImage());
  EXPECT_FALSE(imageResource->getImage()->isNull());
  EXPECT_EQ(1, client->imageChangedCount());
  EXPECT_TRUE(client->notifyFinishedCalled());
  EXPECT_FALSE(imageResource->getImage()->isBitmapImage());
}
void CSSImageValue::restoreCachedResourceIfNeeded(Document& document) const
{
    if (m_isCachePending || !m_cachedImage || !document.fetcher())
        return;
    if (document.fetcher()->cachedResource(KURL(ParsedURLString, m_absoluteURL)))
        return;

    ImageResource* resource = m_cachedImage->cachedImage();
    if (!resource)
        return;

    FetchRequest request(ResourceRequest(m_absoluteURL), m_initiatorName.isEmpty() ? FetchInitiatorTypeNames::css : m_initiatorName, resource->options());
    MixedContentChecker::shouldBlockFetch(document.frame(), resource->lastResourceRequest(),
        resource->lastResourceRequest().url(), MixedContentChecker::SendReport);
    document.fetcher()->requestLoadStarted(resource, request, ResourceFetcher::ResourceLoadingFromCache);
}
void MCommonPixmaps::clear()
{
    // release all most used pixmaps
    foreach(const PixmapIdentifier & id, mostUsedPixmaps) {
        if (toLoadList.contains(id))
            continue;

        ImageResource *resource = daemon->findImageResource(id.imageId);
        resource->releasePixmap(id.size);
    }

    cpuMonitor.stop();
    mostUsedPixmaps.clear();
    toLoadList.clear();
    requestCounts.clear();
    minRequestsForCache = 0;
}
示例#28
0
int main(int argc, char *argv[])
{
    ImageIO reader("texture.dds");
    const auto result = reader.read();

    // if (!result.first) ...

    const auto &contents = result.second;
    for (int index = 0; index < contents.header().imageCount(); ++index) { // read array
        for (int level = 0; level < contents.header().mipmapCount(); ++level) { // read mipmaps
            ImageResource resource = contents.resource(index, level);
            if (resource.type() == ImageResource::Type::Image) {
                const QImage image = resource.image();
                // ...
            } else if (resource.type() == ImageResource::Type::CubeTexture) {
                CubeTexture texture = resource.cubeTexture();
                // ...
            } else if (resource.type() == ImageResource::Type::VolumeTexture) {
                VolumeTexture texture = resource.volumeTexture();
                // ...
            }
        }
    }

    ImageExifMeta exif = contents.exifMeta();
    if (!exif.isEmpty()) {
        // ...
    }

    return 0;
}
示例#29
0
TEST(ImageResourceTest, CancelOnDecodeError) {
  KURL testURL(ParsedURLString, "http://www.test.com/cancelTest.html");
  ScopedRegisteredURL scopedRegisteredURL(testURL);

  ResourceFetcher* fetcher =
      ResourceFetcher::create(ImageResourceTestMockFetchContext::create());
  FetchRequest request(testURL, FetchInitiatorInfo());
  ImageResource* cachedImage = ImageResource::fetch(request, fetcher);

  cachedImage->loader()->didReceiveResponse(
      nullptr, WrappedResourceResponse(ResourceResponse(
                   testURL, "image/jpeg", 18, nullAtom, String())),
      nullptr);
  cachedImage->loader()->didReceiveData(nullptr, "notactuallyanimage", 18, 18,
                                        18);
  EXPECT_EQ(Resource::DecodeError, cachedImage->getStatus());
  EXPECT_FALSE(cachedImage->isLoading());
}
static void writeImageToDataObject(DataObject* dataObject, Element* element, const KURL& url)
{
    // Shove image data into a DataObject for use as a file
    ImageResource* cachedImage = getImageResource(element);
    if (!cachedImage || !cachedImage->imageForLayoutObject(element->layoutObject()) || !cachedImage->isLoaded())
        return;

    SharedBuffer* imageBuffer = cachedImage->imageForLayoutObject(element->layoutObject())->data();
    if (!imageBuffer || !imageBuffer->size())
        return;

    String imageExtension = cachedImage->image()->filenameExtension();
    ASSERT(!imageExtension.isEmpty());

    // Determine the filename for the file contents of the image.
    String filename = cachedImage->response().suggestedFilename();
    if (filename.isEmpty())
        filename = url.lastPathComponent();

    String fileExtension;
    if (filename.isEmpty()) {
        filename = element->getAttribute(HTMLNames::altAttr);
    } else {
        // Strip any existing extension. Assume that alt text is usually not a filename.
        int extensionIndex = filename.reverseFind('.');
        if (extensionIndex != -1) {
            fileExtension = filename.substring(extensionIndex + 1);
            filename.truncate(extensionIndex);
        }
    }

    if (!fileExtension.isEmpty() && fileExtension != imageExtension) {
        String imageMimeType = MIMETypeRegistry::getMIMETypeForExtension(imageExtension);
        ASSERT(imageMimeType.startsWith("image/"));
        // Use the file extension only if it has imageMimeType: it's untrustworthy otherwise.
        if (imageMimeType == MIMETypeRegistry::getMIMETypeForExtension(fileExtension))
            imageExtension = fileExtension;
    }

    imageExtension = "." + imageExtension;
    validateFilename(filename, imageExtension);

    dataObject->addSharedBuffer(filename + imageExtension, imageBuffer);
}