Example #1
0
    virtual void run(Page* page)
    {
        if (m_running)
            return;
        m_running = true;

        Vector<WebViewImpl*> views;

        // 1. Disable input events.
        HashSet<Page*>::const_iterator end =  page->group().pages().end();
        for (HashSet<Page*>::const_iterator it =  page->group().pages().begin(); it != end; ++it) {
            WebViewImpl* view = WebViewImpl::fromPage(*it);
            m_frozenViews.add(view);
            views.append(view);
            view->setIgnoreInputEvents(true);
        }

        // 2. Disable active objects
        WebView::willEnterModalLoop();

        // 3. Process messages until quitNow is called.
        m_messageLoop->run();

        // 4. Resume active objects
        WebView::didExitModalLoop();

        // 5. Resume input events.
        for (Vector<WebViewImpl*>::iterator it = views.begin(); it != views.end(); ++it) {
            if (m_frozenViews.contains(*it)) {
                // The view was not closed during the dispatch.
                (*it)->setIgnoreInputEvents(false);
            }
        }

        // 6. All views have been resumed, clear the set.
        m_frozenViews.clear();

        m_running = false;
    }
Example #2
0
void Fire::checkEnemy(){
    Vector<Enemy*> enemies = global->enemies;

    if (enemies.empty()){
        return;
    }

    Vector<Enemy*>::iterator it = enemies.begin();
    for (; it != enemies.end(); ++it){
        if ((*it)->getState() == ROLE_STATE_DIE){
            continue;
        }
        Rect enemyBox = (*it)->getBodyBox().actual;
        if (enemyBox.intersectsRect(getBodyBox().actual)){
            setVelocity(Vec2(0, 0));
            stopAllActions();
            runAction(m_endAction);
            int hurt = m_baseHurt + rand() % 20 - 10;
            (*it)->onHurt(hurt);
        }
    }
}
Example #3
0
void RenderNamedFlowThread::checkInvalidRegions()
{
    Vector<RenderRegion*> newValidRegions;
    for (RenderRegionList::iterator iter = m_invalidRegionList.begin(); iter != m_invalidRegionList.end(); ++iter) {
        RenderRegion* region = *iter;
        // The only reason a region would be invalid is because it has a parent flow thread.
        ASSERT(!region->isValid() && region->parentNamedFlowThread());
        if (region->parentNamedFlowThread()->dependsOn(this))
            continue;

        newValidRegions.append(region);
    }

    for (Vector<RenderRegion*>::iterator iter = newValidRegions.begin(); iter != newValidRegions.end(); ++iter) {
        RenderRegion* region = *iter;
        m_invalidRegionList.remove(region);
        region->parentNamedFlowThread()->m_observerThreadsSet.remove(this);
        region->setIsValid(true);
        addDependencyOnFlowThread(region->parentNamedFlowThread());
        addRegionToList(m_regionList, region);
    }

    if (!newValidRegions.isEmpty())
        invalidateRegions();

    if (m_observerThreadsSet.isEmpty())
        return;

    // Notify all the flow threads that were dependent on this flow.

    // Create a copy of the list first. That's because observers might change the list when calling checkInvalidRegions.
    Vector<RenderNamedFlowThread*> observers;
    copyToVector(m_observerThreadsSet, observers);

    for (size_t i = 0; i < observers.size(); ++i) {
        RenderNamedFlowThread* flowThread = observers.at(i);
        flowThread->checkInvalidRegions();
    }
}
Vector<RefPtr<TextTrack>> CaptionUserPreferences::sortedTrackListForMenu(TextTrackList* trackList)
{
    ASSERT(trackList);

    Vector<RefPtr<TextTrack>> tracksForMenu;

    for (unsigned i = 0, length = trackList->length(); i < length; ++i) {
        TextTrack* track = trackList->item(i);
        const AtomicString& kind = track->kind();
        if (kind == TextTrack::captionsKeyword() || kind == TextTrack::descriptionsKeyword() || kind == TextTrack::subtitlesKeyword())
            tracksForMenu.append(track);
    }

    std::sort(tracksForMenu.begin(), tracksForMenu.end(), [](const RefPtr<TextTrack>& a, const RefPtr<TextTrack>& b) {
        return codePointCompare(trackDisplayName(a.get()), trackDisplayName(b.get())) < 0;
    });

    tracksForMenu.insert(0, TextTrack::captionMenuOffItem());
    tracksForMenu.insert(1, TextTrack::captionMenuAutomaticItem());

    return tracksForMenu;
}
static void updateFromStyle(Vector<LayoutUnit>& snapOffsets, const RenderStyle& style, ScrollEventAxis axis, LayoutUnit viewSize, LayoutUnit scrollSize, Vector<LayoutUnit>& snapOffsetSubsequence)
{
    std::sort(snapOffsetSubsequence.begin(), snapOffsetSubsequence.end());
    if (snapOffsetSubsequence.isEmpty())
        snapOffsetSubsequence.append(0);

    // Always put a snap point on the zero offset.
    snapOffsets.append(0);

    auto* points = (axis == ScrollEventAxis::Horizontal) ? style.scrollSnapPointsX() : style.scrollSnapPointsY();
    bool hasRepeat = points ? points->hasRepeat : false;
    LayoutUnit repeatOffset = points ? valueForLength(points->repeatOffset, viewSize) : LayoutUnit();
    LayoutUnit destinationOffset = destinationOffsetForViewSize(axis, style.scrollSnapDestination(), viewSize);
    LayoutUnit curSnapPositionShift = 0;
    LayoutUnit maxScrollOffset = scrollSize - viewSize;
    LayoutUnit lastSnapPosition = curSnapPositionShift;
    do {
        for (auto& snapPosition : snapOffsetSubsequence) {
            LayoutUnit potentialSnapPosition = curSnapPositionShift + snapPosition - destinationOffset;
            if (potentialSnapPosition < 0)
                continue;

            if (potentialSnapPosition >= maxScrollOffset)
                break;

            // Don't add another zero offset value.
            if (potentialSnapPosition)
                snapOffsets.append(potentialSnapPosition);

            lastSnapPosition = potentialSnapPosition + destinationOffset;
        }
        curSnapPositionShift = lastSnapPosition + repeatOffset;
    } while (hasRepeat && curSnapPositionShift < maxScrollOffset);

    // Always put a snap point on the maximum scroll offset.
    // Not a part of the spec, but necessary to prevent unreachable content when snapping.
    if (snapOffsets.last() != maxScrollOffset)
        snapOffsets.append(maxScrollOffset);
}
Example #6
0
void Hero::CheckAttack(int base_hurt){
    Vector<Enemy*> enemies = global->enemies;

    if (enemies.empty()){
        return;
    }

    Vector<Enemy*>::iterator it = enemies.begin();
    for (; it != enemies.end(); ++it){
        if ((*it)->getState() == ROLE_STATE_DIE){
            continue;
        }
        Rect enemyBox = (*it)->getBodyBox().actual;
        if (enemyBox.intersectsRect(getAttackBox().actual)){
            int hurt = m_strenth + rand() % 20 - 10;
            if (rand() % 100 < 5){
                hurt *= 2;
            }
            (*it)->onHurt(hurt);
        }
    }
}
Example #7
0
void HTMLLinkElement::tokenizeRelAttribute(const AtomicString& rel, RelAttribute& relAttribute)
{
    relAttribute.m_isStyleSheet = false;
    relAttribute.m_isIcon = false;
    relAttribute.m_isAlternate = false;
    relAttribute.m_isDNSPrefetch = false;
#if ENABLE(LINK_PREFETCH)
    relAttribute.m_isLinkPrefetch = false;
#endif
    if (equalIgnoringCase(rel, "stylesheet"))
        relAttribute.m_isStyleSheet = true;
    else if (equalIgnoringCase(rel, "icon") || equalIgnoringCase(rel, "shortcut icon"))
        relAttribute.m_isIcon = true;
    else if (equalIgnoringCase(rel, "dns-prefetch"))
        relAttribute.m_isDNSPrefetch = true;
#if ENABLE(LINK_PREFETCH)
    else if (equalIgnoringCase(rel, "prefetch"))
        relAttribute.m_isLinkPrefetch = true;
#endif
    else if (equalIgnoringCase(rel, "alternate stylesheet") || equalIgnoringCase(rel, "stylesheet alternate")) {
        relAttribute.m_isStyleSheet = true;
        relAttribute.m_isAlternate = true;
    } else {
        // Tokenize the rel attribute and set bits based on specific keywords that we find.
        String relString = rel.string();
        relString.replace('\n', ' ');
        Vector<String> list;
        relString.split(' ', list);
        Vector<String>::const_iterator end = list.end();
        for (Vector<String>::const_iterator it = list.begin(); it != end; ++it) {
            if (equalIgnoringCase(*it, "stylesheet"))
                relAttribute.m_isStyleSheet = true;
            else if (equalIgnoringCase(*it, "alternate"))
                relAttribute.m_isAlternate = true;
            else if (equalIgnoringCase(*it, "icon"))
                relAttribute.m_isIcon = true;
        }
    }
}
Example #8
0
int main ()
{
    // For convenience.
    typedef std::vector<int, std::allocator<int> >                    Vector;
    typedef std::ostream_iterator<int, char, std::char_traits<char> > Iter;

    // Populate a vector with elements from an array.
    const Vector::value_type arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    Vector v (arr + 0, arr + sizeof arr / sizeof *arr);

    // Write out the contents to cout.
    std::copy (v.begin (), v.end (), Iter (std::cout," "));
    std::cout << std::endl << std::endl;

    // Move the 7 to the end of the vector.
    Vector::iterator result = std::remove (v.begin (), v.end (), 7);

    // Delete the 7 from the vector.
    v.erase (result, v.end ());

    std::copy (v.begin (), v.end (), Iter (std::cout, " "));
    std::cout << std::endl << std::endl;

    // Remove all non-zero elements beyond the fourth element.
    v.erase (std::remove_if (v.begin () + 4, v.end (), 
                             bnd_greater( int_greater (), 0 )), v.end ());

    std::copy (v.begin (), v.end (), Iter (std::cout, " "));
    std::cout << std::endl << std::endl;

    // Now remove all 3s on output.
    std::remove_copy (v.begin (), v.end (), Iter (std::cout, " "), 3);
    std::cout << std::endl << std::endl;

    // Now remove everything satisfying predicate on output.
    std::remove_copy_if (v.begin (), v.end (), Iter (std::cout, " "),
                         bnd_greater( int_greater (), 0 ) );

    // Return 0 on success, a non-zero value on failure
    return !!v.empty ();
}
Example #9
0
		void addNormal(int group, const Vector3& normal)
		{
			bool found = false;

			for (size_t i = 0; i < normals.size(); i++)
			{
				if ((normals[i].group & group) != 0)
				{
					bool otherGroups = (group & ~normals[i].group) != 0;

					if (otherGroups)
					{
						for (size_t j = i + 1; j < normals.size(); j++)
						{
							if ((normals[j].group & group) != 0)
							{
								normals[i].addNormal(normals[j]);
								normals.erase(normals.begin() + j);
								--j;
							}
						}
					}

					normals[i].addNormal(group, normal);

					found = true;
					break;;
				}
			}

			if (!found)
			{
				SmoothNormal smoothNormal;
				smoothNormal.addNormal(group, normal);

				normals.push_back(smoothNormal);
			}
		}
