void PropertyEditor::Private::setTargetState(const QString &label)
{
    Transition* transition = current<Transition>();
    Q_ASSERT(transition);
    if (transition) {
        State *targetState = ElementUtil::findState(transition->sourceState()->machine(), label);
        if (transition->targetState() != targetState) {
            ModifyTransitionCommand *command = new ModifyTransitionCommand(transition);
            command->setTargetState(targetState);
            m_commandController->undoStack()->push(command);
        }
    }
}
Ejemplo n.º 2
0
	Transition* TransitionBase::getTransitionLocally(string transitionId) {
		vector<Transition*>::iterator i;
		Transition* transition;

		i = transitionSet->begin();
		while (i != transitionSet->end()) {
			transition = *i;
			if (transition->getId() == transitionId) {
				return transition;
			}
			++i;
		}
		return NULL;
	}
Ejemplo n.º 3
0
void Thread::run_one_step()
{
	process_messages();
	Net *net = process->get_net();
	if (net == NULL) {
		return;
	}
	Transition *tr = net->pick_active_transition();
	if (tr == NULL) {
		return;
	}
	tr->set_active(false);
	tr->full_fire(this, net);
}
Ejemplo n.º 4
0
void Simulation::PrintStatistics()
{
    Log->Write("\nRooms Egress Time:");
    Log->Write("==================");
    Log->Write("id\tcaption\tegress time (s)");

    for (const auto& it:_building->GetAllRooms()) {
        auto&& room = it.second;
        if (room->GetCaption()!="outside")
            Log->Write("%d\t%s\t%.2f", room->GetID(), room->GetCaption().c_str(), room->GetEgressTime());
    }

    Log->Write("\nUsage of Exits");
    Log->Write("==========");
    for (const auto& itr : _building->GetAllTransitions()) {
        Transition* goal = itr.second;
        if (goal->GetDoorUsage()) {
            Log->Write(
                    "\nExit ID [%d] used by [%d] pedestrians. Last passing time [%0.2f] s",
                    goal->GetID(), goal->GetDoorUsage(),
                    goal->GetLastPassingTime());

            string statsfile = _config->GetTrajectoriesFile()+"_flow_exit_id_"+to_string(goal->GetID())+".dat";
            Log->Write("More Information in the file: %s", statsfile.c_str());
            auto output = new FileHandler(statsfile.c_str());
            output->Write("#Flow at exit "+goal->GetCaption()+"( ID "+to_string(goal->GetID())+" )");
            output->Write("#Time (s)  cummulative number of agents \n");
            output->Write(goal->GetFlowCurve());
        }
    }
    Log->Write("\n");
}
Ejemplo n.º 5
0
// Consider merging this funciton with nullInputTransit()
int Fsm::transit(MessageTuple* inMsg, vector<MessageTuple*>& outMsgs, bool& high_prob, int startIdx )
{
    State* cs = _states[_current];
    outMsgs.clear();

    // Go through the possible transitions, find that matches the message
    for( int tid = startIdx ; tid < cs->getNumTrans(); ++tid ) {
        Transition tr = cs->getTrans((int)tid);

        if( tr.getFromMachineId() == inMsg->subjectId() && tr.getInputMessageId() == inMsg->destMsgId() ) {
            // Matching found. Get all the outLabels
            for( size_t oid = 0 ; oid < tr.getNumOutLabels() ; ++oid ) {
                OutLabel lbl = tr.getOutLabel(oid);
                MessageTuple* out = new FsmMessage(tr.getFromMachineId(), lbl.first,
                                tr.getInputMessageId(), lbl.second, _macLookup->toInt(this->_name)) ;
                outMsgs.push_back(out);
            }

            // Change state
            State* next = cs->getNextState((int)tid);
            _current = next->getID();
            
            if( tr.isHigh() )
                high_prob = true;
            else
                high_prob = false;
            
            return tid+1;
        }
    }

    // The function will get to this line when no more matching transition is found
    return -1;
}
Ejemplo n.º 6
0
//Transit from current state
int StateMachine::loop() {
    int current_state = this->current_state();
    for(int i=0; i < stored_transitions; i++) {
		Transition transition = this->transitions[i];
		if(transition.origin == current_state && transition.transition_function()) {
			this->set_current_state(transition.dest);
            current_state = transition.dest;
			return transition.dest;
		}
	}
    if (state_functions[current_state] != 0) {
		state_functions[current_state]();
	}
	return current_state;
}
Ejemplo n.º 7
0
returnValue ShootingMethod::addTransition( const Transition& transition_ ){

    if( transition_.getNXA() != 0 ) return ACADOERROR( RET_TRANSITION_DEPENDS_ON_ALGEBRAIC_STATES );
    integrator[N-1]->setTransition( transition_ );

    return SUCCESSFUL_RETURN;
}
Ejemplo n.º 8
0
void State::add_epsilon(State* dest)
{
        for (size_t i = 0; i < this->transitions.size(); i++) {
                if (this->transitions[i]->get_dest() == dest) {
                        return;
                }
        }

        Transition* t = new Transition(this->location, '\0', this, dest);
        t->set_epsilon(true);

        transitions.push_back(t);
        dest->add_incoming(t);

        return;
}
Ejemplo n.º 9
0
void XMLizer::writeClip( QDomDocument &document, QDomNode &parent, Clip *clip )
{
	QDomElement n1 = document.createElement( "Clip" );
	parent.appendChild( n1 );

	if ( clip->getSpeed() != 1.0 )
		n1.setAttribute( "speed", QString::number( clip->getSpeed(), 'e', 17 ) );
	XMLizer::createText( document, n1, "Name", clip->sourcePath() );
	XMLizer::createDouble( document, n1, "PosInTrack", clip->position() );
	XMLizer::createDouble( document, n1, "StartTime", clip->start() );
	XMLizer::createDouble( document, n1, "Length", clip->length() );
	
	for ( int i = 0; i < clip->videoFilters.count(); ++i )
		XMLizer::writeFilter( document, n1, false, clip->videoFilters.at( i ) );
	
	for ( int i = 0; i < clip->audioFilters.count(); ++i )
		XMLizer::writeFilter( document, n1, true, clip->audioFilters.at( i ) );
	
	Transition *trans = clip->getTransition();
	if ( trans ) {
		QDomElement t = document.createElement( "Transition" );
		n1.appendChild( t );
		
		XMLizer::createDouble( document, t, "PosInTrack", trans->position() );
		XMLizer::createDouble( document, t, "Length", trans->length() );
		if ( !trans->getVideoFilter().isNull() )
			XMLizer::writeFilter( document, t, false, trans->getVideoFilter() );
		if ( !trans->getAudioFilter().isNull() )
			XMLizer::writeFilter( document, t, true, trans->getAudioFilter() );
	}
}
bool SimulatedState::transitionIsCompatible(const Transition& transition) const
{
	if (_currentState != transition.sourceStateIndex()) {
		return false;
	}

	if (tapes.size() != transition.numberOfTapes()) {
		return false;
	}

	for (int i = 0; i < transition.numberOfTapes(); ++i) {
		if (!transition.isCurrentTapeSymbolForTape(i, characterAtTapehead(i)) && (!_tm->anySymbolSymbolSet() || transition.currentTapeSymbolForTape(i) != _tm->anySymbolSymbol())) {
			return false;
		}
	}

	return true;
}
Ejemplo n.º 11
0
/**
 * @brief Starts a transition effect on this object.
 *
 * The transition will be automatically deleted when finished or stopped.
 * Any previous transition is stopped.
 *
 * @param transition The transition to start.
 * @param callback_ref A Lua registry ref to the function to call when
 * the transition finishes, or LUA_REFNIL.
 * @param lua_context The Lua world for the callback (or NULL).
 */
