Пример #1
0
GameSolution::GameSolution()
{

	//timer =  new Timer();
	//FPSTimer.Initialize();
	Vector2 startPosition(512.0f,364.0f);
	Vector2 firstEnemyStartingPosition(0.0f,MyRandomNumber::RandomInRange(0.0f,728.0f));

	/*ParticleEffect* pe = new ParticleEffect(500,2,startPosition,startPosition,myDT);
	pe->TunnelEffect();
	AddToList(*pe);*/

	//Profiler::getInstance().startUp("ProfileTest.csv");

	meShip = SpaceShip(*this);


	meShip.position = Vector2(500,300);
	//meLerp.position = Vector2(+50.0f,50.0f);
	cm = new CollisionManager();

	for(int i = 0 ; i < 20; i++)
	{
		ParticleEffect pe(myDT,3);
		pe.isFinished = true;
		listOfParticleEffects[i] = pe;

	}


}
Пример #2
0
void AutomationPattern::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
	_this.setAttribute( "pos", startPosition() );
	_this.setAttribute( "len", length() );
	_this.setAttribute( "name", name() );
	_this.setAttribute( "prog", QString::number( progressionType() ) );
	_this.setAttribute( "tens", QString::number( getTension() ) );
	_this.setAttribute( "mute", QString::number( isMuted() ) );

	for( timeMap::const_iterator it = m_timeMap.begin();
						it != m_timeMap.end(); ++it )
	{
		QDomElement element = _doc.createElement( "time" );
		element.setAttribute( "pos", it.key() );
		element.setAttribute( "value", it.value() );
		_this.appendChild( element );
	}

	for( objectVector::const_iterator it = m_objects.begin();
						it != m_objects.end(); ++it )
	{
		if( *it )
		{
			QDomElement element = _doc.createElement( "object" );
			element.setAttribute( "id",
				ProjectJournal::idToSave( ( *it )->id() ) );
			_this.appendChild( element );
		}
	}
}
Пример #3
0
void Pattern::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
	_this.setAttribute( "type", m_patternType );
	_this.setAttribute( "name", name() );
	// as the target of copied/dragged pattern is always an existing
	// pattern, we must not store actual position, instead we store -1
	// which tells loadSettings() not to mess around with position
	if( _this.parentNode().nodeName() == "clipboard" ||
			_this.parentNode().nodeName() == "dnddata" )
	{
		_this.setAttribute( "pos", -1 );
	}
	else
	{
		_this.setAttribute( "pos", startPosition() );
	}
	_this.setAttribute( "len", length() );
	_this.setAttribute( "muted", isMuted() );
	_this.setAttribute( "steps", m_steps );

	// now save settings of all notes
	for( NoteVector::Iterator it = m_notes.begin();
						it != m_notes.end(); ++it )
	{
		if( ( *it )->length() )
		{
			( *it )->saveState( _doc, _this );
		}
	}
}
void DocumentMarkerControllerTest::markNodeContentsWithComposition(Node* node)
{
    // Force layoutObjects to be created; TextIterator, which is used in
    // DocumentMarkerControllerTest::addMarker(), needs them.
    document().updateStyleAndLayout();
    auto range = EphemeralRange::rangeOfContents(*node);
    markerController().addCompositionMarker(range.startPosition(), range.endPosition(), Color::black, false, Color::black);
}
void DocumentMarkerControllerTest::markNodeContents(PassRefPtrWillBeRawPtr<Node> node)
{
    // Force layoutObjects to be created; TextIterator, which is used in
    // DocumentMarkerControllerTest::addMarker(), needs them.
    document().updateLayout();
    auto range = EphemeralRange::rangeOfContents(*node);
    markerController().addMarker(range.startPosition(), range.endPosition(), DocumentMarker::Spelling);
}
EphemeralRangeTemplate<Strategy> CharacterIteratorAlgorithm<Strategy>::calculateCharacterSubrange(int offset, int length)
{
    advance(offset);
    const PositionAlgorithm<Strategy> startPos = startPosition();

    if (length > 1)
        advance(length - 1);
    return EphemeralRangeTemplate<Strategy>(startPos, endPosition());
}
Пример #7
0
QString ClassAnalyzer::getNamespacePrefix(int position)
{
    QString namespacePrefix;

    for (auto it = m_namespaces.begin(); it != m_namespaces.end(); it++)
    {
        if (position > it->startPosition() && position < it->stopPosition())
        {
            namespacePrefix.append(it->name());
            namespacePrefix.append("::");
        }
    }

    return namespacePrefix;
}
Пример #8
0
void bbTCO::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
	_this.setAttribute( "name", name() );
	if( _this.parentNode().nodeName() == "clipboard" )
	{
		_this.setAttribute( "pos", -1 );
	}
	else
	{
		_this.setAttribute( "pos", startPosition() );
	}
	_this.setAttribute( "len", length() );
	_this.setAttribute( "muted", isMuted() );
	_this.setAttribute( "color", m_color );
}
Пример #9
0
/*!
    Validates the content, and cursor position.

    Can alter the content of the document, and cursor parameters.
 */