void PlaybackPipeline::flushAndEnqueueNonDisplayingSamples(Vector<RefPtr<MediaSample> > samples)
{
    ASSERT(WTF::isMainThread());

    if (samples.size() == 0) {
        LOG_MEDIA_MESSAGE("No samples, trackId unknown");
        return;
    }

    AtomicString trackId = samples[0]->trackID();
    LOG_MEDIA_MESSAGE("flushAndEnqueueNonDisplayingSamples: trackId=%s PTS[0]=%f ... PTS[n]=%f", trackId.string().utf8().data(), samples[0]->presentationTime().toFloat(), samples[samples.size()-1]->presentationTime().toFloat());

    GST_DEBUG_OBJECT(m_webKitMediaSrc.get(), "Flushing and re-enqueing %d samples for stream %s", samples.size(), trackId.string().utf8().data());

    GST_OBJECT_LOCK(m_webKitMediaSrc.get());
    Stream* stream = getStreamByTrackId(m_webKitMediaSrc.get(), trackId);

    if (!stream) {
        GST_OBJECT_UNLOCK(m_webKitMediaSrc.get());
        return;
    }

    GstElement* appsrc = stream->appsrc;
    GST_OBJECT_UNLOCK(m_webKitMediaSrc.get());

    // Actually no need to flush. The seek preparations have done it for us.

    for (Vector<RefPtr<MediaSample> >::iterator it = samples.begin(); it != samples.end(); ++it) {
        GStreamerMediaSample* sample = static_cast<GStreamerMediaSample*>(it->get());
        if (sample->sample() && gst_sample_get_buffer(sample->sample())) {
            GstSample* gstsample = gst_sample_ref(sample->sample());
            GST_BUFFER_FLAG_SET(gst_sample_get_buffer(gstsample), GST_BUFFER_FLAG_DECODE_ONLY);
            push_sample(GST_APP_SRC(appsrc), gstsample);
            // gst_app_src_push_sample() uses transfer-none for gstsample
            gst_sample_unref(gstsample);
        }
    }
}
Example #11
0
void ProjectWindow::refreshAssetList()
{
   // Clear list.
   mAssetsTab->assetList->DeleteAllItems();
   mAssetListRoot = mAssetsTab->assetList->AddRoot("ROOT");

   Vector<ModuleInfo>* modules = mEditorManager->getModuleList();

   const char* currentModuleID = "";
   wxTreeItemId currentModuleTreeID = mAssetListRoot;
   for (Vector<ModuleInfo>::iterator modulesItr = modules->begin(); modulesItr != modules->end(); ++modulesItr)
   {
      if (dStrcmp(modulesItr->moduleID, currentModuleID) != 0)
      {
         currentModuleID = modulesItr->moduleID;
         currentModuleTreeID = mAssetsTab->assetList->AppendItem(mAssetListRoot, modulesItr->moduleID, 0, -1, new ModuleTreeItemData(*modulesItr));
      }
      
      for (Vector<AssetCategoryInfo>::iterator assetCatItr = modulesItr->assets.begin(); assetCatItr != modulesItr->assets.end(); ++assetCatItr)
      {
         wxTreeItemId categoryTreeID = mAssetsTab->assetList->AppendItem(currentModuleTreeID, assetCatItr->categoryName, 1, -1, new AssetCategoryTreeItemData(*assetCatItr));

         for (Vector<const AssetDefinition*>::iterator assetItr = assetCatItr->assets.begin(); assetItr != assetCatItr->assets.end(); ++assetItr)
         {
            // Fetch asset definition.
            const AssetDefinition* pAssetDefinition = *assetItr;
            char buf[256];
            dStrcpy(buf, pAssetDefinition->mAssetId);
            const char* moduleName = dStrtok(buf, ":");
            const char* assetName = dStrtok(NULL, ":");
            mAssetsTab->assetList->AppendItem(categoryTreeID, assetName, 2, -1, new AssetTreeItemData(pAssetDefinition));
         }
      }
   }

   // Sort Modules by Name
   mAssetsTab->assetList->SortChildren(mAssetListRoot);
}
Example #12
0
Vector<unsigned> WMLSelectElement::valueStringToOptionIndices(const String& value) const
{
    Vector<unsigned> indices;
    if (value.isEmpty())
        return indices;

    const Vector<Element*>& items = m_data.listItems(this);
    if (items.isEmpty())
        return indices;

    Vector<String> indexStrings;
    value.split(';', indexStrings);

    unsigned optionIndex = 0;

    Vector<String>::const_iterator end = indexStrings.end();
    for (Vector<String>::const_iterator it = indexStrings.begin(); it != end; ++it) {
        String value = *(it);
        // SAMSUNG_WML_FIXES+
        // wml/struct/control/select/element/value/3
        // reset the optionIndex = 0
        for (unsigned i = 0, optionIndex = 0; i < items.size(); ++i) {
            // SAMSUNG_WML_FIXES-
            if (!isOptionElement(items[i]))
                continue;

            ++optionIndex;
            if (OptionElement* optionElement = toOptionElement(items[i])) {
                if (optionElement->value() == value) {
                    indices.append(optionIndex);
                    break;
                }
            }
        }
    }

    return indices;
}
ResourceRequest createAccessControlPreflightRequest(const ResourceRequest& request, SecurityOrigin* securityOrigin)
{
    ResourceRequest preflightRequest(request.url());
    updateRequestForAccessControl(preflightRequest, securityOrigin, DoNotAllowStoredCredentials);
    preflightRequest.setHTTPMethod("OPTIONS");
    preflightRequest.setHTTPHeaderField("Access-Control-Request-Method", request.httpMethod());
    preflightRequest.setPriority(request.priority());
    preflightRequest.setRequestContext(request.requestContext());
    preflightRequest.setSkipServiceWorker(true);

    const HTTPHeaderMap& requestHeaderFields = request.httpHeaderFields();

    if (requestHeaderFields.size() > 0) {
        // Sort header names lexicographically: https://crbug.com/452391
        // Fetch API Spec:
        //   https://fetch.spec.whatwg.org/#cors-preflight-fetch-0
        Vector<String> headers;
        for (const auto& header : requestHeaderFields) {
            if (equalIgnoringCase(header.key, "referer")) {
                // When the request is from a Worker, referrer header was added
                // by WorkerThreadableLoader. But it should not be added to
                // Access-Control-Request-Headers header.
                continue;
            }
            headers.append(header.key.lower());
        }
        std::sort(headers.begin(), headers.end(), WTF::codePointCompareLessThan);
        StringBuilder headerBuffer;
        for (const String& header : headers) {
            if (!headerBuffer.isEmpty())
                headerBuffer.appendLiteral(", ");
            headerBuffer.append(header);
        }
        preflightRequest.setHTTPHeaderField("Access-Control-Request-Headers", AtomicString(headerBuffer.toString()));
    }

    return preflightRequest;
}
Example #14
0
void computePreciseJumpTargetsInternal(Block* codeBlock, Instruction* instructionsBegin, unsigned instructionCount, Vector<unsigned, vectorSize>& out)
{
    ASSERT(out.isEmpty());
    
    // We will derive a superset of the jump targets that the code block thinks it has.
    // So, if the code block claims there are none, then we are done.
    if (Mode == ComputePreciseJumpTargetsMode::FollowCodeBlockClaim && !codeBlock->numberOfJumpTargets())
        return;
    
    for (unsigned i = codeBlock->numberOfExceptionHandlers(); i--;) {
        out.append(codeBlock->exceptionHandler(i).target);
        out.append(codeBlock->exceptionHandler(i).start);
        out.append(codeBlock->exceptionHandler(i).end);
    }

    Interpreter* interpreter = codeBlock->vm()->interpreter;
    for (unsigned bytecodeOffset = 0; bytecodeOffset < instructionCount;) {
        OpcodeID opcodeID = interpreter->getOpcodeID(instructionsBegin[bytecodeOffset]);
        getJumpTargetsForBytecodeOffset(codeBlock, interpreter, instructionsBegin, bytecodeOffset, out);
        bytecodeOffset += opcodeLengths[opcodeID];
    }
    
    std::sort(out.begin(), out.end());
    
    // We will have duplicates, and we must remove them.
    unsigned toIndex = 0;
    unsigned fromIndex = 0;
    unsigned lastValue = UINT_MAX;
    while (fromIndex < out.size()) {
        unsigned value = out[fromIndex++];
        if (value == lastValue)
            continue;
        out[toIndex++] = value;
        lastValue = value;
    }
    out.resize(toIndex);
    out.shrinkToFit();
}
void LandscapeEditorCustomColors::LoadTextureAction(const FilePath &pathToFile)
{
	if(pathToFile.IsEmpty())
		return;

	Vector<Image*> images = ImageLoader::CreateFromFile(pathToFile);
	if(images.empty())
		return;

	Image* image = images.front();
	if(image)
	{
		Texture* texture = Texture::CreateFromData(image->GetPixelFormat(),
												   image->GetData(),
												   image->GetWidth(),
												   image->GetHeight(),
												   false);

		SafeRelease(colorSprite);
		colorSprite = Sprite::CreateAsRenderTarget(texSurf->GetWidth(), texSurf->GetHeight(), FORMAT_RGBA8888);
		Sprite* sprite = Sprite::CreateFromTexture(texture, 0, 0, texture->GetWidth(), texture->GetHeight());

		StoreOriginalState();

		RenderManager::Instance()->SetRenderTarget(colorSprite);
		sprite->Draw();
		RenderManager::Instance()->RestoreRenderTarget();
		PerformLandscapeDraw();

		SafeRelease(sprite);
		SafeRelease(texture);
		for_each(images.begin(), images.end(), SafeRelease<Image>);

		StoreSaveFileName(pathToFile);

		CreateUndoPoint();
	}
}
static ImageCandidate pickBestImageCandidate(float deviceScaleFactor, float sourceSize, Vector<ImageCandidate>& imageCandidates, Document* document = nullptr)
{
    const float defaultDensityValue = 1.0;
    bool ignoreSrc = false;
    if (imageCandidates.isEmpty())
        return ImageCandidate();

    // http://picture.responsiveimages.org/#normalize-source-densities
    for (ImageCandidate& image : imageCandidates) {
        if (image.resourceWidth() > 0) {
            image.setDensity((float)image.resourceWidth() / sourceSize);
            ignoreSrc = true;
        } else if (image.density() < 0) {
            image.setDensity(defaultDensityValue);
        }
    }

    std::stable_sort(imageCandidates.begin(), imageCandidates.end(), compareByDensity);

    Vector<ImageCandidate*> deDupedImageCandidates;
    float prevDensity = -1.0;
    for (ImageCandidate& image : imageCandidates) {
        if (image.density() != prevDensity && (!ignoreSrc || !image.srcOrigin()))
            deDupedImageCandidates.append(&image);
        prevDensity = image.density();
    }
    unsigned winner = selectionLogic(deDupedImageCandidates, deviceScaleFactor);
    ASSERT(winner < deDupedImageCandidates.size());
    winner = avoidDownloadIfHigherDensityResourceIsInCache(deDupedImageCandidates, winner, document);

    float winningDensity = deDupedImageCandidates[winner]->density();
    // 16. If an entry b in candidates has the same associated ... pixel density as an earlier entry a in candidates,
    // then remove entry b
    while ((winner > 0) && (deDupedImageCandidates[winner - 1]->density() == winningDensity))
        --winner;

    return *deDupedImageCandidates[winner];
}
Example #17
0
void EventManager::removeAll(SimObject *cbObj)
{
    // Iterate over all events.
    for( Vector<StringTableEntry>::const_iterator iter1 = mEvents.begin(); iter1 != mEvents.end(); iter1++ )
    {
        Vector<EventManagerListener::Subscriber>* subscribers = mListener.mSubscribers.retreive( *iter1 );
        if( !subscribers )
            continue;
        for( Vector<EventManagerListener::Subscriber>::iterator iter2 = subscribers->begin(); iter2 != subscribers->end(); iter2++ )
        {
            // Erase the event.
            if( iter2->listener == cbObj )
            {
                if (iter2->callDepth > 0)
                    iter2->removeFlag = true;
                else
                    subscribers->erase_fast( iter2 );
                break;
            }
        }
    }

}
Example #18
0
	void Resources::unloadAllUnused()
	{
		Vector<HResource> resourcesToUnload;

		{
			Lock lock(mLoadedResourceMutex);
			for(auto iter = mLoadedResources.begin(); iter != mLoadedResources.end(); ++iter)
			{
				const LoadedResourceData& resData = iter->second;

				if (resData.resource.mData->mRefCount == resData.numInternalRefs) // Only internal references exist, free it
					resourcesToUnload.push_back(resData.resource.lock());
			}
		}

		// Note: When unloading multiple resources it's possible that unloading one will also unload
		// another resource in "resourcesToUnload". This is fine because "unload" deals with invalid
		// handles gracefully.
		for(auto iter = resourcesToUnload.begin(); iter != resourcesToUnload.end(); ++iter)
		{
			release(*iter);
		}
	}
