void StatesEditorView::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
    if (removedNode.hasParentProperty()) {
        const NodeAbstractProperty propertyParent = removedNode.parentProperty();
        if (propertyParent.parentModelNode().isRootNode() && propertyParent.name() == "states") {
            m_lastIndex = propertyParent.indexOf(removedNode);
        }
    }
    if (removedNode == currentState())
        setCurrentState(baseState());
}
Beispiel #2
0
devs::Time Mealy::init(devs::Time /* time */)
{
    if (not isInit()) {
        throw utils::InternalError(
            "FSA::Mealy model, initial state not defined");
    }

    currentState(initialState());
    mPhase = IDLE;
    return 0;
}
// ---------------------------------------------------------------------------
// From MFSMForBody.
// ---------------------------------------------------------------------------
//
MFSMState* CCompositeCableStatusFSM::CurrentState()
    {
    FUNC_LOG;
    MFSMState* currentState( NULL );
    if (    ( 0 <= iCurrentStateId ) && 
            ( ECompositeCableStateMaxValue > iCurrentStateId ))
        {
        currentState = iStateArray[iCurrentStateId];
        }
    return currentState;
    }
void XtgScanner::xtgParse()
{
	/* Enter the default mode as textMode */
	enterState(textMode);
	writer->setCharStyle("");
	writer->setStyle("");
	currentCharStyle = writer->getCurrentCharStyle();
	currentParagraphStyle = writer->getCurrentStyle();
	while (input_Buffer.at(top) != '\0')
	{
		token = getToken();
		QHash<QString,void (XtgScanner::*)(void)> *temp = NULL;
		if (Mode == tagMode)
			temp = &tagModeHash;
		if (Mode == nameMode)
			temp = &nameModeHash;
		if (Mode == textMode)
			temp = &textModeHash;
		if (temp->contains(token) )
		{
			funPointer = temp->value(token);
			(this->*funPointer)();
		}

		/**
				Various character Style Applications <@stylesheetname>. We cannot hash this since stylesheetname
				is not constant
				*/

		else if ( (currentState() == tagMode ) && token.startsWith('@') && token.endsWith('>') )
		{
			/*here we receive a token @stylesheetname>, hence we have to slice of token to 
				get the name of character stylesheet to be applied
			*/
			define = 0;
			sfcName = token.remove(0,1);
			sfcName = sfcName.remove(sfcName.size()-1,1);
			flushText();
			if (styleStatus(definedCStyles,sfcName))
				writer->setCharStyle(sfcName);
			else
			{
				showWarning(sfcName);
				writer->setCharStyle("");
			}
			currentCharStyle = writer->getCurrentCharStyle();
		}
		if (top == input_Buffer.length())
			break;
	}
	writer->appendText(textToAppend);
	qDebug()<<"Unsupported : "<<unSupported;
}
Beispiel #5
0
void Keyboard::Init(HWND hWnd, IDirectInput8* directInput)
{
	Device::Init(hWnd, directInput);

	handleCreateDeviceReturnCode(directInput->CreateDevice(GUID_SysKeyboard, &m_pDevice, NULL));

	assert(SUCCEEDED(m_pDevice->SetDataFormat(&c_dfDIKeyboard)));
	assert(SUCCEEDED(m_pDevice->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)));

	//if this fails, it will be acquired in the keyboard update function
	HRESULT hr = m_pDevice->Acquire();
	assert(DIERR_INVALIDPARAM != hr);
	assert(DIERR_NOTINITIALIZED != hr);
	if(SUCCEEDED(hr))
		m_pDevice->GetDeviceState(N_KEYS*sizeof(unsigned char), (void*) currentState());
	else
		memset(currentState(),0,N_KEYS);

	flipBuffers();
	initialized_=true;
}
// ---------------------------------------------------------------------------
// From MFSMForBody.
// ---------------------------------------------------------------------------
//
TFSMState CCompositeCableStatusFSM::CurrentStateID()
    {
    FUNC_LOG;
    TFSMState currentState( ECompositeCableStateUndefined );
    if ( ( 0 <= iCurrentStateId ) && 
            ( ECompositeCableStateMaxValue > iCurrentStateId ))
        {
        currentState = iCurrentStateId;
        }
    INFO_1( "iCurrentStateId: %i", iCurrentStateId );
    return currentState;
    }
