Example #1
0
/* virtual */
OP_STATUS
ES_TimeoutThread::EvaluateThread()
{
#ifdef DOCUMENT_EDIT_SUPPORT
	if (!IsCompleted() && scheduler->GetFramesDocument() && scheduler->GetFramesDocument()->GetDesignMode())
	{
		// We do not run timeouts or interval threads in designmode documents
		// but we need to keep track of them in case designmode is disabled
		is_completed = is_failed = TRUE;
	}
#endif // DOCUMENT_EDIT_SUPPORT

	if (!IsCompleted() && !IsFailed())
	{
		if (!is_started)
			timer_event->SetNextTimeout();

		OP_STATUS ret = ES_Thread::EvaluateThread();

		if (OpStatus::IsError(ret))
			return ret;
	}

	return OpStatus::OK;
}
Example #2
0
bool CItemState::Update(time_point tick)
{
    if (tick > GetEntryTime() + m_castTime && !IsCompleted())
    {
        m_interrupted = false;
        m_interruptable = false;
        auto PTarget = m_PEntity->IsValidTarget(m_targid, m_PItem->getValidTarget(), m_errorMsg);

        action_t action;

        // attempt to interrupt
        InterruptItem(action);

        if (!m_interrupted)
        {
            FinishItem(action);
        }
        m_PEntity->PAI->EventHandler.triggerListener("ITEM_USE", m_PEntity, m_PItem, &action);
        m_PEntity->loc.zone->PushPacket(m_PEntity, CHAR_INRANGE_SELF, new CActionPacket(action));
        Complete();
    }
    else if (IsCompleted() && tick > GetEntryTime() + m_castTime + m_animationTime)
    {
        m_PEntity->PAI->EventHandler.triggerListener("ITEM_STATE_EXIT", m_PEntity, m_PItem);
        return true;
    }
    return false;
}
bool CDespawnState::Update(time_point tick)
{
    if (tick > GetEntryTime() + 3s && !IsCompleted() && !(static_cast<CMobEntity*>(m_PEntity)->m_Behaviour & BEHAVIOUR_NO_DESPAWN))
    {
        static_cast<CMobEntity*>(m_PEntity)->OnDespawn(*this);
        Complete();
    }
    return IsCompleted();
}
Example #4
0
void CDownload::StartTrying()
{
	ASSERT( ! IsCompleted() || IsSeeding() );
	ASSERT( ! IsPaused() );
	if ( IsTrying() || IsPaused() || ( IsCompleted() && ! IsSeeding() ) )
		return;

	if ( ! Network.IsConnected() && ! Network.Connect( TRUE ) )
		return;

	m_tBegan = GetTickCount();
}
Example #5
0
CString CDownload::GetDownloadSources() const
{
	const int nTotalSources = GetSourceCount();
	const int nSources = GetEffectiveSourceCount();

	CString strText;
	if ( IsCompleted() )
	{
		if ( m_bVerify == TRI_TRUE )
			LoadString( strText, IDS_STATUS_VERIFIED );
		else if ( m_bVerify == TRI_FALSE )
			LoadString( strText, IDS_STATUS_UNVERIFIED );
	}
	else if ( nTotalSources == 0 )
	{
		LoadString( strText, IDS_STATUS_NOSOURCES );
	}
	else if ( nSources == nTotalSources )
	{
		CString strSource;
		LoadSourcesString( strSource, nSources );
		strText.Format( L"(%i %s)", nSources, (LPCTSTR)strSource );
	}
	else
	{
		CString strSource;
		LoadSourcesString( strSource, nTotalSources, true );
		strText.Format( L"(%i/%i %s)", nSources, nTotalSources, (LPCTSTR)strSource );
	}
	return strText;
}
Example #6
0
bool CMission::Reward (ICCItem *pData)

//	Reward
//
//	Reward the player for a mission success

