Example #1
0
void Application::onMessage( const FIX50SP2::ApplicationMessageRequest& message,
                             const FIX::SessionID& sessionID )
{

  FIX50SP2::ExecutionReport executionReport;
  try
  {
    FIX::Session *pSession = FIX::Session::lookupSession(sessionID);
    FIX::UtcTimeStamp startTime;

    std::cout << "Session( " << sessionID << ").onMessage ( order): "
        << " PossibleLongCallback= " << pSession->getPossibleBusyWaitInCalbacks() << std::endl;
    std::cout << "Start time = " << FIX::UtcTimeStampConvertor::convert(startTime, true) << std::endl;

    while (!timedOut(startTime, m_expectedDownloadLatency)) {
      usleep(500000);
      executionReport.set( FIX::ExecID(genExecID()) );
      FIX::Session::sendToTarget( executionReport, sessionID );
    }

    FIX::UtcTimeStamp endTime;
    std::cout << "End time   = " << FIX::UtcTimeStampConvertor::convert(endTime, true) << std::endl;
  }
  catch ( std::exception& ex) {
    std::cout << "ApplicationMessageRequest handling failed: " << ex.what() << std::endl;
  }
}
Example #2
0
bool Ipc::connect(enum Result code, const QObject *reciever, const char *member)
{
	bool connected = false;
	
	switch (code)
	{
		case ResultOk:
			connected = QObject::connect(this, SIGNAL(ok(QByteArray)), reciever, member);
			break;
		case ResultNotImplemented:
			connected = QObject::connect(this, SIGNAL(notImplemented()), reciever, member);
			break;
		case ResultFail:
			connected = QObject::connect(this, SIGNAL(fail(QByteArray)), reciever, member);
			break;
		case ResultTimedOut:
			connected = QObject::connect(this, SIGNAL(timedOut()), reciever, member);
			break;
	}
	
	if (connected && !m_resultConnected.contains(code))
		m_resultConnected << code;
	
	return connected;
}
    bool SleepCommand::executeCommand(QStringList * const arguments)
    {
        if (arguments->size() == 1)
        {
            const int periodInMs = arguments->first().toInt();
            this->timer.setInterval(periodInMs);
            this->timer.setSingleShot(true);
            this->timer.start();
            connect(&this->timer,
                    SIGNAL(timeout()),
                    SLOT(timedOut()));

            // IMPORTANT: Return false and don't send any messages.
            // This will silently fail and when the timer expires
            // it will send the passed OK back to the client
            //
            // The client should be enforcing flow control and not
            // execute anything until the OK message goes back.
            //
            // It also means that this thread of execution (event)
            // can continue to process events without being held
            // by the sleep
        }
        else
        {
            this->client->write("ERROR: Not enough arguments, sleep <timeInMs>\r\n");
        }
        return false;
    }
Example #4
0
NotificationTimeout::NotificationTimeout(NotificationModel *m, int id, int timeout)
:QTimer(m), m_id(id), m_model(m) {
		setInterval(timeout);
		setSingleShot(true);
		connect(this, SIGNAL(timeout()),
				this, SLOT(timedOut()));
		start();
}
Example #5
0
void KTimeout::timerEvent(QTimerEvent* ev) {
    QHash<int, int>::const_iterator it = _timers.constBegin();
    for ( ; it != _timers.constEnd(); ++it) {
        if (it.value() == ev->timerId()) {
            emit timedOut(it.key());
            return;
        }
    }
}
/*!
   Constructor
 */
