/////////////////////////////////////////////////////////////
//
// CProxyDirect3DIndexBuffer::Lock
//
// For stats
//
/////////////////////////////////////////////////////////////
HRESULT CProxyDirect3DIndexBuffer::Lock(UINT OffsetToLock, UINT SizeToLock, void** ppbData, DWORD Flags)
{
    m_stats.iLockedCount++;

    *ppbData = NULL;
    HRESULT hr = m_pOriginal->Lock(OffsetToLock, SizeToLock, ppbData, Flags);

    if (FAILED(hr))
    {
        SString strMessage("Lock IndexBuffer fail: hr:%x Length:%x Usage:%x Format:%x Pool:%x OffsetToLock:%x SizeToLock:%x Flags:%x", hr, m_iMemUsed,
                           m_dwUsage, m_format, m_pool, OffsetToLock, SizeToLock, Flags);
        WriteDebugEvent(strMessage);
        AddReportLog(8625, strMessage);
        CCore::GetSingleton().LogEvent(625, "Lock IndexBuffer", "", strMessage);
    }
    else if (*ppbData == NULL)
    {
        SString strMessage("Lock IndexBuffer result NULL: hr:%x Length:%x Usage:%x Format:%x Pool:%x OffsetToLock:%x SizeToLock:%x Flags:%x", hr, m_iMemUsed,
                           m_dwUsage, m_format, m_pool, OffsetToLock, SizeToLock, Flags);
        WriteDebugEvent(strMessage);
        AddReportLog(8626, strMessage);
        CCore::GetSingleton().LogEvent(626, "Lock IndexBuffer NULL", "", strMessage);
    }
    return hr;
}
Esempio n. 2
0
//Decode all the .gnt files in the file list.
void QxMainWindow::decodeAll()
{
	if (m_FileList.isEmpty())
	{
		QString strTitle("No selected files");
		QString strMessage("No files selected yet. Please press \"Open\" to select files first.");
		QMessageBox::information(this, strTitle, strMessage, QMessageBox::Ok);
		return;
	}

	// If user clicks "Cancel" button when selection decoding options, do not decode files.
	QxDecodeOptionDlg dlg(m_FileList, this);
	if (dlg.exec() != QxDecodeOptionDlg::Accepted)
	{
		return;
	}

	// get selected application, image size, as well as image format
	unsigned uImageSize = dlg.imageSize();
	cv::Size imageSize(uImageSize, uImageSize);
	QString strImageFormat = dlg.imageFormat();
	QString strDestinationPath = dlg.filePath();
	QxDecodeOptionDlg::ApplicationType appType = dlg.application();

	//If files are successfully decode, show a messagebox to inform user.
	if (decodeFiles(m_FileList, strDestinationPath, strImageFormat, imageSize, appType))
	{
		QString strMessage("Files successfully decoded.");
		QMessageBox::information(this, "Result", strMessage, QMessageBox::Ok);
	}
}
/////////////////////////////////////////////////////////////
//
// CProxyDirect3DVertexBuffer::Lock
//
// If lock is writable, tell manager that range content will change
//
/////////////////////////////////////////////////////////////
HRESULT CProxyDirect3DVertexBuffer::Lock ( UINT OffsetToLock, UINT SizeToLock, void** ppbData, DWORD Flags )
{
    m_stats.iLockedCount++;

    if ( ( Flags & D3DLOCK_READONLY ) == 0 )
    {
        CAdditionalVertexStreamManager::GetSingleton ()->OnVertexBufferRangeInvalidated ( m_pOriginal, OffsetToLock, SizeToLock );
        CVertexStreamBoundingBoxManager::GetSingleton ()->OnVertexBufferRangeInvalidated ( m_pOriginal, OffsetToLock, SizeToLock );
    }

    *ppbData = NULL;
    HRESULT hr = m_pOriginal->Lock ( OffsetToLock, SizeToLock, ppbData, Flags );

    if( FAILED( hr ) )
    {
        SString strMessage( "Lock VertexBuffer fail: hr:%x Length:%x Usage:%x FVF:%x Pool:%x OffsetToLock:%x SizeToLock:%x Flags:%x"
                                                        , hr, m_iMemUsed, m_dwUsage, m_dwFVF, m_pool, OffsetToLock, SizeToLock, Flags );
        WriteDebugEvent( strMessage );
        AddReportLog( 8620, strMessage );
        CCore::GetSingleton ().LogEvent ( 620, "Lock VertexBuffer", "", strMessage );
    }
    else
    if ( *ppbData == NULL )
    {
        SString strMessage( "Lock VertexBuffer result NULL: hr:%x Length:%x Usage:%x FVF:%x Pool:%x OffsetToLock:%x SizeToLock:%x Flags:%x"
                                                        , hr, m_iMemUsed, m_dwUsage, m_dwFVF, m_pool, OffsetToLock, SizeToLock, Flags );
        WriteDebugEvent( strMessage );
        AddReportLog( 8621, strMessage );
        CCore::GetSingleton ().LogEvent ( 621, "Lock VertexBuffer NULL", "", strMessage );
    }
    return hr;
}
///////////////////////////////////////////////////////////////
//
// CResourceFileDownloadManager::DownloadFinished
//
// Callback when file download has finished
//
///////////////////////////////////////////////////////////////
void CResourceFileDownloadManager::DownloadFinished(const SHttpDownloadResult& result)
{
    CDownloadableResource* pResourceFile = ResolveDownloadContextString((SString*)result.pObj);
    if (!pResourceFile)
        return;

    assert(ListContains(m_ActiveFileDownloadList, pResourceFile));
    if (result.bSuccess)
    {
        CChecksum checksum = CChecksum::GenerateChecksumFromFile(pResourceFile->GetName());
        if (checksum != pResourceFile->GetServerChecksum())
        {
            // Checksum failed - Try download on next server
            if (BeginResourceFileDownload(pResourceFile, pResourceFile->GetHttpServerIndex() + 1))
            {
                // Was re-added - Add size again to total.
                AddDownloadSize(pResourceFile->GetDownloadSize());
                SString strMessage("External HTTP file mismatch (Retrying this file with internal HTTP) [%s]", *ConformResourcePath(pResourceFile->GetName()));
                g_pClientGame->TellServerSomethingImportant(1011, strMessage, 3);
                return;
            }
        }
    }
    else
    {
        // Download failed due to connection type problem
        CNetHTTPDownloadManagerInterface* pHTTP = g_pNet->GetHTTPDownloadManager(m_HttpServerList[pResourceFile->GetHttpServerIndex()].downloadChannel);
        SString                           strHTTPError = pHTTP->GetError();
        // Disable server from being used (if possible)
        if (DisableHttpServer(pResourceFile->GetHttpServerIndex()))
        {
            //  Try download on next server
            if (BeginResourceFileDownload(pResourceFile, pResourceFile->GetHttpServerIndex() + 1))
            {
                // Was re-added - Add size again to total.
                AddDownloadSize(pResourceFile->GetDownloadSize());
                SString strMessage("External HTTP file download error:[%d] %s (Disabling External HTTP) [%s]", result.iErrorCode, *strHTTPError,
                                   *ConformResourcePath(pResourceFile->GetName()));
                g_pClientGame->TellServerSomethingImportant(1012, strMessage, 3);
                return;
            }
        }
        m_strLastHTTPError = strHTTPError;
    }

    // File now done (or failed)
    ListRemove(m_ActiveFileDownloadList, pResourceFile);
    pResourceFile->SetIsWaitingForDownload(false);
}
Esempio n. 5
0
void CServerBrowser::ProcessConnection( void )
{
	// Attempt to connect to the server
	eNetworkResponse response = pCore->GetNetworkModule()->Connect( m_strServerIP, m_iServerPort, m_strServerPassword );

	// Get the response string
	String strMessage( "An unknown error occurred." );
	switch( response )
	{
	case NETWORK_RESPONSE_SUCCESS: strMessage.Format( "Joining %s:%d...", m_strServerIP.Get(), m_iServerPort ); break;
	case NETWORK_RESPONSE_INVALID_PARAM: strMessage.Set( "An internal error occurred" ); break;
	case NETWORK_RESPONSE_CANT_RESOLVE_DOMAIN: strMessage.Set( "Can't resolve domain name!" ); break;
	case NETWORK_RESPONSE_ALREADY_CONNECTED: strMessage.Set( "You're already connect to a server." ); break;
	case NETWORK_RESPONSE_ALREADY_CONNECTING: strMessage.Set( "A connection attempt is already in progress!" ); break;
	case NETWORK_RESPONSE_SECURITY_FAILED: strMessage.Set( "Security initialisation failed!" ); break;
	case NETWORK_RESPONSE_NO_HOST_SET: strMessage.Set( "An internal error occurred." ); break;
	}

	// Show the message box
	SetMessageBox ( ((int)response == 0 ? "Connecting" : "Failed to connect"), strMessage.Get () );

	// Did we fail to connect?
	if( (int)response > 0 )
	{
		// Set the connection state to failed
		SetConnectionState( CONNECTION_STATE_FAILED );

		// Set the failed time
		m_ulFailedTime = SharedUtility::GetTime();
	}
}
/////////////////////////////////////////////////////////////
//
// CDirect3DEvents9::CreateTexture
//
//
//
/////////////////////////////////////////////////////////////
HRESULT CDirect3DEvents9::CreateTexture ( IDirect3DDevice9 *pDevice, UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture9** ppTexture, HANDLE* pSharedHandle )
{
    HRESULT hr;

    for ( uint i = 0 ; i < 2 ; i++ )
    {
        hr = pDevice->CreateTexture ( Width, Height, Levels, Usage, Format, Pool, ppTexture, pSharedHandle );
        if( SUCCEEDED( hr ) )
            break;

        if ( hr != D3DERR_OUTOFVIDEOMEMORY || i > 0 )
        {
            SString strMessage( "CreateTexture fail: hr:%x W:%x H:%x L:%x Usage:%x Format:%x Pool:%x", hr, Width, Height, Levels, Usage, Format, Pool );
            WriteDebugEvent( strMessage );
            AddReportLog( 8612, strMessage );
            CCore::GetSingleton ().LogEvent ( 612, "CreateTexture", "", strMessage );
            return hr;
        }

        pDevice->EvictManagedResources ();
    }

    // Create proxy so we can track when it's finished with
    *ppTexture = new CProxyDirect3DTexture ( pDevice, *ppTexture, Width, Height, Levels, Usage, Format, Pool );
    return hr;
}
/////////////////////////////////////////////////////////////
//
// CDirect3DEvents9::CreateIndexBuffer
//
//
//
/////////////////////////////////////////////////////////////
HRESULT CDirect3DEvents9::CreateIndexBuffer ( IDirect3DDevice9 *pDevice, UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DIndexBuffer9** ppIndexBuffer, HANDLE* pSharedHandle )
{
    HRESULT hr;

    for ( uint i = 0 ; i < 2 ; i++ )
    {
        hr = pDevice->CreateIndexBuffer ( Length, Usage, Format, Pool, ppIndexBuffer, pSharedHandle );
        if( SUCCEEDED( hr ) )
            break;

        if ( hr != D3DERR_OUTOFVIDEOMEMORY || i > 0 )
        {
            SString strMessage( "CreateIndexBuffer fail: hr:%x Length:%x Usage:%x Format:%x Pool:%x", hr, Length, Usage, Format, Pool );
            WriteDebugEvent( strMessage );
            AddReportLog( 8611, strMessage );
            CCore::GetSingleton ().LogEvent ( 611, "CreateIndexBuffer", "", strMessage );
            return hr;
        }

        pDevice->EvictManagedResources ();
    }

    // Create proxy so we can track when it's finished with
    *ppIndexBuffer = new CProxyDirect3DIndexBuffer ( pDevice, *ppIndexBuffer, Length, Usage, Format, Pool );
    return hr;
}
/////////////////////////////////////////////////////////////
//
// CDirect3DEvents9::CreateVertexBuffer
//
// Creates a proxy object for the new vertex buffer
//
/////////////////////////////////////////////////////////////
HRESULT CDirect3DEvents9::CreateVertexBuffer ( IDirect3DDevice9 *pDevice, UINT Length,DWORD Usage,DWORD FVF,D3DPOOL Pool,IDirect3DVertexBuffer9** ppVertexBuffer,HANDLE* pSharedHandle )
{
    HRESULT hr;

    // We may have to look at the contents to generate normals (Not needed for dynamic buffers)
    if ( ( Usage & D3DUSAGE_DYNAMIC ) == 0 )
        Usage &= -1 - D3DUSAGE_WRITEONLY;

    for ( uint i = 0 ; i < 2 ; i++ )
    {
        hr = pDevice->CreateVertexBuffer ( Length, Usage, FVF, Pool, ppVertexBuffer, pSharedHandle );
        if( SUCCEEDED( hr ) )
            break;

        if ( hr != D3DERR_OUTOFVIDEOMEMORY || i > 0 )
        {
            SString strMessage( "CreateVertexBuffer fail: hr:%x Length:%x Usage:%x FVF:%x Pool:%x", hr, Length, Usage, FVF, Pool );
            WriteDebugEvent( strMessage );
            AddReportLog( 8610, strMessage );
            CCore::GetSingleton ().LogEvent ( 610, "CreateVertexBuffer", "", strMessage );
            return hr;
        }

        pDevice->EvictManagedResources ();
    }

    // Create proxy
    *ppVertexBuffer = new CProxyDirect3DVertexBuffer ( pDevice, *ppVertexBuffer, Length, Usage, FVF, Pool );
    return hr;
}
Esempio n. 9
0
void CClientPlayer::DischargeWeapon ( eWeaponType weaponType, const CVector& vecStart, const CVector& vecEnd, float fBackupDamage, uchar ucBackupHitZone, CClientPlayer* pBackupDamagedPlayer )
{
    if ( m_pPlayerPed )
    {
        g_pApplyDamageLastDamagedPed = NULL;
        g_fApplyDamageLastAmount = 0;

        // Check weapon matches and is enabled for bullet sync
        if ( weaponType == GetCurrentWeaponType () &&
             g_pClientGame->GetWeaponTypeUsesBulletSync ( weaponType ) )
        {
            // Set bullet start and end points
            m_shotSyncData->m_vecRemoteBulletSyncStart = vecStart;
            m_shotSyncData->m_vecRemoteBulletSyncEnd = vecEnd;
            m_shotSyncData->m_bRemoteBulletSyncVectorsValid = true;

            // Fire
            g_iDamageEventLimit = 1;
            CWeapon* pWeapon = m_pPlayerPed->GetWeapon ( m_pPlayerPed->GetCurrentWeaponSlot () );
            pWeapon->FireBullet ( m_pPlayerPed, vecStart, vecEnd );
            g_iDamageEventLimit = -1;

            m_shotSyncData->m_bRemoteBulletSyncVectorsValid = false;
        }

        // Apply extra damage if player has bad network
        if ( pBackupDamagedPlayer && pBackupDamagedPlayer->GetGamePlayer() && pBackupDamagedPlayer->GetWasRecentlyInNetworkInterruption( 1000 ) )
        {
            // Subtract any damage that did get applied during FireBullet
            if ( pBackupDamagedPlayer == g_pApplyDamageLastDamagedPed )
                fBackupDamage -= g_fApplyDamageLastAmount;

            if ( fBackupDamage > 0 )
            {
                // Apply left over damage like what the game would:
                //      CClientPlayer has pre damage health/armor
                //      CPlayerPed has post damage health/armor

                float fPreviousHealth = pBackupDamagedPlayer->m_fHealth;
                float fPreviousArmor = pBackupDamagedPlayer->m_fArmor;

                // Calculate how much damage should be applied to health/armor
                float fArmorDamage = Min( fBackupDamage, pBackupDamagedPlayer->m_fArmor ); 
                float fHealthDamage = Min( fBackupDamage - fArmorDamage, pBackupDamagedPlayer->m_fHealth );

                float fNewArmor = pBackupDamagedPlayer->m_fArmor - fArmorDamage;
                float fNewHealth = pBackupDamagedPlayer->m_fHealth - fHealthDamage;

                // Ensure CPlayerPed has post damage health/armor
                pBackupDamagedPlayer->GetGamePlayer()->SetHealth( fNewHealth );
                pBackupDamagedPlayer->GetGamePlayer()->SetArmor( fNewArmor );

                g_pClientGame->ApplyPedDamageFromGame( weaponType, fBackupDamage, ucBackupHitZone, pBackupDamagedPlayer, this, NULL );

                SString strMessage( "Applied %0.2f damage to %s (from %s) due to network interruption", fBackupDamage, pBackupDamagedPlayer->GetNick(), GetNick() );
                g_pClientGame->TellServerSomethingImportant( 1010, strMessage, false );
            }
        }
    }
}
Esempio n. 10
0
oocl::Message* ChatMessage::create(const char * in)
{
	unsigned int uiUserID = ((unsigned int*)in)[1];
	std::string strMessage( &in[8], ((unsigned short*)in)[1]-4 );

	return new ChatMessage( uiUserID, strMessage );
}
Esempio n. 11
0
//
// CFunctionUseLogger::MaybeFlush
//
void CFunctionUseLogger::MaybeFlush( bool bForce )
{
    CTickCount timeNow = CTickCount::Now();
    for( std::map < SString, SFuncCallRecord >::iterator iter = m_FuncCallRecordMap.begin() ; iter != m_FuncCallRecordMap.end() ; )
    {
        const SFuncCallRecord& callRecord = iter->second;

        // Time to flush this line?
        if ( bForce || ( timeNow - callRecord.timeFirstUsed ).ToInt() > 1500 )
        {
            // Add log line
            SString strMessage( "%s - %s - %s x %d [%s]\n"
                                    , *GetLocalTimeString( true, true )
                                    , *callRecord.strResourceName
                                    , *callRecord.strFunctionName
                                    , callRecord.uiCallCount
                                    , *callRecord.strExampleArgs
                                );

            if ( !m_strLogFilename.empty() )
                FileAppend( m_strLogFilename, strMessage );

            m_FuncCallRecordMap.erase( iter++ );
        }
        else
            ++iter;
    }
}
Esempio n. 12
0
//Save the image names and corresponding labels into a .txt file for Caffe/CNTK/TensorFlow
void QxMainWindow::saveLabelFile(const QString& strFilePath, QxDecodeOptionDlg::ApplicationType appType)
{
	// There's no need to store label files for DIGITS.
	if (appType == QxDecodeOptionDlg::DIGITS)
	{
		return;
	}

	// Use a local file to save path of images and corresponding labels.
	QString strLabelFileName = strFilePath + "/" + g_LabelFileName;
	QFile labelFile(strLabelFileName);
	if (!labelFile.open(QIODevice::WriteOnly | QIODevice::Text))
	{
		QString strTitle("Open file error");
		QString strMessage("Can not open label file:\n");
		strMessage.append(strLabelFileName);
		strMessage.append("\nMaybe you do not have permission to create a new file in the selected folder?");
		strMessage.append("\nOr maybe there is a Read-Only file named \"").append(g_LabelFileName).append("\" in the selected folder?");
		QMessageBox::critical(this, strTitle, strMessage, QMessageBox::Ok);
		return;
	}

	QTextStream textStream(&labelFile);
	for (QMap<QString, quint32>::iterator itr = m_ImageLabelMap.begin(); itr != m_ImageLabelMap.end(); ++itr)
	{
		textStream << getLabelInfo(itr.key(), itr.value(), appType) << "\n";
	}
	labelFile.close();
}
Esempio n. 13
0
////////////////////////////////////////////////
//
// CreateDeviceSecondCallCheck
//
// Check for, and handle subsequent calls to create device
// Know to occur with RTSSHooks.dll (EVGA Precision X on screen display)
//
////////////////////////////////////////////////
bool CreateDeviceSecondCallCheck(HRESULT& hOutResult, IDirect3D9* pDirect3D, UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags,
                                 D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface)
{
    static uint uiCreateCount = 0;

    // Also check for invalid size
    if (pPresentationParameters->BackBufferWidth == 0)
    {
        WriteDebugEvent(SString(" Passing through call #%d to CreateDevice because size is invalid", uiCreateCount));
        return true;
    }

    // Also check for calls from other threads
    if (!IsMainThread())
    {
        SString strMessage(" Passing through call #%d to CreateDevice because not main thread", uiCreateCount);
        WriteDebugEvent(strMessage);
        AddReportLog(8627, strMessage);
        return true;
    }

    if (++uiCreateCount == 1)
        return false;
    WriteDebugEvent(SString(" Passing through call #%d to CreateDevice", uiCreateCount));
    hOutResult = pDirect3D->CreateDevice(Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, ppReturnedDeviceInterface);
    return true;
}
Esempio n. 14
0
	bool ScriptablePluginObject::InvokeDefault(const NPVariant *args, uint32_t argCount,
		NPVariant *result)
	{
		CString strMessage(_T("Welcome to use the IEMode Plugin for firefox!"));
		STRINGZ_TO_NPVARIANT(CStringToNPStringCharacters(strMessage), *result);
		return true;
	}