{
    //	If we haven't yet called success, then do it now

    if (!IsCompleted())
        SetSuccess(NULL);

    //	Reward

    FireOnReward(pData);

    //	Set debriefed to true as a convenience

    m_fDebriefed = true;
    FireOnSetPlayerTarget(REASON_DEBRIEFED);
    CloseMission();

    //	Done

    return true;
}
Example #7
0
void CDownload::Remove()
{
	AbortTask();
	StopTrying();
	CloseTorrent();
	CloseTransfers();

	theApp.Message( MSG_NOTICE, IDS_DOWNLOAD_REMOVE, (LPCTSTR)GetDisplayName() );

	IsCompleted() ?
		CloseFile() :
		DeleteFile();

	DeletePreviews();

	if ( ! m_sPath.IsEmpty() )
	{
		DeleteFileEx( m_sPath + L".png", FALSE, FALSE, TRUE );
		DeleteFileEx( m_sPath + L".sav", FALSE, FALSE, TRUE );
		DeleteFileEx( m_sPath, FALSE, FALSE, TRUE );
		m_sPath.Empty();
	}

	Downloads.Remove( this );
}
Example #8
0
void SyncLock::WaitForUnlock()
{
	Unlock();
	while (!IsCompleted())
	{
		usleep(1000 * 20);
	}
}
Example #9
0
void CMagicState::Cleanup(time_point tick)
{
    if (!IsCompleted())
    {
        action_t action;
        m_PEntity->OnCastInterrupted(*this, action, MSGBASIC_IS_INTERRUPTED);
        m_PEntity->loc.zone->PushPacket(m_PEntity, CHAR_INRANGE_SELF, new CActionPacket(action));
    }
}
bool CMobSkillState::Update(time_point tick)
{
    if (tick > GetEntryTime() + m_castTime && !IsCompleted())
    {
        action_t action;
        m_PEntity->OnMobSkillFinished(*this, action);
        m_PEntity->loc.zone->PushPacket(m_PEntity, CHAR_INRANGE_SELF, new CActionPacket(action));
        auto delay = std::chrono::milliseconds(m_PSkill->getAnimationTime());
        m_finishTime = tick + delay;
        Complete();
    }
    if (IsCompleted() && tick > m_finishTime)
    {
        m_PEntity->PAI->EventHandler.triggerListener("WEAPONSKILL_STATE_EXIT", m_PEntity, m_PSkill->getID());
        return true;
    }
    return false;
}
Example #11
0
bool CMagicState::Update(time_point tick)
{
    if (tick > GetEntryTime() + m_castTime && !IsCompleted())
    {
        m_interrupted = false;
        auto PTarget = m_PEntity->IsValidTarget(m_targid, m_PSpell->getValidTarget(), m_errorMsg);
        MSGBASIC_ID msg = MSGBASIC_IS_INTERRUPTED;

        action_t action;

        if (HasMoved() || !CanCastSpell(PTarget))
        {
            m_interrupted = true;
        }
        else if (battleutils::IsParalyzed(m_PEntity))
        {
            msg = MSGBASIC_IS_PARALYZED;
            m_interrupted = true;
        }
        else if (battleutils::IsIntimidated(m_PEntity, static_cast<CBattleEntity*>(PTarget)))
        {
            msg = MSGBASIC_IS_INTIMIDATED;
            m_interrupted = true;
        }

        if (m_interrupted)
        {
            m_PEntity->OnCastInterrupted(*this, action, msg);
        }
        else
        {
            m_PEntity->OnCastFinished(*this,action);
        }
        m_PEntity->PAI->EventHandler.triggerListener("MAGIC_USE", m_PEntity, PTarget, m_PSpell.get(), &action);
        m_PEntity->loc.zone->PushPacket(m_PEntity, CHAR_INRANGE_SELF, new CActionPacket(action));
        Complete();
    }
    else if (IsCompleted() && tick > GetEntryTime() + m_castTime + std::chrono::milliseconds(m_PSpell->getAnimationTime()))
    {
        m_PEntity->PAI->EventHandler.triggerListener("MAGIC_STATE_EXIT", m_PEntity, m_PSpell.get());
        return true;
    }
    return false;
}
Example #12
0
ICCItem *CMission::GetProperty (const CString &sName)

//	GetProperty
//
//	Returns a property