NmApiEventNotifierPrivate::NmApiEventNotifierPrivate(QObject *parent) :
    QObject(parent), mEmitSignals(NULL), mEngine(NULL), mIsRunning(false)
{
    NM_FUNCTION;
    mEmitSignals = new QTimer(this);
    mEmitSignals->setInterval(IntervalEmitingSignals);
    connect(mEmitSignals, SIGNAL(timeout()), this, SIGNAL(
        timedOut()));
    mEngine = NmApiEngine::instance();
}
Example #7
0
void KTimeout::timeout() {
	const QTimer *t = static_cast<const QTimer*>(sender());
	if (t) {
		QIntDictIterator<QTimer> it(_timers);
		for (; it.current(); ++it) {
			if (it.current() == t) {
				emit timedOut(it.currentKey());
				return;
			}
		}
	}
}
Example #8
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent), m_ApplicationOpenReminderEnabled(true),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowTitle(Version::getApplicationName().append(" (Version ").append(Version::getApplicationVersion().append(")")));
    setWindowIcon(QIcon(":/icon.ico"));

    createShortcuts();

    m_GraphicsScene = new GraphicalGridScene(m_Crossword);
    ui->graphicsView->setScene(m_GraphicsScene);

    m_TableModel = new CrosswordEntryTableModel(m_Crossword, m_Crossword.getRefEntries());
    m_ProxyModel = new QSortFilterProxyModel(this);
    m_ProxyModel->setSourceModel(m_TableModel);
    ui->wordTableView->setModel(m_ProxyModel);

    m_IdleReminder = new IdleReminder(60000);
    m_ClueReader = new ClueReader();

    connect(this, SIGNAL(puzzleLoaded()), m_TableModel, SLOT(crosswordEntriesChanged()));
    connect(this, SIGNAL(puzzleLoaded()), ui->wordTableView, SLOT(setFocus(Qt::OtherFocusReason)));
    connect(this, SIGNAL(puzzleLoaded()), m_GraphicsScene, SLOT(buildPuzzleGrid()));

    connect(m_TableModel, SIGNAL(conflictingWordError()), ui->wordTableView, SLOT(conflictingWordError()));
    connect(ui->wordTableView, SIGNAL(modelIndexChanged(const QModelIndex&, const QModelIndex&)), m_TableModel, SLOT(tableViewSelectionChanged(const QModelIndex&, const QModelIndex&)));

    connect(ui->wordTableView, SIGNAL(guessSubmitted(QString,QModelIndex)), this, SLOT(checkIfPuzzleWasCompleted()));
    connect(ui->wordTableView, SIGNAL(guessSubmitted(QString, QModelIndex)), m_TableModel, SLOT(enterGuess(QString, QModelIndex)));
    connect(ui->wordTableView, SIGNAL(guessAmendationRequested(QString, QModelIndex)), m_TableModel, SLOT(amendGuess(QString, QModelIndex)));
    connect(ui->wordTableView, SIGNAL(guessErasureRequested(QModelIndex)), m_TableModel, SLOT(eraseGuess(QModelIndex)));

    connect(m_TableModel, SIGNAL(guessValidated(QString)), ui->wordTableView, SLOT(reportGuessAccepted(QString)));
    connect(m_TableModel, SIGNAL(guessAmended(QString)), ui->wordTableView, SLOT(reportGuessAmended(QString)));
    connect(m_TableModel, SIGNAL(guessErased()), ui->wordTableView, SLOT(reportGuessErased()));
    connect(m_TableModel, SIGNAL(guessAmendationRequestRejected()), ui->wordTableView, SLOT(reportGuessAmendationRejected()));

    connect(m_TableModel, SIGNAL(guessValidated(QString)), m_GraphicsScene, SLOT(repaintPuzzleGrid()));
    connect(m_TableModel, SIGNAL(guessAmended(QString)), m_GraphicsScene, SLOT(repaintPuzzleGrid()));
    connect(m_TableModel, SIGNAL(guessErased()), m_GraphicsScene, SLOT(repaintPuzzleGrid()));
    connect(m_TableModel, SIGNAL(crosswordEntrySelectionChanged(CrosswordEntry)), m_GraphicsScene, SLOT(highlightSelection(CrosswordEntry)));

    connect(&m_CrosswordLoader, SIGNAL(loaderError(QString, QString)), this, SLOT(showError(QString, QString)));

    connect(m_IdleReminder, SIGNAL(timedOut()), this, SLOT(onIdleReminderTimeout()));
    qApp->installEventFilter(m_IdleReminder);

    connect(m_TableModel, SIGNAL(crosswordEntrySelectionChanged(CrosswordEntry)), m_ClueReader, SLOT(setText(CrosswordEntry)));

    ITextToSpeech::instance().speak(getIntroString());
}
Example #9
0
MCpuMonitor::MCpuMonitor() : d_ptr(new MCpuMonitorPrivate)
{
    Q_D(MCpuMonitor);

    d->usable = false;

#ifdef __linux__
    d->getCpuUsageInformation(d->jiffies_total, d->jiffies_idle);
#endif

    connect(&d->timer, SIGNAL(timeout()), SLOT(timedOut()));
}
Example #10
0
bool AMDetectorSet::addDetector(AMDetector *detector){
	if(!detector)
		return false;

	if( append(detector, detector->name()) ){
		connect(detector, SIGNAL(connected(bool)), this, SLOT(onConnectedChanged(bool)));
		connect(detector, SIGNAL(timedOut()), this, SLOT(onTimedOut()));
		onConnectedChanged(detector->isConnected());

		emit detectorAdded(count() - 1);

		return true;
	}
Example #11
0
SunscraperRPC::SunscraperRPC(QLocalSocket *socket) :
        m_socket(socket), m_state(StateHeader), m_result(false)
{
    m_nextQueryId += 1;
    m_queryId = m_nextQueryId;

    connect(m_socket, SIGNAL(readyRead()), this, SLOT(onInputReadable()));
    connect(m_socket, SIGNAL(disconnected()), this, SLOT(onInputDisconnected()));

    if(m_worker == NULL)
        m_worker = new SunscraperWorker();

    connect(m_worker, SIGNAL(finished(uint)), this, SLOT(onFinish(uint)));
    connect(m_worker, SIGNAL(timedOut(uint)), this, SLOT(onTimeout(uint)));
    connect(m_worker, SIGNAL(htmlFetched(uint,QString)), this, SLOT(onFetchDone(uint,QString)));
}
Example #12
0
int64_t SSLSocket::readImpl(char *buffer, int64_t length) {
  int64_t nr_bytes = 0;
  if (m_data->m_ssl_active) {
    bool retry = true;
    do {
      if (m_data->m_is_blocked) {
        Socket::waitForData();
        if (timedOut()) {
          break;
        }
        // could get here and we only have parts of an SSL packet
      }
      nr_bytes = SSL_read(m_data->m_handle, buffer, length);
      if (nr_bytes > 0) break; /* we got the data */
      retry = handleError(nr_bytes, false);
      setEof(!retry && errno != EAGAIN && !SSL_pending(m_data->m_handle));
    } while (retry);
  } else {
    nr_bytes = Socket::readImpl(buffer, length);
  }
  return nr_bytes < 0 ? 0 : nr_bytes;
}
Example #13
0
Foam::fileStat::fileStat(const fileName& fName, const unsigned int maxTime)
{
    // Work on volatile
    volatile bool locIsValid = false;

    timer myTimer(maxTime);

    if (!timedOut(myTimer))
    {
        if (::stat(fName.c_str(), &status_) != 0)
        {
            locIsValid = false;
        }
        else
        {
            locIsValid = true;
        }
    }

    // Copy into (non-volatile, possible register based) member var
    isValid_ = locIsValid;
}
bool KDLKinematicsPlugin::searchPositionIK(const geometry_msgs::Pose &ik_pose,
                                           const std::vector<double> &ik_seed_state,
                                           double timeout,
                                           std::vector<double> &solution,
                                           const IKCallbackFn &solution_callback,
                                           moveit_msgs::MoveItErrorCodes &error_code,
                                           const std::vector<double> &consistency_limits,
                                           const kinematics::KinematicsQueryOptions &options) const
{
  ros::WallTime n1 = ros::WallTime::now();
  if(!active_)
  {
    ROS_ERROR_NAMED("kdl","kinematics not active");
    error_code.val = error_code.NO_IK_SOLUTION;
    return false;
  }

  if(ik_seed_state.size() != dimension_)
  {
    ROS_ERROR_STREAM_NAMED("kdl","Seed state must have size " << dimension_ << " instead of size " << ik_seed_state.size());
    error_code.val = error_code.NO_IK_SOLUTION;
    return false;
  }

  if(!consistency_limits.empty() && consistency_limits.size() != dimension_)
  {
    ROS_ERROR_STREAM_NAMED("kdl","Consistency limits be empty or must have size " << dimension_ << " instead of size " << consistency_limits.size());
    error_code.val = error_code.NO_IK_SOLUTION;
    return false;
  }

  KDL::JntArray jnt_seed_state(dimension_);
  KDL::JntArray jnt_pos_in(dimension_);
  KDL::JntArray jnt_pos_out(dimension_);

  KDL::ChainFkSolverPos_recursive fk_solver(kdl_chain_);
  KDL::ChainIkSolverVel_pinv_mimic ik_solver_vel(kdl_chain_, joint_model_group_->getMimicJointModels().size(), redundant_joint_indices_.size(), position_ik_);
  KDL::ChainIkSolverPos_NR_JL_Mimic ik_solver_pos(kdl_chain_, joint_min_, joint_max_, fk_solver, ik_solver_vel, max_solver_iterations_, epsilon_, position_ik_);
  ik_solver_vel.setMimicJoints(mimic_joints_);
  ik_solver_pos.setMimicJoints(mimic_joints_);

  if ((redundant_joint_indices_.size() > 0) && !ik_solver_vel.setRedundantJointsMapIndex(redundant_joints_map_index_))
  {
    ROS_ERROR_NAMED("kdl","Could not set redundant joints");
    return false;
  }

  if(options.lock_redundant_joints)
  {
    ik_solver_vel.lockRedundantJoints();
  }

  solution.resize(dimension_);

  KDL::Frame pose_desired;
  tf::poseMsgToKDL(ik_pose, pose_desired);

  ROS_DEBUG_STREAM_NAMED("kdl","searchPositionIK2: Position request pose is " <<
                   ik_pose.position.x << " " <<
                   ik_pose.position.y << " " <<
                   ik_pose.position.z << " " <<
                   ik_pose.orientation.x << " " <<
                   ik_pose.orientation.y << " " <<
                   ik_pose.orientation.z << " " <<
                   ik_pose.orientation.w);
  //Do the IK
  for(unsigned int i=0; i < dimension_; i++)
    jnt_seed_state(i) = ik_seed_state[i];
  jnt_pos_in = jnt_seed_state;

  unsigned int counter(0);
  while(1)
  {
    //    ROS_DEBUG_NAMED("kdl","Iteration: %d, time: %f, Timeout: %f",counter,(ros::WallTime::now()-n1).toSec(),timeout);
    counter++;
    if(timedOut(n1,timeout))
    {
      ROS_DEBUG_NAMED("kdl","IK timed out");
      error_code.val = error_code.TIMED_OUT;
      ik_solver_vel.unlockRedundantJoints();
      return false;
    }
    int ik_valid = ik_solver_pos.CartToJnt(jnt_pos_in, pose_desired, jnt_pos_out);
    ROS_DEBUG_NAMED("kdl","IK valid: %d", ik_valid);
    if(!consistency_limits.empty())
    {
      getRandomConfiguration(jnt_seed_state, consistency_limits, jnt_pos_in, options.lock_redundant_joints);
      if( (ik_valid < 0 && !options.return_approximate_solution) || !checkConsistency(jnt_seed_state, consistency_limits, jnt_pos_out))
      {
        ROS_DEBUG_NAMED("kdl","Could not find IK solution: does not match consistency limits");
        continue;
      }
    }
    else
    {
      getRandomConfiguration(jnt_pos_in, options.lock_redundant_joints);
      ROS_DEBUG_NAMED("kdl","New random configuration");
      for(unsigned int j=0; j < dimension_; j++)
        ROS_DEBUG_NAMED("kdl","%d %f", j, jnt_pos_in(j));

      if(ik_valid < 0 && !options.return_approximate_solution)
      {
        ROS_DEBUG_NAMED("kdl","Could not find IK solution");
        continue;
      }
    }
    ROS_DEBUG_NAMED("kdl","Found IK solution");
    for(unsigned int j=0; j < dimension_; j++)
      solution[j] = jnt_pos_out(j);
    if(!solution_callback.empty())
      solution_callback(ik_pose,solution,error_code);
    else
      error_code.val = error_code.SUCCESS;

    if(error_code.val == error_code.SUCCESS)
    {
      ROS_DEBUG_STREAM_NAMED("kdl","Solved after " << counter << " iterations");
      ik_solver_vel.unlockRedundantJoints();
      return true;
    }
  }
  ROS_DEBUG_NAMED("kdl","An IK that satisifes the constraints and is collision free could not be found");
  error_code.val = error_code.NO_IK_SOLUTION;
  ik_solver_vel.unlockRedundantJoints();
  return false;
}
Example #15
0
void Ipc::timerEvent(QTimerEvent *event)
{
	QByteArray data;
	Message *msg;
	enum Cmd cmd;
	enum Result result;
	(void) event;
	
	if ((m_mode == ModeManager) && (m_cmdSent.msecsTo(QTime::currentTime()) > m_timeout)) // Проверка таймаута
	{
		stopTimer();
		
		if (m_resultConnected.contains(ResultTimedOut))
			emit timedOut(m_sentCmd);
		else
		{
			std::cout << "Command execution timed out" << std::endl;
			qApp->quit();
		}
		
		return;
	}
	
	if (m_shared.lock())
	{
		msg = (Message *)m_shared.constData();
		if (msg->dataSize > 0)
			data.append((const char *)(msg + 1), msg->dataSize);
	}
	else
		return;
	
	switch (m_mode)
	{
		case ModeApplication:
			cmd = (enum Cmd)msg->code;
			if (msg->sender == ModeManager)
			{
#ifdef DEBUG
				dbg << " i: IPC got command = " << cmd << " [" << data.toHex() << "]";
#endif
				if (m_cmdConnected.contains(cmd))
				{
					stopTimer();
					notify(cmd);
				}
				else
					switch (cmd)
					{
						case CmdStatus:
							if (m_state != StateNone)
								send(ResultOk, QByteArray(1, m_state), true);
							else
								send(ResultNotImplemented, true);
							break;
						case CmdStop:
							send(ResultOk, true);
							qApp->quit();
							break;
						case CmdPid:
							send(ResultOk, QByteArray::number(QApplication::applicationPid()), true);
							break;
						default:
							send(ResultNotImplemented, true);
					}
			}
			break;
		case ModeManager:
			result = (enum Result)msg->code;
			if (msg->sender == ModeApplication)
			{
#ifdef DEBUG
				dbg << " i: IPC got response = " << result << " [" << data.toHex() << "]";
#endif
				stopTimer();
				if (m_resultConnected.contains(result))
					notify(result, data);
				else
				{
					switch (result)
					{
						case ResultOk:
							switch (m_sentCmd)
							{
								case CmdPid:
									std::cout << data.data() << std::endl;
									break;
								case CmdStop:
									break;
								default:
									std::cout << "Command execution succeeded. Response dump: " << data.toHex().data() << std::endl;
									break;
							}
							break;
						case ResultNotImplemented:
							std::cout << "Command not implemented" << std::endl;
							break;
						case ResultFail:
							std::cout << "Error while executing command: " << data.data() << std::endl;
							break;
						default:;
					}
					qApp->quit();
				}
			}
			break;
	}
	m_shared.unlock();
}
bool KDLKinematicsPlugin::searchPositionIK(const geometry_msgs::Pose &ik_pose,
                                           const std::vector<double> &ik_seed_state,
                                           double timeout,
                                           std::vector<double> &solution,
                                           const IKCallbackFn &solution_callback,
                                           moveit_msgs::MoveItErrorCodes &error_code,
                                           const std::vector<double> &consistency_limits) const
{
  ros::WallTime n1 = ros::WallTime::now();
  if(!active_)
  {
    ROS_ERROR("kinematics not active");
    error_code.val = error_code.NO_IK_SOLUTION;
    return false;
  }

  if(ik_seed_state.size() != dimension_)
  {
    ROS_ERROR_STREAM("Seed state must have size " << dimension_ << " instead of size " << ik_seed_state.size());
    error_code.val = error_code.NO_IK_SOLUTION;
    return false;    
  }

  if(!consistency_limits.empty() && consistency_limits.size() != dimension_)
  {
    ROS_ERROR_STREAM("Consistency limits be empty or must have size " << dimension_ << " instead of size " << consistency_limits.size());
    error_code.val = error_code.NO_IK_SOLUTION;
    return false;        
  }  

  solution.resize(dimension_);
  
  KDL::Frame pose_desired;
  tf::poseMsgToKDL(ik_pose, pose_desired);
  
  ROS_DEBUG_STREAM("searchPositionIK2: Position request pose is " <<
                   ik_pose.position.x << " " <<
                   ik_pose.position.y << " " <<
                   ik_pose.position.z << " " <<
                   ik_pose.orientation.x << " " << 
                   ik_pose.orientation.y << " " << 
                   ik_pose.orientation.z << " " << 
                   ik_pose.orientation.w);
  //Do the IK
  for(unsigned int i=0; i < dimension_; i++)
    jnt_seed_state_(i) = ik_seed_state[i]; 
  jnt_pos_in_ = jnt_seed_state_;

  unsigned int counter(0);  
  while(1)  
  {
    //    ROS_DEBUG("Iteration: %d, time: %f, Timeout: %f",counter,(ros::WallTime::now()-n1).toSec(),timeout);    
    counter++;    
    if(timedOut(n1,timeout))
    {
      ROS_DEBUG("IK timed out");
      error_code.val = error_code.TIMED_OUT;
      return false;      
    }    
    int ik_valid = ik_solver_pos_->CartToJnt(jnt_pos_in_,pose_desired,jnt_pos_out_);                     
    if(!consistency_limits.empty()) 
    {
      getRandomConfiguration(jnt_seed_state_, consistency_limits, jnt_pos_in_);
      if(ik_valid < 0 || !checkConsistency(jnt_seed_state_, consistency_limits, jnt_pos_out_))
      {
        ROS_DEBUG("Could not find IK solution");        
        continue;
      } 
    }
    else
    {
      getRandomConfiguration(jnt_pos_in_);
      if(ik_valid < 0)
      {
        ROS_DEBUG("Could not find IK solution");        
        continue;
      }      
    }
    ROS_DEBUG("Found IK solution");    
    for(unsigned int j=0; j < dimension_; j++)
      solution[j] = jnt_pos_out_(j);
    if(!solution_callback.empty())
      solution_callback(ik_pose,solution,error_code);
    else
      error_code.val = error_code.SUCCESS;
    
    if(error_code.val == error_code.SUCCESS)
    {
      ROS_DEBUG_STREAM("Solved after " << counter << " iterations");
      return true;
    }
  }
  ROS_DEBUG("An IK that satisifes the constraints and is collision free could not be found");   
  error_code.val = error_code.NO_IK_SOLUTION;
  return false;
}
Example #17
0
bool Foam::ping
(
    const word& destName,
    const label destPort,
    const label timeOut
)
{
    char *serverAddress;
    struct in_addr *ptr;
    struct hostent *hostPtr;
    volatile int sockfd;
    struct sockaddr_in destAddr;      // will hold the destination addr
    u_int addr;

    if ((hostPtr = gethostbyname(destName.c_str())) == NULL)
    {
        FatalErrorIn
        (
            "Foam::ping(const word&, const label)"
        )   << "gethostbyname error " << h_errno << " for host " << destName
            << abort(FatalError);
    }

    // Get first of the SLL of addresses
    serverAddress = *(hostPtr->h_addr_list);
    ptr = reinterpret_cast<struct in_addr*>(serverAddress);
    addr = ptr->s_addr;

    // Allocate socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        FatalErrorIn
        (
            "Foam::ping(const word&, const label)"
        )   << "socket error"
            << abort(FatalError);
    }

    // Fill sockaddr_in structure with dest address and port
    memset (reinterpret_cast<char *>(&destAddr), '\0', sizeof(destAddr));
    destAddr.sin_family = AF_INET;
    destAddr.sin_port = htons(ushort(destPort));
    destAddr.sin_addr.s_addr = addr;


    timer myTimer(timeOut);

    if (timedOut(myTimer))
    {
        // Setjmp from timer jumps back to here
        fdClose(sockfd);
        return false;
    }

    if
    (
        connect
        (
            sockfd,
            reinterpret_cast<struct sockaddr*>(&destAddr),
            sizeof(struct sockaddr)
        ) != 0
    )
    {
        // Connection refused. Check if network was actually used or not.

        int connectErr = errno;

        fdClose(sockfd);

        if (connectErr == ECONNREFUSED)
        {
            return true;
        }
        //perror("connect");

        return false;
    }

    fdClose(sockfd);

    return true;
}
void ChooseGeneralBox::chooseGeneral(QStringList generals) {
    //嶷仟紙崙嘘尚
    if (generals.contains("anjiang(lord)")) generals.removeAll("anjiang(lord)");
    general_number = generals.length();
    update();

    items.clear();
    selected.clear();
    foreach(QString general, generals) {
        if (general.endsWith("(lord)")) continue;
        GeneralCardItem *general_item = new GeneralCardItem(general);
        general_item->setFlag(QGraphicsItem::ItemIsFocusable);

        if (single_result)
            general_item->setFlag(QGraphicsItem::ItemIsMovable, false);
        else {
            general_item->setAutoBack(true);
            connect(general_item, SIGNAL(released()), this, SLOT(_adjust()));
        }

        connect(general_item, SIGNAL(clicked()), this, SLOT(_onItemClicked()));
        connect(general_item, SIGNAL(enter_hover()), this, SLOT(_onCardItemHover()));
        connect(general_item, SIGNAL(leave_hover()), this, SLOT(_onCardItemLeaveHover()));
        connect(general_item, SIGNAL(general_changed()), this, SLOT(adjustItems()));

        if (!single_result) {
            const General *hero = Sanguosha->getGeneral(general);
            foreach (QString other, generals) {
                if (other.endsWith("(lord)")) continue;
                if (general != other && hero->isCompanionWith(other)) {
                    general_item->showCompanion();
                    break;
                }
            }
        }

        items << general_item;
        general_item->setParentItem(this);
    }

    setPos(RoomSceneInstance->tableCenterPos() - QPointF(boundingRect().width() / 2, boundingRect().height() / 2));
    show();

    int card_width = G_COMMON_LAYOUT.m_cardNormalWidth;
    int card_height = G_COMMON_LAYOUT.m_cardNormalHeight;
    int first_row = (general_number < 6) ? general_number : ((general_number + 1) / 2);

    for (int i = 0; i < items.length(); ++ i) {
        GeneralCardItem *card_item = items.at(i);

        QPointF pos;
        if (i < first_row) {
            pos.setX(left_blank_width + (card_width + card_to_center_line) * i + card_width / 2);
            pos.setY(top_blank_width + card_height / 2);
        } else {
            if (items.length() % 2 == 1)
                pos.setX(left_blank_width + card_width / 2 + card_to_center_line / 2 
                    + (card_width + card_to_center_line) * (i - first_row) + card_width / 2);
            else
                pos.setX(left_blank_width + (card_width + card_to_center_line) * (i - first_row) + card_width / 2);
            pos.setY(top_blank_width + card_height + card_to_center_line + card_height / 2);
        }

        card_item->setPos(25, 45);
        if (!single_result)
            //委厘社優廖峽贋和栖�契峭指音栖
            card_item->setData(S_DATA_INITIAL_HOME_POS, pos);
        card_item->setHomePos(pos);
        card_item->goBack(true);
    }

    if (single_result)
        confirm->hide();
    else {
        confirm->setPos(boundingRect().center().x() - confirm->boundingRect().width() / 2, boundingRect().height() - 60);
        confirm->show();
    }
    _initializeItems();

    if (ServerInfo.OperationTimeout != 0) {
        if (!progress_bar) {
	        progress_bar = new QSanCommandProgressBar();
	        progress_bar->setMinimumWidth(200);
	        progress_bar->setMaximumHeight(12);
	        progress_bar->setTimerEnabled(true);
	        progress_bar_item = new QGraphicsProxyWidget(this);
	        progress_bar_item->setWidget(progress_bar);
	        progress_bar_item->setPos(boundingRect().center().x() - progress_bar_item->boundingRect().width() / 2, boundingRect().height() - 30);
	        connect(progress_bar, SIGNAL(timedOut()), this, SLOT(reply()));
        }
        progress_bar->setCountdown(QSanProtocol::S_COMMAND_CHOOSE_GENERAL);
        progress_bar->show();
    }
}
void PlayerCardBox::chooseCard(const QString &reason, const ClientPlayer *player,
                          const QString &flags, bool handcardVisible,
                          Card::HandlingMethod method, const QList<int> &disabledIds)
{
    nameRects.clear();
    rowCount = 0;
    intervalsBetweenAreas = -1;
    intervalsBetweenRows = 0;
    maxCardsInOneRow = 0;

    this->player = player;
    this->title = tr("%1: please choose %2's card").arg(reason).arg(ClientInstance->getPlayerName(player->objectName()));
    this->flags = flags;
    bool handcard = false;
    bool equip = false;
    bool judging = false;

    if (flags.contains(handcardFlag) && !player->isKongcheng()) {
        updateNumbers(player->getHandcardNum());
        handcard = true;
    }

    if (flags.contains(equipmentFlag) && player->hasEquip()) {
        updateNumbers(player->getEquips().length());
        equip = true;
    }

    if (flags.contains(judgingFlag) && !player->getJudgingArea().isEmpty()) {
        updateNumbers(player->getJudgingArea().length());
        judging = true;
    }

    int max = maxCardsInOneRow;
    int maxNumber = maxCardNumberInOneRow;
    maxCardsInOneRow = qMin(max, maxNumber);

    prepareGeometryChange();

    moveToCenter();
    show();

    this->handcardVisible = handcardVisible;
    this->method = method;
    this->disabledIds = disabledIds;

    const int startX = verticalBlankWidth + placeNameAreaWidth + intervalBetweenNameAndCard;
    int index = 0;

    if (handcard) {
        if (Self == player || handcardVisible) {
            arrangeCards(player->getHandcards(), QPoint(startX, nameRects.at(index).y()));
        } else {
            const int handcardNumber = player->getHandcardNum();
            CardList cards;
            for(int i = 0; i < handcardNumber; ++ i)
                cards << NULL;
            arrangeCards(cards, QPoint(startX, nameRects.at(index).y()));
        }

        ++ index;
    }

    if (equip) {
        arrangeCards(player->getEquips(), QPoint(startX, nameRects.at(index).y()));

        ++ index;
    }

    if (judging)
        arrangeCards(player->getJudgingArea(), QPoint(startX, nameRects.at(index).y()));

    if (ServerInfo.OperationTimeout != 0) {
        if (!progressBar) {
            progressBar = new QSanCommandProgressBar();
            progressBar->setMaximumWidth(qMin(boundingRect().width() - 16, (qreal) 150));
            progressBar->setMaximumHeight(12);
            progressBar->setTimerEnabled(true);
            progressBarItem = new QGraphicsProxyWidget(this);
            progressBarItem->setWidget(progressBar);
            progressBarItem->setPos(boundingRect().center().x() - progressBarItem->boundingRect().width() / 2, boundingRect().height() - 20);
            connect(progressBar, SIGNAL(timedOut()), this, SLOT(reply()));
        }
        progressBar->setCountdown(QSanProtocol::S_COMMAND_CHOOSE_CARD);
        progressBar->show();
    }
}