Example #1
0
static bool PlatformPathEqual(const std::string &a, const std::string &b)
{
    // Case-sensitivity is actually per-volume on both Windows and OS X,
    // but it is extremely tedious to implement and test for little benefit.
#if defined(WIN32)
    std::wstring wa = Widen(a), wb = Widen(b);
    return std::equal(wa.begin(), wa.end(), wb.begin(), /*wb.end(),*/
                [](wchar_t wca, wchar_t wcb) { return towlower(wca) == towlower(wcb); });
#elif defined(__APPLE__)
    return !strcasecmp(a.c_str(), b.c_str());
#else
    return a == b;
#endif
}
Example #2
0
HBITMAP LoadLocalPNG( const std::string& sPath, const RASize& sz )
{
	SetCurrentDirectory( Widen( g_sHomeDir ).c_str() );

	ASSERT( _FileExists( sPath ) );
	if( !_FileExists( sPath ) )
	{
		RA_LOG( "File could not be found: %s\n", sPath.c_str() );
		return nullptr;
	}

	HBITMAP hRetVal = nullptr;
	// Step 2: Decode the source image to IWICBitmapSource
	IWICBitmapDecoder* pDecoder = nullptr;
	HRESULT hr = g_UserImageFactoryInst.m_pIWICFactory->CreateDecoderFromFilename( Widen( sPath ).c_str(),			// Image to be decoded
																				   nullptr,							// Do not prefer a particular vendor
																				   GENERIC_READ,					// Desired read access to the file
																				   WICDecodeMetadataCacheOnDemand,	// Cache metadata when needed
																				   &pDecoder );						// Pointer to the decoder
	
	// Retrieve the first frame of the image from the decoder
	IWICBitmapFrameDecode* pFrame = nullptr;
	if( SUCCEEDED( hr ) )
		hr = pDecoder->GetFrame( 0, &pFrame );

	// Retrieve IWICBitmapSource from the frame
	if( SUCCEEDED( hr ) )
	{
		SAFE_RELEASE( g_UserImageFactoryInst.m_pOriginalBitmapSource );	//##SD ???
		pFrame->QueryInterface( IID_IWICBitmapSource, reinterpret_cast<void**>( &g_UserImageFactoryInst.m_pOriginalBitmapSource ) );
	}

	// Step 3: Scale the original IWICBitmapSource to the client rect size
	// and convert the pixel format
	IWICBitmapSource* pToRenderBitmapSource = nullptr;
	if( SUCCEEDED( hr ) )
		hr = ConvertBitmapSource( { 0, 0, sz.Width(), sz.Height() }, pToRenderBitmapSource );

	// Step 4: Create a DIB from the converted IWICBitmapSource
	if( SUCCEEDED( hr ) )
		hr = UserImageFactory_CreateDIBSectionFromBitmapSource( pToRenderBitmapSource, hRetVal );

	SAFE_RELEASE( pToRenderBitmapSource );
	SAFE_RELEASE( pDecoder );
	SAFE_RELEASE( pFrame );
	SAFE_RELEASE( g_UserImageFactoryInst.m_pOriginalBitmapSource );
	
	return hRetVal;
}
Example #3
0
void RADebugLog( const char* format, ... )
{
	char buf[ 4096 ];
	char* p = buf;

	va_list args;
	va_start( args, format );
	int n = _vsnprintf_s( p, 4096, sizeof buf - 3, format, args ); // buf-3 is room for CR/LF/NUL
	va_end( args );

	p += ( n < 0 ) ? sizeof buf - 3 : n;

	while( ( p > buf ) && ( isspace( p[ -1 ] ) ) )
		*--p = '\0';

	*p++ = '\r';
	*p++ = '\n';
	*p   = '\0';

	OutputDebugString( Widen( buf ).c_str() );
	
	//SetCurrentDirectory( g_sHomeDir.c_str() );//?
	FILE* pf = NULL;
	if( fopen_s( &pf, RA_LOG_FILENAME, "a" ) == 0 )
	{
		fwrite( buf, sizeof(char), strlen( buf ), pf );
		fclose( pf );
	}
}
Example #4
0
//	static
BOOL AchievementSet::DeletePatchFile( AchievementSetType nSet, GameID nGameID )
{
	if( nGameID != 0 )
	{
		std::string sFilename = AchievementSet::GetAchievementSetFilename( nGameID );
							
		//	Remove the text file
		SetCurrentDirectory( Widen( g_sHomeDir ).c_str() );
		
		if( _access( sFilename.c_str(), 06 ) != -1 )	//	06= Read/write permission
		{
			if( remove( sFilename.c_str() ) == -1 )
			{
				//	Remove issues?
				ASSERT( !"Could not remove patch file!?" );
				return FALSE;
			}
		}

		return TRUE;
	}
	else
	{
		//	m_nGameID == 0, therefore there will be no patch file.
		return TRUE;
	}
}
void Dlg_AchievementsReporter::SetupColumns( HWND hList )
{
	//	Remove all columns,
	while( ListView_DeleteColumn( hList, 0 ) ) {}

	//	Remove all data.
	ListView_DeleteAllItems( hList );

	LV_COLUMN col;
	ZeroMemory( &col, sizeof( col ) );

	for( size_t i = 0; i < SIZEOF_ARRAY( COL_TITLE ); ++i )
	{
		col.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM | LVCF_FMT;
		col.cx = COL_SIZE[ i ];
		col.cchTextMax = 255;
		std::wstring sStrWide = Widen( COL_TITLE[ i ] );
		col.pszText = const_cast<LPWSTR>( sStrWide.c_str() );
		col.iSubItem = i;

		col.fmt = LVCFMT_LEFT | LVCFMT_FIXED_WIDTH;
		if( i == SIZEOF_ARRAY( COL_TITLE ) - 1 )
			col.fmt |= LVCFMT_FILL;

		ListView_InsertColumn( hList, i, reinterpret_cast<LPARAM>( &col ) );
	}

	ms_nNumOccupiedRows = 0;
}
Example #6
0
const char* CCONV _RA_InstallIntegration()
{
	SetErrorMode( 0 );
	
#ifdef _DEBUG
	g_hRADLL = LoadLibraryEx( TEXT( "RA_Integration_d.dll" ), nullptr, 0 );
#else
	g_hRADLL = LoadLibrary( TEXT( "RA_Integration.dll" ) );
#endif
	if( g_hRADLL == NULL )
	{
		char buffer[ 1024 ];
		sprintf_s( buffer, 1024, "LoadLibrary failed: %d : %s\n", ::GetLastError(), GetLastErrorAsString().c_str() );

#ifdef UNICODE
		MessageBox( nullptr, Widen( buffer ).c_str(), _T( "Sorry!" ), MB_OK );
#else
		MessageBox( nullptr, buffer, _T( "Sorry!" ), MB_OK );
#endif

		return "0.000";
	}

	//	Install function pointers one by one
 
	_RA_IntegrationVersion	= (const char*(CCONV *)())								GetProcAddress( g_hRADLL, "_RA_IntegrationVersion" );
	_RA_InitI				= (int(CCONV *)(HWND, int, const char*))				GetProcAddress( g_hRADLL, "_RA_InitI" );
	_RA_Shutdown			= (int(CCONV *)())										GetProcAddress( g_hRADLL, "_RA_Shutdown" );
	_RA_UserLoggedIn		= (bool(CCONV *)())										GetProcAddress( g_hRADLL, "_RA_UserLoggedIn" );
	_RA_Username			= (const char*(CCONV *)())								GetProcAddress( g_hRADLL, "_RA_Username" );
	_RA_AttemptLogin		= (void(CCONV *)(bool))									GetProcAddress( g_hRADLL, "_RA_AttemptLogin" );
	_RA_UpdateOverlay		= (int(CCONV *)(ControllerInput*, float, bool, bool))	GetProcAddress( g_hRADLL, "_RA_UpdateOverlay" );
	_RA_UpdatePopups		= (int(CCONV *)(ControllerInput*, float, bool, bool))	GetProcAddress( g_hRADLL, "_RA_UpdatePopups" );
	_RA_RenderOverlay		= (void(CCONV *)(HDC, RECT*))							GetProcAddress( g_hRADLL, "_RA_RenderOverlay" );
	_RA_RenderPopups		= (void(CCONV *)(HDC, RECT*))							GetProcAddress( g_hRADLL, "_RA_RenderPopups" );
	_RA_OnLoadNewRom		= (int(CCONV *)(const BYTE*, unsigned int))				GetProcAddress( g_hRADLL, "_RA_OnLoadNewRom" );
	_RA_InstallMemoryBank	= (void(CCONV *)(int, void*, void*, int))				GetProcAddress( g_hRADLL, "_RA_InstallMemoryBank" );
	_RA_ClearMemoryBanks	= (void(CCONV *)())										GetProcAddress( g_hRADLL, "_RA_ClearMemoryBanks" );
	_RA_UpdateAppTitle		= (void(CCONV *)(const char*))							GetProcAddress( g_hRADLL, "_RA_UpdateAppTitle" );
	_RA_HandleHTTPResults	= (void(CCONV *)())										GetProcAddress( g_hRADLL, "_RA_HandleHTTPResults" );
	_RA_ConfirmLoadNewRom	= (bool(CCONV *)(bool))									GetProcAddress( g_hRADLL, "_RA_ConfirmLoadNewRom" );
	_RA_CreatePopupMenu		= (HMENU(CCONV *)(void))								GetProcAddress( g_hRADLL, "_RA_CreatePopupMenu" );
	_RA_InitDirectX			= (void(CCONV *)(void))									GetProcAddress( g_hRADLL, "_RA_InitDirectX" );
	_RA_OnPaint				= (void(CCONV *)(HWND))									GetProcAddress( g_hRADLL, "_RA_OnPaint" );
	_RA_InvokeDialog		= (void(CCONV *)(LPARAM))								GetProcAddress( g_hRADLL, "_RA_InvokeDialog" );
	_RA_SetPaused			= (void(CCONV *)(bool))									GetProcAddress( g_hRADLL, "_RA_SetPaused" );
	_RA_OnLoadState			= (void(CCONV *)(const char*))							GetProcAddress( g_hRADLL, "_RA_OnLoadState" );
	_RA_OnSaveState			= (void(CCONV *)(const char*))							GetProcAddress( g_hRADLL, "_RA_OnSaveState" );
	_RA_DoAchievementsFrame = (void(CCONV *)())										GetProcAddress( g_hRADLL, "_RA_DoAchievementsFrame" );
	_RA_SetConsoleID		= (int(CCONV *)(unsigned int))							GetProcAddress( g_hRADLL, "_RA_SetConsoleID" );
	_RA_HardcoreModeIsActive= (int(CCONV *)())										GetProcAddress( g_hRADLL, "_RA_HardcoreModeIsActive" );
	_RA_HTTPGetRequestExists= (int(CCONV *)(const char*))							GetProcAddress( g_hRADLL, "_RA_HTTPGetRequestExists" );

	_RA_InstallSharedFunctions = ( void(CCONV *)( bool(*)(), void(*)(), void(*)(), void(*)(char*), void(*)(), void(*)(const char*) ) ) GetProcAddress( g_hRADLL, "_RA_InstallSharedFunctions" );

	return _RA_IntegrationVersion ? _RA_IntegrationVersion() : "0.000";
}
Example #7
0
 std::string ToString(const Line& line) const
 {
   std::string res;
   for (uint_t idx = 0; idx != Fields; ++idx)
   {
     res += Widen(line[idx], Widths[idx] + 1);
   }
   *res.rbegin() = '\n';
   return res;
 }