Esempio n. 15
0
void DlgGroupChat::OnBnClickedBtnsend()
{
	// TODO:  在此添加控件通知处理程序代码
	UpdateData(TRUE);
	if (!m_csGroupMessage.IsEmpty())
	{
		//显示自己发送的消息;
		SYSTEMTIME curtime;
		GetLocalTime(&curtime);
		CString csTime;
		csTime.Format(_T("%4.4d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d"),
			curtime.wYear, curtime.wMonth + 1, curtime.wDay,
			curtime.wHour, curtime.wMinute, curtime.wSecond);


#ifdef UNICODE
		CW2A m_strTemp(m_csGroupMessage.GetBuffer(0));
		std::string strMessage(m_strTemp);
#else
		//MultiByteToWideChar
		std::string strMessage(m_csChatMessage.GetBuffer(0));
#endif
#ifdef UNICODE
		CA2W nickNameTemp(m_userDataMe.nick_name().c_str());
		CString csNickName(nickNameTemp);
#else
		//MultiByteToWideChar
		CString csNickName(m_userData.nick_name().c_str());
#endif
		m_csChatLog.Append(csNickName);
		m_csChatLog.Append(csTime);
		m_csChatLog.Append(_T("\r\n"));
		m_csChatLog.Append(m_csGroupMessage);
		m_csChatLog.Append(_T("\r\n"));

		m_csGroupMessage.SetString(_T(""));
		UpdateData(FALSE);
		//滚动条自动下拉;
		::PostMessage(m_editLog.GetSafeHwnd(), WM_VSCROLL, SB_BOTTOM, 0);

		::SendMessage(GetParent()->m_hWnd, WM_USE_GROUPCHATMESSAGE, (WPARAM)&strMessage, (LPARAM)&m_groupInfo.groupid());
	}
	else
	{
		MessageBox(_T("不能发送空消息"), _T("提示"));
	}	
}
Esempio n. 16
0
///////////////////////////////////////////////////////////////
//
// CResourceChecker::CheckLuaDeobfuscateRequirements
//
// Updates version requirements and returns true if obfuscated
//
///////////////////////////////////////////////////////////////
bool CResourceChecker::CheckLuaDeobfuscateRequirements ( const string& strFileContents, const string& strFileName, const string& strResourceName, bool bClientScript )
{
    // Get embedded version requirements
    SScriptInfo scriptInfo;
    if ( !g_pRealNetServer->GetScriptInfo( strFileContents.c_str(), strFileContents.length(), &scriptInfo ) )
    {
        if ( bClientScript && IsLuaCompiledScript( strFileContents.c_str(), strFileContents.length() ) )
        {
            // Compiled client script with no version info
    #if MTA_DM_VERSION < 0x135 
            SString strMessage( "%s is invalid and will not work in future versions. Please re-compile at http://luac.mtasa.com/", strFileName.c_str() ); 
            CLogger::LogPrint ( SString ( "WARNING: %s %s\n", strResourceName.c_str (), *strMessage ) );
    #else
            SString strMessage( "%s is invalid. Please re-compile at http://luac.mtasa.com/", strFileName.c_str() ); 
            CLogger::LogPrint ( SString ( "ERROR: %s %s\n", strResourceName.c_str (), *strMessage ) );
    #endif
        }
        return false;
    }

    SString strMinServerHostVer = scriptInfo.szMinServerHostVer;
    SString strMinServerRunVer = scriptInfo.szMinServerRunVer;
    SString strMinClientRunVer = scriptInfo.szMinClientRunVer;

    // Check server host requirements
    if ( strMinServerHostVer > m_strReqServerVersion )
    {
        m_strReqServerVersion = strMinServerHostVer;
        m_strReqServerReason = strFileName;
    }

    // Check run requirements
    if ( bClientScript && strMinClientRunVer > m_strReqClientVersion )
    {
        m_strReqClientVersion = strMinClientRunVer;
        m_strReqClientReason = strFileName;
    }
    else
    if ( !bClientScript && strMinServerRunVer > m_strReqServerVersion )
    {
        m_strReqServerVersion = strMinServerRunVer;
        m_strReqServerReason = strFileName;
    }

    return IsLuaObfuscatedScript( strFileContents.c_str(), strFileContents.length() );
}
Esempio n. 17
0
void CNetworkManager::Connect(CString strHost, unsigned short usPort, CString strPass)
{
	// Are we already connected?
	if(IsConnected())
	{
		// Disconnect
		Disconnect();
	}

	// Store the connection info
	SetLastConnection(strHost, usPort, strPass);

	// Attempt to connect
	int iConnectionResult = m_pRakPeer->Connect(strHost.Get(), usPort, strPass.Get(), strPass.GetLength());

	// Set the network state
	SetNetworkState(NETSTATE_CONNECTING);

	// Create the string for the connection message
	CString strMessage("Failed to connected!");

	// Get the result from the connection
	switch(iConnectionResult)
	{
		case 0: strMessage.Format("Connecting to %s:%d...", strHost.Get(), usPort); break;
		case 1: strMessage.Set("Failed to connect! (Invalid parameter)"); break;
		case 2: strMessage.Set("Failed to connect! (Cannot resolve domain name)"); break;
		case 3: strMessage.Set("Failed to connect! (Already connected)"); break;
		case 4: strMessage.Set("Failed to connect! (Connection attempt already in progress)"); break;
		case 5: strMessage.Set("Failed to connect! (Security initialization failed)"); break;
		case 6: strMessage.Set("Failed to connect! (No host set)"); break;
	}

	// Did we fail to connect?
	if(iConnectionResult != 0)
	{
		// Set the network state
		SetNetworkState(NETSTATE_DISCONNECTED);

		// Set the last connection try
		m_uiLastConnectionTry = (unsigned int)SharedUtility::GetTime();
	}

	CGUI* pGUI = g_pCore->GetGUI();
	if (pGUI)
	{
		//pGUI->ClearView(CGUI::GUI_SERVER);
		//pGUI->SetView(CGUI::GUI_SERVER);
	}

	// Output the connection message
	g_pCore->GetChat()->Outputf(true, "#16C5F2%s", strMessage.Get());
}
Esempio n. 18
0
/////////////////////////////////////////////////////////////
//
// CMainMenu::AskUserIfHeWantsToDisconnect
//
// Ask user if he wants to disconnect
//
/////////////////////////////////////////////////////////////
void CMainMenu::AskUserIfHeWantsToDisconnect(uchar menuType)
{
    SStringX strMessage(
        _("This will disconnect you from the current server."
          "\n\nAre you sure you want to disconnect?"));
    CQuestionBox* pQuestionBox = CCore::GetSingleton().GetLocalGUI()->GetMainMenu()->GetQuestionWindow();
    pQuestionBox->Reset();
    pQuestionBox->SetTitle(_("DISCONNECT WARNING"));
    pQuestionBox->SetMessage(strMessage);
    pQuestionBox->SetButton(0, _("No"));
    pQuestionBox->SetButton(1, _("Yes"));
    pQuestionBox->SetCallback(StaticWantsToDisconnectCallBack, (void*)menuType);
    pQuestionBox->Show();
}
Esempio n. 19
0
//Decode selected .gnt file. in the file list.
void QxMainWindow::decodeSelected()
{
	QList<QListWidgetItem*> selectedItems = m_pFileListWidget->selectedItems();
	if (m_FileList.isEmpty() || selectedItems.size()==0)
	{
		QString strTitle("No selected files");
		QString strMessage("No files selected yet. Please select the file you want to decode.\n");
		strMessage.append("If there are no files listed in the file list, please press \"Open\" to select files first.");
		QMessageBox::information(this, strTitle, strMessage, QMessageBox::Ok);
		return;
	}
	QStringList fileList;
	for (QList<QListWidgetItem*>::iterator itr = selectedItems.begin(); itr != selectedItems.end(); ++itr)
	{
		fileList.push_back((*itr)->text());
	}
	QxDecodeOptionDlg dlg(fileList, this);
	if (dlg.exec() != QxDecodeOptionDlg::Accepted)
	{
		return;
	}

	// get selected application, image size, as well as image format
	unsigned uImageSize = dlg.imageSize();
	cv::Size imageSize(uImageSize, uImageSize);
	QString strImageFormat = dlg.imageFormat();
	QString strDestinationPath = dlg.filePath();
	QxDecodeOptionDlg::ApplicationType appType = dlg.application();

	//If files are successfully decode, show a messagebox to inform user.
	if (decodeFiles(fileList, strDestinationPath, strImageFormat, imageSize, appType))
	{
		QString strMessage("Files successfully decoded.");
		QMessageBox::information(this, "Result", strMessage, QMessageBox::Ok);
	}
}
Esempio n. 20
0
	bool Context::makeCurrent(GPU::RenderTarget *target)
	{
		// If the target is null, we are really making the target the hidden window.
		if ( nullptr == target )
			target = mHiddenWindow;

		// Check if the context is already cunrrent on the passed target.
		if ( mTarget == target && this == currentContext )
			return true;

		if ( nullptr != mTarget )
			doneCurrent();

		if ( false == checkPixelFormat(target) )
			return false;

		if ( TRUE == wglMakeCurrent(target->hdc(), mHGLRC) )
		{
			mTarget = target;
			currentContext = this;

			currentGLEW = &mGlewCtxt;
			currentWGLEW = &mWGlewCtxt;

			return true;
		}
		else
		{
			 LPVOID lpMsgBuf;
			 DWORD dw = GetLastError(); 

			 FormatMessage(
				FORMAT_MESSAGE_ALLOCATE_BUFFER | 
				FORMAT_MESSAGE_FROM_SYSTEM |
				FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL,
				dw,
				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
				(LPTSTR) &lpMsgBuf,
				0, NULL );

			// Display the error message and exit the process
			std::string strMessage((char*)lpMsgBuf);
			LocalFree(lpMsgBuf);
		}

		return false;
	}
