Exemplo n.º 1
0
UnitClass::UnitClass(BWAPI::Unit* unit)
	: mUnit(unit)
	, mStoredPosition(BWAPI::Positions::Unknown)
	, mStoredTargetPosition(BWAPI::Positions::None)
	, mStoredAccessType(AccessType::Full)
	, mStoredPlayer(BWAPI::Broodwar->neutral())
	, mStoredBoolOne(false)
	, mStoredCompleted(false)
	, mStoredMorphing(false)
	, mStoredCompletedTime(0)
	, mStoredTime(0)
	, mStoredInt(0)
	, mStoredExistsTime(Requirement::maxTime)
	, mStoredHealth(0)
	, mStoredShield(0)
	, mLastOrderExecuteTime(0)
{
	if(exists())
	{
		mStoredCompleted = unit->isCompleted();
		mStoredMorphing = unit->isMorphing();
	}
	update();
	if(exists())
	{
		if(!isCompleted())
			mStoredCompletedTime = BWAPI::Broodwar->getFrameCount() + unit->getType().buildTime();
		else if(isMorphing())
			mStoredCompletedTime = BWAPI::Broodwar->getFrameCount() + unit->getBuildType().buildTime();
	}
}
Exemplo n.º 2
0
/**
 * Check for state of this progress event
 */
void ProgressTask::_notifyUpdate ( const std::string& message ) {
    CRASH_REPORT_BEGIN;

	// Store the last message
	lastMessage = message;

	// Check if we are completed
	if (isCompleted()) {

		// Send a completion notification
		_notifyCompleted( message );

	} else {

		// Call all the progress callbacks
		fireProgress( message, getProgress() );

		// Propagate event
		if (parent) {
			parent->_notifyUpdate( message );
		}

	}

    CRASH_REPORT_END;
}
Exemplo n.º 3
0
std::string Mission::getName(Player* player) const
{
	if (isCompleted(player)) {
		return name + " (completed)";
	}
	return name;
}
Exemplo n.º 4
0
String FileReaderLoader::stringResult()
{
    ASSERT(m_readType != ReadAsArrayBuffer && m_readType != ReadAsBlob);

    // If the loading is not started or an error occurs, return an empty result.
    if (!m_rawData || m_errorCode)
        return m_stringResult;

    // If already converted from the raw data, return the result now.
    if (m_isRawDataConverted)
        return m_stringResult;

    switch (m_readType) {
    case ReadAsArrayBuffer:
        // No conversion is needed.
        break;
    case ReadAsBinaryString:
        m_stringResult = String(static_cast<const char*>(m_rawData->data()), m_bytesLoaded);
        break;
    case ReadAsText:
        convertToText();
        break;
    case ReadAsDataURL:
        // Partial data is not supported when reading as data URL.
        if (isCompleted())
            convertToDataURL();
        break;
    default:
        ASSERT_NOT_REACHED();
    }
    
    return m_stringResult;
}
Exemplo n.º 5
0
	void SlidePuzzleModel::check() {
		if (_status == SlidePuzzleStatus::PLAY && isCompleted()) {
			_status = SlidePuzzleStatus::COMPLETE;
			_scheduleManager->scheduleOnce(TIME_SLIDE, [this]() {
				emitComplete();
			});
		}
	}
Exemplo n.º 6
0
void Fracture::grow() {
	double deltaBeta1 = elementsL.back().calcAngleOfRotation();
	double deltaBeta2 = elementsR.back().calcAngleOfRotation();
	print("predictor ", "K1 = ", elementsR.back().K1(), "\tK2 = ", elementsR.back().K2());
	deltaBetaL = deltaBeta1; deltaBetaR = deltaBeta2;
	// Fracture grows after injecting
	//if ( ! isStopped() ) grow(deltaBeta1, deltaBeta2);
	// Fracture doesn't grow after injecting
	if ( ! isCompleted() ) grow(deltaBeta1, deltaBeta2);
}
Exemplo n.º 7
0
 void CommandQueue::waitForCommands()
 {
     if (!isCompleted())
     {
         enforce<Direct3DException>(
             SUCCEEDED(fence_->SetEventOnCompletion(fenceValue_, fenceEvent_.get())),
             "Failed to set the signal event.");
         WaitForSingleObject(fenceEvent_.get(), INFINITE);
     }
     updateExecutionState();
 }