Example #19
0
static inline Region transformSurfaceOpaqueRegion(const RenderSurfaceType* surface, const Region& region, const TransformationMatrix& transform)
{
    // Verify that rects within the |surface| will remain rects in its target surface after applying |transform|. If this is true, then
    // apply |transform| to each rect within |region| in order to transform the entire Region.

    IntRect bounds = region.bounds();
    FloatRect centeredBounds(-bounds.width() / 2.0, -bounds.height() / 2.0, bounds.width(), bounds.height());
    FloatQuad transformedBoundsQuad = transform.mapQuad(FloatQuad(centeredBounds));
    if (!transformedBoundsQuad.isRectilinear())
        return Region();

    Region transformedRegion;

    IntRect surfaceBounds = surface->contentRect();
    Vector<IntRect> rects = region.rects();
    Vector<IntRect>::const_iterator end = rects.end();
    for (Vector<IntRect>::const_iterator i = rects.begin(); i != end; ++i) {
        FloatRect centeredOriginRect(-i->width() / 2.0 + i->x() - surfaceBounds.x(), -i->height() / 2.0 + i->y() - surfaceBounds.y(), i->width(), i->height());
        FloatRect transformedRect = transform.mapRect(FloatRect(centeredOriginRect));
        transformedRegion.unite(enclosedIntRect(transformedRect));
    }
    return transformedRegion;
}
Example #20
0
// CodeReview [tom, 2/20/2007] The "listener" argument was an IMessageListener,
// but it was actually used as a SimObject and never a listener. Thus, it is now a SimObject.
void EventManager::remove(SimObject *cbObj, const char* event)
{
    // If the event doesn't exist, we have succeeded in removing it!
    if( !isRegisteredEvent( event ) )
        return;

    Vector<EventManagerListener::Subscriber>* subscribers = mListener.mSubscribers.retreive( event );
    if( !subscribers )
        return;

    for( Vector<EventManagerListener::Subscriber>::iterator iter = subscribers->begin(); iter != subscribers->end(); iter++ )
    {
        // Erase the event.
        if( iter->listener == cbObj )
        {
            if (iter->callDepth > 0)
                iter->removeFlag = true;
            else
                subscribers->erase_fast( iter );
            break;
        }
    }
}
bool SurfaceCollection::drawGL(const SkRect& visibleContentRect)
{
    TRACE_METHOD();
#ifdef DEBUG_COUNT
    ClassTracker::instance()->show();
#endif

    bool needsRedraw = false;
    updateLayerPositions(visibleContentRect);
    bool layerTilesDisabled = m_compositedRoot->state()->isSingleSurfaceRenderingMode();

    // create a duplicate vector of surfaces, sorted by z value
    Vector <Surface*> surfaces;
    for (unsigned int i = 0; i < m_surfaces.size(); i++)
        surfaces.append(m_surfaces[i]);
    std::stable_sort(surfaces.begin()+1, surfaces.end(), compareSurfaceZ);

    // draw the sorted vector
    for (unsigned int i = 0; i < m_surfaces.size(); i++)
        needsRedraw |= surfaces[i]->drawGL(layerTilesDisabled);

    return needsRedraw;
}
Example #22
0
void PluginDatabase::getPluginPathsInDirectories(HashSet<String>& paths) const
{
    // FIXME: This should be a case insensitive set.
    HashSet<String> uniqueFilenames;

#if defined(XP_UNIX)
    String fileNameFilter("*.so");
#else
    String fileNameFilter("");
#endif

    Vector<String>::const_iterator dirsEnd = m_pluginDirectories.end();
    for (Vector<String>::const_iterator dIt = m_pluginDirectories.begin(); dIt != dirsEnd; ++dIt) {
        Vector<String> pluginPaths = listDirectory(*dIt, fileNameFilter);
        Vector<String>::const_iterator pluginsEnd = pluginPaths.end();
        for (Vector<String>::const_iterator pIt = pluginPaths.begin(); pIt != pluginsEnd; ++pIt) {
            if (!fileExists(*pIt))
                continue;

            paths.add(*pIt);
        }
    }
}
Example #23
0
Vector<IntRect> FindController::rectsForTextMatches()
{
    Vector<IntRect> rects;

    for (Frame* frame = m_webPage->corePage()->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
        Document* document = frame->document();
        if (!document)
            continue;

        IntRect visibleRect = frame->view()->visibleContentRect();
        Vector<IntRect> frameRects = document->markers()->renderedRectsForMarkers(DocumentMarker::TextMatch);
        IntPoint frameOffset(-frame->view()->scrollOffsetRelativeToDocument().width(), -frame->view()->scrollOffsetRelativeToDocument().height());
        frameOffset = frame->view()->convertToContainingWindow(frameOffset);

        for (Vector<IntRect>::iterator it = frameRects.begin(), end = frameRects.end(); it != end; ++it) {
            it->intersect(visibleRect);
            it->move(frameOffset.x(), frameOffset.y());
            rects.append(*it);
        }
    }

    return rects;
}
void XMLHttpRequestProgressEventThrottle::dispatchDeferredEvents(Timer<XMLHttpRequestProgressEventThrottle>* timer)
{
    ASSERT_UNUSED(timer, timer == &m_dispatchDeferredEventsTimer);
    ASSERT(m_deferEvents);
    m_deferEvents = false;

    // Take over the deferred events before dispatching them which can potentially add more.
    Vector<RefPtr<Event>> deferredEvents;
    m_deferredEvents.swap(deferredEvents);

    RefPtr<Event> deferredProgressEvent = m_deferredProgressEvent;
    m_deferredProgressEvent = 0;

    Vector<RefPtr<Event>>::const_iterator it = deferredEvents.begin();
    const Vector<RefPtr<Event>>::const_iterator end = deferredEvents.end();
    for (; it != end; ++it)
        dispatchEvent(*it);

    // The progress event will be in the m_deferredEvents vector if the load was finished while suspended.
    // If not, just send the most up-to-date progress on resume.
    if (deferredProgressEvent)
        dispatchEvent(deferredProgressEvent);
}
Example #25
0
TEST(WTF_Vector, Iterator)
{
    Vector<int> intVector;
    intVector.append(10);
    intVector.append(11);
    intVector.append(12);
    intVector.append(13);

    Vector<int>::iterator it = intVector.begin();
    Vector<int>::iterator end = intVector.end();
    EXPECT_TRUE(end != it);

    EXPECT_EQ(10, *it);
    ++it;
    EXPECT_EQ(11, *it);
    ++it;
    EXPECT_EQ(12, *it);
    ++it;
    EXPECT_EQ(13, *it);
    ++it;

    EXPECT_TRUE(end == it);
}
void mgtk_event_set_color(int id, float r, float g, float b, float a)
{
#ifdef DISABLE_GTK_COLORBUTTON
	return;
#else
	Vector<GtkWidget*> *widgets;
	GtkWidget *colorbutton;
	GdkColor color;
	guint16 alpha;
	unsigned int i;

	widgets = gWidgetMap[id];

	if (!widgets)
		return;

	for (i = widgets->begin(); i < widgets->end(); ++i)
	{
		colorbutton = (*widgets)[i];

		if (colorbutton && GTK_IS_COLOR_BUTTON(colorbutton))
		{
			color.red = (unsigned short)(r * 65535.0);
			color.green = (unsigned short)(g * 65535.0);
			color.blue = (unsigned short)(b * 65535.0);
			alpha = (unsigned short)(a * 65535.0);
			
			gtk_color_button_set_color(GTK_COLOR_BUTTON(colorbutton), &color);
			gtk_color_button_set_alpha(GTK_COLOR_BUTTON(colorbutton), alpha);
		}
		else
		{
			mgtk_print("mgtk_event_set_color> %d:%d failed", id, i);
		}
	}
#endif
}
Example #27
0
void InspectorPageAgent::searchInResources(ErrorString*, const String& text, const bool* const optionalCaseSensitive, const bool* const optionalIsRegex, RefPtr<InspectorArray>* object)
{
    RefPtr<InspectorArray> result = InspectorArray::create();

    bool isRegex = optionalIsRegex ? *optionalIsRegex : false;
    String regexSource = isRegex ? text : createSearchRegexSource(text);

    bool caseSensitive = optionalCaseSensitive ? *optionalCaseSensitive : false;
    RegularExpression regex(regexSource, caseSensitive ? TextCaseSensitive : TextCaseInsensitive);

    for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext(m_page->mainFrame())) {
        String content;
        Vector<CachedResource*> allResources = cachedResourcesForFrame(frame);
        for (Vector<CachedResource*>::const_iterator it = allResources.begin(); it != allResources.end(); ++it) {
            CachedResource* cachedResource = *it;
            switch (InspectorPageAgent::cachedResourceType(*cachedResource)) {
            case InspectorPageAgent::StylesheetResource:
            case InspectorPageAgent::ScriptResource:
                if (decodeCachedResource(cachedResource, &content)) {
                    int matchesCount = countRegularExpressionMatches(regex, content);
                    if (matchesCount)
                        result->pushValue(buildObjectForSearchMatch(frameId(frame), cachedResource->url(), matchesCount));
                }
                break;
            default:
                break;
            }
        }
        if (decodeMainResource(frame, &content)) {
            int matchesCount = countRegularExpressionMatches(regex, content);
            if (matchesCount)
                result->pushValue(buildObjectForSearchMatch(frameId(frame), frame->document()->url(), matchesCount));
        }
    }

    *object = result;
}
void ScrollbarThemeChromium::paintTickmarks(GraphicsContext* context, Scrollbar* scrollbar, const IntRect& rect)
{
    if (scrollbar->orientation() != VerticalScrollbar)
        return;

    if (rect.height() <= 0 || rect.width() <= 0)
        return;  // nothing to draw on.

    // Get the tickmarks for the frameview.
    Vector<IntRect> tickmarks;
    scrollbar->client()->getTickmarks(tickmarks);
    if (!tickmarks.size())
        return;

    // Get the image for the tickmarks.
    static RefPtr<Image> dash = Image::loadPlatformResource("tickmarkDash");
    if (dash->isNull()) {
        ASSERT_NOT_REACHED();
        return;
    }

    context->save();

    for (Vector<IntRect>::const_iterator i = tickmarks.begin(); i != tickmarks.end(); ++i) {
        // Calculate how far down (in %) the tick-mark should appear.
        const float percent = static_cast<float>(i->y()) / scrollbar->totalSize();

        // Calculate how far down (in pixels) the tick-mark should appear.
        const int yPos = rect.topLeft().y() + (rect.height() * percent);

        IntPoint tick(scrollbar->x(), yPos);
        context->drawImage(dash.get(), tick);
    }

    context->restore();
}
void SVGDocumentExtensions::rebuildAllElementReferencesForTarget(SVGElement* referencedElement)
{
    ASSERT(referencedElement);
    HashMap<SVGElement*, OwnPtr<HashSet<SVGElement*> > >::iterator it = m_elementDependencies.find(referencedElement);
    if (it == m_elementDependencies.end())
        return;
    ASSERT(it->key == referencedElement);
    Vector<SVGElement*> toBeNotified;

    HashSet<SVGElement*>* referencingElements = it->value.get();
    HashSet<SVGElement*>::iterator setEnd = referencingElements->end();
    for (HashSet<SVGElement*>::iterator setIt = referencingElements->begin(); setIt != setEnd; ++setIt)
        toBeNotified.append(*setIt);

    // Force rebuilding the referencingElement so it knows about this change.
    Vector<SVGElement*>::iterator vectorEnd = toBeNotified.end();
    for (Vector<SVGElement*>::iterator vectorIt = toBeNotified.begin(); vectorIt != vectorEnd; ++vectorIt) {
        // Before rebuilding referencingElement ensure it was not removed from under us.
        if (HashSet<SVGElement*>* referencingElements = setOfElementsReferencingTarget(referencedElement)) {
            if (referencingElements->contains(*vectorIt))
                (*vectorIt)->svgAttributeChanged(XLinkNames::hrefAttr);
        }
    }
}
void WebNotificationManagerProxy::clearNotifications(WebPageProxy* webPage, const Vector<uint64_t>& pageNotificationIDs, NotificationFilterFunction filterFunction)
{
    uint64_t targetPageID = webPage->pageID();

    Vector<uint64_t> globalNotificationIDs;
    globalNotificationIDs.reserveCapacity(m_globalNotificationMap.size());

    for (auto it = m_notifications.begin(), end = m_notifications.end(); it != end; ++it) {
        uint64_t webPageID = it->key.first;
        uint64_t pageNotificationID = it->key.second;
        if (!filterFunction(webPageID, pageNotificationID, targetPageID, pageNotificationIDs))
            continue;

        uint64_t globalNotificationID = it->value.first;
        globalNotificationIDs.append(globalNotificationID);
    }

    for (auto it = globalNotificationIDs.begin(), end = globalNotificationIDs.end(); it != end; ++it) {
        auto pageNotification = m_globalNotificationMap.take(*it);
        m_notifications.remove(pageNotification);
    }

    m_provider.clearNotifications(globalNotificationIDs);
}