{
    CCodeChain &CC = g_pUniverse->GetCC();

    if (strEquals(sName, PROPERTY_IS_ACTIVE))
        return CC.CreateBool(IsActive());

    else if (strEquals(sName, PROPERTY_IS_COMPLETED))
        return CC.CreateBool(IsCompleted());

    else if (strEquals(sName, PROPERTY_IS_DEBRIEFED))
        return CC.CreateBool(m_fDebriefed);

    else if (strEquals(sName, PROPERTY_IS_DECLINED))
        return CC.CreateBool(m_fDeclined);

    else if (strEquals(sName, PROPERTY_IS_FAILURE))
        return CC.CreateBool(IsFailure());

    else if (strEquals(sName, PROPERTY_IS_INTRO_SHOWN))
        return CC.CreateBool(m_fIntroShown);

    else if (strEquals(sName, PROPERTY_IS_OPEN))
        return CC.CreateBool(m_iStatus == statusOpen);

    else if (strEquals(sName, PROPERTY_IS_RECORDED))
        return CC.CreateBool(IsRecorded());

    else if (strEquals(sName, PROPERTY_IS_SUCCESS))
        return CC.CreateBool(IsSuccess());

    else if (strEquals(sName, PROPERTY_IS_UNAVAILABLE))
        return CC.CreateBool(IsUnavailable());

    else if (strEquals(sName, PROPERTY_NODE_ID))
        return (m_sNodeID.IsBlank() ? CC.CreateNil() : CC.CreateString(m_sNodeID));

    else if (strEquals(sName, PROPERTY_OWNER_ID))
    {
        if (m_pOwner.GetID() == OBJID_NULL)
            return CC.CreateNil();
        else
            return CC.CreateInteger(m_pOwner.GetID());
    }

    else if (strEquals(sName, PROPERTY_UNID))
        return CC.CreateInteger(m_pType->GetUNID());

    else
        return CSpaceObject::GetProperty(sName);
}
void CLR_RT_HeapBlock_I2CXAction::CopyBuffer( CLR_UINT8* dst, size_t length, size_t unit )
{
    NATIVE_PROFILE_CLR_I2C();
    ASSERT(unit<m_xActionUnits);
        
    if(!m_HalXAction || !IsCompleted())
    {
        return;
    }

    ::I2C_XActionUnit_CopyBuffer( m_HalXActionUnits[ unit ], dst, length );
}
Example #14
0
bool CRangeState::Update(time_point tick)
{
    if (tick > GetEntryTime() + m_aimTime && !IsCompleted())
    {
        auto PTarget = m_PEntity->IsValidTarget(m_targid, TARGET_ENEMY, m_errorMsg);

        CanUseRangedAttack(PTarget);
        if (m_startPos.x != m_PEntity->loc.p.x || m_startPos.y != m_PEntity->loc.p.y)
        {
            m_errorMsg = std::make_unique<CMessageBasicPacket>(m_PEntity, m_PEntity, 0, 0, MSGBASIC_MOVE_AND_INTERRUPT);
        }
        action_t action;
        if (m_errorMsg && m_errorMsg->getMessageID() != MSGBASIC_CANNOT_SEE)
        {
            action.id = m_PEntity->id;
            action.actiontype = ACTION_RANGED_INTERRUPT;

            actionList_t& actionList = action.getNewActionList();
            actionList.ActionTargetID = PTarget ? PTarget->id : m_PEntity->id;

            actionTarget_t& actionTarget = actionList.getNewActionTarget();
            actionTarget.animation = ANIMATION_RANGED;
            m_PEntity->pushPacket(m_errorMsg.release());
            m_PEntity->loc.zone->PushPacket(m_PEntity, CHAR_INRANGE_SELF, new CActionPacket(action));
        }
        else
        {
            m_errorMsg.reset();
            m_PEntity->OnRangedAttack(*this, action);
            m_PEntity->loc.zone->PushPacket(m_PEntity, CHAR_INRANGE_SELF, new CActionPacket(action));
        }
        Complete();
    }

    if (IsCompleted() && tick > GetEntryTime() + m_aimTime + 1.5s)
    {
        return true;
    }
    return false;
}
Example #15
0
bool CAbilityState::Update(time_point tick)
{
    if (!IsCompleted() && tick > GetEntryTime() + m_castTime)
    {
        if (CanUseAbility())
        {
            action_t action;
            m_PEntity->OnAbility(*this, action);
            m_PEntity->PAI->EventHandler.triggerListener("ABILITY_USE", m_PEntity, GetTarget(), m_PAbility.get(), &action);
            m_PEntity->loc.zone->PushPacket(m_PEntity, CHAR_INRANGE_SELF, new CActionPacket(action));
        }
        Complete();
    }

    if (IsCompleted() && tick > GetEntryTime() + m_castTime + m_PAbility->getAnimationTime())
    {
        m_PEntity->PAI->EventHandler.triggerListener("ABILITY_STATE_EXIT", m_PEntity, m_PAbility.get());
        return true;
    }

    return false;
}
Example #16
0
bool CDeathState::Update(time_point tick)
{
    if (IsCompleted() || m_PEntity->animation != ANIMATION_DEATH)
    {
        return true;
    }
    else if (tick > GetEntryTime() + m_deathTime && !IsCompleted())
    {
        Complete();
        m_PEntity->OnDeathTimer();
    }
    else if (m_PEntity->objtype == TYPE_PC && tick > GetEntryTime() + 8s && !IsCompleted() &&
             !m_raiseSent && m_PEntity->isDead())
    {
        auto PChar = static_cast<CCharEntity*>(m_PEntity);
        if (PChar->m_hasRaise)
        {
            PChar->pushPacket(new CRaiseTractorMenuPacket(PChar, TYPE_RAISE));
            m_raiseSent = true;
        }
    }
    return false;
}
Example #17
0
void DungeonPersistentState::UpdateEncounterState(EncounterCreditType type, uint32 creditEntry)
{
    DungeonEncounterMapBounds bounds = sObjectMgr.GetDungeonEncounterBounds(creditEntry);

    for (DungeonEncounterMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
    {
        DungeonEncounterEntry const* dbcEntry = itr->second->dbcEntry;

        if (itr->second->creditType == type && dbcEntry->Difficulty == GetDifficulty() && dbcEntry->mapId == GetMapId())
        {
            uint32 oldMask = m_completedEncountersMask;
            m_completedEncountersMask |= 1 << dbcEntry->encounterIndex;

            if ( m_completedEncountersMask != oldMask)
            {
                CharacterDatabase.PExecute("UPDATE instance SET encountersMask = '%u' WHERE id = '%u'", m_completedEncountersMask, GetInstanceId());

                DEBUG_LOG("DungeonPersistentState: Dungeon %s (Id %u) completed encounter %s", GetMap()->GetMapName(), GetInstanceId(), dbcEntry->encounterName[sWorld.GetDefaultDbcLocale()]);

                uint32 dungeonId = itr->second->lastEncounterDungeon;

                if (dungeonId)
                    DEBUG_LOG("DungeonPersistentState:: Dungeon %s (Id %u) completed last encounter %s", GetMap()->GetMapName(), GetInstanceId(), dbcEntry->encounterName[sWorld.GetDefaultDbcLocale()]);

                DungeonMap* dungeon = (DungeonMap*)GetMap();

                if (!dungeon || dungeon->GetPlayers().isEmpty())
                    return;

                Player* player = dungeon->GetPlayers().begin()->getSource();

                if (dungeon && player)
                    dungeon->PermBindAllPlayers(player, dungeon->IsRaidOrHeroicDungeon());

                SaveToDB();

                if (dungeon && player->GetGroup() && player->GetGroup()->isLFGGroup())
                {
                    sLFGMgr.DungeonEncounterReached(player->GetGroup());

                    if ((sWorld.getConfig(CONFIG_BOOL_LFG_ONLYLASTENCOUNTER) && dungeonId)
                            || IsCompleted())
                        sLFGMgr.SendLFGRewards(player->GetGroup());
                }
            }
            return;
        }
    }
}
void CMobSkillState::Cleanup(time_point tick)
{
    if (!IsCompleted())
    {
        action_t action;
        action.id = m_PEntity->id;
        action.actiontype = ACTION_MOBABILITY_INTERRUPT;

        actionList_t& actionList = action.getNewActionList();
        actionList.ActionTargetID = m_PEntity->id;

        actionTarget_t& actionTarget = actionList.getNewActionTarget();
        actionTarget.animation = m_PSkill->getID();

        m_PEntity->loc.zone->PushPacket(m_PEntity, CHAR_INRANGE, new CActionPacket(action));
    }
}
Example #19
0
void CDownload::Resume()
{
	if ( IsCompleted() && ! IsSeeding() )
		return;

	if ( ! IsPaused() )
	{
		StartTrying();
		return;
	}

	theApp.Message( MSG_NOTICE, IDS_DOWNLOAD_RESUMED, (LPCTSTR)GetDisplayName() );

	if ( IsFileOpen() )
	{
		for ( POSITION posSource = GetIterator(); posSource; )
		{
			CDownloadSource* pSource = GetNext( posSource );

			pSource->OnResume();
		}
	}

	m_bPaused				= FALSE;
	m_bTempPaused			= FALSE;
	m_bTorrentTrackerError	= FALSE;
	m_tReceived				= GetTickCount();

	// Try again
	ClearFileError();

	// Obsolete: Remove this
	//if ( IsTorrent() )
	//{
	//	if ( Downloads.GetTryingCount( true ) < Settings.BitTorrent.DownloadTorrents )
	//		SetStartTimer();
	//}
	//else
	//{
	//	if ( Downloads.GetTryingCount() < ( Settings.Downloads.MaxFiles + Settings.Downloads.MaxFileSearches ) )
	//		SetStartTimer();
	//}

	SetModified();
}
Example #20
0
void CDownload::StopTrying()
{
	if ( ! IsTrying() || ( IsCompleted() && ! IsSeeding() ) )
		return;

	m_tBegan = 0;
	m_bDownloading = false;

	// If m_bTorrentRequested = TRUE, sends Stop
	// CloseTorrent() additionally closes uploads
	if ( IsTorrent() )
		CloseTorrent();

	CloseTransfers();
	CloseFile();
	StopSearch();
	SetModified();
}
Example #21
0
bool CWeaponSkillState::Update(time_point tick)
{
    if (!IsCompleted())
    {
        SpendCost();
        action_t action;
        m_PEntity->OnWeaponSkillFinished(*this, action);
        m_PEntity->loc.zone->PushPacket(m_PEntity, CHAR_INRANGE_SELF, new CActionPacket(action));
        auto delay = m_PSkill->getAnimationTime();
        m_finishTime = tick + delay;
        Complete();
    }
    else if (tick > m_finishTime)
    {
        m_PEntity->PAI->EventHandler.triggerListener("WEAPONSKILL_STATE_EXIT", m_PEntity, m_PSkill->getID());
        return true;
    }
    return false;
}
Example #22
0
    void ActionGroup::Update(const long double& dt)
    {
        if (IsPaused() || IsCompleted())
        {
            return;
        }
        if (IsEmpty())
        {
            Completed = true;
        }

        Completed = true;
        while (CurrentAction != ActionQueue.end())
        {
            (*CurrentAction)->Update(dt);
            if ((*CurrentAction)->IsCompleted())
            {
                ++CurrentAction;
                continue;
            }
            //If we have not completed ALL of the actions in the group, the group has not finished.
            Completed = false;
            ++CurrentAction;
        }
        if (Completed)
        {
            if (Looping())
            {
                Restart();
            }
            else
            {
                Clear();
            }
        }
        CurrentAction = ActionQueue.begin();
    }
void DungeonPersistentState::UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Player* player)
{
    DungeonEncounterList const* encounterList = sObjectMgr.GetDungeonEncounterList(GetMapId(), GetDifficulty());

    if (!encounterList)
        return;

    for (DungeonEncounterList::const_iterator itr = encounterList->begin(); itr != encounterList->end(); ++itr)
    {
        if ((*itr)->creditType == type && (*itr)->creditEntry == creditEntry)
        {
            uint32 oldMask = m_completedEncountersMask;
            m_completedEncountersMask |= 1 << (*itr)->dbcEntry->encounterIndex;
            if ( m_completedEncountersMask != oldMask)
            {
                CharacterDatabase.PExecute("UPDATE instance SET encountersMask = '%u' WHERE id = '%u'", m_completedEncountersMask, GetInstanceId());

                DEBUG_LOG("DungeonPersistentState: Dungeon %s (Id %u) completed encounter %s", GetMap()->GetMapName(), GetInstanceId(), (*itr)->dbcEntry->encounterName[sWorld.GetDefaultDbcLocale()]);

                uint32 dungeonId = (*itr)->lastEncounterDungeon;
                if (dungeonId)
                    DEBUG_LOG("DungeonPersistentState:: Dungeon %s (Id %u) completed last encounter %s", GetMap()->GetMapName(), GetInstanceId(), (*itr)->dbcEntry->encounterName[sWorld.GetDefaultDbcLocale()]);

                if (IsCompleted())
                    sLFGMgr.SendLFGRewards(player);

                DungeonMap* dungeon = (DungeonMap*)GetMap();

                if (dungeon && player)
                    dungeon->PermBindAllPlayers(player, dungeon->IsRaidOrHeroicDungeon());
                SaveToDB();
            }
            return;
        }
    }
}
Example #24
0
CString CDownload::GetDownloadStatus() const
{
	CString strText;

	if ( m_bClearing )	// Briefly marked for removal
	{
		LoadString( strText, IDS_STATUS_CLEARING );
	}
	else if ( IsPaused() )
	{
		if ( GetFileError() == ERROR_SUCCESS || IsSeeding() )
			LoadString( strText, IDS_STATUS_PAUSED );
		else
			LoadString( strText, IsMoving() ? IDS_STATUS_CANTMOVE : IDS_STATUS_FILEERROR );
	}
	else if ( IsCompleted() )
	{
		if ( IsSeeding() )
			LoadString( strText, m_bTorrentTrackerError ? IDS_STATUS_TRACKERDOWN : IDS_STATUS_SEEDING );
		else
			LoadString( strText, IDS_STATUS_COMPLETED );
	}
	else if ( IsMoving() )
	{
		LoadString( strText, IDS_STATUS_MOVING );
	}
	else if ( IsStarted() && GetProgress() == 100.0f )
	{
		LoadString( strText, IDS_STATUS_VERIFYING );
	}
	else if ( ! IsTrying() )
	{
		LoadString( strText, IDS_STATUS_QUEUED );
	}
	else if ( IsDownloading() )
	{
		const DWORD nTime = GetTimeRemaining();

		if ( nTime == 0xFFFFFFFF )
			LoadString( strText, IDS_STATUS_ACTIVE );	// IDS_STATUS_DOWNLOADING
		else if ( nTime == 0 )
			LoadString( strText, IDS_STATUS_DOWNLOADING );
		else if ( nTime > 86400 )
			strText.Format( L"%u:%.2u:%.2u:%.2u", nTime / 86400, ( nTime / 3600 ) % 24, ( nTime / 60 ) % 60, nTime % 60 );
		else
			strText.Format( L"%u:%.2u:%.2u", nTime / 3600, ( nTime / 60 ) % 60, nTime % 60 );
	}
	else if ( GetEffectiveSourceCount() > 0 )
	{
		LoadString( strText, IDS_STATUS_PENDING );
	}
	else if ( IsTorrent() )
	{
		if ( GetTaskType() == dtaskAllocate )
			LoadString( strText, IDS_STATUS_CREATING );
		else if ( m_bTorrentTrackerError )
			LoadString( strText, IDS_STATUS_TRACKERDOWN );
		else
			LoadString( strText, IDS_STATUS_TORRENT );
	}
	else // Inactive
	{
		LoadString( strText, IDS_STATUS_QUEUED );
	}

	return strText;
}
Example #25
0
void CDownload::OnRun()
{
	// Set the currently downloading state
	// (Used to optimize display in Ctrl/Wnd functions)
	m_bDownloading = false;

	const DWORD tNow = GetTickCount();

	if ( ! IsPaused() )
	{
		if ( GetFileError() != ERROR_SUCCESS )
		{
			// File or disk errors
			Pause( FALSE );
		}
		else if ( IsMoving() )
		{
			if ( ! IsCompleted() && ! IsTasking() )
				OnDownloaded();
		}
		else if ( IsTrying() || IsSeeding() )
		{
			// This download is trying to download
			if ( HasHash() )		// Workaround for direct downloads stuck "verifying"
				OpenDownload();

			// Dead Download Check: if download appears dead, give up and allow another to start.
			// Incomplete, and trying for at least 3 hours:
			if ( ! IsCompleted() && tNow > GetStartTimer() + ( 3 * 60 * 60 * 1000 ) )
			{
				const DWORD tHoursToTry = min( ( GetEffectiveSourceCount() + 49u ) / 50u, 9lu ) + Settings.Downloads.StarveGiveUp;

				// No new data for 5-14 hours
				if ( tNow > m_tReceived + ( tHoursToTry * 60 * 60 * 1000 ) )
				{
					if ( IsTorrent() )
					{
						// Are there other torrents that should start?
						if ( Downloads.GetTryingCount( TRUE ) >= Settings.BitTorrent.DownloadTorrents )
						{
							StopTrying();		// Give up for now, try again later
							return;
						}
					}
					else	// Regular download
					{
						// Are there other downloads that should try?
						if ( Downloads.GetTryingCount() >= ( Settings.Downloads.MaxFiles + Settings.Downloads.MaxFileSearches ) )
						{
							StopTrying();		// Give up for now, try again later
							return;
						}
					}
				}
			}
			// End Dead Download Check

			// Run the download
			RunTorrent( tNow );
			RunSearch( tNow );
			RunValidation();

			if ( IsSeeding() )
			{
				// Mark as collapsed to get correct heights when dragging files
				if ( ! Settings.General.DebugBTSources && m_bExpanded )
					m_bExpanded = FALSE;
			}
			else // if ( ! IsMoving() )
			{
				if ( IsComplete() && IsFileOpen() )
				{
					if ( IsFullyVerified() )
						OnDownloaded();
				}
				else if ( CheckTorrentRatio() )
				{
					if ( ! Network.IsConnected() )
					{
						StopTrying();
						return;
					}

					StartTransfersIfNeeded( tNow );
				}
			}

			// Calculate current downloading state
			if ( HasActiveTransfers() )
				m_bDownloading = true;

			// Mutate regular download to torrent download
			if ( Settings.BitTorrent.EnablePromote && m_oBTH && ! IsTorrent() )
			{
				m_pTorrent.Clear();
				m_pTorrent.m_oMD5	= m_oMD5;
				m_pTorrent.m_oBTH	= m_oBTH;
				m_pTorrent.m_oSHA1	= m_oSHA1;
				m_pTorrent.m_oED2K	= m_oED2K;
				m_pTorrent.m_oTiger	= m_oTiger;
				m_pTorrent.m_sName	= m_sName;
				m_pTorrent.m_nSize	= m_nSize;
				SetTorrent();
			}
		}
		else if ( ! IsCompleted() && m_bVerify != TRI_TRUE )
		{
			// This is pending download
		//	// If this download isn't trying to download, see if it can try
		//	if ( IsDownloading() )
		//		SetStartTimer();	// This download was probably started by a push/etc

			if ( Network.IsConnected() )
			{
				// Have extra regular downloads 'trying' so when a new slot is ready,
				// a download has sources and is ready to go.
				if ( Downloads.GetTryingCount() < ( Settings.Downloads.MaxFiles + Settings.Downloads.MaxFileSearches ) )
				{
					if ( ! IsTorrent() ||
						Downloads.GetTryingCount( true ) < Settings.BitTorrent.DownloadTorrents )
					{
						// Torrents only try when 'ready to go'. (Reduce tracker load)
						Resume();
					}
				}
			}
		//	else
		//		ASSERT( ! IsTrying() );
		}
	}

	// Don't save Downloads with many sources too often, since it's slow
	if ( tNow >= m_tSaved + ( GetCount() > 20 ? 5 * Settings.Downloads.SaveInterval : Settings.Downloads.SaveInterval ) )
	{
		if ( IsModified() )
		{
			FlushFile();
			if ( Save() )
				m_tSaved = tNow;
		}
	}
}
Example #26
0
BOOL CDownload::SeedTorrent()
{
	if ( IsMoving() || IsCompleted() )
		return FALSE;

	ASSERT( IsFileOpen() == FALSE );
	if ( IsFileOpen() )
		return FALSE;

	ASSERT( m_pTorrent.GetCount() );

	augment::auto_ptr< CFragmentedFile > pFragmentedFile( new CFragmentedFile );
	if ( ! pFragmentedFile.get() )
		return FALSE;	// Out of memory

	if ( ! pFragmentedFile->Open( m_pTorrent, FALSE ) )
	{
		SetFileError( pFragmentedFile->GetFileError(), pFragmentedFile->GetFileErrorString() );
		return FALSE;
	}

	AttachFile( pFragmentedFile.release() );

	if ( IsSingleFileTorrent() )
	{
		// Refill missing hashes for single-file torrent
		const CBTInfo::CBTFile* pBTFile = m_pTorrent.m_pFiles.GetHead();
		if ( ! m_pTorrent.m_oSHA1 && pBTFile->m_oSHA1 )
			m_pTorrent.m_oSHA1 = pBTFile->m_oSHA1;
		if ( ! m_pTorrent.m_oTiger && pBTFile->m_oTiger )
			m_pTorrent.m_oTiger = pBTFile->m_oTiger;
		if ( ! m_pTorrent.m_oED2K && pBTFile->m_oED2K )
			m_pTorrent.m_oED2K = pBTFile->m_oED2K;
		if ( ! m_pTorrent.m_oMD5 && pBTFile->m_oMD5 )
			m_pTorrent.m_oMD5 = pBTFile->m_oMD5;

		// Refill missed hash for library file
		CQuickLock oLock( Library.m_pSection );
		if ( CLibraryFile* pLibraryFile = LibraryMaps.LookupFileByPath( pBTFile->FindFile() ) )
		{
			if ( ! pLibraryFile->m_oBTH && m_oBTH )
			{
				Library.RemoveFile( pLibraryFile );
				pLibraryFile->m_oBTH = m_oBTH;
				Library.AddFile( pLibraryFile );
			}
		}
	}

	// Refill missing hashes
	if ( ! m_oSHA1 && m_pTorrent.m_oSHA1 )
		m_oSHA1 = m_pTorrent.m_oSHA1;
	if ( ! m_oTiger && m_pTorrent.m_oTiger )
		 m_oTiger = m_pTorrent.m_oTiger;
	if ( ! m_oED2K && m_pTorrent.m_oED2K )
		m_oED2K = m_pTorrent.m_oED2K;
	if ( ! m_oMD5 && m_pTorrent.m_oMD5 )
		m_oMD5 = m_pTorrent.m_oMD5;

	GenerateTorrentDownloadID();

	m_bSeeding = TRUE;
	m_bComplete = true;
	m_tCompleted = GetTickCount();
	m_bVerify = TRI_TRUE;

	memset( m_pTorrentBlock, TRI_TRUE, m_nTorrentBlock );
	m_nTorrentSuccess = m_nTorrentBlock;

	MakeComplete();
	ResetVerification();

	return TRUE;
}
Example #27
0
/* virtual */
OP_STATUS
ES_JavascriptURLThread::EvaluateThread()
{
	OP_STATUS ret = OpStatus::OK;

	switch (eval_state)
	{
	case STATE_INITIAL:
		{
			eval_state = STATE_SET_PROGRAM;

#ifdef USER_JAVASCRIPT
			DOM_Environment *environment = scheduler->GetFramesDocument()->GetDOMEnvironment();

			RETURN_IF_ERROR(environment->HandleJavascriptURL(this));

			if (IsBlocked())
				return OpStatus::OK;
#endif // USER_JAVASCRIPT
		}
		// fall through

	case STATE_SET_PROGRAM:
		if (source)
		{
			ES_ProgramText program_text;

			program_text.program_text = source;
			program_text.program_text_length = uni_strlen(source);

			ES_Runtime *runtime = scheduler->GetRuntime();

			ES_Program *program;
			OP_STATUS status;

			ES_Runtime::CompileProgramOptions options;
			options.generate_result = TRUE;
			options.global_scope = FALSE;
			options.script_type = SCRIPT_TYPE_JAVASCRIPT_URL;
			options.when = UNI_L("while loading");
			options.script_url = &url;
#ifdef ECMASCRIPT_DEBUGGER
			options.reformat_source = g_ecmaManager->GetWantReformatScript(runtime);
#endif // ECMASCRIPT_DEBUGGER

			if (OpStatus::IsSuccess(status = runtime->CompileProgram(&program_text, 1, &program, options)))
				if (program)
					SetProgram(program);
				else
					status = OpStatus::ERR;

			if (OpStatus::IsMemoryError(status))
			{
				is_completed = is_failed = TRUE;
				return status;
			}
			else if (OpStatus::IsError(status))
			{
				is_completed = is_failed = TRUE;
				return OpStatus::OK;
			}
		}
		eval_state = STATE_EVALUATE;
		// fall through

	case STATE_EVALUATE:
		{
			ret = ES_Thread::EvaluateThread();
			if (OpStatus::IsError(ret))
			{
				eval_state = STATE_HANDLE_RESULT;
				is_completed = TRUE;
				break;
			}
			else if (IsCompleted())
			{
				if (IsFailed())
				{
					eval_state = STATE_DONE;
					break;
				}
				else
#ifdef USER_JAVASCRIPT
					eval_state = STATE_SEND_USER_JS_AFTER;
#else // USER_JAVASCRIPT
					eval_state = STATE_HANDLE_RESULT;
#endif // USER_JAVASCRIPT
			}
			else
				break;
		}
		// fall through

#ifdef USER_JAVASCRIPT
	case STATE_SEND_USER_JS_AFTER:
		{
			DOM_Environment *environment = scheduler->GetFramesDocument()->GetDOMEnvironment();

			RETURN_IF_ERROR(environment->HandleJavascriptURLFinished(this));

			eval_state = STATE_HANDLE_RESULT;

			if (IsBlocked())
			{
				is_completed = FALSE;
				break;
			}
		}
		// fall through
#endif // USER_JAVASCRIPT

	case STATE_HANDLE_RESULT:
		{
			is_completed = TRUE;
			const uni_char *use_result = NULL;

#ifdef USER_JAVASCRIPT
			if (has_result)
				use_result = result;
			else
#endif // USER_JAVASCRIPT
				if (ReturnedValue())
				{
					ES_Value return_value;

					RETURN_IF_ERROR(GetReturnedValue(&return_value));

					if (return_value.type == VALUE_STRING)
						use_result = return_value.value.string;
				}

			FramesDocument *frames_doc = GetFramesDocument();
			OP_ASSERT(frames_doc); // Since we're executing we must be in a document
			if (use_result)
			{
				if (write_result_to_document)
				{
					// The HTML5 spec says that we should load this data exactly as if it had come
					// from an HTTP connection with content type text/html and status 200. This
					// is a very bad approximation of that.
					BOOL is_busy = scheduler->IsDraining() || !frames_doc->IsCurrentDoc();
					write_result_to_document = FALSE; // Since it's enough to do it once
					frames_doc->SetWaitForJavascriptURL(FALSE);

					if (!is_busy)
						if (HLDocProfile *hld_profile = frames_doc->GetHLDocProfile())
							is_busy = hld_profile->GetESLoadManager()->GetScriptGeneratingDoc();

					if (!is_busy)
					{
						if (GetOriginInfo().open_in_new_window)
							RETURN_IF_ERROR(DOM_Environment::OpenWindowWithData(use_result, frames_doc, this, GetOriginInfo().is_user_requested));
						else
						{
							// The ESOpen()/ESClose() calls are just done in order to create an
							// empty document in The Right Way(tm) in order to parse some data
							// into it as if it had been loaded from a URL, and not to set up
							// a document.write call like they are usually used for.
							ESDocException doc_exception; // Ignored
							RETURN_IF_ERROR(frames_doc->ESOpen(scheduler->GetRuntime(), &url, is_reload, NULL, NULL, &doc_exception));

							FramesDocument *new_frames_doc = frames_doc->GetDocManager()->GetCurrentDoc();
							RETURN_IF_ERROR(new_frames_doc->ESClose(scheduler->GetRuntime()));

							SetBlockType(ES_BLOCK_NONE);

							if (frames_doc != new_frames_doc)
								RETURN_IF_ERROR(new_frames_doc->GetLogicalDocument()->ParseHtmlFromString(use_result, uni_strlen(use_result), FALSE, FALSE, FALSE));
							else
								OP_ASSERT(!"ESOpen might have failed, but if it didn't then we're stuck with a hung thread in a document and nothing will work");

							new_frames_doc->ESStoppedGeneratingDocument();
						}
					}
				}

				if (write_result_to_url)
				{
					if (want_utf8)
					{
						UTF16toUTF8Converter converter;

						unsigned length = uni_strlen(use_result) * sizeof source[0], needed = converter.BytesNeeded(use_result, length);
						converter.Reset();

						char *data;
						if (needed < g_memory_manager->GetTempBufLen())
							data = (char *) g_memory_manager->GetTempBuf();
						else
							data = OP_NEWA(char, needed);

						if (!data)
						{
							ret = OpStatus::ERR_NO_MEMORY;
							break;
						}
						else
						{
							int read, written = converter.Convert(use_result, length, data, needed, &read);

							url.WriteDocumentData(URL::KNormal, data, written);
							url.WriteDocumentDataFinished();

							if (data != g_memory_manager->GetTempBuf())
								OP_DELETEA(data);
						}
					}
					else
					{
						url.WriteDocumentData(URL::KNormal, use_result, uni_strlen(use_result));
						url.WriteDocumentDataFinished();
					}
				}
			}
			else if (write_result_to_document)
			{
				// The HTML5 spec says this should be handled as a HTTP status 204, NO_CONTENT
				frames_doc->GetMessageHandler()->PostMessage(MSG_URL_LOADING_FAILED, url.Id(), DH_ERRSTR(SI,ERR_HTTP_NO_CONTENT));
				frames_doc->SetWaitForJavascriptURL(FALSE);
				write_result_to_document = FALSE; // Since it's done and we don't want to do it again.
			}

			eval_state = STATE_DONE;
		}
Example #28
0
ICCItem *CMission::GetProperty (CCodeChainCtx &Ctx, const CString &sName)

//	GetProperty
//
//	Returns a property

	{
	CCodeChain &CC = g_pUniverse->GetCC();

	if (strEquals(sName, PROPERTY_ACCEPTED_ON))
		return (m_fAcceptedByPlayer ? CC.CreateInteger(m_dwAcceptedOn) : CC.CreateNil());

	else if (strEquals(sName, PROPERTY_CAN_BE_DELETED))
		return CC.CreateBool(m_pType->CanBeDeleted());

	else if (strEquals(sName, PROPERTY_DEBRIEFER_ID))
		{
		if (m_pDebriefer.GetID() != OBJID_NULL)
			return CC.CreateInteger(m_pDebriefer.GetID());
		else if (m_pOwner.GetID() != OBJID_NULL)
			return CC.CreateInteger(m_pOwner.GetID());
		else
			return CC.CreateNil();
		}

	else if (strEquals(sName, PROPERTY_FORCE_UNDOCK_AFTER_DEBRIEF))
		return CC.CreateBool(m_pType->ForceUndockAfterDebrief());

	else if (strEquals(sName, PROPERTY_IS_ACTIVE))
		return CC.CreateBool(IsActive());

	else if (strEquals(sName, PROPERTY_IS_COMPLETED))
		return CC.CreateBool(IsCompleted());

	else if (strEquals(sName, PROPERTY_IS_DEBRIEFED))
		return CC.CreateBool(m_fDebriefed);

	else if (strEquals(sName, PROPERTY_IS_DECLINED))
		return CC.CreateBool(m_fDeclined);

	else if (strEquals(sName, PROPERTY_IS_FAILURE))
		return CC.CreateBool(IsFailure());

	else if (strEquals(sName, PROPERTY_IS_INTRO_SHOWN))
		return CC.CreateBool(m_fIntroShown);

	else if (strEquals(sName, PROPERTY_IS_OPEN))
		return CC.CreateBool(m_iStatus == statusOpen);

	else if (strEquals(sName, PROPERTY_IS_RECORDED))
		return CC.CreateBool(IsRecorded());

	else if (strEquals(sName, PROPERTY_IS_SUCCESS))
		return CC.CreateBool(IsSuccess());

	else if (strEquals(sName, PROPERTY_IS_UNAVAILABLE))
		return CC.CreateBool(IsUnavailable());

	else if (strEquals(sName, PROPERTY_NAME))
		return CC.CreateString(m_sTitle);

	else if (strEquals(sName, PROPERTY_NODE_ID))
		return (m_sNodeID.IsBlank() ? CC.CreateNil() : CC.CreateString(m_sNodeID));

	else if (strEquals(sName, PROPERTY_OWNER_ID))
		{
		if (m_pOwner.GetID() == OBJID_NULL)
			return CC.CreateNil();
		else
			return CC.CreateInteger(m_pOwner.GetID());
		}

	else if (strEquals(sName, PROPERTY_SUMMARY))
		return CC.CreateString(m_sInstructions);

	else if (strEquals(sName, PROPERTY_UNID))
		return CC.CreateInteger(m_pType->GetUNID());

	else
		return CSpaceObject::GetProperty(Ctx, sName);
	}
Example #29
0
bool CAbilityState::CanChangeState()
{
    return IsCompleted();
}
Example #30
0
void CMission::CompleteMission (ECompletedReasons iReason)

//	CompleteMission
//
//	Complete the mission

{
    if (IsCompleted())
        return;

    bool bIsPlayerMission = (m_iStatus == statusAccepted);

    //	Handle player missions differently

    if (bIsPlayerMission)
    {
        //	Mission failure

        if (iReason == completeFailure || iReason == completeDestroyed)
        {
            m_iStatus = statusPlayerFailure;

            //	Tell the player that we failed

            CSpaceObject *pPlayer = g_pUniverse->GetPlayer();
            if (pPlayer)
            {
                CString sMessage;
                if (!Translate(CONSTLIT("FailureMsg"), &sMessage))
                    sMessage = CONSTLIT("Mission failed!");

                pPlayer->SendMessage(NULL, sMessage);
            }

            //	Set the player target (mission usually sets the target back to the
            //	station that gave the mission).

            FireOnSetPlayerTarget(REASON_FAILURE);
        }

        //	Mission success

        else if (iReason == completeSuccess)
        {
            m_iStatus = statusPlayerSuccess;

            //	Tell the player that we succeeded

            CSpaceObject *pPlayer = g_pUniverse->GetPlayer();
            if (pPlayer)
            {
                CString sMessage;
                if (!Translate(CONSTLIT("SuccessMsg"), &sMessage))
                    sMessage = CONSTLIT("Mission complete!");

                pPlayer->SendMessage(NULL, sMessage);
            }

            //	Set the player target (mission usually sets the target back to the
            //	station that gave the mission).

            FireOnSetPlayerTarget(REASON_SUCCESS);
        }
    }

    //	Set status for non-player missions

    else
    {
        if (iReason == completeFailure || iReason == completeDestroyed)
            m_iStatus = statusFailure;
        else if (iReason == completeSuccess)
            m_iStatus = statusSuccess;

        //	For non-player missions we can close now. (For players we wait until
        //	debrief.)

        CloseMission();
    }
}