void Drawable::start_transition(Transition& transition,
    int callback_ref, LuaContext* lua_context) {

  stop_transition();

  this->transition = &transition;
  this->transition_callback_ref = callback_ref;
  this->lua_context = lua_context;
  transition.start();
}
Ejemplo n.º 12
0
void StateMachineViewerWidgetNG::transitionAdded(const TransitionId transitionId, const StateId sourceId, const StateId targetId, const QString& label)
{
  if (m_idToTransitionMap.contains(transitionId))
    return;

  IF_DEBUG(qDebug() << "transitionAdded" << transitionId << label << sourceId << targetId);

  State* source = m_idToStateMap.value(sourceId);
  State* target = m_idToStateMap.value(targetId);
  if (!source || !target) {
    qDebug() << "Null source or target for transition:" <<  transitionId;
    return;
  }

  Transition* transition = new Transition(source);
  transition->setTargetState(target);
  transition->setLabel(label);
  m_idToTransitionMap[transitionId] = transition;
}
Ejemplo n.º 13
0
void State::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent) {
    if(mouseEvent->button() == Qt::LeftButton && dynamic_cast<GraphGraphicsScene* >(this->scene())->mode() == MODE::DELETE) {
        for(Transition *t : m_transitions) {
            t->removeSelf();

        }
        updateStateId(this->m_id);
        delete this;
    }
    else if(mouseEvent->button() == Qt::LeftButton && dynamic_cast<GraphGraphicsScene* >(this->scene())->mode() == MODE::TRANSITION) {
        Transition *transition = new Transition();
        transition->setFrom(this);
        transition->setTo(this);
        transition->setDrawMode(DRAW_SHAPE::NORMAL);
        transition->setFlag(true);
        this->scene()->addItem(transition);
        this->addTransiton(transition);
        instructionLab->addToInstructionlab(transition);
    }
}
  //
  // Notification
  //
  void Script::State::Notify(U32 message, U32 data)
  {
    // Ask the action to translate this notification
    if (action)
    {
      U32 translation = action->Notify(message, data);

      // Was the notification ignored ?
      if (translation != Status::Ignored)
      {
        // Find the transition
        Transition *transition = transitions.Find(translation);

        if (transition)
        {
          // Perform the transition
          transition->Perform(GetScript());
        }
      }
    }
  }