QmlItemNode QmlModelView::createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, const QPointF &position, QmlItemNode parentNode)
{
    if (!parentNode.isValid())
        parentNode = rootQmlItemNode();

    Q_ASSERT(parentNode.isValid());


    QmlItemNode newNode;
    RewriterTransaction transaction = beginRewriterTransaction();
    {
        QList<QPair<QString, QVariant> > propertyPairList;
        propertyPairList.append(qMakePair(QString("x"), QVariant(round(position.x(), 4))));
        propertyPairList.append(qMakePair(QString("y"), QVariant(round(position.y(), 4))));

        foreach (const PropertyContainer &property, itemLibraryEntry.properties())
            propertyPairList.append(qMakePair(property.name(), property.value()));

        newNode = createQmlItemNode(itemLibraryEntry.typeName(), itemLibraryEntry.majorVersion(), itemLibraryEntry.minorVersion(), propertyPairList);
        parentNode.nodeAbstractProperty("data").reparentHere(newNode);

        Q_ASSERT(newNode.isValid());

        QString id;
        int i = 1;
        QString name(itemLibraryEntry.name().toLower());
        //remove forbidden characters
        name.replace(QRegExp(QLatin1String("[^a-zA-Z0-9_]")), QLatin1String("_"));
        do {
            id = name + QString::number(i);
            i++;
        } while (hasId(id)); //If the name already exists count upwards

        try {
            newNode.setId(id);
        } catch (InvalidIdException &e) {
            // should never happen
            QMessageBox::warning(0, tr("Invalid Id"), e.description());
        }

        if (!currentState().isBaseState()) {
            newNode.modelNode().variantProperty("opacity") = 0;
            newNode.setVariantProperty("opacity", 1);
        }

        Q_ASSERT(newNode.isValid());
    }

    Q_ASSERT(newNode.isValid());

    return newNode;
}
Beispiel #8
0
void Mealy::output(devs::Time time,
		   devs::ExternalEventList& output) const
{
    if (mPhase == PROCESSING) {
        const devs::ExternalEventList& events = *mToProcessEvents.front();
        const devs::ExternalEvent& event = events.front();
        OutputFuncsIterator itof = mOutputFuncs.find(currentState());

        if (itof != mOutputFuncs.end()  and
            itof->second.find(event.getPortName()) != itof->second.end()) {
            (itof->second.find(event.getPortName())->second)(time, output);
        } else {
            OutputsIterator ito = mOutputs.find(currentState());

            if (ito != mOutputs.end() and
                ito->second.find(event.getPortName()) != ito->second.end()) {
                output.emplace_back(
                    ito->second.find(event.getPortName())->second);
            }
        }
    }
}
Beispiel #9
0
void
RiscOperators::startInstruction(SgAsmInstruction *insn) {
    ASSERT_not_null(partitioner_);
    Super::startInstruction(insn);
    if (mlog[DEBUG]) {
        SymbolicSemantics::Formatter fmt = symbolicFormat("      ");
        mlog[DEBUG] <<"  +-------------------------------------------------\n"
                    <<"  | " <<unparseInstructionWithAddress(insn) <<"\n"
                    <<"  +-------------------------------------------------\n"
                    <<"    state before instruction:\n"
                    <<(*currentState() + fmt);
    }
}
QmlItemNode QmlModelView::createQmlItemNodeFromImage(const QString &imageName, const QPointF &position, QmlItemNode parentNode)
{
    if (!parentNode.isValid())
        parentNode = rootQmlItemNode();

    if (!parentNode.isValid())
        return QmlItemNode();

    QmlItemNode newNode;
    RewriterTransaction transaction = beginRewriterTransaction();
    {
        QList<QPair<QString, QVariant> > propertyPairList;
        propertyPairList.append(qMakePair(QString("x"), QVariant( round(position.x(), 4))));
        propertyPairList.append(qMakePair(QString("y"), QVariant( round(position.y(), 4))));

        QString relativeImageName = imageName;

        //use relative path
        if (QFileInfo(model()->fileUrl().toLocalFile()).exists()) {
            QDir fileDir(QFileInfo(model()->fileUrl().toLocalFile()).absolutePath());
            relativeImageName = fileDir.relativeFilePath(imageName);
        }

        propertyPairList.append(qMakePair(QString("source"), QVariant(relativeImageName)));
        newNode = createQmlItemNode("Qt/Image",4, 7, propertyPairList);
        parentNode.nodeAbstractProperty("data").reparentHere(newNode);

        Q_ASSERT(newNode.isValid());

        QString id;
        int i = 1;
        QString name("image");
        name.remove(QLatin1Char(' '));
        do {
            id = name + QString::number(i);
            i++;
        } while (hasId(id)); //If the name already exists count upwards

        newNode.setId(id);
        if (!currentState().isBaseState()) {
            newNode.modelNode().variantProperty("opacity") = 0;
            newNode.setVariantProperty("opacity", 1);
        }

        Q_ASSERT(newNode.isValid());
    }

    Q_ASSERT(newNode.isValid());

    return newNode;
}
Beispiel #11
0
std::string
RiscOperators::commentForVariable(RegisterDescriptor reg, const std::string &accessMode) const {
    const RegisterDictionary *regs = currentState()->registerState()->get_register_dictionary();
    std::string varComment = RegisterNames(regs)(reg) + " first " + accessMode;
    if (pathInsnIndex_ == (size_t)(-1) && currentInstruction() == NULL) {
        varComment += " by initialization";
    } else {
        if (pathInsnIndex_ != (size_t)(-1))
            varComment += " at path position #" + StringUtility::numberToString(pathInsnIndex_);
        if (SgAsmInstruction *insn = currentInstruction())
            varComment += " by " + unparseInstructionWithAddress(insn);
    }
    return varComment;
}
Beispiel #12
0
// ---------------------------------------------------------------------------
// From MFSMBody.
// ---------------------------------------------------------------------------
//
MFSMState* CPDEngine::CurrentState( TFSMId aFSMId )
    {
    FUNC_LOG;
    MFSMState* currentState( NULL );
    if ( (  0 <= aFSMId ) && 
            ( EPDEFSMIdFirstUnused > aFSMId ))
        {
        if (iFSMPtr[ aFSMId ])
            {
            currentState = iFSMPtr[ aFSMId ]->CurrentState();
            }
        }
    return currentState;
    }