Example #8
0
	std::wstring FromLocaleStr(std::string s)
	{
#ifdef WIN32
		wchar_t wcs[MAX_STRING_SIZE];
		size_t len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), s.length(), wcs, MAX_STRING_SIZE);
		wcs[len] = 0;
#else
		return Widen(s);
#endif
	}
int Dlg_AchievementsReporter::AddAchievementToListBox( HWND hList, const Achievement* pAch )
{
	for( size_t i = 0; i < NumReporterColumns; ++i )
	{
		switch( i )
		{
		case Checked:
			sprintf_s( ms_lbxData[ ms_nNumOccupiedRows ][ i ], MAX_TEXT_LEN, "" );
			break;
		case Title:
			sprintf_s( ms_lbxData[ ms_nNumOccupiedRows ][ i ], MAX_TEXT_LEN, pAch->Title().c_str() );
			break;
		case Desc:
			sprintf_s( ms_lbxData[ ms_nNumOccupiedRows ][ i ], MAX_TEXT_LEN, pAch->Description().c_str() );
			break;
		case Author:
			sprintf_s( ms_lbxData[ ms_nNumOccupiedRows ][ i ], MAX_TEXT_LEN, pAch->Author().c_str() );
			break;
		case Achieved:
			sprintf_s( ms_lbxData[ ms_nNumOccupiedRows ][ i ], MAX_TEXT_LEN, !pAch->Active() ? "Yes" : "No" );
			break;
		default:
			ASSERT( !"Unknown col!" );
			break;
		}
	}

	LV_ITEM item;
	ZeroMemory( &item, sizeof( item ) );

	item.mask = LVIF_TEXT;
	item.cchTextMax = 256;
	item.iItem = ms_nNumOccupiedRows;

	for( size_t i = 0; i < NumReporterColumns; ++i )
	{
		item.iSubItem = i;
		std::wstring sStrWide = Widen( ms_lbxData[ ms_nNumOccupiedRows ][ i ] );	//Scoped cache
		item.pszText = const_cast<LPWSTR>( sStrWide.c_str() );

		if( i == 0 )
			item.iItem = ListView_InsertItem( hList, &item );
		else
			ListView_SetItem( hList, &item );
	}

	ASSERT( item.iItem == ms_nNumOccupiedRows );

	ms_nNumOccupiedRows++;	//	Last thing to do!
	return item.iItem;
}
void Dlg_MemBookmark::ImportFromFile( std::string sFilename )
{
	FILE* pFile = nullptr;
	errno_t nErr = fopen_s( &pFile, sFilename.c_str(), "r" );
	if ( pFile != nullptr )
	{
		Document doc;
		doc.ParseStream( FileStream( pFile ) );
		if ( !doc.HasParseError() )
		{
			if ( doc.HasMember( "Bookmarks" ) )
			{
				ClearAllBookmarks();

				const Value& BookmarksData = doc[ "Bookmarks" ];
				for ( SizeType i = 0; i < BookmarksData.Size(); ++i )
				{
					MemBookmark* NewBookmark = new MemBookmark();

					wchar_t buffer[ 256 ];
					swprintf_s ( buffer, 256, L"%s", Widen( BookmarksData[ i ][ "Description" ].GetString() ).c_str() );
					NewBookmark->SetDescription ( buffer );

					NewBookmark->SetAddress( BookmarksData[ i ][ "Address" ].GetUint() );
					NewBookmark->SetType( BookmarksData[ i ][ "Type" ].GetInt() );
					NewBookmark->SetDecimal( BookmarksData[ i ][ "Decimal" ].GetBool() );

					NewBookmark->SetValue( GetMemory( NewBookmark->Address(), NewBookmark->Type() ) );
					NewBookmark->SetPrevious ( NewBookmark->Value() );

					AddBookmark ( NewBookmark );
					AddBookmarkMap( NewBookmark );
				}

				if ( m_vBookmarks.size() > 0 )
					PopulateList();
			}
			else
			{
				ASSERT ( " !Invalid Bookmark File..." );
				MessageBox( nullptr, _T("Could not load properly. Invalid Bookmark file."), _T("Error"), MB_OK | MB_ICONERROR );
				return;
			}
		}

		fclose( pFile );
	}
}
Example #11
0
bool GxSystemInterfaceWin32::GetClipboardText(GxString& text)
{
	if(!OpenClipboard(NULL)) return false;

	bool success = false;
	HANDLE hData = GetClipboardData(CF_TEXT);
	char* source = (char*)GlobalLock(hData);
	if(source != NULL)
	{
		GxList<wchar_t> wstr = Widen(source);
		text = GxUnicode::FromWide(wstr.Data());
		success = true;
	}
	GlobalUnlock(hData);
	CloseClipboard();

	return success;
}
Example #12
0
void WriteBufferToFile( const char* sFile, const char* sBuffer, int nBytes )
{
	FILE* pf;
	fopen_s( &pf, sFile, "wb" );
	if( pf != nullptr )
	{
		fwrite( sBuffer, 1, nBytes, pf );
		fclose( pf );
	}
	else
	{
#ifdef UNICODE
		MessageBox( nullptr, _T( "Problems writing file!" ), Widen( sFile ).c_str(), MB_OK );
#else
		MessageBox( nullptr, _T( "Problems writing file!" ), sFile, MB_OK );
#endif
	}
}
Example #13
0
HBITMAP LoadOrFetchBadge( const std::string& sBadgeURI, const RASize& sz )
{
	SetCurrentDirectory( Widen( g_sHomeDir ).c_str() );

	if( !_FileExists( RA_DIR_BADGE + sBadgeURI + ".png" ) )
	{
		PostArgs args;
		args[ 'b' ] = sBadgeURI;
		//	Ensure it's not in the queue to be processed or has been processed, waiting for handling:
		if( !RAWeb::HTTPRequestExists( RequestBadge, sBadgeURI ) && !RAWeb::HTTPResponseExists( RequestBadge, sBadgeURI ) )
			RAWeb::CreateThreadedHTTPRequest( RequestBadge, args, sBadgeURI );

		return NULL;
	}
	else
	{
		return LoadLocalPNG( RA_DIR_BADGE + sBadgeURI + ".png", sz );
	}
}
Example #14
0
HBITMAP LoadOrFetchUserPic( const std::string& sUserName, const RASize& sz )
{
	SetCurrentDirectory( Widen( g_sHomeDir ).c_str() );

	if( !_FileExists( RA_DIR_USERPIC + sUserName + ".png" ) )
	{
		PostArgs args;
		args['u'] = sUserName;
		//	Ensure it's not in the queue to be processed or has been processed, waiting for handling:
		if( !RAWeb::HTTPRequestExists( RequestUserPic, sUserName ) && !RAWeb::HTTPResponseExists( RequestUserPic, sUserName ) )
			RAWeb::CreateThreadedHTTPRequest( RequestUserPic, args, sUserName );

		return NULL;
	}
	else
	{
		return LoadLocalPNG( RA_DIR_USERPIC + sUserName + ".png", sz );
	}
}
Example #15
0
void Iterate(POS *p, int *pv) {

  int val = 0, cur_val = 0;
  U64 nps = 0;
  Timer.SetIterationTiming();
  
  int max_root_depth = Timer.GetData(MAX_DEPTH);

  root_side = p->side;
  SetAsymmetricEval(p->side);

  // Are we operating in slowdown mode or on node limit?

  Timer.special_mode = 0;
  if (Timer.nps_limit 
  || Timer.GetData(MAX_NODES) > 0) Timer.special_mode = 1;

  // Search with increasing depth

  for (root_depth = 1; root_depth <= max_root_depth; root_depth++) {
    int elapsed = Timer.GetElapsedTime();
    if (elapsed) nps = nodes * 1000 / elapsed;

#if defined _WIN32 || defined _WIN64 
    printf("info depth %d time %d nodes %I64d nps %I64d\n", root_depth, elapsed, nodes, nps);
#else
    printf("info depth %d time %d nodes %lld nps %lld\n", root_depth, elapsed, nodes, nps);
#endif

    if (use_aspiration) cur_val = Widen(p, root_depth, pv, cur_val);
    else                cur_val = SearchRoot(p, 0, -INF, INF, root_depth, pv); // full window search

    // don't search too deep with only one move available

    if (root_depth == 8 
    && !fl_has_choice 
    && !Timer.IsInfiniteMode() ) break;

    if (abort_search || Timer.FinishIteration()) break;
    val = cur_val;
  }
}
void Dlg_MemBookmark::AddAddress()
{
	if ( g_pCurrentGameData->GetGameID() == 0 )
		return;

	MemBookmark* NewBookmark = new MemBookmark();

	// Fetch Memory Address from Memory Inspector
	TCHAR buffer[ 256 ];
	GetDlgItemText( g_MemoryDialog.GetHWND(), IDC_RA_WATCHING, buffer, 256 );
	unsigned int nAddr = strtol( Narrow( buffer ).c_str(), nullptr, 16 );
	NewBookmark->SetAddress( nAddr );

	// Check Data Type
	if ( SendDlgItemMessage( g_MemoryDialog.GetHWND(), IDC_RA_MEMVIEW8BIT, BM_GETCHECK, 0, 0 ) == BST_CHECKED )
		NewBookmark->SetType( 1 );
	else if ( SendDlgItemMessage( g_MemoryDialog.GetHWND(), IDC_RA_MEMVIEW16BIT, BM_GETCHECK, 0, 0 ) == BST_CHECKED )
		NewBookmark->SetType( 2 );
	else
		NewBookmark->SetType( 3 );

	// Get Memory Value
	NewBookmark->SetValue( GetMemory( nAddr, NewBookmark->Type() ) );
	NewBookmark->SetPrevious( NewBookmark->Value() );

	// Get Code Note and add as description
	const CodeNotes::CodeNoteObj* pSavedNote = g_MemoryDialog.Notes().FindCodeNote( nAddr );
	if ( ( pSavedNote != nullptr ) && ( pSavedNote->Note().length() > 0 ) )
		NewBookmark->SetDescription( Widen( pSavedNote->Note() ).c_str()  );

	// Add Bookmark to vector and map
	AddBookmark( NewBookmark );
	AddBookmarkMap( NewBookmark );

	PopulateList();
}
Example #17
0
	MyCos100()
	{
		for (int i = 0; i <= (1 << bits); ++i)
			table[i] = Calculate(Widen(i));
	}