Exemplo n.º 8
0
UnitGroup ConstructionTask::getFinishedUnits()
{
	UnitGroup returnUnits;

	if(mBuilder && finishedWithBuilder())
		returnUnits.insert(mBuilder);

	if(mProducedUnit && mProducedUnit->exists() && isCompleted())
		returnUnits.insert(mProducedUnit);

	return returnUnits;
}
Exemplo n.º 9
0
bool TechTask::preUpdate()
{
	if(BWAPI::Broodwar->self()->hasResearched(mType))
		complete();

	if((isStopped() || isCanceled() || isCompleted()) && mUnit && !mUnit->isResearching())
		return true;

	updateRequirements();

	return false;
}
Exemplo n.º 10
0
	void ThreadLoading::doUpdate(const UpdateState &us)
	{
		_m2n.update();

		if (isCompleted())
		{
			Event ev(COMPLETE, true);

			dispatchEvent(&ev);

			detach();
		}
	}
Exemplo n.º 11
0
PassRefPtr<ArrayBuffer> FileReaderLoader::arrayBufferResult() const
{
    ASSERT(m_readType == ReadAsArrayBuffer);

    // If the loading is not started or an error occurs, return an empty result.
    if (!m_rawData || m_errorCode)
        return 0;

    // If completed, we can simply return our buffer.
    if (isCompleted())
        return m_rawData;

    // Otherwise, return a copy.
    return ArrayBuffer::create(m_rawData.get());
}
Exemplo n.º 12
0
void ExLineEdit::focusOutEvent(QFocusEvent *event)
{
    m_lineEdit->event(event);

    if (m_lineEdit->completer()) {
        connect(m_lineEdit->completer(), SIGNAL(activated(QString)),
                m_lineEdit, SLOT(setText(QString)));

        connect(m_lineEdit->completer(), SIGNAL(activated(QString)),
                this, SLOT(isCompleted(QString)));

        connect(m_lineEdit->completer(), SIGNAL(highlighted(QString)),
                m_lineEdit, SLOT(_q_completionHighlighted(QString)));
    }
    QWidget::focusOutEvent(event);
}
Exemplo n.º 13
0
void FileReaderLoader::convertToText()
{
    if (!m_bytesLoaded)
        return;

    // Decode the data.
    // The File API spec says that we should use the supplied encoding if it is valid. However, we choose to ignore this
    // requirement in order to be consistent with how WebKit decodes the web content: always has the BOM override the
    // provided encoding.     
    // FIXME: consider supporting incremental decoding to improve the perf.
    if (!m_decoder)
        m_decoder = TextResourceDecoder::create("text/plain", m_encoding.isValid() ? m_encoding : UTF8Encoding());
    if (isCompleted())
        m_stringResult = m_decoder->decodeAndFlush(static_cast<const char*>(m_rawData->data()), m_bytesLoaded);
    else
        m_stringResult = m_decoder->decode(static_cast<const char*>(m_rawData->data()), m_bytesLoaded);
}
Exemplo n.º 14
0
void ExeTask::cbackBy_Timerfunc(PVOID param, bool timerOrWaitFired)
{

  	QueryPerformanceFrequency(&liFrequency);  // retrieves the frequency of the high-resolution performance counter    
	QueryPerformanceCounter(&liCounter1);         // Start
	litemp = (double)(liCounter1.QuadPart - liCounter0.QuadPart) / (double)liFrequency.QuadPart;
	liCounter0 = liCounter1;

	if(m_stop){
		SetEvent(m_DoneEvent);
		//m_running = false; //이건 RThread에게 있는 멤버 데이터
		return;
	}
		
	try{
		if(m_runner->isDebugMode() && !m_isDbgCondCreated){
			//디버깅인데 cond가 아직 생성이 안되면 아무것도 안한다.
		}
		else{
			m_runner->enterTask(this, m_task);
			if(isCompleted()) {
				SetEvent(m_DoneEvent);
				return;
			}
		}
	}
	catch(RuntimeEH& runEH){
		//runEH.printError();
		FLOG_ERROR(m_logFile, "  (RUNNING:%d) 값을 획득하는데 실패하였습니다.", runEH.getErrorCode());
		//return runEH.getErrorCode();
	}

	FLOG_TRACE(m_logFile, "  (RUNNING:CYCLE) This is the end of a cycle.\n");
	m_iterCount++;			

	QueryPerformanceCounter(&liCounter2);
	PeRecord rec;
	rec.name = getInstanceName();
	rec.cycle = litemp;
	rec.proc = (double)(liCounter2.QuadPart - liCounter1.QuadPart) / (double)liFrequency.QuadPart;
	PerformTable::addPeRecord(rec);

	//printf("<%s> Cycle Time : %f, Process Time : %f\n", getInstanceName().c_str(), litemp, (double)(liCounter2.QuadPart - liCounter1.QuadPart) / (double)liFrequency.QuadPart);
	
}
Exemplo n.º 15
0
    void CommandQueue::updateExecutionState()
    {
        if (!isCompleted())
        {
            return;
        }

        for (const auto& a : executingAllocators_)
        {
            a->protect(false);
        }
        for (const auto& c : executingCommands_)
        {
            c->protect(false);
        }
        executingAllocators_.clear();
        executingCommands_.clear();
    }