Beispiel #13
0
GTEST_TEST(DownhillSimplex, bench2)
{
  std::array<Rangef, 2> ranges;
  ranges[0] = Rangef(-50.f, 50);
  ranges[1] = Rangef(-50.f, 50);

  auto errorFunction = []
                       (const Vector2f& vals)
  {
    LIP currentState(250.f);
    LIP targetState(250.f);
    float timeToStep = 0.3f;
    float timeAfterStep = 0.3f;
    float footTrans = -50.f;
    float posWeight = 1;
    float velWeight = 50;

    const float currentZmp = vals(0);
    const float nextZmp = vals(1);

    LIP forwardedState = currentState.predict(timeToStep, currentZmp);
    forwardedState.position += footTrans;
    forwardedState.update(timeAfterStep, nextZmp);

    return posWeight * sqr(targetState.position - forwardedState.position) +
           velWeight * sqr(targetState.velocity - forwardedState.velocity);
  };
  auto optimizer = Optimizer::makeDownhillSimplexOptimizer(errorFunction, ranges);

  Eigen::BenchTimer optTimer;

  for(int i = 0; i < TRIES; ++i)
  {
    optimizer.initRandom(Vector2f(-1.f, 0.f));
    auto copy = optimizer.simplex;
    // waste some cycles to get the return type automatically
    auto res = optimizer.optimize(0.0001f, 1);
    optTimer.start();
    for(int j = 0; j < RUNS; ++j)
    {
      optimizer.simplex = copy;
      res = optimizer.optimize(0.0001f, 100);
    }
    optTimer.stop();
  }

  PRINTF("overall - best: %.3fs, avg: %.3fs, worst: %.3fs \n", optTimer.best(), optTimer.total() / TRIES, optTimer.worst());
  PRINTF("per run - best: %.6fs, avg: %.6fs, worst: %.6fs \n", optTimer.best() / RUNS, optTimer.total() / (TRIES * RUNS), optTimer.worst() / RUNS);
}
Beispiel #14
0
    void KukieControlQueue::jointPtpInternal(arma::vec joints) {

        ptpReached = false;

        komoMutex.lock();
        if(!plannerInitialized) {

            planner = KUKADU_SHARED_PTR<PathPlanner>(new KomoPlanner(shared_from_this(),
                                                                     resolvePath("$KUKADU_HOME/external/komo/share/data/kuka/data/iis_robot.kvg"),
                                                                     resolvePath("$KUKADU_HOME/external/komo/share/data/kuka/config/MT.cfg"),
                                                                     getRobotSidePrefix(), acceptCollisions));
            plannerInitialized = true;

        }

        bool performPtp = false;
        vec currentState = getCurrentJoints().joints;
        for(int i = 0; i < joints.n_elem; ++i)
            if(abs(currentState(i) - joints(i)) > 0.01) {
                performPtp = true;
                break;
            }


        vector<vec> desiredJointPlan;
        if(performPtp) {

            vector<arma::vec> desiredPlan;
            desiredPlan.push_back(getCurrentJoints().joints);
            desiredPlan.push_back(joints);
            desiredJointPlan = planner->planJointTrajectory(desiredPlan);

        }
        komoMutex.unlock();

        if(performPtp) {
            if(desiredJointPlan.size() > 0) {

                for(int i = 0; i < desiredJointPlan.size(); ++i)
                    addJointsPosToQueue(desiredJointPlan.at(i));

                synchronizeToControlQueue(1);

            } else {
                ROS_ERROR("(KukieControlQueue) Joint plan not reachable");
            }
        }

    }