Example #18
0
void RangeCheck::OptimizeRangeCheck(BasicBlock* block, GenTreePtr stmt, GenTreePtr treeParent)
{
    // Check if we are dealing with a bounds check node.
    if (treeParent->OperGet() != GT_COMMA)
    {
        return;
    }

    // If we are not looking at array bounds check, bail.
    GenTreePtr tree = treeParent->gtOp.gtOp1;
    if (tree->gtOper != GT_ARR_BOUNDS_CHECK)
    {
        return;
    }

    GenTreeBoundsChk* bndsChk = tree->AsBoundsChk();
    m_pCurBndsChk = bndsChk;
    GenTreePtr treeIndex = bndsChk->gtIndex;

    // Take care of constant index first, like a[2], for example.
    ValueNum idxVn = treeIndex->gtVNPair.GetConservative();
    ValueNum arrLenVn = bndsChk->gtArrLen->gtVNPair.GetConservative();
    int arrSize = GetArrLength(arrLenVn);
    JITDUMP("ArrSize for lengthVN:%03X = %d\n", arrLenVn, arrSize);
    if (m_pCompiler->vnStore->IsVNConstant(idxVn) && arrSize > 0)
    {
        ssize_t idxVal = -1;
        unsigned iconFlags = 0;
        if (!m_pCompiler->optIsTreeKnownIntValue(true, treeIndex, &idxVal, &iconFlags))
        {
            return;
        }

        JITDUMP("[RangeCheck::OptimizeRangeCheck] Is index %d in <0, arrLenVn VN%X sz:%d>.\n", idxVal, arrLenVn, arrSize);
        if (arrSize > 0 && idxVal < arrSize && idxVal >= 0)
        {
            JITDUMP("Removing range check\n");
            m_pCompiler->optRemoveRangeCheck(treeParent, stmt, true, GTF_ASG, true /* force remove */);
            return;
        }
    }

    GetRangeMap()->RemoveAll();
    GetOverflowMap()->RemoveAll();

    // Get the range for this index.
    SearchPath* path = new (m_pCompiler->getAllocator()) SearchPath(m_pCompiler->getAllocator());

    Range range = GetRange(block, stmt, treeIndex, path, false DEBUGARG(0));

    // If upper or lower limit is found to be unknown (top), or it was found to
    // be unknown because of over budget or a deep search, then return early.
    if (range.UpperLimit().IsUnknown() || range.LowerLimit().IsUnknown())
    {
        // Note: If we had stack depth too deep in the GetRange call, we'd be
        // too deep even in the DoesOverflow call. So return early.
        return;
    }

    if (DoesOverflow(block, stmt, treeIndex, path))
    {
        JITDUMP("Method determined to overflow.\n");
        return;
    }

    JITDUMP("Range value %s\n", range.ToString(m_pCompiler->getAllocatorDebugOnly()));
    path->RemoveAll();
    Widen(block, stmt, treeIndex, path, &range);

    // If upper or lower limit is unknown, then return.
    if (range.UpperLimit().IsUnknown() || range.LowerLimit().IsUnknown())
    {
        return;
    }

    // Is the range between the lower and upper bound values.
    if (BetweenBounds(range, 0, bndsChk->gtArrLen))
    {
        JITDUMP("[RangeCheck::OptimizeRangeCheck] Between bounds\n");
        m_pCompiler->optRemoveRangeCheck(treeParent, stmt, true, GTF_ASG, true /* force remove */);
    }
    return;
}
Example #19
0
void RangeCheck::OptimizeRangeCheck(BasicBlock* block, GenTreeStmt* stmt, GenTree* treeParent)
{
    // Check if we are dealing with a bounds check node.
    if (treeParent->OperGet() != GT_COMMA)
    {
        return;
    }

    // If we are not looking at array bounds check, bail.
    GenTree* tree = treeParent->gtOp.gtOp1;
    if (!tree->OperIsBoundsCheck())
    {
        return;
    }

    GenTreeBoundsChk* bndsChk = tree->AsBoundsChk();
    m_pCurBndsChk             = bndsChk;
    GenTree* treeIndex        = bndsChk->gtIndex;

    // Take care of constant index first, like a[2], for example.
    ValueNum idxVn    = m_pCompiler->vnStore->VNConservativeNormalValue(treeIndex->gtVNPair);
    ValueNum arrLenVn = m_pCompiler->vnStore->VNConservativeNormalValue(bndsChk->gtArrLen->gtVNPair);
    int      arrSize  = 0;

    if (m_pCompiler->vnStore->IsVNConstant(arrLenVn))
    {
        ssize_t  constVal  = -1;
        unsigned iconFlags = 0;

        if (m_pCompiler->optIsTreeKnownIntValue(true, bndsChk->gtArrLen, &constVal, &iconFlags))
        {
            arrSize = (int)constVal;
        }
    }
    else
#ifdef FEATURE_SIMD
        if (tree->gtOper != GT_SIMD_CHK
#ifdef FEATURE_HW_INTRINSICS
            && tree->gtOper != GT_HW_INTRINSIC_CHK
#endif // FEATURE_HW_INTRINSICS
            )
#endif // FEATURE_SIMD
    {
        arrSize = GetArrLength(arrLenVn);
    }

    JITDUMP("ArrSize for lengthVN:%03X = %d\n", arrLenVn, arrSize);
    if (m_pCompiler->vnStore->IsVNConstant(idxVn) && (arrSize > 0))
    {
        ssize_t  idxVal    = -1;
        unsigned iconFlags = 0;
        if (!m_pCompiler->optIsTreeKnownIntValue(true, treeIndex, &idxVal, &iconFlags))
        {
            return;
        }

        JITDUMP("[RangeCheck::OptimizeRangeCheck] Is index %d in <0, arrLenVn " FMT_VN " sz:%d>.\n", idxVal, arrLenVn,
                arrSize);
        if ((idxVal < arrSize) && (idxVal >= 0))
        {
            JITDUMP("Removing range check\n");
            m_pCompiler->optRemoveRangeCheck(treeParent, stmt);
            return;
        }
    }

    GetRangeMap()->RemoveAll();
    GetOverflowMap()->RemoveAll();
    m_pSearchPath = new (m_alloc) SearchPath(m_alloc);

    // Get the range for this index.
    Range range = GetRange(block, treeIndex, false DEBUGARG(0));

    // If upper or lower limit is found to be unknown (top), or it was found to
    // be unknown because of over budget or a deep search, then return early.
    if (range.UpperLimit().IsUnknown() || range.LowerLimit().IsUnknown())
    {
        // Note: If we had stack depth too deep in the GetRange call, we'd be
        // too deep even in the DoesOverflow call. So return early.
        return;
    }

    if (DoesOverflow(block, treeIndex))
    {
        JITDUMP("Method determined to overflow.\n");
        return;
    }

    JITDUMP("Range value %s\n", range.ToString(m_pCompiler->getAllocatorDebugOnly()));
    m_pSearchPath->RemoveAll();
    Widen(block, treeIndex, &range);

    // If upper or lower limit is unknown, then return.
    if (range.UpperLimit().IsUnknown() || range.LowerLimit().IsUnknown())
    {
        return;
    }

    // Is the range between the lower and upper bound values.
    if (BetweenBounds(range, 0, bndsChk->gtArrLen))
    {
        JITDUMP("[RangeCheck::OptimizeRangeCheck] Between bounds\n");
        m_pCompiler->optRemoveRangeCheck(treeParent, stmt);
    }
    return;
}
Example #20
0
	void draw()const override{
		Table.map(Window::Width(), Window::Height()).draw();
		Board.map(520, 520).draw(140, 40);
		board.Render();

		if (!(passCount > 1 || waycount > 59) && !selectMode) {
			SetAble = board.WhereSetAble(black ? Piece::black : Piece::white);
			for (auto set : SetAble) {
				Rect(160 + set.x * 60, 60 + 60 * set.y, 60, 60).draw(Color(255, 20, 20, 100));
			}
		}

		if (this->black){
			font(Widen("Black\n(You)\nScore:" + std::to_string(blackCount) + "")).draw({ 10, 100 }, Palette::Black);
			font(Widen("White\n(COM)\nScore:" + std::to_string(whiteCount) + "")).draw(670, 100);
		}
		else{
			font(Widen("Black\n(COM)\nScore:" + std::to_string(blackCount) + "")).draw({ 10, 100 }, Palette::Black);
			font(Widen("White\n(You)\nScore:" + std::to_string(whiteCount) + "")).draw(670, 100);
		}
		Rect(0, 0, Window::Width(), Window::Height()).draw(Color(0, 0, 0, val1));
		if (selectMode){
			if (this->black){
				font(L"Black\n  ↑").draw({ 200, 270 }, Palette::Red);
				font(L"White").draw({ 500, 270 }, Palette::White);
			}
			else{
				font(L"Black").draw({ 200, 270 }, Palette::White);
				font(L"White\n  ↑").draw({ 500, 270 }, Palette::Red);
			}

			font(L"Select Either").draw({ 160, 100 }, Palette::White);
		}
		else{
			if (!(passCount > 1 || waycount > 59))
				Rect(160 + selectPos.x * 60, 60 + selectPos.y * 60, 60, 60).drawFrame(0, 3, Palette::Red);
		}
#ifdef _DEBUG
		font(Profiler::FPS(), L"FPS").draw();
#endif
		font(L"Pass").draw(val2, 270);

		if (passCount > 1 || waycount > 59){
			font(L"Result Announcement").draw(val3 - 160, 130);
			if (black){
				font(L"Black(You):" + Widen(std::to_string(black ? blackCount : whiteCount))).draw(val3 - 100, 270);
				font(L"White(Computer):" + Widen(std::to_string(black ? whiteCount : blackCount))).draw(val3 - 100, 330);
				font(L"Press ZKey to Back to Title").draw(val3 - 100, 420);
				if (blackCount > whiteCount){
					font(L"You are a ").draw({ val3 - 100, 200 }, Palette::White);
					font(L"Winner!!").draw({ val3 + 50, 200 }, Palette::Red);
				}
				else if (blackCount == whiteCount){
					font(L"You draw with Computer").draw({ val3 - 100, 200 }, Palette::White);
				}
				else{
					font(L"You are a ").draw({ val3 - 100, 200 }, Palette::White);
					font(L"Loser...").draw({ val3 + 50, 200 }, Palette::Blue);
				}
			}
			else{
				font(L"black(Computer):" + Widen(std::to_string(!black ? blackCount : whiteCount))).draw(val3 - 100, 270);
				font(L"white(You):" + Widen(std::to_string(!black ? whiteCount : blackCount))).draw(val3 - 100, 330);
				font(L"Press ZKey to Back to Title").draw(val3 - 100, 420);
				if (blackCount < whiteCount){
					font(L"You are a ").draw({ val3 - 100, 200 }, Palette::White);
					font(L"Winner!!").draw({ val3 + 50, 200 }, Palette::Red);
				}
				else if (blackCount == whiteCount){
					font(L"You draw with Computer").draw({ val3 - 200, 200 }, Palette::White);
				}
				else{
					font(L"You are a ").draw({ val3 - 100, 200 }, Palette::White);
					font(L"Loser...").draw({ val3 + 50, 200 }, Palette::Blue);
				}
			}
		}
		else{
			if (wait > 0 && !selectMode&&!myturn && (passCount < 2 || waycount < 59)){
				font(L"Computer Thinking...").draw(400, 0);
			}
			else if (wait > 0 && !selectMode&&myturn && (passCount < 2 || waycount < 59)){
				font(L"Your Turn").draw(400, 0);
			}
		}



	}
