示例#1
0
文件: HttpHelper.cpp 项目: azalpy/sdk
HttpHelper::HttpHelper(int status, const char* reason)
{
	InitStatus();
	SetStatus(status, reason);
}
示例#2
0
void HTTPSocket::SendResponse(const std::string& status_num, const std::string& status_text) {
	SetStatus(status_num, status_text);
	SendResponse();
}
示例#3
0
bool
Job::TerminateSuccess()
{
	SetStatus( STATUS_DONE );
	return true;
} 
示例#4
0
void BattleGroundAB::Update(time_t diff)
{
    BattleGround::Update(diff);

    if( GetStatus() == STATUS_WAIT_JOIN && GetPlayersSize() )
    {
        ModifyStartDelayTime(diff);

        if( !(m_Events & 0x01) )
        {
            m_Events |= 0x01;

            sLog.outDebug("Arathi Basin: entering state STATUS_WAIT_JOIN ...");

            // despawn banners, auras and buffs
            for (int obj = BG_AB_OBJECT_BANNER_NEUTRAL; obj < BG_AB_DYNAMIC_NODES_COUNT * 8; ++obj)
                SpawnBGObject(obj, RESPAWN_ONE_DAY);
            for (int i = 0; i < BG_AB_DYNAMIC_NODES_COUNT * 3; ++i)
                SpawnBGObject(BG_AB_OBJECT_SPEEDBUFF_STABLES + i, RESPAWN_ONE_DAY);

            // Starting doors
            SpawnBGObject(BG_AB_OBJECT_GATE_A, RESPAWN_IMMEDIATELY);
            SpawnBGObject(BG_AB_OBJECT_GATE_H, RESPAWN_IMMEDIATELY);
            DoorClose(BG_AB_OBJECT_GATE_A);
            DoorClose(BG_AB_OBJECT_GATE_H);

            // Starting base spirit guides
            _NodeOccupied(BG_AB_SPIRIT_ALIANCE,ALLIANCE);
            _NodeOccupied(BG_AB_SPIRIT_HORDE,HORDE);

            SetStartDelayTime(START_DELAY0);
        }
        // After 1 minute, warning is signalled
        else if( GetStartDelayTime() <= START_DELAY1 && !(m_Events & 0x04) )
        {
            m_Events |= 0x04;
            SendMessageToAll(GetMangosString(LANG_BG_AB_ONEMINTOSTART));
        }
        // After 1,5 minute, warning is signalled
        else if( GetStartDelayTime() <= START_DELAY2 && !(m_Events & 0x08) )
        {
            m_Events |= 0x08;
            SendMessageToAll(GetMangosString(LANG_BG_AB_HALFMINTOSTART));
        }
        // After 2 minutes, gates OPEN ! x)
        else if( GetStartDelayTime() < 0 && !(m_Events & 0x10) )
        {
            m_Events |= 0x10;
            SendMessageToAll(GetMangosString(LANG_BG_AB_STARTED));

            // spawn neutral banners
            for (int banner = BG_AB_OBJECT_BANNER_NEUTRAL, i = 0; i < 5; banner += 8, ++i)
                SpawnBGObject(banner, RESPAWN_IMMEDIATELY);
            for (int i = 0; i < BG_AB_DYNAMIC_NODES_COUNT; ++i)
            {
                //randomly select buff to spawn
                uint8 buff = urand(0, 2);
                SpawnBGObject(BG_AB_OBJECT_SPEEDBUFF_STABLES + buff + i * 3, RESPAWN_IMMEDIATELY);
            }
            DoorOpen(BG_AB_OBJECT_GATE_A);
            DoorOpen(BG_AB_OBJECT_GATE_H);

            PlaySoundToAll(SOUND_BG_START);
            SetStatus(STATUS_IN_PROGRESS);

            for(BattleGroundPlayerMap::const_iterator itr = GetPlayers().begin(); itr != GetPlayers().end(); ++itr)
                if(Player* plr = objmgr.GetPlayer(itr->first))
                    plr->RemoveAurasDueToSpell(SPELL_PREPARATION);
        }

    }
    else if( GetStatus() == STATUS_IN_PROGRESS )
    {
        // 3 sec delay to spawn new banner instead previous despawned one
        for (int node = 0; node < BG_AB_DYNAMIC_NODES_COUNT; ++node)
            if( m_BannerTimers[node].timer )
                if( m_BannerTimers[node].timer > diff )
                    m_BannerTimers[node].timer -= diff;
                else
                {
                    m_BannerTimers[node].timer = 0;
                    _CreateBanner(node, m_BannerTimers[node].type, m_BannerTimers[node].teamIndex, false);
                }

        // 1-minute to occupy a node from contested state
        for (int node = 0; node < BG_AB_DYNAMIC_NODES_COUNT; ++node)
            if( m_NodeTimers[node] )
                if( m_NodeTimers[node] > diff )
                    m_NodeTimers[node] -= diff;
                else
                {
                    m_NodeTimers[node] = 0;
                    // Change from contested to occupied !
                    uint8 teamIndex = m_Nodes[node]-1;
                    m_prevNodes[node] = m_Nodes[node];
                    m_Nodes[node] += 2;
                    // burn current contested banner
                    _DelBanner(node, BG_AB_NODE_TYPE_CONTESTED, teamIndex);
                    // create new occupied banner
                    _CreateBanner(node, BG_AB_BODE_TYPE_OCCUPIED, teamIndex, true);
                    _SendNodeUpdate(node);
                    _NodeOccupied(node,(teamIndex == 0) ? ALLIANCE:HORDE);
                    // Message to chatlog
                    char buf[256];
                    uint8 type = (teamIndex == 0) ? CHAT_MSG_BG_SYSTEM_ALLIANCE : CHAT_MSG_BG_SYSTEM_HORDE;
                    sprintf(buf, GetMangosString(LANG_BG_AB_NODE_TAKEN), (teamIndex == 0) ? GetMangosString(LANG_BG_AB_ALLY) : GetMangosString(LANG_BG_AB_HORDE), _GetNodeName(node));
                    WorldPacket data;
                    ChatHandler::FillMessageData(&data, NULL, type, LANG_UNIVERSAL, NULL, 0, buf, NULL);
                    SendPacketToAll(&data);
                    PlaySoundToAll((teamIndex == 0) ? SOUND_NODE_CAPTURED_ALLIANCE : SOUND_NODE_CAPTURED_HORDE);
                }

        // Accumulate points
        for (int team = 0; team < 2; ++team)
        {
            int points = 0;
            // Go throught all nodes
            for (int node = 0; node < BG_AB_DYNAMIC_NODES_COUNT; ++node)
                if( m_Nodes[node] == team + 3 )
                    ++points;
            if( !points )
                continue;
            m_lastTick[team] += diff;
            if( m_lastTick[team] > BG_AB_TickIntervals[points] )
            {
                m_lastTick[team] -= BG_AB_TickIntervals[points];
                m_TeamScores[team] += BG_AB_TickPoints[points];
                m_HonorScoreTics[team] += BG_AB_TickPoints[points];
                m_ReputationScoreTics[team] += BG_AB_TickPoints[points];
                if( m_ReputationScoreTics[team] >= 200 )
                {
                    (team == BG_TEAM_ALLIANCE) ? RewardReputationToTeam(509, 10, ALLIANCE) : RewardReputationToTeam(510, 10, HORDE);
                    m_ReputationScoreTics[team] -= 200;
                }
                if( m_HonorScoreTics[team] >= BG_HONOR_SCORE_TICKS )
                {
                    (team == BG_TEAM_ALLIANCE) ? RewardHonorToTeam(20, ALLIANCE) : RewardHonorToTeam(20, HORDE);
                    m_HonorScoreTics[team] -= BG_HONOR_SCORE_TICKS;
                }
                if( !m_IsInformedNearVictory && m_TeamScores[team] > 1800 )
                {
                    if( team == BG_TEAM_ALLIANCE )
                        SendMessageToAll(GetMangosString(LANG_BG_AB_A_NEAR_VICTORY));
                    else
                        SendMessageToAll(GetMangosString(LANG_BG_AB_H_NEAR_VICTORY));
                    PlaySoundToAll(SOUND_NEAR_VICTORY);
                    m_IsInformedNearVictory = true;
                }

                if( m_TeamScores[team] > 2000 )
                    m_TeamScores[team] = 2000;
                if( team == BG_TEAM_ALLIANCE )
                    UpdateWorldState(BG_AB_OP_RESOURCES_ALLY, m_TeamScores[team]);
                if( team == BG_TEAM_HORDE )
                    UpdateWorldState(BG_AB_OP_RESOURCES_HORDE, m_TeamScores[team]);
            }
        }

        // Test win condition
        if( m_TeamScores[BG_TEAM_ALLIANCE] >= 2000 )
            EndBattleGround(ALLIANCE);
        if( m_TeamScores[BG_TEAM_HORDE] >= 2000 )
            EndBattleGround(HORDE);
    }
}
示例#5
0
void CAICHHashSet::UntrustedHashReceived(const CAICHHash& Hash, uint32 dwFromIP)
{
	switch(GetStatus()) {
		case AICH_EMPTY:
		case AICH_UNTRUSTED:
		case AICH_TRUSTED:
			break;
		default:
			return;
	}
	bool bFound = false;
	bool bAdded = false;
	for (uint32 i = 0; i < m_aUntrustedHashs.size(); ++i) {
		if (m_aUntrustedHashs[i].m_Hash == Hash) {
			bAdded = m_aUntrustedHashs[i].AddSigningIP(dwFromIP);
			bFound = true;
			break;
		}
	}
	if (!bFound) {
		bAdded = true;
		CAICHUntrustedHash uhToAdd;
		uhToAdd.m_Hash = Hash;
		uhToAdd.AddSigningIP(dwFromIP);
		m_aUntrustedHashs.push_back(uhToAdd);
	}

	uint32 nSigningIPsTotal = 0;	// unique clients who send us a hash
	int nMostTrustedPos = (-1);  // the hash which most clients send us
	uint32 nMostTrustedIPs = 0;
	for (uint32 i = 0; i < (uint32)m_aUntrustedHashs.size(); ++i) {
		nSigningIPsTotal += m_aUntrustedHashs[i].m_adwIpsSigning.size();
		if ((uint32)m_aUntrustedHashs[i].m_adwIpsSigning.size() > nMostTrustedIPs) {
			nMostTrustedIPs = m_aUntrustedHashs[i].m_adwIpsSigning.size();
			nMostTrustedPos = i;
		}
	}
	if (nMostTrustedPos == (-1) || nSigningIPsTotal == 0) {
		wxFAIL;
		return;
	}
	// the check if we trust any hash
	if ( thePrefs::IsTrustingEveryHash() ||
		(nMostTrustedIPs >= MINUNIQUEIPS_TOTRUST && (100 * nMostTrustedIPs)/nSigningIPsTotal >= MINPERCENTAGE_TOTRUST)) {
		//trusted
		AddDebugLogLineN(logSHAHashSet,
			CFormat(wxT("AICH Hash received (%sadded), We have now %u hash(es) from %u unique IP(s). ")
					wxT("We trust the Hash %s from %u client(s) (%u%%). File: %s"))
				% (bAdded ? wxT("") : wxT("not "))
				% m_aUntrustedHashs.size()
				% nSigningIPsTotal
				% m_aUntrustedHashs[nMostTrustedPos].m_Hash.GetString()
				% nMostTrustedIPs
				% ((100 * nMostTrustedIPs) / nSigningIPsTotal)
				% m_pOwner->GetFileName());

		SetStatus(AICH_TRUSTED);
		if (!HasValidMasterHash() || GetMasterHash() != m_aUntrustedHashs[nMostTrustedPos].m_Hash) {
			SetMasterHash(m_aUntrustedHashs[nMostTrustedPos].m_Hash, AICH_TRUSTED);
			FreeHashSet();
		}
	} else {
		// untrusted
		AddDebugLogLineN(logSHAHashSet,
			CFormat(wxT("AICH Hash received (%sadded), We have now %u hash(es) from %u unique IP(s). ")
					wxT("Best Hash %s from %u clients (%u%%) - but we don't trust it yet. File: %s"))
				% (bAdded ? wxT(""): wxT("not "))
				% m_aUntrustedHashs.size()
				% nSigningIPsTotal
				% m_aUntrustedHashs[nMostTrustedPos].m_Hash.GetString()
				% nMostTrustedIPs
				% ((100 * nMostTrustedIPs) / nSigningIPsTotal)
				% m_pOwner->GetFileName());

		SetStatus(AICH_UNTRUSTED);
		if (!HasValidMasterHash() || GetMasterHash() != m_aUntrustedHashs[nMostTrustedPos].m_Hash) {
			SetMasterHash(m_aUntrustedHashs[nMostTrustedPos].m_Hash, AICH_UNTRUSTED);
			FreeHashSet();
		}
	}
	if (bAdded) {}	// get rid of unused variable warning
}
示例#6
0
BYTE ModemGSM_OnNoBlk( void ){

#ifndef _BAUDRATE_AUTOBAUD
  return TRUE;
#else

  char cBuffer[16];
  static BYTE contTent = 0;
  static BYTE bState = 0;
  static TIMER_HANDLE bTimer = TIMER_NULL;

  if ( contTent > 4 ) {
    contTent = 0;
    return GSM_MODEM_NTENPT;    
  }

  switch( bState ){
    case 0:
      if ( bTimer == TIMER_NULL ){
        bTimer = GetTimer( DELAY_POWER_ON );
      }

      GSM_PWRKEY_OFF();     // coloca o PWR_KEY para nível zero. 
      bState = 1;
      return GSM_IDLE;

    case 1 :
     if ( IsTimerTimeOut( bTimer ) == TRUE ) {
        // ocorreu o timeout da operação com o modem
        // deve verificar o valor de GSM_STATUS
        GSM_PWRKEY_ON();
        contTent++;

        if ( GSM_STATUS == 0 ){
          // não foi possível ligar o modem.
          delay( 10 );
          GSM_PWRKEY_OFF();
          bState = 2;
          bTimer = GetTimer( DELAY_POWER_ON );
          return GSM_IDLE;
        }
        else{
          contTent = 0;
          bState = 3;
          RestartTimer( bTimer, TIMEOUT_START_MODEM );
          return GSM_IDLE;
        }
     }

    case 2:
      if ( IsTimerTimeOut( bTimer ) == TRUE ){ 
        bState = 1; 
      }
      return GSM_IDLE;


    case 3:
      
      if ( IsTimerTimeOut( bTimer ) == TRUE ){
        
        // Send a .AT. string to modem to detect the baudrate
        strcpypgm2ram( (char*)cBuffer, (const MEM_MODEL rom char*)".AT." );
        ModemGSM_SendATCMD( (BYTE*)cBuffer, strlen( cBuffer ) );   

        RestartTimer( bTimer, TIMEOUT_START_MODEM );
        bState = 4;
      }
      return GSM_IDLE;
  
    case 4:
      if ( IsTimerTimeOut( bTimer ) == TRUE ){
        
        // Send a .AT. string to modem to detect the baudrate
        strcpypgm2ram( (char*)cBuffer, (const MEM_MODEL rom char*)"AT+IPR=?\r\n" );
        ModemGSM_SendATCMD( (BYTE*)cBuffer, strlen( cBuffer ) );

        bState = 5;
        RestartTimer( bTimer, 10000 );        
      }
      return GSM_IDLE;

    case 5:
      
      if ( (IsTimerTimeOut( bTimer ) == TRUE) || ( ModemGSM_IsReady( ) == TRUE ) ){
        ReleaseTimer( &bTimer );
        bState = 0;

        if ( ModemGSM_IsReady( ) == TRUE ) {
          SetStatus( ST_MODEM_RDY );
          return GSM_OK;
        }        
        else{
          return GSM_MODEM_TIMEOUT;      
        }
      }
      return GSM_IDLE;

    default:
      return GSM_MODEM_ERROR;
  }
#endif
}
示例#7
0
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void CurlBlastDlg::DoStartup(void)
{
    QueryPerfFrequency(freq);

    InstallFlash();

    log.LogEvent(event_Started);
    log.LogMachineInfo();

    // register pagetest if we have a dll locally
    TCHAR pagetest[MAX_PATH];
    if( GetModuleFileName(NULL, pagetest, _countof(pagetest)) )
    {
        lstrcpy( PathFindFileName(pagetest), _T("pagetest.dll") );
        HMODULE hPagetest = LoadLibrary(pagetest);
        if( hPagetest )
        {
            SetStatus(_T("Registering pagetest..."));
            DLLREGISTERSERVER proc = (DLLREGISTERSERVER)GetProcAddress(hPagetest, "DllRegisterServer");
            if( proc )
                proc();
            FreeLibrary(hPagetest);
        }
    }

    InstallSystemGDIHook();

    // stop services that can interfere with our measurements
    SetStatus(_T("Stoping services..."));
    StopService(_T("WinDefend")); // defender
    StopService(_T("wscsvc"));    // security center

    // kill the action center (next reboot)
    HKEY hKey;
    if( SUCCEEDED(RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"), 0, KEY_SET_VALUE, &hKey)) )
    {
        DWORD val = 1;
        RegSetValueEx(hKey, _T("HideSCAHealth"), 0, REG_DWORD, (LPBYTE)&val, sizeof(val));
        RegCloseKey(hKey);
    }
    if( SUCCEEDED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"), 0, KEY_SET_VALUE, &hKey)) )
    {
        RegDeleteValue(hKey, _T("HideSCAHealth"));
        RegCloseKey(hKey);
    }

    // set the OS to not boost foreground processes
    if( SUCCEEDED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\PriorityControl"), 0, KEY_SET_VALUE, &hKey)) )
    {
        DWORD val = 0x18;
        RegSetValueEx(hKey, _T("Win32PrioritySeparation"), 0, REG_DWORD, (LPBYTE)&val, sizeof(val));

        RegCloseKey(hKey);
    }

    // block IE9 automatic install
    if( SUCCEEDED(RegCreateKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Internet Explorer\\Setup\\9.0"), 0, 0, 0, KEY_READ | KEY_WRITE, NULL, &hKey, NULL)) )
    {
        DWORD val = 1;
        RegSetValueEx(hKey, _T("DoNotAllowIE90"), 0, REG_DWORD, (LPBYTE)&val, sizeof(val));

        RegCloseKey(hKey);
    }

    // block IE10 automatic install
    if( SUCCEEDED(RegCreateKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Internet Explorer\\Setup\\10.0"), 0, 0, 0, KEY_READ | KEY_WRITE, NULL, &hKey, NULL)) )
    {
        DWORD val = 1;
        RegSetValueEx(hKey, _T("DoNotAllowIE10"), 0, REG_DWORD, (LPBYTE)&val, sizeof(val));

        RegCloseKey(hKey);
    }

    // block IE11 automatic install
    if( SUCCEEDED(RegCreateKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Internet Explorer\\Setup\\11.0"), 0, 0, 0, KEY_READ | KEY_WRITE, NULL, &hKey, NULL)) ) {
        DWORD val = 1;
        RegSetValueEx(hKey, _T("DoNotAllowIE11"), 0, REG_DWORD, (LPBYTE)&val, sizeof(val));
        RegCloseKey(hKey);
    }

    // start up the url manager
    urlManager.Start();

    // create all of the worker
    SetStatus(_T("Starting worker..."));

    CRect desktop(0,0,browserWidth,browserHeight);

    // launch the worker thread
    worker = new CURLBlaster(m_hWnd, log, ipfw, testingMutex, *this);

    // pass on configuration information
    worker->errorLog		  = logFile;
    worker->urlManager		= &urlManager;
    worker->timeout		  = timeout;
    worker->desktop		  = desktop;
    worker->customEventText= customEventText;
    worker->accountBase	= accountBase;
    worker->password		  = password;
    worker->preLaunch		= preLaunch;
    worker->postLaunch		= postLaunch;
    worker->dynaTrace		= dynaTrace;
    worker->pipeIn			  = pipeIn;
    worker->pipeOut		  = pipeOut;
    worker->useBitBlt		= 1;
    worker->keepDNS      = keepDNS;

    // force 1024x768 for screen shots
    worker->pos.right = browserWidth;
    worker->pos.bottom = browserHeight;

    if( useCurrentAccount )
        worker->hProfile = HKEY_CURRENT_USER;

    worker->Start(1);

    SetStatus(_T("Running..."));
    running = true;
}
示例#8
0
void CFTPTransferDlg::SetStatus(UINT nID, const CString& lpsz1)
{
  CString sStatus;
  AfxFormatString1(sStatus, nID, lpsz1);
  SetStatus(sStatus);
}
示例#9
0
void CFTPTransferDlg::TransferThread()
{
  //Create the Internet session handle (if needed)
  if (!m_bUsingAttached)
  {
    ASSERT(m_hInternetSession == NULL);

    if (m_bUsePreconfig)
      m_hInternetSession = ::InternetOpen(AfxGetAppName(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );
    else if (m_bUseProxy)
      m_hInternetSession = ::InternetOpen(AfxGetAppName(), INTERNET_OPEN_TYPE_PROXY, m_sProxy, NULL, 0);
    else
      m_hInternetSession = ::InternetOpen(AfxGetAppName(), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);

    if (m_hInternetSession == NULL)
    {
      _XLog( FALSE,_T("Failed in call to InternetOpen, Error:%d\n"), ::GetLastError());
      HandleThreadErrorWithLastError(IDS_FTPTRANSFER_GENERIC_ERROR);
      return;
    }

    //Should we exit the thread
    if (m_bAbort)
    {
      PostMessage(WM_FTPTRANSFER_THREAD_FINISHED);
      return;
    } 
  } 
  ASSERT(m_hInternetSession);  

  //Setup the status callback function on the Internet session handle
  INTERNET_STATUS_CALLBACK pOldCallback = ::InternetSetStatusCallback(m_hInternetSession, _OnStatusCallBack);
  if (pOldCallback == INTERNET_INVALID_STATUS_CALLBACK)
  {
    _XLog( FALSE,_T("Failed in call to InternetSetStatusCallback, Error:%d\n"), ::GetLastError());
    HandleThreadErrorWithLastError(IDS_FTPTRANSFER_GENERIC_ERROR);
    return;
  }

  //Should we exit the thread
  if (m_bAbort)
  {
    if (pOldCallback)
      ::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
    PostMessage(WM_FTPTRANSFER_THREAD_FINISHED);
    return;
  }  

  //Make the connection to the FTP server (if needed)
  if (!m_bUsingAttached)
  {
    ASSERT(m_hFTPConnection == NULL);
    ASSERT(m_sServer.GetLength());
    if (m_sUserName.GetLength())
      m_hFTPConnection = ::InternetConnect(m_hInternetSession, m_sServer, m_nPort, m_sUserName, 
                                            m_sPassword, INTERNET_SERVICE_FTP, m_bPasv ? INTERNET_FLAG_PASSIVE : 0, (DWORD) this);
    else
      m_hFTPConnection = ::InternetConnect(m_hInternetSession, m_sServer, m_nPort, NULL, 
                                            NULL, INTERNET_SERVICE_FTP, m_bPasv ? INTERNET_FLAG_PASSIVE : 0, (DWORD) this);
    if (m_hFTPConnection == NULL)
    {
      _XLog( FALSE,_T("Failed in call to InternetConnect, Error:%d\n"), ::GetLastError());
      if (pOldCallback)
        ::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
      HandleThreadErrorWithLastError(IDS_FTPTRANSFER_FAIL_CONNECT_SERVER);
      return;
    }

    //Should we exit the thread
    if (m_bAbort)
    {
      if (pOldCallback)
        ::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
      PostMessage(WM_FTPTRANSFER_THREAD_FINISHED);
      return;
    } 
  }
  ASSERT(m_hFTPConnection); 

  //Update the status control to reflect that we are getting the file information
  SetStatus(IDS_FTPTRANSFER_GETTING_FILE_INFORMATION);

  // Get the length of the file to transfer            
  DWORD dwFileSize = 0;
  BOOL bGotFileSize = FALSE;
  if (m_bDownload)
  {
	_XLog( FALSE, _T("Find ftp file [%s]\n"), m_sRemoteFile );
    WIN32_FIND_DATA wfd;
    HINTERNET hFind = ::FtpFindFirstFile(m_hFTPConnection, m_sRemoteFile, &wfd, INTERNET_FLAG_RELOAD |  
                                         INTERNET_FLAG_DONT_CACHE, (DWORD) this); 
    if (hFind)
    {
      //Set the progress control range
      bGotFileSize = TRUE;
      dwFileSize = (DWORD) wfd.nFileSizeLow;
	  //SetProgressRange(dwFileSize);
      //Destroy the enumeration handle now that we are finished with it
      InternetCloseHandle(hFind);
    }
  }
  else
  {
    bGotFileSize = TRUE;
    dwFileSize = m_LocalFile.GetLength();
	//SetProgressRange(dwFileSize);
  }

  //Should we exit the thread
  if (m_bAbort)
  {
    if (pOldCallback)
      ::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
    PostMessage(WM_FTPTRANSFER_THREAD_FINISHED);
    return;
  }  

  //check to see if the file already exists on the server  
  if (!m_bDownload && m_bPromptOverwrite)
  {
    WIN32_FIND_DATA wfd;
    HINTERNET hFind = ::FtpFindFirstFile(m_hFTPConnection, m_sRemoteFile, &wfd, INTERNET_FLAG_RELOAD | 
                                         INTERNET_FLAG_DONT_CACHE, (DWORD) this); 
    BOOL bFound = FALSE;
    if (hFind)
    {
      bFound = TRUE;
      
      //Destroy the enumeration handle now that we are finished with it
      InternetCloseHandle(hFind);
    }

    if (bFound && SendMessage(WM_FTPTRANSFER_ASK_OVERWRITE_FILE) == 0)  
    {
      if (pOldCallback)
        ::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
      PostMessage(WM_FTPTRANSFER_THREAD_FINISHED, 1);
      return;
    }
  }

  //Should we exit the thread
  if (m_bAbort)
  {
    if (pOldCallback)
      ::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
    PostMessage(WM_FTPTRANSFER_THREAD_FINISHED);
    return;
  }  

  //Open the remote file
  _XLog( FALSE, _T("Download ftp file [%s]\n"), m_sRemoteFile );
  ASSERT(m_hFTPFile == NULL);
  if (m_bDownload)
  {
    if (m_bBinary)
      m_hFTPFile = FtpOpenFile(m_hFTPConnection, m_sRemoteFile, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY | 
                               INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, (DWORD) this);
    else
      m_hFTPFile = FtpOpenFile(m_hFTPConnection, m_sRemoteFile, GENERIC_READ, FTP_TRANSFER_TYPE_ASCII | 
                               INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, (DWORD) this);
  }
  else
  {
    if (m_bBinary)  
      m_hFTPFile = FtpOpenFile(m_hFTPConnection, m_sRemoteFile, GENERIC_WRITE, FTP_TRANSFER_TYPE_BINARY | 
                               INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, (DWORD) this);
    else
      m_hFTPFile = FtpOpenFile(m_hFTPConnection, m_sRemoteFile, GENERIC_WRITE, FTP_TRANSFER_TYPE_ASCII | 
                               INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, (DWORD) this);
  }
  if (m_hFTPFile == NULL)
  {
    _XLog( FALSE,_T("Failed in call to FtpOpenFile, Error:%d\n"), ::GetLastError());
    if (pOldCallback)
      ::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
    HandleThreadErrorWithLastError(IDS_FTPTRANSFER_FAIL_OPEN_FILE);
    return;
  }
  else _XLog( FALSE, _T("Downloaded ftp file [%s]\n"), m_sRemoteFile );

  //Should we exit the thread
  if (m_bAbort)
  {
    if (pOldCallback)
      ::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
    PostMessage(WM_FTPTRANSFER_THREAD_FINISHED);
    return;
  }  

  //Update the status to say that we are now uploading / downloading the file
  if (m_bDownload)
    SetStatus(IDS_FTPTRANSFER_RETREIVEING_FILE);
  else
    SetStatus(IDS_FTPTRANSFER_UPLOADING_FILE);

  //Now do the actual reading / writing of the file
  DWORD dwStartTicks = ::GetTickCount();
  DWORD dwCurrentTicks = dwStartTicks;
  DWORD dwBytesRead = 0;
  DWORD dwBytesWritten = 0;
  char szReadBuf[1024];
  DWORD dwBytesToRead = 1024;
  DWORD dwTotalBytesRead = 0;
  DWORD dwTotalBytesWritten = 0;  
  DWORD dwLastTotalBytes = 0;
  DWORD dwLastPercentage = 0;
  double q = 0.0f;

  do
  {
    if (m_bDownload)
    {
      //Read from the remote file
      if (!::InternetReadFile(m_hFTPFile, szReadBuf, dwBytesToRead, &dwBytesRead))
      {
        _XLog( FALSE,_T("Failed in call to InternetReadFile, Error:%d\n"), ::GetLastError());
        if (pOldCallback)
          ::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
        HandleThreadErrorWithLastError(IDS_FTPTRANSFER_ERROR_READFILE);
        return;
      }
      else if (dwBytesRead && !m_bAbort)
      {
        //Write the data to file
        try
        {
          m_LocalFile.Write(szReadBuf, dwBytesRead);
        }
        catch(CFileException* pEx)
        {
          _XLog( FALSE,_T("An exception occured while writing to the download file\n"));
          if (pOldCallback)
            ::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
          HandleThreadErrorWithLastError(IDS_FTPTRANSFER_ERROR_READFILE, pEx->m_lOsError);
          pEx->Delete();
          return;
        }

        // For bandwidth throtling
		    if (m_dbLimit > 0.0f) 
        {
		      double t = (double)(GetTickCount() - dwStartTicks);
		      q = (double)((double)dwTotalBytesRead / t);
		     
		      if (q > m_dbLimit)	 
  			    Sleep((DWORD)((((q*t)/m_dbLimit)-t)));
		    }

        //Increment the total number of bytes read
        dwTotalBytesRead += dwBytesRead;  

        UpdateControlsDuringTransfer(dwStartTicks, dwCurrentTicks, dwTotalBytesRead, dwLastTotalBytes, 
                                     dwLastPercentage, bGotFileSize, dwFileSize);
      }
    }
    else
    {
      //Read the data from the local file
      try
      {
        dwBytesRead = m_LocalFile.Read(szReadBuf, 1024);
      }
      catch(CFileException* pEx)
      {
        _XLog( FALSE,_T("An exception occured while reading the local file\n"));
        if (pOldCallback)
          ::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
        HandleThreadErrorWithLastError(IDS_FTPTRANSFER_ERROR_READFILE, pEx->m_lOsError);
        pEx->Delete();
        return;
      }

      //Write to the remote file
      if (dwBytesRead)
      {
        if (!::InternetWriteFile(m_hFTPFile, szReadBuf, dwBytesRead, &dwBytesWritten))
        {
          _XLog( FALSE,_T("Failed in call to InternetWriteFile, Error:%d\n"), ::GetLastError());
          if (pOldCallback)
            ::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
          HandleThreadErrorWithLastError(IDS_FTPTRANSFER_ERROR_WRITEFILE);
          return;
        }
        else if (dwBytesWritten && !m_bAbort)
        {
          //Increment the total number of bytes read
          dwTotalBytesWritten += dwBytesWritten;  

          UpdateControlsDuringTransfer(dwStartTicks, dwCurrentTicks, dwTotalBytesWritten, dwLastTotalBytes, 
                                       dwLastPercentage, bGotFileSize, dwFileSize);
        }

        // For bandwidth throtling
		    if (m_dbLimit > 0.0f) 
        {
		      double t = (double)(GetTickCount() - dwStartTicks);
		      q = (double)((double)dwTotalBytesWritten / t);
		     
		      if (q > m_dbLimit)	 
  			    Sleep((DWORD)((((q*t)/m_dbLimit)-t)));
		    }
      }
    }
  } 
  while (dwBytesRead && !m_bAbort);

  //Delete the file being downloaded, if it is present and the download was aborted
  m_LocalFile.Close();
  if (m_bAbort && m_bDownload)
    ::DeleteFile(m_sLocalFile);

  //We're finished
  PostMessage(WM_FTPTRANSFER_THREAD_FINISHED);
}
示例#10
0
BOOL CFTPTransferDlg::OnInitDialog() 
{
  //Let the parent class do its thing
  CDialog::OnInitDialog();

  m_bSafeToClose  = FALSE;

  if( !m_ShowWindow ) ShowWindow( SW_MINIMIZE );
  
  //Change the caption of the dialog if necessary
  if (!m_bDownload)
  {
    CString sCaption;
    sCaption.LoadString(IDS_FTPTRANSFER_UPLOAD_CAPTION);
    SetWindowText(sCaption);
  }
  
  m_ctrlProgress.SetRange(0, 100);
  
  RECT	rect;
  m_ProgressMessageList.GetClientRect(&rect);
  m_ProgressMessageList.InsertColumn(0, _T("Progress Status"), LVCFMT_LEFT, rect.right - rect.left);
  m_ProgressMessageList.SetExtendedStyle(LVS_EX_FULLROWSELECT);

  //Try and open the file we will downloading into / uploading from
  if (m_bDownload )
  {
    if (!m_LocalFile.Open(m_sLocalFile, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite))
    {
      _XLog( FALSE,_T("Failed to open the file to download into, Error:%d\n"), GetLastError());
      CString sError;
      sError.Format(_T("%d"), ::GetLastError());
      CString sMsg;
      AfxFormatString1(sMsg, IDS_FTPTRANSFER_FAIL_LOCALFILE_OPEN1, sError);      
	  SetStatus( sMsg );
      EndDialog(IDCANCEL);
      return TRUE;
    }
  }
  else
  {
    if (!m_LocalFile.Open(m_sLocalFile, CFile::modeRead | CFile::shareDenyWrite))
    {
      _XLog( FALSE,_T("Failed to open the file to upload, Error:%d\n"), GetLastError());
      CString sError;
      sError.Format(_T("%d"), ::GetLastError());
      CString sMsg;
      AfxFormatString1(sMsg, IDS_FTPTRANSFER_FAIL_LOCALFILE_OPEN2, sError);
      SetStatus( sMsg );
      EndDialog(IDCANCEL);
      return TRUE;
    }
  }

  //Set the file status text
  CString sFileStatus;
  ASSERT(m_sRemoteFile.GetLength());
  ASSERT(m_sServer.GetLength());
  if (m_bDownload)    
    AfxFormatString2(sFileStatus, IDS_FTPTRANSFER_FILESTATUS1, m_sRemoteFile, m_sServer);
  else
    AfxFormatString2(sFileStatus, IDS_FTPTRANSFER_FILESTATUS2, m_sRemoteFile, m_sServer);
  m_ctrlFileStatus.SetWindowText(sFileStatus);

  //Spin off the background thread which will do the actual file transfer
  m_pThread = AfxBeginThread(_TransferThread, this, THREAD_PRIORITY_NORMAL, CREATE_SUSPENDED);
  if (m_pThread == NULL)
  {
    _XLog( FALSE,_T("Failed to create transfer thread, dialog is aborting\n"));
    EndDialog(IDCANCEL);
    return TRUE;
  }
  m_pThread->m_bAutoDelete = FALSE;
  m_pThread->ResumeThread();
	
	return TRUE;
}
示例#11
0
void CFTPTransferDlg::SetStatus(UINT nID)
{
  CString sCaption;
  sCaption.LoadString(nID);
  SetStatus(sCaption);
}
示例#12
0
void GBStackBrain::ExecutePrimitive(GBSymbolIndex index, GBRobot * robot, GBWorld * world) {
	GBStackDatum temp, temp2, temp3;
	long tempInt;
	switch ( index ) {
		case opNop: break;
	// stack manipulation
		case opDrop: Pop(); break;
		case op2Drop: Pop(); Pop(); break;
		case opNip: temp = Pop(); Pop(); Push(temp); break;
		case opRDrop: PopReturn(); break;
		case opDropN: {
			int n = PopInteger();
			if ( n > stackHeight ) throw GBBadArgumentError();
			stackHeight -= n;
		} break;
		case opSwap: temp = Pop(); temp2 = Pop(); Push(temp); Push(temp2); break;
		case op2Swap: { GBVector v1 = PopVector(); GBVector v2 = PopVector();
			PushVector(v1); PushVector(v2); } break;
		case opRotate: temp = Pop(); temp2 = Pop(); temp3 = Pop(); Push(temp2); Push(temp); Push(temp3); break;
		case opReverseRotate: temp = Pop(); temp2 = Pop(); temp3 = Pop(); Push(temp); Push(temp3); Push(temp2); break;
		case opDup: temp = Peek(); Push(temp); break;
		case op2Dup: temp = Peek(2); temp2 = Peek(); Push(temp); Push(temp2); break;
		case opTuck: temp = Pop(); temp2 = Pop(); Push(temp); Push(temp2); Push(temp); break;
		case opOver: temp = Peek(2); Push(temp); break;
		case op2Over: temp = Peek(4); temp2 = Peek(3); Push(temp); Push(temp2); break;
		case opStackHeight: Push(stackHeight); break;
		case opStackLimit: Push(kStackLimit); break;
		case opPick: Push(Peek(PopInteger())); break;
		case opToReturn: PushReturn(ToAddress(Pop())); break;
		case opFromReturn: Push(PopReturn()); break;
	// branches
		case opJump: pc = ToAddress(Pop()); break;
		case opCall: ExecuteCall(ToAddress(Pop())); break;
		case opReturn: pc = PopReturn(); break;
		case opIfGo: temp = Pop(); if ( Pop().Nonzero() ) pc = ToAddress(temp); break;
		case opIfElseGo: temp = Pop(); temp2 = Pop();
			if ( Pop().Nonzero() ) pc = ToAddress(temp2); else pc = ToAddress(temp); break;
		case opIfCall: temp = Pop(); if ( Pop().Nonzero() ) ExecuteCall(ToAddress(temp)); break;
		case opIfElseCall: temp = Pop(); temp2 = Pop();
			if ( Pop().Nonzero() ) ExecuteCall(ToAddress(temp2)); else ExecuteCall(ToAddress(temp)); break;
		case opIfReturn: if ( Pop().Nonzero() ) pc = PopReturn(); break;
		case opNotIfGo: temp = Pop(); if ( ! Pop().Nonzero() ) pc = ToAddress(temp); break;
		case opNotIfReturn: if ( ! Pop().Nonzero() ) pc = PopReturn(); break;
		case opNotIfCall: temp = Pop(); if ( ! Pop().Nonzero() ) ExecuteCall(ToAddress(temp)); break;
	// arithmetic
		case opAdd: TwoNumberToNumberOp(&GBNumber::operator +); break;
		case opSubtract: TwoNumberToNumberOp(&GBNumber::operator -); break;
		case opNegate: NumberToNumberOp(&GBNumber::operator -); break;
		// mult and divide are written out because of MrCpp internal error
		case opMultiply: temp = Pop(); Push(Pop() * temp); break;
		case opDivide: temp = Pop(); Push(Pop() / temp); break;
		case opReciprocal: Push(GBNumber(1) / Pop()); break;
		case opMod: TwoNumberToNumberOp(&GBNumber::Mod); break;
		case opRem: TwoNumberToNumberOp(&GBNumber::Rem); break;
		case opSqrt: NumberToNumberOp(&GBNumber::Sqrt); break;
		case opExponent: TwoNumberToNumberOp(&GBNumber::Exponent); break;
		case opIsInteger: PushBoolean(Pop().IsInteger()); break;
		case opFloor: Push(Pop().Floor()); break;
		case opCeiling: Push(Pop().Ceiling()); break;
		case opRound: Push(Pop().Round()); break;
		case opMin: TwoNumberToNumberOp(&GBNumber::Min); break;
		case opMax: TwoNumberToNumberOp(&GBNumber::Max); break;
		case opAbs: NumberToNumberOp(&GBNumber::Abs); break;
		case opSignum: NumberToNumberOp(&GBNumber::Signum); break;
		case opReorient: NumberToNumberOp(&GBNumber::Reorient); break;
		case opSine: NumberToNumberOp(&GBNumber::Sin); break;
		case opCosine: NumberToNumberOp(&GBNumber::Cos); break;
		case opTangent: NumberToNumberOp(&GBNumber::Tan); break;
		case opArcSine: NumberToNumberOp(&GBNumber::ArcSin); break;
		case opArcCosine: NumberToNumberOp(&GBNumber::ArcCos); break;
		case opArcTangent: NumberToNumberOp(&GBNumber::ArcTan); break;
		case opRandom: temp = Pop(); Push(world->Randoms().InRange(Pop(), temp)); break;
		case opRandomAngle: Push(world->Randoms().Angle()); break;
		case opRandomInt: temp = Pop(); Push(world->Randoms().LongInRange(Pop().Ceiling(), temp.Floor())); break;
		case opRandomBoolean: PushBoolean(world->Randoms().Boolean(Pop())); break;
	// constants
		case opPi: Push(GBNumber::pi); break;
		case op2Pi: Push(GBNumber::pi * 2); break;
		case opPiOver2: Push(GBNumber::pi / 2); break;
		case opE: Push(GBNumber::e); break;
		case opEpsilon: Push(GBNumber::epsilon); break;
		case opInfinity: Push(GBNumber::infinity); break;
	// vector operations
		case opRectToPolar: { GBVector v = PopVector(); Push(v.Norm()); Push(v.Angle()); } break;
		case opPolarToRect: temp = Pop(); temp2 = Pop(); PushVector(GBFinePoint::MakePolar(temp2, temp)); break;
		case opVectorAdd: TwoVectorToVectorOp(&GBFinePoint::operator +); break;
		case opVectorSubtract: TwoVectorToVectorOp(&GBFinePoint::operator -); break;
		case opVectorNegate: VectorToVectorOp(&GBFinePoint::operator -); break;
		case opVectorScalarMultiply: temp = Pop(); PushVector(PopVector() * temp); break;
		case opVectorScalarDivide: temp = Pop(); PushVector(PopVector() / temp); break;
		case opVectorNorm: VectorToScalarOp(&GBFinePoint::Norm); break;
		case opVectorAngle: VectorToScalarOp(&GBFinePoint::Angle); break;
		case opDotProduct: TwoVectorToScalarOp(&GBFinePoint::DotProduct);  break;
		case opProject: TwoVectorToVectorOp(&GBFinePoint::Projection); break;
		case opCross: TwoVectorToScalarOp(&GBFinePoint::Cross); break;
		case opUnitize: VectorToVectorOp(&GBFinePoint::Unit); break;
		case opDistance: Push((PopVector() - PopVector()).Norm()); break;
		case opInRange: temp = Pop(); PushBoolean(PopVector().InRange(PopVector(), temp)); break;
		case opRestrictPosition: {
			temp = Pop(); //wall distance
			GBVector pos = PopVector();
			Push(pos.x.Max(temp).Min(world->Size().x - temp));
			Push(pos.y.Max(temp).Min(world->Size().y - temp));
			} break;
		case opVectorEqual: PushBoolean(PopVector() == PopVector()); break;
		case opVectorNotEqual: PushBoolean(PopVector() != PopVector()); break;
	// comparisons
		case opEqual: PushBoolean(Pop() == Pop()); break;
		case opNotEqual: PushBoolean(Pop() != Pop()); break;
		case opLessThan: temp = Pop(); PushBoolean(Pop() < temp); break;
		case opLessThanOrEqual: temp = Pop(); PushBoolean(Pop() <= temp); break;
		case opGreaterThan: temp = Pop(); PushBoolean(Pop() > temp); break;
		case opGreaterThanOrEqual: temp = Pop(); PushBoolean(Pop() >= temp); break;
	// booleans
		case opNot: PushBoolean(! Pop().Nonzero()); break;
		case opAnd: temp = Pop(); temp2 = Pop(); PushBoolean(temp.Nonzero() && temp2.Nonzero()); break;
		case opOr: temp = Pop(); temp2 = Pop(); PushBoolean(temp.Nonzero() || temp2.Nonzero()); break;
		case opXor: temp = Pop(); temp2 = Pop();
			PushBoolean(temp.Nonzero() && ! temp2.Nonzero() || ! temp.Nonzero() && temp2.Nonzero()); break;
		case opNand: temp = Pop(); temp2 = Pop(); PushBoolean(! (temp.Nonzero() && temp2.Nonzero())); break;
		case opNor: temp = Pop(); temp2 = Pop(); PushBoolean(! (temp.Nonzero() || temp2.Nonzero())); break;
		case opValueConditional: temp = Pop(); temp2 = Pop();
			if ( Pop().Nonzero() ) Push(temp2); else Push(temp);
			break;
	// misc external
		case opPrint:
			DoPrint(ToString(Pop()));
			if ( world->reportPrints )
				NonfatalError(robot->Description() + " prints: " + *lastPrint);
			break;
		case opPrintVector:
			DoPrint(ToString(PopVector()));
			if ( world->reportPrints )
				NonfatalError(robot->Description() + " prints: " + *lastPrint);
			break;
		case opBeep: StartSound(siBeep); break;
		case opStop: SetStatus(bsStopped); break;
		case opPause: if ( world->reportErrors ) world->running = false; break;
		case opSync: remaining = 0; break;
	// basic hardware
		case opSeekLocation: robot->EngineSeek(PopVector(), GBVector(0, 0)); break;
		case opSeekMovingLocation: {
			GBVector vel = PopVector();
			robot->EngineSeek(PopVector(), vel);
			} break;
		case opDie: robot->Die(robot->Owner()); SetStatus(bsStopped); break;
		case opWriteLocalMemory:
			tempInt = PopInteger();
			WriteLocalMemory(tempInt, Pop(), robot);
			break;
		case opReadLocalMemory:
			tempInt = PopInteger();
			Push(ReadLocalMemory(tempInt, robot));
			break;
		case opWriteLocalVector:
			tempInt = PopInteger();
			WriteLocalMemory(tempInt + 1, Pop(), robot);
			WriteLocalMemory(tempInt, Pop(), robot);
			break;
		case opReadLocalVector:
			tempInt = PopInteger();
			Push(ReadLocalMemory(tempInt, robot));
			Push(ReadLocalMemory(tempInt + 1, robot));
			break;
		case opWriteSharedMemory:
			tempInt = PopInteger();
			robot->hardware.radio.Write(Pop(), tempInt, robot->Owner());
			break;
		case opReadSharedMemory:
			Push(robot->hardware.radio.Read(PopInteger(), robot->Owner()));
			break;
		case opWriteSharedVector:
			tempInt = PopInteger();
			robot->hardware.radio.Write(Pop(), tempInt + 1, robot->Owner());
			robot->hardware.radio.Write(Pop(), tempInt, robot->Owner());
			break;
		case opReadSharedVector:
			tempInt = PopInteger();
			Push(robot->hardware.radio.Read(tempInt, robot->Owner()));
			Push(robot->hardware.radio.Read(tempInt + 1, robot->Owner()));
			break;
		case opMessagesWaiting:
			Push(robot->hardware.radio.MessagesWaiting(PopInteger(), robot->Owner()));
			break;
		case opSendMessage: {
				GBMessage sendee;
				tempInt = PopInteger(); //channel
				int numArgs = ToInteger(Pop()); //number of numbers
				for ( int i = 0; i < numArgs; i++ ) {
					sendee.AddDatum(Pop()); //higher indices in message correspond with earlier numbers in stack. :(
				}
				if ( numArgs <= 0 )
					throw GBGenericError("Cannot send message of non-positive length");
				robot->hardware.radio.Send(sendee, tempInt, robot->Owner());
			} break;
		case opReceiveMessage: {
				tempInt = PopInteger();
				const GBMessage * received = robot->hardware.radio.Receive(tempInt, robot->Owner());
				if ( received == 0 ) {
					Push(0);
				} else {
					if ( received->Length() <= 0 ) {
						throw GBGenericError("non-positive length message received");
					}
					for ( int i = received->Length() - 1; i >= 0; i-- )
						Push(received->Datum(i));
					Push(received->Length());
				}
			} break;
		case opClearMessages:
			robot->hardware.radio.ClearChannel(PopInteger(), robot->Owner());
			break;
		case opSkipMessages:
			tempInt = PopInteger();
			robot->hardware.radio.SkipMessages(tempInt, PopInteger(), robot->Owner());
			break;
		case opTypePopulation: {
				GBRobotType * theType = robot->Owner()->GetType(PopInteger());
				if (theType)
					Push(theType->Population());
				else
					Push(-1);
			} break;
		case opAutoConstruct: {
			GBConstructorState & ctor = robot->hardware.constructor;
			if ( robot->Energy() > robot->hardware.MaxEnergy() * .9 ) {
				if ( ! ctor.Type() ) ctor.Start(robot->Type());
				ctor.SetRate(ctor.MaxRate());
			} else
				ctor.SetRate(ctor.Type() && robot->Energy() > ctor.Remaining() + 10 ? ctor.MaxRate() : GBNumber(0));
			} break;
		case opBalanceTypes: { // frac type --
				GBRobotType * theType = robot->Owner()->GetType(PopInteger());
				GBNumber fraction = Pop();
				if (theType && GBNumber(theType->Population()) < fraction * robot->Owner()->Scores().Population())
					robot->hardware.constructor.Start(theType); //FIXME don't abort?
			} break;
	// sensors
		case opFireRobotSensor: robot->hardware.sensor1.Fire(); break;
		case opFireFoodSensor: robot->hardware.sensor2.Fire(); break;
		case opFireShotSensor: robot->hardware.sensor3.Fire(); break;
		case opRobotSensorNext: Push(robot->hardware.sensor1.NextResult() ? 1 : 0); break;
		case opFoodSensorNext: Push(robot->hardware.sensor2.NextResult() ? 1 : 0); break;
		case opShotSensorNext: Push(robot->hardware.sensor3.NextResult() ? 1 : 0); break;
		case opPeriodicRobotSensor:
			FirePeriodic(robot->hardware.sensor1, world);
			break;
		case opPeriodicFoodSensor:
			FirePeriodic(robot->hardware.sensor2, world);
			break;
		case opPeriodicShotSensor:
			FirePeriodic(robot->hardware.sensor3, world);
			break;
	// weapons
		case opFireBlaster: robot->hardware.blaster.Fire(Pop()); break;
		case opFireGrenade: temp = Pop(); robot->hardware.grenades.Fire(Pop(), temp); break;
		case opLeadBlaster: { //pos vel --
			GBVelocity vel = PopVector() - robot->Velocity();
			GBPosition pos = PopVector() - robot->Position();
			GBPosition target = LeadShot(pos, vel, robot->hardware.blaster.Speed(), robot->Radius());
			if ( target.Nonzero() && target.Norm() <= robot->hardware.blaster.MaxRange() + robot->Radius() )
				robot->hardware.blaster.Fire(target.Angle());
			} break;
		case opLeadGrenade: { //pos vel --
			GBVelocity vel = PopVector() - robot->Velocity();
			GBPosition pos = PopVector() - robot->Position();
			GBPosition target = LeadShot(pos, vel, robot->hardware.grenades.Speed(), robot->Radius());
			if ( target.Nonzero() && target.Norm() <= robot->hardware.grenades.MaxRange() + robot->Radius() )
				robot->hardware.grenades.Fire(target.Norm(), target.Angle()); //worry about short range?
			} break;
		case opSetForceField: { //pos angle --
			temp = Pop();
			GBPosition pos = PopVector() - robot->Position();
			robot->hardware.forceField.SetDistance(pos.Norm());
			robot->hardware.forceField.SetDirection(pos.Angle());
			robot->hardware.forceField.SetAngle(temp);
			robot->hardware.forceField.SetPower(robot->hardware.forceField.MaxPower());
			} break;
	// otherwise...
		default:	
			throw GBUnknownInstructionError();
			break;
	}
}
示例#13
0
void BattleGroundWS::Update(time_t diff)
{
    BattleGround::Update(diff);

    // after bg start we get there (once)
    if (GetStatus() == STATUS_WAIT_JOIN && GetPlayersSize())
    {
        ModifyStartDelayTime(diff);

        if(!(m_Events & 0x01))
        {
            m_Events |= 0x01;

            // setup here, only when at least one player has ported to the map
            if(!SetupBattleGround())
            {
                EndNow();
                return;
            }

//            for(uint32 i = WS_SPIRIT_MAIN_ALLIANCE; i <= WS_SPIRIT_MAIN_HORDE; i++)
//                SpawnBGCreature(i, RESPAWN_IMMEDIATELY);

            for(uint32 i = BG_WS_OBJECT_DOOR_A_1; i <= BG_WS_OBJECT_DOOR_H_4; i++)
            {
                SpawnBGObject(i, RESPAWN_IMMEDIATELY);
                DoorClose(i);
            }
            for(uint32 i = BG_WS_OBJECT_A_FLAG; i <= BG_WS_OBJECT_BERSERKBUFF_2; i++)
                SpawnBGObject(i, RESPAWN_ONE_DAY);

            SetStartDelayTime(START_DELAY0);
        }
        // After 1 minute, warning is signalled
        else if(GetStartDelayTime() <= START_DELAY1 && !(m_Events & 0x04))
        {
            m_Events |= 0x04;
            SendMessageToAll(GetTrinityString(LANG_BG_WS_ONE_MINUTE));
        }
        // After 1,5 minute, warning is signalled
        else if(GetStartDelayTime() <= START_DELAY2 && !(m_Events & 0x08))
        {
            m_Events |= 0x08;
            SendMessageToAll(GetTrinityString(LANG_BG_WS_HALF_MINUTE));
        }
        // After 2 minutes, gates OPEN ! x)
        else if(GetStartDelayTime() < 0 && !(m_Events & 0x10))
        {
            m_Events |= 0x10;
            for(uint32 i = BG_WS_OBJECT_DOOR_A_1; i <= BG_WS_OBJECT_DOOR_A_4; i++)
                DoorOpen(i);
            for(uint32 i = BG_WS_OBJECT_DOOR_H_1; i <= BG_WS_OBJECT_DOOR_H_2; i++)
                DoorOpen(i);

            SpawnBGObject(BG_WS_OBJECT_DOOR_A_5, RESPAWN_ONE_DAY);
            SpawnBGObject(BG_WS_OBJECT_DOOR_A_6, RESPAWN_ONE_DAY);
            SpawnBGObject(BG_WS_OBJECT_DOOR_H_3, RESPAWN_ONE_DAY);
            SpawnBGObject(BG_WS_OBJECT_DOOR_H_4, RESPAWN_ONE_DAY);

            for(uint32 i = BG_WS_OBJECT_A_FLAG; i <= BG_WS_OBJECT_BERSERKBUFF_2; i++)
                SpawnBGObject(i, RESPAWN_IMMEDIATELY);

            SendMessageToAll(GetTrinityString(LANG_BG_WS_BEGIN));

            PlaySoundToAll(SOUND_BG_START);
            if(sWorld.getConfig(CONFIG_BG_START_MUSIC))
                PlaySoundToAll(SOUND_BG_START_L70ETC); //MUSIC - Custom config
            SetStatus(STATUS_IN_PROGRESS);

            for(BattleGroundPlayerMap::const_iterator itr = GetPlayers().begin(); itr != GetPlayers().end(); ++itr)
                if(Player* plr = objmgr.GetPlayer(itr->first))
                    plr->RemoveAurasDueToSpell(SPELL_PREPARATION);
        }
    }
    else if(GetStatus() == STATUS_IN_PROGRESS)
    {
        if(m_FlagState[BG_TEAM_ALLIANCE] == BG_WS_FLAG_STATE_WAIT_RESPAWN)
        {
            m_FlagsTimer[BG_TEAM_ALLIANCE] -= diff;

            if(m_FlagsTimer[BG_TEAM_ALLIANCE] < 0)
            {
                m_FlagsTimer[BG_TEAM_ALLIANCE] = 0;
                RespawnFlag(ALLIANCE, true);
            }
        }
        if(m_FlagState[BG_TEAM_ALLIANCE] == BG_WS_FLAG_STATE_ON_GROUND)
        {
            m_FlagsDropTimer[BG_TEAM_ALLIANCE] -= diff;

            if(m_FlagsDropTimer[BG_TEAM_ALLIANCE] < 0)
            {
                m_FlagsDropTimer[BG_TEAM_ALLIANCE] = 0;
                RespawnFlagAfterDrop(ALLIANCE);
            }
        }
        if(m_FlagState[BG_TEAM_HORDE] == BG_WS_FLAG_STATE_WAIT_RESPAWN)
        {
            m_FlagsTimer[BG_TEAM_HORDE] -= diff;

            if(m_FlagsTimer[BG_TEAM_HORDE] < 0)
            {
                m_FlagsTimer[BG_TEAM_HORDE] = 0;
                RespawnFlag(HORDE, true);
            }
        }
        if(m_FlagState[BG_TEAM_HORDE] == BG_WS_FLAG_STATE_ON_GROUND)
        {
            m_FlagsDropTimer[BG_TEAM_HORDE] -= diff;

            if(m_FlagsDropTimer[BG_TEAM_HORDE] < 0)
            {
                m_FlagsDropTimer[BG_TEAM_HORDE] = 0;
                RespawnFlagAfterDrop(HORDE);
            }
        }
    }
}
示例#14
0
void BattleGroundWS::Update(uint32 diff)
{
    BattleGround::Update(diff);

    // after bg start we get there (once)
    if (GetStatus() == STATUS_WAIT_JOIN && GetPlayersSize())
    {
        ModifyStartDelayTime(diff);

        if (!(m_Events & 0x01))
        {
            m_Events |= 0x01;

            // setup here, only when at least one player has ported to the map
            if (!SetupBattleGround())
            {
                EndNow();
                return;
            }

            SetStartDelayTime(START_DELAY0);
        }
        // After 1 minute, warning is signalled
        else if (GetStartDelayTime() <= START_DELAY1 && !(m_Events & 0x04))
        {
            m_Events |= 0x04;
            SendMessageToAll(GetMangosString(LANG_BG_WS_ONE_MINUTE));
        }
        // After 1,5 minute, warning is signalled
        else if (GetStartDelayTime() <= START_DELAY2 && !(m_Events & 0x08))
        {
            m_Events |= 0x08;
            SendMessageToAll(GetMangosString(LANG_BG_WS_HALF_MINUTE));
        }
        // After 2 minutes, gates OPEN ! x)
        else if (GetStartDelayTime() < 0 && !(m_Events & 0x10))
        {
            m_Events |= 0x10;
            // TODO implement timer to despawn doors after a short while
            OpenDoorEvent(BG_EVENT_DOOR);

            SpawnEvent(WS_EVENT_SPIRITGUIDES_SPAWN, 0, true);
            SpawnEvent(WS_EVENT_FLAG_A, 0, true);
            SpawnEvent(WS_EVENT_FLAG_H, 0, true);

            SendMessageToAll(GetMangosString(LANG_BG_WS_BEGIN));

            PlaySoundToAll(SOUND_BG_START);
            SetStatus(STATUS_IN_PROGRESS);

            for(BattleGroundPlayerMap::const_iterator itr = GetPlayers().begin(); itr != GetPlayers().end(); ++itr)
                if (Player* plr = sObjectMgr.GetPlayer(itr->first))
                    plr->RemoveAurasDueToSpell(SPELL_PREPARATION);
        }
    }
    else if (GetStatus() == STATUS_IN_PROGRESS)
    {
        if (m_FlagState[BG_TEAM_ALLIANCE] == BG_WS_FLAG_STATE_WAIT_RESPAWN)
        {
            m_FlagsTimer[BG_TEAM_ALLIANCE] -= diff;

            if (m_FlagsTimer[BG_TEAM_ALLIANCE] < 0)
            {
                m_FlagsTimer[BG_TEAM_ALLIANCE] = 0;
                RespawnFlag(ALLIANCE, true);
            }
        }
        if (m_FlagState[BG_TEAM_ALLIANCE] == BG_WS_FLAG_STATE_ON_GROUND)
        {
            m_FlagsDropTimer[BG_TEAM_ALLIANCE] -= diff;

            if (m_FlagsDropTimer[BG_TEAM_ALLIANCE] < 0)
            {
                m_FlagsDropTimer[BG_TEAM_ALLIANCE] = 0;
                RespawnFlagAfterDrop(ALLIANCE);
            }
        }
        if (m_FlagState[BG_TEAM_HORDE] == BG_WS_FLAG_STATE_WAIT_RESPAWN)
        {
            m_FlagsTimer[BG_TEAM_HORDE] -= diff;

            if (m_FlagsTimer[BG_TEAM_HORDE] < 0)
            {
                m_FlagsTimer[BG_TEAM_HORDE] = 0;
                RespawnFlag(HORDE, true);
            }
        }
        if (m_FlagState[BG_TEAM_HORDE] == BG_WS_FLAG_STATE_ON_GROUND)
        {
            m_FlagsDropTimer[BG_TEAM_HORDE] -= diff;

            if (m_FlagsDropTimer[BG_TEAM_HORDE] < 0)
            {
                m_FlagsDropTimer[BG_TEAM_HORDE] = 0;
                RespawnFlagAfterDrop(HORDE);
            }
        }
    }
}
示例#15
0
void ModemGSM_Init( void ){
  
  char cBuffer[32]; 
  BYTE i;
  INT iCounter;

  // inicializa a conexão serial com o Modem
  InitSerial( 0, MODEM_BAUD, ST_1, PR_NONE, ModemGSM_ProcessaMensagens );
  //cdantas - alterei a função de UART para utilizar o HardWare

  //memset( (char*)ModemGSM_Varzea, 0, sizeof( ModemGSM_Varzea ));
  //for ( i = 0; i < sizeof( ModemGSM_Varzea ); i++ ){
  //  ModemGSM_Varzea[i] = (i % 2)? 0x55 : 0xAA;
  //}

  //for ( i = 0; i < sizeof( ModemGSM_Varzea2 ); i++ ){
  //  ModemGSM_Varzea2[i] = (i % 2)? 0x55 : 0xAA;
  //}

  for( ModemGSM_DataCounter = 0; ModemGSM_DataCounter < /*sizeof ( ModemGSM_Buffer )*/BUFFER_GSM_LEN; ModemGSM_DataCounter++ ){
    ModemGSM_Buffer[ModemGSM_DataCounter] = (ModemGSM_DataCounter % 2) ? 0xAA: 0x55;
  }

  // inicializa os pinos de conexão com os SIMs cards
  ModemGSM_InitGPIO();

  ModemGSM_ResetStateSIMCARD();

  ModemGSM_Change_State_SIM_PRESENCE( 0 );

  ModemGSM_Ready = FALSE;
  ModemGSM_ActiveSIMCard = 0xFF;
  
  ModemGSM_DataCounter = 0;

  ModemGSM_TimerHandle = GetTimer( MODEMGSM_TIMEROVF );

 if ( !ModemGSM_IsOn() ){

#ifdef _BAUDRATE_AUTOBAUD      
    if ( ModemGSM_On() == TRUE ){
      // wait a delay before send a first command to modem. 
      delay( TIMEOUT_START_MODEM );
      
      // Send a .AT. string to modem to detect the baudrate
      strcpypgm2ram( (char*)cBuffer, (const MEM_MODEL rom char*)".AT." );
      ModemGSM_SendATCMD( (BYTE*)cBuffer, strlen( cBuffer ) );
      
      delay( TIMEOUT_START_MODEM ); 
      strcpypgm2ram( (char*)cBuffer, (const MEM_MODEL rom char*)"AT+IPR=?\r\n" );
      ModemGSM_SendATCMD( (BYTE*)cBuffer, strlen( cBuffer ) );
    }    
#else
    ModemGSM_On();
#endif
  }
  else{
    ModemGSM_Ready = TRUE;
  }

  if ( ModemGSM_Ready == TRUE ){
    //Dev_ChangeState( DEV_GSM_PWR_KEY, ON );
    
    SetStatus( ST_MODEM_RDY );

    for ( i = 0 ; i < GET_VEC_NUM_MEMBERS(dev); i++ ){
      if ( dev[i].ID == DEV_GSM_PWR_KEY ){
        dev[i].bState = ON;
        dev[i].bNextState = ON;
      }
    }
    
  }

  timerCheckONOFF = GetTimer( TIMEOUT_START_MODEM );

  return;
}
示例#16
0
GR_SelectionSet::~GR_SelectionSet(void)
{
	SetStatus(GR_SelectionSet::eUnSel);
}
示例#17
0
void ModemGSM_CheckMSG( void ){
  char * pChar = NULL;
  BYTE i;

  //static const char strPowerDown[] = "\r\nNORMAL POWER DOWN\r\n";
  //static const char strPowerLowDown[] = "\r\nPOWER LOW DOWN\r\n";
  //static const char strPowerDownLowTemp[] = "\r\n+CMTE:-2\r\n";
  //static const char strPowerDownHighTemp[] = "\r\n+CMTE: 2\r\n";
  
  if (ModemGSM_DataCounter) {
    if ( (ModemGSM_DataCounter >= /*sizeof( ModemGSM_Buffer )*/ BUFFER_GSM_LEN - 1) || (IsTimerTimeOut( ModemGSM_TimerHandle ) == TRUE) ){

#ifdef _BAUDRATE_AUTOBAUD

      if ( ModemGSM_Ready == FALSE ){
        // busca por RDY no buffer de recepção
        pChar = strstrrampgm( (const char*)ModemGSM_Buffer, (const MEM_MODEL rom char*)"+IPR" );
        if ( pChar != NULL ){
          ModemGSM_Ready = TRUE;
          SetStatus( ST_MODEM_RDY );

          for ( i = 0 ; i < GET_VEC_NUM_MEMBERS(dev); i++ ){
            if ( dev[i].ID == DEV_GSM_PWR_KEY ){
              dev[i].bState = ON;
              dev[i].bNextState = ON;
            }
          }
        }
      }
      else{
        //ModemGSM_Buffer[ModemGSM_DataCounter] = 0;
        // verify the modem power down cause
        //if ( (strncmp( (const char*)ModemGSM_Buffer, strPowerDown,         ModemGSM_DataCounter ) == 0) ||
        //     (strncmp( (const char*)ModemGSM_Buffer, strPowerLowDown,      ModemGSM_DataCounter ) == 0) || 
        //     (strncmp( (const char*)ModemGSM_Buffer, strPowerDownLowTemp,  ModemGSM_DataCounter ) == 0) || 
        //     (strncmp( (const char*)ModemGSM_Buffer, strPowerDownHighTemp, ModemGSM_DataCounter ) == 0)  )
        //{
        //  for ( i = 0 ; i < GET_VEC_NUM_MEMBERS(dev); i++ ){
        //    if ( dev[i].ID == DEV_GSM_PWR_KEY ){
        //      dev[i].bState = OFF;
        //      dev[i].bNextState = OFF;
        //    }
        //  }
        //  ModemGSM_Ready = FALSE;
        //  CleanStatus( ST_MODEM_RDY );      
        //}

        EnviaCMD_MODEM((BYTE*)ModemGSM_Buffer, ModemGSM_DataCounter );
      }
#else
      if ( ModemGSM_Ready == FALSE ){
        // busca por RDY no buffer de recepção
        pChar = strstrrampgm( (const char*)ModemGSM_Buffer, (const MEM_MODEL rom char*)"RDY" );
        if ( pChar != NULL ){
          ModemGSM_Ready = TRUE;

          for ( i = 0 ; i < GET_VEC_NUM_MEMBERS(dev); i++ ){
            if ( dev[i].ID == DEV_GSM_PWR_KEY ){
              dev[i].bState = ON;
              dev[i].bNextState = ON;
            }
          }
        }
      }
      else{
        EnviaCMD_MODEM( ModemGSM_Buffer, ModemGSM_DataCounter );
      }
#endif
      ModemGSM_DataCounter = 0;
    }
  }
  return;
}
示例#18
0
void CComDateTime::CheckRange()
{
	if (m_dt > MAX_DATE || m_dt < MIN_DATE) // about year 100 to about 9999
		SetStatus(invalid);
}
示例#19
0
/*-----------------------------------------------------------------------------
  Background thread for managing the state of the agent
-----------------------------------------------------------------------------*/
void CurlBlastDlg::ThreadProc(void)
{
    LoadSettings();

    // configure the desktop resolution
    WaitForSingleObject(testingMutex, INFINITE);
    SetupScreen();
    ReleaseMutex(testingMutex);

    // wait for the statup delay
    SetStatus(_T("Starting up..."));
    DWORD ms = startupDelay;
    while( ms > 0 && WaitForSingleObject(hMustExit,0) == WAIT_TIMEOUT) {
        Sleep(500);
        ms -= 500;
    }

    // launch the watchdog
    TCHAR path[MAX_PATH];
    GetModuleFileName(NULL, path, MAX_PATH);
    lstrcpy(PathFindFileName(path), _T("wptwatchdog.exe"));
    CString watchdog;
    watchdog.Format(_T("\"%s\" %d"), path, GetCurrentProcessId());
    HANDLE process = NULL;
    LaunchProcess(watchdog, &process);
    if (process)
        CloseHandle(process);

    if (WaitForSingleObject(hMustExit,0) == WAIT_TIMEOUT) {
        DoStartup();
    }

    // handle the periodic cleanup until it is time to exit
    Alive();
    DWORD msCleanup = 500;
    DWORD msTemp = 20000;
    while(WaitForSingleObject(hMustExit,0) == WAIT_TIMEOUT) {
        if (!msCleanup) {
            CloseDialogs();
            KillProcs();
            msCleanup = 500;
        } else
            msCleanup -= 500;

        if (!msTemp) {
            if (WaitForSingleObject(testingMutex, 0) != WAIT_TIMEOUT) {
                ClearTemp();
                msTemp = 20000;
                ReleaseMutex(testingMutex);
            }
        } else
            msTemp -= 500;

        CheckAlive();
        Sleep(500);
    }

    // signal and wait for all of the workers to finish
    KillWorker();

    // shut down the url manager
    urlManager.Stop();
}
示例#20
0
int FacebookProto::OnPreShutdown(WPARAM wParam, LPARAM lParam)
{
	SetStatus(ID_STATUS_OFFLINE);
	return 0;
}
示例#21
0
void SetMotor(char Drive,bool State) {
	if (Drive==0) LEDs.Disc0=State; else LEDs.Disc1=State;
	if (State) SetStatus(7);
}
示例#22
0
void TicketMgr::Initialize() {
    SetStatus(sWorld->getBoolConfig(CONFIG_ALLOW_TICKETS));
}
示例#23
0
void CAICHHashSet::SetMasterHash(const CAICHHash& Hash, EAICHStatus eNewStatus)
{
	m_pHashTree.m_Hash = Hash;
	m_pHashTree.m_bHashValid = true;
	SetStatus(eNewStatus);
}
示例#24
0
int32 CDiskFile::Open(const CFileName& oFileName, const char* sOption)
{
	char sFullName[FOCP_MAX_PATH];
	CPathDetailInfo oDetailInfo;
	CDiskFileSystem* pFileSytem;
	uint32 nOption = GetOpenOption(sOption);
	if(nOption & FOCP_FILE_OPTION_LISTEN)
	{
		if(oFileName.oBindName.Empty())
			return FOCP_FILE_BINDNAME_ERROR;
		return FOCP_FILE_BIND_ERROR;
	}
	if(oFileName.oConnectName.Empty())
		return FOCP_FILE_CONNECTNAME_ERROR;
	pFileSytem = CDiskFileSystem::GetInstance();
	if(!pFileSytem->GetFullPath(oFileName.oConnectName.GetStr(), sFullName, &oDetailInfo))
		return FOCP_FILE_CONNECTNAME_ERROR;
	if(oDetailInfo.bExist && !oDetailInfo.sFilePart)
		return FOCP_FILE_CONNECTNAME_ERROR;
	char* pDir = CString::CharOfString(sFullName, '/', true);
	pDir[0] = '\0';
	AfcCreateDirectory(sFullName);
	pDir[0] = '/';
	m_oFileName.oConnectName = sFullName;
	pFileSytem->GetOsPathName(sFullName);
#if defined(WINDOWS)
	uint32 dwDesiredAccess = 0;
	uint32 dwShareMode = 0;
	uint32 dwCreationDisposition = 0;
	uint32 dwFlagsAndAttributes = 0;
	if(nOption & FOCP_FILE_OPTION_READ)
		dwDesiredAccess |= GENERIC_READ;
	if(nOption & FOCP_FILE_OPTION_WRITE)
		dwDesiredAccess |= GENERIC_WRITE;
	if(nOption & FOCP_FILE_OPTION_SHARE_READ)
		dwShareMode |= FILE_SHARE_READ;
	if(nOption & FOCP_FILE_OPTION_SHARE_WRITE)
		dwShareMode |= FILE_SHARE_WRITE;
	if(nOption & FOCP_FILE_OPTION_CREATE)
		dwCreationDisposition = OPEN_ALWAYS;
	else if(nOption & FOCP_FILE_OPTION_NEW)
		dwCreationDisposition = CREATE_NEW;
	else if(nOption & FOCP_FILE_OPTION_DESTROY)
		dwCreationDisposition = CREATE_ALWAYS;
	else if(nOption & FOCP_FILE_OPTION_APPEND)
		dwCreationDisposition = OPEN_ALWAYS;
	else
		dwCreationDisposition = OPEN_EXISTING;
	dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
	if(nOption & FOCP_FILE_OPTION_WRITE)
		dwFlagsAndAttributes |= FILE_ATTRIBUTE_NORMAL;
	else
		dwFlagsAndAttributes |= FILE_ATTRIBUTE_READONLY;
	m_hHandle = (ulong)CreateFile(sFullName, dwDesiredAccess, dwShareMode, NULL,
								  dwCreationDisposition, dwFlagsAndAttributes, NULL);
	if(m_hHandle == (ulong)(-1))
		return FOCP_FILE_CONNECT_ERROR;
	if(nOption & FOCP_FILE_OPTION_APPEND)
	{
		uint32 nLowSize, nHighSize;
		nLowSize = GetFileSize((HANDLE)m_hHandle, (DWORD*)&nHighSize);
		if(nHighSize || nLowSize > 0x7FFFFFFF)
			nLowSize = 0x7FFFFFFF;
		SetFilePointer((HANDLE)m_hHandle, nLowSize, NULL, FILE_BEGIN);
	}
#else
	uint32 nFlags = 0, nLock;
	if(nOption & FOCP_FILE_OPTION_READ)
		nFlags |= O_RDONLY;
	if(nOption & FOCP_FILE_OPTION_WRITE)
	{
		nFlags &= ~(uint32)O_RDONLY;
		nFlags |= O_RDWR;
	}
	if(nOption & FOCP_FILE_OPTION_CREATE)
		nFlags |= O_CREAT;
	else if(nOption & FOCP_FILE_OPTION_NEW)
		nFlags |= O_CREAT|O_EXCL;
	else if(nOption & FOCP_FILE_OPTION_DESTROY)
		nFlags |= O_CREAT|O_TRUNC;
	else if(nOption & FOCP_FILE_OPTION_APPEND)
		nFlags |= O_CREAT|O_APPEND;
//else
//	nFlags |= OPEN_EXISTING;
	nFlags |= O_SYNC;
	m_hHandle = (ulong)open(sFullName, (int32)nFlags);
	if(m_hHandle == (ulong)(-1))
		return FOCP_FILE_CONNECT_ERROR;
	if(nFlags & O_CREAT)
#ifdef WINDOWS
		chmod(sFullName, _S_IREAD | _S_IWRITE);
#else
		chmod(sFullName, S_IRUSR | S_IWUSR);
#endif
	if( (nOption & FOCP_FILE_OPTION_SHARE_READ) ||
			(nOption & FOCP_FILE_OPTION_SHARE_WRITE))
		nLock = LOCK_SH|LOCK_NB;
	else
		nLock = LOCK_EX|LOCK_NB;
	while(flock((int32)m_hHandle, nLock))
	{
		if(errno != EINTR)
		{
			close(m_hHandle);
			m_hHandle = (ulong)(-1);
			return FOCP_FILE_CONNECT_ERROR;
		}
	}
#endif
	SetStatus(FOCP_FILE_NORMAL);
	return 0;
}
示例#25
0
void MpMessageDialog::Button_2_Clicked (void)
{
  ExitLocalLoop = true;  
  SetStatus(Button_2);
}
示例#26
0
void BattleGroundNA::Update(uint32 diff)
{
    BattleGround::Update(diff);

    // after bg start we get there
    if (GetStatus() == STATUS_WAIT_JOIN && GetPlayersSize())
    {
        ModifyStartDelayTime(diff);

        if (!(m_Events & 0x01))
        {
            m_Events |= 0x01;
            // setup here, only when at least one player has ported to the map
            if (!SetupBattleGround())
            {
                EndNow();
                return;
            }
            for (uint32 i = BG_NA_OBJECT_DOOR_1; i <= BG_NA_OBJECT_DOOR_4; i++)
                SpawnBGObject(i, RESPAWN_IMMEDIATELY);

            AddSpectatorNPC(4055.74f, 2921.20f, 39.54f, 0.0f);

            SetStartDelayTime(START_DELAY1);
            SendMessageToAll(LANG_ARENA_ONE_MINUTE);
        }
        // After 30 seconds, warning is signalled
        else if (GetStartDelayTime() <= START_DELAY2 && !(m_Events & 0x04))
        {
            m_Events |= 0x04;
            SendMessageToAll(LANG_ARENA_THIRTY_SECONDS);
        }
        // After 15 seconds, warning is signalled
        else if (GetStartDelayTime() <= START_DELAY3 && !(m_Events & 0x08))
        {
            m_Events |= 0x08;
            SendMessageToAll(LANG_ARENA_FIFTEEN_SECONDS);
        }
        // delay expired (1 minute)
        else if (GetStartDelayTime() <= 0 && !(m_Events & 0x10))
        {
            m_Events |= 0x10;

            for (uint32 i = BG_NA_OBJECT_DOOR_1; i <= BG_NA_OBJECT_DOOR_2; i++)
                DoorOpen(i);

            for (uint32 i = BG_NA_OBJECT_BUFF_1; i <= BG_NA_OBJECT_BUFF_2; i++)
                SpawnBGObject(i, 60);

            SendMessageToAll(LANG_ARENA_BEGUN);
            SetStatus(STATUS_IN_PROGRESS);
            SetStartDelayTime(0);

            for (BattleGroundPlayerMap::const_iterator itr = GetPlayers().begin(); itr != GetPlayers().end(); ++itr)
                if (Player *plr = sObjectMgr.GetPlayer(itr->first))
                    plr->RemoveAurasDueToSpell(SPELL_ARENA_PREPARATION);

            if (!GetPlayersCountByTeam(ALLIANCE) && GetPlayersCountByTeam(HORDE))
                EndBattleGround(HORDE);
            else if (GetPlayersCountByTeam(ALLIANCE) && !GetPlayersCountByTeam(HORDE))
                EndBattleGround(ALLIANCE);
        }
    }

    /*if(GetStatus() == STATUS_IN_PROGRESS)
    {
        // update something
    }*/
}
示例#27
0
int Connections::Create(Network* pNetwork)
{
    FUNCTION_BEGIN();


    if (IsStatus(CONNSTATUS_CREATE))
    {
        Logger::Log("true == IsStatus( STATUS_CREATE )\n");
        return 1;
    }


    if (NULL == pNetwork)
    {
        Logger::Log("NULL == pNetwork\n");
        return 2;
    }


    if (NULL != _NetworkRef)
    {
        Logger::Log("NULL != _NetworkRef, _NetworkRef = %016x\n", _NetworkRef);
        return 3;
    }


    if (false == _recvBuffer.Create(GetMaxRecvPacketCount(), GetMaxRecvPacketSize()))
    {
        return 4;
    }


    if (false == _sendBuffer.Create(GetMaxSendPacketCount(), GetMaxRecvPacketSize()))
    {
        return 5;
    }


    int rc = _socket.Create();
    if (0 != rc)
    {
        return rc;
    }


    rc = _socket.SetKeepAlive(CONNECTION_KEEP_ALIVE_TIME, CONNECTION_KEEP_ALIVE_INTERVAL);
    if (0 != rc)
    {
        return rc;
    }


    rc = _socket.SetLinger(true, 0);
    if (0 != rc)
    {
        return rc;
    }

    _PacketEncoder = GetPacketEncoder();

    _NetworkRef = pNetwork;


    SetStatus(CONNSTATUS_CREATE);

    return 0;
}
示例#28
0
static void Cn3D_ExportKin(IteM i)
{
    PDNMS pdnmsThis = NULL;
    PMSD pmsdThis = NULL;
    Char pcSavestr[60];
    Char pcSavename[32];
    CharPtr Cn3D_pcKinName;
    GrouP g, g2, g3, g4;
    GrouP gMS;
    ButtoN b;
    Int2 iCount;

    if (Cn3D_Export_InUse)
        return;
    else
        Cn3D_Export_InUse = TRUE;

    pdnmsThis = GetSelectedModelstruc();
    if (!pdnmsThis) {
        Cn3D_Export_InUse = FALSE;
        return;
    }
    pmsdThis = (PMSD) pdnmsThis->data.ptrvalue;

    Cn3D_wKinSave = ModalWindow(-20, -13, -10, -10, NULL);

    /* set up a group encolosing structures - models selection lists and - "info strings" */
    Cn3D_pcKinName = StringSave(GetStrucStrings(pdnmsThis, PDB_ACC));
    sprintf(pcSavestr, "Save %s As a Kinemage Rendered File ...",
            Cn3D_pcKinName);
    g = HiddenGroup(Cn3D_wKinSave, 0, 5, NULL);
    SetGroupMargins(g, 10, 10);
    SetGroupSpacing(g, 10, 5);
    StaticPrompt(g, pcSavestr, 0, 0, systemFont, 'l');
    g2 = HiddenGroup(g, 2, 0, NULL);
    SetGroupMargins(g2, 10, 10);
    SetGroupSpacing(g2, 10, 5);
    StringNCpy(pcSavename, Cn3D_pcKinName, 8);
    StringCat(pcSavename, ".kin");
    Cn3D_tKinSave =
        DialogText(g2, pcSavename, 18, (TxtActnProc) Cn3D_KinEnableProc);
    MemFree(Cn3D_pcKinName);

    Cn3D_bKinBrowse =
        PushButton(g2, " browse...", (BtnActnProc) Cn3D_KinBrowseProc);
    g3 = HiddenGroup(g, 2, 0, NULL);
    gMS = Cn3D_ModelSelect(g3, FALSE); /* no vector models for Kin files saves */
    g4 = HiddenGroup(g3, 0, 2, NULL);
    SetGroupMargins(g4, 10, 10);
    SetGroupSpacing(g4, 10, 5);
    Cn3D_bKinOk = PushButton(g4, "OK", Cn3D_ExportKinNow);
    b = PushButton(g4, "Cancel", Cn3D_CancelKin);

    Cn3D_gColorAtoms =
        NormalGroup(g, 2, 2, " color by...", systemFont, NULL);
    SetGroupMargins(Cn3D_gColorAtoms, 10, 10);
    SetGroupSpacing(Cn3D_gColorAtoms, 10, 5);
    RadioButton(Cn3D_gColorAtoms, "Molecule number");
    RadioButton(Cn3D_gColorAtoms, "Secondary Structure & Residue Type");
    RadioButton(Cn3D_gColorAtoms, "Thermal Factors");
    RadioButton(Cn3D_gColorAtoms, "Element");
    SetValue(Cn3D_gColorAtoms, 1);

    Cn3D_gRenderOpts =
        NormalGroup(g, 2, 3, " viewable subsets...", systemFont, NULL);
    Cn3D_bRender[0] = CheckBox(Cn3D_gRenderOpts, "Virtual Backbone", NULL);
    Cn3D_bRender[1] = CheckBox(Cn3D_gRenderOpts, "Real Backbone", NULL);
    Cn3D_bRender[2] = CheckBox(Cn3D_gRenderOpts, "Residues", NULL);
    Cn3D_bRender[3] = CheckBox(Cn3D_gRenderOpts, "Heterogens", NULL);
    Cn3D_bRender[4] =
        CheckBox(Cn3D_gRenderOpts, "Alternate Conformations", NULL);
    Cn3D_bRender[5] = CheckBox(Cn3D_gRenderOpts, "NMR Animations", NULL);
    for (iCount = 0; iCount < 6; iCount++)
        SetStatus(Cn3D_bRender[iCount], TRUE);

    Cn3D_KinEnableProc(NULL);
    Select(Cn3D_bKinOk);
    /* disable appropriate stuff here */
    Cn3D_DisableFileOps();
    Show(Cn3D_wKinSave);

    return;
}
示例#29
0
bool
Job::TerminateFailure()
{
	SetStatus( STATUS_ERROR );
	return true;
} 
示例#30
0
文件: HttpHelper.cpp 项目: azalpy/sdk
HttpHelper::HttpHelper()
{
	InitStatus();
	SetStatus(200, NULL);
}