void StatesEditorView::synchonizeCurrentStateFromWidget()
{
    if (!model())
        return;
    int internalId = m_statesEditorWidget->currentStateInternalId();

    if (internalId > 0 && hasModelNodeForInternalId(internalId)) {
        ModelNode node = modelNodeForInternalId(internalId);
        QmlModelState modelState(node);
        if (modelState.isValid() && modelState != currentState())
            setCurrentState(modelState);
    } else {
        setCurrentState(baseState());
    }
}
Beispiel #16
0
/** Write value to memory.
 *
 *  If multi-path is enabled, then return a new memory expression that updates memory with a new address/value pair;
 *  otherwise update the memory directly.  In any case, record some information about the address that was written if we've
 *  never seen it before. */
void
RiscOperators::writeMemory(RegisterDescriptor segreg, const BaseSemantics::SValuePtr &addr,
                           const BaseSemantics::SValuePtr &value, const BaseSemantics::SValuePtr &cond) {
    if (cond->is_number() && !cond->get_number())
        return;
    Super::writeMemory(segreg, addr, value, cond);

    // Save a description of the variable
    SymbolicExpr::Ptr valExpr = SValue::promote(value)->get_expression();
    if (valExpr->isLeafNode() && valExpr->isLeafNode()->isVariable()) {
        std::string comment = commentForVariable(addr, "write");
        State::promote(currentState())->varComment(valExpr->isLeafNode()->toString(), comment);
    }

    // Save a description for its addresses
    size_t nBytes = value->get_width() / 8;
    for (size_t i=0; i<nBytes; ++i) {
        SValuePtr va = SValue::promote(add(addr, number_(addr->get_width(), i)));
        if (va->get_expression()->isLeafNode()) {
            std::string comment = commentForVariable(addr, "read", i, nBytes);
            State::promote(currentState())->varComment(va->get_expression()->isLeafNode()->toString(), comment);
        }
    }
}
void HCJointOffsetOptimization::optimize(
		KinematicCalibrationState& optimizedState) {
	boost::shared_ptr<LocOptKinCalState> currentState(
			new LocOptKinCalState(context, initialState, measurements,
					kinematicChains, frameImageConverter));
	boost::shared_ptr<LocOptKinCalState> bestNeighbor(
			new LocOptKinCalState(context, initialState, measurements,
					kinematicChains, frameImageConverter));
	//double bestError = INFINITY;
	bool canImprove = true;
	int numOfIterations = 0;
	double step = 0.1;

	while (canImprove) {

		if (numOfIterations++ % 100 == 0 || true) {
			std::cout << "iteration: " << numOfIterations << " error: "
					<< currentState->getError() << std::endl;

		}

		vector<boost::shared_ptr<LocOptKinCalState> > neighbors =
				currentState->getNeighborStates(step);
		boost::shared_ptr<LocOptKinCalState> bestNeighbor = currentState;

		// find the best neighbor
		for (int i = 0; i < neighbors.size(); i++) {
			//cout << "neighbour " << i << " has error " << neighbors[i]->getError() << endl;
			boost::shared_ptr<LocOptKinCalState> currentNeighbor = neighbors[i];
			if (currentNeighbor->getError() < bestNeighbor->getError()) {
				bestNeighbor = currentNeighbor;
			}
		}

		// check whether the current best neighbor improves
		if (bestNeighbor->getError() < currentState->getError()) {
			currentState = bestNeighbor;
			step = 0.1;
		} else {
			step = step / 10;
			if(step < 1e-6)
				canImprove = false;
		}
	}

	optimizedState = currentState->getResult();
}
void StatesEditorView::renameState(int internalNodeId, const QString &newName)
{
    if (hasModelNodeForInternalId(internalNodeId)) {
        QmlModelState state(modelNodeForInternalId(internalNodeId));
        try {
            if (state.isValid() && state.name() != newName) {
                // Jump to base state for the change
                QmlModelState oldState = currentState();
                setCurrentState(baseState());
                state.setName(newName);
                setCurrentState(oldState);
            }
        }  catch (const RewritingException &e) {
            e.showException();
        }
    }
}
void StatesEditorView::renameState(int nodeId, const QString &newName)
{
    if (hasModelNodeForInternalId(nodeId)) {
        QmlModelState state(modelNodeForInternalId(nodeId));
        try {
            if (state.isValid() && state.name() != newName) {
                // Jump to base state for the change
                QmlModelState oldState = currentState();
                setCurrentState(baseState());
                state.setName(newName);
                setCurrentState(oldState);
            }
        }  catch (RewritingException &e) {
            QMessageBox::warning(0, "Error", e.description());
        }
    }
}
Beispiel #20
0
void CreationTool::on_released(QPointF scene, Scenario::Point sp)
{
    if(auto cs = currentState())
    {
        mapWithCollision(scene,
        [&] (const Id<StateModel>& id)
        { localSM().postEvent(new ReleaseOnState_Event{id, sp}); },
        [&] (const Id<EventModel>& id)
        { localSM().postEvent(new ReleaseOnEvent_Event{id, sp}); },
        [&] (const Id<TimeNodeModel>& id)
        { localSM().postEvent(new ReleaseOnTimeNode_Event{id, sp}); },
        [&] ()
        { localSM().postEvent(new ReleaseOnNothing_Event{sp}); },
        cs->createdStates,
        cs->createdEvents,
        cs->createdTimeNodes);
    }
}
Beispiel #21
0
void CSysController::onUpdateProcessfinished(int exitCode)
{
    Q_UNUSED(exitCode);

    if (currentState() != eUPDATING)
        return;
    mCurrentUpdate++;
    if (mCurrentUpdate == mvUpdatesToApply.size())
    {
        if (misRebootRequired)
        {
            system("touch /tmp/.fbsdup-reboot");
        }
        check();
    }
    else
    {
        launchUpdate();
    }
}
bool CPLJSonStreamingParser::CheckAndEmitTrueFalseOrNull(char ch)
{
    State eCurState = currentState();

    if( eCurState == STATE_TRUE )
    {
        if( m_osToken == "true" )
        {
            Boolean(true);
        }
        else
        {
            return EmitUnexpectedChar(ch);
        }
    }
    else if( eCurState == STATE_FALSE)
    {
        if( m_osToken == "false" )
        {
            Boolean(false);
        }
        else
        {
            return EmitUnexpectedChar(ch);
        }
    }
    else /* if( eCurState == STATE_NULL ) */
    {
        if( m_osToken == "null" )
        {
            Null();
        }
        else
        {
            return EmitUnexpectedChar(ch);
        }
    }
    m_aState.pop_back();
    m_osToken.clear();
    return true;
}
Beispiel #23
0
devs::Time Moore::init(devs::Time time)
{
    if (not isInit()) {
        throw utils::InternalError(
            "FSA::Moore model, initial state not defined");
    }

    currentState(initialState());

    ActionsIterator it = mActions.find(initialState());

    if (it != mActions.end()) {
        devs::ExternalEvent* event = new devs::ExternalEvent("");

        (it->second)(time, event);
        delete event;
    }

    mPhase = IDLE;
    return 0;
}
Beispiel #24
0
QString ScriptObject::executeProcess(bool blocking)
{
  int index = ( states().findIndex( currentState()) );
  if (index == -1)
  {
    printError(i18n("Invalid state for associated text."));
    return QString();
  }
  QString evalText = m_associatedText[index];

  if ((KommanderWidget::useInternalParser && !evalText.startsWith("#!")) || evalText.startsWith("#!kommander"))
  {
    evalAssociatedText(evalText);
    return global(widgetName() + "_RESULT");
  } else
  {
    MyProcess process(this);
    process.setBlocking(blocking);
    return process.run(evalAssociatedText(evalText));
  }
}
void StatesEditorView::duplicateCurrentState()
{
    QmlModelState state = currentState();

    Q_ASSERT(!state.isBaseState());

    QString newName = state.name();

    // Strip out numbers at the end of the string
    QRegExp regEx(QString("[0-9]+$"));
    int numberIndex = newName.indexOf(regEx);
    if ((numberIndex != -1) && (numberIndex+regEx.matchedLength()==newName.length()))
        newName = newName.left(numberIndex);

    int i = 1;
    QStringList stateNames = rootStateGroup().names();
    while (stateNames.contains(newName + QString::number(i)))
        i++;

    QmlModelState newState = state.duplicate(newName + QString::number(i));
    setCurrentState(newState);
}
Beispiel #26
0
void Moore::process(const devs::Time& time,
                       const devs::ExternalEvent* event)
{
    if (mTransitions.find(currentState()) !=
        mTransitions.end() and
        (mTransitions[currentState()].find(event->
                                                    getPortName())
         != mTransitions[currentState()].end())) {
        currentState(mTransitions[currentState()]
                              [event->getPortName()]);

        ActionsIterator it = mActions.find(currentState());

        if (it != mActions.end()) {
            (it->second)(time, event);
        }
    }
}
Beispiel #27
0
void Mealy::process(const devs::Time& time,
		    const devs::ExternalEvent* event)
{
    if (mTransitions.find(currentState()) !=
        mTransitions.end() and
        (mTransitions[currentState()].find(event->
                                                    getPortName())
         != mTransitions[currentState()].end())) {
        ActionsIterator ita = mActions.find(currentState());

        if (ita != mActions.end() and
            ita->second.find(event->getPortName()) != ita->second.end()) {

            (ita->second.find(event->getPortName())->second)(time, event);
        }

        currentState(mTransitions[currentState()]
                              [event->getPortName()]);
    }
}
QmlItemNode QmlModelView::createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, const QPointF &position, QmlItemNode parentNode)
{
    if (!parentNode.isValid())
        parentNode = rootQmlItemNode();

    Q_ASSERT(parentNode.isValid());

    QmlItemNode newNode;

    try {
        RewriterTransaction transaction = beginRewriterTransaction();
        if (itemLibraryEntry.typeName().contains('.')) {

            const QString newImportUrl = itemLibraryEntry.requiredImport();

            if (!itemLibraryEntry.requiredImport().isEmpty()) {
                const QString newImportVersion = QString("%1.%2").arg(QString::number(itemLibraryEntry.majorVersion()), QString::number(itemLibraryEntry.minorVersion()));
                Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);

                foreach (const Import &import, model()->imports()) {
                    if (import.isLibraryImport()
                            && import.url() == newImport.url()
                            && import.version() == newImport.version()) {
                        // reuse this import
                        newImport = import;
                        break;
                    }
                }

                if (!model()->hasImport(newImport, true, true)) {
                    model()->changeImports(QList<Import>() << newImport, QList<Import>());
                }
            }
        }

        QList<QPair<QString, QVariant> > propertyPairList;
        propertyPairList.append(qMakePair(QString("x"), QVariant(round(position.x(), 4))));
        propertyPairList.append(qMakePair(QString("y"), QVariant(round(position.y(), 4))));

        if (itemLibraryEntry.qml().isEmpty()) {
            foreach (const PropertyContainer &property, itemLibraryEntry.properties())
                propertyPairList.append(qMakePair(property.name(), property.value()));

            newNode = createQmlItemNode(itemLibraryEntry.typeName(), itemLibraryEntry.majorVersion(), itemLibraryEntry.minorVersion(), propertyPairList);
        } else {
            QScopedPointer<Model> inputModel(Model::create("QtQuick.Rectangle", 1, 0, model()));
            inputModel->setFileUrl(model()->fileUrl());
            QPlainTextEdit textEdit;


            textEdit.setPlainText(Utils::FileReader::fetchQrc(itemLibraryEntry.qml()));
            NotIndentingTextEditModifier modifier(&textEdit);

            QScopedPointer<RewriterView> rewriterView(new RewriterView(RewriterView::Amend, 0));
            rewriterView->setCheckSemanticErrors(false);
            rewriterView->setTextModifier(&modifier);
            inputModel->attachView(rewriterView.data());

            if (rewriterView->errors().isEmpty() && rewriterView->rootModelNode().isValid()) {
                ModelNode rootModelNode = rewriterView->rootModelNode();
                inputModel->detachView(rewriterView.data());

                rootModelNode.variantProperty("x") = propertyPairList.first().second;
                rootModelNode.variantProperty("y") = propertyPairList.at(1).second;

                ModelMerger merger(this);
                newNode = merger.insertModel(rootModelNode);               
            }
        }

        if (parentNode.hasDefaultProperty()) {
            parentNode.nodeAbstractProperty(parentNode.defaultProperty()).reparentHere(newNode);
        }

        if (!newNode.isValid())
            return newNode;

        QString id;
        int i = 1;
        QString name(itemLibraryEntry.name().toLower());
        //remove forbidden characters
        name.replace(QRegExp(QLatin1String("[^a-zA-Z0-9_]")), QLatin1String("_"));
        do {
            id = name + QString::number(i);
            i++;
        } while (hasId(id)); //If the name already exists count upwards

        newNode.setId(id);

        if (!currentState().isBaseState()) {
            newNode.modelNode().variantProperty("opacity") = 0;
            newNode.setVariantProperty("opacity", 1);
        }

        Q_ASSERT(newNode.isValid());
    }