Example #21
0
BOOL AchievementSet::FetchFromWebBlocking( GameID nGameID )
{
	//	Can't open file: attempt to find it on SQL server!
	PostArgs args;
	args['u'] = RAUsers::LocalUser().Username();
	args['t'] = RAUsers::LocalUser().Token();
	args['g'] = std::to_string( nGameID );
	args['h'] = g_bHardcoreModeActive ? "1" : "0";

	Document doc;
	if( RAWeb::DoBlockingRequest( RequestPatch, args, doc ) && 
		doc.HasMember( "Success" ) && 
		doc[ "Success" ].GetBool() && 
		doc.HasMember( "PatchData" ) )
	{
		const Value& PatchData = doc[ "PatchData" ];

		//const std::string& sMinVer = PatchData["MinVer"].GetString();
		//const long nMinVerRequired = strtol( sMinVer.substr( 2 ).c_str(), NULL, 10 );
		
		//const long CURRENT_VER = strtol( std::string( g_sClientVersion ).substr( 2 ).c_str(), nullptr, 10 );
		//if( CURRENT_VER < nMinVerRequired )
		//{
		//	//	Client version too old!

		//	char buffer[4096];
		//	sprintf_s( buffer, 4096, 
		//		"Client version of 0.%03d is too old for the latest patch format.\r\n"
		//		"Version 0.%03d or greater required.\r\n"
		//		"Visit " RA_HOST " for a more recent version? ",
		//		CURRENT_VER,
		//		nMinVerRequired );

		//	if( MessageBox( nullptr, buffer, "Client out of date!", MB_YESNO ) == IDYES )
		//	{
		//		sprintf_s( buffer, 4096, "http://" RA_HOST "/download.php" );

		//		ShellExecute( NULL,
		//			"open",
		//			buffer,
		//			NULL,
		//			NULL,
		//			SW_SHOWNORMAL );
		//	}
		//	else
		//	{
		//		//MessageBox( nullptr, "Cannot load achievements for this game.", "Error", MB_OK );
		//	}

		//	return FALSE;
		//}
		//else
		{
			SetCurrentDirectory( Widen( g_sHomeDir ).c_str() );
			FILE* pf = nullptr;
			fopen_s( &pf, std::string( RA_DIR_DATA + std::to_string( nGameID ) + ".txt" ).c_str(), "wb" );
			if( pf != nullptr )
			{
				FileStream fs( pf );
				Writer<FileStream> writer( fs );
				PatchData.Accept( writer );
				fclose( pf );
				return TRUE;
			}
			else
			{
				ASSERT( !"Could not open patch file for writing?" );
				RA_LOG( "Could not open patch file for writing?" );
				return FALSE;
			}
		}
	}
	else
	{
		//	Could not connect...
		PopupWindows::AchievementPopups().AddMessage( 
			MessagePopup( "Could not connect to " RA_HOST_URL "...", "Working offline...", PopupInfo ) ); //?

		return FALSE;
	}
}
Example #22
0
//	static
BOOL AchievementSet::LoadFromFile( GameID nGameID )
{
	//	Is this safe?
	CoreAchievements->Clear();
	UnofficialAchievements->Clear();
	LocalAchievements->Clear();			//?!?!?

	if( nGameID == 0 )
		return TRUE;

	const std::string sFilename = GetAchievementSetFilename( nGameID );

	SetCurrentDirectory( Widen( g_sHomeDir ).c_str() );
	FILE* pFile = NULL;
	fopen_s( &pFile, sFilename.c_str(), "rb" );
	if( pFile != NULL )
	{
		//	Store this: we are now assuming this is the correct checksum if we have a file for it
		CoreAchievements->SetGameID( nGameID );
		UnofficialAchievements->SetGameID( nGameID );
		LocalAchievements->SetGameID( nGameID );

		Document doc;
		doc.ParseStream( FileStream( pFile ) );
		if( !doc.HasParseError() )
		{
			//ASSERT( doc["Success"].GetBool() );
			//const Value& PatchData = doc["PatchData"];
			const GameID nGameIDFetched = doc["ID"].GetUint();
			ASSERT( nGameIDFetched == nGameID );
			const std::string& sGameTitle = doc["Title"].GetString();
			const unsigned int nConsoleID = doc["ConsoleID"].GetUint();
			const std::string& sConsoleName = doc["ConsoleName"].GetString();
			const unsigned int nForumTopicID = doc["ForumTopicID"].GetUint();
			const unsigned int nGameFlags = doc["Flags"].GetUint();
			const std::string& sImageIcon = doc["ImageIcon"].GetString();
			const std::string& sImageTitle = doc["ImageTitle"].GetString();
			const std::string& sImageIngame = doc["ImageIngame"].GetString();
			const std::string& sImageBoxArt = doc["ImageBoxArt"].GetString();
			const std::string& sPublisher = doc["Publisher"].IsNull() ? "Unknown" : doc["Publisher"].GetString();
			const std::string& sDeveloper = doc["Developer"].IsNull() ? "Unknown" : doc["Developer"].GetString();
			const std::string& sGenre = doc["Genre"].IsNull() ? "Unknown" : doc["Genre"].GetString();
			const std::string& sReleased = doc["Released"].IsNull() ? "Unknown" : doc["Released"].GetString();
			const bool bIsFinal = doc["IsFinal"].GetBool();
			const std::string& sRichPresencePatch = doc["RichPresencePatch"].IsNull() ? "" : doc["RichPresencePatch"].GetString();
			
			//##SD store all this data somewhere? Do we want it?
			m_sPreferredGameTitle = sGameTitle;

			RA_RichPresenceInterpretter::PersistAndParseScript( nGameIDFetched, sRichPresencePatch );

			const Value& AchievementsData = doc["Achievements"];

			for( SizeType i = 0; i < AchievementsData.Size(); ++i )
			{
				//	Parse into correct boxes
				unsigned int nFlags = AchievementsData[i]["Flags"].GetUint();
				if( nFlags == 3 )
				{
					Achievement& newAch = CoreAchievements->AddAchievement();
					newAch.Parse( AchievementsData[i] );
				}
				else if( nFlags == 5 )
				{
					Achievement& newAch = UnofficialAchievements->AddAchievement();
					newAch.Parse( AchievementsData[i] );
				}
				else
				{
					RA_LOG( "Cannot deal with achievement with flags: %d\n", nFlags );
				}
			}
			
			const Value& LeaderboardsData = doc["Leaderboards"];
			
			for( SizeType i = 0; i < LeaderboardsData.Size(); ++i )
			{
				//"Leaderboards":[{"ID":"2","Mem":"STA:0xfe10=h0000_0xhf601=h0c_d0xhf601!=h0c_0xfff0=0_0xfffb=0::CAN:0xhfe13<d0xhfe13::SUB:0xf7cc!=0_d0xf7cc=0::VAL:0xhfe24*1_0xhfe25*60_0xhfe22*3600","Format":"TIME","Title":"Green Hill Act 1","Description":"Complete this act in the fastest time!"},
				
				RA_Leaderboard lb( LeaderboardsData[i]["ID"].GetUint() );
				lb.LoadFromJSON( LeaderboardsData[i] );

				g_LeaderboardManager.AddLeaderboard( lb );
			}
		}
		else
		{
			fclose( pFile );
			ASSERT( !"Could not parse file?!" );
			return FALSE;
		}

		fclose( pFile );
		
		unsigned int nTotalPoints = 0;
		for( size_t i = 0; i < CoreAchievements->NumAchievements(); ++i )
			nTotalPoints += CoreAchievements->GetAchievement( i ).Points();

		if( RAUsers::LocalUser().IsLoggedIn() )
		{	
			//	Loaded OK: post a request for unlocks
			PostArgs args;
			args['u'] = RAUsers::LocalUser().Username();
			args['t'] = RAUsers::LocalUser().Token();
			args['g'] = std::to_string( nGameID );
			args['h'] = g_bHardcoreModeActive ? "1" : "0";

			RAWeb::CreateThreadedHTTPRequest( RequestUnlocks, args );
			
			std::string sNumCoreAch = std::to_string( CoreAchievements->NumAchievements() );

			g_PopupWindows.AchievementPopups().AddMessage( 
				MessagePopup( "Loaded " + sNumCoreAch + " achievements, Total Score " + std::to_string( nTotalPoints ), "", PopupInfo ) );	//	TBD
		}

		return TRUE;
	}
	else
	{
		//	Cannot open file
		RA_LOG( "Cannot open file %s\n", sFilename.c_str() );
		return FALSE;
	}
}
INT_PTR CALLBACK Dlg_AchievementsReporter::AchievementsReporterProc( HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
	switch( uMsg )
	{
		case WM_INITDIALOG:
		{
			HWND hList = GetDlgItem( hDlg, IDC_RA_REPORTBROKENACHIEVEMENTSLIST );
			SetupColumns( hList );

			for( size_t i = 0; i < g_pActiveAchievements->NumAchievements(); ++i )
				AddAchievementToListBox( hList, &g_pActiveAchievements->GetAchievement( i ) );

			ListView_SetExtendedListViewStyle( hList, LVS_EX_CHECKBOXES | LVS_EX_HEADERDRAGDROP );
			SetDlgItemText( hDlg, IDC_RA_BROKENACH_BUGREPORTER, Widen( RAUsers::LocalUser().Username() ).c_str() );
		}
		return FALSE;

	case WM_COMMAND:
		switch( LOWORD( wParam ) )
		{
		case IDOK:
		{
			HWND hList = GetDlgItem( hDlg, IDC_RA_REPORTBROKENACHIEVEMENTSLIST );

			const bool bProblem1Sel = ( IsDlgButtonChecked( hDlg, IDC_RA_PROBLEMTYPE1 ) == BST_CHECKED );
			const bool bProblem2Sel = ( IsDlgButtonChecked( hDlg, IDC_RA_PROBLEMTYPE2 ) == BST_CHECKED );

			if( ( bProblem1Sel == false ) && ( bProblem2Sel == false ) )
			{
				MessageBox( nullptr, L"Please select a problem type.", L"Warning", MB_ICONWARNING );
				return FALSE;
			}

			int nProblemType = bProblem1Sel ? 1 : bProblem2Sel ? 2 : 0;	// 0==?
			const char* sProblemTypeNice = PROBLEM_STR[ nProblemType ];

			char sBuggedIDs[ 1024 ];
			sprintf_s( sBuggedIDs, 1024, "" );

			int nReportCount = 0;

			const size_t nListSize = ListView_GetItemCount( hList );
			for( size_t i = 0; i < nListSize; ++i )
			{
				if( ListView_GetCheckState( hList, i ) != 0 )
				{
					//	NASTY big assumption here...
					char buffer[ 1024 ];
					sprintf_s( buffer, 1024, "%d,", g_pActiveAchievements->GetAchievement( i ).ID() );
					strcat_s( sBuggedIDs, 1024, buffer );

					//ListView_GetItem( hList );	
					nReportCount++;
				}
			}

			if( nReportCount > 5 )
			{
				if( MessageBox( nullptr, L"You have over 5 achievements selected. Is this OK?", L"Warning", MB_YESNO ) == IDNO )
					return FALSE;
			}

			wchar_t sBugReportCommentWide[ 4096 ];
			GetDlgItemText( hDlg, IDC_RA_BROKENACHIEVEMENTREPORTCOMMENT, sBugReportCommentWide, 4096 );
			std::string sBugReportComment = Narrow( sBugReportCommentWide );

			char sBugReportInFull[ 8192 ];
			sprintf_s( sBugReportInFull, 8192,
					"--New Bug Report--\n"
					"\n"
					"Game: %s\n"
					"Achievement IDs: %s\n"
					"Problem: %s\n"
					"Reporter: %s\n"
					"ROM Checksum: %s\n"
					"\n"
					"Comment: %s\n"
					"\n"
					"Is this OK?",
					CoreAchievements->GameTitle().c_str(),
					sBuggedIDs,
					sProblemTypeNice,
					RAUsers::LocalUser().Username().c_str(),
					g_sCurrentROMMD5.c_str(),
					sBugReportComment.c_str() );

			if( MessageBox( nullptr, Widen( sBugReportInFull ).c_str(), L"Summary", MB_YESNO ) == IDNO )
				return FALSE;

			PostArgs args;
			args[ 'u' ] = RAUsers::LocalUser().Username();
			args[ 't' ] = RAUsers::LocalUser().Token();
			args[ 'i' ] = sBuggedIDs;
			args[ 'p' ] = std::to_string( nProblemType );
			args[ 'n' ] = sBugReportComment.c_str();
			args[ 'm' ] = g_sCurrentROMMD5;

			Document doc;
			if( RAWeb::DoBlockingRequest( RequestSubmitTicket, args, doc ) )
			{
				if( doc[ "Success" ].GetBool() )
				{
					char buffer[ 2048 ];
					sprintf_s( buffer, 2048, "Submitted OK!\n"
							"\n"
							"Thankyou for reporting that bug(s), and sorry it hasn't worked correctly.\n"
							"\n"
							"The development team will investigate this bug as soon as possible\n"
							"and we will send you a message on RetroAchievements.org\n"
							"as soon as we have a solution.\n"
							"\n"
							"Thanks again!" );

					MessageBox( hDlg, Widen( buffer ).c_str(), L"Success!", MB_OK );
					EndDialog( hDlg, TRUE );
					return TRUE;
				}
				else
				{
					char buffer[ 2048 ];
					sprintf_s( buffer, 2048,
							"Failed!\n"
							"\n"
							"Response From Server:\n"
							"\n"
							"Error code: %d", doc.GetParseError() );
					MessageBox( hDlg, Widen( buffer ).c_str(), L"Error from server!", MB_OK );
					return FALSE;
				}
			}
			else
			{
				MessageBox( hDlg,
							L"Failed!\n"
							L"\n"
							L"Cannot reach server... are you online?\n"
							L"\n",
							L"Error!", MB_OK );
				return FALSE;
			}
		}
		break;

		case IDCANCEL:
			EndDialog( hDlg, TRUE );
			return TRUE;
		}
		return FALSE;

	case WM_CLOSE:
		EndDialog( hDlg, FALSE );
		return TRUE;

	default:
		return FALSE;
	}
}
Example #24
0
void AchievementSet::SaveProgress( const char* sSaveStateFilename )
{
	if( !RAUsers::LocalUser().IsLoggedIn() )
		return;

	if( sSaveStateFilename == NULL )
		return;
	
	SetCurrentDirectory( Widen( g_sHomeDir ).c_str() );
	char buffer[ 4096 ];
	sprintf_s( buffer, 4096, "%s.rap", sSaveStateFilename );
	FILE* pf = NULL;
	fopen_s( &pf, buffer, "w" );
	if( pf == NULL )
	{
		ASSERT( !"Could not save progress!" );
		return;
	}

	for( size_t i = 0; i < NumAchievements(); ++i )
	{
		Achievement* pAch = &m_Achievements[i];
		if( !pAch->Active() )
			continue;

		//	Write ID of achievement and num conditions:
		char cheevoProgressString[4096];
		memset( cheevoProgressString, '\0', 4096 );

		for( unsigned int nGrp = 0; nGrp < pAch->NumConditionGroups(); ++nGrp )
		{
			sprintf_s( buffer, "%d:%d:", pAch->ID(), pAch->NumConditions( nGrp ) );
			strcat_s( cheevoProgressString, 4096, buffer );

			for( unsigned int j = 0; j < pAch->NumConditions( nGrp ); ++j )
			{
				Condition& cond = pAch->GetCondition( nGrp, j );
				sprintf_s( buffer, 4096, "%d:%d:%d:%d:%d:", 
					cond.CurrentHits(),
					cond.CompSource().RawValue(),
					cond.CompSource().RawPreviousValue(),
					cond.CompTarget().RawValue(),
					cond.CompTarget().RawPreviousValue() );
				strcat_s( cheevoProgressString, 4096, buffer );
			}
		}
		
		//	Generate a slightly different key to md5ify:
		char sCheevoProgressMangled[4096];
		sprintf_s( sCheevoProgressMangled, 4096, "%s%s%s%d", 
			RAUsers::LocalUser().Username().c_str(), cheevoProgressString, RAUsers::LocalUser().Username().c_str(), pAch->ID() );
		
		std::string sMD5Progress = RAGenerateMD5( std::string( sCheevoProgressMangled ) );
		std::string sMD5Achievement = RAGenerateMD5( pAch->CreateMemString() );
		
		fwrite( cheevoProgressString, sizeof(char), strlen(cheevoProgressString), pf );
		fwrite( sMD5Progress.c_str(), sizeof(char), sMD5Progress.length(), pf );
		fwrite( ":", sizeof(char), 1, pf );
		fwrite( sMD5Achievement.c_str(), sizeof(char), sMD5Achievement.length(), pf );
		fwrite( ":", sizeof(char), 1, pf );	//	Check!
	}

	fclose( pf );
}
void Dlg_MemBookmark::ExportJSON()
{
	if ( g_pCurrentGameData->GetGameID() == 0 )
	{
		MessageBox( nullptr, _T("ROM not loaded: please load a ROM first!"), _T("Error!"), MB_OK );
		return;
	}

	if ( m_vBookmarks.size() == 0)
	{
		MessageBox( nullptr, _T("No bookmarks to save: please create a bookmark before attempting to save."), _T("Error!"), MB_OK );
		return;
	}

	std::string defaultDir = RA_DIR_BOOKMARKS;
	defaultDir.erase ( 0, 2 ); // Removes the characters (".\\")
	defaultDir = g_sHomeDir + defaultDir;

	IFileSaveDialog* pDlg = nullptr;
	HRESULT hr = CoCreateInstance( CLSID_FileSaveDialog, NULL, CLSCTX_ALL, IID_IFileSaveDialog, reinterpret_cast<void**>( &pDlg ) );
	if ( hr == S_OK )
	{
		hr = pDlg->SetFileTypes( ARRAYSIZE( c_rgFileTypes ), c_rgFileTypes );
		if ( hr == S_OK )
		{
			char defaultFileName[ 512 ];
			sprintf_s ( defaultFileName, 512, "%s-Bookmarks.txt", std::to_string( g_pCurrentGameData->GetGameID() ).c_str() );
			hr = pDlg->SetFileName( Widen( defaultFileName ).c_str() );
			if ( hr == S_OK )
			{
				PIDLIST_ABSOLUTE pidl;
				hr = SHParseDisplayName( Widen( defaultDir ).c_str(), NULL, &pidl, SFGAO_FOLDER, 0 );
				if ( hr == S_OK )
				{
					IShellItem* pItem = nullptr;
					SHCreateShellItem( NULL, NULL, pidl, &pItem );
					hr = pDlg->SetDefaultFolder( pItem );
					if ( hr == S_OK )
					{
						pDlg->SetDefaultExtension( L"txt" );
						hr = pDlg->Show( nullptr );
						if ( hr == S_OK )
						{

							hr = pDlg->GetResult( &pItem );
							if ( hr == S_OK )
							{
								LPWSTR pStr = nullptr;
								hr = pItem->GetDisplayName( SIGDN_FILESYSPATH, &pStr );
								if ( hr == S_OK )
								{
									Document doc;
									Document::AllocatorType& allocator = doc.GetAllocator();
									doc.SetObject();

									Value bookmarks( kArrayType );
									for ( MemBookmark* bookmark : m_vBookmarks )
									{
										Value item( kObjectType );
										char buffer[ 256 ];
										sprintf_s( buffer, Narrow( bookmark->Description() ).c_str(), sizeof( buffer ) );
										Value s( buffer, allocator );

										item.AddMember( "Description", s, allocator );
										item.AddMember( "Address", bookmark->Address(), allocator );
										item.AddMember( "Type", bookmark->Type(), allocator );
										item.AddMember( "Decimal", bookmark->Decimal(), allocator );
										bookmarks.PushBack( item, allocator );
									}
									doc.AddMember( "Bookmarks", bookmarks, allocator );

									_WriteBufferToFile( Narrow( pStr ), doc );
								}

								pItem->Release();
								ILFree( pidl );
							}
						}
					}
				}
			}
		}
		pDlg->Release();
	}
}
Example #26
0
BOOL DirectoryExists( const char* sPath )
{
	DWORD dwAttrib = GetFileAttributes( Widen( sPath ).c_str() );
	return( dwAttrib != INVALID_FILE_ATTRIBUTES && ( dwAttrib & FILE_ATTRIBUTE_DIRECTORY ) );
}
Example #27
0
void TestUTF8 (void)
{
    cout << "Generating Unicode characters ";
    vector<wchar_t> srcChars;
    srcChars.resize (0xFFFF);
    iota (srcChars.begin(), srcChars.end(), 0);
    cout << size_t(srcChars[0]) << " - " << size_t(srcChars.back()) << endl;

    cout << "Encoding to utf8." << endl;
    string encoded;
    encoded.reserve (srcChars.size() * 4);
    copy (srcChars, utf8out (back_inserter(encoded)));
    const char c_ProperEncoding[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    if (encoded.compare (encoded.begin(), encoded.begin() + VectorSize(c_ProperEncoding), VectorRange(c_ProperEncoding))) {
	cout << "Encoding failed: ";
	for (string::const_iterator i = encoded.begin(); i != encoded.begin() + VectorSize(c_ProperEncoding); ++ i)
	    cout << uint32_t(*i);
	cout << endl;
    }

    cout << "Decoding back." << endl;
    vector<wchar_t> decChars;
    assert( decChars.size() == 0 );
    Widen (encoded, decChars);

    cout << "Comparing." << endl;
    cout << "src = " << srcChars.size();
    cout << " chars, encoded = " << encoded.size();
    cout << " chars, decoded = " << decChars.size() << endl;
    size_t nDiffs = 0;
    for (uoff_t i = 0; i < min (srcChars.size(), decChars.size()); ++ i) {
	if (srcChars[i] != decChars[i]) {
	    cout << uint32_t(srcChars[i]) << " != " << uint32_t(decChars[i]) << endl;
	    ++ nDiffs;
	}
    }
    cout << nDiffs << " differences between src and decoded." << endl;

    cout << "Testing wide character string::insert" << endl;
    string ws ("1234567890", 10);

    ws.insert (0, wchar_t(1234));
    ws.insert (3, wchar_t(2345));
    const wchar_t c_WChars[2] = { 3456, 4567 };
    ws.insert (3, VectorRange(c_WChars), 2);
    ws.insert (ws.utf_length(), wchar_t(5678));
    cout << "Values[" << ws.utf_length() << "]:";
    for (string::utf8_iterator j = ws.utf8_begin(); j < ws.utf8_end(); ++ j)
	cout << ' ' << (uint32_t) *j;
    cout << endl;

    cout << "Character offsets:";
    for (string::utf8_iterator k = ws.utf8_begin(); k < ws.utf8_end(); ++ k)
	cout << ' ' << distance (ws.begin(), k.base());
    cout << endl;

    cout << "Erasing character " << ws.utf_length() - 1 << ": ";
    ws.erase (ws.utf_length() - 1);
    Widen (ws, decChars);
    DumpWchars (decChars);
    cout << endl;

    cout << "Erasing characters 3-5: ";
    ws.erase (3, 2);
    Widen (ws, decChars);
    DumpWchars (decChars);
    cout << endl;
}
Example #28
0
void AchievementPopup::Render( HDC hDC, RECT& rcDest )
{
	if( !MessagesPresent() )
		return;

	const int nPixelWidth = rcDest.right - rcDest.left;

	//SetBkColor( hDC, RGB( 0, 212, 0 ) );
	SetBkColor( hDC, COL_TEXT_HIGHLIGHT );
	SetTextColor( hDC, COL_POPUP );

	HFONT hFontTitle = CreateFont( FONT_SIZE_TITLE, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
								   DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_CHARACTER_PRECIS, ANTIALIASED_QUALITY,/*NONANTIALIASED_QUALITY,*/
								   DEFAULT_PITCH, FONT_TO_USE );

	HFONT hFontDesc = CreateFont( FONT_SIZE_SUBTITLE, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
								  DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_CHARACTER_PRECIS, ANTIALIASED_QUALITY,/*NONANTIALIASED_QUALITY,*/
								  DEFAULT_PITCH, FONT_TO_USE );

	int nTitleX = 10;
	int nDescX = nTitleX + 2;

	const int nHeight = rcDest.bottom - rcDest.top;

	float fFadeInY = GetYOffsetPct() * ( POPUP_DIST_Y_FROM_PCT * static_cast<float>( nHeight ) );
	fFadeInY += ( POPUP_DIST_Y_TO_PCT * static_cast<float>( nHeight ) );

	const int nTitleY = static_cast<int>( fFadeInY );
	const int nDescY = nTitleY + 32;

	if( ActiveMessage().Type() == PopupAchievementUnlocked || ActiveMessage().Type() == PopupAchievementError )
	{
		DrawImage( hDC, ActiveMessage().Image(), nTitleX, nTitleY, 64, 64 );

		nTitleX += 64 + 4 + 2;	//	Negate the 2 from earlier!
		nDescX += 64 + 4;
	}
	else if( ActiveMessage().Type() == PopupLeaderboardInfo )
	{
		//	meh
	}

	const std::string sTitle = std::string( " " + ActiveMessage().Title() + " " );
	const std::string sSubTitle = std::string( " " + ActiveMessage().Subtitle() + " " );

	SelectObject( hDC, hFontTitle );
	TextOut( hDC, nTitleX, nTitleY, Widen( sTitle ).c_str(), sTitle.length() );
	SIZE szTitle = { 0, 0 };
	GetTextExtentPoint32( hDC, Widen( sTitle ).c_str(), sTitle.length(), &szTitle );

	SIZE szAchievement = { 0, 0 };
	if( ActiveMessage().Subtitle().length() > 0 )
	{
		SelectObject( hDC, hFontDesc );
		TextOut( hDC, nDescX, nDescY, Widen( sSubTitle ).c_str(), sSubTitle.length() );
		GetTextExtentPoint32( hDC, Widen( sSubTitle ).c_str(), sSubTitle.length(), &szAchievement );
	}

	HGDIOBJ hPen = CreatePen( PS_SOLID, 2, COL_POPUP_SHADOW );
	SelectObject( hDC, hPen );

	MoveToEx( hDC, nTitleX, nTitleY + szTitle.cy, NULL );
	LineTo( hDC, nTitleX + szTitle.cx, nTitleY + szTitle.cy );	//	right
	LineTo( hDC, nTitleX + szTitle.cx, nTitleY + 1 );			//	up

	if( ActiveMessage().Subtitle().length() > 0 )
	{
		MoveToEx( hDC, nDescX, nDescY + szAchievement.cy, NULL );
		LineTo( hDC, nDescX + szAchievement.cx, nDescY + szAchievement.cy );
		LineTo( hDC, nDescX + szAchievement.cx, nDescY + 1 );
	}

	DeleteObject( hPen );
	DeleteObject( hFontTitle );
	DeleteObject( hFontDesc );
}
Example #29
0
void ProgressPopup::Render( HDC hDC, RECT& rcDest )
{
	if( !IsActive() )
		return;

	SetBkColor( hDC, RGB( 0, 212, 0 ) );
	SetTextColor( hDC, RGB( 0, 40, 0 ) );

	HFONT hFontTitle = CreateFont( FONT_SIZE_MAIN, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
								   DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_CHARACTER_PRECIS, ANTIALIASED_QUALITY,/*NONANTIALIASED_QUALITY,*/
								   DEFAULT_PITCH, Widen( FONT_TO_USE ).c_str() );

	HFONT hFontDesc = CreateFont( FONT_SIZE_SUBTITLE, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
								  DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_CHARACTER_PRECIS, ANTIALIASED_QUALITY,/*NONANTIALIASED_QUALITY,*/
								  DEFAULT_PITCH, Widen( FONT_TO_USE ).c_str() );


	int nTitleX = 10;
	int nDescX = nTitleX + 2;

	const int nHeight = rcDest.bottom - rcDest.top;

	float fFadeInY = GetYOffsetPct() * ( POPUP_DIST_Y_FROM_PCT * (float)nHeight );
	fFadeInY += ( POPUP_DIST_Y_TO_PCT * (float)nHeight );

	int nTitleY = (int)fFadeInY;
	int nDescY = nTitleY + 32;

	if( GetMessageType() == 1 )
	{
		DrawImage( hDC, GetImage(), nTitleX, nTitleY, 64, 64 );

		nTitleX += 64 + 4 + 2;	//	Negate the 2 from earlier!
		nDescX += 64 + 4;
	}

	SIZE szTitle, szAchievement;

	SelectObject( hDC, hFontTitle );
	TextOut( hDC, nTitleX, nTitleY, Widen( GetTitle() ).c_str(), strlen( GetTitle() ) );
	GetTextExtentPoint32( hDC, Widen( GetTitle() ).c_str(), strlen( GetTitle() ), &szTitle );

	SelectObject( hDC, hFontDesc );
	TextOut( hDC, nDescX, nDescY, Widen( GetDesc() ).c_str(), strlen( GetDesc() ) );
	GetTextExtentPoint32( hDC, Widen( GetDesc() ).c_str(), strlen( GetDesc() ), &szAchievement );

	HGDIOBJ hPen = CreatePen( PS_SOLID, 2, RGB( 0, 0, 0 ) );
	SelectObject( hDC, hPen );

	MoveToEx( hDC, nTitleX, nTitleY + szTitle.cy, NULL );
	LineTo( hDC, nTitleX + szTitle.cx, nTitleY + szTitle.cy );	//	right
	LineTo( hDC, nTitleX + szTitle.cx, nTitleY + 1 );			//	up

	if( GetDesc()[ 0 ] != '\0' )
	{
		MoveToEx( hDC, nDescX, nDescY + szAchievement.cy, NULL );
		LineTo( hDC, nDescX + szAchievement.cx, nDescY + szAchievement.cy );
		LineTo( hDC, nDescX + szAchievement.cx, nDescY + 1 );
	}

	DeleteObject( hPen );
	DeleteObject( hFontTitle );
	DeleteObject( hFontDesc );
}