Esempio n. 21
0
BOOL AFXAPI AfxAssertFailedLine( LPCSTR lpszFileName, int nLine )
/***************************************************************/
{
    CString strMessage( _T("Assertion failed!\n\nFile: ") );
    strMessage += lpszFileName;
    strMessage.AppendFormat( _T("\nLine: %d\n\n"), nLine );
    strMessage += _T("Select Abort to terminate the program.\n");
    strMessage += _T("Select Retry to debug.\n");
    strMessage += _T("Select Ignore to continue execution.");
    int nResult = ::MessageBox( NULL, strMessage, NULL, MB_ABORTRETRYIGNORE );
    if( nResult == IDABORT ) {
        AfxAbort();
    } else if( nResult == IDRETRY ) {
        return( TRUE );
    }
    return( FALSE );
}
Esempio n. 22
0
void IpAddressWidget::okButton()
{
    QString ipAddress = this->getIpAddressString();
    QString port = m_LineEdit->text();
    if( ipAddress.isEmpty() ) {
        QMessageBox::warning( this, tr("Error"), tr("非法ip地址") );
    }
    else if (port.isEmpty()) {
        QMessageBox::warning( this, tr("Error"), tr("非法端口号") );
    }
    else {
        QMessageBox::information(this, tr("ip地址"), ipAddress);
        data.ip = ipAddress;
        data.port = port.toInt();
        emit strMessage(&data);
        accept();
    }
}
Esempio n. 23
0
void CServerBrowser::ProcessNetworkPacket( DefaultMessageIDTypes packet )
{
	// Did we connect?
	if( packet == ID_CONNECTION_REQUEST_ACCEPTED )
	{
		// Set the server information
		pCore->SetHost( m_strServerIP );
		pCore->SetPort( m_iServerPort );

		// Hide the mouse cursor
		pCore->GetGUI()->SetCursorVisible( false );

		// Show the chat
		pCore->GetChat()->SetVisible( true );

		// Hide the message box
		m_pMessageBox->SetVisible ( false );
		return;
	}

	// Get the label text
	String strMessage( "You were disconnected from the server." );
	bool bLost = false;
	switch( packet )
	{
	case ID_NO_FREE_INCOMING_CONNECTIONS: strMessage.Set( "The maximum number of players has been reached." ); break;
	case ID_DISCONNECTION_NOTIFICATION: strMessage.Set( "The connection with the server was closed." ); bLost = true; break;
	case ID_INVALID_PASSWORD: strMessage.Set( "The password you entered was invalid." ); break;
	case ID_CONNECTION_BANNED: strMessage.Set( "You're banned from playing on this server." ); break;
	case ID_CONNECTION_LOST: strMessage.Set( "The connection with the server was lost." ); bLost = true; break;
	case ID_CONNECTION_ATTEMPT_FAILED: strMessage.Set( "Failed to connect to the server." ); break;
	case ID_ALREADY_CONNECTED: strMessage.Set( "You're already connected to a server." ); break;
	}

	// Show the message box
	SetMessageBox ( (bLost ? "Connection terminated" : "Failed to connect"), strMessage.Get () );
}
Esempio n. 24
0
/////////////////////////////////////////////////////////////
//
// CDirect3DEvents9::CreateVertexDeclaration
//
// Creates a proxy object for the new vertex declaration
//
/////////////////////////////////////////////////////////////
HRESULT CDirect3DEvents9::CreateVertexDeclaration ( IDirect3DDevice9 *pDevice, CONST D3DVERTEXELEMENT9* pVertexElements, IDirect3DVertexDeclaration9** ppDecl )
{
    HRESULT hr;

    hr = pDevice->CreateVertexDeclaration ( pVertexElements, ppDecl );
    if ( FAILED(hr) )
    {
        SString strStatus;
        // Make a string with decl info
        for ( uint i = 0 ; i < MAXD3DDECLLENGTH ; i++ )
        {
            const D3DVERTEXELEMENT9& element = pVertexElements[ i ];
            if ( element.Stream == 0xFF )
                break;

            strStatus += SString( "[%d,%d,%d,%d,%d,%d]"
                                    ,element.Stream
                                    ,element.Offset
                                    ,element.Type
                                    ,element.Method
                                    ,element.Usage
                                    ,element.UsageIndex
                                    );
        }

        SString strMessage( "CreateVertexDecl fail: hr:%x %s", hr, *strStatus );
        WriteDebugEvent( strMessage );
        AddReportLog( 8613, strMessage );
        CCore::GetSingleton ().LogEvent ( 613, "CreateVertexDecl", "", strMessage );
        return hr;
    }

    // Create proxy
	*ppDecl = new CProxyDirect3DVertexDeclaration ( pDevice, *ppDecl, pVertexElements );
    return hr;
}
Esempio n. 25
0
IDirect3D9* CDirect3DHook9::API_Direct3DCreate9 ( UINT SDKVersion )
{
    // Get our self instance.
    CDirect3DHook9* pThis = CDirect3DHook9::GetSingletonPtr ( );
    assert( pThis && "API_Direct3DCreate9: No CDirect3DHook9" );

    if ( pThis->m_bDirect3DCreate9Suspended )
        return pThis->m_pfnDirect3DCreate9( SDKVersion );

    // A little hack to get past the loading time required to decrypt the gta 
    // executable into memory...
    if ( !CCore::GetSingleton ( ).AreModulesLoaded ( ) )
    {
        CCore::GetSingleton ( ).SetModulesLoaded ( true );
        CCore::GetSingleton ( ).CreateNetwork ( );
        CCore::GetSingleton ( ).CreateGame ( );
        CCore::GetSingleton ( ).CreateMultiplayer ( );
        CCore::GetSingleton ( ).CreateXML ( );
        CCore::GetSingleton ( ).CreateGUI ( );
    }

    // D3DX_SDK_VERSION checks
    // August 2009 SDK required for shaders to work properly
    #if D3DX_SDK_VERSION != 42
        WriteDebugEvent( "D3DX_SDK_VERSION incorrect " QUOTE_DEFINE( D3DX_SDK_VERSION ) );
        #pragma message( "WARNING: Microsoft DirectX SDK (August 2009) includes missing" )
        #ifndef MTA_DEBUG
            #error "Microsoft DirectX SDK (August 2009) includes missing"
        #endif
    #endif
    if ( !D3DXCheckVersion( D3D_SDK_VERSION, D3DX_SDK_VERSION ) )
    {
        SString strMessage( "D3DXCheckVersion FAILED (D3D_SDK_VERSION: %d  D3DX_SDK_VERSION: %d  SDKVersion: %d)", D3D_SDK_VERSION, D3DX_SDK_VERSION, SDKVersion );
        WriteDebugEvent( strMessage );
        AddReportLog( 9640, strMessage );
    }
    else
    {
        SString strMessage( "D3DXCheckVersion success (D3D_SDK_VERSION: %d  D3DX_SDK_VERSION: %d  SDKVersion: %d)", D3D_SDK_VERSION, D3DX_SDK_VERSION, SDKVersion );
        WriteDebugEvent( strMessage );
    }


    // Create our interface.
    WriteDebugEvent ( "Calling Direct3DCreate9" );
    IDirect3D9* pDirect3D9 = pThis->m_pfnDirect3DCreate9 ( SDKVersion );

    if ( !pDirect3D9 )
    {
        WriteDebugEvent ( "Direct3DCreate9 failed" );

        MessageBoxUTF8 ( NULL, _("Could not initialize Direct3D9.\n\n"
                           "Please ensure the DirectX End-User Runtime and\n"
                           "latest Windows Service Packs are installed correctly.")
                           , _("Error")+_E("CC50"), MB_OK | MB_ICONERROR | MB_TOPMOST  ); // Could not initialize Direct3D9.  Please ensure the DirectX End-User Runtime and latest Windows Service Packs are installed correctly.
        return NULL;
    }

    WriteDebugEvent ( "Direct3DCreate9 succeded" );

    GetServerCache ();

    // Create a proxy device.
    CProxyDirect3D9* pProxyDirect3D9 = new CProxyDirect3D9 ( pDirect3D9 );

    return pProxyDirect3D9;
}
BOOL CPropPageRestore::CheckData()
{
    switch(m_iSource)
    {
    case FILE_MODE:
        if(m_strBackupPath.IsEmpty())
        {
            ::AfxMessageBox(IDS_ERR_NO_BACKUP_PATH);
            CWnd*   pWnd = GetDlgItem(IDC_BACKUP_PATH_EDIT);
            GotoDlgCtrl(pWnd);
            return FALSE;
        }
        else
        {
            if(m_strBackupPath.Find(_T('.')) == -1)
            {
                m_strBackupPath += _T(".4cb");
                CWnd*   pWnd = GetDlgItem(IDC_BACKUP_PATH_EDIT);
                pWnd->SetWindowText(m_strBackupPath);
                pWnd->UpdateWindow();
            }
            CFileStatus tStatus;
            if(!CFile::GetStatus(m_strBackupPath, tStatus))
            {
                ::AfxMessageBox(_T("Specified backup file does not exist."));
                CWnd*   pWnd = GetDlgItem(IDC_BACKUP_PATH_EDIT);
                GotoDlgCtrl(pWnd);
                return FALSE;
            }
        }
        break;
    case TARGET_MODE:
        if(m_strAddress.IsEmpty())
        {
            ::AfxMessageBox(IDS_ERR_NO_ADDRESS);
            CWnd*   pWnd = GetDlgItem(IDC_ADDRESS_EDIT);
            GotoDlgCtrl(pWnd);
            return FALSE;
        }
        break;
    }

    if(m_strProjectPath.IsEmpty())
    {
        ::AfxMessageBox(IDS_ERR_NO_PROJECT_PATH);
        CWnd*   pWnd = GetDlgItem(IDC_PROJECT_PATH_EDIT);
        GotoDlgCtrl(pWnd);
        return FALSE;
    }

    CFileStatus tStatus;
    if(CFile::GetStatus(m_strProjectPath, tStatus))
    {
        CString strMessage(_T("Project Path already exists."));
        ::AfxMessageBox(strMessage);
        m_pMainSheet->SetStatusText(strMessage);
        CWnd*   pWnd = GetDlgItem(IDC_PROJECT_PATH_EDIT);
        GotoDlgCtrl(pWnd);
        return FALSE;
    }
    return TRUE;
}
Esempio n. 27
0
void GProfile::Load()
{
	// if there is no external config file, there is nothing to load.
	if (m_strFile.IsEmpty() || m_strFile == "NONE")
		return;	

	if (m_bCached)
		return;

	// destroy the cached objects
	Destroy();

	if (m_bIsXML)
	{
		//FromXMLFile(m_strFile);
		m_objectContainer.FromXMLFile(m_strFile);
		m_bCached = true;
		return;
	}


	char *szBuffer = 0;
	long dwSize = 0;

#if defined(_WIN32) && !defined(__WINPHONE)
	try {
		// open the file
		HANDLE hFile = CreateFile(m_strFile, 
								  GENERIC_READ, 0, 0, OPEN_EXISTING,
								  FILE_ATTRIBUTE_NORMAL, 0);
		if (INVALID_HANDLE_VALUE == hFile)
			ThrowLastError(m_strFile);

		dwSize = GetFileSize(hFile, NULL); 
		if (dwSize == -1)
			ThrowLastError(m_strFile);
 
		szBuffer = new char[dwSize + 1];
		if (!szBuffer)
			throw -1;

		// read the file
		long dwRead;
		if (!ReadFile(hFile, szBuffer, dwSize, (DWORD *)&dwRead, 0))
		{
			delete [] szBuffer;
			CloseHandle(hFile);
			ThrowLastError(m_strFile);
		}

		// close the file
		CloseHandle(hFile);
	}
	catch(GException &)
	{
		GString strMessage("\nFailed to open a configuration file for this application.\n");
		throw GException(2, (const char *)strMessage);
	}

#else
	// open the file
	GString strTemp;
	int nResult = strTemp.FromFile((const char *)m_strFile, 0);
	if (nResult == 0)
	{
		GString strMessage("\nFailed to open a configuration file for this application.\n");

		throw GException(2, (const char *)strMessage);
	}
	szBuffer = new char[strTemp.Length() + 1];
	memcpy(szBuffer,(const char *)strTemp, strTemp.Length());
	dwSize = strTemp.Length();

#endif


	// terminate the buffer
	szBuffer[dwSize] = 0;
	ProfileParse(szBuffer, dwSize);
	delete [] szBuffer;
}
Esempio n. 28
0
HWND TabView::CreateNewConsole(ConsoleViewCreate* consoleViewCreate, const wstring& strCmdLineInitialDir /*= wstring(L"")*/, const wstring& strCmdLineInitialCmd /*= wstring(L"")*/, DWORD dwBasePriority /*= ULONG_MAX*/)
{
	DWORD dwRows    = g_settingsHandler->GetConsoleSettings().dwRows;
	DWORD dwColumns = g_settingsHandler->GetConsoleSettings().dwColumns;

	MutexLock	viewMapLock(m_viewsMutex);
#if 0
	if (m_views.size() > 0)
	{
		SharedMemory<ConsoleParams>& consoleParams = m_views.begin()->second->GetConsoleHandler().GetConsoleParams();
		dwRows		= consoleParams->dwRows;
		dwColumns	= consoleParams->dwColumns;
	}
	else
	{
		// initialize member variables for the first view
		m_dwRows	= dwRows;
		m_dwColumns	= dwColumns;
	}
#endif
	std::shared_ptr<ConsoleView> consoleView(new ConsoleView(m_mainFrame, m_hWnd, m_tabData, dwRows, dwColumns, strCmdLineInitialDir, strCmdLineInitialCmd, dwBasePriority));
	consoleView->Group(this->IsGrouped());
	UserCredentials userCredentials;

	if( consoleViewCreate->type == ConsoleViewCreate::CREATE )
	{
		consoleViewCreate->u.userCredentials = &userCredentials;

		if (m_tabData->bRunAsUser)
		{
			userCredentials.netOnly = m_tabData->bNetOnly;
#ifdef _USE_AERO
			// Display a dialog box to request credentials.
			CREDUI_INFO ui;
			ui.cbSize = sizeof(ui);
			ui.hwndParent = m_hWnd;
			ui.pszMessageText = m_tabData->strShell.c_str();
			ui.pszCaptionText = L"Run as different user";
			ui.hbmBanner = NULL;

			// we need a target
			WCHAR szModuleFileName[_MAX_PATH] = L"";
			::GetModuleFileName(NULL, szModuleFileName, ARRAYSIZE(szModuleFileName));

			WCHAR szUser    [CREDUI_MAX_USERNAME_LENGTH + 1] = L"";
			WCHAR szPassword[CREDUI_MAX_PASSWORD_LENGTH + 1] = L"";
			wcscpy_s(szUser, ARRAYSIZE(szUser), m_tabData->strUser.c_str());

			try
			{
				if (g_settingsHandler->GetBehaviorSettings2().runAsUserSettings.bUseCredentialProviders)
				{
					ULONG ulAuthPackage = 0;
					std::unique_ptr<BYTE[]> pvInAuthBlob;
					ULONG cbInAuthBlob  = 0;
					std::unique_ptr<void, CoTaskMemFreeHelper> pvOutAuthBlob;
					ULONG cbOutAuthBlob = 0;
					BOOL  fSave         = FALSE;

					if( szUser[0] )
					{
						::CredPackAuthenticationBuffer(
							0,                                //_In_     DWORD dwFlags,
							szUser,                           //_In_     LPTSTR pszUserName,
							szPassword,                       //_In_     LPTSTR pszPassword,
							nullptr,                          //_Out_    PBYTE pPackedCredentials,
							&cbInAuthBlob                     //_Inout_  DWORD *pcbPackedCredentials
							);

						pvInAuthBlob.reset(new BYTE [cbInAuthBlob]);

						if( !::CredPackAuthenticationBuffer(
							0,                                //_In_     DWORD dwFlags,
							szUser,                           //_In_     LPTSTR pszUserName,
							szPassword,                       //_In_     LPTSTR pszPassword,
							pvInAuthBlob.get(),               //_Out_    PBYTE pPackedCredentials,
							&cbInAuthBlob                     //_Inout_  DWORD *pcbPackedCredentials
							) )
							Win32Exception::ThrowFromLastError("CredPackAuthenticationBuffer");
					}

					{
						PVOID pvAuthBlob = nullptr;
						DWORD rc = ::CredUIPromptForWindowsCredentials(
							&ui,                              //_In_opt_     PCREDUI_INFO pUiInfo,
							0,                                //_In_         DWORD dwAuthError,
							&ulAuthPackage,                   //_Inout_      ULONG *pulAuthPackage,
							pvInAuthBlob.get(),               //_In_opt_     LPCVOID pvInAuthBuffer,
							cbInAuthBlob,                     //_In_         ULONG ulInAuthBufferSize,
							&pvAuthBlob,                      //_Out_        LPVOID *ppvOutAuthBuffer,
							&cbOutAuthBlob,                   //_Out_        ULONG *pulOutAuthBufferSize,
							&fSave,                           //_Inout_opt_  BOOL *pfSave,
							pvInAuthBlob.get()                //_In_         DWORD dwFlags
							? CREDUIWIN_IN_CRED_ONLY
							: 0
							);

						if( rc == ERROR_CANCELLED )
							return 0;

						if( rc != NO_ERROR )
							Win32Exception::Throw("CredUIPromptForWindowsCredentials", rc);

						pvOutAuthBlob.reset(pvAuthBlob);
					}

					TCHAR szDomain[CREDUI_MAX_DOMAIN_TARGET_LENGTH + 1] = L"";
					DWORD maxLenName     = CREDUI_MAX_USERNAME_LENGTH      + 1;
					DWORD maxLenPassword = CREDUI_MAX_PASSWORD_LENGTH      + 1;
					DWORD maxLenDomain   = CREDUI_MAX_DOMAIN_TARGET_LENGTH + 1;

					if( !::CredUnPackAuthenticationBuffer(
						0,
						pvOutAuthBlob.get(),
						cbOutAuthBlob,
						szUser,
						&maxLenName,
						szDomain,
						&maxLenDomain,
						szPassword,
						&maxLenPassword
						) )
						Win32Exception::ThrowFromLastError("CredUIPromptForWindowsCredentials");

					userCredentials.SetUser(szUser);
					userCredentials.password = szPassword;

					::SecureZeroMemory(pvOutAuthBlob.get(), cbOutAuthBlob);
				}
				else
				{
					DWORD rc = ::CredUIPromptForCredentials(
						&ui,                                //__in_opt  PCREDUI_INFO pUiInfo,
						szModuleFileName,                   //__in      PCTSTR pszTargetName,
						NULL,                               //__in      PCtxtHandle Reserved,
						0,                                  //__in_opt  DWORD dwAuthError,
						szUser,                             //__inout   PCTSTR pszUserName,
						ARRAYSIZE(szUser),                  //__in      ULONG ulUserNameMaxChars,
						szPassword,                         //__inout   PCTSTR pszPassword,
						ARRAYSIZE(szPassword),              //__in      ULONG ulPasswordMaxChars,
						NULL,                               //__inout   PBOOL pfSave,
						CREDUI_FLAGS_EXCLUDE_CERTIFICATES | //__in      DWORD dwFlags
						CREDUI_FLAGS_ALWAYS_SHOW_UI       |
						CREDUI_FLAGS_GENERIC_CREDENTIALS  |
						CREDUI_FLAGS_DO_NOT_PERSIST
						);

						if( rc == ERROR_CANCELLED )
							return 0;

						if( rc != NO_ERROR )
							Win32Exception::Throw("CredUIPromptForCredentials", rc);

					userCredentials.SetUser(szUser);
					userCredentials.password = szPassword;
				}
			}
			catch(std::exception& err)
			{
				MessageBox(
					boost::str(boost::wformat(Helpers::LoadStringW(IDS_ERR_CANT_START_SHELL_AS_USER)) % L"?" % m_tabData->strUser % err.what()).c_str(),
					L"Error",
					MB_OK|MB_ICONERROR);
				return 0;
			}

#else
			DlgCredentials dlg(m_tabData->strUser.c_str());

			if (dlg.DoModal() != IDOK) return 0;

			userCredentials.user     = dlg.GetUser();
			userCredentials.password = dlg.GetPassword();
#endif
		}
		else
		{
			userCredentials.runAsAdministrator = m_tabData->bRunAsAdministrator;
		}
	}

	HWND hwndConsoleView = consoleView->Create(
											m_hWnd, 
											rcDefault, 
											NULL, 
											WS_CHILD | WS_VISIBLE,// | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 
											0,
											0U,
											reinterpret_cast<void*>(consoleViewCreate));

	if (hwndConsoleView == NULL)
	{
		CString	strMessage(consoleView->GetExceptionMessage());

		if (strMessage.GetLength() == 0)
		{
			strMessage.Format(IDS_ERR_TAB_CREATE_FAILED, m_tabData->strTitle.c_str(), m_tabData->strShell.c_str());
		}

		::MessageBox(m_hWnd, strMessage, L"Error", MB_OK|MB_ICONERROR);

		return 0;
	}

	m_views.insert(ConsoleViewMap::value_type(hwndConsoleView, consoleView));

	return hwndConsoleView;
}
Esempio n. 29
0
//////////////////////////////////////////////////////////
//
// CheckDataFiles
//
// Basic check for some essential files
//
//////////////////////////////////////////////////////////
void CheckDataFiles( void )
{
    const SString strMTASAPath = GetMTASAPath();
    const SString strGTAPath = GetGTAPath();

    const char* dataFilesFiles [] = { "MTA\\cgui\\images\\background_logo.png"
                                     ,"MTA\\cgui\\images\\radarset\\up.png"
                                     ,"MTA\\cgui\\images\\busy_spinner.png"
                                     ,"MTA\\cgui\\images\\rect_edge.png"
                                     ,"MTA\\D3DX9_42.dll"
                                     ,"MTA\\D3DCompiler_42.dll"
                                     ,"MTA\\bass.dll"
                                     ,"MTA\\bass_fx.dll"
                                     ,"MTA\\tags.dll"
                                     ,"MTA\\sa.dat"
                                     ,"MTA\\XInput9_1_0_mta.dll"
                                     ,"MTA\\vea.dll"};

    for ( uint i = 0 ; i < NUMELMS( dataFilesFiles ) ; i++ )
    {
        if ( !FileExists ( PathJoin( strMTASAPath, dataFilesFiles [ i ] ) ) )
        {
            DisplayErrorMessageBox ( _("Load failed. Please ensure that the latest data files have been installed correctly."), _E("CL16"), "mta-datafiles-missing" );
            return ExitProcess( EXIT_ERROR );
        }
    }

    if ( FileSize ( PathJoin( strMTASAPath, "MTA", "bass.dll" ) ) != 0x0001A440 )
    {
        DisplayErrorMessageBox ( _("Load failed. Please ensure that the latest data files have been installed correctly."), _E("CL17"), "mta-datafiles-missing" );
        return ExitProcess( EXIT_ERROR );
    }

    // Check for client file
    if ( !FileExists ( PathJoin( strMTASAPath, CHECK_DM_CLIENT_NAME ) ) )
    {
        DisplayErrorMessageBox ( SString(_("Load failed. Please ensure that %s is installed correctly."),CHECK_DM_CLIENT_NAME), _E("CL18"), "client-missing" );
        return ExitProcess( EXIT_ERROR );
    }

    // Make sure the gta executable exists
    if ( !FileExists( PathJoin( strGTAPath, MTA_GTAEXE_NAME ) ) )
    {
        DisplayErrorMessageBox ( SString ( _("Load failed. Could not find gta_sa.exe in %s."), strGTAPath.c_str () ), _E("CL20"), "gta_sa-missing" );
        return ExitProcess( EXIT_ERROR );
    }

    // Make sure important dll's do not exist in the wrong place
    const char* dllCheckList[] = { "xmll.dll", "cgui.dll", "netc.dll", "libcurl.dll", "pthread.dll" };
    for ( int i = 0 ; i < NUMELMS ( dllCheckList ); i++ )
    {
        if ( FileExists( PathJoin( strGTAPath, dllCheckList[i] ) ) )
        {
            DisplayErrorMessageBox ( SString ( _("Load failed. %s exists in the GTA directory. Please delete before continuing."), dllCheckList[i] ), _E("CL21"), "file-clash" );
            return ExitProcess( EXIT_ERROR );
        }    
    }

    // Check main exe has the correct name
    if ( GetLaunchFilename().CompareI( MTA_EXE_NAME ) == false )
    {
        SString strMessage( _("Main file has an incorrect name (%s)"), *GetLaunchFilename() );
        int iResponse = MessageBoxUTF8 ( NULL, strMessage, _("Error")+_E("CL33"), MB_RETRYCANCEL | MB_ICONERROR | MB_TOPMOST  );
        ReleaseSingleInstanceMutex ();
        if ( iResponse == IDRETRY )
            ShellExecuteNonBlocking( "open", PathJoin ( strMTASAPath, MTA_EXE_NAME ) );            
        return ExitProcess( EXIT_ERROR );
    }

    // Check for possible virus file changing activities
    if ( !VerifyEmbeddedSignature( PathJoin( strMTASAPath, MTA_EXE_NAME ) ) )
    {
        SString strMessage( _("Main file is unsigned. Possible virus activity.\n\nSee online help if MTA does not work correctly.") );
        #if MTASA_VERSION_BUILD > 0 && defined(MTA_DM_CONNECT_TO_PUBLIC) && !defined(MTA_DEBUG)
            DisplayErrorMessageBox( strMessage, _E("CL29"), "maybe-virus1" );
        #endif
    }

    struct {
        const char* szMd5;
        const char* szFilename;
    } integrityCheckList[] = { { "9586E7BE6AE8016932038932D1417241", "bass.dll", },
                               { "B2E49F0C22C8B7D92D615F942BA19353", "bass_aac.dll", },
                               { "569C60F8397C34034E685A303B7404C0", "bass_ac3.dll", },
                               { "0E44BCAC0E940DB2BFB13448E96E4B29", "bass_fx.dll", },
                               { "50AF8A7D49E83A723ED0F70FB682DCFB", "bassflac.dll", },
                               { "BEBA64522AA8265751187E38D1FC0653", "bassmidi.dll", },
                               { "99F4F38007D347CEED482B7C04FDD122", "bassmix.dll", },
                               { "7B52BE6D702AA590DB57A0E135F81C45", "basswma.dll", }, 
                               { "38D7679D3B8B6D7F16A0AA9BF2A60043", "tags.dll", },
                               { "309D860FC8137E5FE9E7056C33B4B8BE", "vea.dll", },
                               { "0602F672BA595716E64EC4040E6DE376", "vog.dll", },
                               { "B37D7DF4A1430DB65AD3EA84801F9EC3", "vvo.dll", },
                               { "47FF3EE45DE53528F1AFD9F5982DF8C7", "vvof.dll", },
                               { "ADFB6D7B61E301761C700652B6FE7CCD", "XInput9_1_0_mta.dll", }, };
    for ( int i = 0 ; i < NUMELMS ( integrityCheckList ); i++ )
    {
        SString strMd5 = CMD5Hasher::CalculateHexString( PathJoin( strMTASAPath, "mta", integrityCheckList[i].szFilename ) );
        if ( !strMd5.CompareI( integrityCheckList[i].szMd5 ) )
        {
            DisplayErrorMessageBox( _("Data files modified. Possible virus activity.\n\nSee online help if MTA does not work correctly."), _E("CL30"), "maybe-virus2" );
            break;
        }    
    }

    // Check for asi files
    {
        bool bFoundInGTADir = !FindFiles( PathJoin( strGTAPath, "*.asi" ), true, false ).empty();
        bool bFoundInMTADir = !FindFiles( PathJoin( strMTASAPath, "mta", "*.asi" ), true, false ).empty();
        if ( bFoundInGTADir || bFoundInMTADir )
        {
            DisplayErrorMessageBox (_( ".asi files are in the 'MTA:SA' or 'GTA: San Andreas' installation directory.\n\n"
                                       "Remove these .asi files if you experience problems with MTA:SA." ), _E("CL28"), "asi-files" );
        }
    }

    // Warning if d3d9.dll exists in the GTA install directory
    if ( FileExists( PathJoin ( strGTAPath, "d3d9.dll" ) ) )
    {
        ShowD3dDllDialog ( g_hInstance, PathJoin ( strGTAPath, "d3d9.dll" ) );
        HideD3dDllDialog ();
    }

    // Remove old log files saved in the wrong place
    SString strMtaDir = PathJoin( strMTASAPath, "mta" );
    if ( strGTAPath.CompareI( strMtaDir ) == false )
    {
        FileDelete( PathJoin( strGTAPath, "CEGUI.log" ) );
        FileDelete( PathJoin( strGTAPath, "logfile.txt" ) );
        FileDelete( PathJoin( strGTAPath, "shutdown.log" ) );
    }
}
Esempio n. 30
0
bool CLuaMain::LoadScriptFromBuffer ( const char* cpInBuffer, unsigned int uiInSize, const char* szFileName )
{
    SString strNiceFilename = ConformResourcePath( szFileName );

    // Decrypt if required
    const char* cpBuffer;
    uint uiSize;
    if ( !g_pRealNetServer->DecryptScript( cpInBuffer, uiInSize, &cpBuffer, &uiSize, strNiceFilename ) )
    {
        SString strMessage( "%s is invalid. Please re-compile at http://luac.mtasa.com/", *strNiceFilename ); 
        g_pGame->GetScriptDebugging()->LogError ( m_luaVM, "Loading script failed: %s", *strMessage );
        return false;
    }

    bool bUTF8;

    // UTF-8 BOM?  Compare by checking the standard UTF-8 BOM
    if ( IsUTF8BOM( cpBuffer, uiSize ) == false )
    {
        // Maybe not UTF-8, if we have a >80% heuristic detection confidence, assume it is
        bUTF8 = ( GetUTF8Confidence ( (const unsigned char*)cpBuffer, uiSize ) >= 80 );
    }
    else
    {
        // If there's a BOM, load ignoring the first 3 bytes
        bUTF8 = true;
        cpBuffer += 3;
        uiSize -= 3;
    }

    // If compiled script, make sure correct chunkname is embedded
    EmbedChunkName( strNiceFilename, &cpBuffer, &uiSize );

    if ( m_luaVM )
    {
        // Are we not marked as UTF-8 already, and not precompiled?
        std::string strUTFScript;
        if ( !bUTF8 && !IsLuaCompiledScript( cpBuffer, uiSize ) )
        {
            std::string strBuffer = std::string(cpBuffer, uiSize);
#ifdef WIN32
            std::setlocale(LC_CTYPE,""); // Temporarilly use locales to read the script
            strUTFScript = UTF16ToMbUTF8(ANSIToUTF16( strBuffer ));
            std::setlocale(LC_CTYPE,"C");
#else
            strUTFScript = UTF16ToMbUTF8(ANSIToUTF16( strBuffer ));
#endif

            if ( uiSize != strUTFScript.size() )
            {
                uiSize = strUTFScript.size();
                g_pGame->GetScriptDebugging()->LogWarning ( m_luaVM, "Script '%s' is not encoded in UTF-8.  Loading as ANSI...", strNiceFilename.c_str() );
            }
        }
        else
            strUTFScript = std::string(cpBuffer, uiSize);

        // Run the script
        if ( CLuaMain::LuaLoadBuffer ( m_luaVM, bUTF8 ? cpBuffer : strUTFScript.c_str(), uiSize, SString ( "@%s", *strNiceFilename ) ) )
        {
            // Print the error
            std::string strRes = lua_tostring( m_luaVM, -1 );
            if ( strRes.length () )
            {
                CLogger::LogPrintf ( "SCRIPT ERROR: %s\n", strRes.c_str () );
                g_pGame->GetScriptDebugging()->LogError ( m_luaVM, "Loading script failed: %s", strRes.c_str () );
            }
            else
            {
                CLogger::LogPrint ( "SCRIPT ERROR: Unknown\n" );
                g_pGame->GetScriptDebugging()->LogError ( m_luaVM, "Loading script failed for unknown reason" );
            }
        }
        else
        {
            ResetInstructionCount ();
            int luaSavedTop = lua_gettop ( m_luaVM );
            int iret = this->PCall ( m_luaVM, 0, LUA_MULTRET, 0 ) ;
            if ( iret == LUA_ERRRUN || iret == LUA_ERRMEM )
            {
                SString strRes = lua_tostring( m_luaVM, -1 );
                g_pGame->GetScriptDebugging()->LogPCallError( m_luaVM, strRes, true );
            }
            // Cleanup any return values
            if ( lua_gettop ( m_luaVM ) > luaSavedTop )
                lua_settop( m_luaVM, luaSavedTop );
            return true;
        }
    }

    return false;
}