Exemplo n.º 16
0
PassRefPtr<Blob> FileReaderLoader::blobResult()
{
    ASSERT(m_readType == ReadAsBlob);

    // If the loading is not finished or an error occurs, return an empty result.
    if (!m_rawData || m_errorCode || !isCompleted())
        return 0;

    if (!m_blobResult) {
        OwnPtr<BlobData> blobData = BlobData::create();
        size_t size = 0;
        RefPtr<RawData> rawData = RawData::create();
        size = m_rawData->byteLength();
        rawData->mutableData()->append(static_cast<char*>(m_rawData->data()), size);
        blobData->appendData(rawData, 0, size);
        blobData->setContentType(m_dataType);
        m_blobResult = Blob::create(blobData.release(), size);
    }
    return m_blobResult;
}
Exemplo n.º 17
0
	void SlidePuzzleModel::shuffleProc() {
		if (_shuffleHorizontal) {
			RandomInt r(0, _width - 2);
			int x = r();
			if (x >= _emptyPos.x) { x++; }
			slide_p(Position(x, _emptyPos.y));
		} else {
			RandomInt r(0, _height - 2);
			int y = r();
			if (y >= _emptyPos.y) { y++; }
			slide_p(Position(_emptyPos.x, y));
		}
		_shuffleCount++;
		_shuffleHorizontal = !_shuffleHorizontal;
		if (_shuffleCount >= 50 && !isCompleted()) {
			_scheduleManager->cancel(_scheduleShuffle);
			_scheduleManager->scheduleOnce(TIME_SLIDE, [this]() {
				_status = SlidePuzzleStatus::PLAY;
			});
		}
	}