/* Name: view
* Purpose: Prints out all of the transitions.
* Operation: This method is used to print out the value of the transition. 
	This is used by class Show_Command though the class Turing_Machine.
*/
void Transition_Function::view() const{

		// Display a empty set if it is empty.
	if (transitions.size() == 0){
		cout << "Delta = {}\n\n";
		return;
	}

	for (unsigned int i = 0; i < transitions.size(); i++){

		Transition Temp = transitions[i];
	
		cout << "Delta("
			<< Temp.Source_State()
			<< ", "
			<< Temp.Read_Character()
			<< ") = ("
			<< Temp.Destination_State()
			<< ", "
			<< Temp.Write_Character()
			<< ", "
			<< Temp.Move_Direction()
			<< ")\n";
	}

	cout << "\n";
}
Ejemplo n.º 16
0
void Place::produceTokens(unsigned int nbOfTokens, unsigned int colorLabel, int tokensTime)
{
	unsigned int oldNumberOfTokens = getNbOfTokens(colorLabel);

	for (unsigned int i = 0; i < nbOfTokens; ++i) {
        Token token(tokensTime);
		m_tokenByColor[colorLabel - 1].push_back(token);
	}

//    if(tokensTime < 0){tokensTime = 0;} // CB incompatible with deactivation (tokenTime = -1)

	if ((oldNumberOfTokens < NB_OF_TOKEN_TO_ACTIVE_ARC) && (getNbOfTokens(colorLabel) >= NB_OF_TOKEN_TO_ACTIVE_ARC)) { // CB WTF : Si un token et deux arcs sortant, bug ?
		arcList outGoingArcs = outGoingArcsOf(colorLabel);
		for (unsigned int i = 0 ; i < outGoingArcs.size() ; ++i) {
			PetriNetArc* arc = outGoingArcs[i];
            
//            if (!arc->getCondition()) { // CB check if the arc can be activated
//                continue;
//            }

            Transition* transitionTo = dynamic_cast<Transition*>(arc->getTo());
            
			if (!transitionTo) {
				throw IncoherentStateException();
			}

			transitionTo->setArcAsActive(arc, tokensTime, true);

			if (transitionTo->isStatic()) {
				if(arc->getRelativeMinValue().getValue() < (int) tokensTime) {
					getPetriNet()->pushTransitionToCrossWhenAcceleration(transitionTo);
				}
			} else {
				if(arc->getRelativeMaxValue().getValue() < (int) tokensTime) {
					getPetriNet()->pushTransitionToCrossWhenAcceleration(transitionTo);
				}
			}
		}
	}
}
Ejemplo n.º 17
0
void Simulation::UpdateFlowAtDoors(const Pedestrian& ped) const
{
    if (_config->ShowStatistics()) {
        Transition* trans = _building->GetTransitionByUID(ped.GetExitIndex());
        if (trans) {
            //check if the pedestrian left the door correctly
            if (trans->DistTo(ped.GetPos())>0.5) {
                Log->Write("WARNING:\t pedestrian [%d] left room/subroom [%d/%d] in an unusual way. Please check",
                        ped.GetID(), ped.GetRoomID(), ped.GetSubRoomID());
                Log->Write("       :\t distance to last door (%d | %d) is %f. That should be smaller.",
                        trans->GetUniqueID(), ped.GetExitIndex(),
                        trans->DistTo(ped.GetPos()));
                Log->Write("       :\t correcting the door statistics");
                //ped.Dump(ped.GetID());

                //checking the history and picking the nearest previous destination
                double biggest = 0.3;
                bool success = false;
                for (const auto& dest:ped.GetLastDestinations()) {
                    if (dest!=-1) {
                        Transition* trans_tmp = _building->GetTransitionByUID(dest);
                        if (trans_tmp && trans_tmp->DistTo(ped.GetPos())<biggest) {
                            biggest = trans_tmp->DistTo(ped.GetPos());
                            trans = trans_tmp;
                            Log->Write("       :\t Best match found at door %d", dest);
                            success = true;//at least one door was found
                        }
                    }
                }

                if (!success) {
                    Log->Write("WARNING       :\t correcting the door statistics");
                    return; //todo we need to check if the ped is in a subroom neighboring the target. If so, no problems!
                }
            }
//#pragma omp critical
            trans->IncreaseDoorUsage(1, ped.GetGlobalTime());
        }
    }
}
Ejemplo n.º 18
0
bool Automaton::step()
{
	//cout << this->name << " state: " << this->cur->id << " ";
	for (int i=0; i < cur->transitions.size(); i++) {
		Transition * t = cur->transitions[i];
		if (t->guard() && t->next->inv()) { // если выполнено условие
			if (t->needSync() ) {// если есть действия по синхронизации
				bool sync = t->synchronize();
				//cout << " channel " << t->channelParticipant->channel->id	<< " ";
				if (sync) {
					t->action(); //выполняем действия перехода
					cerr << "time = " << net->timeForInternalUse << " " << name << ": " << cur->name << " -> " << t->next->name << endl;
					cur = t->next; //изменяем текущее состояние
					//cout << this->cur->id << "\n";
					return true; //был совершен переход
				}
			}
			else { // синхронизации нет, условие выполнено
				t->action(); //выполняем действия перехода
				cerr << "time = " << net->timeForInternalUse << " " << name << ": " << cur->name << " -> " << t->next->name << endl;
				cur = t->next; //изменяем текущее состояние
				//cout << this->cur->id << "\n";
				return true; //был совершен переход
			}
		}
	}
	//cout << "no trans\n";
	return false; //перехода не было
}
Ejemplo n.º 19
0
void Place::produceTokens(unsigned int nbOfTokens, unsigned int colorLabel, unsigned int tokensTime) {
	unsigned int oldNumberOfTokens = getNbOfTokens(colorLabel);

	for (unsigned int i = 0; i < nbOfTokens; ++i) {
		Token token;
		token.setRemainingTime(tokensTime);
		m_tokenByColor[colorLabel - 1].push_back(token);
	}

	if ((oldNumberOfTokens < NB_OF_TOKEN_TO_ACTIVE_ARC) && (getNbOfTokens(colorLabel) >= NB_OF_TOKEN_TO_ACTIVE_ARC)) {
		arcList outGoingArcs = outGoingArcsOf(colorLabel);
		for (unsigned int i = 0 ; i < outGoingArcs.size() ; ++i) {
			Arc* arc = outGoingArcs[i];

			if (!(dynamic_cast<Transition*>(arc->getTo()))) {
				throw IncoherentStateException();
			}

			Transition* transitionTo = ((Transition*) arc->getTo());

			transitionTo->setArcAsActive(arc, tokensTime, true);

			if (transitionTo->isStatic()) {
				if(arc->getRelativeMinValue().getValue() < (int) tokensTime) {
					getPetriNet()->pushTransitionToCrossWhenAcceleration(transitionTo);
				}
			} else {
				if(arc->getRelativeMaxValue().getValue() < (int) tokensTime) {
					getPetriNet()->pushTransitionToCrossWhenAcceleration(transitionTo);
				}
			}

		}
	}



}
Ejemplo n.º 20
0
void Simulation::oneStep() {
    //Search for possible transitions by source state
    vector<Transition*> filteredTransitions;
	//std::cout << curState << " ==> ";
    auto ret = transitions.equal_range(curState);
    for (auto it=ret.first;it!=ret.second;++it) {
        filteredTransitions.push_back((*it).second);
    }
    if (filteredTransitions.empty()) {
		curState = "reject";
		return;
    }
    
    //Search for possible transitions by read character
    vector<Transition*> possibleTransitions;
	char readValue = tape->getChar();
    for (Transition* tr : filteredTransitions ) {
        if (tr->getRead() == readValue) {
            possibleTransitions.push_back(tr);
        }
    }
    if (possibleTransitions.empty()) {
		curState = "reject";
		return;
    }
    
    // transition
	assert(possibleTransitions.size() == 1); // cannot copy with multi transitions
	Transition* select = possibleTransitions[0];
	char wt = select->getWrite();
	char mv = select->getMove();
	std::string nextState = select->getNextState();
	tape->setChar(wt);
	tape->move(mv);
	curState = nextState;

	//std::cout << nextState << std::endl;
}
Ejemplo n.º 21
0
void State::add_transition(char name, State* dest)
{
        if (dest == NULL) {
                return;
        }

        size_t i = 0;
        Transition* t = NULL;

        for (; i < this->transitions.size(); i++) {
                t = this->transitions[i];
                if (t->get_token() == name && t->get_dest() == dest) {
                        return;
                }
        }

        Transition* transition = new Transition(this->location, name, this,
                        dest);

        this->transitions.push_back(transition);
        dest->add_incoming(transition);

        return;
}
Ejemplo n.º 22
0
void
ResultBecomesNegative::logNegativeResult (const Transition& tr,
                          const SBase& object)
{
  msg =
    "The Transition with id '";
  msg += tr.getId();
  msg += "' includes a resultLevel";
  msg += " that may cause the QualitativeSpecies '";
  msg += object.getId();
  msg += "' to become negative.";
  
  logFailure(object);

}
void
ResultExceedsMaximum::logExceedsMaximum (const Transition& tr,
                          const SBase& object)
{
  msg =
    "The <transition> with id '";
  msg += tr.getId();
  msg += "' includes a resultLevel";
  msg += " that may cause the <qualitativeSpecies> '";
  msg += object.getId();
  msg += "' to exceed its maximumLevel.";
  
  logFailure(object);

}
Ejemplo n.º 24
0
void
QSAssignedOnce::logMultipleAssignment (const Transition& tr,
                          const SBase& object,
                          std::string name)
{
  msg =
    "The Transition with id '";
  msg += tr.getId();
  msg += "' includes an Output";
  msg += " that uses an assignment to the QualitativeSpecies '";
  msg += name;
  msg += "' that has already been assigned.";
  
  logFailure(object);

}
Ejemplo n.º 25
0
Place* PNP::addAction(string name, Node *p0) {
    Transition *ts = addTransition(name+".start");
    Place *pe = addPlace(name+".exec");
    Transition *te = addTransition(name+".end");
    Place *pf = addPlace("X",-1);
    ts->setY(p0->getY()); pe->setY(p0->getY()); // same line as p0
    te->setY(p0->getY()); pf->setY(p0->getY());
    ts->setX(p0->getX()+1);  pe->setX(p0->getX()+2); // X pos after p0
    te->setX(p0->getX()+3);  pf->setX(p0->getX()+4);
    connect(p0,ts); connect(ts,pe); connect(pe,te); connect(te,pf);
    nactions++;
    return pf;
}
Ejemplo n.º 26
0
void *Transition::process(void *ptr) {

	Transition* transition = (Transition*) ptr;

	do { 

	Token* current = transition->getToken();

	if (current != NULL) {

#ifdef P_EVENT
		transition->dispatchPStartEvent();
#endif

		//Process token
		//1.BIN Routing


		//2.Dynamic Fuzzy Routing
		double result = FuzzyLogicDSL::Evaluate(1, 1, 1, 1, 0.3, 0, 1);
		cout << result << endl;

		transition->forwardToken(current);

	} else {

		pthread_mutex_t* mutex = transition->getMutex();//TODO remove from transition
		pthread_cond_t* cond_var = transition->getCondVar();

		pthread_mutex_lock(mutex);
		pthread_cond_wait(cond_var, mutex);
		pthread_mutex_unlock(mutex);

	}

	} while (!transition->isStopped());

	pthread_exit(0);

	return 0;

}
Ejemplo n.º 27
0
void
ModuleInstance::add_transition(const Transition& transition)
{
#ifndef NDEBUG
	if (0 <= globalIndex_ || 0 <= firstClock_)
		throw_FigException("this module has already been added to the network");
	if (!is_our_clock(transition.triggeringClock))
		throw_FigException(std::string("triggering clock \"")
						   .append(transition.triggeringClock)
						   .append("\" does not reside in module \"")
						   .append(name).append("\""));
	for (const auto& clockName: transition.resetClocksList())
		if (!is_our_clock(clockName))
			throw_FigException(std::string("reset clock \"").append(clockName)
							   .append("\" does not reside in module \"")
							   .append(name).append("\""));
#else
	if (0 <= globalIndex_ || 0 <= firstClock_)
		return;
#endif
	transitions_.emplace_back(transition);
}
Ejemplo n.º 28
0
vector<Place*> PNP::addSensingAction(string name, Place* p0, vector<string> outcomes) {
    vector<Place *> v;

    Transition *ts = addTransition(name+".start");  
    Place *pe = addPlace(name+".exec"); 
    ts->setY(p0->getY()); pe->setY(p0->getY());  // same line as p0
    ts->setX(p0->getX()+1);  pe->setX(p0->getX()+2); // X pos after p0
    connect(p0,ts); connect(ts,pe);

    int k=0;
    for (vector<string>::iterator it = outcomes.begin(); it!=outcomes.end(); it++, k++) {
        Transition *te = addTransition("["+(*it)+"] "+name+".end"); 
        Place *pf = addPlace("X",-1);  
        te->setY(p0->getY()+k); pf->setY(p0->getY()+k);
        te->setX(p0->getX()+3);  pf->setX(p0->getX()+4);
        connect(pe,te); connect(te,pf);
        v.push_back(pf);
    }

    nactions++;
    return v;
}
Ejemplo n.º 29
0
void ManhattanStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option,
                                   QPainter *painter, const QWidget *widget) const {
    if (!panelWidget(widget))
        return d->style->drawPrimitive(element, option, painter, widget);

    bool animating = (option->state & State_Animating);
    int state = option->state;
    QRect rect = option->rect;
    QRect oldRect;
    QRect newRect;
    if (widget && (element == PE_PanelButtonTool) && !animating) {
        QWidget *w = const_cast<QWidget *> (widget);
        int oldState = w->property("_q_stylestate").toInt();
        oldRect = w->property("_q_stylerect").toRect();
        newRect = w->rect();
        w->setProperty("_q_stylestate", (int)option->state);
        w->setProperty("_q_stylerect", w->rect());

        // Determine the animated transition
        bool doTransition = ((state & State_On)         != (oldState & State_On)     ||
                             (state & State_MouseOver)  != (oldState & State_MouseOver));
        if (oldRect != newRect) {
            doTransition = false;
            d->animator.stopAnimation(widget);
        }

        if (doTransition) {
            QImage startImage(option->rect.size(), QImage::Format_ARGB32_Premultiplied);
            QImage endImage(option->rect.size(), QImage::Format_ARGB32_Premultiplied);
            Animation *anim = d->animator.widgetAnimation(widget);
            QStyleOption opt = *option;
            opt.state = (QStyle::State)oldState;
            opt.state |= (State)State_Animating;
            startImage.fill(0);
            Transition *t = new Transition;
            t->setWidget(w);
            QPainter startPainter(&startImage);
            if (!anim) {
                drawPrimitive(element, &opt, &startPainter, widget);
            } else {
                anim->paint(&startPainter, &opt);
                d->animator.stopAnimation(widget);
            }
            QStyleOption endOpt = *option;
            endOpt.state |= (State)State_Animating;
            t->setStartImage(startImage);
            d->animator.startAnimation(t);
            endImage.fill(0);
            QPainter endPainter(&endImage);
            drawPrimitive(element, &endOpt, &endPainter, widget);
            t->setEndImage(endImage);
            t->setDuration(130);
            t->setStartTime(QTime::currentTime());
        }
    }

    switch (element) {
    case PE_PanelLineEdit: {
        painter->save();
        if (option->state & State_Enabled)
            drawCornerImage(d->lineeditImage, painter, option->rect, 2, 2, 2, 2);
        else
            drawCornerImage(d->lineeditImage_disabled, painter, option->rect, 2, 2, 2, 2);

        if (option->state & State_HasFocus || option->state & State_MouseOver) {
            QColor hover = StyleHelper::baseColor();
            if (state & State_HasFocus)
                hover.setAlpha(100);
            else
                hover.setAlpha(50);

            painter->setPen(QPen(hover, 1));
            painter->drawRect(option->rect.adjusted(1, 1, -2 ,-2));
        }
        painter->restore();
    }
    break;

    case PE_FrameStatusBarItem:
        break;

    case PE_PanelButtonTool: {
        Animation *anim = d->animator.widgetAnimation(widget);
        if (!animating && anim) {
            anim->paint(painter, option);
        } else {
            bool pressed = option->state & State_Sunken || option->state & State_On;
            QColor shadow(0, 0, 0, 30);
            painter->setPen(shadow);
            if (pressed) {
                QColor shade(0, 0, 0, 40);
                painter->fillRect(rect, shade);
                painter->drawLine(rect.topLeft() + QPoint(1, 0), rect.topRight() - QPoint(1, 0));
                painter->drawLine(rect.topLeft(), rect.bottomLeft());
                painter->drawLine(rect.topRight(), rect.bottomRight());
                // painter->drawLine(rect.bottomLeft()  + QPoint(1, 0), rect.bottomRight()  - QPoint(1, 0));
                QColor highlight(255, 255, 255, 30);
                painter->setPen(highlight);
            } else if (option->state & State_Enabled &&
                       option->state & State_MouseOver) {
                QColor lighter(255, 255, 255, 37);
                painter->fillRect(rect, lighter);
            }
        }
    }
    break;

    case PE_PanelStatusBar: {
        painter->save();
        QLinearGradient grad(option->rect.topLeft(), QPoint(rect.center().x(), rect.bottom()));
        QColor startColor = StyleHelper::shadowColor().darker(164);
        QColor endColor = StyleHelper::baseColor().darker(130);
        grad.setColorAt(0, endColor);
        grad.setColorAt(1, endColor);
        painter->fillRect(option->rect, grad);
        painter->setPen(QColor(255, 255, 255, 60));
        painter->drawLine(rect.topLeft() + QPoint(0,1),
                          rect.topRight()+ QPoint(0,1));
        painter->setPen(StyleHelper::borderColor().darker(110));
        painter->drawLine(rect.topLeft(), rect.topRight());
        painter->restore();
    }
    break;

    case PE_IndicatorToolBarSeparator: {
        QColor separatorColor = StyleHelper::borderColor();
        separatorColor.setAlpha(100);
        painter->setPen(separatorColor);
        const int margin = 3;
        if (option->state & State_Horizontal) {
            const int offset = rect.width()/2;
            painter->drawLine(rect.bottomLeft().x() + offset,
                              rect.bottomLeft().y() - margin,
                              rect.topLeft().x() + offset,
                              rect.topLeft().y() + margin);
        } else { //Draw vertical separator
            const int offset = rect.height()/2;
            painter->setPen(QPen(option->palette.background().color().darker(110)));
            painter->drawLine(rect.topLeft().x() + margin ,
                              rect.topLeft().y() + offset,
                              rect.topRight().x() - margin,
                              rect.topRight().y() + offset);
        }
    }
    break;

    case PE_IndicatorToolBarHandle: {
        bool horizontal = option->state & State_Horizontal;
        painter->save();
        QPainterPath path;
        int x = option->rect.x() + horizontal ? 2 : 6;
        int y = option->rect.y() + horizontal ? 6 : 2;
        static const int RectHeight = 2;
        if (horizontal) {
            while (y < option->rect.height() - RectHeight - 6) {
                path.moveTo(x, y);
                path.addRect(x, y, RectHeight, RectHeight);
                y += 6;
            }
        } else {
            while (x < option->rect.width() - RectHeight - 6) {
                path.moveTo(x, y);
                path.addRect(x, y, RectHeight, RectHeight);
                x += 6;
            }
        }

        painter->setPen(Qt::NoPen);
        QColor dark = StyleHelper::borderColor();
        dark.setAlphaF(0.4);

        QColor light = StyleHelper::baseColor();
        light.setAlphaF(0.4);

        painter->fillPath(path, light);
        painter->save();
        painter->translate(1, 1);
        painter->fillPath(path, dark);
        painter->restore();
        painter->translate(3, 3);
        painter->fillPath(path, light);
        painter->translate(1, 1);
        painter->fillPath(path, dark);
        painter->restore();
    }
    break;
    case PE_IndicatorArrowUp:
    case PE_IndicatorArrowDown:
    case PE_IndicatorArrowRight:
    case PE_IndicatorArrowLeft: {
        // From windowsstyle but modified to enable AA
        if (option->rect.width() <= 1 || option->rect.height() <= 1)
            break;

        QRect r = option->rect;
        int size = qMin(r.height(), r.width());
        QPixmap pixmap;
        QString pixmapName;
        pixmapName.sprintf("%s-%s-%d-%d-%d-%lld",
                           "$qt_ia", metaObject()->className(),
                           uint(option->state), element,
                           size, option->palette.cacheKey());
        if (!QPixmapCache::find(pixmapName, pixmap)) {
            int border = size/5;
            int sqsize = 2*(size/2);
            QImage image(sqsize, sqsize, QImage::Format_ARGB32);
            image.fill(Qt::transparent);
            QPainter imagePainter(&image);
            imagePainter.setRenderHint(QPainter::Antialiasing, true);
            imagePainter.translate(0.5, 0.5);
            QPolygon a;
            switch (element) {
            case PE_IndicatorArrowUp:
                a.setPoints(3, border, sqsize/2,  sqsize/2, border,  sqsize - border, sqsize/2);
                break;
            case PE_IndicatorArrowDown:
                a.setPoints(3, border, sqsize/2,  sqsize/2, sqsize - border,  sqsize - border, sqsize/2);
                break;
            case PE_IndicatorArrowRight:
                a.setPoints(3, sqsize - border, sqsize/2,  sqsize/2, border,  sqsize/2, sqsize - border);
                break;
            case PE_IndicatorArrowLeft:
                a.setPoints(3, border, sqsize/2,  sqsize/2, border,  sqsize/2, sqsize - border);
                break;
            default:
                break;
            }

            int bsx = 0;
            int bsy = 0;

            if (option->state & State_Sunken) {
                bsx = pixelMetric(PM_ButtonShiftHorizontal);
                bsy = pixelMetric(PM_ButtonShiftVertical);
            }

            QRect bounds = a.boundingRect();
            int sx = sqsize / 2 - bounds.center().x() - 1;
            int sy = sqsize / 2 - bounds.center().y() - 1;
            imagePainter.translate(sx + bsx, sy + bsy);

            if (!(option->state & State_Enabled)) {
                QColor foreGround(150, 150, 150, 150);
                imagePainter.setBrush(option->palette.mid().color());
                imagePainter.setPen(option->palette.mid().color());
            } else {
                QColor shadow(0, 0, 0, 100);
                imagePainter.translate(0, 1);
                imagePainter.setPen(shadow);
                imagePainter.setBrush(shadow);
                QColor foreGround(255, 255, 255, 210);
                imagePainter.drawPolygon(a);
                imagePainter.translate(0, -1);
                imagePainter.setPen(foreGround);
                imagePainter.setBrush(foreGround);
            }
            imagePainter.drawPolygon(a);
            imagePainter.end();
            pixmap = QPixmap::fromImage(image);
            QPixmapCache::insert(pixmapName, pixmap);
        }
        int xOffset = r.x() + (r.width() - size)/2;
        int yOffset = r.y() + (r.height() - size)/2;
        painter->drawPixmap(xOffset, yOffset, pixmap);
    }
    break;

    default:
        d->style->drawPrimitive(element, option, painter, widget);
        break;
    }
}
Ejemplo n.º 30
0
std::vector<size_t> ATNSerializer::serialize() {
  std::vector<size_t> data;
  data.push_back(ATNDeserializer::SERIALIZED_VERSION);
  serializeUUID(data, ATNDeserializer::SERIALIZED_UUID());

  // convert grammar type to ATN const to avoid dependence on ANTLRParser
  data.push_back((size_t)atn->grammarType);
  data.push_back((size_t)atn->maxTokenType);
  size_t nedges = 0;

  std::unordered_map<misc::IntervalSet, int> setIndices;
  std::vector<misc::IntervalSet> sets;

  // dump states, count edges and collect sets while doing so
  std::vector<int> nonGreedyStates;
  std::vector<int> precedenceStates;
  data.push_back(atn->states.size());
  for (ATNState *s : atn->states) {
    if (s == nullptr) {  // might be optimized away
      data.push_back(ATNState::ATN_INVALID_TYPE);
      continue;
    }

    int stateType = s->getStateType();
    if (is<DecisionState *>(s) && (static_cast<DecisionState *>(s))->nonGreedy) {
      nonGreedyStates.push_back(s->stateNumber);
    }

    if (is<RuleStartState *>(s) && (static_cast<RuleStartState *>(s))->isLeftRecursiveRule) {
      precedenceStates.push_back(s->stateNumber);
    }

    data.push_back((size_t)stateType);

    if (s->ruleIndex == -1) {
      data.push_back(0xFFFF);
    }
    else {
      data.push_back((size_t)s->ruleIndex);
    }

    if (s->getStateType() == ATNState::LOOP_END) {
      data.push_back((size_t)(static_cast<LoopEndState *>(s))->loopBackState->stateNumber);
    }
    else if (is<BlockStartState *>(s)) {
      data.push_back((size_t)(static_cast<BlockStartState *>(s))->endState->stateNumber);
    }

    if (s->getStateType() != ATNState::RULE_STOP) {
      // the deserializer can trivially derive these edges, so there's no need
      // to serialize them
      nedges += s->getNumberOfTransitions();
    }

    for (size_t i = 0; i < s->getNumberOfTransitions(); i++) {
      Transition *t = s->transition(i);
      int edgeType = t->getSerializationType();
      if (edgeType == Transition::SET || edgeType == Transition::NOT_SET) {
        SetTransition *st = static_cast<SetTransition *>(t);
        if (setIndices.find(st->set) != setIndices.end()) {
          sets.push_back(st->set);
          setIndices.insert({ st->set, (int)sets.size() - 1 });
        }
      }
    }
  }

  // non-greedy states
  data.push_back(nonGreedyStates.size());
  for (size_t i = 0; i < nonGreedyStates.size(); i++) {
    data.push_back((size_t)nonGreedyStates.at(i));
  }

  // precedence states
  data.push_back(precedenceStates.size());
  for (size_t i = 0; i < precedenceStates.size(); i++) {
    data.push_back((size_t)precedenceStates.at(i));
  }

  size_t nrules = atn->ruleToStartState.size();
  data.push_back(nrules);
  for (size_t r = 0; r < nrules; r++) {
    ATNState *ruleStartState = atn->ruleToStartState[r];
    data.push_back((size_t)ruleStartState->stateNumber);
    if (atn->grammarType == ATNType::LEXER) {
      if (atn->ruleToTokenType[r] == Token::EOF) {
        data.push_back(0xFFFF);
      }
      else {
        data.push_back((size_t)atn->ruleToTokenType[r]);
      }
    }
  }

  size_t nmodes = atn->modeToStartState.size();
  data.push_back(nmodes);
  if (nmodes > 0) {
    for (const auto &modeStartState : atn->modeToStartState) {
      data.push_back((size_t)modeStartState->stateNumber);
    }
  }

  size_t nsets = sets.size();
  data.push_back(nsets);
  for (auto set : sets) {
    bool containsEof = set.contains(Token::EOF);
    if (containsEof && set.getIntervals().at(0).b == Token::EOF) {
      data.push_back(set.getIntervals().size() - 1);
    }
    else {
      data.push_back(set.getIntervals().size());
    }

    data.push_back(containsEof ? 1 : 0);
    for (auto &interval : set.getIntervals()) {
      if (interval.a == Token::EOF) {
        if (interval.b == Token::EOF) {
          continue;
        } else {
          data.push_back(0);
        }
      }
      else {
        data.push_back((size_t)interval.a);
      }

      data.push_back((size_t)interval.b);
    }
  }

  data.push_back(nedges);
  for (ATNState *s : atn->states) {
    if (s == nullptr) {
      // might be optimized away
      continue;
    }

    if (s->getStateType() == ATNState::RULE_STOP) {
      continue;
    }

    for (size_t i = 0; i < s->getNumberOfTransitions(); i++) {
      Transition *t = s->transition(i);

      if (atn->states[(size_t)t->target->stateNumber] == nullptr) {
        throw IllegalStateException("Cannot serialize a transition to a removed state.");
      }

      int src = s->stateNumber;
      int trg = t->target->stateNumber;
      int edgeType = t->getSerializationType();
      int arg1 = 0;
      int arg2 = 0;
      int arg3 = 0;
      switch (edgeType) {
        case Transition::RULE:
          trg = (static_cast<RuleTransition *>(t))->followState->stateNumber;
          arg1 = (static_cast<RuleTransition *>(t))->target->stateNumber;
          arg2 = (static_cast<RuleTransition *>(t))->ruleIndex;
          arg3 = (static_cast<RuleTransition *>(t))->precedence;
          break;
        case Transition::PRECEDENCE:
        {
          PrecedencePredicateTransition *ppt =
          static_cast<PrecedencePredicateTransition *>(t);
          arg1 = ppt->precedence;
        }
          break;
        case Transition::PREDICATE:
        {
          PredicateTransition *pt = static_cast<PredicateTransition *>(t);
          arg1 = pt->ruleIndex;
          arg2 = pt->predIndex;
          arg3 = pt->isCtxDependent ? 1 : 0;
        }
          break;
        case Transition::RANGE:
          arg1 = (int)(static_cast<RangeTransition *>(t))->from;
          arg2 = (int)(static_cast<RangeTransition *>(t))->to;
          if (arg1 == Token::EOF) {
            arg1 = 0;
            arg3 = 1;
          }

          break;
        case Transition::ATOM:
          arg1 = (int)(static_cast<AtomTransition *>(t))->_label;
          if (arg1 == Token::EOF) {
            arg1 = 0;
            arg3 = 1;
          }

          break;
        case Transition::ACTION:
        {
          ActionTransition *at = static_cast<ActionTransition *>(t);
          arg1 = at->ruleIndex;
          arg2 = at->actionIndex;
          if (arg2 == -1) {
            arg2 = 0xFFFF;
          }

          arg3 = at->isCtxDependent ? 1 : 0;
        }
          break;
        case Transition::SET:
          arg1 = setIndices[(static_cast<SetTransition *>(t))->set];
          break;

        case Transition::NOT_SET:
          arg1 = setIndices[(static_cast<SetTransition *>(t))->set];
          break;
        case Transition::WILDCARD:
          break;
      }

      data.push_back((size_t)src);
      data.push_back((size_t)trg);
      data.push_back((size_t)edgeType);
      data.push_back((size_t)arg1);
      data.push_back((size_t)arg2);
      data.push_back((size_t)arg3);
    }
  }

  size_t ndecisions = atn->decisionToState.size();
  data.push_back(ndecisions);
  for (DecisionState *decStartState : atn->decisionToState) {
    data.push_back((size_t)decStartState->stateNumber);
  }

  // LEXER ACTIONS
  if (atn->grammarType == ATNType::LEXER) {
    data.push_back(atn->lexerActions.size());
    for (Ref<LexerAction> action : atn->lexerActions) {
      data.push_back((size_t)action->getActionType());
      switch (action->getActionType()) {
        case LexerActionType::CHANNEL:
        {
          int channel = std::dynamic_pointer_cast<LexerChannelAction>(action)->getChannel();
          data.push_back(channel != -1 ? channel : 0xFFFF);
          data.push_back(0);
          break;
        }

        case LexerActionType::CUSTOM:
        {
          int ruleIndex = std::dynamic_pointer_cast<LexerCustomAction>(action)->getRuleIndex();
          int actionIndex = std::dynamic_pointer_cast<LexerCustomAction>(action)->getActionIndex();
          data.push_back(ruleIndex != -1 ? ruleIndex : 0xFFFF);
          data.push_back(actionIndex != -1 ? actionIndex : 0xFFFF);
          break;
        }

        case LexerActionType::MODE:
        {
          int mode = std::dynamic_pointer_cast<LexerModeAction>(action)->getMode();
          data.push_back(mode != -1 ? mode : 0xFFFF);
          data.push_back(0);
          break;
        }

        case LexerActionType::MORE:
          data.push_back(0);
          data.push_back(0);
          break;

        case LexerActionType::POP_MODE:
          data.push_back(0);
          data.push_back(0);
          break;

        case LexerActionType::PUSH_MODE:
        {
          int mode = std::dynamic_pointer_cast<LexerPushModeAction>(action)->getMode();
          data.push_back(mode != -1 ? mode : 0xFFFF);
          data.push_back(0);
          break;
        }

        case LexerActionType::SKIP:
          data.push_back(0);
          data.push_back(0);
          break;

        case LexerActionType::TYPE:
        {
          int type = std::dynamic_pointer_cast<LexerTypeAction>(action)->getType();
          data.push_back(type != -1 ? type : 0xFFFF);
          data.push_back(0);
          break;
        }

        default:
          throw IllegalArgumentException("The specified lexer action type " +
                                         std::to_string((size_t)action->getActionType()) + " is not valid.");
      }
    }
  }

  // don't adjust the first value since that's the version number
  for (size_t i = 1; i < data.size(); i++) {
    if (data.at(i) > 0xFFFF) {
      throw UnsupportedOperationException("Serialized ATN data element out of range.");
    }

    size_t value = (data.at(i) + 2) & 0xFFFF;
    data.assign(i, value);
  }

  return data;
}