QmlItemNode QmlModelView::createQmlItemNodeFromImage(const QString &imageName, const QPointF &position, QmlItemNode parentNode)
{
    if (!parentNode.isValid())
        parentNode = rootQmlItemNode();

    if (!parentNode.isValid())
        return QmlItemNode();

    QmlItemNode newNode;
    RewriterTransaction transaction = beginRewriterTransaction();
    {
        const QString newImportUrl = QLatin1String("QtQuick");
        const QString newImportVersion = QLatin1String("1.0");
        Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);

        foreach (const Import &import, model()->imports()) {
            if (import.isLibraryImport()
                && import.url() == newImport.url()
                && import.version() == newImport.version()) {
                // reuse this import
                newImport = import;
                break;
            }
        }

        if (!model()->imports().contains(newImport)) {
            model()->changeImports(QList<Import>() << newImport, QList<Import>());
        }

        QList<QPair<QString, QVariant> > propertyPairList;
        propertyPairList.append(qMakePair(QString("x"), QVariant( round(position.x(), 4))));
        propertyPairList.append(qMakePair(QString("y"), QVariant( round(position.y(), 4))));

        QString relativeImageName = imageName;

        //use relative path
        if (QFileInfo(model()->fileUrl().toLocalFile()).exists()) {
            QDir fileDir(QFileInfo(model()->fileUrl().toLocalFile()).absolutePath());
            relativeImageName = fileDir.relativeFilePath(imageName);
        }

        propertyPairList.append(qMakePair(QString("source"), QVariant(relativeImageName)));
        newNode = createQmlItemNode("QtQuick.Image", 1, 0, propertyPairList);
        parentNode.nodeAbstractProperty("data").reparentHere(newNode);

        Q_ASSERT(newNode.isValid());

        QString id;
        int i = 1;
        QString name("image");
        name.remove(QLatin1Char(' '));
        do {
            id = name + QString::number(i);
            i++;
        } while (hasId(id)); //If the name already exists count upwards

        newNode.setId(id);
        if (!currentState().isBaseState()) {
            newNode.modelNode().variantProperty("opacity") = 0;
            newNode.setVariantProperty("opacity", 1);
        }

        Q_ASSERT(newNode.isValid());
    }

    Q_ASSERT(newNode.isValid());

    return newNode;
}
void Layer::lockPageFlip(bool& recomputeVisibleRegions)
{
    ClientRef::Access sharedClient(mUserClientRef);
    SharedBufferServer* lcblk(sharedClient.get());
    if (!lcblk) {
        // client died
        recomputeVisibleRegions = true;
        return;
    }

    ssize_t buf = lcblk->retireAndLock();
    if (buf == NOT_ENOUGH_DATA) {
        // NOTE: This is not an error, it simply means there is nothing to
        // retire. The buffer is locked because we will use it
        // for composition later in the loop
        return;
    }

    if (buf < NO_ERROR) {
        LOGE("retireAndLock() buffer index (%d) out of range", int(buf));
        mPostedDirtyRegion.clear();
        return;
    }

    // we retired a buffer, which becomes the new front buffer
    if (mBufferManager.setActiveBufferIndex(buf) < NO_ERROR) {
        LOGE("retireAndLock() buffer index (%d) out of range", int(buf));
        mPostedDirtyRegion.clear();
        return;
    }

    sp<GraphicBuffer> newFrontBuffer(getBuffer(buf));
    if (newFrontBuffer != NULL) {
        // get the dirty region
        // compute the posted region
        const Region dirty(lcblk->getDirtyRegion(buf));
        mPostedDirtyRegion = dirty.intersect( newFrontBuffer->getBounds() );

        // update the layer size and release freeze-lock
        const Layer::State& front(drawingState());
        if (newFrontBuffer->getWidth()  == front.requested_w &&
            newFrontBuffer->getHeight() == front.requested_h)
        {
            if ((front.w != front.requested_w) ||
                (front.h != front.requested_h))
            {
                // Here we pretend the transaction happened by updating the
                // current and drawing states. Drawing state is only accessed
                // in this thread, no need to have it locked
                Layer::State& editDraw(mDrawingState);
                editDraw.w = editDraw.requested_w;
                editDraw.h = editDraw.requested_h;

                // We also need to update the current state so that we don't
                // end-up doing too much work during the next transaction.
                // NOTE: We actually don't need hold the transaction lock here
                // because State::w and State::h are only accessed from
                // this thread
                Layer::State& editTemp(currentState());
                editTemp.w = editDraw.w;
                editTemp.h = editDraw.h;

                // recompute visible region
                recomputeVisibleRegions = true;
            }

            // we now have the correct size, unfreeze the screen
            mFreezeLock.clear();
        }

        // get the crop region
        setBufferCrop( lcblk->getCrop(buf) );

        // get the transformation
        setBufferTransform( lcblk->getTransform(buf) );

    } else {
        // this should not happen unless we ran out of memory while
        // allocating the buffer. we're hoping that things will get back
        // to normal the next time the app tries to draw into this buffer.
        // meanwhile, pretend the screen didn't update.
        mPostedDirtyRegion.clear();
    }

    if (lcblk->getQueuedCount()) {
        // signal an event if we have more buffers waiting
        mFlinger->signalEvent();
    }

    /* a buffer was posted, so we need to call reloadTexture(), which
     * will update our internal data structures (eg: EGLImageKHR or
     * texture names). we need to do this even if mPostedDirtyRegion is
     * empty -- it's orthogonal to the fact that a new buffer was posted,
     * for instance, a degenerate case could be that the user did an empty
     * update but repainted the buffer with appropriate content (after a
     * resize for instance).
     */
    reloadTexture( mPostedDirtyRegion );
}