QValidator::State HbValidatorField::validate(QTextDocument* doc, QTextCursor& cursor, int changePosition, int changeCharsRemoved, int changeCharsAdded)
{
    Q_D(HbValidatorField);

    Q_UNUSED(cursor);
    Q_UNUSED(changePosition);
    Q_UNUSED(changeCharsRemoved);
    Q_UNUSED(changeCharsAdded);

    int pos = 0;
    QString content = doc->toPlainText();   //TODO check if formating is needed, if yes use QTextCursor
    QString fieldText = content.mid(startPosition(), length());
    QValidator::State state = d->validator->validate(fieldText, pos);
    return state;
}
Пример #10
0
void TimelineSelectionTool::mouseMoveEvent(TimelineMovableAbstractItem *item,
                                           QGraphicsSceneMouseEvent *event)
{
    Q_UNUSED(item);

    if (event->buttons() == Qt::LeftButton) {
        auto endPoint = event->scenePos();
        if (endPoint.x() < 0)
            endPoint.rx() = 0;
        if (endPoint.y() < 0)
            endPoint.ry() = 0;
        m_selectionRect->setRect(QRectF(startPosition(), endPoint).normalized());
        m_selectionRect->show();

        aboutToSelect(selectionMode(event),
                      scene()->items(m_selectionRect->rect(), Qt::ContainsItemShape));
    }
}
Пример #11
0
void DB::WipeDB( std::vector<RectangleF*>& db )
{
	if (db.empty())
		return;

	Vector2F startPosition(0,0);

	std::vector<RectangleF*>::iterator it = db.begin();
	while (it != db.end())
	{
		if (*it)
		{
			(*it)->SetPosition(startPosition);
			(*it)->SetStatus(FREE);
		}
		++it;
	}
}
Пример #12
0
void SampleTCO::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
	if( _this.parentNode().nodeName() == "clipboard" )
	{
		_this.setAttribute( "pos", -1 );
	}
	else
	{
		_this.setAttribute( "pos", startPosition() );
	}
	_this.setAttribute( "len", length() );
	_this.setAttribute( "muted", isMuted() );
	_this.setAttribute( "src", sampleFile() );
	if( sampleFile() == "" )
	{
		QString s;
		_this.setAttribute( "data", m_sampleBuffer->toBase64( s ) );
	}
	// TODO: start- and end-frame
}
TEST_F(OsgScreenSpaceQuadRenderTests, InitTest)
{
	std::shared_ptr<OsgScreenSpaceQuadRepresentation> quad =
		std::make_shared<OsgScreenSpaceQuadRepresentation>("Screen Quad");

	viewElement->addComponent(quad);

	/// Run the thread
	runtime->start();
	EXPECT_TRUE(graphicsManager->isInitialized());
	EXPECT_TRUE(viewElement->isInitialized());
	quad->setSize(100, 100);
	boost::this_thread::sleep(boost::posix_time::milliseconds(1000));

	auto dimensions = viewElement->getView()->getDimensions();

	SurgSim::Math::Vector3d startPosition(0.0, 0.0, 0.0);
	SurgSim::Math::Vector3d endPosition(dimensions[0], dimensions[1], 0.0);

	SurgSim::Math::Vector2d startSize(0.0, 0.0);
	SurgSim::Math::Vector2d endSize(200, 200);

	int numSteps = 100;
	for (int i = 0; i < numSteps; ++i)
	{
		/// Calculate t in [0.0, 1.0]
		double t = static_cast<double>(i) / numSteps;
		RigidTransform3d currentPose = SurgSim::Testing::interpolatePose(
										   Vector3d::Identity(), Vector3d::Identity(),
										   startPosition, endPosition, t);

		quad->setLocalPose(currentPose);

		SurgSim::Math::Vector2d size = SurgSim::Testing::interpolate(startSize, endSize, t);
		quad->setSize(size.x(), size.y());

		boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps));
	}

}
void SpaceOrientation:: initializePosition()
{
#ifdef __linux__
    try
    {
        AL::ALMotionProxy motion(robotIp);
        bool useSensors = true;
        naoPositionOnStartInSpace = motion.getRobotPosition(useSensors);
//        std::cout << "sensors: " << naoPositionOnStartInSpace << std::endl;
        cv::Point2d startPosition(naoPositionOnStartInSpace[1],
                                  naoPositionOnStartInSpace[0]);
        startPosition = rotatePoint(startPosition,
                                    naoPositionOnStartInSpace[2]);
//        std::cout << "rotation: " << rotatePoint(cv::Point2d(1,1), -M_PI/2);
        naoPositionOnStartInSpace[0] = startPosition.y;
        naoPositionOnStartInSpace[1] = startPosition.x;

//        std::cout << "Start position: " << startPosition << std::endl;

        naoPositionInSpace.push_back(0);
        naoPositionInSpace.push_back(0);
        naoPositionInSpace.push_back(0);
        naoPreviousPositionInSpace = naoPositionInSpace;

    }
    catch (const AL::ALError& e)
    {
        std::cerr << "Caught exception: " << e.what() << std::endl;
        exit(EXIT_FAILURE);
    }
#else
    std::cout << "initializePosition() not on Linux." << std::endl;
    naoPositionInSpace.push_back(0);
    naoPositionInSpace.push_back(0);
    naoPositionInSpace.push_back(0);
    naoPreviousPositionInSpace = naoPositionInSpace;
    naoPositionOnStartInSpace = naoPositionInSpace;

#endif
}
Пример #15
0
void BBTCO::saveSettings( QDomDocument & doc, QDomElement & element )
{
	element.setAttribute( "name", name() );
	if( element.parentNode().nodeName() == "clipboard" )
	{
		element.setAttribute( "pos", -1 );
	}
	else
	{
		element.setAttribute( "pos", startPosition() );
	}
	element.setAttribute( "len", length() );
	element.setAttribute( "muted", isMuted() );
	element.setAttribute( "color", color() );
	
	if( m_useStyleColor )
	{
		element.setAttribute( "usestyle", 1 );
	}
	else
	{
		element.setAttribute( "usestyle", 0 );
	}
}
void InsertTextCommand::input(const String& text, bool selectInsertedText)
{
    
    ASSERT(text.find('\n') == notFound);

    if (!endingSelection().isNonOrphanedCaretOrRange())
        return;

    // Delete the current selection.
    // FIXME: This delete operation blows away the typing style.
    if (endingSelection().isRange()) {
        if (performTrivialReplace(text, selectInsertedText))
            return;
        deleteSelection(false, true, true, false);
    }

    Position startPosition(endingSelection().start());
    
    Position placeholder;
    // We want to remove preserved newlines and brs that will collapse (and thus become unnecessary) when content 
    // is inserted just before them.
    // FIXME: We shouldn't really have to do this, but removing placeholders is a workaround for 9661.
    // If the caret is just before a placeholder, downstream will normalize the caret to it.
    Position downstream(startPosition.downstream());
    if (lineBreakExistsAtPosition(downstream)) {
        // FIXME: This doesn't handle placeholders at the end of anonymous blocks.
        VisiblePosition caret(startPosition);
        if (isEndOfBlock(caret) && isStartOfParagraph(caret))
            placeholder = downstream;
        // Don't remove the placeholder yet, otherwise the block we're inserting into would collapse before
        // we get a chance to insert into it.  We check for a placeholder now, though, because doing so requires
        // the creation of a VisiblePosition, and if we did that post-insertion it would force a layout.
    }
    
    // Insert the character at the leftmost candidate.
    startPosition = startPosition.upstream();
    
    // It is possible for the node that contains startPosition to contain only unrendered whitespace,
    // and so deleteInsignificantText could remove it.  Save the position before the node in case that happens.
    Position positionBeforeStartNode(positionInParentBeforeNode(startPosition.node()));
    deleteInsignificantText(startPosition.upstream(), startPosition.downstream());
    if (!startPosition.node()->inDocument())
        startPosition = positionBeforeStartNode;
    if (!startPosition.isCandidate())
        startPosition = startPosition.downstream();
    
    startPosition = positionAvoidingSpecialElementBoundary(startPosition);
    
    Position endPosition;
    
    if (text == "\t") {
        endPosition = insertTab(startPosition);
        startPosition = endPosition.previous();
        if (placeholder.isNotNull())
            removePlaceholderAt(placeholder);
        m_charactersAdded += 1;
    } else {
        // Make sure the document is set up to receive text
        startPosition = prepareForTextInsertion(startPosition);
        if (placeholder.isNotNull())
            removePlaceholderAt(placeholder);
        Text *textNode = static_cast<Text *>(startPosition.node());
        int offset = startPosition.deprecatedEditingOffset();

        insertTextIntoNode(textNode, offset, text);
        endPosition = Position(textNode, offset + text.length());

        // The insertion may require adjusting adjacent whitespace, if it is present.
        rebalanceWhitespaceAt(endPosition);
        // Rebalancing on both sides isn't necessary if we've inserted a space.
        if (text != " ") 
            rebalanceWhitespaceAt(startPosition);
            
        m_charactersAdded += text.length();
    }

    // We could have inserted a part of composed character sequence,
    // so we are basically treating ending selection as a range to avoid validation.
    // <http://bugs.webkit.org/show_bug.cgi?id=15781>
    VisibleSelection forcedEndingSelection;
    forcedEndingSelection.setWithoutValidation(startPosition, endPosition);
    setEndingSelection(forcedEndingSelection);

    // Handle the case where there is a typing style.
    CSSMutableStyleDeclaration* typingStyle = document()->frame()->selection()->typingStyle();
    RefPtr<CSSComputedStyleDeclaration> endingStyle = endPosition.computedStyle();
    RefPtr<CSSValue> unicodeBidi;
    RefPtr<CSSValue> direction;
    if (typingStyle) {
        unicodeBidi = typingStyle->getPropertyCSSValue(CSSPropertyUnicodeBidi);
        direction = typingStyle->getPropertyCSSValue(CSSPropertyDirection);
    }
    endingStyle->diff(typingStyle);
    if (typingStyle && unicodeBidi) {
        ASSERT(unicodeBidi->isPrimitiveValue());
        typingStyle->setProperty(CSSPropertyUnicodeBidi, static_cast<CSSPrimitiveValue*>(unicodeBidi.get())->getIdent());
        if (direction) {
            ASSERT(direction->isPrimitiveValue());
            typingStyle->setProperty(CSSPropertyDirection, static_cast<CSSPrimitiveValue*>(direction.get())->getIdent());
        }
    }

    if (typingStyle && typingStyle->length())
        applyStyle(typingStyle);

    if (!selectInsertedText)
        setEndingSelection(VisibleSelection(endingSelection().end(), endingSelection().affinity()));
}
Пример #17
0
PassRefPtrWillBeRawPtr<Range> PlainTextRange::createRangeFor(const ContainerNode& scope, GetRangeFor getRangeFor) const
{
    ASSERT(isNotNull());

    RefPtrWillBeRawPtr<Range> resultRange = scope.document().createRange();

    size_t docTextPosition = 0;
    bool startRangeFound = false;

    Position textRunStartPosition;
    Position textRunEndPosition;

    TextIteratorBehaviorFlags behaviorFlags = TextIteratorEmitsObjectReplacementCharacter;
    if (getRangeFor == ForSelection)
        behaviorFlags |= TextIteratorEmitsCharactersBetweenAllVisiblePositions;
    auto range = rangeOfContents(const_cast<ContainerNode*>(&scope));
    TextIterator it(range->startPosition(), range->endPosition(), behaviorFlags);

    // FIXME: the atEnd() check shouldn't be necessary, workaround for <http://bugs.webkit.org/show_bug.cgi?id=6289>.
    if (!start() && !length() && it.atEnd()) {
        resultRange->setStart(it.currentContainer(), 0, ASSERT_NO_EXCEPTION);
        resultRange->setEnd(it.currentContainer(), 0, ASSERT_NO_EXCEPTION);
        return resultRange.release();
    }

    for (; !it.atEnd(); it.advance()) {
        int len = it.length();

        textRunStartPosition = it.startPositionInCurrentContainer();
        textRunEndPosition = it.endPositionInCurrentContainer();

        bool foundStart = start() >= docTextPosition && start() <= docTextPosition + len;
        bool foundEnd = end() >= docTextPosition && end() <= docTextPosition + len;

        // Fix textRunRange->endPosition(), but only if foundStart || foundEnd, because it is only
        // in those cases that textRunRange is used.
        if (foundEnd) {
            // FIXME: This is a workaround for the fact that the end of a run
            // is often at the wrong position for emitted '\n's or if the
            // renderer of the current node is a replaced element.
            if (len == 1 && (it.characterAt(0) == '\n' || it.isInsideReplacedElement())) {
                it.advance();
                if (!it.atEnd()) {
                    textRunEndPosition = it.startPositionInCurrentContainer();
                } else {
                    Position runEnd = VisiblePosition(textRunStartPosition).next().deepEquivalent();
                    if (runEnd.isNotNull())
                        textRunEndPosition = createLegacyEditingPosition(runEnd.containerNode(), runEnd.computeOffsetInContainerNode());
                }
            }
        }

        if (foundStart) {
            startRangeFound = true;
            if (textRunStartPosition.containerNode()->isTextNode()) {
                int offset = start() - docTextPosition;
                resultRange->setStart(textRunStartPosition.containerNode(), offset + textRunStartPosition.offsetInContainerNode(), IGNORE_EXCEPTION);
            } else {
                if (start() == docTextPosition)
                    resultRange->setStart(textRunStartPosition.containerNode(), textRunStartPosition.offsetInContainerNode(), IGNORE_EXCEPTION);
                else
                    resultRange->setStart(textRunEndPosition.containerNode(), textRunEndPosition.offsetInContainerNode(), IGNORE_EXCEPTION);
            }
        }

        if (foundEnd) {
            if (textRunStartPosition.containerNode()->isTextNode()) {
                int offset = end() - docTextPosition;
                resultRange->setEnd(textRunStartPosition.containerNode(), offset + textRunStartPosition.offsetInContainerNode(), IGNORE_EXCEPTION);
            } else {
                if (end() == docTextPosition)
                    resultRange->setEnd(textRunStartPosition.containerNode(), textRunStartPosition.offsetInContainerNode(), IGNORE_EXCEPTION);
                else
                    resultRange->setEnd(textRunEndPosition.containerNode(), textRunEndPosition.offsetInContainerNode(), IGNORE_EXCEPTION);
            }
            docTextPosition += len;
            break;
        }
        docTextPosition += len;
    }

    if (!startRangeFound)
        return nullptr;

    if (length() && end() > docTextPosition) { // end() is out of bounds
        resultRange->setEnd(textRunEndPosition.containerNode(), textRunEndPosition.offsetInContainerNode(), IGNORE_EXCEPTION);
    }

    return resultRange.release();
}
Пример #18
0
void Song::processAutomations(const TrackList &tracklist, MidiTime timeStart, fpp_t)
{
	AutomatedValueMap values;

	QSet<const AutomatableModel*> recordedModels;

	TrackContainer* container = this;
	int tcoNum = -1;

	switch (m_playMode)
	{
	case Mode_PlaySong:
		break;
	case Mode_PlayBB:
	{
		Q_ASSERT(tracklist.size() == 1);
		Q_ASSERT(tracklist.at(0)->type() == Track::BBTrack);
		auto bbTrack = dynamic_cast<BBTrack*>(tracklist.at(0));
		auto bbContainer = Engine::getBBTrackContainer();
		container = bbContainer;
		tcoNum = bbTrack->index();
	}
		break;
	default:
		return;
	}

	values = container->automatedValuesAt(timeStart, tcoNum);
	TrackList tracks = container->tracks();

	Track::tcoVector tcos;
	for (Track* track : tracks)
	{
		if (track->type() == Track::AutomationTrack) {
			track->getTCOsInRange(tcos, 0, timeStart);
		}
	}

	// Process recording
	for (TrackContentObject* tco : tcos)
	{
		auto p = dynamic_cast<AutomationPattern *>(tco);
		MidiTime relTime = timeStart - p->startPosition();
		if (p->isRecording() && relTime >= 0 && relTime < p->length())
		{
			const AutomatableModel* recordedModel = p->firstObject();
			p->recordValue(relTime, recordedModel->value<float>());

			recordedModels << recordedModel;
		}
	}

	// Apply values
	for (auto it = values.begin(); it != values.end(); it++)
	{
		if (! recordedModels.contains(it.key()))
		{
			it.key()->setAutomatedValue(it.value());
		}
	}
}
Пример #19
0
int main(){
    
    Vector2 startPosition(300, 500);
    Vector2 startDirection(0, -1);
    
    /* This list is used to store all user emmitted active missiles */
    MissileList enemy2Missiles;
    MissileList playerMissiles;
    
    /* Create the thunder */
    Thunder thunder(startPosition, startDirection);
    thunder.setVelocity(5);
    thunder.SwitchWeapon(BULLET, playerMissiles);
    
    Plane *player;
    player = &thunder;
    
    /* Create the boss */
    LazerEnemy enemy2(Vector2(300, 0), Vector2(0,1));
    enemy2.Init(enemy2Missiles);
    enemy2.setVelocity(15);
    Plane *enemy;
    enemy = &enemy2;
  
    
    FsOpenWindow(0,0,WINDOW_WID,WINDOW_HEI,1);
    glClearColor(0.1, 0.1, 0.1, 1);
    
    bool running = true;
    int i = 0;
    int cntDown = 0;
    
    while(running)
    {
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
        FsPollDevice();
        
        int key=FsInkey();
        int lb, mb, rb, mx, my;
        int mouse = FsGetMouseEvent(lb, mb, rb, mx, my);
        
        if(FSKEY_ESC==key) {
            running=false;
            break;
        } else if (FSKEY_UP == key) {
            /* UP for power up */
            ((Thunder *)player)->PowerUp(playerMissiles);
        }
        if (FSMOUSEEVENT_RBUTTONDOWN == mouse) {
            /* Right click for switch between 3 types of weapons */
            i = (i+1) % 3;
            ((Thunder *)player)->SwitchWeapon((MissileType)i, playerMissiles);
        }
        
        /* Thunder: shoot and cool down weapon. */
        player->Shoot(mouse, playerMissiles);
        player->CoolDown();
        
        /* Thunder: move and draw. */
        player->Move(1.0);
        player->Draw();
        
        /* Draw the enemy */
        enemy->Aim(player);
        printf("before move\n");
        enemy->Move(0.4);
        printf("after move\n");
        enemy->Draw();
        /* Enemy fire */
        ((LazerEnemy *)enemy)->Shoot(enemy2Missiles);
        enemy->CoolDown();
        
        if (enemy->CheckHit(playerMissiles) == 1) {
            ((LazerEnemy *)enemy)->Disappear(enemy2Missiles);
            cntDown = 100;
        }
        
        /* Stay for a while after boss die */
        if (cntDown > 0) {
            cntDown--;
            if (cntDown == 0)
                running = false;
        }
        
        /* traverse the missiles list, move missile */
        MissileNode *node;
        node = enemy2Missiles.getFront();
        while(node) {
            node->dat->Move(1.0);
            
            if (!node->dat->CheckInWindow()) {
                node = enemy2Missiles.Delete(node);
            } else {
                node = node->next;
            }
        }
        node = playerMissiles.getFront();
        while(node) {
            node->dat->Move(1.0);
            
            if (!node->dat->CheckInWindow()) {
                node = playerMissiles.Delete(node);
            } else {
                node = node->next;
            }
        }
        
        FOR_EACH(node, enemy2Missiles) {
            node->dat->Draw();
        }
        FOR_EACH(node, playerMissiles) {
            node->dat->Draw();
        }
        PrintPower(((LazerEnemy *)enemy)->getLife());
        FsSwapBuffers();
        FsSleep(25);
    }
    
    return 0;
}
EphemeralRange PlainTextRange::createRangeFor(const ContainerNode& scope, GetRangeFor getRangeFor) const
{
    ASSERT(isNotNull());

    size_t docTextPosition = 0;
    bool startRangeFound = false;

    Position textRunStartPosition;
    Position textRunEndPosition;

    TextIteratorBehaviorFlags behaviorFlags = TextIteratorEmitsObjectReplacementCharacter;
    if (getRangeFor == ForSelection)
        behaviorFlags |= TextIteratorEmitsCharactersBetweenAllVisiblePositions;
    auto range = EphemeralRange::rangeOfContents(scope);
    TextIterator it(range.startPosition(), range.endPosition(), behaviorFlags);

    // FIXME: the atEnd() check shouldn't be necessary, workaround for
    // <http://bugs.webkit.org/show_bug.cgi?id=6289>.
    if (!start() && !length() && it.atEnd())
        return EphemeralRange(Position(it.currentContainer(), 0));

    Position resultStart = Position(&scope.document(), 0);
    Position resultEnd = resultStart;

    for (; !it.atEnd(); it.advance()) {
        int len = it.length();

        textRunStartPosition = it.startPositionInCurrentContainer();
        textRunEndPosition = it.endPositionInCurrentContainer();

        bool foundStart = start() >= docTextPosition && start() <= docTextPosition + len;
        bool foundEnd = end() >= docTextPosition && end() <= docTextPosition + len;

        // Fix textRunRange->endPosition(), but only if foundStart || foundEnd, because it is only
        // in those cases that textRunRange is used.
        if (foundEnd) {
            // FIXME: This is a workaround for the fact that the end of a run
            // is often at the wrong position for emitted '\n's or if the
            // layoutObject of the current node is a replaced element.
            if (len == 1 && (it.characterAt(0) == '\n' || it.isInsideAtomicInlineElement())) {
                it.advance();
                if (!it.atEnd()) {
                    textRunEndPosition = it.startPositionInCurrentContainer();
                } else {
                    Position runEnd = nextPositionOf(createVisiblePosition(textRunStartPosition)).deepEquivalent();
                    if (runEnd.isNotNull())
                        textRunEndPosition = runEnd;
                }
            }
        }

        if (foundStart) {
            startRangeFound = true;
            if (textRunStartPosition.computeContainerNode()->isTextNode()) {
                int offset = start() - docTextPosition;
                resultStart = Position(textRunStartPosition.computeContainerNode(), offset + textRunStartPosition.offsetInContainerNode());
            } else {
                if (start() == docTextPosition)
                    resultStart = textRunStartPosition;
                else
                    resultStart = textRunEndPosition;
            }
        }

        if (foundEnd) {
            if (textRunStartPosition.computeContainerNode()->isTextNode()) {
                int offset = end() - docTextPosition;
                resultEnd = Position(textRunStartPosition.computeContainerNode(), offset + textRunStartPosition.offsetInContainerNode());
            } else {
                if (end() == docTextPosition)
                    resultEnd = textRunStartPosition;
                else
                    resultEnd = textRunEndPosition;
            }
            docTextPosition += len;
            break;
        }
        docTextPosition += len;
    }

    if (!startRangeFound)
        return EphemeralRange();

    if (length() && end() > docTextPosition) { // end() is out of bounds
        resultEnd = textRunEndPosition;
    }

    return EphemeralRange(resultStart.toOffsetInAnchor(), resultEnd.toOffsetInAnchor());
}
void LegacyCentrality::PSDSimulation(const evt::Event &event, double (&moduleEnergy)[45], std::vector< evt::Index<evt::sim::VertexTrack> > &specList)
{  
  unsigned int runNumber = event.GetEventHeader().GetRunNumber();
  det::Detector::GetInstance().Update(event.GetEventHeader().GetTime(), runNumber);
  const evt::SimEvent& simEvent = event.GetSimEvent();
  if (!simEvent.HasMainVertex())
    return;
  
  double psdPosition = 0;
  double psdShift = 10000;
  if (fDataSet == 40){
    psdPosition = 1667 - 580;
    psdShift = 13;
  } else {
    psdPosition = 2200 - 580;
    psdShift = 18;
  }
  
  for (int i = 0; i < 45; ++i){
    moduleEnergy[i] = 0;
  }
  
  const det::MagneticFieldTracker
        tracker(det::Detector::GetInstance().GetMagneticField(), utl::Tracker::eConservativeTrackStepper);
  const det::PSD &detectorPSD = det::Detector::GetInstance().GetPSD();
  
  TF2 showerProfile("showerProfile", radialShowerFit, -1000, 1000, -1000, 1000, 5);
  double showerDecay     = 1.91085;  // Values from fitting to beam shower from data
  double showerDecaySlow = 7.8342;   // Values from fitting to beam shower from data
  double fraction        = 0.964088; // Values from fitting to beam shower from data
  showerProfile.SetParameters(0, 0, showerDecay, showerDecaySlow, fraction);
  double cutOff = 100;
  double energyNorm = showerProfile.Integral(-cutOff, +cutOff, -cutOff, +cutOff);
  
  
  for (std::list< evt::sim::VertexTrack >::const_iterator vtxTrackIter =  simEvent.Begin<evt::sim::VertexTrack>(),
                                                               endIter =  simEvent.End<evt::sim::VertexTrack>();
                                                          vtxTrackIter != endIter;
                                                        ++vtxTrackIter){
    
    
    evt::sim::VertexTrack vtxTrack = *vtxTrackIter;
    if (vtxTrack.GetType() != evt::sim::VertexTrackConst::eGeneratorFinal && vtxTrack.GetType() != evt::sim::VertexTrackConst::eDetector)
      continue;
    utl::Vector trackMom = vtxTrack.GetMomentum();
    const double pt = sqrt(trackMom.GetX()*trackMom.GetX() + trackMom.GetY()*trackMom.GetY());
    
    evt::sim::Vertex startVertex;
    if (simEvent.Has(vtxTrack.GetStartVertexIndex()))
      startVertex = simEvent.Get(vtxTrack.GetStartVertexIndex());
    if (vtxTrack.HasStopVertex()){
      const evt::sim::Vertex& stopVertex = simEvent.Get(vtxTrack.GetStopVertexIndex());
      if (stopVertex.GetPosition().GetZ() < psdPosition)
        continue;
    }
    if (trackMom.GetMag() < 1)
      continue;
    if (trackMom.GetZ() < 0.5)
      continue;
    if (pt > 2) 
      continue;
    if (vtxTrack.GetCharge() == -1 && trackMom.GetMag() > 120.)
      continue;
    //if (vtxTrack.GetType() == evt::sim::VertexTrackConst::eDetector && vtxTrack.GetParticleId() <= 22)
    //  continue;
    
    int isSpec = 0;
    
    if (vtxTrack.GetType() == evt::sim::VertexTrackConst::eGeneratorFinal){
      if (std::find(specList.begin(), specList.end(), vtxTrack.GetIndex())!=specList.end()){
        int A = 0;
        if (vtxTrack.GetParticleId() > 1000000000) {
          A = (vtxTrack.GetParticleId() % 10000) / 10;
        } else {
          A = 1;
        }
        isSpec += A;
      }
    }
    
    if (isSpec){
      double fermiMom = fRandGen.Gaus(0, 0.2/sqrt(isSpec));
      if (fermiMom < 0) fermiMom *= -1;
      double theta = fRandGen.Uniform(0, 3.1415);
      double phi   = fRandGen.Uniform(0, 2*3.1415);
      double oldPx = trackMom.GetX();
      double oldPy = trackMom.GetY();
      double newPx = oldPx + fermiMom*sin(theta)*sin(phi);
      double newPy = oldPy + fermiMom*sin(theta)*cos(phi);
      trackMom.Set(newPx, newPy, trackMom.GetZ());
    }

    utl::Vector stopMomentum;
    utl::Point stopPosition;
    
    utl::Point startPosition(startVertex.GetPosition().GetX(), startVertex.GetPosition().GetY(), startVertex.GetPosition().GetZ());
    
    bool trackSuccess = tracker.TrackToZ(psdPosition, vtxTrack.GetCharge(),
                                         startPosition, trackMom,
                                         stopPosition, stopMomentum);

    double hitX = stopPosition.GetX();
    double hitY = stopPosition.GetY();
    
    if (hitX < -40 + psdShift || hitX > 40 + psdShift || hitY < -60 - 1 || hitY > 40 - 1 || !trackSuccess)
      continue;
    
    //if (vtxTrack.GetCharge() == -1) neg->Fill(trackMom.GetMag(), pt);
    //if (vtxTrack.GetCharge() ==  0) neu->Fill(trackMom.GetMag(), pt);
    //if (vtxTrack.GetCharge() ==  1) pos->Fill(trackMom.GetMag(), pt);
    
    /*if (vtxTrack.GetType() == evt::sim::VertexTrackConst::eDetector && vtxTrack.GetParticleId() == 22){
      evt::sim::Vertex startVert = simEvent.Get(vtxTrack.GetStartVertexIndex());
      evt::sim::VertexTrack parTrack = simEvent.Get(startVert.GetFirstParentTrackIndex());
      startVert = simEvent.Get(parTrack.GetStartVertexIndex());
      parTrack = simEvent.Get(startVert.GetFirstParentTrackIndex());
      
      parEne->Fill(TString::Format("%d", parTrack.GetParticleId()), stopMomentum.GetMag());
    }*/
    
    double energy = sqrt(stopMomentum.GetMag2());
    //std::cout << energy << "\t";
    energy = fRandGen.Gaus(energy, (0.72/sqrt(energy) + 0.026)*energy);  //Values from T3 trigger study
    
    if (energy < 0) energy = 0;
    showerProfile.SetParameters(hitX, hitY, showerDecay, showerDecaySlow, fraction);
    
    for (int i = 1; i <= 44; ++i){
      double modSizeXlow  = -1 * detectorPSD.GetPositionX(i)/10 + psdShift - detectorPSD.GetWidth(i)/2;
      double modSizeXhigh = -1 * detectorPSD.GetPositionX(i)/10 + psdShift + detectorPSD.GetWidth(i)/2;
      double modSizeYlow  = detectorPSD.GetPositionY(i)/10 - 1  - detectorPSD.GetHeight(i)/2;
      double modSizeYhigh = detectorPSD.GetPositionY(i)/10 - 1  + detectorPSD.GetHeight(i)/2;
      
      double energyFraction = showerProfile.Integral(modSizeXlow, modSizeXhigh, modSizeYlow, modSizeYhigh)/energyNorm;
      //std::cout << energyFraction << "\t";
      moduleEnergy[i] += energy * energyFraction;
      //std::cout << moduleEnergy[i] << "\t";
    }
  }
  //std::cout << std::endl;
}
Пример #22
0
void Esh3DRenderer::render(const EshShape& in_shape, EshRendererContext& in_rendererContext,MfGdiBrush *in_brush)
{
    ChLOG_DEBUG_START_FN;
    if (!setUp(in_shape, in_rendererContext))
    {
        return;
    }

    // temporary pen & brush so I can see what I'm doing!
    //ChAutoPtr<MfGdiBrush> pBrush = m_driver.CreateSolidBrush(CsColour(0x88, 0x88, 0x88));
    //ChAutoPtr<MfGdiPen> pPen = m_driver.CreatePen(MfGdiPen::Style_Solid, 4, CsColour(0,0,0), ChVector<ChFLT8>());
    //ChAutoPtr<MfGdiBrush> pBrush = EshGdiObjectFactory::makeNullBrush(m_driver);
    ChAutoPtr<MfGdiPen> pPen(EshGdiObjectFactory::makeNullPen(m_driver)); // LINUX_PORT
    // TODO - pen must be null pen, but because faces aren't being shaded according to normal angle, an
    //        outline is being drawn to figure out where the faces are
    //in_rendererContext.getDeviceContextReference().SetBrush(*pBrush);
    //in_rendererContext.getDeviceContextReference().TakeBrush(pBrush.giveUpOwnership());
    in_rendererContext.getDeviceContextReference().TakePen(pPen.giveUpOwnership());

    if (in_rendererContext.hasTransformation())
    {
        // 2D rotation must be done before any 3D rotation/skew, so multiply on right of current
        // 3D world transform, which at this point will have the skew and rotation already
        m_worldTransform = m_worldTransform * CsMatrix3D<ChFLT8>(in_rendererContext.getTransformationMatrix());
    }

    m_pPathData = ChNEW EshPathRendererData(*m_pGeometry, in_rendererContext);
    m_pPathData->init();
    MfGdiDeviceContext& deviceContext = in_rendererContext.getDeviceContextReference();

    // use non-const verion of method to have geometry add implied segments
    const EshPathCommandTable& pathCommands = m_pPathData->getPathCommandsReference();
    if (pathCommands.size() == 0)
    {
        return;
    }

	bool skip				 = true;
    bool isFirstSegmentDrawn = false;

    CsPoint<ChFLT8> startPosition(0,0);
    CsPoint<ChFLT8> position(0,0);
    CsPoint<ChFLT8> nextPosition(0,0);

    const EshPathCommand* pCurrentPathCommand;
    const EshPathCommand* pNextPathCommand;

    ChUINT2 j = 0;

    /**
     * TODO - is it possible for the first path param to be an editing command?
     */
    pNextPathCommand = &pathCommands[0];
    EshPathCommandTypeEnums nextPathCommandType = pNextPathCommand->m_type;

    CsPlanarPolygon<ChFLT8> frontFace;
    CsPlanarPolygon<ChFLT8> extrusion;

    for (ChUINT4 i=1; i <= pathCommands.size(); i++)
    {
        pCurrentPathCommand = pNextPathCommand;

        // Skip editing commands
		skip = true;
        while ( skip && i < pathCommands.size())
        {
			skip = (ESH_PATH_CMD_HA <= pathCommands[i].m_type && pathCommands[i].m_type <= ESH_PATH_CMD_HI);
			if(skip)
			{
				++i;
			}
		}     
        
        if (i == pathCommands.size())
        {
            nextPathCommandType = ESH_PATH_CMD_E;
        }
        else
        {
            pNextPathCommand = &pathCommands[i];
            nextPathCommandType = pNextPathCommand->m_type;
        }

        bool isLastCommand = (nextPathCommandType == ESH_PATH_CMD_E);
        bool isEnd = isLastCommand;
        
        switch (pCurrentPathCommand->m_type)
        {
        case ESH_PATH_CMD_L:
            // Line to
//            openClosedPath(deviceContext);
            for (j=0; j < pCurrentPathCommand->m_unCount; j++)
            {
                isEnd = isLastCommand && (j == pCurrentPathCommand->m_unCount - 1);
                m_pPathData->getPoint(nextPosition);
                //m_pPathData->getPoint(nextPosition);
                if (!isFirstSegmentDrawn)
                {
                    startPosition = position;
                    frontFace.addPoint(m_worldTransform * ChPoint3DF8(position, m_lForeDepth));
                    isFirstSegmentDrawn = true;
                }

                if (m_isFilled)
                {
                    frontFace.addPoint(m_worldTransform * ChPoint3DF8(nextPosition, m_lForeDepth));
                }
                // TODO - linecap stuff

                makePolygon(position, nextPosition, extrusion);
                m_tree.insert(extrusion);
                position = nextPosition;
            }
            break;

        case ESH_PATH_CMD_C:
            // Cubic curve
//            openClosedPath(deviceContext);
            for (j=0; j < pCurrentPathCommand->m_unCount; j++)
            {
                ChPoint3DF8 p0(position.getX(), position.getY(), m_lForeDepth);
                ChPoint3DF8 p1(m_pPathData->getPointF8(), m_lForeDepth);  // 1st control point
                ChPoint3DF8 p2(m_pPathData->getPointF8(), m_lForeDepth);  // 2nd control point
                m_pPathData->getPoint(nextPosition);
                ChPoint3DF8 p3(nextPosition, m_lForeDepth);  // endpoint
                if (!isFirstSegmentDrawn)
                {
                    startPosition = position;
                    if (m_isFilled)
                    {
                        frontFace.addPoint(m_worldTransform * ChPoint3DF8(position, m_lForeDepth));
                    }
                    isFirstSegmentDrawn = true;
                }

                divideBezier(p0, p1, p2, p3, frontFace);
                position = nextPosition;
            }
            break;

        case ESH_PATH_CMD_M:
            // Move to - count is always 1
            ChASSERT(pCurrentPathCommand->m_unCount == 1);
            m_pPathData->getPoint(position);
            break;
        case ESH_PATH_CMD_X:
            // Close path
            nextPosition = startPosition;
            if (position != nextPosition)
            {
                makePolygon(position, nextPosition, extrusion);
                m_tree.insert(extrusion);
                position = nextPosition;
            }
            
           if (m_isFilled)
            {
                m_faces.push_back(frontFace);
                frontFace.clear();
            }
            isFirstSegmentDrawn = false;
            break;
        case ESH_PATH_CMD_E:
            // End path data attribute
            /* Freeform paths will not have a close path command, however, if
               the path is filled, we still need a polygon for that line segment. */
            if (m_isFilled && position != startPosition)
            {
                makePolygon(position, startPosition, extrusion);
                m_tree.insert(extrusion);
                position = startPosition;
                m_faces.push_back(frontFace);
                frontFace.clear();
            }
            break;
       
        case ESH_PATH_CMD_AE:
            // Angle ellipse to
            for (j=0; j < pCurrentPathCommand->m_unCount; j++)
            {
                isEnd = isLastCommand && (j == pCurrentPathCommand->m_unCount - 1);
                if (!isFirstSegmentDrawn)
                {
                    startPosition =  makeAngleEllipse(in_rendererContext, position, false, j, frontFace);
                    isFirstSegmentDrawn = true;
                }
                else
                {
                    makeAngleEllipse(in_rendererContext, position, false, j, frontFace);
                }
            }
            break;

        case ESH_PATH_CMD_AL:
            // Angle ellipse
            for (j=0; j < pCurrentPathCommand->m_unCount; j++)
            {
                isEnd = isLastCommand && (j == pCurrentPathCommand->m_unCount - 1);
                if (!isFirstSegmentDrawn)
                {
                    startPosition =  makeAngleEllipse(in_rendererContext, position, true, j, frontFace);
                    isFirstSegmentDrawn = true;
                }
                else
                {
                    makeAngleEllipse(in_rendererContext, position, true, j, frontFace);
                }
            }
            break;

        case ESH_PATH_CMD_AT:
            // Arc to
            for (j=0; j < pCurrentPathCommand->m_unCount; j++)
            {
                isEnd = isLastCommand && (j == pCurrentPathCommand->m_unCount - 1);
                if (!isFirstSegmentDrawn)
                {
                    startPosition = makeArc(position, false, j, false, frontFace);
                    isFirstSegmentDrawn = true;
                }
                else
                {
                    makeArc(position, false, j, false, frontFace);
                }

                
            }
            break;

        case ESH_PATH_CMD_AR:
            // Arc
            for (j=0; j < pCurrentPathCommand->m_unCount; j++)
            {
                isEnd = isLastCommand && (j == pCurrentPathCommand->m_unCount - 1);
                if (!isFirstSegmentDrawn)
                {
                    startPosition = makeArc(position, true, j, false, frontFace);
                    frontFace.addPoint(m_worldTransform * ChPoint3DF8(position, m_lForeDepth));
                    isFirstSegmentDrawn = true;
                }
                else
                {
                    makeArc(position, true, j, false, frontFace);
                }
            }
            break;

        case ESH_PATH_CMD_WA:
            // Clockwise arc to
            for (j=0; j < pCurrentPathCommand->m_unCount; j++)
            {
                isEnd = isLastCommand && (j == pCurrentPathCommand->m_unCount - 1);
                if (!isFirstSegmentDrawn)
                {
                    startPosition = makeArc(position, false, j, true, frontFace);
                    isFirstSegmentDrawn = true;
                }
                else
                {
                    makeArc(position, false, j, true, frontFace);
                }
            }
            break;

        case ESH_PATH_CMD_WR:
            // Clockwise arc
            for (j=0; j < pCurrentPathCommand->m_unCount; j++)
            {
                isEnd = isLastCommand && (j == pCurrentPathCommand->m_unCount - 1);
                if (!isFirstSegmentDrawn)
                {
                    startPosition = makeArc(position, true, j, true, frontFace);
                    frontFace.addPoint(m_worldTransform * ChPoint3DF8(position, m_lForeDepth));
                    isFirstSegmentDrawn = true;
                }
                else
                {
                    makeArc(position, true, j, true, frontFace);
                }               
            }
            break;

        case ESH_PATH_CMD_QX:
            // Elliptical quadrant x
            for (j=0; j < pCurrentPathCommand->m_unCount; j++)
            {
                if (!isFirstSegmentDrawn)
                {
                    startPosition = position;
                    isFirstSegmentDrawn = true;
                }
                isEnd = isLastCommand && (j == pCurrentPathCommand->m_unCount - 1);
                makeQuadrantArc(position, j % 2 == 0, frontFace);

            }
            break;

        case ESH_PATH_CMD_QY:
            // Elliptical quadrant y
            for (j=0; j < pCurrentPathCommand->m_unCount; j++)
            {
                if (!isFirstSegmentDrawn)
                {
                    startPosition = position;
                    frontFace.addPoint(m_worldTransform * ChPoint3DF8(position, m_lForeDepth));
                    isFirstSegmentDrawn = true;
                }
                isEnd = isLastCommand && (j == pCurrentPathCommand->m_unCount - 1);
                makeQuadrantArc(position, j % 2 == 1, frontFace);
            }
            break;
        }

    }

    // Draw the actual shape.
    m_tree.render(m_driver, in_rendererContext);
    if (m_isFilled)
    {
        ChBYTE opacity = 255;
        const EshFill &fill = in_shape.getFill();

        if (fill.isOpacitySet())
        {
            opacity = fill.getOpacity() >> 8;
        }

        renderPrimaryFaces(deviceContext,in_brush,opacity);
    }
Пример #23
0
qint64 BassPlayer::position() const {
    return BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetPosition(chan, BASS_POS_BYTE)) * BASS_POSITION_MULTIPLIER - startPosition();
}
Пример #24
0
bool BassPlayer::newPosProcessing(const qint64 & new_pos) {
    return BASS_ChannelSetPosition(chan, BASS_ChannelSeconds2Bytes(chan, (new_pos + startPosition()) / BASS_POSITION_MULTIPLIER), BASS_POS_BYTE);
}
Пример #25
0
void InsertTextCommand::input(const String& text, bool selectInsertedText, RebalanceType whitespaceRebalance)
{
    
    ASSERT(text.find('\n') == notFound);

    if (!endingSelection().isNonOrphanedCaretOrRange())
        return;

    // Delete the current selection.
    // FIXME: This delete operation blows away the typing style.
    if (endingSelection().isRange()) {
        if (performTrivialReplace(text, selectInsertedText))
            return;
        deleteSelection(false, true, true, false);
    }

    Position startPosition(endingSelection().start());
    
    Position placeholder;
    // We want to remove preserved newlines and brs that will collapse (and thus become unnecessary) when content 
    // is inserted just before them.
    // FIXME: We shouldn't really have to do this, but removing placeholders is a workaround for 9661.
    // If the caret is just before a placeholder, downstream will normalize the caret to it.
    Position downstream(startPosition.downstream());
    if (lineBreakExistsAtPosition(downstream)) {
        // FIXME: This doesn't handle placeholders at the end of anonymous blocks.
        VisiblePosition caret(startPosition);
        if (isEndOfBlock(caret) && isStartOfParagraph(caret))
            placeholder = downstream;
        // Don't remove the placeholder yet, otherwise the block we're inserting into would collapse before
        // we get a chance to insert into it.  We check for a placeholder now, though, because doing so requires
        // the creation of a VisiblePosition, and if we did that post-insertion it would force a layout.
    }
    
    // Insert the character at the leftmost candidate.
    startPosition = startPosition.upstream();
    
    // It is possible for the node that contains startPosition to contain only unrendered whitespace,
    // and so deleteInsignificantText could remove it.  Save the position before the node in case that happens.
    Position positionBeforeStartNode(positionInParentBeforeNode(startPosition.containerNode()));
    deleteInsignificantText(startPosition.upstream(), startPosition.downstream());
    if (!startPosition.anchorNode()->inDocument())
        startPosition = positionBeforeStartNode;
    if (!startPosition.isCandidate())
        startPosition = startPosition.downstream();
    
    startPosition = positionAvoidingSpecialElementBoundary(startPosition);
    
    Position endPosition;
    
    if (text == "\t") {
        endPosition = insertTab(startPosition);
        startPosition = endPosition.previous();
        if (placeholder.isNotNull())
            removePlaceholderAt(placeholder);
    } else {
        // Make sure the document is set up to receive text
        startPosition = positionInsideTextNode(startPosition);
        ASSERT(startPosition.anchorType() == Position::PositionIsOffsetInAnchor);
        ASSERT(startPosition.containerNode());
        ASSERT(startPosition.containerNode()->isTextNode());
        if (placeholder.isNotNull())
            removePlaceholderAt(placeholder);
        RefPtr<Text> textNode = static_cast<Text*>(startPosition.containerNode());
        const unsigned offset = startPosition.offsetInContainerNode();

        insertTextIntoNode(textNode, offset, text);
        endPosition = Position(textNode, offset + text.length());

        if (whitespaceRebalance == RebalanceLeadingAndTrailingWhitespaces) {
            // The insertion may require adjusting adjacent whitespace, if it is present.
            rebalanceWhitespaceAt(endPosition);
            // Rebalancing on both sides isn't necessary if we've inserted only spaces.
            if (!shouldRebalanceLeadingWhitespaceFor(text))
                rebalanceWhitespaceAt(startPosition);
        } else {
            ASSERT(whitespaceRebalance == RebalanceAllWhitespaces);
            if (canRebalance(startPosition) && canRebalance(endPosition))
                rebalanceWhitespaceOnTextSubstring(textNode, startPosition.offsetInContainerNode(), endPosition.offsetInContainerNode());
        }
    }

    // We could have inserted a part of composed character sequence,
    // so we are basically treating ending selection as a range to avoid validation.
    // <http://bugs.webkit.org/show_bug.cgi?id=15781>
    VisibleSelection forcedEndingSelection;
    forcedEndingSelection.setWithoutValidation(startPosition, endPosition);
    setEndingSelection(forcedEndingSelection);

    // Handle the case where there is a typing style.
    if (RefPtr<EditingStyle> typingStyle = document()->frame()->selection()->typingStyle()) {
        typingStyle->prepareToApplyAt(endPosition, EditingStyle::PreserveWritingDirection);
        if (!typingStyle->isEmpty())
            applyStyle(typingStyle.get());
    }

    if (!selectInsertedText)
        setEndingSelection(VisibleSelection(endingSelection().end(), endingSelection().affinity()));
}
Пример #26
-1
void InsertTextCommand::doApply()
{
    ASSERT(m_text.find('\n') == kNotFound);

    if (!endingSelection().isNonOrphanedCaretOrRange())
        return;

    // Delete the current selection.
    // FIXME: This delete operation blows away the typing style.
    if (endingSelection().isRange()) {
        if (performTrivialReplace(m_text, m_selectInsertedText))
            return;
        bool endOfSelectionWasAtStartOfBlock = isStartOfBlock(endingSelection().visibleEnd());
        deleteSelection(false, true, false, false);
        // deleteSelection eventually makes a new endingSelection out of a Position. If that Position doesn't have
        // a renderer (e.g. it is on a <frameset> in the DOM), the VisibleSelection cannot be canonicalized to
        // anything other than NoSelection. The rest of this function requires a real endingSelection, so bail out.
        if (endingSelection().isNone())
            return;
        if (endOfSelectionWasAtStartOfBlock) {
            if (EditingStyle* typingStyle = document().frame()->selection().typingStyle())
                typingStyle->removeBlockProperties();
        }
    } else if (document().frame()->editor().isOverwriteModeEnabled()) {
        if (performOverwrite(m_text, m_selectInsertedText))
            return;
    }

    Position startPosition(endingSelection().start());

    Position placeholder;
    // We want to remove preserved newlines and brs that will collapse (and thus become unnecessary) when content
    // is inserted just before them.
    // FIXME: We shouldn't really have to do this, but removing placeholders is a workaround for 9661.
    // If the caret is just before a placeholder, downstream will normalize the caret to it.
    Position downstream(startPosition.downstream());
    if (lineBreakExistsAtPosition(downstream)) {
        // FIXME: This doesn't handle placeholders at the end of anonymous blocks.
        VisiblePosition caret(startPosition);
        if (isEndOfBlock(caret) && isStartOfParagraph(caret))
            placeholder = downstream;
        // Don't remove the placeholder yet, otherwise the block we're inserting into would collapse before
        // we get a chance to insert into it.  We check for a placeholder now, though, because doing so requires
        // the creation of a VisiblePosition, and if we did that post-insertion it would force a layout.
    }

    // Insert the character at the leftmost candidate.
    startPosition = startPosition.upstream();

    // It is possible for the node that contains startPosition to contain only unrendered whitespace,
    // and so deleteInsignificantText could remove it.  Save the position before the node in case that happens.
    ASSERT(startPosition.containerNode());
    Position positionBeforeStartNode(positionInParentBeforeNode(*startPosition.containerNode()));
    deleteInsignificantText(startPosition, startPosition.downstream());
    if (!startPosition.inDocument())
        startPosition = positionBeforeStartNode;
    if (!startPosition.isCandidate())
        startPosition = startPosition.downstream();

    startPosition = positionAvoidingSpecialElementBoundary(startPosition);

    Position endPosition;

    if (m_text == "\t") {
        endPosition = insertTab(startPosition);
        startPosition = endPosition.previous();
        if (placeholder.isNotNull())
            removePlaceholderAt(placeholder);
    } else {
        // Make sure the document is set up to receive m_text
        startPosition = positionInsideTextNode(startPosition);
        ASSERT(startPosition.anchorType() == Position::PositionIsOffsetInAnchor);
        ASSERT(startPosition.containerNode());
        ASSERT(startPosition.containerNode()->isTextNode());
        if (placeholder.isNotNull())
            removePlaceholderAt(placeholder);
        RefPtrWillBeRawPtr<Text> textNode = startPosition.containerText();
        const unsigned offset = startPosition.offsetInContainerNode();

        insertTextIntoNode(textNode, offset, m_text);
        endPosition = Position(textNode, offset + m_text.length());

        if (m_rebalanceType == RebalanceLeadingAndTrailingWhitespaces) {
            // The insertion may require adjusting adjacent whitespace, if it is present.
            rebalanceWhitespaceAt(endPosition);
            // Rebalancing on both sides isn't necessary if we've inserted only spaces.
            if (!shouldRebalanceLeadingWhitespaceFor(m_text))
                rebalanceWhitespaceAt(startPosition);
        } else {
            ASSERT(m_rebalanceType == RebalanceAllWhitespaces);
            if (canRebalance(startPosition) && canRebalance(endPosition))
                rebalanceWhitespaceOnTextSubstring(textNode, startPosition.offsetInContainerNode(), endPosition.offsetInContainerNode());
        }
    }

    setEndingSelectionWithoutValidation(startPosition, endPosition);

    // Handle the case where there is a typing style.
    if (RefPtrWillBeRawPtr<EditingStyle> typingStyle = document().frame()->selection().typingStyle()) {
        typingStyle->prepareToApplyAt(endPosition, EditingStyle::PreserveWritingDirection);
        if (!typingStyle->isEmpty())
            applyStyle(typingStyle.get());
    }

    if (!m_selectInsertedText)
        setEndingSelection(VisibleSelection(endingSelection().end(), endingSelection().affinity(), endingSelection().isDirectional()));
}