Exemplo n.º 18
0
// +-----------------------------------------------------------
void gc::Questionnaire::fieldChanged(const uint iIndex)
{
	Q_ASSERT(static_cast<uint>(m_vQuestionTypes.size()) >= iIndex);
	QuestionType eType = m_vQuestionTypes[iIndex];

	Q_ASSERT(static_cast<uint>(m_vQuestionFields.size()) >= iIndex);
	QVariant vValue = QVariant::Invalid;
	bool bUndefined = false;
	switch(eType)
	{
		case Integer:
			vValue = static_cast<QSpinBox*>(m_vQuestionFields[iIndex])->value();
			if(vValue.toInt() <= 0)
				bUndefined = true;
			break;

		case String:
			vValue = static_cast<QLineEdit*>(m_vQuestionFields[iIndex])->text();
			if(vValue.toString().length() == 0)
				bUndefined = true;
			break;

		case Likert:
			vValue = static_cast<LikertScale*>(m_vQuestionFields[iIndex])->getSelected();
			if(vValue.toInt() == -1)
				bUndefined = true;
			break;
	}
	emit questionChanged(iIndex, eType, vValue);

	if(isCompleted())
		emit completed();

	QLabel *pLabel = m_vQuestionLabels[iIndex];
	pLabel->setProperty("undefined", bUndefined);
	pLabel->style()->unpolish(pLabel);
	pLabel->style()->polish(pLabel);
}
Exemplo n.º 19
0
int UnitClass::getCompletedTime()
{
	if(isCompleted())
		return BWAPI::Broodwar->getFrameCount();

	if(exists())
	{
		if(mUnit->getPlayer() == BWAPI::Broodwar->self())
			return BWAPI::Broodwar->getFrameCount() + mUnit->getRemainingBuildTime();
	}
	else
	{
		const int existsTime = getExistTime();
		const int completeTime = existsTime + getType().buildTime();

		if(completeTime < existsTime)
			return std::numeric_limits<int>::max();
		else
			return completeTime;
	}

	return std::max(mStoredCompletedTime, BWAPI::Broodwar->getFrameCount() + 1);
}
Exemplo n.º 20
0
void ExeTask::cbackBy_Thrfunc()
{
	bool isWin = false;
	m_iterCount = 0;
	m_running = true;
	m_joining = false;
	setCompleted(false);
	if(m_task != NULL){

		std::string performFile = getNodeName();
		if(TaskConfig::isloggingTimePeriod()) {
			PerformTable::init();			
		}
		#ifdef _WIN32	
		isWin = true;
		QueryPerformanceCounter(&liCounter0);  
		#else
		struct timespec tp0, tp1, tp2;
		double litemp;
		clock_gettime(CLOCK_MONOTONIC, &tp0);
		#endif

		if(isWin && TaskConfig::isUsingQueueTimer()){
			this->start_que(m_TimerQueue, getNodeName());
			if(TaskConfig::isloggingTimePeriod()) performFile.append("-Timer");	
		}
		else{
			//2. run
			while(1){
				
				#ifdef _WIN32	
				QueryPerformanceFrequency(&liFrequency);  // retrieves the frequency of the high-resolution performance counter    
				QueryPerformanceCounter(&liCounter1);         // Start
				litemp = (double)(liCounter1.QuadPart - liCounter0.QuadPart) / (double)liFrequency.QuadPart;
				liCounter0 = liCounter1;
				#else
				clock_gettime(CLOCK_MONOTONIC, &tp1);
				litemp = ((double)(tp1.tv_sec*1000) + (double)(tp1.tv_nsec)/1000000)-((double)(tp0.tv_sec*1000) + (double)(tp0.tv_nsec)/1000000);
				tp0.tv_sec = tp1.tv_sec;
				tp0.tv_nsec = tp1.tv_nsec;
				#endif

				if(m_stop){  //외부로 부터 쓰레드 중지 명령			
					break;
				}
					
				try{
					if(m_runner->isDebugMode() && !m_isDbgCondCreated){
						//디버깅인데 cond가 아직 생성이 안되면 아무것도 안한다.
					}
					else{
						m_runner->enterTask(this, m_task);
						if(isCompleted()) break;
					}
				}
				catch(RuntimeEH& runEH){
					//runEH.printError();
					FLOG_ERROR(m_logFile, "  (RUNNING:%d) 값을 획득하는데 실패하였습니다.", runEH.getErrorCode());
					//return runEH.getErrorCode();
				}
			
				FLOG_TRACE(m_logFile, "  (RUNNING:CYCLE) This is the end of a cycle.\n");
				m_iterCount++;	

				#ifdef _WIN32			
				QueryPerformanceCounter(&liCounter2);
				PeRecord rec;
				rec.name = getInstanceName();
				rec.cycle = litemp;
				rec.proc = (double)(liCounter2.QuadPart - liCounter1.QuadPart) / (double)liFrequency.QuadPart;				
				//printf("<%s> Cycle Time : %f, Process Time : %f\n", getInstanceName().c_str(), litemp, (double)(liCounter2.QuadPart - liCounter1.QuadPart) / (double)liFrequency.QuadPart);
				#else
				clock_gettime(CLOCK_MONOTONIC, &tp2);
				PeRecord rec;
				rec.name = getInstanceName();
				rec.cycle = litemp;
				rec.proc = ((double)(tp2.tv_sec*1000) + (double)(tp2.tv_nsec)/1000000)-((double)(tp1.tv_sec*1000) + (double)(tp1.tv_nsec)/1000000);				
				#endif

				if(TaskConfig::isloggingTimePeriod()){
					PerformTable::addPeRecord(rec);
				}
				
				float sleeptime = m_timePeriod - rec.proc*1000;
				if(sleeptime<0) sleeptime = 0;
				thread_sleep(sleeptime);
			
				//timespec a;
				//a.tv_sec = 0;
				//a.tv_nsec = 5000000 - rec.proc * 1000000;
				//nanosleep(&a, NULL);
				
			}
			if(TaskConfig::isloggingTimePeriod()) performFile.append("-Thread");	
		}
		m_runner->enterDestruct(this);
		m_running = false;
		
		if(TaskConfig::isloggingTimePeriod()) PerformTable::makeFile(performFile);
	}
	
	if(m_runner->isDebugMode()||m_runner->isMonitorMode()){
		m_runner->delCondMu4BP(getThreadNum());
		m_isDbgCondCreated = false;
		this->sendThreadInfo("delete"); //Task 쓰레드 delete가 전송되면 종료임을 알 수 있다.
		this->sendMonitorMsg("RES-EOT");
		DbgTable::clearTable();
	}
}
Exemplo n.º 21
0
//------------------------------------------------------------------------------
// serialize
//------------------------------------------------------------------------------
std::ostream& TargetData::serialize(std::ostream& sout, const int i, const bool slotsOnly) const
{
    int j = 0;
    if ( !slotsOnly ) {
        sout << "( " << getFactoryName() << std::endl;
        j = 4;
    }

    BaseClass::serialize(sout,i+j,true);

    indent(sout,i+j);
    sout << "enabled: " << (isEnabled() ? "true" : "false")  << std::endl;

    indent(sout,i+j);
    sout << "completed: " << (isCompleted() ? "true" : "false")  << std::endl;

    {
        const Basic::String* s = getWpnType();
        if (s != 0) {
            indent(sout,i+j);
            sout << "weaponType: " << s  << std::endl;
        }
    }

    indent(sout,i+j);
    sout << "quantity: " << getQuantity()  << std::endl;

    indent(sout,i+j);
    sout << "manualAssign: " <<  (getManualAssign() ? "true" : "false")  << std::endl;

    {
        unsigned int st = getStickType();
        if (st == MIDPOINT) {
            indent(sout,i+j);
            sout << "stickType: " << "MIDPOINT" << std::endl;
        }
        else if (st == LEADING_EDGE) {
            indent(sout,i+j);
            sout << "stickType: " << "LEADING_EDGE" << std::endl;
        }
    }

    indent(sout,i+j);
    sout << "stickDistance:  ( Feet " << getStickDistance()  << " )"  << std::endl;

    indent(sout,i+j);
    sout << "interval: ( MilliSeconds " << getInterval()  << " )"     << std::endl;

    indent(sout,i+j);
    sout << "maxMissDistance: ( Feet " << getMaxMissDistance()  << " )"  << std::endl;

    indent(sout,i+j);
    sout << "armDelay: ( Seconds " << getArmDelay()  << " )"     << std::endl;

    indent(sout,i+j);
    sout << "angle: ( Degrees  " << getAngle()  << " )"        << std::endl;

    indent(sout,i+j);
    sout << "azimuth: ( Degrees " << getAzimuth()  << " )"      << std::endl;

    indent(sout,i+j);
    sout << "velocity: " << getVelocity()     << std::endl;

    if ( !slotsOnly ) {
        indent(sout,i);
        sout << ")" << std::endl;
    }
    return sout;
}
Exemplo n.º 22
0
void UnitClass::drawUnitPosition()
{
	const Position &pos = getPosition();
	const BWAPI::UnitType &type = getType();
	Player player = getPlayer();

	const int barHeight = 4;

	if((!isCompleted() || isMorphing()) && accessibility() != AccessType::Prediction)
	{
		double progress = getCompletedTime() - BWAPI::Broodwar->getFrameCount();

		if(isMorphing())
			progress /= getBuildType().buildTime();
		else
			progress /= type.buildTime();

		progress = 1.0 - progress;

		BWAPI::Color barColour = isMorphing() ? BWAPI::Colors::Red : BWAPI::Colors::Purple;

		Position bottomLeft(pos.x() - type.dimensionLeft(), pos.y() + type.dimensionDown() + barHeight - 1);

		DrawingHelper::Instance().drawProgressBar(bottomLeft, type.dimensionLeft()+type.dimensionRight(), barHeight, progress, barColour, player->getColor());
	}

	if(type.maxShields() > 0)
	{
		double progress = getShield();
		progress /= type.maxShields();

		Position bottomLeft(pos.x() - type.dimensionLeft(), pos.y() - type.dimensionUp() - barHeight + 2);

		DrawingHelper::Instance().drawProgressBar(bottomLeft, type.dimensionLeft()+type.dimensionRight(), barHeight, progress, BWAPI::Colors::Blue, player->getColor());
	}

	if(type.maxHitPoints() > 0)
	{
		double progress = getHealth();
		progress /= type.maxHitPoints();

		Position bottomLeft(pos.x() - type.dimensionLeft(), pos.y() - type.dimensionUp() + 1);

		DrawingHelper::Instance().drawProgressBar(bottomLeft, type.dimensionLeft()+type.dimensionRight(), barHeight, progress, BWAPI::Colors::Green, player->getColor());
	}

	BWAPI::Broodwar->drawBox(BWAPI::CoordinateType::Map, pos.x() - type.dimensionLeft(), pos.y() - type.dimensionUp(), pos.x() + type.dimensionRight(), pos.y() + type.dimensionDown(), player->getColor());

	BWAPI::Broodwar->drawTextMap(pos.x() + type.dimensionRight(), pos.y(), "%s", player->getName().c_str());

	AccessType access = accessibility();
	BWAPI::Broodwar->drawTextMap(pos.x() + type.dimensionRight(), pos.y()+10, "%s", AccessType::getName(access.underlying()).c_str());

	int existTime = getExistTime() - BWAPI::Broodwar->getFrameCount();
	int completeTime = getCompletedTime() - BWAPI::Broodwar->getFrameCount() - existTime;
	BWAPI::Broodwar->drawTextMap(pos.x() + type.dimensionRight(), pos.y()+20, "%d : %d", existTime, completeTime);

	if(isMorphing())
		BWAPI::Broodwar->drawTextMap(pos.x() + type.dimensionRight(), pos.y()+30, "Morphing");
	else if(isCompleted())
		BWAPI::Broodwar->drawTextMap(pos.x() + type.dimensionRight(), pos.y()+30, "Completed");

	Position target = getTargetPosition();
	BWAPI::Broodwar->drawLine(BWAPI::CoordinateType::Map, pos.x(), pos.y(), target.x(), target.y(), player->getColor());
}
Exemplo n.º 23
0
const bool SM_Net::download_file ( void )
{
	if( ! define_info( sm_download->option == OPTION_NOT_ASKED ) )
		return false;
	if( sm_download->option == OPTION_NOT_ASKED )
	{
		sm_download->size      = get_totalSize();
		sm_download->completed = get_comSize();
		sm_download->option    = get_replace();
	}
	else
	{
		set_totalSize ( sm_download->size );
		set_replace   ( sm_download->option );
	}

	if( isHTTP() )
	{
		sm_httpSocket = new SM_HTTP ();
		if( ! sm_httpSocket )
		{
			SM_Util::msg_err( "Error: could not allocate http socket." );
			delete sm_httpSocket;
			sm_httpSocket = NULL;
			return false;
		}
		if( ! sm_httpSocket->configure( sm_address, sm_port ) )
		{
			SM_Util::msg_err( "Error: could not connect to server." );
			delete sm_httpSocket;
			sm_httpSocket = NULL;
			return false;
		}
		if( ! donwload )
		{
			running = true;

			sm_httpSocket->set_speedLimit( sm_speedLimit );

			bool get_return;
			if( replace && get_comSize() == 0 )
				get_return = sm_httpSocket->get_file( sm_download, sm_fileName, sm_path, get_totalSize(), replace );
			else
				get_return = sm_httpSocket->get_file( sm_download, sm_fileName, sm_path, get_totalSize() - sm_size, replace );

			running = false;
			delete sm_httpSocket;
			sm_httpSocket = NULL;

			if( get_return )
			{
				if( isCompleted() )
					sm_signal_completed( this );
				else
					sm_signal_paused( this );
				return true;
			}
			else
			{
				SM_Util::msg_err( "Error: could not get file." );
				return false;
			}
		}
		delete sm_httpSocket;
		sm_httpSocket = NULL;
		return true;
	}
	else if ( isFTP() )
	{
		sm_ftpSocket = new SM_FTP();

		if( ! sm_ftpSocket )
		{
			SM_Util::msg_err( "Error: could not allocate ftp socket." );
			delete sm_ftpSocket;
			sm_ftpSocket = NULL;
			return false;
		}
		if( ! sm_ftpSocket->configure( sm_address, sm_port ) )
		{
			SM_Util::msg_err( "Error: could not connect to server." );
			delete sm_ftpSocket;
			sm_ftpSocket = NULL;
			return false;
		}
		if( ! sm_ftpSocket->user_conf( sm_download->user, sm_download->pass ) )
		{
			SM_Util::msg_err( "Error: could not authenticate." );
			delete sm_ftpSocket;
			sm_ftpSocket = NULL;
			return false;
		}
		if( ! sm_ftpSocket->set_type( true ) )
		{
			SM_Util::msg_err( "Error: could not set connection type." );
			delete sm_ftpSocket;
			sm_ftpSocket = NULL;
			return false;
		}
		if( ! donwload )
		{
			running = true;

			sm_ftpSocket->set_speedLimit( sm_speedLimit );

			bool get_return;
			if( replace && get_comSize() == 0 )
				get_return = sm_ftpSocket->get_file( sm_download, sm_fileName, sm_path, 0, replace );
			else
				get_return = sm_ftpSocket->get_file( sm_download, sm_fileName, sm_path, sm_size, replace );

			running = false;

			if( get_return )
			{
				delete sm_ftpSocket;
				sm_ftpSocket = NULL;

				if( isCompleted() )
					sm_signal_completed( this );
				else
					sm_signal_paused( this );
				return true;
			}
			else
			{
				SM_Util::msg_err( "Error: could not make download." );

				if( ! sm_ftpSocket->quit() )
					SM_Util::msg_err( "Error: could not quit connection." );

				delete sm_ftpSocket;
				sm_ftpSocket = NULL;

				return false;
			}
		}
		delete sm_ftpSocket;
		sm_ftpSocket = NULL;
		return true;
	}
	else
	{
		SM_Util::msg_err( "Error: network protocol not supported." );
		return false;
	}	
}
Exemplo n.º 24
0
/**
 * Calculate the detection chance of this base.
 * Big bases without mindshields are easier to detect.
 * @return The detection chance.
 */
unsigned Base::getDetectionChance() const
{
	unsigned mindShields = std::count_if(_facilities.begin(), _facilities.end(), isMindShield());
	unsigned completedFacilities = std::count_if(_facilities.begin(), _facilities.end(), isCompleted());
	return (completedFacilities / 6 + 15) / (mindShields + 1);
}
Exemplo n.º 25
0
void VirtCoreThread::run() {
	// Implementation for command line:
	// VBoxManage startvm "Windows XP"
	// timeout 10
	// VBoxManage guestcontrol "Windows XP" --username "vbox" --password "12345" run fsutil.exe --wait-stdout -- fsinfo drives
	// VBoxManage guestcontrol "Windows XP" --username "vbox" --password "12345" run fsutil.exe --wait-stdout -- volume diskfree c:\
	// ...
	enum { waitLaunchPeriod = 120000 };
	enum { waitLoginPeriod = 2000 };
	enum { delayLaunchVM = 5000 };
	enum { delayLogin = 500 };
	enum { reloginCount = 3 };

	const CoInit coInit;
	
	// Get machine and create session
	const auto machine = machineByName(virtualBox(), machine_.machine);
	const auto session = ::session();

	// Launch and lock machine
	if (isRuning(machine)) {
		if (!lock(machine, session)) {
			emit processMessage(
				tr("Lock machine '%1' fail").arg(machine_.machine)
			);
			return;
		}
	}
	else {
		const auto progress = launchVM(machine, session);

		emit processMessage(tr("Launch machine '%1'").arg(machine_.machine));

		if (!progress || !waitFor(
			[&progress, &machine]() {
				progress->WaitForCompletion(ticPeriod);
				return isCompleted(progress) && isRuning(machine);
			},
			waitLaunchPeriod
		)) {
			if (progress) {
				progress->Cancel();
			}

			if (!stop_) {
				emit processMessage(
					tr("Launch error for machine '%1'").arg(machine_.machine)
				);
			}

			return;
		}
		else {
			msleep(delayLaunchVM);
			if (stop_) { return; }
		}
	}

	// Login
	CComPtr<IGuestSession> guestSession;
	struct closer {
		CComPtr<IGuestSession> session;
		~closer() { if(session) session->Close(); }
	} closeSession = { nullptr };

	emit processMessage(
		tr("Login user '%1' on machine '%2")
		.arg(machine_.userName)
		.arg(machine_.machine)
	);
	
	bool sucessLogin = false;
	for (int relogin = 0; relogin < reloginCount; ++relogin)
	{
		guestSession = createGuestSession(
			session,
			machine_.userName,
			machine_.password
		);
		
		if (guestSession && waitFor([&guestSession, this]() {
				return waitForLogin(guestSession, ticPeriod);
			}, waitLoginPeriod)) {
			sucessLogin = true;
			break;
		}
	}
	
	if (!sucessLogin) {
		emit processMessage(
			tr("Login failed for user '%1' on machine '%2'")
			.arg(machine_.userName)
			.arg(machine_.machine)
		);

		return;
	}

	closeSession.session = guestSession;

	emit processMessage(
		tr("Success login user '%1' on machine '%2")
		.arg(machine_.userName)
		.arg(machine_.machine)
	);

	msleep(delayLogin);
	if (stop_) { return; }

	// Get volume information
	emit processMessage(tr("Get the volume list"));

	const auto volumeList = ::volumeList(guestSession);
	if (volumeList.isEmpty()) {
		emit processMessage(tr("Failed to get the volume list"));
		return;
	}
	if (stop_) { return; }

	VolumeInformationList volumeInformationList;
	volumeInformationList.reserve(volumeList.size());
	for (auto& volume : volumeList) {
		emit processMessage(tr("Get information for volume '%1'").arg(volume));
		const auto volumeSize = ::volumeSize(guestSession, volume);
		volumeInformationList.push_back({
			volume,
			volumeSize.size,
			volumeSize.freeSize
		});
		if (stop_) { return; }
	}
	
	emit volumeInformation(machine_.machine, volumeInformationList);
}