diff --git a/common/PS2Etypes.h b/common/PS2Etypes.h index f4c8b3185e..2cb32f425b 100644 --- a/common/PS2Etypes.h +++ b/common/PS2Etypes.h @@ -145,42 +145,6 @@ typedef union _LARGE_INTEGER #define PCSX2_ALIGNED16_DECL(x) x -// The various plugins react to C++ in a header that is supposed to be C -// in much the same way a vampire reacts to the sign of a cross. -// Even if the file calling it is a C++ file. -// -// And removing the extern "C"'s makes it even worse. --Arcum42 -#if defined(SECURE_SPRINTF) - -// Define some handy equivalents of MSVC++ specific functions. -#ifdef __cplusplus - -#include -#include -#include - -template -__forceinline int vsprintf_s(char (&dest)[Size], const char* fmt, va_list args ) -{ - int retval = vsnprintf( dest, Size, fmt, args ); - dest[Size-1] = 0; - return retval; -} - -template -__forceinline int sprintf_s(char (&dest)[Size], const char* fmt, ... ) -{ - va_list list; - - va_start( list, dest ); - int retval = vsprintf_s( dest, fmt, list ); - va_end( list ); - - return retval; -} - -#endif // __cplusplus -#endif // SECURE_SPRINTF #endif // _MSC_VER #if !defined(__LINUX__) || !defined(HAVE_STDINT_H) diff --git a/pcsx2/CDVD.cpp b/pcsx2/CDVD.cpp index 833004005f..073f7c5149 100644 --- a/pcsx2/CDVD.cpp +++ b/pcsx2/CDVD.cpp @@ -222,14 +222,16 @@ FILE *_cdvdOpenMechaVer() { char *ptr; int i; char file[g_MaxPath]; - char Bios[g_MaxPath]; + string Bios; FILE* fd; // get the name of the bios file - CombinePaths( Bios, Config.BiosDir, Config.Bios ); + Path::Combine( Bios, Config.BiosDir, Config.Bios ); // use the bios filename to get the name of the mecha ver file - strcpy(file, Bios); + // [TODO] : Upgrade this to use std::string! + + strcpy(file, Bios.c_str()); ptr = file; i = (int)strlen(file); while (i > 0) { if (ptr[i] == '.') break; i--; } ptr[i+1] = '\0'; @@ -241,7 +243,7 @@ FILE *_cdvdOpenMechaVer() { SysPrintf("MEC File Not Found , Creating Blank File\n"); fd = fopen(file, "wb"); if (fd == NULL) { - Console::Alert("_cdvdOpenMechaVer: Error creating %s", file); + Msgbox::Alert("_cdvdOpenMechaVer: Error creating %s", params file); exit(1); } fputc(0x03, fd); @@ -265,15 +267,17 @@ s32 cdvdGetMechaVer(u8* ver) FILE *_cdvdOpenNVM() { char *ptr; int i; - char Bios[g_MaxPath]; + string Bios; char file[g_MaxPath]; FILE* fd; // get the name of the bios file - CombinePaths( Bios, Config.BiosDir, Config.Bios ); + Path::Combine( Bios, Config.BiosDir, Config.Bios ); // use the bios filename to get the name of the nvm file - strcpy( file, Bios ); + // [TODO] : Upgrade this to use std::string! + + strcpy( file, Bios.c_str() ); ptr = file; i = (int)strlen(file); while (i > 0) { if (ptr[i] == '.') break; i--; } ptr[i+1] = '\0'; @@ -285,7 +289,7 @@ FILE *_cdvdOpenNVM() { SysPrintf("NVM File Not Found , Creating Blank File\n"); fd = fopen(file, "wb"); if (fd == NULL) { - Console::Alert("_cdvdOpenNVM: Error creating %s", file); + Msgbox::Alert("_cdvdOpenNVM: Error creating %s", params file); exit(1); } for (i=0; i<1024; i++) fputc(0, fd); @@ -464,7 +468,7 @@ void cdvdReadKey(u8 arg0, u16 arg1, u32 arg2, u8* key) { // get main elf name GetPS2ElfName(str); sprintf(exeName, "%c%c%c%c%c%c%c%c%c%c%c",str[8],str[9],str[10],str[11],str[12],str[13],str[14],str[15],str[16],str[17],str[18]); - DevCon::Notice("exeName = %s",&str[8]); + DevCon::Notice("exeName = %s", params &str[8]); // convert the number characters to a real 32bit number numbers = ((((exeName[5] - '0'))*10000) + @@ -519,11 +523,16 @@ void cdvdReadKey(u8 arg0, u16 arg1, u32 arg2, u8* key) { key[15] = 0x01; } - Console::WriteLn( "CDVD.KEY = %02X,%02X,%02X,%02X,%02X,%02X,%02X",cdvd.Key[0],cdvd.Key[1],cdvd.Key[2],cdvd.Key[3],cdvd.Key[4],cdvd.Key[14],cdvd.Key[15] ); + Console::WriteLn( "CDVD.KEY = %02X,%02X,%02X,%02X,%02X,%02X,%02X", params + cdvd.Key[0],cdvd.Key[1],cdvd.Key[2],cdvd.Key[3],cdvd.Key[4],cdvd.Key[14],cdvd.Key[15] ); // Now's a good time to reload the ELF info... if( ElfCRC == 0 ) - loadElfCRC( str ); + { + ElfCRC = loadElfCRC( str ); + ElfApplyPatches(); + LoadGameSpecificSettings(); + } } s32 cdvdGetToc(void* toc) @@ -823,8 +832,8 @@ void cdvdNewDiskCB() if(GetPS2ElfName(str) == 1) { cdvd.Type = CDVD_TYPE_PSCD; } // ENDIF- Does the SYSTEM.CNF file only say "BOOT="? PS1 CD then. - } // ENDIF- Is the type listed as a PS2 CD? -} // END cdvdNewDiskCB() + } +} void mechaDecryptBytes(unsigned char* buffer, int size) { @@ -996,7 +1005,7 @@ __forceinline void cdvdReadInterrupt() { } else cdr.pTransfer = NULL; if (cdr.pTransfer == NULL) { cdvd.RetryCntP++; - Console::Error("CDVD READ ERROR, sector=%d", cdvd.Sector); + Console::Error("CDVD READ ERROR, sector=%d", params cdvd.Sector); if (cdvd.RetryCntP <= cdvd.RetryCnt) { cdvd.RErr = CDVDreadTrack(cdvd.Sector, cdvd.ReadMode); CDVDREAD_INT(cdvd.ReadTime); @@ -1347,14 +1356,14 @@ void cdvdWrite04(u8 rt) { // NCOMMAND // Seek to sector zero. The cdvdStartSeek function will simulate // spinup times if needed. - DevCon::Notice( "CdStandby : %d", rt ); + DevCon::Notice( "CdStandby : %d", params rt ); cdvd.Action = cdvdAction_Standby; cdvd.ReadTime = cdvdBlockReadTime( MODE_DVDROM ); CDVD_INT( cdvdStartSeek( 0 ) ); break; case 0x03: // CdStop - DevCon::Notice( "CdStop : %d", rt ); + DevCon::Notice( "CdStop : %d", params rt ); cdvd.Action = cdvdAction_Stop; CDVD_INT( PSXCLK / 6 ); // 166ms delay? break; @@ -1474,7 +1483,7 @@ void cdvdWrite04(u8 rt) { // NCOMMAND //the code below handles only CdGetToc! //if(cdvd.Param[0]==0x01) //{ - DevCon::WriteLn("CDGetToc Param[0]=%d, Param[1]=%d",cdvd.Param[0],cdvd.Param[1]); + DevCon::WriteLn("CDGetToc Param[0]=%d, Param[1]=%d", params cdvd.Param[0],cdvd.Param[1]); //} cdvdGetToc( PSXM( HW_DMA3_MADR ) ); cdvdSetIrq( (1<filename, localTocEntry.filename); memcpy(tocEntry->date, localTocEntry.date, 7); - DbgCon::MsgLn("CDVD_findfile: found file"); + DbgCon::WriteLn("CDVD_findfile: found file"); return TRUE; } diff --git a/pcsx2/COP0.cpp b/pcsx2/COP0.cpp index f31f322398..19dff77f0e 100644 --- a/pcsx2/COP0.cpp +++ b/pcsx2/COP0.cpp @@ -226,7 +226,7 @@ void MapTLB(int i) u32 saddr, eaddr; #ifndef PCSX2_VIRTUAL_MEM - DevCon::WriteLn("MAP TLB %d: %08x-> [%08x %08x] S=%d G=%d ASID=%d Mask= %03X", + DevCon::WriteLn("MAP TLB %d: %08x-> [%08x %08x] S=%d G=%d ASID=%d Mask= %03X", params i,tlb[i].VPN2,tlb[i].PFN0,tlb[i].PFN1,tlb[i].S,tlb[i].G,tlb[i].ASID,tlb[i].Mask); if (tlb[i].S) diff --git a/pcsx2/Console.cpp b/pcsx2/Console.cpp new file mode 100644 index 0000000000..9a4ae3a642 --- /dev/null +++ b/pcsx2/Console.cpp @@ -0,0 +1,190 @@ +/* Pcsx2 - Pc Ps2 Emulator + * Copyright (C) 2002-2008 Pcsx2 Team + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#include "PrecompiledHeader.h" + +#include "System.h" +#include "Debug.h" + +using namespace std; + +VARG_PARAM va_arg_dummy; + +// Methods of the Console namespace not defined here are to be found in the platform +// dependent implementations in WinConsole.cpp and LnxConsole.cpp. + +namespace Console +{ + static __forceinline void __fastcall _WriteLn( Colors color, const string& fmt, va_list args ) + { + string dest; + vssprintf( dest, fmt, args); + SetColor( color ); + WriteLn( dest ); + ClearColor(); + } + + bool Write( const string& fmt, VARG_PARAM dummy, ... ) + { + dummy_assert(); + + string dest; + + va_list list; + va_start(list,dummy); + vssprintf( dest, fmt, list); + va_end(list); + + WriteLn( dest ); + return false; + } + + bool Write( Colors color, const string& fmt ) + { + SetColor( color ); + Write( fmt ); + ClearColor(); + return false; + } + + bool Write( Colors color, const string& fmt, VARG_PARAM dummy, ... ) + { + dummy_assert(); + + string dest; + + va_list list; + va_start(list,dummy); + vssprintf( dest, fmt, list); + va_end(list); + + Write( dest ); + return false; + } + + bool WriteLn( const string& fmt, VARG_PARAM dummy, ... ) + { + dummy_assert(); + + string dest; + + va_list list; + va_start(list,dummy); + vssprintf( dest, fmt, list); + va_end(list); + + WriteLn( dest ); + return false; + } + + // Writes an unformatted string of text to the console (fast!) + // A newline is automatically appended. + __forceinline bool __fastcall WriteLn( const string& fmt ) + { + Write( fmt ); + Newline(); + return false; + } + + // Writes an unformatted string of text to the console (fast!) + // A newline is automatically appended. + __forceinline bool __fastcall WriteLn( Colors color, const string& fmt ) + { + Write( color, fmt ); + Newline(); + return false; + } + + // Writes a line of colored text to the console, with automatic newline appendage. + bool WriteLn( Colors color, const string& fmt, VARG_PARAM dummy, ... ) + { + dummy_assert(); + + va_list list; + va_start(list,dummy); + _WriteLn( Color_White, fmt, list ); + va_end(list); + return false; + } + + // Displays a message in the console with red emphasis. + // Newline is automatically appended. + bool Error( const string& fmt, VARG_PARAM dummy, ... ) + { + dummy_assert(); + + va_list list; + va_start(list,dummy); + _WriteLn( Color_Red, fmt, list ); + va_end(list); + return false; + } + + // Displays a message in the console with yellow emphasis. + // Newline is automatically appended. + bool Notice( const string& fmt, VARG_PARAM dummy, ... ) + { + dummy_assert(); + + va_list list; + + va_start(list,dummy); + _WriteLn( Color_Yellow, fmt, list ); + va_end(list); + return false; + } + + // Displays a message in the console with green emphasis. + // Newline is automatically appended. + bool Status( const string& fmt, VARG_PARAM dummy, ... ) + { + dummy_assert(); + + va_list list; + va_start(list,dummy); + _WriteLn( Color_Yellow, fmt, list ); + va_end(list); + return false; + } + + // Displays a message in the console with red emphasis. + // Newline is automatically appended. + bool Error( const string& fmt ) + { + WriteLn( Color_Red, fmt ); + return false; + } + + // Displays a message in the console with yellow emphasis. + // Newline is automatically appended. + bool Notice( const string& fmt ) + { + WriteLn( Color_Yellow, fmt ); + return false; + } + + // Displays a message in the console with green emphasis. + // Newline is automatically appended. + bool Status( const string& fmt ) + { + WriteLn( Color_Yellow, fmt ); + return false; + } + +} + diff --git a/pcsx2/Counters.cpp b/pcsx2/Counters.cpp index eadd6d3f2f..efff0bad0f 100644 --- a/pcsx2/Counters.cpp +++ b/pcsx2/Counters.cpp @@ -332,7 +332,7 @@ void vSyncDebugStuff() { if( --g_nLeftGSFrames <= 0 ) { safe_delete( g_fGSSave ); g_SaveGSStream = 0; - Console::MsgLn("Done saving GS stream"); + Console::WriteLn("Done saving GS stream"); } } #endif diff --git a/pcsx2/Elfheader.cpp b/pcsx2/Elfheader.cpp index aef4facfb9..98ddfd8860 100644 --- a/pcsx2/Elfheader.cpp +++ b/pcsx2/Elfheader.cpp @@ -376,7 +376,7 @@ struct ElfObject size = proghead[ i ].p_filesz; if( proghead[ i ].p_vaddr != proghead[ i ].p_paddr ) - Console::Notice( "ElfProgram different load addrs: paddr=0x%8.8x, vaddr=0x%8.8x", + Console::Notice( "ElfProgram different load addrs: paddr=0x%8.8x, vaddr=0x%8.8x", params proghead[ i ].p_paddr, proghead[ i ].p_vaddr); // used to be paddr @@ -487,7 +487,7 @@ struct ElfObject SymNames = (char*)data.GetPtr( secthead[ i_dt ].sh_offset ); eS = (Elf32_Sym*)data.GetPtr( secthead[ i_st ].sh_offset ); - Console::WriteLn("found %d symbols", secthead[ i_st ].sh_size / sizeof( Elf32_Sym )); + Console::WriteLn("found %d symbols", params secthead[ i_st ].sh_size / sizeof( Elf32_Sym )); for( uint i = 1; i < ( secthead[ i_st ].sh_size / sizeof( Elf32_Sym ) ); i++ ) { if ( ( eS[ i ].st_value != 0 ) && ( ELF32_ST_TYPE( eS[ i ].st_info ) == 2 ) ) { @@ -502,52 +502,50 @@ void ElfApplyPatches() { if( !Config.Patch ) return; - char str[256],str2[256]; + string filename; + ssprintf( filename, "%8.8x", params ElfCRC ); - sprintf(str, "%8.8x", ElfCRC); + // if patches found the following status msg will be overwritten + Console::SetTitle( fmt_string( "Game running without patches. [CRC=%S]", params &filename ) ); - sprintf(str2,"Game running without patches. [CRC=%8.8x]", ElfCRC);//if patches found it will overwritten :p - Console::SetTitle( str2 ); - - if(LoadPatch( str ) != 0) + if(LoadPatch( filename ) != 0) { - Console::MsgLn("XML Loader returned an error. Trying to load a pnatch..."); - inifile_read(str); + Console::WriteLn("XML Loader returned an error. Trying to load a pnatch..."); + inifile_read( filename.c_str() ); } else - Console::MsgLn("XML Loading success. Will not load from pnatch..."); + Console::WriteLn("XML Loading success. Will not load from pnatch..."); applypatch( 0 ); } // Fetches the CRC of the game bound to the CDVD plugin. -void loadElfCRC( const char* filename ) +u32 loadElfCRC( const char* filename ) { TocEntry toc; CDVDFS_init( ); if ( CDVD_findfile( filename + strlen( "cdromN:" ), &toc ) == -1 ) - return; + return 0; - DevCon::WriteLn( Color_Green, "loadElfFile: %d bytes", toc.fileSize); - ElfCRC = ElfObject( filename, toc.fileSize ).GetCRC(); - Console::WriteLn( Color_Green, "loadElfFile: %s; CRC = %8.8X\n", filename, ElfCRC); + DevCon::Status( "loadElfFile: %d bytes", params toc.fileSize ); + u32 crcval = ElfObject( filename, toc.fileSize ).GetCRC(); + Console::Status( "loadElfFile: %s; CRC = %8.8X", params filename, crcval ); - ElfApplyPatches(); - LoadGameSpecificSettings(); + return crcval; } int loadElfFile(const char *filename) { if( filename == NULL || filename[0] == 0 ) { - Console::Notice( "Running the PS2 BIOS...", filename ); + Console::Notice( "Running the PS2 BIOS...", params filename ); return -1; } int elfsize; - Console::WriteLn("loadElfFile: %s", filename); + Console::Status("loadElfFile: %s", params filename); if (strnicmp( filename, "cdrom0:", strlen( "cdromN:" ) ) && strnicmp( filename, "cdrom1:", strlen( "cdromN:" ) ) ) { @@ -567,7 +565,7 @@ int loadElfFile(const char *filename) elfsize = toc.fileSize; } - Console::WriteLn( Color_Green, "loadElfFile: %d", elfsize); + Console::Status( "loadElfFile: %d", params elfsize); ElfObject elfobj( filename, elfsize ); //2002-09-19 (Florin) @@ -586,12 +584,12 @@ int loadElfFile(const char *filename) for ( uint i = 0; i < 0x100000; i++ ) { if ( strcmp( "rom0:OSDSYS", (char*)PSM( i ) ) == 0 ) { strcpy( (char*)PSM( i ), filename ); - Console::WriteLn( Color_Green, "addr %x \"%s\" -> \"%s\"", i, "rom0:OSDSYS", filename ); + DevCon::Status( "addr %x \"%s\" -> \"%s\"", params i, "rom0:OSDSYS", filename ); } } ElfCRC = elfobj.GetCRC(); - Console::WriteLn( Color_Green, "loadElfFile: %s; CRC = %8.8X\n", filename, ElfCRC); + Console::Status( "loadElfFile: %s; CRC = %8.8X\n", params filename, ElfCRC); ElfApplyPatches(); LoadGameSpecificSettings(); diff --git a/pcsx2/Elfheader.h b/pcsx2/Elfheader.h index 4a012a7bf0..35a9c036fa 100644 --- a/pcsx2/Elfheader.h +++ b/pcsx2/Elfheader.h @@ -25,8 +25,9 @@ extern unsigned int args_ptr; //------------------- int loadElfFile(const char *filename); -void loadElfCRC(const char *filename); +u32 loadElfCRC(const char *filename); void LoadGameSpecificSettings(); +void ElfApplyPatches(); extern u32 ElfCRC; diff --git a/pcsx2/Exceptions.h b/pcsx2/Exceptions.h index f181f7b116..7887025941 100644 --- a/pcsx2/Exceptions.h +++ b/pcsx2/Exceptions.h @@ -20,7 +20,6 @@ #define _PCSX2_EXCEPTIONS_H_ #include -#include // This class provides an easy and clean method for ensuring objects are not copyable. class NoncopyableObject @@ -61,43 +60,78 @@ protected: namespace Exception { - class OutOfMemory : public std::runtime_error + // std::exception sucks, so I made a replacement. + // Note, this class is "abstract" which means you shouldn't use it directly like, ever. + // Use Exception::RuntimeError or Exception::LogicError instead. + class BaseException + { + protected: + const std::string m_message; // a "detailed" message of what disasterous thing has occured! + + public: + virtual ~BaseException() throw()=0; // the =0; syntax forces this class into "abstract" mode. + explicit BaseException( const std::string& msg="Unhandled exception." ) : + m_message( msg ) + {} + + const std::string& Message() const { return m_message; } + }; + + class RuntimeError : public BaseException + { + public: + virtual ~RuntimeError() throw() {} + explicit RuntimeError( const std::string& msg="An unhandled runtime error has occured, somewhere in the depths of Pcsx2's cluttered brain-matter." ) : + BaseException( msg ) + {} + }; + + class LogicError : public BaseException + { + public: + virtual ~LogicError() throw() {} + explicit LogicError( const std::string& msg="An unhandled logic error has occured." ) : + BaseException( msg ) + {} + }; + + class OutOfMemory : public RuntimeError { public: explicit OutOfMemory( const std::string& msg="Out of memory!" ) : - runtime_error( msg ) {} + RuntimeError( msg ) {} }; // This exception exception thrown any time an operation is attempted when an object // is in an uninitialized state. - class InvalidOperation : public std::logic_error + class InvalidOperation : public LogicError { public: virtual ~InvalidOperation() throw() {} explicit InvalidOperation( const std::string& msg="Attempted method call is invalid for the current object or program state." ) : - logic_error( msg ) {} + LogicError( msg ) {} }; - class HardwareDeficiency : public std::runtime_error + class HardwareDeficiency : public RuntimeError { public: explicit HardwareDeficiency( const std::string& msg="Your machine's hardware is incapable of running Pcsx2. Sorry dood." ) : - runtime_error( msg ) {} + RuntimeError( msg ) {} }; // This exception is thrown by the PS2 emulation (R5900, etc) when bad things happen // that force the emulation state to terminate. The GUI should handle them by returning // the user to the GUI. - class CpuStateShutdown : public std::runtime_error + class CpuStateShutdown : public RuntimeError { public: virtual ~CpuStateShutdown() throw() {} explicit CpuStateShutdown( const std::string& msg="The PS2 emulated state was shut down unexpectedly." ) : - runtime_error( msg ) {} + RuntimeError( msg ) {} }; // Exception thrown by SaveState class when a critical plugin or gzread - class FreezePluginFailure : public std::runtime_error + class FreezePluginFailure : public RuntimeError { public: std::string plugin_name; // name of the plugin @@ -105,43 +139,102 @@ namespace Exception virtual ~FreezePluginFailure() throw() {} explicit FreezePluginFailure( const std::string& plugin, const std::string& action ) : - runtime_error( plugin + " plugin returned an error while " + action + " the state." ) + RuntimeError( plugin + " plugin returned an error while " + action + " the state." ) , plugin_name( plugin ) , freeze_action( action ){} }; - class UnsupportedStateVersion : public std::runtime_error + // The savestate code throws Recoverable errors when it fails prior to actually modifying + // the current emulation state. Recoverable errors are always thrown from the SaveState + // object construction (and never from Freeze methods). + class StateLoadError_Recoverable : public RuntimeError { public: - virtual ~UnsupportedStateVersion() throw() {} - explicit UnsupportedStateVersion( const std::string& msg="Unknown or unsupported savestate version." ) : - runtime_error( msg ) {} + virtual ~StateLoadError_Recoverable() throw() {} + explicit StateLoadError_Recoverable( const std::string& msg="Recoverable error while loading savestate (existing emulation state is still intact)." ) : + RuntimeError( msg ) {} }; - class PluginFailure : public std::runtime_error + // A recoverable exception thrown when the savestate being loaded isn't supported. + class UnsupportedStateVersion : public StateLoadError_Recoverable + { + public: + u32 Version; // version number of the unsupported state. + + public: + virtual ~UnsupportedStateVersion() throw() {} + explicit UnsupportedStateVersion( int version ) : + StateLoadError_Recoverable( fmt_string( "Unknown or unsupported savestate version: 0x%x", params version ) ) + {} + + explicit UnsupportedStateVersion( int version, const std::string& msg ) : + StateLoadError_Recoverable( msg ) {} + }; + + // A recoverable exception thrown when the CRC of the savestate does not match the + // CRC returned by the Cdvd driver. + class StateCrcMismatch : public StateLoadError_Recoverable + { + public: + u32 Crc_Savestate; + u32 Crc_Cdvd; + + public: + virtual ~StateCrcMismatch() throw() {} + explicit StateCrcMismatch( u32 crc_save, u32 crc_cdvd ) + : StateLoadError_Recoverable( fmt_string( + "Game/CDVD does not match the savestate CRC.\n" + "\tCdvd CRC: 0x%X\n\tGame CRC: 0x%X\n", params crc_save, crc_cdvd + ) ) + , Crc_Savestate( crc_save ) + , Crc_Cdvd( crc_cdvd ) + {} + + explicit StateCrcMismatch( u32 crc_save, u32 crc_cdvd, const std::string& msg ) + : StateLoadError_Recoverable( msg ) + , Crc_Savestate( crc_save ) + , Crc_Cdvd( crc_cdvd ) + {} + }; + + class PluginFailure : public RuntimeError { public: std::string plugin_name; // name of the plugin virtual ~PluginFailure() throw() {} explicit PluginFailure( const std::string& plugin, const std::string& msg = "An error occured in the " ) : - runtime_error( plugin + msg + " Plugin" ) + RuntimeError( plugin + msg + " Plugin" ) , plugin_name( plugin ) {} }; - class ThreadCreationError : public std::runtime_error + class ThreadCreationError : public RuntimeError { public: virtual ~ThreadCreationError() throw() {} explicit ThreadCreationError( const std::string& msg="Thread could not be created." ) : - runtime_error( msg ) {} + RuntimeError( msg ) {} }; - /**** BEGIN STREAMING EXCEPTIONS ****/ + // This is a "special" exception that's primarily included for safe functioning in the + // Win32's ASCII API (ie, the non-Unicode one). Many of the old Win32 APIs don't support + // paths over 256 characters. + class PathTooLong : public RuntimeError + { + public: + virtual ~PathTooLong() throw() {} + explicit PathTooLong( const std::string& msg= + "A Pcsx2 pathname was too long for the system. Please move or reinstall Pcsx2 to\n" + "a location on your hard drive that has a shorter path." ) : + RuntimeError( msg ) {} + }; + + /////////////////////////////////////////////////////////////////////// + // BEGIN STREAMING EXCEPTIONS // Generic stream error. Contains the name of the stream and a message. // This exception is usually thrown via derrived classes, except in the (rare) case of a generic / unknown error. - class Stream : public std::runtime_error + class Stream : public RuntimeError { public: std::string stream_name; // name of the stream (if applicable) @@ -150,13 +243,13 @@ namespace Exception // copy construct! Stream( const Stream& src ) : - std::runtime_error( src.what() ) + RuntimeError( src.Message() ) , stream_name( src.stream_name ) {} explicit Stream( const std::string& objname=std::string(), const std::string& msg="Invalid stream object" ) : - std::runtime_error( msg + ": " + objname ) + RuntimeError( msg + ": " + objname ) , stream_name( objname ) {} }; diff --git a/pcsx2/FiFo.cpp b/pcsx2/FiFo.cpp index f40f981f78..0420a08eb2 100644 --- a/pcsx2/FiFo.cpp +++ b/pcsx2/FiFo.cpp @@ -139,11 +139,11 @@ void WriteFIFO(u32 mem, const u64 *value) { //commiting every 16 bytes while( FIFOto_write((u32*)value, 1) == 0 ) { - Console::MsgLn("IPU sleeping"); + Console::WriteLn("IPU sleeping"); Threading::Timeslice(); } } else { - Console::Notice("WriteFIFO Unknown %x", mem); + Console::Notice("WriteFIFO Unknown %x", params mem); } } diff --git a/pcsx2/GS.cpp b/pcsx2/GS.cpp index 29fc77d77b..69ce546eb5 100644 --- a/pcsx2/GS.cpp +++ b/pcsx2/GS.cpp @@ -167,14 +167,14 @@ void gsSetVideoRegionType( u32 isPal ) if( isPal ) { if( Config.PsxType & 1 ) return; - Console::MsgLn( "PAL Display Mode Initialized." ); + Console::WriteLn( "PAL Display Mode Initialized." ); Config.PsxType |= 1; framerate = FRAMERATE_PAL; } else { if( !(Config.PsxType & 1 ) ) return; - Console::MsgLn( "NTSC Display Mode Initialized." ); + Console::WriteLn( "NTSC Display Mode Initialized." ); Config.PsxType &= ~1; framerate = FRAMERATE_NTSC; } @@ -194,7 +194,7 @@ void gsInit() if( GSsetFrameSkip == NULL ) { Config.Options &= ~PCSX2_FRAMELIMIT_MASK; - Console::MsgLn("Notice: Disabling frameskip -- GS plugin does not support it."); + Console::WriteLn("Notice: Disabling frameskip -- GS plugin does not support it."); } break; } diff --git a/pcsx2/Hw.cpp b/pcsx2/Hw.cpp index fd08c29a7b..62b65716a8 100644 --- a/pcsx2/Hw.cpp +++ b/pcsx2/Hw.cpp @@ -43,7 +43,7 @@ int hwInit() { #ifndef PCSX2_VIRTUAL_MEM psH = (u8*)_aligned_malloc(0x00010000, 16); if (psH == NULL) { - Console::Alert("Error allocating memory"); + Msgbox::Alert("Error allocating memory"); return -1; } #endif @@ -85,7 +85,7 @@ u8 hwRead8(u32 mem) u8 ret; if( mem >= 0x10000000 && mem < 0x10008000 ) - DevCon::Notice("hwRead8 to %x", mem); + DevCon::Notice("hwRead8 to %x", params mem); SPR_LOG("Hardware read 8bit at %lx, ret %lx\n", mem, psHu8(mem)); @@ -118,7 +118,7 @@ u16 hwRead16(u32 mem) u16 ret; if( mem >= 0x10002000 && mem < 0x10008000 ) - Console::Notice("hwRead16 to %x", mem); + Console::Notice("hwRead16 to %x", params mem); SPR_LOG("Hardware read 16bit at %lx, ret %lx\n", mem, psHu16(mem)); @@ -1016,7 +1016,7 @@ void hwWrite64(u32 mem, u64 value) { switch (mem) { case GIF_CTRL: - DevCon::Status("GIF_CTRL write 64", value); + DevCon::Status("GIF_CTRL write 64", params value); psHu32(mem) = value & 0x8; if(value & 0x1) { gsGIFReset(); @@ -1031,7 +1031,7 @@ void hwWrite64(u32 mem, u64 value) { case GIF_MODE: #ifdef GSPATH3FIX - Console::Status("GIFMODE64 %x\n", value); + Console::Status("GIFMODE64 %x\n", params value); #endif psHu64(GIF_MODE) = value; if (value & 0x1) psHu32(GIF_STAT)|= 0x1; diff --git a/pcsx2/Hw.h b/pcsx2/Hw.h index 47570a57b8..48cbebd0f8 100644 --- a/pcsx2/Hw.h +++ b/pcsx2/Hw.h @@ -353,7 +353,7 @@ static __forceinline void *dmaGetAddr(u32 addr) { ptr = (u8*)vtlb_GetPhyPtr(addr&0x1FFFFFF0); if (ptr == NULL) { - Console::Error("*PCSX2*: DMA error: %8.8x", addr); + Console::Error("*PCSX2*: DMA error: %8.8x", params addr); return NULL; } return ptr; diff --git a/pcsx2/Interpreter.cpp b/pcsx2/Interpreter.cpp index fc375877d5..717f380cda 100644 --- a/pcsx2/Interpreter.cpp +++ b/pcsx2/Interpreter.cpp @@ -834,7 +834,7 @@ int __Deci2Call(int call, u32 *addr) { return 1; case 0x10://kputs - Console::Write( Color_Cyan, "%s", PSM(*addr)); + Console::Write( Color_Cyan, "%s", params PSM(*addr)); return 1; } @@ -851,7 +851,7 @@ void SYSCALL() { else call = cpuRegs.GPR.n.v1.UC[0]; BIOS_LOG("Bios call: %s (%x)\n", bios[call], call); if (call == 0x7c && cpuRegs.GPR.n.a0.UL[0] == 0x10) { - Console::Write( Color_Cyan, "%s", PSM(PSMu32(cpuRegs.GPR.n.a1.UL[0]))); + Console::Write( Color_Cyan, "%s", params PSM(PSMu32(cpuRegs.GPR.n.a1.UL[0]))); } else //if (call == 0x7c) SysPrintf("Deci2Call: %x\n", cpuRegs.GPR.n.a0.UL[0]); if (call == 0x7c) __Deci2Call(cpuRegs.GPR.n.a0.UL[0], (u32*)PSM(cpuRegs.GPR.n.a1.UL[0])); diff --git a/pcsx2/Linux/ConfigDlg.cpp b/pcsx2/Linux/ConfigDlg.cpp index 9836da8dde..7f8d1cf60a 100644 --- a/pcsx2/Linux/ConfigDlg.cpp +++ b/pcsx2/Linux/ConfigDlg.cpp @@ -472,7 +472,7 @@ void FindPlugins() { Handle = dlopen(plugin, RTLD_NOW); if (Handle == NULL) { - Console::Error("Can't open %s: %s\n", ent->d_name, dlerror()); + Console::Error("Can't open %s: %s\n"_F, ent->d_name, dlerror()); continue; } @@ -482,17 +482,17 @@ void FindPlugins() { if (PS2EgetLibType == NULL) { - Console::Error("PS2EgetLibType==NULL for %s", ent->d_name); + Console::Error("PS2EgetLibType==NULL for %s"_F, ent->d_name); continue; } if (PS2EgetLibName == NULL) { - Console::Error("PS2EgetLibName==NULL for %s", ent->d_name); + Console::Error("PS2EgetLibName==NULL for %s"_F, ent->d_name); continue; } if (PS2EgetLibVersion2 == NULL) { - Console::Error("PS2EgetLibVersion2==NULL for %s", ent->d_name); + Console::Error("PS2EgetLibVersion2==NULL for %s"_F, ent->d_name); continue; } @@ -505,7 +505,7 @@ void FindPlugins() { if (((version >> 16)&0xff) == PS2E_GS_VERSION) ComboAddPlugin(name, &GSConfS, version, ent); else - Console::Notice("Plugin %s: Version %x != %x", plugin, (version >> 16)&0xff, PS2E_GS_VERSION); + Console::Notice("Plugin %s: Version %x != %x"F_, plugin, (version >> 16)&0xff, PS2E_GS_VERSION); } if (type & PS2E_LT_PAD) { @@ -520,7 +520,7 @@ void FindPlugins() { if (query() & 0x2) ComboAddPlugin(name, &PAD2ConfS, version, ent); } else - Console::Notice("Plugin %s: Version %x != %x", plugin, (version >> 16)&0xff, PS2E_PAD_VERSION); + Console::Notice("Plugin %s: Version %x != %x"_F, plugin, (version >> 16)&0xff, PS2E_PAD_VERSION); } if (type & PS2E_LT_SPU2) { @@ -529,7 +529,7 @@ void FindPlugins() { if (((version >> 16)&0xff) == PS2E_SPU2_VERSION) ComboAddPlugin(name, &SPU2ConfS, version, ent); else - Console::Notice("Plugin %s: Version %x != %x", plugin, (version >> 16)&0xff, PS2E_SPU2_VERSION); + Console::Notice("Plugin %s: Version %x != %x"_F, plugin, (version >> 16)&0xff, PS2E_SPU2_VERSION); } if (type & PS2E_LT_CDVD) { @@ -538,7 +538,7 @@ void FindPlugins() { if (((version >> 16)&0xff) == PS2E_CDVD_VERSION) ComboAddPlugin(name, &CDVDConfS, version, ent); else - Console::Notice("Plugin %s: Version %x != %x", plugin, (version >> 16)&0xff, PS2E_CDVD_VERSION); + Console::Notice("Plugin %s: Version %x != %x"_F, plugin, (version >> 16)&0xff, PS2E_CDVD_VERSION); } if (type & PS2E_LT_DEV9) { @@ -547,7 +547,7 @@ void FindPlugins() { if (((version >> 16)&0xff) == PS2E_DEV9_VERSION) ComboAddPlugin(name, &DEV9ConfS, version, ent); else - Console::Notice("DEV9Plugin %s: Version %x != %x", plugin, (version >> 16)&0xff, PS2E_DEV9_VERSION); + Console::Notice("DEV9Plugin %s: Version %x != %x"_F, plugin, (version >> 16)&0xff, PS2E_DEV9_VERSION); } if (type & PS2E_LT_USB) { @@ -556,7 +556,7 @@ void FindPlugins() { if (((version >> 16)&0xff) == PS2E_USB_VERSION) ComboAddPlugin(name, &USBConfS, version, ent); else - Console::Notice("USBPlugin %s: Version %x != %x", plugin, (version >> 16)&0xff, PS2E_USB_VERSION); + Console::Notice("USBPlugin %s: Version %x != %x"_F, plugin, (version >> 16)&0xff, PS2E_USB_VERSION); } if (type & PS2E_LT_FW) { @@ -565,7 +565,7 @@ void FindPlugins() { if (((version >> 16)&0xff) == PS2E_FW_VERSION) ComboAddPlugin(name, &FWConfS, version, ent); else - Console::Notice("FWPlugin %s: Version %x != %x", plugin, (version >> 16)&0xff, PS2E_FW_VERSION); + Console::Notice("FWPlugin %s: Version %x != %x"_F, plugin, (version >> 16)&0xff, PS2E_FW_VERSION); } } closedir(dir); diff --git a/pcsx2/Linux/GtkGui.cpp b/pcsx2/Linux/GtkGui.cpp index f65ec6925c..d0f565ad1c 100644 --- a/pcsx2/Linux/GtkGui.cpp +++ b/pcsx2/Linux/GtkGui.cpp @@ -369,9 +369,9 @@ void States_Load(const char* file, int num = -1 ) catch( std::exception& ex ) { if( num != -1 ) - Console::Error( _("Error occured while trying to load savestate slot %d"), num); + Console::Error( _("Error occured while trying to load savestate slot %d")F_, num); else - Console::Error( _("Error occured while trying to load savestate file: %d"), file); + Console::Error( _("Error occured while trying to load savestate file: %d")F_, file); Console::Error( ex.what() ); @@ -397,7 +397,7 @@ void States_Load(int num) { struct stat buf; if( stat(Text, &buf ) == -1 ) { - Console::Notice( "Saveslot %d is empty.", num ); + Console::Notice( "Saveslot %d is empty."F_, num ); return; } States_Load( Text, num ); @@ -409,9 +409,9 @@ void States_Save( const char* file, int num = -1 ) { gzSavingState(file).FreezeAll(); if( num != -1 ) - Console::Notice( _( "State saved to slot %d" ), num ); + Console::Notice( _( "State saved to slot %d" )F_, num ); else - Console::Notice( _( "State saved to file: %s" ), file ); + Console::Notice( _( "State saved to file: %s" )F_, file ); } catch( std::exception& ex ) { diff --git a/pcsx2/Linux/LnxConsole.cpp b/pcsx2/Linux/LnxConsole.cpp index cd048fe172..d389bd5774 100644 --- a/pcsx2/Linux/LnxConsole.cpp +++ b/pcsx2/Linux/LnxConsole.cpp @@ -37,7 +37,7 @@ namespace Console , "\033[37m" // white! }; - void SetTitle( const char* title ) + void SetTitle( const string& title ) { } @@ -51,7 +51,7 @@ namespace Console __forceinline bool __fastcall Newline() { - if (Config.PsxOut != 0) + if (Config.PsxOut) puts( "\n" ); if (emuLog != NULL) @@ -63,14 +63,13 @@ namespace Console return false; } - __forceinline bool __fastcall Msg( const char* fmt ) + __forceinline bool __fastcall Write( const string& fmt ) { - if (Config.PsxOut != 0) - puts( fmt ); + if (Config.PsxOut) + puts( fmt.c_str() ); - // No flushing here -- only flush after newlines. if (emuLog != NULL) - fputs(fmt, emuLog); + fputs(fmt.c_str(), emuLog); return false; } @@ -84,145 +83,46 @@ namespace Console { Msg( COLOR_RESET ); } +} - __forceinline bool __fastcall MsgLn( const char* fmt ) +namespace Msgbox +{ + bool Alert( const string& fmt ) { - Msg( fmt ); - Newline(); - return false; + if (!UseGui) + { + Error( msg ); + return false; + } + + GtkWidget *dialog; + + dialog = gtk_message_dialog_new (GTK_WINDOW(MainWindow), + GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_MESSAGE_ERROR, + GTK_BUTTONS_OK, fmt); + gtk_dialog_run (GTK_DIALOG (dialog)); + gtk_widget_destroy (dialog); + + return false; } - // Writes an unformatted string of text to the console (fast!) - // A newline is automatically appended. - __forceinline bool __fastcall MsgLn( Colors color, const char* fmt ) - { - SetColor( color ); - Write( fmt ); - ClearColor(); - Newline(); - return false; - } - - static __forceinline void __fastcall _WriteLn( Colors color, const char* fmt, va_list args ) - { - char msg[2048]; - - vsnprintf(msg,2045,fmt,args); - msg[2044] = '\0'; - strcat( msg, "\n" ); - SetColor( color ); - Msg( msg ); - ClearColor(); - - if( emuLog != NULL ) - fflush( emuLog ); // manual flush to accompany manual newline - } - - // Writes a line of colored text to the console, with automatic newline appendage. - bool WriteLn( Colors color, const char* fmt, ... ) - { - va_list list; - va_start(list,fmt); - _WriteLn( Color_White, fmt, list ); - va_end(list); - return false; - } - - bool Write( Colors color, const char* fmt, ... ) - { - va_list list; - char msg[2048]; - - va_start(list,fmt); - vsnprintf(msg,2047,fmt,list); - msg[2047] = '\0'; - va_end(list); - - SetColor( color ); - Msg( msg ); - ClearColor(); - return false; - } - - bool Write( const char* fmt, ... ) - { - va_list list; - char msg[2048]; - - va_start(list,fmt); - vsnprintf(msg,2047,fmt,list); - msg[2047] = '\0'; - va_end(list); - - Msg( msg ); - return false; - } - - bool WriteLn( const char* fmt, ... ) - { - va_list list; - char msg[2048]; - - va_start(list,fmt); - vsnprintf(msg,2046,fmt,list); // 2046 to leave room for the newline - va_end(list); - - strcat( msg, "\n" ); // yeah, that newline! - Msg( msg ); - if( emuLog != NULL ) - fflush( emuLog ); // manual flush to accomany manual newline - return false; - } - - // Displays a message in the console with red emphasis. - // Newline is automatically appended. - bool Error( const char* fmt, ... ) - { - va_list list; - va_start(list,fmt); - _WriteLn( Color_Red, fmt, list ); - va_end(list); - return false; - } - - // Displays a message in the console with yellow emphasis. - // Newline is automatically appended. - bool Notice( const char* fmt, ... ) - { - va_list list; - va_start(list,fmt); - _WriteLn( Color_Yellow, fmt, list ); - va_end(list); - return false; - } - - // Displays a message in the console with green emphasis. - // Newline is automatically appended. - bool Status( const char* fmt, ... ) - { - va_list list; - va_start(list,fmt); - _WriteLn( Color_Yellow, fmt, list ); - va_end(list); - return false; - } - - bool Alert(const char *fmt, ...) + bool Alert(const string& fmt, VARG_PARAM dummy, ...) { GtkWidget *dialog; - va_list list; - char msg[512]; + string msg; - va_start(list, fmt); - vsprintf(msg, fmt, list); + va_list list; + va_start(list, dummy); + ssprintf(msg, fmt, list); va_end(list); - if (msg[strlen(msg)-1] == '\n') - msg[strlen(msg)-1] = 0; + if (msg[msg.length()-1] == '\n') + msg[msg.length()-1] = 0; if (!UseGui) { - Error("%s",msg); + Error( msg ); return false; } dialog = gtk_message_dialog_new (GTK_WINDOW(MainWindow), diff --git a/pcsx2/Linux/LnxMain.cpp b/pcsx2/Linux/LnxMain.cpp index 2b4107460d..a9c73d4878 100644 --- a/pcsx2/Linux/LnxMain.cpp +++ b/pcsx2/Linux/LnxMain.cpp @@ -341,7 +341,7 @@ void SysMessage(const char *fmt, ...) { msg[511] = '\0'; va_end(list); - Console::Alert(msg); + Msgbox::Alert(msg); } bool SysInit() diff --git a/pcsx2/Linux/LnxThreads.cpp b/pcsx2/Linux/LnxThreads.cpp index 04f0bbe528..a1146d1ba8 100644 --- a/pcsx2/Linux/LnxThreads.cpp +++ b/pcsx2/Linux/LnxThreads.cpp @@ -72,7 +72,7 @@ namespace Threading } catch( std::exception& ex ) { - Console::Error( "Thread terminated abnormally with error:\n\t%s", ex.what() ); + Console::Error( "Thread terminated abnormally with error:\n\t%s"_F, ex.what() ); owner.m_returncode = -1; } diff --git a/pcsx2/MTGS.cpp b/pcsx2/MTGS.cpp index 30ea6c490b..6f5c2408dd 100644 --- a/pcsx2/MTGS.cpp +++ b/pcsx2/MTGS.cpp @@ -223,7 +223,7 @@ mtgsThreadObject::mtgsThreadObject() : mtgsThreadObject::~mtgsThreadObject() { - Console::MsgLn( "MTGS > Closing GS thread..." ); + Console::WriteLn( "MTGS > Closing GS thread..." ); SetEvent(); // rest of the cleanup will be handled by the inherited object destructors... @@ -416,7 +416,7 @@ __forceinline u32 mtgsThreadObject::_gifTransferDummy( GIF_PATH pathidx, const u if(!path.tag.eop && path.tag.nloop > 0) { path.tag.nloop = 0; - DevCon::Msg( "path1 hack! " ); + DevCon::Write( "path1 hack! " ); } } #ifdef PCSX2_GSRING_SAMPLING_STATS @@ -431,12 +431,12 @@ __forceinline u32 mtgsThreadObject::_gifTransferDummy( GIF_PATH pathidx, const u int mtgsThreadObject::Callback() { - Console::MsgLn("MTGS > Thread Started, Opening GS Plugin..."); + Console::WriteLn("MTGS > Thread Started, Opening GS Plugin..."); m_returncode = GSopen((void *)&pDsp, "PCSX2", 1); GSCSRr = 0x551B400F; // 0x55190000 m_wait_InitDone.Set(); if (m_returncode != 0) { return m_returncode; } // error msg will be issued to the user by Plugins.c - Console::MsgLn("MTGS > GSopen Finished."); + Console::WriteLn("MTGS > GSopen Finished."); #ifdef RINGBUF_DEBUG_STACK u32 prevCmd=0; @@ -569,7 +569,7 @@ int mtgsThreadObject::Callback() #ifdef PCSX2_DEVBUILD default: - Console::Error("GSThreadProc, bad packet (%x) at m_RingPos: %x, m_WritePos: %x", tag, m_RingPos, m_WritePos); + Console::Error("GSThreadProc, bad packet (%x) at m_RingPos: %x, m_WritePos: %x", params tag, m_RingPos, m_WritePos); assert(0); m_RingPos = m_WritePos; continue; diff --git a/pcsx2/Memory.cpp b/pcsx2/Memory.cpp index bf95b792ab..4701f6409b 100644 --- a/pcsx2/Memory.cpp +++ b/pcsx2/Memory.cpp @@ -229,10 +229,10 @@ int memInit() { } catch( vm_alloc_failed_exception& ex ) { - Console::Error( "Virtual Memory Error > Cannot reserve %dk memory block at 0x%8.8x", + Console::Error( "Virtual Memory Error > Cannot reserve %dk memory block at 0x%8.8x", params ex.requested_size / 1024, ex.requested_addr ); - Console::Error( "\tError code: %d \tReturned address: 0x%8.8x", + Console::Error( "\tError code: %d \tReturned address: 0x%8.8x", params GetLastError(), ex.returned_addr); memShutdown(); @@ -406,7 +406,7 @@ int SysPageFaultExceptionFilter(EXCEPTION_POINTERS* eps) if( SysMapUserPhysicalPages((void*)curvaddr, 1, pmap->aPFNs, 0) ) return EXCEPTION_CONTINUE_EXECUTION; - Console::Error("Virtual Memory Error > page 0x%x cannot be found %d (p:%x,v:%x)\n", + Console::Error("Virtual Memory Error > page 0x%x cannot be found %d (p:%x,v:%x)", params addr-(u32)PS2MEM_BASE, GetLastError(), pmap->aPFNs[0], curvaddr); } } @@ -2597,12 +2597,7 @@ static u8* m_psAllMem = NULL; int memInit() { #ifdef __LINUX__ - struct sigaction sa; - - sigemptyset(&sa.sa_mask); - sa.sa_flags = SA_SIGINFO; - sa.sa_sigaction = &SysPageFaultExceptionFilter; - sigaction(SIGSEGV, &sa, NULL); + InstallLinuxExceptionHandler(); #endif if (!vtlb_Init()) return -1; @@ -2651,7 +2646,7 @@ int memInit() #endif if( m_psAllMem == NULL) { - Console::Alert("Error allocating memory"); + Msgbox::Alert("Error allocating memory"); return -1; } @@ -2716,56 +2711,47 @@ void memClearPageAddr(u32 vaddr) } #endif // PCSX2_VIRTUAL_MEM +// Attempts to load a BIOS rom file, by trying multiple combinations of base filename +// and extension. The bios specified in Config.Bios is used as the base. void loadBiosRom( const char *ext, u8 *dest, long maxSize ) { - struct stat buf; - char Bios1[g_MaxPath]; - char Bios[g_MaxPath]; - FILE *fp; - char *ptr; - int i; + string Bios1; + string Bios; + long filesize; - CombinePaths( Bios, Config.BiosDir, Config.Bios ); + Path::Combine( Bios, Config.BiosDir, Config.Bios ); - sprintf(Bios1, "%s.%s", Bios, ext); - if (stat(Bios1, &buf) != -1) { - fp = fopen(Bios1, "rb"); - fread(dest, 1, buf.st_size, fp); - fclose(fp); - return; + ssprintf(Bios1, "%S.%s", params &Bios, ext); + if( (filesize=Path::isFile( Bios1 ) ) <= 0 ) + { + Path::ReplaceExtension( Bios1, Bios, ext ); + if( (filesize=Path::isFile( Bios1 ) ) <= 0 ) + { + // And this check is... well I'm not sure whf this check is trying to accomplish! (air) + ssprintf( Bios1, "%s%s.bin", params Config.BiosDir, ext ); + if( (filesize=Path::isFile( Bios1 ) ) <= 0 ) + { + Console::Error( "\n\n\n" + "**************\n" + "%s NOT FOUND\n" + "**************\n\n\n", params ext + ); + return; + } + } } - sprintf(Bios1, "%s", Bios); - ptr = Bios1; i = strlen(Bios1); - while (i > 0) { if (ptr[i] == '.') break; i--; } - ptr[i+1] = 0; - strcat(Bios1, ext); - if (stat(Bios1, &buf) != -1) { - fp = fopen(Bios1, "rb"); - fread(dest, 1, std::min( maxSize, buf.st_size ), fp); - fclose(fp); - return; - } + // if we made it this far, we have a successful file found: - sprintf(Bios1, "%s%s.bin", Config.BiosDir, ext); - if (stat(Bios1, &buf) != -1) { - fp = fopen(Bios1, "rb"); - fread(dest, 1, std::min( maxSize, buf.st_size ), fp); - fclose(fp); - return; - } - - Console::Error( "\n\n\n" - "**************\n" - "%s NOT FOUND\n" - "**************\n\n\n", ext - ); + FILE *fp = fopen(Bios1.c_str(), "rb"); + fread(dest, 1, std::min( maxSize, filesize ), fp); + fclose(fp); } void memReset() { struct stat buf; - char Bios[g_MaxPath]; + string Bios; FILE *fp; #ifdef PCSX2_VIRTUAL_MEM @@ -2778,11 +2764,12 @@ void memReset() memset(psS, 0, Ps2MemSize::Scratch); #endif - CombinePaths( Bios, Config.BiosDir, Config.Bios ); + Path::Combine( Bios, Config.BiosDir, Config.Bios ); - if (stat(Bios, &buf) == -1) + long filesize; + if( ( filesize = Path::getFileSize( Bios ) ) <= 0 ) { - Console::Error(_("Unable to load bios: '%s', PCSX2 can't run without that"), Bios); + Console::Error(_("Unable to load bios: '%s', PCSX2 can't run without that"), params Bios); throw Exception::FileNotFound( Bios, "The specified Bios file was not found. A bios is required for Pcsx2 to run.\n\nFile not found" ); } @@ -2804,12 +2791,12 @@ void memReset() #endif - fp = fopen(Bios, "rb"); - fread(PS2MEM_ROM, 1, buf.st_size, fp); + fp = fopen(Bios.c_str(), "rb"); + fread(PS2MEM_ROM, 1, std::min( (long)Ps2MemSize::Rom, filesize ), fp); fclose(fp); BiosVersion = GetBiosVersion(); - Console::WriteLn("Bios Version %d.%d", BiosVersion >> 8, BiosVersion & 0xff); + Console::Status("Bios Version %d.%d", params BiosVersion >> 8, BiosVersion & 0xff); //injectIRX("host.irx"); //not fully tested; still buggy @@ -2883,7 +2870,7 @@ void mmap_MarkCountedRamPage(void* ptr,u32 vaddr) } void mmap_ResetBlockTracking() { - Console::MsgLn("vtlb/mmap: Block Tracking reseted .."); + Console::WriteLn("vtlb/mmap: Block Tracking reseted .."); memset(psMPWC,0,sizeof(psMPWC)); for(u32 i=0;i<(Ps2MemSize::Base>>12);i++) { @@ -2930,14 +2917,29 @@ int SysPageFaultExceptionFilter(EXCEPTION_POINTERS* eps) } #else +#include "errno.h" + +__forceinline void __fastcall InstallLinuxExceptionHandler() +{ + struct sigaction sa; + + sigemptyset(&sa.sa_mask); + sa.sa_flags = SA_SIGINFO; + sa.sa_sigaction = &SysPageFaultExceptionFilter; + sigaction(SIGSEGV, &sa, NULL); +} // Linux implementation of SIGSEGV handler. Bind it using sigaction(). // This is my shot in the dark. Probably needs some work. Good luck! (air) __forceinline void __fastcall SysPageFaultExceptionFilter( int signal, siginfo_t *info, void * ) { - //Console::Error("SysPageFaultExceptionFilter!"); + int err; + u32 pagesize = getpagesize(); + + //DevCon::Error("SysPageFaultExceptionFilter!"); // get bad virtual address u32 offset = (u8*)info->si_addr - psM; + uptr pageoffset = ( offset / pagesize ) * pagesize; if (offset>=Ps2MemSize::Base) { @@ -2946,8 +2948,9 @@ __forceinline void __fastcall SysPageFaultExceptionFilter( int signal, siginfo_t assert( false ); } - mprotect(&psM[offset], 1, PROT_READ|PROT_WRITE); - + err = mprotect( &psM[pageoffset], pagesize, PROT_READ | PROT_WRITE ); + if (err) DevCon::Error("SysPageFaultExceptionFilter: %s", strerror(errno)); + offset>>=12; psMPWC[(offset/32)]|=(1<<(offset&31)); diff --git a/pcsx2/Misc.cpp b/pcsx2/Misc.cpp index 234fcab538..3b2b0224a4 100644 --- a/pcsx2/Misc.cpp +++ b/pcsx2/Misc.cpp @@ -351,7 +351,7 @@ int GetPS2ElfName(char *name){ u32 addr; - Console::MsgLn("Loading System.map..."); + Console::WriteLn("Loading System.map..."); while (!feof(fp)) { fseek(fp, 8, SEEK_CUR); buffer[0] = '0'; buffer[1] = 'x'; @@ -377,11 +377,11 @@ extern u32 dumplog; #ifdef PCSX2_DEVBUILD -void SaveGSState(const char *file) +void SaveGSState(const string& file) { if( g_SaveGSStream ) return; - Console::Msg( "SaveGSState: " ); Console::MsgLn( file ); + Console::WriteLn( _("Saving GS State...") + file ); g_fGSSave = new gzSavingState( file ); g_SaveGSStream = 1; @@ -391,27 +391,25 @@ void SaveGSState(const char *file) } extern uptr pDsp; -void LoadGSState(const char *file) +void LoadGSState(const string& file) { int ret; gzLoadingState* f; - Console::Msg( "LoadGSState: " ); + Console::Status( "Loading GS State..." ); try { f = new gzLoadingState( file ); - Console::MsgLn( file ); } catch( Exception::FileNotFound& ) { // file not found? try prefixing with sstates folder: - if( !isPathRooted( file ) ) + if( !Path::isRooted( file ) ) { - char strfile[g_MaxPath]; - CombinePaths( strfile, SSTATES_DIR, file ); - f = new gzLoadingState( file ); - Console::MsgLn( strfile ); + string strfile; + Path::Combine( strfile, SSTATES_DIR, file ); + f = new gzLoadingState( strfile.c_str() ); // If this load attempt fails, then let the exception bubble up to // the caller to deal with... @@ -503,16 +501,16 @@ char* mystrlwr( char* string ) return string; } -static void GetGSStateFilename( char* dest ) +static void GetGSStateFilename( string& dest ) { - char gsText[72]; - sprintf( gsText, "/%8.8X.%d.gs", ElfCRC, StatesC); - CombinePaths( dest, SSTATES_DIR, gsText ); + string gsText; + ssprintf( gsText, "/%8.8X.%d.gs",params ElfCRC, StatesC); + Path::Combine( dest, SSTATES_DIR, gsText ); } void ProcessFKeys(int fkey, int shift) { - char Text[g_MaxPath]; + string Text; assert(fkey >= 1 && fkey <= 12 ); @@ -521,14 +519,14 @@ void ProcessFKeys(int fkey, int shift) try { SaveState::GetFilename( Text, StatesC ); - gzSavingState(Text).FreezeAll(); + gzSavingState( Text ).FreezeAll(); } catch( std::exception& ex ) { // 99% of the time this is a file permission error and the // cpu state is intact so just display a passive msg to console. - Console::Error( _( "Error > Could not save state to slot %d" ), StatesC ); + Console::Error( _( "Error > Could not save state to slot %d" ), params StatesC ); Console::Error( ex.what() ); } break; @@ -539,11 +537,11 @@ void ProcessFKeys(int fkey, int shift) else StatesC = (StatesC+1) % NUM_STATES; - Console::Notice( _( " > Selected savestate slot %d" ), StatesC); + Console::Notice( _( " > Selected savestate slot %d" ), params StatesC); if( GSchangeSaveState != NULL ) { SaveState::GetFilename(Text, StatesC); - GSchangeSaveState(StatesC, Text); + GSchangeSaveState(StatesC, Text.c_str()); } break; @@ -551,27 +549,27 @@ void ProcessFKeys(int fkey, int shift) try { SaveState::GetFilename( Text, StatesC ); - gzLoadingState joe(Text); // throws exception on version mismatch + gzLoadingState joe( Text ); // throws exception on version mismatch cpuReset(); joe.FreezeAll(); } - catch( Exception::UnsupportedStateVersion& ) + catch( Exception::StateLoadError_Recoverable& ) { // At this point the cpu hasn't been reset, so we can return - // control to the user safely... + // control to the user safely... (and silently) } catch( Exception::FileNotFound& ) { - Console::Notice( _("Saveslot %d cannot be loaded; slot does not exist (file not found)"), StatesC ); + Console::Notice( _("Saveslot %d cannot be loaded; slot does not exist (file not found)"), params StatesC ); } catch( std::runtime_error& ex ) { // This is the bad one. Chances are the cpu has been reset, so emulation has // to be aborted. Sorry user! We'll give you some info for your trouble: - Console::Error( _("An error occured while trying to load saveslot %d"), StatesC ); + Console::Error( _("An error occured while trying to load saveslot %d"), params StatesC ); Console::Error( ex.what() ); - Console::Alert( + Msgbox::Alert( "Pcsx2 encountered an error while trying to load the savestate\n" "and emulation had to be aborted." ); @@ -626,7 +624,7 @@ void ProcessFKeys(int fkey, int shift) } Threading::AtomicExchange( Config.Options, newOptions ); - Console::Notice("Frame Limit Mode Changed: %s", limitMsg ); + Console::Notice("Frame Limit Mode Changed: %s", params limitMsg ); // [Air]: Do we really want to save runtime changes to frameskipping? //SaveConfig(); @@ -666,15 +664,15 @@ void ProcessFKeys(int fkey, int shift) if( strgametitle[0] != 0 ) { // only take the first two words char name[256], *tok; - char gsText[256]; + string gsText; tok = strtok(strgametitle, " "); sprintf(name, "%s_", mystrlwr(tok)); tok = strtok(NULL, " "); if( tok != NULL ) strcat(name, tok); - sprintf( gsText, "%s.%d.gs", name, StatesC); - CombinePaths( Text, SSTATES_DIR, gsText ); + ssprintf( gsText, "%s.%d.gs", params name, StatesC); + Path::Combine( Text, SSTATES_DIR, gsText ); } else GetGSStateFilename( Text ); @@ -688,7 +686,7 @@ void ProcessFKeys(int fkey, int shift) if( shift ) { #ifdef PCSX2_DEVBUILD iDumpRegisters(cpuRegs.pc, 0); - Console::Notice("hardware registers dumped EE:%x, IOP:%x\n", cpuRegs.pc, psxRegs.pc); + Console::Notice("hardware registers dumped EE:%x, IOP:%x\n", params cpuRegs.pc, psxRegs.pc); #endif } else { @@ -750,7 +748,7 @@ void injectIRX(const char *filename){ strcat(path, filename); if (stat(path, &buf) == -1){ - Console::Alert("Unable to hack in %s%s\n", Config.BiosDir, filename); + Msgbox::Alert("Unable to hack in %s%s\n", params Config.BiosDir, filename); return; } diff --git a/pcsx2/Misc.h b/pcsx2/Misc.h index 74712f8ca1..400e84e16a 100644 --- a/pcsx2/Misc.h +++ b/pcsx2/Misc.h @@ -56,10 +56,18 @@ // --->> Path Utilities [PathUtil.c] #define g_MaxPath 255 // 255 is safer with antiquitated Win32 ASCII APIs. -extern int g_Error_PathTooLong; -int isPathRooted( const char* path ); -void CombinePaths( char* dest, const char* srcPath, const char* srcFile ); +namespace Path +{ + void Combine( string& dest, const string& srcPath, const string& srcFile ); + bool isRooted( const string& path ); + bool isDirectory( const string& path ); + bool isFile( const string& path ); + bool Exists( const string& path ); + int getFileSize( const string& path ); + + void ReplaceExtension( string& dest, const string& src, const string& ext ); +} // <<--- END Path Utilities [PathUtil.c] @@ -107,7 +115,8 @@ void CombinePaths( char* dest, const char* srcPath, const char* srcFile ); #define CHECK_VU1REC (Config.Options&PCSX2_VU1REC) -struct PcsxConfig { +struct PcsxConfig +{ char Bios[g_MaxPath]; char GS[g_MaxPath]; char PAD1[g_MaxPath]; @@ -122,11 +131,13 @@ struct PcsxConfig { char PluginsDir[g_MaxPath]; char BiosDir[g_MaxPath]; char Lang[g_MaxPath]; + u32 Options; // PCSX2_X options bool PsxOut; bool Profiler; // Displays profiling info to console bool cdvdPrint; // Prints cdvd reads to console + bool closeGSonEsc; // closes the GS (and saves its state) on escape automatically. int PsxType; int Cdda; @@ -157,8 +168,8 @@ int GetPS2ElfName(char*); extern const char *LabelAuthors; extern const char *LabelGreets; -void SaveGSState(const char *file); -void LoadGSState(const char *file); +void SaveGSState(const string& file); +void LoadGSState(const string& file); char *ParseLang(char *id); void ProcessFKeys(int fkey, int shift); // processes fkey related commands value 1-12 diff --git a/pcsx2/Patch.cpp b/pcsx2/Patch.cpp index 19ddb581e8..4023ff6003 100644 --- a/pcsx2/Patch.cpp +++ b/pcsx2/Patch.cpp @@ -346,7 +346,7 @@ void applypatch(int place) { int i; if (place == 0) { - Console::WriteLn(" patchnumber: %d", patchnumber); + Console::WriteLn(" patchnumber: %d", params patchnumber); } for ( i = 0; i < patchnumber; i++ ) { @@ -356,13 +356,13 @@ void applypatch(int place) { void patchFunc_comment( char * text1, char * text2 ) { - Console::WriteLn( "comment: %s", text2 ); + Console::WriteLn( "comment: %s", params text2 ); } void patchFunc_gametitle( char * text1, char * text2 ) { - Console::WriteLn( "gametitle: %s", text2 ); + Console::WriteLn( "gametitle: %s", params text2 ); sprintf(strgametitle,"%s",text2); Console::SetTitle(strgametitle); } @@ -373,7 +373,7 @@ void patchFunc_patch( char * cmd, char * param ) if ( patchnumber >= MAX_PATCH ) { - Console::Error( "Patch ERROR: Maximum number of patches reached: %s=%s", cmd, param ); + Console::Error( "Patch ERROR: Maximum number of patches reached: %s=%s", params cmd, param ); return; } @@ -387,7 +387,7 @@ void patchFunc_patch( char * cmd, char * param ) patch[ patchnumber ].cpu = (patch_cpu_type)PatchTableExecute( pText, NULL, cpuCore ); if ( patch[ patchnumber ].cpu == 0 ) { - Console::Error( "Unrecognized patch '%s'", pText ); + Console::Error( "Unrecognized patch '%s'", params pText ); return; } @@ -400,7 +400,7 @@ void patchFunc_patch( char * cmd, char * param ) patch[ patchnumber ].type = (patch_data_type)PatchTableExecute( pText, NULL, dataType ); if ( patch[ patchnumber ].type == 0 ) { - Console::Error( "Unrecognized patch '%s'", pText ); + Console::Error( "Unrecognized patch '%s'", params pText ); return; } @@ -490,7 +490,7 @@ void inisection_process( FILE * f1 ) //this routine is for reading the ini file -void inifile_read( char * name ) +void inifile_read( const char * name ) { FILE * f1; char buffer[ 1024 ]; @@ -522,7 +522,7 @@ void inifile_read( char * name ) if( !f1 ) { - Console::MsgLn( _( "No patch found.Resuming execution without a patch (this is NOT an error)." )); + Console::WriteLn( _( "No patch found.Resuming execution without a patch (this is NOT an error)." )); return; } @@ -636,7 +636,7 @@ void patchFunc_zerogs(char* cmd, char* param) void SetRoundMode(u32 ee, u32 vu) { // don't set a state for interpreter only - //Console::Alert("SetRoundMode: Config.sseMXCSR = %x; Config.sseVUMXCSR = %x \n", Config.sseMXCSR, Config.sseVUMXCSR); + //Msgbox::Alert("SetRoundMode: Config.sseMXCSR = %x; Config.sseVUMXCSR = %x \n", Config.sseMXCSR, Config.sseVUMXCSR); SetCPUState( (Config.sseMXCSR & 0x9fff) | ee, (Config.sseVUMXCSR & 0x9fff) | vu); } diff --git a/pcsx2/Patch.h b/pcsx2/Patch.h index 80db33d882..ecdfb8edf8 100644 --- a/pcsx2/Patch.h +++ b/pcsx2/Patch.h @@ -111,7 +111,7 @@ extern u32 LinuxsseVUMXCSR; #endif void applypatch( int place ); -void inifile_read( char * name ); +void inifile_read( const char * name ); void inifile_command( char * cmd ); void resetpatch( void ); @@ -134,7 +134,7 @@ extern u32 g_sseVUMXCSR; void SetCPUState(u32 sseMXCSR, u32 sseVUMXCSR); void SetRoundMode(u32 ee, u32 vu); -int LoadPatch(char *patchfile); +int LoadPatch(const std::string& patchfile); #endif /* __PATCH_H__ */ diff --git a/pcsx2/PathUtils.cpp b/pcsx2/PathUtils.cpp index 2455227fa5..174d593ef3 100644 --- a/pcsx2/PathUtils.cpp +++ b/pcsx2/PathUtils.cpp @@ -17,22 +17,51 @@ */ #include "PrecompiledHeader.h" - #include "Common.h" -// This global set true by path methods when they encounter long paths. -// If it flags true it means the app isn't stable and should be terminated. -// (someday this should be replaced with proper C++ exception handling) -int g_Error_PathTooLong = FALSE; +namespace Path +{ #ifdef WIN32 -static const char PathSeparator = '\\'; +static const char Separator = '\\'; #else -static const char PathSeparator = '/'; +static const char Separator = '/'; #endif +bool Exists( const string& path ) +{ + struct stat sbuf; + return stat( path.c_str(), &sbuf ) == 0; +} -int isPathRooted( const char* path ) +// This function returns false if the path does not exist, or if the path exists and +// is a file. +bool isDirectory( const string& path ) +{ + struct stat sbuf; + if( stat( path.c_str(), &sbuf ) == -1 ) return false; + return !!(sbuf.st_mode & _S_IFDIR); +} + +// This function returns false if the path does not exist, or if the path exists and +// is a directory. +bool isFile( const string& path ) +{ + struct stat sbuf; + if( stat( path.c_str(), &sbuf ) == -1 ) return false; + return !!(sbuf.st_mode & _S_IFREG); +} + +// Returns the length of the file. +// returns -1 if the file is not found. +int getFileSize( const string& path ) +{ + struct stat sbuf; + if( stat( path.c_str(), &sbuf ) == -1 ) return -1; + return sbuf.st_size; +} + +bool isRooted( const string& path ) { // if the first character is a backslash or period, or the second character // a colon, it's a safe bet we're rooted. @@ -47,65 +76,60 @@ int isPathRooted( const char* path ) // Concatenates two pathnames together, inserting delimiters (backslash on win32) // as needed! Assumes the 'dest' is allocated to at least g_MaxPath length. -void CombinePaths( char* dest, const char* srcPath, const char* srcFile ) +void Combine( string& dest, const string& srcPath, const string& srcFile ) { int pathlen, guesslen; - char tmp[g_MaxPath]; - if( g_Error_PathTooLong ) - { - // This means a previous call has already failed and given the user - // a message. Pcsx2 will exit as soon as it finds out, so skip - // this operation (avoids the redundant message below) - // [TODO] : Proper exception handling would resolve this hack! - - return; - } - - if( srcFile == NULL || srcFile[0] == 0 ) + if( srcFile.empty() ) { // No source filename? Return the path unmodified. - if( srcPath != NULL ) strcpy( dest, srcPath ); + dest = srcPath; return; } - if( isPathRooted( srcFile ) || srcPath == NULL || srcPath[0] == 0 ) + if( isRooted( srcFile ) || srcPath.empty() ) { // No source path? Or source filename is rooted? // Return the filename unmodified. - strcpy( dest, srcFile ); + dest = srcFile; return; } - - // strip off the srcPath's trialing backslashes (if any) + // strip off the srcPath's trailing backslashes (if any) // Note: The win32 build works better if I check for both forward and backslashes. // This might be a problem on Linux builds or maybe it doesn't matter? - strcpy( tmp, srcPath ); - pathlen = strlen( tmp ); - while( pathlen > 0 && ((tmp[pathlen-1] == '\\') || (tmp[pathlen-1] == '/')) ) - { + + pathlen = srcPath.length(); + while( pathlen > 0 && ((srcPath[pathlen-1] == '\\') || (srcPath[pathlen-1] == '/')) ) --pathlen; - tmp[pathlen] = 0; - } // Concatenate strings: - guesslen = pathlen + strlen(srcFile) + 2; + guesslen = pathlen + srcFile.length() + 2; if( guesslen >= g_MaxPath ) - { - Console::Alert( - "Pcsx2 path names are too long. Please move or reinstall Pcsx2 to\n" - "a location on your hard drive that has a shorter total path." - ); - - g_Error_PathTooLong = TRUE; - // [TODO]: Here would be a nice place for future C++ exception handling! - } + throw Exception::PathTooLong(); -#ifdef WIN32 - sprintf_s( dest, g_MaxPath, "%s%c%s", tmp, PathSeparator, srcFile ); -#else - sprintf( dest, "%s%c%s", srcPath, PathSeparator, srcFile ); -#endif + // Concatenate! + + dest.assign( srcPath.begin(), srcPath.begin()+pathlen ); + dest += Separator; + dest += srcFile; } + +// Replaces the extension of the file with the one given. +void ReplaceExtension( string& dest, const string& src, const string& ext ) +{ + int pos = src.find_last_of( '.' ); + if( pos == 0 ) + dest = src; + else + dest.assign( src.begin(), src.begin()+pos ); + + if( !ext.empty() ) + { + dest += '.'; + dest += ext; + } +} + +} \ No newline at end of file diff --git a/pcsx2/Paths.h b/pcsx2/Paths.h index 143baf4f9d..b98cde45de 100644 --- a/pcsx2/Paths.h +++ b/pcsx2/Paths.h @@ -10,9 +10,10 @@ #define PATCHES_DIR "patches" #define SSTATES_DIR "sstates" - #define LANGS_DIR "Langs" - #define LOGS_DIR "logs" + +#define DEFAULT_MEMCARD1 "Mcd001.ps2" +#define DEFAULT_MEMCARD2 "Mcd002.ps2" #endif diff --git a/pcsx2/Plugins.cpp b/pcsx2/Plugins.cpp index a345a6bafe..021ca01db9 100644 --- a/pcsx2/Plugins.cpp +++ b/pcsx2/Plugins.cpp @@ -18,8 +18,6 @@ #include "PrecompiledHeader.h" -#include - #include "Common.h" #include "PsxCommon.h" #include "GS.h" @@ -225,7 +223,7 @@ USBhandler usbHandler; #define MapSymbolVar_Error(var,name) if((MapSymbolVar(var,name))==NULL) \ { \ const char* errString = SysLibError(); \ - Console::Alert("%s: Error loading %s: %s", filename, #name, errString); \ + Msgbox::Alert("%s: Error loading %S: %s", params &filename, #name, errString); \ return -1; \ } @@ -240,7 +238,7 @@ USBhandler usbHandler; #define TestPS2Esyms(type) if(_TestPS2Esyms(drv,PS2E_LT_##type,PS2E_##type##_VERSION,filename) < 0) return -1; -int _TestPS2Esyms(void* drv, int type, int expected_version, const char* filename) +int _TestPS2Esyms(void* drv, int type, int expected_version, const string& filename) { _PS2EgetLibType PS2EgetLibType; _PS2EgetLibVersion2 PS2EgetLibVersion2; @@ -253,7 +251,7 @@ int _TestPS2Esyms(void* drv, int type, int expected_version, const char* filenam int actual_version = ((PS2EgetLibVersion2(type) >> 16)&0xff); if( actual_version != expected_version) { - Console::Alert("Can't load '%s', wrong PS2E version (%x != %x)", filename, actual_version, expected_version); + Msgbox::Alert("Can't load '%S', wrong PS2E version (%x != %x)", params &filename, actual_version, expected_version); return -1; } @@ -284,11 +282,12 @@ void CALLBACK GS_configure() {} void CALLBACK GS_about() {} s32 CALLBACK GS_test() { return 0; } -int LoadGSplugin(char *filename) { +int LoadGSplugin(const string& filename) +{ void *drv; - GSplugin = SysLoadLibrary(filename); - if (GSplugin == NULL) { Console::Alert ("Could Not Load GS Plugin '%s': %s", filename, SysLibError()); return -1; } + GSplugin = SysLoadLibrary(filename.c_str()); + if (GSplugin == NULL) { Msgbox::Alert ("Could Not Load GS Plugin '%S': %s", params &filename, SysLibError()); return -1; } drv = GSplugin; TestPS2Esyms(GS); MapSymbol_Error(GSinit); @@ -336,11 +335,11 @@ void CALLBACK PAD1_configure() {} void CALLBACK PAD1_about() {} s32 CALLBACK PAD1_test() { return 0; } -int LoadPAD1plugin(char *filename) { +int LoadPAD1plugin(const string& filename) { void *drv; - PAD1plugin = SysLoadLibrary(filename); - if (PAD1plugin == NULL) { Console::Alert("Could Not Load PAD1 Plugin '%s': %s", filename, SysLibError()); return -1; } + PAD1plugin = SysLoadLibrary(filename.c_str()); + if (PAD1plugin == NULL) { Msgbox::Alert("Could Not Load PAD1 Plugin '%S': %s", params &filename, SysLibError()); return -1; } drv = PAD1plugin; TestPS2Esyms(PAD); MapSymbolPAD_Error(PAD1,PAD,init); @@ -367,11 +366,11 @@ void CALLBACK PAD2_configure() {} void CALLBACK PAD2_about() {} s32 CALLBACK PAD2_test() { return 0; } -int LoadPAD2plugin(char *filename) { +int LoadPAD2plugin(const string& filename) { void *drv; - PAD2plugin = SysLoadLibrary(filename); - if (PAD2plugin == NULL) { Console::Alert("Could Not Load PAD2 Plugin '%s': %s", filename, SysLibError()); return -1; } + PAD2plugin = SysLoadLibrary(filename.c_str()); + if (PAD2plugin == NULL) { Msgbox::Alert("Could Not Load PAD2 Plugin '%S': %s", params &filename, SysLibError()); return -1; } drv = PAD2plugin; TestPS2Esyms(PAD); MapSymbolPAD_Error(PAD2,PAD,init); @@ -399,11 +398,11 @@ void CALLBACK SPU2_configure() {} void CALLBACK SPU2_about() {} s32 CALLBACK SPU2_test() { return 0; } -int LoadSPU2plugin(char *filename) { +int LoadSPU2plugin(const string& filename) { void *drv; - SPU2plugin = SysLoadLibrary(filename); - if (SPU2plugin == NULL) { Console::Alert("Could Not Load SPU2 Plugin '%s': %s", filename, SysLibError()); return -1; } + SPU2plugin = SysLoadLibrary(filename.c_str()); + if (SPU2plugin == NULL) { Msgbox::Alert("Could Not Load SPU2 Plugin '%S': %s", params &filename, SysLibError()); return -1; } drv = SPU2plugin; TestPS2Esyms(SPU2); MapSymbol_Error(SPU2init); @@ -442,11 +441,11 @@ void CALLBACK CDVD_configure() {} void CALLBACK CDVD_about() {} s32 CALLBACK CDVD_test() { return 0; } -int LoadCDVDplugin(char *filename) { +int LoadCDVDplugin(const string& filename) { void *drv; - CDVDplugin = SysLoadLibrary(filename); - if (CDVDplugin == NULL) { Console::Alert("Could Not Load CDVD Plugin '%s': %s", filename, SysLibError()); return -1; } + CDVDplugin = SysLoadLibrary(filename.c_str()); + if (CDVDplugin == NULL) { Msgbox::Alert("Could Not Load CDVD Plugin '%S': %s", params &filename, SysLibError()); return -1; } drv = CDVDplugin; TestPS2Esyms(CDVD); MapSymbol_Error(CDVDinit); @@ -479,11 +478,11 @@ void CALLBACK DEV9_configure() {} void CALLBACK DEV9_about() {} s32 CALLBACK DEV9_test() { return 0; } -int LoadDEV9plugin(char *filename) { +int LoadDEV9plugin(const string& filename) { void *drv; - DEV9plugin = SysLoadLibrary(filename); - if (DEV9plugin == NULL) { Console::Alert("Could Not Load DEV9 Plugin '%s': %s", filename, SysLibError()); return -1; } + DEV9plugin = SysLoadLibrary(filename.c_str()); + if (DEV9plugin == NULL) { Msgbox::Alert("Could Not Load DEV9 Plugin '%S': %s", params &filename, SysLibError()); return -1; } drv = DEV9plugin; TestPS2Esyms(DEV9); MapSymbol_Error(DEV9init); @@ -516,11 +515,11 @@ void CALLBACK USB_configure() {} void CALLBACK USB_about() {} s32 CALLBACK USB_test() { return 0; } -int LoadUSBplugin(char *filename) { +int LoadUSBplugin(const string& filename) { void *drv; - USBplugin = SysLoadLibrary(filename); - if (USBplugin == NULL) { Console::Alert("Could Not Load USB Plugin '%s': %s", filename, SysLibError()); return -1; } + USBplugin = SysLoadLibrary(filename.c_str()); + if (USBplugin == NULL) { Msgbox::Alert("Could Not Load USB Plugin '%S': %s", params &filename, SysLibError()); return -1; } drv = USBplugin; TestPS2Esyms(USB); MapSymbol_Error(USBinit); @@ -553,11 +552,11 @@ void CALLBACK FW_configure() {} void CALLBACK FW_about() {} s32 CALLBACK FW_test() { return 0; } -int LoadFWplugin(char *filename) { +int LoadFWplugin(const string& filename) { void *drv; - FWplugin = SysLoadLibrary(filename); - if (FWplugin == NULL) { Console::Alert("Could Not Load FW Plugin '%s': %s", filename, SysLibError()); return -1; } + FWplugin = SysLoadLibrary(filename.c_str()); + if (FWplugin == NULL) { Msgbox::Alert("Could Not Load FW Plugin '%S': %s", params &filename, SysLibError()); return -1; } drv = FWplugin; TestPS2Esyms(FW); MapSymbol_Error(FWinit); @@ -597,21 +596,21 @@ int InitPlugins() { int ret; ret = GSinit(); - if (ret != 0) { Console::Alert("GSinit error: %d", ret); return -1; } + if (ret != 0) { Msgbox::Alert("GSinit error: %d", params ret); return -1; } ret = PAD1init(1); - if (ret != 0) { Console::Alert("PAD1init error: %d", ret); return -1; } + if (ret != 0) { Msgbox::Alert("PAD1init error: %d", params ret); return -1; } ret = PAD2init(2); - if (ret != 0) { Console::Alert("PAD2init error: %d", ret); return -1; } + if (ret != 0) { Msgbox::Alert("PAD2init error: %d", params ret); return -1; } ret = SPU2init(); - if (ret != 0) { Console::Alert("SPU2init error: %d", ret); return -1; } + if (ret != 0) { Msgbox::Alert("SPU2init error: %d", params ret); return -1; } ret = CDVDinit(); - if (ret != 0) { Console::Alert("CDVDinit error: %d", ret); return -1; } + if (ret != 0) { Msgbox::Alert("CDVDinit error: %d", params ret); return -1; } ret = DEV9init(); - if (ret != 0) { Console::Alert("DEV9init error: %d", ret); return -1; } + if (ret != 0) { Msgbox::Alert("DEV9init error: %d", params ret); return -1; } ret = USBinit(); - if (ret != 0) { Console::Alert("USBinit error: %d", ret); return -1; } + if (ret != 0) { Msgbox::Alert("USBinit error: %d", params ret); return -1; } ret = FWinit(); - if (ret != 0) { Console::Alert("FWinit error: %d", ret); return -1; } + if (ret != 0) { Msgbox::Alert("FWinit error: %d", params ret); return -1; } return 0; } @@ -640,33 +639,32 @@ void ShutdownPlugins() int LoadPlugins() { if( loadp ) return 0; - char Plugin[g_MaxPath]; + string Plugin; - CombinePaths( Plugin, Config.PluginsDir, Config.GS ); + Path::Combine( Plugin, Config.PluginsDir, Config.GS ); if (LoadGSplugin(Plugin) == -1) return -1; - CombinePaths( Plugin, Config.PluginsDir, Config.PAD1 ); + Path::Combine( Plugin, Config.PluginsDir, Config.PAD1 ); if (LoadPAD1plugin(Plugin) == -1) return -1; - CombinePaths( Plugin, Config.PluginsDir, Config.PAD2); + Path::Combine( Plugin, Config.PluginsDir, Config.PAD2); if (LoadPAD2plugin(Plugin) == -1) return -1; - CombinePaths( Plugin, Config.PluginsDir, Config.SPU2); + Path::Combine( Plugin, Config.PluginsDir, Config.SPU2); if (LoadSPU2plugin(Plugin) == -1) return -1; - CombinePaths( Plugin, Config.PluginsDir, Config.CDVD); + Path::Combine( Plugin, Config.PluginsDir, Config.CDVD); if (LoadCDVDplugin(Plugin) == -1) return -1; - CombinePaths( Plugin, Config.PluginsDir, Config.DEV9); + Path::Combine( Plugin, Config.PluginsDir, Config.DEV9); if (LoadDEV9plugin(Plugin) == -1) return -1; - CombinePaths( Plugin, Config.PluginsDir, Config.USB); + Path::Combine( Plugin, Config.PluginsDir, Config.USB); if (LoadUSBplugin(Plugin) == -1) return -1; - CombinePaths( Plugin, Config.PluginsDir, Config.FW); + Path::Combine( Plugin, Config.PluginsDir, Config.FW); if (LoadFWplugin(Plugin) == -1) return -1; - if( g_Error_PathTooLong ) return -1; if (InitPlugins() == -1) return -1; loadp=true; @@ -706,7 +704,7 @@ int OpenPlugins(const char* pTitleFilename) { ret = CDVDopen(pTitleFilename); - if (ret != 0) { Console::Alert("Error Opening CDVD Plugin"); goto OpenError; } + if (ret != 0) { Msgbox::Alert("Error Opening CDVD Plugin"); goto OpenError; } OpenStatus.CDVD = true; cdvdNewDiskCB(); } @@ -714,7 +712,7 @@ int OpenPlugins(const char* pTitleFilename) { // GS isn't closed during emu pauses, so only open it once per instance. if( !OpenStatus.GS ) { ret = gsOpen(); - if (ret != 0) { Console::Alert("Error Opening GS Plugin"); goto OpenError; } + if (ret != 0) { Msgbox::Alert("Error Opening GS Plugin"); goto OpenError; } OpenStatus.GS = true; //then the user input @@ -728,14 +726,14 @@ int OpenPlugins(const char* pTitleFilename) { if( !OpenStatus.PAD1 ) { ret = PAD1open((void *)&pDsp); - if (ret != 0) { Console::Alert("Error Opening PAD1 Plugin"); goto OpenError; } + if (ret != 0) { Msgbox::Alert("Error Opening PAD1 Plugin"); goto OpenError; } OpenStatus.PAD1 = true; } if( !OpenStatus.PAD2 ) { ret = PAD2open((void *)&pDsp); - if (ret != 0) { Console::Alert("Error Opening PAD2 Plugin"); goto OpenError; } + if (ret != 0) { Msgbox::Alert("Error Opening PAD2 Plugin"); goto OpenError; } OpenStatus.PAD2 = true; } @@ -751,7 +749,7 @@ int OpenPlugins(const char* pTitleFilename) { SPU2setClockPtr(&psxRegs.cycle); ret = SPU2open((void*)&pDsp); - if (ret != 0) { Console::Alert("Error Opening SPU2 Plugin"); goto OpenError; } + if (ret != 0) { Msgbox::Alert("Error Opening SPU2 Plugin"); goto OpenError; } OpenStatus.SPU2 = true; } @@ -761,7 +759,7 @@ int OpenPlugins(const char* pTitleFilename) { DEV9irqCallback(dev9Irq); dev9Handler = DEV9irqHandler(); ret = DEV9open(&(psxRegs.pc)); //((void *)&pDsp); - if (ret != 0) { Console::Alert("Error Opening DEV9 Plugin"); goto OpenError; } + if (ret != 0) { Msgbox::Alert("Error Opening DEV9 Plugin"); goto OpenError; } OpenStatus.DEV9 = true; } @@ -771,7 +769,7 @@ int OpenPlugins(const char* pTitleFilename) { usbHandler = USBirqHandler(); USBsetRAM(psxM); ret = USBopen((void *)&pDsp); - if (ret != 0) { Console::Alert("Error Opening USB Plugin"); goto OpenError; } + if (ret != 0) { Msgbox::Alert("Error Opening USB Plugin"); goto OpenError; } OpenStatus.USB = true; } @@ -779,7 +777,7 @@ int OpenPlugins(const char* pTitleFilename) { { FWirqCallback(fwIrq); ret = FWopen((void *)&pDsp); - if (ret != 0) { Console::Alert("Error Opening FW Plugin"); goto OpenError; } + if (ret != 0) { Msgbox::Alert("Error Opening FW Plugin"); goto OpenError; } OpenStatus.FW = true; } @@ -864,5 +862,5 @@ void PluginsResetGS() GSshutdown(); int ret = GSinit(); - if (ret != 0) { Console::Alert("GSinit error: %d", ret); } + if (ret != 0) { Msgbox::Alert("GSinit error: %d", params ret); } } \ No newline at end of file diff --git a/pcsx2/Plugins.h b/pcsx2/Plugins.h index 5cbf4dd63d..a9759fded6 100644 --- a/pcsx2/Plugins.h +++ b/pcsx2/Plugins.h @@ -33,6 +33,8 @@ void ReleasePlugins(); int OpenPlugins(const char* pTitleFilename); void ClosePlugins(); +int InitPlugins(); + // Completely shuts down all plugins and re-initializes them. (clean slate) // Plugins are not unloaded, so changes to Config.Plugins values will not // take effect. Use a manual set oc alls to ReleasePlugins and LoadPlugins for that. diff --git a/pcsx2/PrecompiledHeader.h b/pcsx2/PrecompiledHeader.h index ac328c6d8d..ba1417c691 100644 --- a/pcsx2/PrecompiledHeader.h +++ b/pcsx2/PrecompiledHeader.h @@ -45,11 +45,13 @@ #include // TODO : Add items here that are local to Pcsx2 but stay relatively unchanged for -// long periods of time. Right now that includes... well... zlib. That's about it. +// long periods of time. + +using std::string; // we use it enough, so bring it into the global namespace. -// Well, maybe Ps2Etypes. --arcum42 #include "zlib.h" #include "PS2Etypes.h" +#include "StringUtils.h" //////////////////////////////////////////////////////////////////// // Compiler/OS specific macros and defines -- Begin Section diff --git a/pcsx2/PsxBios.cpp b/pcsx2/PsxBios.cpp index e821d5a5fc..4f1593a868 100644 --- a/pcsx2/PsxBios.cpp +++ b/pcsx2/PsxBios.cpp @@ -249,13 +249,13 @@ _start: memcpy((char*)PSXM(sp), save, 4*4); - Console::Write( Color_Cyan, "%s", tmp); + Console::Write( Color_Cyan, "%s", params tmp); pc0 = ra; } void bios_putchar () { // 3d - Console::Write( Color_Cyan, "%c", a0 ); + Console::Write( Color_Cyan, "%c", params a0 ); pc0 = ra; } diff --git a/pcsx2/PsxDma.cpp b/pcsx2/PsxDma.cpp index 49606afb8e..198f048d7e 100644 --- a/pcsx2/PsxDma.cpp +++ b/pcsx2/PsxDma.cpp @@ -66,7 +66,7 @@ static void __fastcall psxDmaGeneric(u32 madr, u32 bcr, u32 chcr, u32 spuCore, _ break; default: - Console::Error("*** DMA %c - SPU unknown *** %lx addr = %lx size = %lx\n", dmaNum, chcr, madr, bcr); + Console::Error("*** DMA %c - SPU unknown *** %lx addr = %lx size = %lx\n", params dmaNum, chcr, madr, bcr); break; } } diff --git a/pcsx2/PsxHw.cpp b/pcsx2/PsxHw.cpp index 883b9e9a5b..b9e6a4d32c 100644 --- a/pcsx2/PsxHw.cpp +++ b/pcsx2/PsxHw.cpp @@ -705,7 +705,7 @@ void psxHwWrite16(u32 add, u16 value) { USBwrite16(add, value); return; } - if((add & 0xf) == 0x9) DevCon::WriteLn("16bit write (possible chcr set) %x value %x", add, value); + if((add & 0xf) == 0x9) DevCon::WriteLn("16bit write (possible chcr set) %x value %x", params add, value); switch (add) { case 0x1f801040: @@ -1245,7 +1245,7 @@ void psxHwWrite32(u32 add, u32 value) { //------------------------------------------------------------------ case 0x1f8014c0: PSXHW_LOG("RTC_HOLDMODE 32bit write %lx\n", value); - Console::Notice("** RTC_HOLDMODE 32bit write %lx", value); + Console::Notice("** RTC_HOLDMODE 32bit write %lx", params value); break; case 0x1f801450: @@ -1388,7 +1388,7 @@ void psxHw4Write8(u32 add, u8 value) { case 0x1f40203A: cdvdWrite3A(value); return; default: //PSXHW_LOG("*Unknown 8bit write at address %lx value %x\n", add, value); - Console::Notice("*Unknown 8bit write at address %lx value %x", add, value); + Console::Notice("*Unknown 8bit write at address %lx value %x", params add, value); return; } PSXHW_LOG("*Known 8bit write at address %lx value %x\n", add, value); diff --git a/pcsx2/PsxInterpreter.cpp b/pcsx2/PsxInterpreter.cpp index 81437a94bc..a81175c505 100644 --- a/pcsx2/PsxInterpreter.cpp +++ b/pcsx2/PsxInterpreter.cpp @@ -270,15 +270,15 @@ void zeroEx() } if (!strncmp(lib, "loadcore", 8) && code == 6) { - DevCon::WriteLn("loadcore RegisterLibraryEntries (%x): %8.8s", psxRegs.pc, PSXM(psxRegs.GPR.n.a0+12)); + DevCon::WriteLn("loadcore RegisterLibraryEntries (%x): %8.8s", params psxRegs.pc, PSXM(psxRegs.GPR.n.a0+12)); } if (!strncmp(lib, "intrman", 7) && code == 4) { - DevCon::WriteLn("intrman RegisterIntrHandler (%x): intr %s, handler %x", psxRegs.pc, intrname[psxRegs.GPR.n.a0], psxRegs.GPR.n.a2); + DevCon::WriteLn("intrman RegisterIntrHandler (%x): intr %s, handler %x", params psxRegs.pc, intrname[psxRegs.GPR.n.a0], psxRegs.GPR.n.a2); } if (!strncmp(lib, "sifcmd", 6) && code == 17) { - DevCon::WriteLn("sifcmd sceSifRegisterRpc (%x): rpc_id %x", psxRegs.pc, psxRegs.GPR.n.a1); + DevCon::WriteLn("sifcmd sceSifRegisterRpc (%x): rpc_id %x", params psxRegs.pc, psxRegs.GPR.n.a1); } if (!strncmp(lib, "sysclib", 8)) diff --git a/pcsx2/PsxMem.cpp b/pcsx2/PsxMem.cpp index 263458d2fe..2fa5aa135d 100644 --- a/pcsx2/PsxMem.cpp +++ b/pcsx2/PsxMem.cpp @@ -392,7 +392,7 @@ int psxMemInit() if( m_psxAllMem == NULL) { - Console::Alert("Error allocating memory for the IOP processor."); + Msgbox::Alert("Error allocating memory for the IOP processor."); return -1; } diff --git a/pcsx2/R5900.cpp b/pcsx2/R5900.cpp index fdffee82d9..4dbb50c540 100644 --- a/pcsx2/R5900.cpp +++ b/pcsx2/R5900.cpp @@ -65,7 +65,7 @@ bool cpuInit() } catch( std::exception& ex ) { - Console::Error( "Error > %s", ex.what() ); + Console::Error( "Error > %s", params ex.what() ); if( Cpu == &recCpu ) { @@ -83,23 +83,27 @@ bool cpuInit() #ifdef PCSX2_VIRTUAL_MEM if (memInit() == -1) { - PROCESS_INFORMATION pi; - STARTUPINFO si; - char strdir[g_MaxPath], strexe[g_MaxPath]; - if( MessageBox(NULL, "Failed to allocate enough physical memory to run pcsx2. Try closing\n" + if( MessageBox(NULL, + "Failed to allocate enough physical memory to run pcsx2. Try closing\n" "down background programs, restarting windows, or buying more memory.\n\n" - "Launch TLB version of pcsx2 (pcsx2t.exe)?", "Memory Allocation Error", MB_YESNO) == IDYES ) { + "Launch TLB version of pcsx2 (pcsx2t.exe)?", "Memory Allocation Error", MB_YESNO) == IDYES ) + { + PROCESS_INFORMATION pi; + STARTUPINFO si; - GetCurrentDirectory(ARRAYSIZE(strdir), strdir); - //_snprintf(strexe, ARRAYSIZE(strexe), "%s\\pcsx2t.exe", strdir); - CombinePaths( strexe, strdir, "pcsx2t.exe" ); + MemoryAlloc strdir( GetCurrentDirectory( 0, NULL )+2, "VTLB Launcher" ); + string strexe; + + GetCurrentDirectory(strdir.GetLength(), strdir.GetPtr()); + Path::Combine( strexe, strdir.GetPtr(), "pcsx2-vtlb.exe" ); memset(&si, 0, sizeof(si)); - if( !CreateProcess(strexe, "", NULL, NULL, FALSE, DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP, NULL, strdir, &si, &pi)) { - _snprintf(strdir, ARRAYSIZE(strdir), "Failed to launch %s\n", strexe); - MessageBox(NULL, strdir, "Failure", MB_OK); + if( !CreateProcess(strexe.c_str(), "", NULL, NULL, FALSE, DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP, NULL, strdir.GetPtr(), &si, &pi)) + { + MessageBox(NULL, fmt_string( "Failed to launch %S\n", params &strexe ).c_str(), "Failure", MB_OK); } - else { + else + { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } @@ -210,7 +214,7 @@ void cpuException(u32 code, u32 bd) { } } else { offset = 0x180; //Overrride the cause - Console::Notice("cpuException: Status.EXL = 1 cause %x", code); + Console::Notice("cpuException: Status.EXL = 1 cause %x", params code); } if (cpuRegs.CP0.n.Status.b.BEV == 0) { cpuRegs.pc = 0x80000000 + offset; @@ -226,7 +230,7 @@ void cpuException(u32 code, u32 bd) { return; } else if((code & 0x38000) == 0x10000) offset = 0x80; //Performance Counter else if((code & 0x38000) == 0x18000) offset = 0x100; //Debug - else Console::Error("Unknown Level 2 Exception!! Cause %x", code); + else Console::Error("Unknown Level 2 Exception!! Cause %x", params code); if (cpuRegs.CP0.n.Status.b.EXL == 0) { cpuRegs.CP0.n.Status.b.EXL = 1; @@ -240,7 +244,7 @@ void cpuException(u32 code, u32 bd) { } } else { offset = 0x180; //Overrride the cause - Console::Notice("cpuException: Status.EXL = 1 cause %x", code); + Console::Notice("cpuException: Status.EXL = 1 cause %x", params code); } if (cpuRegs.CP0.n.Status.b.DEV == 0) { cpuRegs.pc = 0x80000000 + offset; @@ -252,9 +256,9 @@ void cpuException(u32 code, u32 bd) { } void cpuTlbMiss(u32 addr, u32 bd, u32 excode) { - SysPrintf("cpuTlbMiss pc:%x, cycl:%x, addr: %x, status=%x, code=%x\n", cpuRegs.pc, cpuRegs.cycle, addr, cpuRegs.CP0.n.Status.val, excode); + Console::Error("cpuTlbMiss pc:%x, cycl:%x, addr: %x, status=%x, code=%x", params cpuRegs.pc, cpuRegs.cycle, addr, cpuRegs.CP0.n.Status.val, excode); if (bd) { - SysPrintf("branch delay!!\n"); + Console::Notice("branch delay!!"); } assert(0); // temporary @@ -450,7 +454,7 @@ static __forceinline void _cpuTestTIMR() if ( (cpuRegs.CP0.n.Status.val & 0x8000) && cpuRegs.CP0.n.Count >= cpuRegs.CP0.n.Compare && cpuRegs.CP0.n.Count < cpuRegs.CP0.n.Compare+1000 ) { - Console::Status("timr intr: %x, %x", cpuRegs.CP0.n.Count, cpuRegs.CP0.n.Compare); + Console::Status("timr intr: %x, %x", params cpuRegs.CP0.n.Count, cpuRegs.CP0.n.Compare); cpuException(0x808000, cpuRegs.branch); } } diff --git a/pcsx2/RDebug/deci2_ttyp.cpp b/pcsx2/RDebug/deci2_ttyp.cpp index 1309d31604..8ee434b65d 100644 --- a/pcsx2/RDebug/deci2_ttyp.cpp +++ b/pcsx2/RDebug/deci2_ttyp.cpp @@ -36,7 +36,7 @@ void sendTTYP(u16 protocol, u8 source, char *data){ ((DECI2_TTYP_HEADER*)tmp)->h.destination='H'; ((DECI2_TTYP_HEADER*)tmp)->flushreq =0; if (((DECI2_TTYP_HEADER*)tmp)->h.length>2048) - Console::Alert("TTYP: Buffer overflow"); + Msgbox::Alert("TTYP: Buffer overflow"); else memcpy(&tmp[sizeof(DECI2_TTYP_HEADER)], data, strlen(data)); //writeData(tmp); diff --git a/pcsx2/SaveState.cpp b/pcsx2/SaveState.cpp index 1f64700662..c0f0193851 100644 --- a/pcsx2/SaveState.cpp +++ b/pcsx2/SaveState.cpp @@ -66,17 +66,24 @@ static void PostLoadPrep() for(int i=0; i<48; i++) MapTLB(i); } -void SaveState::GetFilename( char* dest, int slot ) +void SaveState::GetFilename( string& dest, int slot ) { - char elfcrcText[72]; - sprintf( elfcrcText, "%8.8X.%3.3d", ElfCRC, slot ); - CombinePaths( dest, SSTATES_DIR, elfcrcText ); + string elfcrcText; + ssprintf( elfcrcText, "%8.8X.%3.3d", params ElfCRC, slot ); + Path::Combine( dest, SSTATES_DIR, elfcrcText ); } -SaveState::SaveState( const char* msg, const char* destination ) : - m_version( g_SaveVersion ) +string SaveState::GetFilename( int slot ) { - Console::WriteLn( "%s %s", msg, destination ); + string elfcrcText, dest; + GetFilename( dest, slot ); + return dest; +} + + +SaveState::SaveState( const char* msg, const string& destination ) : m_version( g_SaveVersion ) +{ + Console::WriteLn( "%s %S", params msg, &destination ); } void SaveState::FreezeAll() @@ -145,10 +152,22 @@ void SaveState::FreezeAll() PostLoadPrep(); } +// this function is yet incomplete. Version numbers hare still < 12 so it won't be run. +// (which is good because it won't work :P) +void SaveState::_testCdvdCrc() +{ + /*if( GetVersion() < 0x0012 ) return; + + u32 thiscrc = ElfCRC; + Freeze( thiscrc ); + if( thiscrc != ElfCRC ) + throw Exception::StateCrcMismatch( thiscrc, ElfCRC );*/ +} + ///////////////////////////////////////////////////////////////////////////// // gzipped to/from disk state saves implementation -gzBaseStateInfo::gzBaseStateInfo( const char* msg, const char* filename ) : +gzBaseStateInfo::gzBaseStateInfo( const char* msg, const string& filename ) : SaveState( msg, filename ) , m_filename( filename ) , m_file( NULL ) @@ -165,10 +184,10 @@ gzBaseStateInfo::~gzBaseStateInfo() } -gzSavingState::gzSavingState( const char* filename ) : +gzSavingState::gzSavingState( const string& filename ) : gzBaseStateInfo( _("Saving state to: "), filename ) { - m_file = gzopen(filename, "wb"); + m_file = gzopen(filename.c_str(), "wb"); if( m_file == NULL ) throw Exception::FileNotFound(); @@ -176,10 +195,10 @@ gzSavingState::gzSavingState( const char* filename ) : } -gzLoadingState::gzLoadingState( const char* filename ) : +gzLoadingState::gzLoadingState( const string& filename ) : gzBaseStateInfo( _("Loading state from: "), filename ) { - m_file = gzopen(filename, "rb"); + m_file = gzopen(filename.c_str(), "rb"); if( m_file == NULL ) throw Exception::FileNotFound(); @@ -190,28 +209,23 @@ gzLoadingState::gzLoadingState( const char* filename ) : #ifdef PCSX2_VIRTUAL_MEM if( m_version >= 0x8b400000 ) { - Console::Error( - "Savestate load aborted:\n" - "\tVM edition cannot safely load savestates created by the VTLB edition." - ); - throw Exception::UnsupportedStateVersion(); + throw Exception::UnsupportedStateVersion( m_version, "VM edition cannot safely load savestates created by the VTLB edition." ); } // pcsx2 vm supports opening these formats if( m_version < 0x7a30000d ) - { - Console::WriteLn( "Unsupported or unrecognized savestate version: %x.", m_version ); - throw Exception::UnsupportedStateVersion(); - } + throw Exception::UnsupportedStateVersion( m_version ); #else if( ( m_version >> 16 ) == 0x7a30 ) { Console::Error( "Savestate load aborted:\n" "\tVTLB edition cannot safely load savestates created by the VM edition." ); - throw Exception::UnsupportedStateVersion(); + throw Exception::UnsupportedStateVersion( m_version ); } #endif } + + _testCdvdCrc(); } gzLoadingState::~gzLoadingState() { } @@ -231,7 +245,7 @@ void gzLoadingState::FreezeMem( void* data, int size ) void gzSavingState::FreezePlugin( const char* name, s32 (CALLBACK *freezer)(int mode, freezeData *data) ) { - Console::WriteLn( "\tSaving %s", name ); + Console::WriteLn( "\tSaving %s", params name ); freezeData fP = { 0, NULL }; if (freezer(FREEZE_SIZE, &fP) == -1) @@ -257,7 +271,7 @@ void gzSavingState::FreezePlugin( const char* name, s32 (CALLBACK *freezer)(int void gzLoadingState::FreezePlugin( const char* name, s32 (CALLBACK *freezer)(int mode, freezeData *data) ) { freezeData fP = { 0, NULL }; - Console::WriteLn( "\tLoading %s", name ); + Console::WriteLn( "\tLoading %s", params name ); gzread(m_file, &fP.size, sizeof(fP.size)); if( fP.size == 0 ) return; @@ -326,7 +340,7 @@ void memLoadingState::FreezeMem( void* data, int size ) void memSavingState::FreezePlugin( const char* name, s32 (CALLBACK *freezer)(int mode, freezeData *data) ) { freezeData fP = { 0, NULL }; - Console::WriteLn( "\tSaving %s", name ); + Console::WriteLn( "\tSaving %s", params name ); if( freezer(FREEZE_SIZE, &fP) == -1 ) throw Exception::FreezePluginFailure( name, "saving" ); @@ -347,7 +361,7 @@ void memSavingState::FreezePlugin( const char* name, s32 (CALLBACK *freezer)(int void memLoadingState::FreezePlugin( const char* name, s32 (CALLBACK *freezer)(int mode, freezeData *data) ) { freezeData fP; - Console::WriteLn( "\tLoading %s", name ); + Console::WriteLn( "\tLoading %s", params name ); Freeze( fP.size ); if( fP.size == 0 ) return; diff --git a/pcsx2/SaveState.h b/pcsx2/SaveState.h index 0b169f2577..ee8315b346 100644 --- a/pcsx2/SaveState.h +++ b/pcsx2/SaveState.h @@ -45,10 +45,11 @@ protected: u32 m_version; // version of the savestate being loaded. public: - SaveState( const char* msg, const char* destination ); + SaveState( const char* msg, const string& destination ); virtual ~SaveState() { } - static void GetFilename( char* dest, int slot ); + static void GetFilename( string& dest, int slot ); + static string GetFilename( int slot ); // Gets the version of savestate that this object is acting on. // The version refers to the low 16 bits only (high 16 bits classifies Pcsx2 build types) @@ -75,7 +76,7 @@ public: FreezeMem( &data, sizeof( T ) ); } - // FreezeLEgacy can be used to load structures short of their full size, which is + // FreezeLegacy can be used to load structures short of their full size, which is // useful for loading structures that have had new stuff added since a previous version. template void FreezeLegacy( T& data, int sizeOfNewStuff ) @@ -84,7 +85,7 @@ public: } // Loads or saves a plugin. Plugin name is for console logging purposes. - virtual void FreezePlugin( const char* name,s32(CALLBACK* freezer)(int mode, freezeData *data) )=0; + virtual void FreezePlugin( const char* name, s32 (CALLBACK* freezer)(int mode, freezeData *data) )=0; // Loads or saves a memory block. virtual void FreezeMem( void* data, int size )=0; @@ -98,10 +99,15 @@ public: // note: gsFreeze() needs to be public because of the GSState recorder. public: - void gsFreeze(); + virtual void gsFreeze(); protected: + // Used internally by constructors to check the cdvd's crc against the CRC of the savestate. + // This allows for proper exception handling of changed CDs on-the-fly. + void _testCdvdCrc(); + + // Load/Save functions for the various components of our glorious emulator! void rcntFreeze(); @@ -129,11 +135,11 @@ protected: class gzBaseStateInfo : public SaveState { protected: - const char* m_filename; + const string m_filename; gzFile m_file; // used for reading/writing disk saves public: - gzBaseStateInfo( const char* msg, const char* filename ); + gzBaseStateInfo( const char* msg, const string& filename ); virtual ~gzBaseStateInfo(); }; @@ -142,7 +148,7 @@ class gzSavingState : public gzBaseStateInfo { public: virtual ~gzSavingState() {} - gzSavingState( const char* filename ) ; + gzSavingState( const string& filename ) ; void FreezePlugin( const char* name, s32(CALLBACK *freezer)(int mode, freezeData *data) ); void FreezeMem( void* data, int size ); bool IsSaving() const { return true; } @@ -152,7 +158,7 @@ class gzLoadingState : public gzBaseStateInfo { public: virtual ~gzLoadingState(); - gzLoadingState( const char* filename ); + gzLoadingState( const string& filename ); void FreezePlugin( const char* name, s32(CALLBACK *freezer)(int mode, freezeData *data) ); void FreezeMem( void* data, int size ); diff --git a/pcsx2/Sio.cpp b/pcsx2/Sio.cpp index aec7624286..4de85b6601 100644 --- a/pcsx2/Sio.cpp +++ b/pcsx2/Sio.cpp @@ -544,7 +544,7 @@ FILE *LoadMcd(int mcd) { f = fopen(str, "r+b"); } if (f == NULL) { - Console::Alert("Failed loading MemCard %s", str); + Msgbox::Alert("Failed loading MemCard %s", params str); return NULL; } diff --git a/pcsx2/SourceLog.cpp b/pcsx2/SourceLog.cpp index 6361f141d6..8166f09c12 100644 --- a/pcsx2/SourceLog.cpp +++ b/pcsx2/SourceLog.cpp @@ -59,13 +59,13 @@ void __Log( const char* fmt, ... ) assert( length <= 2020 ); if( length > 2020 ) { - Console::Alert("Source Log Stack Corruption Detected. Program execution may become unstable."); + Msgbox::Alert("Source Log Stack Corruption Detected. Program execution may become unstable."); // fixme: should throw an exception here once we have proper exception handling implemented. } if (varLog & 0x80000000) // log to console enabled? { - Console::Msg(tmp); + Console::Write(tmp); } else if( emuLog != NULL ) // manually write to the logfile. { @@ -86,7 +86,7 @@ static __forceinline void _vSourceLog( u16 protocol, u8 source, u32 cpuPc, u32 c assert( length <= 2020 ); if( length > 2020 ) { - Console::Alert("Source Log Stack Corruption Detected. Program execution may become unstable."); + Msgbox::Alert("Source Log Stack Corruption Detected. Program execution may become unstable."); // fixme: should throw an exception here once we have proper exception handling implemented. } @@ -102,7 +102,7 @@ static __forceinline void _vSourceLog( u16 protocol, u8 source, u32 cpuPc, u32 c if (varLog & 0x80000000) // log to console enabled? { - Console::MsgLn(tmp); + Console::WriteLn(tmp); } else if( emuLog != NULL ) // manually write to the logfile. { diff --git a/pcsx2/StringUtils.cpp b/pcsx2/StringUtils.cpp new file mode 100644 index 0000000000..2cf391eced --- /dev/null +++ b/pcsx2/StringUtils.cpp @@ -0,0 +1,68 @@ +void/* Pcsx2 - Pc Ps2 Emulator + * Copyright (C) 2002-2008 Pcsx2 Team + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#include "PrecompiledHeader.h" +#include "System.h" + +using namespace std; + +void _format_vstring( string& dest, const char* format, va_list args ) +{ + int writtenCount; + int newSize = strlen(format) * 2; + char *buf; + + while( true ) + { + buf = new char[newSize + 1]; + + // note! vsnprintf doesn't always return consistent results on GCC. + // We can't assume it returns -1; + writtenCount = vsnprintf(buf, newSize, format, args); + + if (writtenCount >= newSize) + writtenCount = -1; + else if( writtenCount != -1 ) break; + + // Gotta try again -_- + newSize += newSize / 2; + delete[] buf; + } + + buf[writtenCount] = '\0'; + out = buf; + delete[] buf; +} + +string format_string( const char* format, ... ) +{ + string joe; + va_list args; + va_start(args, format); + _format_vstring( joe, format, args ); + va_end(args); + return joe; +} + +void format_string( string& dest, const char* format, ... ) +{ + va_list args; + va_start(args, format); + _format_vstring( dest, format, args ); + va_end(args); +} diff --git a/pcsx2/StringUtils.h b/pcsx2/StringUtils.h new file mode 100644 index 0000000000..616b47e136 --- /dev/null +++ b/pcsx2/StringUtils.h @@ -0,0 +1,57 @@ +/* Pcsx2 - Pc Ps2 Emulator + * Copyright (C) 2002-2008 Pcsx2 Team + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#ifndef _PCSX2_STRINGUTILS_H_ +#define _PCSX2_STRINGUTILS_H_ + +#include +#include + +// to_string: A utility template for quick and easy inline string type conversion. +// Use to_string(intval), or to_string(float), etc. Anything that the STL itself +// would support should be supported here. :) +template< typename T > +std::string to_string(const T& value) +{ + std::ostringstream oss; + oss << value; + return oss.str(); +} + +// when the dummy assert fails, it usually means you forgot to use the params macro. + +#ifdef PCSX2_DEVBUILD +#define params va_arg_dummy, +#define dummy_assert() // jASSUME( dummy == &va_arg_dummy ); +#else +#define params va_arg_dummy, // use null in release -- faster! +#define dummy_assert() // jASSUME( dummy == 0 ); +#endif + +// dummy structure used to type-guard the dummy parameter that's been inserted to +// allow us to use the va_list feature on references. +struct VARG_PARAM +{ +}; + +extern VARG_PARAM va_arg_dummy; + +extern void ssprintf(std::string& dest, const std::string& fmt, VARG_PARAM dummy, ...); +extern void vssprintf(std::string& dest, const std::string& format, va_list args); +extern std::string fmt_string( const std::string& fmt, VARG_PARAM dummy, ... ); +#endif diff --git a/pcsx2/System.cpp b/pcsx2/System.cpp index 3228419134..eb17bc9040 100644 --- a/pcsx2/System.cpp +++ b/pcsx2/System.cpp @@ -29,6 +29,10 @@ using namespace Console; bool sysInitialized = false; +namespace Exception +{ + BaseException::~BaseException() {} +} // I can't believe I had to make my own version of trim. C++'s STL is totally whack. // And I still had to fix it too. I found three samples of trim online and *all* three @@ -86,10 +90,10 @@ void SysDetect() sysInitialized = true; Notice("PCSX2 " PCSX2_VERSION " - compiled on " __DATE__ ); - Notice("Savestate version: %x", g_SaveVersion); + Notice("Savestate version: %x", params g_SaveVersion); // fixme: what's the point of this line? Anything? Or just to look "cool"? (air) - DevCon::Notice("EE pc offset: 0x%x, IOP pc offset: 0x%x", (u32)&cpuRegs.pc - (u32)&cpuRegs, (u32)&psxRegs.pc - (u32)&psxRegs); + DevCon::Notice( "EE pc offset: 0x%x, IOP pc offset: 0x%x", params (u32)&cpuRegs.pc - (u32)&cpuRegs, (u32)&psxRegs.pc - (u32)&psxRegs ); cpudetectInit(); @@ -98,7 +102,7 @@ void SysDetect() SetColor( Console::Color_White ); - MsgLn( "x86Init:" ); + WriteLn( "x86Init:" ); WriteLn( "\tCPU vendor name = %s\n" "\tFamilyID = %x\n" @@ -107,21 +111,21 @@ void SysDetect() "\tCores = %d physical [%d logical]\n" "\tx86PType = %s\n" "\tx86Flags = %8.8x %8.8x\n" - "\tx86EFlags = %8.8x\n", - cpuinfo.x86ID, cpuinfo.x86StepID, family.c_str(), + "\tx86EFlags = %8.8x\n", params + cpuinfo.x86ID, cpuinfo.x86StepID, family.c_str(), cpuinfo.cpuspeed / 1000, cpuinfo.cpuspeed%1000, cpuinfo.PhysicalCores, cpuinfo.LogicalCores, cpuinfo.x86Type, cpuinfo.x86Flags, cpuinfo.x86Flags2, cpuinfo.x86EFlags ); - MsgLn( "Features:" ); + WriteLn( "Features:" ); WriteLn( "\t%sDetected MMX\n" "\t%sDetected SSE\n" "\t%sDetected SSE2\n" "\t%sDetected SSE3\n" - "\t%sDetected SSE4.1\n", + "\t%sDetected SSE4.1\n", params cpucaps.hasMultimediaExtensions ? "" : "Not ", cpucaps.hasStreamingSIMDExtensions ? "" : "Not ", cpucaps.hasStreamingSIMD2Extensions ? "" : "Not ", @@ -131,11 +135,11 @@ void SysDetect() if ( cpuinfo.x86ID[0] == 'A' ) //AMD cpu { - MsgLn( " Extended AMD Features:" ); + WriteLn( " Extended AMD Features:" ); WriteLn( "\t%sDetected MMX2\n" "\t%sDetected 3DNOW\n" - "\t%sDetected 3DNOW2\n", + "\t%sDetected 3DNOW2\n", params cpucaps.hasMultimediaExtensionsExt ? "" : "Not ", cpucaps.has3DNOWInstructionExtensions ? "" : "Not ", cpucaps.has3DNOWInstructionExtensionsExt ? "" : "Not " diff --git a/pcsx2/System.h b/pcsx2/System.h index abaa4402e6..216e7969f8 100644 --- a/pcsx2/System.h +++ b/pcsx2/System.h @@ -34,10 +34,6 @@ void *SysLoadSym(void *lib, const char *sym); // Loads Symbol from Library const char *SysLibError(); // Gets previous error loading sysbols void SysCloseLibrary(void *lib); // Closes Library -// Causes a pop-up to appear with the specified message. Use this to issue -// critical or fatal messages to the user. -void SysMessage(const char *fmt, ...); - // Maps a block of memory for use as a recompiled code buffer. // The allocated block has code execution privliges. // Returns NULL on allocation failure. @@ -56,17 +52,6 @@ static __forceinline void SysMunmap( void* base, u32 size ) SysMunmap( (uptr)base, size ); } -// to_string: A utility template for quick and easy inline string type conversion. -// Use to_string(intval), or to_string(float), etc. Anything that the STL itself -// would support should be supported here. :) -template< typename T > -std::string to_string(const T& value) -{ - std::ostringstream oss; - oss << value; - return oss.str(); -} - // Console Namespace -- Replacements for SysPrintf. // SysPrintf is depreciated -- We should phase these in over time. namespace Console @@ -83,9 +68,12 @@ namespace Console Color_White }; + // va_args version of WriteLn, mostly for internal use only. + extern void __fastcall _WriteLn( Colors color, const std::string& fmt, va_list args ); + extern void Open(); extern void Close(); - extern void SetTitle( const char* title ); + extern void SetTitle( const std::string& title ); // Changes the active console color. // This color will be unset by calls to colored text methods @@ -103,45 +91,61 @@ namespace Console // Writes an unformatted string of text to the console (fast!) // No newline is appended. - extern bool __fastcall Msg( const char* fmt ); + extern bool __fastcall Write( const std::string& fmt ); // Writes an unformatted string of text to the console (fast!) // A newline is automatically appended. - extern bool __fastcall MsgLn( const char* fmt ); + extern bool __fastcall WriteLn( const std::string& fmt ); // Writes an unformatted string of text to the console (fast!) // A newline is automatically appended, and the console color reset to default. - extern bool __fastcall MsgLn( Colors color, const char* fmt ); + extern bool __fastcall WriteLn( Colors color, const std::string& fmt ); // Writes a line of colored text to the console, with automatic newline appendage. // The console color is reset to default when the operation is complete. - extern bool WriteLn( Colors color, const char* fmt, ... ); + extern bool WriteLn( Colors color, const std::string& fmt, VARG_PARAM dummy, ... ); // Writes a line of colored text to the console (no newline). // The console color is reset to default when the operation is complete. - extern bool Write( Colors color, const char* fmt, ... ); + extern bool Write( Colors color, const std::string& fmt, VARG_PARAM dummy, ... ); + extern bool Write( Colors color, const std::string& fmt ); // Writes a formatted message to the console (no newline) - extern bool Write( const char* fmt, ... ); + extern bool Write( const std::string& fmt, VARG_PARAM dummy, ... ); // Writes a formatted message to the console, with appended newline. - extern bool WriteLn( const char* fmt, ... ); + extern bool WriteLn( const std::string& fmt, VARG_PARAM dummy, ... ); // Displays a message in the console with red emphasis. // Newline is automatically appended. - extern bool Error( const char* fmt, ... ); + extern bool Error( const std::string& fmt, VARG_PARAM dummy, ... ); + extern bool Error( const std::string& fmt ); // Displays a message in the console with yellow emphasis. // Newline is automatically appended. - extern bool Notice( const char* fmt, ... ); + extern bool Notice( const std::string& fmt, VARG_PARAM dummy, ... ); + extern bool Notice( const std::string& fmt ); // Displays a message in the console with yellow emphasis. // Newline is automatically appended. - extern bool Status( const char* fmt, ... ); - - // Pops up an alert Dialog Box. - // Replacement for SysMessage. - extern bool Alert( const char* fmt, ... ); + extern bool Status( const std::string& fmt, VARG_PARAM dummy, ... ); + extern bool Status( const std::string& fmt ); +} + +// Different types of message boxes that the emulator can employ from the friendly confines +// of it's blissful unawareness of whatever GUI it runs under. :) All message boxes exhibit +// blocking behavior -- they promt the user for action and only return after the user has +// responded to the prompt. +namespace Msgbox +{ + // Pops up an alert Dialog Box with a singular "OK" button. + // Always returns false. Replacement for SysMessage. + extern bool Alert( const std::string& fmt, VARG_PARAM dummy, ... ); + extern bool Alert( const std::string& fmt ); + + // Pops up a dialog box with Ok/Cancel buttons. Returns the result of the inquiry, + // true if OK, false if cancel. + extern bool OkCancel( const std::string& fmt, VARG_PARAM dummy, ... ); } using Console::Color_Red; @@ -187,29 +191,34 @@ using Console::Color_White; } ////////////////////////////////////////////////////////////// -// Consts for using if() statements instead of uglier #ifdef macros. +// Dev / Debug conditionals -- +// Consts for using if() statements instead of uglier #ifdef macros. +// Abbrivated macros for dev/debug only consoles and mesgboxes. #ifdef PCSX2_DEVBUILD # define DevCon Console -static const bool IsDevBuild = true; +# define DevMsg MsgBox + static const bool IsDevBuild = true; #else # define DevCon 0&&Console -static const bool IsDevBuild = false; +# define DevMsg + static const bool IsDevBuild = false; #endif #ifdef _DEBUG # define DbgCon Console -static const bool IsDebugBuild = true; + static const bool IsDebugBuild = true; #else # define DbgCon 0&&Console -static const bool IsDebugBuild = false; + static const bool IsDebugBuild = false; + #endif #ifdef PCSX2_VIRTUAL_MEM diff --git a/pcsx2/VU.h b/pcsx2/VU.h index ce59ac9ac0..d95d98bd45 100644 --- a/pcsx2/VU.h +++ b/pcsx2/VU.h @@ -137,6 +137,11 @@ struct VURegs { fdivPipe fdiv; efuPipe efu; + VURegs() : + Mem( NULL ) + , Micro( NULL ) + { + } }; #define VUPIPE_NONE 0 diff --git a/pcsx2/VU0micro.cpp b/pcsx2/VU0micro.cpp index 9b3cb0c006..c7ca93246f 100644 --- a/pcsx2/VU0micro.cpp +++ b/pcsx2/VU0micro.cpp @@ -75,11 +75,12 @@ int vu0Init() memLUT[0x11003].aPFNs = &s_psVuMem.aPFNs[0]; memLUT[0x11003].aVFNs = &s_psVuMem.aVFNs[0]; // since vuregisters are mapped in vumem0, go to diff addr, but mapping to same physical addr - VirtualFree((void*)0x11000000, 0x10000, MEM_RELEASE); // free just in case - VU0.Mem = (u8*)VirtualAlloc((void*)0x11000000, 0x10000, MEM_RESERVE|MEM_PHYSICAL, PAGE_READWRITE); + //VirtualFree((void*)0x11000000, 0x10000, MEM_RELEASE); // free just in case + if( VU0.Mem == NULL ) + VU0.Mem = (u8*)VirtualAlloc((void*)0x11000000, 0x10000, MEM_RESERVE|MEM_PHYSICAL, PAGE_READWRITE); if( VU0.Mem != (void*)0x11000000 ) { - Console::WriteLn("Failed to alloc vu0mem 0x11000000 %d", GetLastError()); + Console::WriteLn("Failed to alloc vu0mem 0x11000000 %d", params GetLastError()); return -1; } @@ -101,7 +102,7 @@ int vu0Init() // VU0.VF = (VECTOR*)_aligned_malloc(32*sizeof(VECTOR), 16); // VU0.VI = (REG_VI*)_aligned_malloc(32*sizeof(REG_VI), 16); // if (VU0.VF == NULL || VU0.VI == NULL) { -// Console::Alert("Error allocating memory"); +// Msgbox::Alert("Error allocating memory"); // return -1; // } @@ -129,10 +130,10 @@ void vu0Shutdown() #ifdef PCSX2_VIRTUAL_MEM if( !SysMapUserPhysicalPages(VU0.Mem, 16, NULL, 0) ) - Console::Error("Error releasing vu0 memory %d\n", GetLastError()); + Console::Error("Error releasing vu0 memory %d", params GetLastError()); if( VirtualFree(VU0.Mem, 0, MEM_RELEASE) == 0 ) - Console::Error("Error freeing vu0 memory %d\n", GetLastError()); + Console::Error("Error freeing vu0 memory %d", params GetLastError()); #else safe_aligned_free(VU0.Mem); safe_aligned_free(VU0.Micro); @@ -140,8 +141,6 @@ void vu0Shutdown() VU0.Mem = NULL; VU0.Micro = NULL; -// _aligned_free(VU0.VF); VU0.VF = NULL; -// _aligned_free(VU0.VI); VU0.VI = NULL; } void vu0ResetRegs() diff --git a/pcsx2/VU1micro.cpp b/pcsx2/VU1micro.cpp index 022c022ecb..561e360076 100644 --- a/pcsx2/VU1micro.cpp +++ b/pcsx2/VU1micro.cpp @@ -76,7 +76,7 @@ int vu1Init() VU1.Mem = (u8*)_aligned_malloc(16*1024, 16); VU1.Micro = (u8*)_aligned_malloc(16*1024, 16); if (VU1.Mem == NULL || VU1.Micro == NULL) { - Console::Alert("Error allocating memory"); + Msgbox::Alert("Error allocating memory"); return -1; } memset(VU1.Mem, 0,16*1024); diff --git a/pcsx2/vssprintf.cpp b/pcsx2/vssprintf.cpp new file mode 100644 index 0000000000..2c578f4a9e --- /dev/null +++ b/pcsx2/vssprintf.cpp @@ -0,0 +1,725 @@ +// +// Code base on: vsprintf.c +// +// Print formatting routines +// +// Copyright (C) 2002 Michael Ringgaard. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// 3. Neither the name of the project nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +// SUCH DAMAGE. +// + +// modified by gigahers and air to write formatted output directly into a std::string container. + +#include "PrecompiledHeader.h" + +#include + +#ifdef KERNEL +#define NOFLOAT +#endif + +#define ZEROPAD 1 // Pad with zero (not to be confused with Zero's PAD plugin) +#define SIGN 2 // Unsigned/signed long +#define PLUS 4 // Show plus +#define SPACE 8 // Space if plus +#define LEFT 16 // Left justified +#define SPECIAL 32 // 0x +#define LARGE 64 // Use 'ABCDEF' instead of 'abcdef' + +#define is_digit(c) ((c) >= '0' && (c) <= '9') + +static char *digits = "0123456789abcdefghijklmnopqrstuvwxyz"; +static char *upper_digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +#ifdef NEED_STRLEN +static size_t strnlen(const char *s, size_t count) +{ + const char *sc; + for (sc = s; *sc != '\0' && count--; ++sc); + return sc - s; +} +#endif + +static void cvt(char (&buf)[_CVTBUFSIZE], double arg, int preci, int& decpt, int& sign, int eflag) +{ + int r2; + double fi, fj; + char *p, *p1; + + r2 = 0; + sign = 0; + p = &buf[0]; + if (arg < 0) + { + sign = 1; + arg = -arg; + } + arg = modf(arg, &fi); + p1 = &buf[_CVTBUFSIZE]; + + if (fi != 0) + { + while (fi != 0) + { + fj = modf(fi / 10, &fi); + *--p1 = (int)((fj + .03) * 10) + '0'; + r2++; + } + while (p1 < &buf[_CVTBUFSIZE]) *p++ = *p1++; + } + else if (arg > 0) + { + while ((fj = arg * 10) < 1) + { + arg = fj; + r2--; + } + } + + p1 = &buf[preci]; + + if (eflag == 0) p1 += r2; + decpt = r2; + if (p1 < &buf[0]) + { + buf[0] = '\0'; + return; + } + while (p <= p1 && p < &buf[_CVTBUFSIZE]) + { + arg *= 10; + arg = modf(arg, &fj); + *p++ = (int) fj + '0'; + } + if (p1 >= &buf[_CVTBUFSIZE]) + { + buf[_CVTBUFSIZE - 1] = '\0'; + return; + } + p = p1; + *p1 += 5; + while (*p1 > '9') + { + *p1 = '0'; + if (p1 > buf) + ++*--p1; + else + { + *p1 = '1'; + decpt++; + if (eflag == 0) + { + if (p > buf) *p = '0'; + p++; + } + } + } + *p = '\0'; + return; +} + +static void ecvtbuf(char (&buf)[_CVTBUFSIZE], double arg, int preci, int& decpt, int& sign) +{ + cvt(buf, arg, preci, decpt, sign, 1); +} + +static void fcvtbuf(char (&buf)[_CVTBUFSIZE], double arg, int preci, int& decpt, int& sign) +{ + cvt(buf, arg, preci, decpt, sign, 0); +} + +static int skip_atoi(const char **s) +{ + int i = 0; + while (is_digit(**s)) i = i*10 + *((*s)++) - '0'; + return i; +} + +static void number(std::string& dest, long num, int base, int size, int precision, int type) +{ + char c, sign, tmp[66]; + char *dig = digits; + int i; + + if (type & LARGE) dig = upper_digits; + if (type & LEFT) type &= ~ZEROPAD; + if (base < 2 || base > 36) return; + + c = (type & ZEROPAD) ? '0' : ' '; + sign = 0; + if (type & SIGN) + { + if (num < 0) + { + sign = '-'; + num = -num; + size--; + } + else if (type & PLUS) + { + sign = '+'; + size--; + } + else if (type & SPACE) + { + sign = ' '; + size--; + } + } + + if (type & SPECIAL) + { + if (base == 16) + size -= 2; + else if (base == 8) + size--; + } + + i = 0; + + if (num == 0) + tmp[i++] = '0'; + else + { + while (num != 0) + { + tmp[i++] = dig[((unsigned long) num) % (unsigned) base]; + num = ((unsigned long) num) / (unsigned) base; + } + } + + if (i > precision) precision = i; + size -= precision; + if (!(type & (ZEROPAD | LEFT))) while (size-- > 0) dest += ' '; + if (sign) dest += sign; + + if (type & SPECIAL) + { + if (base == 8) + dest += '0'; + else if (base == 16) + { + dest += '0'; + dest += digits[33]; + } + } + + if (!(type & LEFT)) while (size-- > 0) dest += c; + while (i < precision--) dest += '0'; + while (i-- > 0) dest += tmp[i]; + while (size-- > 0) dest += ' '; +} + +static void eaddr( std::string& dest, unsigned char *addr, int size, int precision, int type) +{ + char tmp[24]; + char *dig = digits; + int i, len; + + if (type & LARGE) dig = upper_digits; + len = 0; + for (i = 0; i < 6; i++) + { + if (i != 0) tmp[len++] = ':'; + tmp[len++] = dig[addr[i] >> 4]; + tmp[len++] = dig[addr[i] & 0x0F]; + } + + if (!(type & LEFT)) while (len < size--) dest += ' '; + for (i = 0; i < len; ++i) dest += tmp[i]; + while (len < size--) dest += ' '; +} + +static void iaddr( std::string& dest, unsigned char *addr, int size, int precision, int type) +{ + char tmp[24]; + int i, n, len; + + len = 0; + for (i = 0; i < 4; i++) + { + if (i != 0) tmp[len++] = '.'; + n = addr[i]; + + if (n == 0) + tmp[len++] = digits[0]; + else + { + if (n >= 100) + { + tmp[len++] = digits[n / 100]; + n = n % 100; + tmp[len++] = digits[n / 10]; + n = n % 10; + } + else if (n >= 10) + { + tmp[len++] = digits[n / 10]; + n = n % 10; + } + + tmp[len++] = digits[n]; + } + } + + if (!(type & LEFT)) while (len < size--) dest += ' '; + for (i = 0; i < len; ++i) dest += tmp[i]; + while (len < size--) dest += ' '; +} + +#ifndef NOFLOAT + +static void cfltcvt(double value, char *buffer, char fmt, int precision) +{ + int decpt, sign, exp, pos; + char cvtbuf[_CVTBUFSIZE]; + int capexp = 0; + int magnitude; + + if (fmt == 'G' || fmt == 'E') + { + capexp = 1; + fmt += 'a' - 'A'; + } + + if (fmt == 'g') + { + ecvtbuf(cvtbuf, value, precision, decpt, sign); + + magnitude = decpt - 1; + if (magnitude < -4 || magnitude > precision - 1) + { + fmt = 'e'; + precision -= 1; + } + else + { + fmt = 'f'; + precision -= decpt; + } + } + + if (fmt == 'e') + { + ecvtbuf(cvtbuf, value, precision+1, decpt, sign); + + const char* digits = cvtbuf; + + if (sign) *buffer++ = '-'; + *buffer++ = *digits; + if (precision > 0) *buffer++ = '.'; + memcpy(buffer, digits + 1, precision); + buffer += precision; + *buffer++ = capexp ? 'E' : 'e'; + + if (decpt == 0) + { + if (value == 0.0) + exp = 0; + else + exp = -1; + } + else + exp = decpt - 1; + + if (exp < 0) + { + *buffer++ = '-'; + exp = -exp; + } + else + *buffer++ = '+'; + + buffer[2] = (exp % 10) + '0'; + exp = exp / 10; + buffer[1] = (exp % 10) + '0'; + exp = exp / 10; + buffer[0] = (exp % 10) + '0'; + buffer += 3; + } + else if (fmt == 'f') + { + fcvtbuf(cvtbuf, value, precision, decpt, sign); + + const char* digits = cvtbuf; + + if (sign) *buffer++ = '-'; + if (*digits) + { + if (decpt <= 0) + { + *buffer++ = '0'; + *buffer++ = '.'; + for (pos = 0; pos < -decpt; pos++) *buffer++ = '0'; + while (*digits) *buffer++ = *digits++; + } + else + { + pos = 0; + while (*digits) + { + if (pos++ == decpt) *buffer++ = '.'; + *buffer++ = *digits++; + } + } + } + else + { + *buffer++ = '0'; + if (precision > 0) + { + *buffer++ = '.'; + for (pos = 0; pos < precision; pos++) *buffer++ = '0'; + } + } + } + + *buffer = '\0'; +} + +static void forcdecpt(char *buffer) +{ + while (*buffer) + { + if (*buffer == '.') return; + if (*buffer == 'e' || *buffer == 'E') break; + buffer++; + } + + if (*buffer) + { + int n = strlen(buffer); + while (n > 0) + { + buffer[n + 1] = buffer[n]; + n--; + } + + *buffer = '.'; + } + else + { + *buffer++ = '.'; + *buffer = '\0'; + } +} + +static void cropzeros(char *buffer) +{ + char *stop; + + while (*buffer && *buffer != '.') buffer++; + if (*buffer++) + { + while (*buffer && *buffer != 'e' && *buffer != 'E') buffer++; + stop = buffer--; + while (*buffer == '0') buffer--; + if (*buffer == '.') buffer--; + while (*++buffer = *stop++); + } +} + +static void flt( std::string& dest, double num, int size, int precision, char fmt, int flags) +{ + char tmp[80]; + char c, sign; + int n, i; + + // Left align means no zero padding + if (flags & LEFT) flags &= ~ZEROPAD; + + // Determine padding and sign char + c = (flags & ZEROPAD) ? '0' : ' '; + sign = 0; + if (flags & SIGN) + { + if (num < 0.0) + { + sign = '-'; + num = -num; + size--; + } + else if (flags & PLUS) + { + sign = '+'; + size--; + } + else if (flags & SPACE) + { + sign = ' '; + size--; + } + } + + // Compute the precision value + if (precision < 0) + precision = 6; // Default precision: 6 + else if (precision == 0 && fmt == 'g') + precision = 1; // ANSI specified + + // Convert floating point number to text + cfltcvt(num, tmp, fmt, precision); + + // '#' and precision == 0 means force a decimal point + if ((flags & SPECIAL) && precision == 0) forcdecpt(tmp); + + // 'g' format means crop zero unless '#' given + if (fmt == 'g' && !(flags & SPECIAL)) cropzeros(tmp); + + n = strlen(tmp); + + // Output number with alignment and padding + size -= n; + if (!(flags & (ZEROPAD | LEFT))) while (size-- > 0) dest += ' '; + if (sign) dest += sign; + if (!(flags & LEFT)) while (size-- > 0) dest += c; + for (i = 0; i < n; i++) dest += tmp[i]; + while (size-- > 0) dest += ' '; +} + +#endif + +void vssprintf(std::string& dest, const std::string& format, va_list args) +{ + int len; + unsigned long num; + int i, base; + + int flags; // Flags to number() + + int field_width; // Width of output field + int precision; // Min. # of digits for integers; max number of chars for from string + int qualifier; // 'h', 'l', or 'L' for integer fields + + dest.clear(); + + for( const char* fmt = format.c_str(); *fmt; fmt++ ) + { + if (*fmt != '%') + { + dest += *fmt; + continue; + } + + // Process flags + flags = 0; +repeat: + fmt++; // This also skips first '%' + switch (*fmt) + { + case '-': flags |= LEFT; goto repeat; + case '+': flags |= PLUS; goto repeat; + case ' ': flags |= SPACE; goto repeat; + case '#': flags |= SPECIAL; goto repeat; + case '0': flags |= ZEROPAD; goto repeat; + } + + // Get field width + field_width = -1; + if (is_digit(*fmt)) + field_width = skip_atoi(&fmt); + else if (*fmt == '*') + { + fmt++; + field_width = va_arg(args, int); + if (field_width < 0) + { + field_width = -field_width; + flags |= LEFT; + } + } + + // Get the precision + precision = -1; + if (*fmt == '.') + { + ++fmt; + if (is_digit(*fmt)) + precision = skip_atoi(&fmt); + else if (*fmt == '*') + { + ++fmt; + precision = va_arg(args, int); + } + if (precision < 0) precision = 0; + } + + // Get the conversion qualifier + qualifier = -1; + if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L') + { + qualifier = *fmt; + fmt++; + } + + // Default base + base = 10; + + switch (*fmt) + { + case 'c': + if (!(flags & LEFT)) while (--field_width > 0) dest += ' '; + dest += (unsigned char) va_arg(args, int); + while (--field_width > 0) dest += ' '; + continue; + + case 's': + { + const char* s = va_arg(args, char *); + if (!s) s = ""; + len = strnlen(s, precision); + if (!(flags & LEFT)) while (len < field_width--) dest += ' '; + for (i = 0; i < len; ++i) dest += *s++; + while (len < field_width--) dest += ' '; + } + continue; + + // let's add support for std:string as a formatted parameter! (air) + case 'S': + { + std::string* ss = va_arg(args, std::string*); + const char* s = ( ss!=NULL ) ? ss->c_str() : ""; + len = strnlen(s, precision); + if (!(flags & LEFT)) while (len < field_width--) dest += ' '; + for (i = 0; i < len; ++i) dest += *s++; + while (len < field_width--) dest += ' '; + } + continue; + + case 'p': + { + if (field_width == -1) + { + field_width = 2 * sizeof(void *); + flags |= ZEROPAD; + } + number(dest, (unsigned long) va_arg(args, void *), 16, field_width, precision, flags); + } + continue; + + case 'n': + if (qualifier == 'l') + { + long *ip = va_arg(args, long *); + *ip = dest.length(); + } + else + { + int *ip = va_arg(args, int *); + *ip = dest.length(); + } + continue; + + case 'A': + flags |= LARGE; + + case 'a': + if (qualifier == 'l') + eaddr(dest, va_arg(args, unsigned char *), field_width, precision, flags); + else + iaddr(dest, va_arg(args, unsigned char *), field_width, precision, flags); + continue; + + // Integer number formats - set up the flags and "break" + case 'o': + base = 8; + break; + + case 'X': + flags |= LARGE; + + case 'x': + base = 16; + break; + + case 'd': + case 'i': + flags |= SIGN; + + case 'u': + break; + +#ifndef NOFLOAT + + case 'E': + case 'G': + case 'e': + case 'f': + case 'g': + flt(dest, va_arg(args, double), field_width, precision, *fmt, flags | SIGN); + continue; + +#endif + + default: + if (*fmt != '%') dest += '%'; + if (*fmt) + dest += *fmt; + else + --fmt; + continue; + } + + if (qualifier == 'l') + num = va_arg(args, unsigned long); + else if (qualifier == 'h') + { + if (flags & SIGN) + num = va_arg(args, short); + else + num = va_arg(args, unsigned short); + } + else if (flags & SIGN) + num = va_arg(args, int); + else + num = va_arg(args, unsigned int); + + number(dest, num, base, field_width, precision, flags); + } +} + +void ssprintf(std::string& str, const std::string& fmt, VARG_PARAM dummy, ...) +{ + dummy_assert(); + + va_list args; + va_start(args, dummy); + vssprintf(str, fmt, args); + va_end(args); +} + +std::string fmt_string( const std::string& fmt, VARG_PARAM dummy, ... ) +{ + dummy_assert(); + + std::string retval; + va_list args; + va_start( args, dummy ); + vssprintf( retval, fmt, args ); + va_end( args ); + + return retval; +} \ No newline at end of file diff --git a/pcsx2/windows/ConfigDlg.cpp b/pcsx2/windows/ConfigDlg.cpp index 64f5262be6..4c99d135fd 100644 --- a/pcsx2/windows/ConfigDlg.cpp +++ b/pcsx2/windows/ConfigDlg.cpp @@ -48,9 +48,9 @@ struct ComboInitializer , PS2E_GetLibName( NULL ) , PS2E_GetLibVersion2( NULL ) { - char tmpStr[g_MaxPath]; - CombinePaths(tmpStr, Config.PluginsDir, "*.dll"); - Find = FindFirstFile(tmpStr, &FindData); + string tmpStr; + Path::Combine( tmpStr, Config.PluginsDir, "*.dll" ); + Find = FindFirstFile(tmpStr.c_str(), &FindData); } ~ComboInitializer() @@ -66,10 +66,10 @@ struct ComboInitializer bool LoadNextLibrary() { - char tmpStr[g_MaxPath]; - CombinePaths( tmpStr, Config.PluginsDir, FindData.cFileName ); - Lib = LoadLibrary(tmpStr); - if (Lib == NULL) { Console::Error("%s: %s", tmpStr, SysLibError()); return false; } + string tmpStr; + Path::Combine( tmpStr, Config.PluginsDir, FindData.cFileName ); + Lib = LoadLibrary(tmpStr.c_str()); + if (Lib == NULL) { Console::Error( "%S: %s", params &tmpStr, SysLibError()); return false; } PS2E_GetLibType = (_PS2EgetLibType) GetProcAddress((HMODULE)Lib,"PS2EgetLibType"); PS2E_GetLibName = (_PS2EgetLibName) GetProcAddress((HMODULE)Lib,"PS2EgetLibName"); @@ -84,13 +84,13 @@ struct ComboInitializer void AddPlugin(HWND hwndCombo, const char* str) { - char tmpStr[g_MaxPath]; + string tmpStr; int i; - sprintf(tmpStr, "%s %d.%d.%d", PS2E_GetLibName(), (version>>8)&0xff, version&0xff, (version>>24)&0xff); + ssprintf(tmpStr, "%s %d.%d.%d", params PS2E_GetLibName(), (version>>8)&0xff, version&0xff, (version>>24)&0xff); char* lp = (char *)malloc(strlen(FindData.cFileName)+8); sprintf(lp, "%s", FindData.cFileName); - i = ComboBox_AddString(hwndCombo, tmpStr); + i = ComboBox_AddString(hwndCombo, tmpStr.c_str()); ComboBox_SetItemData(hwndCombo, i, lp); if (_stricmp(str, lp)==0) ComboBox_SetCurSel(hwndCombo, i); @@ -104,7 +104,7 @@ struct ComboInitializer if ( ((version >> 16)&0xff) == checkver ) return true; - Console::Notice("%s Plugin %s: Version %x != %x", typeStr, FindData.cFileName, 0xff&(version >> 16), checkver); + Console::Notice("%s Plugin %s: Version %x != %x", params typeStr, FindData.cFileName, 0xff&(version >> 16), checkver); } return false; } @@ -307,12 +307,12 @@ static void ConfPlugin( HWND hW, int confs, const char* name ) void *drv; void (*conf)(); char * pDLL = GetComboSel(hW, confs); - char file[g_MaxPath]; + string file; if(pDLL==NULL) return; - CombinePaths( file, Config.PluginsDir, pDLL ); + Path::Combine( file, Config.PluginsDir, pDLL ); - drv = SysLoadLibrary(file); + drv = SysLoadLibrary(file.c_str()); if (drv == NULL) return; conf = (void (*)()) SysLoadSym(drv, name); @@ -388,12 +388,12 @@ static void TestPlugin( HWND hW, int confs, const char* name ) int (*conf)(); int ret = 0; char * pDLL = GetComboSel(hW, confs); - char file[g_MaxPath]; + string file; if (pDLL== NULL) return; - CombinePaths( file, Config.PluginsDir, pDLL ); + Path::Combine( file, Config.PluginsDir, pDLL ); - drv = SysLoadLibrary(file); + drv = SysLoadLibrary(file.c_str()); if (drv == NULL) return; conf = (int (*)()) SysLoadSym(drv, name); @@ -401,9 +401,9 @@ static void TestPlugin( HWND hW, int confs, const char* name ) SysCloseLibrary(drv); if (ret == 0) - Console::Alert("This plugin reports that should work correctly"); + Msgbox::Alert("Success!\nThis plugin reports that should work correctly."); else - Console::Alert("This plugin reports that should not work correctly"); + Msgbox::Alert("Test Failed.\nThis plugin may not work correctly."); } void TestGS(HWND hW) { @@ -562,10 +562,13 @@ BOOL CALLBACK ConfigureDlgProc(HWND hW, UINT uMsg, WPARAM wParam, LPARAM lParam) } -BOOL Pcsx2Configure(HWND hWnd) { - return DialogBox(gApp.hInstance, - MAKEINTRESOURCE(IDD_CONFIG), - hWnd, - (DLGPROC)ConfigureDlgProc); +BOOL Pcsx2Configure(HWND hWnd) +{ + return DialogBox( + gApp.hInstance, + MAKEINTRESOURCE(IDD_CONFIG), + hWnd, + (DLGPROC)ConfigureDlgProc + ); } diff --git a/pcsx2/windows/Console.cpp b/pcsx2/windows/Console.cpp deleted file mode 100644 index 02e1757646..0000000000 --- a/pcsx2/windows/Console.cpp +++ /dev/null @@ -1,265 +0,0 @@ -/* Pcsx2 - Pc Ps2 Emulator - * Copyright (C) 2002-2008 Pcsx2 Team - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA - */ - -#include "PrecompiledHeader.h" - -#include "System.h" -#include "Debug.h" - -namespace Console -{ - static HANDLE hConsole = NULL; - - static const int tbl_color_codes[] = - { - 0 // black - , FOREGROUND_RED | FOREGROUND_INTENSITY - , FOREGROUND_GREEN | FOREGROUND_INTENSITY - , FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY - , FOREGROUND_BLUE | FOREGROUND_INTENSITY - , FOREGROUND_RED | FOREGROUND_BLUE - , FOREGROUND_GREEN | FOREGROUND_BLUE - , FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY - }; - - void SetTitle( const char* title ) - { - if( !hConsole || title==NULL ) return; - SetConsoleTitle( title ); - } - - void Open() - { - COORD csize; - CONSOLE_SCREEN_BUFFER_INFO csbiInfo; - SMALL_RECT srect; - - if( hConsole ) return; - AllocConsole(); - SetConsoleTitle(_("Ps2 Output")); - - csize.X = 100; - csize.Y = 2048; - SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), csize); - GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbiInfo); - - srect = csbiInfo.srWindow; - srect.Right = srect.Left + 99; - srect.Bottom = srect.Top + 64; - SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &srect); - hConsole = GetStdHandle(STD_OUTPUT_HANDLE); - } - - void Close() - { - if( hConsole == NULL ) return; - FreeConsole(); - hConsole = NULL; - } - - __forceinline void __fastcall SetColor( Colors color ) - { - SetConsoleTextAttribute( hConsole, tbl_color_codes[color] ); - } - - __forceinline void ClearColor() - { - SetConsoleTextAttribute( hConsole, - FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE ); - } - - - // Writes a newline to the console. - __forceinline bool __fastcall Newline() - { - if (hConsole != NULL) - { - DWORD tmp; - WriteConsole(hConsole, "\r\n", 2, &tmp, 0); - } - - if (emuLog != NULL) - { - fputs("\n", emuLog); - fflush( emuLog ); - } - - return false; - } - - // Writes an unformatted string of text to the console (fast!) - // No newline is appended. - __forceinline bool __fastcall Msg( const char* fmt ) - { - if (hConsole != NULL) - { - DWORD tmp; - WriteConsole(hConsole, fmt, (DWORD)strlen(fmt), &tmp, 0); - } - - // No flushing here -- only flush after newlines. - if (emuLog != NULL) - fputs(fmt, emuLog); - - return false; - } - - // Writes an unformatted string of text to the console (fast!) - // A newline is automatically appended. - __forceinline bool __fastcall MsgLn( const char* fmt ) - { - Write( fmt ); - Newline(); - return false; - } - - // Writes an unformatted string of text to the console (fast!) - // A newline is automatically appended. - __forceinline bool __fastcall MsgLn( Colors color, const char* fmt ) - { - SetColor( color ); - Write( fmt ); - ClearColor(); - Newline(); - return false; - } - - // Writes a formatted message to the console, with appended newline. - static __forceinline void __fastcall _WriteLn( Colors color, const char* fmt, va_list args ) - { - char msg[2048]; - - vsprintf_s(msg,2045,fmt,args); - strcat( msg, "\n" ); - SetColor( color ); - Write( msg ); - ClearColor(); - - if( emuLog != NULL ) - fflush( emuLog ); // manual flush to accompany manual newline - } - - // Writes a line of colored text to the console, with automatic newline appendage. - bool WriteLn( Colors color, const char* fmt, ... ) - { - va_list list; - va_start(list,fmt); - _WriteLn( color, fmt, list ); - va_end(list); - return false; - } - - // writes a formatted message to the console (no newline and no color) - bool Write( const char* fmt, ... ) - { - va_list list; - char msg[2048]; - - va_start(list,fmt); - vsprintf_s(msg,fmt,list); - msg[2047] = '\0'; - va_end(list); - - Msg( msg ); - return false; - } - - // writes a formatted message to the console (no newline and no color) - bool Write( Colors color, const char* fmt, ... ) - { - va_list list; - char msg[2048]; - - va_start(list,fmt); - vsprintf_s(msg,fmt,list); - msg[2047] = '\0'; - va_end(list); - - SetColor( color ); - Msg( msg ); - ClearColor(); - return false; - } - - // Writes a formatted message to the console, with appended newline. - // (no coloring) - bool WriteLn( const char* fmt, ... ) - { - va_list list; - char msg[2048]; - - va_start(list,fmt); - vsprintf_s(msg,2045,fmt,list); - va_end(list); - - strcat( msg, "\n" ); - Msg( msg ); - if( emuLog != NULL ) - fflush( emuLog ); // manual flush to accomany manual newline - return false; - } - - // Displays a message in the console with red emphasis. - // Newline is automatically appended. - bool Error( const char* fmt, ... ) - { - va_list list; - va_start(list,fmt); - _WriteLn( Color_Red, fmt, list ); - va_end(list); - return false; - } - - // Displays a message in the console with yellow emphasis. - // Newline is automatically appended. - bool Notice( const char* fmt, ... ) - { - va_list list; - va_start(list,fmt); - _WriteLn( Color_Yellow, fmt, list ); - va_end(list); - return false; - } - - // Displays a message in the console with green emphasis. - // Newline is automatically appended. - bool Status( const char* fmt, ... ) - { - va_list list; - va_start(list,fmt); - _WriteLn( Color_Green, fmt, list ); - va_end(list); - return false; - } - - // Pops up an alert Dialog Box. - // Replacement for SysMessage. - bool Alert( const char* fmt, ... ) - { - va_list list; - char tmp[512]; - - va_start(list,fmt); - vsprintf_s(tmp,fmt,list); - tmp[511] = '\0'; - va_end(list); - MessageBox(0, tmp, _("Pcsx2 Msg"), 0); - - return false; - } -} diff --git a/pcsx2/windows/DebugMemory.cpp b/pcsx2/windows/DebugMemory.cpp index 013b1a692e..5c85820814 100644 --- a/pcsx2/windows/DebugMemory.cpp +++ b/pcsx2/windows/DebugMemory.cpp @@ -131,7 +131,7 @@ BOOL APIENTRY DumpMemProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) fp = fopen(fname, "wb"); if (fp == NULL) { - Console::Alert("Can't open file '%s' for writing!\n", fname); + Msgbox::Alert("Can't open file '%s' for writing!", params fname); } else { diff --git a/pcsx2/windows/McdsDlg.cpp b/pcsx2/windows/McdsDlg.cpp index fd3937b7b2..cae7a20b78 100644 --- a/pcsx2/windows/McdsDlg.cpp +++ b/pcsx2/windows/McdsDlg.cpp @@ -658,7 +658,7 @@ class MemoryCard return 0; } - DbgCon::WriteLn("IFC: %d", IFC); + DbgCon::WriteLn("IFC: %d", params IFC); // Read the cluster with the indirect data to the FAT. fseek(fp, 0x420 * IFC, SEEK_SET); @@ -1619,8 +1619,8 @@ BOOL CALLBACK ConfigureMcdsDlgProc(HWND hW, UINT uMsg, WPARAM wParam, LPARAM lPa Static_SetText(GetDlgItem(hW, IDC_FRAMEMCD1), _("Memory Card 1")); Static_SetText(GetDlgItem(hW, IDC_FRAMEMCD2), _("Memory Card 2")); - if (!strlen(Config.Mcd1)) strcpy(Config.Mcd1, "memcards\\Mcd001.ps2"); - if (!strlen(Config.Mcd2)) strcpy(Config.Mcd2, "memcards\\Mcd002.ps2"); + if (!strlen(Config.Mcd1)) strcpy(Config.Mcd1, MEMCARDS_DIR "\\" DEFAULT_MEMCARD1); + if (!strlen(Config.Mcd2)) strcpy(Config.Mcd2, MEMCARDS_DIR "\\" DEFAULT_MEMCARD2); Edit_SetText(GetDlgItem(hW,IDC_MCD1), Config.Mcd1); Edit_SetText(GetDlgItem(hW,IDC_MCD2), Config.Mcd2); diff --git a/pcsx2/windows/RDebugger.cpp b/pcsx2/windows/RDebugger.cpp index ee5ee17c99..18683d9c21 100644 --- a/pcsx2/windows/RDebugger.cpp +++ b/pcsx2/windows/RDebugger.cpp @@ -134,7 +134,7 @@ int writeData(const u8 *result){ sprintf(p, "%02X ", result[i]); strcat(l, p); } - Console::Alert(l); + Msgbox::Alert(l); */ return r; } diff --git a/pcsx2/windows/SamplProf.cpp b/pcsx2/windows/SamplProf.cpp index 915af9f643..41c44de87b 100644 --- a/pcsx2/windows/SamplProf.cpp +++ b/pcsx2/windows/SamplProf.cpp @@ -280,7 +280,7 @@ void ProfilerInit() hProfThread=CreateThread(0,0,(LPTHREAD_START_ROUTINE)ProfilerThread,0,0,0); SetThreadPriority(hProfThread,THREAD_PRIORITY_HIGHEST); - //Console::MsgLn( " Done!" ); + //Console::WriteLn( " Done!" ); } void ProfilerTerm() @@ -305,7 +305,7 @@ void ProfilerTerm() CloseHandle( hMtgsThread ); DeleteCriticalSection( &ProfModulesLock ); - //Console::MsgLn( " Done!" ); + //Console::WriteLn( " Done!" ); } void ProfilerSetEnabled(bool Enabled) diff --git a/pcsx2/windows/VCprojects/pcsx2_2008.vcproj b/pcsx2/windows/VCprojects/pcsx2_2008.vcproj index 1f718b6646..da532cd640 100644 --- a/pcsx2/windows/VCprojects/pcsx2_2008.vcproj +++ b/pcsx2/windows/VCprojects/pcsx2_2008.vcproj @@ -220,7 +220,6 @@ AdditionalIncludeDirectories="$(SolutionDir)\common" PreprocessorDefinitions="WIN32_PTHREADS" MinimalRebuild="true" - ExceptionHandling="1" SmallerTypeCheck="false" EnableFunctionLevelLinking="true" UsePrecompiledHeader="2" @@ -312,7 +311,6 @@ AdditionalIncludeDirectories="$(SolutionDir)\common" PreprocessorDefinitions="NDEBUG;WIN32_PTHREADS" StringPooling="true" - ExceptionHandling="1" SmallerTypeCheck="false" RuntimeLibrary="0" StructMemberAlignment="5" @@ -552,10 +550,6 @@ RelativePath="..\ConfigDlg.cpp" > - - @@ -592,6 +586,10 @@ RelativePath="..\Win32.h" > + + @@ -600,7 +598,8 @@ > @@ -712,7 +716,7 @@ > @@ -845,6 +849,14 @@ RelativePath="..\..\SourceLog.cpp" > + + + + @@ -1067,6 +1079,326 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1118,20 +1450,748 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -2932,313 +3248,13 @@ > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + diff --git a/pcsx2/windows/Win32.h b/pcsx2/windows/Win32.h index d5c014e120..77a135d62f 100644 --- a/pcsx2/windows/Win32.h +++ b/pcsx2/windows/Win32.h @@ -32,7 +32,7 @@ extern char g_WorkingFolder[g_MaxPath]; extern const char* g_CustomConfigFile; -int LoadConfig(); +bool LoadConfig(); void SaveConfig(); // <<--- END Ini Configuration [ini.c] @@ -62,13 +62,12 @@ void InitLanguages(); char *GetLanguageNext(); void CloseLanguages(); void ChangeLanguage(char *lang); -#define StatusSet(text) SendMessage(hStatusWnd, SB_SETTEXT, 0, (LPARAM)(text)); void SysRestorableReset(); void WinClose(); -void States_Load( const char* file, int num=-1 ); -void States_Save( const char* file, int num=-1 ); +void States_Load( const string& file, int num=-1 ); +void States_Save( const string& file, int num=-1 ); void States_Load(int num); void States_Save(int num); void OnStates_LoadOther(); @@ -94,8 +93,14 @@ extern bool AccBreak; extern unsigned int langsMax; extern MemoryAlloc* g_RecoveryState; +extern MemoryAlloc* g_gsRecoveryState; extern const char* g_pRunGSState; extern int g_SaveGSStream; + +// sets the contents of the Pcsx2 status bar... +void StatusBar_Notice( const std::string& text ); +void StatusBar_SetMsg( const std::string& text ); + #endif diff --git a/pcsx2/windows/WinConsole.cpp b/pcsx2/windows/WinConsole.cpp new file mode 100644 index 0000000000..682c6193d6 --- /dev/null +++ b/pcsx2/windows/WinConsole.cpp @@ -0,0 +1,148 @@ +/* Pcsx2 - Pc Ps2 Emulator + * Copyright (C) 2002-2008 Pcsx2 Team + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#include "PrecompiledHeader.h" + +#include "System.h" +#include "Debug.h" + +namespace Console +{ + static HANDLE hConsole = NULL; + + static const int tbl_color_codes[] = + { + 0 // black + , FOREGROUND_RED | FOREGROUND_INTENSITY + , FOREGROUND_GREEN | FOREGROUND_INTENSITY + , FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY + , FOREGROUND_BLUE | FOREGROUND_INTENSITY + , FOREGROUND_RED | FOREGROUND_BLUE + , FOREGROUND_GREEN | FOREGROUND_BLUE + , FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY + }; + + void SetTitle( const string& title ) + { + if( !hConsole ) return; + SetConsoleTitle( title.c_str() ); + } + + void Open() + { + COORD csize; + CONSOLE_SCREEN_BUFFER_INFO csbiInfo; + SMALL_RECT srect; + + if( hConsole ) return; + AllocConsole(); + SetConsoleTitle(_("Ps2 Output")); + + csize.X = 100; + csize.Y = 2048; + SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), csize); + GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbiInfo); + + srect = csbiInfo.srWindow; + srect.Right = srect.Left + 99; + srect.Bottom = srect.Top + 64; + SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &srect); + hConsole = GetStdHandle(STD_OUTPUT_HANDLE); + } + + void Close() + { + if( hConsole == NULL ) return; + FreeConsole(); + hConsole = NULL; + } + + __forceinline void __fastcall SetColor( Colors color ) + { + SetConsoleTextAttribute( hConsole, tbl_color_codes[color] ); + } + + __forceinline void ClearColor() + { + SetConsoleTextAttribute( hConsole, + FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE ); + } + + + // Writes a newline to the console. + __forceinline bool __fastcall Newline() + { + if (hConsole != NULL) + { + DWORD tmp; + WriteConsole(hConsole, "\r\n", 2, &tmp, 0); + } + + if (emuLog != NULL) + { + fputs("\n", emuLog); + fflush( emuLog ); + } + + return false; + } + + // Writes an unformatted string of text to the console (fast!) + // No newline is appended. + __forceinline bool __fastcall Write( const string& fmt ) + { + if (hConsole != NULL) + { + DWORD tmp; + WriteConsole(hConsole, fmt.c_str(), (DWORD)fmt.length(), &tmp, 0); + } + + // No flushing here -- only flush after newlines. + if (emuLog != NULL) + fputs((char*)fmt.c_str(), emuLog); + + return false; + } + +} + +namespace Msgbox +{ + bool Alert( const string& fmt ) + { + MessageBox(0, fmt.c_str(), _("Pcsx2 Msg"), 0); + return false; + } + + // Pops up an alert Dialog Box. + // Replacement for SysMessage. + bool Alert( const string& fmt, VARG_PARAM dummy, ... ) + { + dummy_assert(); + + string dest; + va_list list; + + va_start(list,dummy); + vssprintf(dest,fmt,list); + va_end(list); + MessageBox(0, dest.c_str(), _("Pcsx2 Msg"), 0); + + return false; + } +} diff --git a/pcsx2/windows/WinMain.cpp b/pcsx2/windows/WinMain.cpp index 86672e7f96..6a8ae6ef6f 100644 --- a/pcsx2/windows/WinMain.cpp +++ b/pcsx2/windows/WinMain.cpp @@ -202,10 +202,13 @@ void WinClose() BOOL SysLoggedSetLockPagesPrivilege ( HANDLE hProcess, BOOL bEnable); -int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) +{ char *lang; int i; + CreateDirectory(LOGS_DIR, NULL); + #ifdef PCSX2_VIRTUAL_MEM LPVOID lpMemReserved; @@ -220,6 +223,7 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine MessageBox(NULL, str, "SysError", MB_OK); return -1; } + #endif InitCommonControls(); @@ -228,9 +232,6 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine pthread_win32_process_attach_np(); - __try - { - gApp.hInstance = hInstance; gApp.hMenu = NULL; gApp.hWnd = NULL; @@ -244,52 +245,33 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine _getcwd( g_WorkingFolder, g_MaxPath ); + __try { - int argc; - TCHAR *const *const argv = _CommandLineToArgv( lpCmdLine, &argc ); - if( argv == NULL ) - { - Console::Alert( "A fatal error occured while attempting to parse the command line.\n" ); - return 2; - } + int argc; + TCHAR *const *const argv = _CommandLineToArgv( lpCmdLine, &argc ); - switch( ParseCommandLine( argc, argv ) ) - { - case 1: // display help and exit: - printf( "%s", phelpmsg ); - MessageBox( NULL, phelpmsg, "Pcsx2 Help", MB_OK); + if( argv == NULL ) + { + Msgbox::Alert( "A fatal error occured while attempting to parse the command line.\n" ); + return 2; + } - case -1: // exit... - return 0; - } + switch( ParseCommandLine( argc, argv ) ) + { + case 1: // display help and exit: + printf( "%s", phelpmsg ); + MessageBox( NULL, phelpmsg, "Pcsx2 Help", MB_OK); - switch( LoadConfig() ) - { - case 0: break; // everything worked! - case 1: - // configure some defaults, notify the user, and the quit. - memset(&Config, 0, sizeof(Config)); - //strcpy(Config.Bios, "HLE"); - strcpy(Config.BiosDir, "Bios\\"); - strcpy(Config.PluginsDir, "Plugins\\"); - Config.Patch = 1; - Config.Options = PCSX2_EEREC|PCSX2_VU0REC|PCSX2_VU1REC|PCSX2_COP2REC; - Config.sseMXCSR = DEFAULT_sseMXCSR; - Config.sseVUMXCSR = DEFAULT_sseVUMXCSR; - Config.eeOptions = DEFAULT_eeOptions; - Config.vuOptions = DEFAULT_vuOptions; - Config.GameFixes = 0; - Config.Hacks = 0; + case -1: // exit... + return 0; + } - Console::Alert("Pcsx2 needs to be configured"); - Pcsx2Configure(NULL); - - case -1: // Error occured. Quit. - return 0; - } - - if( g_Error_PathTooLong ) return 3; + if( !LoadConfig() ) + { + // Prompt the user for a valid configuration before starting the program. + Msgbox::Alert( "Pcsx2 needs to be configured." ); + Pcsx2Configure( NULL ); } if (Config.Lang[0] == 0) { @@ -307,32 +289,33 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine CloseLanguages(); langsMax = i; - if( winConfig.PsxOut ) + if( Config.PsxOut ) { Console::Open(); //if( lpCmdLine == NULL || *lpCmdLine == 0 ) - // Console::MsgLn("-help to see arguments"); + // Console::WriteLn("-help to see arguments"); } - // Load the command line overrides for plugins: + // Load the command line overrides for plugins. + // Back up the user's preferences in winConfig. - memcpy( &Config, &winConfig, sizeof( PcsxConfig ) ); + memcpy( &winConfig, &Config, sizeof( PcsxConfig ) ); if( g_TestRun.pgsdll ) { _tcscpy_s( Config.GS, g_MaxPath, g_TestRun.pgsdll ); - Console::Notice( "* GS plugin override: \n\t%s\n", Config.GS ); + Console::Notice( "* GS plugin override: \n\t%s\n", params Config.GS ); } if( g_TestRun.pcdvddll ) { _tcscpy_s( Config.CDVD, g_MaxPath, g_TestRun.pcdvddll ); - Console::Notice( "* CDVD plugin override: \n\t%s\n", Config.CDVD ); + Console::Notice( "* CDVD plugin override: \n\t%s\n", params Config.CDVD ); } if( g_TestRun.pspudll ) { _tcscpy_s( Config.SPU2, g_MaxPath, g_TestRun.pspudll ); - Console::Notice( "* SPU2 plugin override: \n\t%s\n", Config.SPU2 ); + Console::Notice( "* SPU2 plugin override: \n\t%s\n", params Config.SPU2 ); } // [TODO] : Add the other plugin overrides here... @@ -377,15 +360,15 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine // output the help commands Console::SetColor( Console::Color_White ); - Console::MsgLn( "Hotkeys:" ); + Console::WriteLn( "Hotkeys:" ); - Console::MsgLn( + Console::WriteLn( "\tF1 - save state\n" "\t(Shift +) F2 - cycle states\n" "\tF3 - load state" ); - DevCon::MsgLn( + DevCon::WriteLn( "\tF10 - dump performance counters\n" "\tF11 - save GS state\n" "\tF12 - dump hardware registers" @@ -638,19 +621,21 @@ LRESULT WINAPI MainWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) case ID_RUN_EXECUTE: if( g_GameInProgress ) - m_ReturnToGame = 1; + { + m_ReturnToGame = true; + } else RunExecute( NULL, true ); // boots bios if no savestate is to be recovered return FALSE; case ID_FILE_RUNCD: safe_free( g_RecoveryState ); + safe_free( g_gsRecoveryState ); ResetPlugins(); RunExecute( NULL ); return FALSE; case ID_RUN_RESET: - safe_free( g_RecoveryState ); SysReset(); return FALSE; @@ -814,14 +799,18 @@ LRESULT WINAPI MainWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) case ID_PATCHES: Config.Patch = !Config.Patch; CheckMenuItem(gApp.hMenu, ID_PATCHES, Config.Patch ? MF_CHECKED : MF_UNCHECKED); - SaveConfig(); return FALSE; case ID_CDVDPRINT: Config.cdvdPrint = !Config.cdvdPrint; CheckMenuItem(gApp.hMenu, ID_CDVDPRINT, Config.cdvdPrint ? MF_CHECKED : MF_UNCHECKED); + SaveConfig(); + return FALSE; + case ID_CLOSEGS: + Config.closeGSonEsc = !Config.closeGSonEsc; + CheckMenuItem(gApp.hMenu, ID_CLOSEGS, Config.closeGSonEsc ? MF_CHECKED : MF_UNCHECKED); SaveConfig(); return FALSE; @@ -1021,6 +1010,7 @@ void CreateMainMenu() { ADDSUBMENU(0, _("&Misc")); ADDMENUITEM(0,_("Print cdvd &Info"), ID_CDVDPRINT); + ADDMENUITEM(0,_("Close GS Window on Esc"), ID_CLOSEGS); ADDSEPARATOR(0); #ifndef _DEBUG ADDMENUITEM(0,_("Enable &Profiler"), ID_PROFILER); @@ -1088,7 +1078,8 @@ void CreateMainWindow(int nCmdShow) { hWnd = CreateWindow( "PCSX2 Main", buf, WS_OVERLAPPED | WS_SYSMENU, - 20, 20, 320, 240, NULL, NULL, + 20, 20, 320, 240, + NULL, NULL, gApp.hInstance, NULL ); @@ -1104,9 +1095,9 @@ void CreateMainWindow(int nCmdShow) { if(Config.Patch) CheckMenuItem(gApp.hMenu,ID_PATCHES,MF_CHECKED); if(Config.Profiler) CheckMenuItem(gApp.hMenu,ID_PROFILER,MF_CHECKED); if(Config.cdvdPrint)CheckMenuItem(gApp.hMenu,ID_CDVDPRINT,MF_CHECKED); + if(Config.closeGSonEsc)CheckMenuItem(gApp.hMenu,ID_CLOSEGS,MF_CHECKED); + hStatusWnd = CreateStatusWindow(WS_CHILD | WS_VISIBLE, "", hWnd, 100); - sprintf(buf, "PCSX2 %s", PCSX2_VERSION); - StatusSet(buf); w = bm.bmWidth; h = bm.bmHeight; GetWindowRect(hStatusWnd, &rect); @@ -1114,14 +1105,16 @@ void CreateMainWindow(int nCmdShow) { GetMenuItemRect(hWnd, gApp.hMenu, 0, &rect); h+= rect.bottom - rect.top; MoveWindow(hWnd, 60, 60, w, h, TRUE); + SendMessage( hStatusWnd, WM_SIZE, 0, 0 ); + + StatusBar_SetMsg("F1 - save, F2 - next state, Shift+F2 - prev state, F3 - load, F8 - snapshot"); - DestroyWindow(hStatusWnd); - hStatusWnd = CreateStatusWindow(WS_CHILD | WS_VISIBLE, "", hWnd, 100); - sprintf(buf, "F1 - save, F2 - next state, Shift+F2 - prev state, F3 - load, F8 - snapshot", PCSX2_VERSION); - StatusSet(buf); ShowWindow(hWnd, nCmdShow); SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE); - SetForegroundWindow( hWnd ); + + // If we're coming off the GS plugin then we need to force ourselves to the top: + if( g_GameInProgress ) + SetForegroundWindow( hWnd ); } diff --git a/pcsx2/windows/WinSysExec.cpp b/pcsx2/windows/WinSysExec.cpp index 08a2ba9535..16255ff6fa 100644 --- a/pcsx2/windows/WinSysExec.cpp +++ b/pcsx2/windows/WinSysExec.cpp @@ -30,10 +30,14 @@ #include "Common.h" #include "PsxCommon.h" +using std::string; + int UseGui = 1; int nDisableSC = 0; // screensaver MemoryAlloc* g_RecoveryState = NULL; +MemoryAlloc* g_gsRecoveryState = NULL; + bool m_ReturnToGame = false; // set to exit the RunGui message pump bool g_GameInProgress = false; // Set TRUE if a game is actively running. @@ -51,6 +55,25 @@ const char* g_pRunGSState = NULL; #define CmdSwitchIs( text ) ( stricmp( command, text ) == 0 ) +// For issuing notices to both the status bar and the console at the same time. +// Single-line text only please! Mutli-line msgs should be directed to the +// console directly, thanks. +void StatusBar_Notice( const std::string& text ) +{ + // mirror output to the console! + Console::Status( text.c_str() ); + + // don't try this in GCC folks! + SendMessage(hStatusWnd, SB_SETTEXT, 0, (LPARAM)text.c_str() ); +} + +// Sets the status bar message without mirroring the output to the console. +void StatusBar_SetMsg( const std::string& text ) +{ + // don't try this in GCC folks! + SendMessage(hStatusWnd, SB_SETTEXT, 0, (LPARAM)text.c_str() ); +} + // returns 1 if the user requested help (show help and exit) // returns zero on success. // returns -1 on failure (bad command line argument) @@ -142,15 +165,32 @@ int ParseCommandLine( int tokenCount, TCHAR *const *const tokens ) return 0; } +void SysPrintf(const char *fmt, ...) +{ + va_list list; + char msg[512]; + + va_start(list,fmt); + vsprintf_s(msg,fmt,list); + msg[511] = '\0'; + va_end(list); + + Console::Write( msg ); +} + void ExecuteCpu() { + // Make sure any left-over recovery states are cleaned up. + safe_delete( g_RecoveryState ); + safe_delete( g_gsRecoveryState ); + // This tells the WM_DELETE handler of our GUI that we don't want the // system and plugins shut down, thanks... if( UseGui ) AccBreak = true; // ... and destroy the window. Ugly thing. - DestroyWindow(gApp.hWnd); + DestroyWindow( gApp.hWnd ); gApp.hWnd = NULL; g_GameInProgress = true; @@ -167,14 +207,14 @@ void RunExecute( const char* elf_file, bool use_bios ) nDisableSC = 1; g_GameInProgress = false; - + try { cpuReset(); } catch( std::exception& ex ) { - Console::Alert( ex.what() ); + Msgbox::Alert( ex.what() ); return; } @@ -191,9 +231,9 @@ void RunExecute( const char* elf_file, bool use_bios ) } catch( std::runtime_error& ex ) { - Console::Alert( + Msgbox::Alert( "Gamestate recovery failed. Your game progress will be lost (sorry!)\n" - "\nError: %s\n", ex.what() ); + "\nError: %s\n", params ex.what() ); // Take the user back to the GUI... safe_delete( g_RecoveryState ); @@ -213,7 +253,7 @@ void RunExecute( const char* elf_file, bool use_bios ) char ename[g_MaxPath]; ename[0] = 0; if( !use_bios ) - GetPS2ElfName(ename); + GetPS2ElfName( ename ); loadElfFile( ename ); } } @@ -222,8 +262,10 @@ void RunExecute( const char* elf_file, bool use_bios ) // Custom ELF specified (not using CDVD). // Run the BIOS and load the ELF. + SetCursor( LoadCursor( gApp.hInstance, IDC_WAIT ) ); cpuExecuteBios(); loadElfFile( elf_file ); + SetCursor( LoadCursor( gApp.hInstance, IDC_ARROW ) ); } // this needs to be called for every new game! @@ -235,19 +277,132 @@ void RunExecute( const char* elf_file, bool use_bios ) ExecuteCpu(); } -void States_Load( const char* file, int num ) -{ - struct stat buf; - if( stat(file, &buf ) == -1 ) +void RunGuiAndReturn() { + MSG msg; + + m_ReturnToGame = false; + while( !m_ReturnToGame ) { - Console::Notice( "Saveslot %d is empty.", num ); + if(PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + + Sleep(10); + } + + // re-init plugins before returning execution: + + OpenPlugins( NULL ); + + if( g_gsRecoveryState != NULL ) + { + memLoadingState eddie( *g_gsRecoveryState ); + eddie.FreezePlugin( "GS", GSfreeze ); + eddie.gsFreeze(); + + safe_delete( g_gsRecoveryState ); + + if( GSsetGameCRC != NULL ) + GSsetGameCRC(ElfCRC, g_ZeroGSOptions); + } + + AccBreak = true; + DestroyWindow(gApp.hWnd); + gApp.hWnd = NULL; +} + +class RecoveryMemSavingState : public memSavingState, Sealed +{ +public: + virtual ~RecoveryMemSavingState() { } + RecoveryMemSavingState() : memSavingState( *g_RecoveryState ) + { + } + + void gsFreeze() + { + if( g_gsRecoveryState != NULL ) + { + // just copy the data from src to dst. + // the normal savestate doesn't expect a length prefix for internal structures, + // so don't copy that part. + u32& pluginlen = *((u32*)g_gsRecoveryState->GetPtr(0)); + u32& gslen = *((u32*)g_gsRecoveryState->GetPtr(pluginlen+4)); + memcpy( m_memory.GetPtr(m_idx), g_gsRecoveryState->GetPtr(pluginlen+4), gslen ); + m_idx += gslen; + } + else + memSavingState::gsFreeze(); + } + + void FreezePlugin( const char* name, s32 (CALLBACK* freezer)(int mode, freezeData *data) ) + { + if( (freezer == GSfreeze) && (g_gsRecoveryState != NULL) ) + { + // Gs data is already in memory, so just copy from src to dest: + // length of the GS data is stored as the first u32, so use that to run the copy: + u32& len = *((u32*)g_gsRecoveryState->GetPtr()); + memcpy( m_memory.GetPtr(m_idx), g_gsRecoveryState->GetPtr(), len+4 ); + m_idx += len+4; + } + else + memSavingState::FreezePlugin( name, freezer ); + } +}; + +class RecoveryZipSavingState : public gzSavingState, Sealed +{ +public: + virtual ~RecoveryZipSavingState() { } + RecoveryZipSavingState( const string& filename ) : gzSavingState( filename ) + { + } + + void gsFreeze() + { + if( g_gsRecoveryState != NULL ) + { + // read data from the gsRecoveryState allocation instead of the GS, since the gs + // info was invalidated when the plugin was shut down. + + // the normal savestate doesn't expect a length prefix for internal structures, + // so don't copy that part. + + u32& pluginlen = *((u32*)g_gsRecoveryState->GetPtr(0)); + u32& gslen = *((u32*)g_gsRecoveryState->GetPtr(pluginlen+4)); + gzwrite( m_file, g_gsRecoveryState->GetPtr(pluginlen+4), gslen ); + } + else + gzSavingState::gsFreeze(); + } + + void FreezePlugin( const char* name, s32 (CALLBACK* freezer)(int mode, freezeData *data) ) + { + if( (freezer == GSfreeze) && (g_gsRecoveryState != NULL) ) + { + // Gs data is already in memory, so just copy from there into the gzip file. + // length of the GS data is stored as the first u32, so use that to run the copy: + u32& len = *((u32*)g_gsRecoveryState->GetPtr()); + gzwrite( m_file, g_gsRecoveryState->GetPtr(), len+4 ); + } + else + gzSavingState::FreezePlugin( name, freezer ); + } +}; + +void States_Load( const string& file, int num ) +{ + if( !Path::isFile( file ) ) + { + Console::Notice( "Saveslot %d is empty.", params num ); return; } try { - char Text[128]; - gzLoadingState joe( file ); // this'll throw an UnsupportedStateVersion. + char Text[g_MaxPath]; + gzLoadingState joe( file ); // this'll throw an StateLoadError_Recoverable. // Make sure the cpu and plugins are ready to be state-ified! cpuReset(); @@ -260,37 +415,43 @@ void States_Load( const char* file, int num ) else sprintf (Text, _("*PCSX2*: Loaded State %s"), file); - StatusSet( Text ); + StatusBar_Notice( Text ); + + if( GSsetGameCRC != NULL ) + GSsetGameCRC(ElfCRC, g_ZeroGSOptions); } - catch( Exception::UnsupportedStateVersion& ) + catch( Exception::StateLoadError_Recoverable& ex) { if( num != -1 ) - Console::Alert("Savestate slot %d is an unsupported version.", num); + Console::Notice( "Could not load savestate from slot %d.\n\n" + ex.Message(), params num ); else - Console::Alert("%s : This is an unsupported savestate version.", file); + Console::Notice( "Could not load savestate file: %s.\n\n" + ex.Message(), params file ); // At this point the cpu hasn't been reset, so we can return - // control to the user safely... + // control to the user safely... (that's why we use a console notice instead of a popup) return; } - catch( std::exception& ex ) + catch( Exception::BaseException& ex ) { - if( num != -1 ) - Console::Error( _("Error occured while trying to load savestate slot %d"), num); - else - Console::Error( _("Error occured while trying to load savestate file: %d"), file); - - Console::Error( ex.what() ); - // The emulation state is ruined. Might as well give them a popup and start the gui. - Console::Alert( - "An error occured while trying to load the savestate data.\n" - "Pcsx2 emulation state has been reset." - ); + string message; - cpuShutdown(); + if( num != -1 ) + ssprintf( message, + "Encountered an error while loading savestate from slot %d.\n", params num ); + else + ssprintf( message, + "Encountered an error while loading savestate from file: %s.\n", params file ); + + if( g_GameInProgress ) + message += "Since the savestate load was incomplete, the emulator has been reset.\n"; + + message += "\nError: " + ex.Message(); + + Msgbox::Alert( message ); + SysClose(); return; } @@ -298,63 +459,68 @@ void States_Load( const char* file, int num ) ExecuteCpu(); } -void States_Save( const char* file, int num ) +void States_Save( const string& file, int num ) { try { - char Text[128]; - gzSavingState(file).FreezeAll(); + string text; + RecoveryZipSavingState( file ).FreezeAll(); if( num != -1 ) - sprintf( Text, _( "State saved to slot %d" ), num ); + ssprintf( text, _( "State saved to slot %d" ), params num ); else - sprintf( Text, _( "State saved to file: %s" ), file ); + ssprintf( text, _( "State saved to file: %s" ), params file ); - StatusSet( Text ); + StatusBar_Notice( text ); } - catch( std::exception& ex ) + catch( Exception::BaseException& ex ) { + string message; + if( num != -1 ) - Console::Alert("An error occured while trying to save to slot %d", num ); + ssprintf( message, "An error occured while trying to save to slot %d\n", params num ); else - Console::Alert("An error occured while trying to save to file: %s", file ); + ssprintf( message, "An error occured while trying to save to file: %s\n", params file ); - Console::Error( _( "Save state request failed with the following error:" ) ); - Console::Error( ex.what() ); + message += "Your emulation state has not been saved!\n\nError: " + ex.Message(); + + Console::Error( message ); } } -void RunGuiAndReturn() { - MSG msg; - - m_ReturnToGame = false; - while( !m_ReturnToGame ) { - if(PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - - Sleep(10); - } - - // re-init plugins before returning execution: - - OpenPlugins( NULL ); - AccBreak = true; - DestroyWindow(gApp.hWnd); -} - void States_Load(int num) { - char Text[g_MaxPath]; - SaveState::GetFilename( Text, num ); - States_Load( Text, num ); + States_Load( SaveState::GetFilename( num ), num ); } void States_Save(int num) { - char Text[g_MaxPath]; - SaveState::GetFilename( Text, num ); - States_Save( Text, num ); + if( g_RecoveryState != NULL ) + { + // State is already saved into memory, and the emulator (and in-progress flag) + // have likely been cleared out. So save from the Recovery buffer instead of + // doing a "standard" save: + + string text; + SaveState::GetFilename( text, num ); + gzFile fileptr = gzopen( text.c_str(), "wb" ); + if( fileptr == NULL ) + { + Msgbox::Alert( _("File permissions error while trying to save to slot %d"), params num ); + return; + } + gzwrite( fileptr, &g_SaveVersion, sizeof( u32 ) ); + gzwrite( fileptr, g_RecoveryState->GetPtr(), g_RecoveryState->GetSizeInBytes() ); + gzclose( fileptr ); + return; + } + + if( !g_GameInProgress ) + { + Msgbox::Alert( "You need to start a game first before you can save it's state." ); + return; + } + + States_Save( SaveState::GetFilename( num ), num ); } void OnStates_LoadOther() @@ -421,6 +587,26 @@ void OnStates_SaveOther() States_Save( szFileName ); } +class JustGsSavingState : public memSavingState, Sealed +{ +public: + virtual ~JustGsSavingState() { } + JustGsSavingState() : memSavingState( *g_gsRecoveryState ) + { + } + + // This special override saves the gs info to m_idx+4, and then goes back and + // writes in the length of data saved. + void gsFreeze() + { + int oldmidx = m_idx; + m_idx += 4; + memSavingState::gsFreeze(); + s32& len = *((s32*)m_memory.GetPtr( oldmidx )); + len = (m_idx - oldmidx)-4; + } +}; + static int shiftkey = 0; void CALLBACK KeyEvent(keyEvent* ev) { @@ -473,14 +659,25 @@ void CALLBACK KeyEvent(keyEvent* ev) PostMessage(GetForegroundWindow(), WM_CLOSE, 0, 0); WinClose(); } - else { - ClosePlugins(); - + else + { if( !UseGui ) { // not using GUI and user just quit, so exit WinClose(); } + if( Config.closeGSonEsc ) + { + safe_delete( g_gsRecoveryState ); + g_gsRecoveryState = new MemoryAlloc(); + JustGsSavingState eddie; + eddie.FreezePlugin( "GS", GSfreeze ) ; + eddie.gsFreeze(); + PluginsResetGS(); + } + + ClosePlugins(); + CreateMainWindow(SW_SHOWNORMAL); nDisableSC = 0; RunGuiAndReturn(); @@ -495,6 +692,7 @@ void CALLBACK KeyEvent(keyEvent* ev) static bool sinit=false; + void SysRestorableReset() { // already reset? and saved? @@ -503,32 +701,39 @@ void SysRestorableReset() try { + SetCursor( LoadCursor( gApp.hInstance, IDC_APPSTARTING ) ); g_RecoveryState = new MemoryAlloc( "Memory Savestate Recovery" ); - memSavingState( *g_RecoveryState ).FreezeAll(); + RecoveryMemSavingState().FreezeAll(); + safe_delete( g_gsRecoveryState ); cpuShutdown(); g_GameInProgress = false; } catch( std::runtime_error& ex ) { - Console::Alert( + Msgbox::Alert( "Pcsx2 gamestate recovery failed. Some options may have been reverted to protect your game's state.\n" - "Error: %s", ex.what() ); + "Error: %s", params ex.what() ); safe_delete( g_RecoveryState ); } + SetCursor( LoadCursor( gApp.hInstance, IDC_ARROW ) ); } void SysReset() { if (!sinit) return; - StatusSet(_("Resetting...")); + // fixme - this code sets the sttusbar but never returns control to the window message pump + // so the status bar won't recieve the WM_PAINT messages needed to update itself anyway. + // Oops! (air) + + StatusBar_Notice(_("Resetting...")); g_GameInProgress = false; safe_free( g_RecoveryState ); - + safe_free( g_gsRecoveryState ); ResetPlugins(); - StatusSet(_("Ready")); + StatusBar_Notice(_("Ready")); } bool SysInit() @@ -538,7 +743,6 @@ bool SysInit() CreateDirectory(MEMCARDS_DIR, NULL); CreateDirectory(SSTATES_DIR, NULL); - CreateDirectory(LOGS_DIR, NULL); if( IsDevBuild && emuLog == NULL && g_TestRun.plogname != NULL ) emuLog = fopen(g_TestRun.plogname, "w"); @@ -570,31 +774,6 @@ void SysClose() { sinit=false; } -void SysPrintf(const char *fmt, ...) -{ - va_list list; - char msg[512]; - - va_start(list,fmt); - vsprintf_s(msg,fmt,list); - msg[511] = '\0'; - va_end(list); - - Console::Msg( msg ); -} - -void SysMessage(const char *fmt, ...) -{ - va_list list; - char msg[512]; - - va_start(list,fmt); - vsprintf_s(msg,fmt,list); - msg[511] = '\0'; - va_end(list); - - Console::Alert(msg); -} void SysUpdate() { @@ -645,7 +824,9 @@ void *SysMmap(uptr base, u32 size) { return mem; } -void SysMunmap(uptr base, u32 size) { +void SysMunmap(uptr base, u32 size) +{ + if( base == NULL ) return; VirtualFree((void*)base, size, MEM_DECOMMIT); VirtualFree((void*)base, 0, MEM_RELEASE); } diff --git a/pcsx2/windows/WinThreads.cpp b/pcsx2/windows/WinThreads.cpp index 3ba58574e6..1faa20c157 100644 --- a/pcsx2/windows/WinThreads.cpp +++ b/pcsx2/windows/WinThreads.cpp @@ -78,7 +78,7 @@ namespace Threading } catch( std::exception& ex ) { - Console::Error( "Thread terminated abnormally with error:\n\t%s", ex.what() ); + Console::Error( "Thread terminated abnormally with error:\n\t%s", params ex.what() ); owner.m_returncode = -1; } diff --git a/pcsx2/windows/WinVM.cpp b/pcsx2/windows/WinVM.cpp index 58ad2dd26b..be8e30b4b0 100644 --- a/pcsx2/windows/WinVM.cpp +++ b/pcsx2/windows/WinVM.cpp @@ -39,7 +39,7 @@ LRESULT WINAPI UserNameProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { wchar_t str[255]; GetWindowTextW(GetDlgItem(hDlg, IDC_USER_NAME), str, 255); - swprintf(s_szUserName, 255, L"%S", str); + swprintf(s_szUserName, 255, L"%S", &str); EndDialog(hDlg, TRUE ); return TRUE; } @@ -262,7 +262,7 @@ BOOL SysLoggedSetLockPagesPrivilege ( HANDLE hProcess, BOOL bEnable) if( Result != TRUE ) { - Console::Error( "VirtualMemory Error > Cannot get privilege value for %s.", SE_LOCK_MEMORY_NAME ); + Console::Error( "VirtualMemory Error > Cannot get privilege value for %s.", params SE_LOCK_MEMORY_NAME ); return FALSE; } @@ -275,7 +275,7 @@ BOOL SysLoggedSetLockPagesPrivilege ( HANDLE hProcess, BOOL bEnable) // Check the result. if( Result != TRUE ) { - Console::Error( "VirtualMemory Error > Cannot adjust token privileges, error %u.", GetLastError() ); + Console::Error( "VirtualMemory Error > Cannot adjust token privileges, error %u.", params GetLastError() ); return FALSE; } else @@ -355,7 +355,7 @@ int SysPhysicalAlloc(u32 size, PSMEMORYBLOCK* pblock) s_dwPageSize = sSysInfo.dwPageSize; if( s_dwPageSize != 0x1000 ) { - Console::Alert("Error! OS page size must be 4Kb!\n" + Msgbox::Alert("Error! OS page size must be 4Kb!\n" "If for some reason the OS cannot have 4Kb pages, then run the TLB build."); return -1; } @@ -378,13 +378,13 @@ int SysPhysicalAlloc(u32 size, PSMEMORYBLOCK* pblock) if( bResult != TRUE ) { - Console::Error("Virtual Memory Error %u > Cannot allocate physical pages.", GetLastError() ); + Console::Error("Virtual Memory Error %u > Cannot allocate physical pages.", params GetLastError() ); goto eCleanupAndExit; } if( NumberOfPagesInitial != pblock->NumberPages ) { - Console::Error("Virtual Memory > Physical allocation failed!\n\tAllocated only %p of %p pages.", pblock->NumberPages, NumberOfPagesInitial ); + Console::Error("Virtual Memory > Physical allocation failed!\n\tAllocated only %p of %p pages.", params pblock->NumberPages, NumberOfPagesInitial ); goto eCleanupAndExit; } @@ -417,7 +417,7 @@ int SysVirtualPhyAlloc(void* base, u32 size, PSMEMORYBLOCK* pblock) LPVOID lpMemReserved = VirtualAlloc( base, size, MEM_RESERVE | MEM_PHYSICAL, PAGE_READWRITE ); if( lpMemReserved == NULL || base != lpMemReserved ) { - Console::WriteLn("VirtualMemory Error %d > Cannot reserve memory at 0x%8.8x(%x).", base, lpMemReserved, GetLastError()); + Console::WriteLn("VirtualMemory Error %d > Cannot reserve memory at 0x%8.8x(%x).", params base, lpMemReserved, GetLastError()); goto eCleanupAndExit; } @@ -429,7 +429,7 @@ int SysVirtualPhyAlloc(void* base, u32 size, PSMEMORYBLOCK* pblock) if( bResult != TRUE ) { - Console::WriteLn("VirtualMemory Error %u > MapUserPhysicalPages failed to map.", GetLastError() ); + Console::WriteLn("VirtualMemory Error %u > MapUserPhysicalPages failed to map.", params GetLastError() ); goto eCleanupAndExit; } @@ -445,7 +445,7 @@ void SysVirtualFree(void* lpMemReserved, u32 size) // unmap if( MapUserPhysicalPages( lpMemReserved, (size+s_dwPageSize-1)/s_dwPageSize, NULL ) != TRUE ) { - Console::WriteLn("VirtualMemory Error %u > MapUserPhysicalPages failed to unmap", GetLastError() ); + Console::WriteLn("VirtualMemory Error %u > MapUserPhysicalPages failed to unmap", params GetLastError() ); return; } diff --git a/pcsx2/windows/ini.cpp b/pcsx2/windows/ini.cpp index 8e6b0b27df..3d68a20b00 100644 --- a/pcsx2/windows/ini.cpp +++ b/pcsx2/windows/ini.cpp @@ -15,9 +15,6 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -/* -15-09-2004 : file rewriten for work with inis (shadow) -*/ #include "PrecompiledHeader.h" #include "win32.h" @@ -25,24 +22,26 @@ #include "Common.h" #include "Paths.h" +static const u32 IniVersion = 100; + const char* g_CustomConfigFile; char g_WorkingFolder[g_MaxPath]; // Working folder at application startup // Returns TRUE if the user has invoked the -cfg command line option. -BOOLEAN hasCustomConfig() +static bool hasCustomConfig() { return (g_CustomConfigFile != NULL) && (g_CustomConfigFile[0] != 0); } // Returns the FULL (absolute) path and filename of the configuration file. -void GetConfigFilename( char* dest ) +static void GetConfigFilename( string& dest ) { if( hasCustomConfig() ) { // Load a user-specified configuration. // If the configuration isn't found, fail outright (see below) - CombinePaths( dest, g_WorkingFolder, g_CustomConfigFile ); + Path::Combine( dest, g_WorkingFolder, g_CustomConfigFile ); } else { @@ -50,213 +49,298 @@ void GetConfigFilename( char* dest ) // Our current working directory can change, so we use the one we detected // at startup: - CombinePaths( dest, g_WorkingFolder, CONFIG_DIR "\\pcsx2pg.ini" ); + Path::Combine( dest, g_WorkingFolder, CONFIG_DIR "\\pcsx2pg.ini" ); } } -int LoadConfig() +class IniFile { - FILE *fp; - PcsxConfig& Conf = winConfig; +protected: + string m_filename; + string m_section; - char szIniFile[g_MaxPath], szValue[g_MaxPath]; +public: + virtual ~IniFile() {} + IniFile() : m_filename(), m_section("Misc") + { + GetConfigFilename( m_filename ); + } + + void SetCurrentSection( const string& newsection ) + { + m_section = newsection; + } + + virtual void Entry( const string& var, string& value, const string& defvalue=string() )=0; + virtual void Entry( const string& var, char (&value)[g_MaxPath], const string& defvalue=string() )=0; + virtual void Entry( const string& var, int& value, const int defvalue=0 )=0; + virtual void Entry( const string& var, uint& value, const uint defvalue=0 )=0; + virtual void Entry( const string& var, bool& value, const bool defvalue=0 )=0; + virtual void EnumEntry( const string& var, int& value, const char* const* enumArray, const int defvalue=0 )=0; + + void DoConfig( PcsxConfig& Conf ) + { + SetCurrentSection( "Misc" ); + + Entry( "Patching", Conf.Patch, true ); + Entry( "GameFixes", Conf.GameFixes); +#ifdef PCSX2_DEVBUILD + Entry( "DevLogFlags", varLog ); +#endif + + //interface + SetCurrentSection( "Interface" ); + Entry( "Bios", Conf.Bios ); + Entry( "Language", Conf.Lang ); + Entry( "PluginsDir", Conf.PluginsDir, DEFAULT_PLUGINS_DIR ); + Entry( "BiosDir", Conf.BiosDir, DEFAULT_BIOS_DIR ); + Entry( "CloseGsOnEscape", Conf.closeGSonEsc, true ); + + SetCurrentSection( "Console" ); + Entry( "ConsoleWindow", Conf.PsxOut, true ); + Entry( "Profiler", Conf.Profiler, false ); + Entry( "CdvdVerbose", Conf.cdvdPrint, false ); + + Entry( "ThreadPriority", Conf.ThPriority, THREAD_PRIORITY_NORMAL ); + Entry( "Memorycard1", Conf.Mcd1, DEFAULT_MEMCARD1 ); + Entry( "Memorycard2", Conf.Mcd2, DEFAULT_MEMCARD2 ); + + SetCurrentSection( "Framelimiter" ); + Entry( "CustomFps", Conf.CustomFps ); + Entry( "FrameskipMode", Conf.CustomFrameSkip ); + Entry( "ConsecutiveFramesToRender", Conf.CustomConsecutiveFrames ); + Entry( "ConsecutiveFramesToSkip", Conf.CustomConsecutiveSkip ); + + // Plugins are saved from the winConfig struct. + // It contains the user config settings and not the + // runtime cmdline overrides. + + SetCurrentSection( "Plugins" ); + + Entry( "GS", Conf.GS ); + Entry( "SPU2", Conf.SPU2 ); + Entry( "CDVD", Conf.CDVD ); + Entry( "PAD1", Conf.PAD1 ); + Entry( "PAD2", Conf.PAD2 ); + Entry( "DEV9", Conf.DEV9 ); + Entry( "USB", Conf.USB ); + Entry( "FW", Conf.FW ); + + //cpu + SetCurrentSection( "Cpu" ); + Entry( "Options", Conf.Options, PCSX2_EEREC|PCSX2_VU0REC|PCSX2_VU1REC|PCSX2_COP2REC ); + Entry( "sseMXCSR", Conf.sseMXCSR, DEFAULT_sseMXCSR ); + Entry( "sseVUMXCSR", Conf.sseVUMXCSR, DEFAULT_sseVUMXCSR ); + Entry( "eeOptions", Conf.eeOptions, DEFAULT_eeOptions ); + Entry( "vuOptions", Conf.vuOptions, DEFAULT_vuOptions ); + Entry( "SpeedHacks", Conf.Hacks ); + } +}; + +class IniFileLoader : public IniFile +{ +protected: + MemoryAlloc m_workspace; + +public: + virtual ~IniFileLoader() {} + IniFileLoader() : IniFile(), + m_workspace( 4096, "IniFileLoader Workspace" ) + { + } + + void Entry( const string& var, string& value, const string& defvalue=string() ) + { + int retval = GetPrivateProfileString( + m_section.c_str(), var.c_str(), defvalue.c_str(), m_workspace.GetPtr(), m_workspace.GetLength(), m_filename.c_str() + ); + + if( retval >= m_workspace.GetLength() - 2 ) + Console::Notice( "Loadini Warning > Possible truncated value on key '%S'", params &var ); + value = m_workspace.GetPtr(); + } + + void Entry( const string& var, char (&value)[g_MaxPath], const string& defvalue=string() ) + { + int retval = GetPrivateProfileString( + m_section.c_str(), var.c_str(), defvalue.c_str(), value, sizeof( value ), m_filename.c_str() + ); + + if( retval >= sizeof(value) - 2 ) + Console::Notice( "Loadini Warning > Possible truncated value on key '%S'", params &var ); + } + + void Entry( const string& var, int& value, const int defvalue=0 ) + { + string retval; + Entry( var, retval, to_string( defvalue ) ); + value = atoi( retval.c_str() ); + } + + void Entry( const string& var, uint& value, const uint defvalue=0 ) + { + string retval; + Entry( var, retval, to_string( defvalue ) ); + value = atoi( retval.c_str() ); + } + + void Entry( const string& var, bool& value, const bool defvalue=false ) + { + string retval; + Entry( var, retval, defvalue ? "enabled" : "disabled" ); + value = (retval == "enabled"); + } + + void EnumEntry( const string& var, int& value, const char* const* enumArray, const int defvalue=0 ) + { + string retval; + Entry( var, retval, enumArray[defvalue] ); + + int i=0; + while( enumArray[i] != NULL && ( retval != enumArray[i] ) ) i++; + + if( enumArray[i] == NULL ) + { + Console::Notice( "Loadini Warning > Unrecognized value '%S' on key '%S'\n\tUsing the default setting of '%s'.", + params &retval, &var, enumArray[defvalue] ); + value = defvalue; + } + else + value = i; + } + +}; + +class IniFileSaver : public IniFile +{ +public: + virtual ~IniFileSaver() {} + IniFileSaver() : IniFile() + { + char versionStr[20]; + _itoa( IniVersion, versionStr, 10 ); + WritePrivateProfileString( "Misc", "IniVersion", versionStr, m_filename.c_str() ); + } + + void Entry( const string& var, const string& value, const string& defvalue=string() ) + { + WritePrivateProfileString( m_section.c_str(), var.c_str(), value.c_str(), m_filename.c_str() ); + } + + void Entry( const string& var, string& value, const string& defvalue=string() ) + { + WritePrivateProfileString( m_section.c_str(), var.c_str(), value.c_str(), m_filename.c_str() ); + } + + void Entry( const string& var, char (&value)[g_MaxPath], const string& defvalue=string() ) + { + WritePrivateProfileString( m_section.c_str(), var.c_str(), value, m_filename.c_str() ); + } + + void Entry( const string& var, int& value, const int defvalue=0 ) + { + Entry( var, to_string( value ) ); + } + + void Entry( const string& var, uint& value, const uint defvalue=0 ) + { + Entry( var, to_string( value ) ); + } + + void Entry( const string& var, bool& value, const bool defvalue=false ) + { + Entry( var, value ? "enabled" : "disabled" ); + } + + void EnumEntry( const string& var, int& value, const char* const* enumArray, const int defvalue=0 ) + { + Entry( var, enumArray[value] ); + } +}; + +bool LoadConfig() +{ + string szIniFile; + bool status = true; GetConfigFilename( szIniFile ); - if( g_Error_PathTooLong ) return -1; - - fp = fopen( szIniFile, "rt" ); - if( fp == NULL) + if( !Path::Exists( szIniFile ) ) { if( hasCustomConfig() ) { // using custom config, so fail outright: - Console::Alert( "User-specified configuration file not found:\n %s\nPCSX2 will now exit." ); - return -1; + throw Exception::FileNotFound( + "User-specified configuration file not found:\n\t%s\n\nPCSX2 will now exit." + ); } // standard mode operation. Create the directory. - // Conf File will be created and saved later. - CreateDirectory("inis",NULL); - return 1; + CreateDirectory( "inis", NULL ); + status = false; // inform caller that we're not configured. } - fclose(fp); - //interface - GetPrivateProfileString("Interface", "Bios", NULL, szValue, g_MaxPath, szIniFile); - strcpy(Conf.Bios, szValue); - GetPrivateProfileString("Interface", "Lang", NULL, szValue, g_MaxPath, szIniFile); - strcpy(Conf.Lang, szValue); - GetPrivateProfileString("Interface", "Ps2Out", NULL, szValue, 20, szIniFile); - Conf.PsxOut = !!strtoul(szValue, NULL, 10); - GetPrivateProfileString("Interface", "Profiler", NULL, szValue, 20, szIniFile); - Conf.Profiler = !!strtoul(szValue, NULL, 10); - GetPrivateProfileString("Interface", "cdvdPrint", NULL, szValue, 20, szIniFile); - Conf.cdvdPrint = !!strtoul(szValue, NULL, 10); - GetPrivateProfileString("Interface", "ThPriority", NULL, szValue, 20, szIniFile); - Conf.ThPriority = strtoul(szValue, NULL, 10); - GetPrivateProfileString("Interface", "PluginsDir", NULL, szValue, g_MaxPath, szIniFile); - strcpy(Conf.PluginsDir, szValue); - GetPrivateProfileString("Interface", "BiosDir", NULL, szValue, g_MaxPath, szIniFile); - strcpy(Conf.BiosDir, szValue); - GetPrivateProfileString("Interface", "Mcd1", NULL, szValue, g_MaxPath, szIniFile); - strcpy(Conf.Mcd1, szValue); - GetPrivateProfileString("Interface", "Mcd2", NULL, szValue, g_MaxPath, szIniFile); - strcpy(Conf.Mcd2, szValue); - Conf.CustomFps = GetPrivateProfileInt("Interface", "CustomFps", 0, szIniFile); - Conf.CustomFrameSkip = GetPrivateProfileInt("Interface", "CustomFrameskip", 0, szIniFile); - Conf.CustomConsecutiveFrames = GetPrivateProfileInt("Interface", "CustomConsecutiveFrames", 0, szIniFile); - Conf.CustomConsecutiveSkip = GetPrivateProfileInt("Interface", "CustomConsecutiveSkip", 0, szIniFile); + else + { + // sanity check to make sure the user doesn't have some kind of + // crazy ass setup... why not! - //plugins - GetPrivateProfileString("Plugins", "GS", NULL, szValue, g_MaxPath, szIniFile); - strcpy(Conf.GS, szValue); - GetPrivateProfileString("Plugins", "SPU2", NULL, szValue, g_MaxPath, szIniFile); - strcpy(Conf.SPU2, szValue); - GetPrivateProfileString("Plugins", "CDVD", NULL, szValue, g_MaxPath, szIniFile); - strcpy(Conf.CDVD, szValue); - GetPrivateProfileString("Plugins", "PAD1", NULL, szValue, g_MaxPath, szIniFile); - strcpy(Conf.PAD1, szValue); - GetPrivateProfileString("Plugins", "PAD2", NULL, szValue, g_MaxPath, szIniFile); - strcpy(Conf.PAD2, szValue); - GetPrivateProfileString("Plugins", "DEV9", NULL, szValue, g_MaxPath, szIniFile); - strcpy(Conf.DEV9, szValue); - GetPrivateProfileString("Plugins", "USB", NULL, szValue, g_MaxPath, szIniFile); - strcpy(Conf.USB, szValue); - GetPrivateProfileString("Plugins", "FW", NULL, szValue, g_MaxPath, szIniFile); - strcpy(Conf.FW, szValue); - //cpu - GetPrivateProfileString("Cpu Options", "Options", NULL, szValue, 20, szIniFile); - Conf.Options= (u32)strtoul(szValue, NULL, 10); + if( Path::isDirectory( szIniFile ) ) + throw Exception::Stream( + "Cannot open or create the Pcsx2 ini file because a directory of\n" + "the same name already exists! Please delete it or reinstall Pcsx2\n" + "fresh and try again." + ); - GetPrivateProfileString("Cpu Options", "sseMXCSR", NULL, szValue, 20, szIniFile); - Conf.sseMXCSR = strtoul(szValue, NULL, 0); - g_sseMXCSR = Conf.sseMXCSR; + // Ini Version check! ----> + // If the user's ini is old, give them a friendly warning that says they should + // probably delete it. - GetPrivateProfileString("Cpu Options", "sseVUMXCSR", NULL, szValue, 20, szIniFile); - Conf.sseVUMXCSR = strtoul(szValue, NULL, 0); - g_sseVUMXCSR = Conf.sseVUMXCSR; + char versionStr[20]; + u32 version; - GetPrivateProfileString("Cpu Options", "eeOptions", NULL, szValue, 20, szIniFile); - Conf.eeOptions = strtoul(szValue, NULL, 0); - GetPrivateProfileString("Cpu Options", "vuOptions", NULL, szValue, 20, szIniFile); - Conf.vuOptions = strtoul(szValue, NULL, 0); + GetPrivateProfileString( "Misc", "IniVersion", NULL, versionStr, 20, szIniFile.c_str() ); + version = atoi( versionStr ); + if( version < IniVersion ) + { + // Warn the user of a version mismatch. + Msgbox::Alert( + "Configuration versions do not match. Pcsx2 may be unstable.\n" + "If you experience problems, delete the pcsx2-pg.ini file from the ini dir." + ); - //Misc - GetPrivateProfileString("Misc", "Patch", NULL, szValue, 20, szIniFile); - Conf.Patch = !!strtoul(szValue, NULL, 10); + // save the new version -- gets rid of the warning on subsequent startups + _itoa( IniVersion, versionStr, 10 ); + WritePrivateProfileString( "Misc", "IniVersion", versionStr, szIniFile.c_str() ); + } + } -#ifdef PCSX2_DEVBUILD - GetPrivateProfileString("Misc", "varLog", NULL, szValue, 20, szIniFile); - varLog = strtoul(szValue, NULL, 16); -#endif - GetPrivateProfileString("Misc", "Hacks", NULL, szValue, 20, szIniFile); - Conf.Hacks = strtoul(szValue, NULL, 0); - GetPrivateProfileString("Misc", "GameFixes", NULL, szValue, 20, szIniFile); - Conf.GameFixes = strtoul(szValue, NULL, 0); - - // Remove Fast Branches hack for now: - Conf.Hacks &= ~0x80; + IniFileLoader().DoConfig( Config ); #ifdef ENABLE_NLS { - char text[256]; + string text; extern int _nl_msg_cat_cntr; - sprintf_s(text, 256, "LANGUAGE=%s", Conf.Lang); - gettext_putenv(text); + ssprintf(text, "LANGUAGE=%s", params Config.Lang); + gettext_putenv(text.c_str()); } #endif - return 0; + return status; } -///////////////////////////////////////////////////////// - void SaveConfig() { - const PcsxConfig& Conf = Config; - char szIniFile[g_MaxPath], szValue[g_MaxPath]; + PcsxConfig tmpConf = Config; - //GetModuleFileName(GetModuleHandle((LPCSTR)gApp.hInstance), szIniFile, 256); - //szTemp = strrchr(szIniFile, '\\'); - - GetConfigFilename( szIniFile ); - - // This should never be true anyway since long pathnames would have in theory - // been caught earlier by LoadConfig -- but no harm in being safe. - if( g_Error_PathTooLong ) return; - - //interface - sprintf(szValue,"%s",Conf.Bios); - WritePrivateProfileString("Interface","Bios",szValue,szIniFile); - sprintf(szValue,"%s",Conf.Lang); - WritePrivateProfileString("Interface","Lang",szValue,szIniFile); - sprintf(szValue,"%s",Conf.PluginsDir); - WritePrivateProfileString("Interface","PluginsDir",szValue,szIniFile); - sprintf(szValue,"%s",Conf.BiosDir); - WritePrivateProfileString("Interface","BiosDir",szValue,szIniFile); - sprintf(szValue,"%u",(int)Conf.PsxOut); - WritePrivateProfileString("Interface","Ps2Out",szValue,szIniFile); - sprintf(szValue,"%u",(int)Conf.Profiler); - WritePrivateProfileString("Interface","Profiler",szValue,szIniFile); - sprintf(szValue,"%u",(int)Conf.cdvdPrint); - WritePrivateProfileString("Interface","cdvdPrint",szValue,szIniFile); - sprintf(szValue,"%u",Conf.ThPriority); - WritePrivateProfileString("Interface","ThPriority",szValue,szIniFile); - sprintf(szValue,"%s",Conf.Mcd1); - WritePrivateProfileString("Interface","Mcd1",szValue,szIniFile); - sprintf(szValue,"%s",Conf.Mcd2); - WritePrivateProfileString("Interface","Mcd2",szValue,szIniFile); - sprintf(szValue,"%d",Conf.CustomFps); - WritePrivateProfileString("Interface", "CustomFps", szValue, szIniFile); - sprintf(szValue,"%d",Conf.CustomFrameSkip); - WritePrivateProfileString("Interface", "CustomFrameskip", szValue, szIniFile); - sprintf(szValue,"%d",Conf.CustomConsecutiveFrames); - WritePrivateProfileString("Interface", "CustomConsecutiveFrames", szValue, szIniFile); - sprintf(szValue,"%d",Conf.CustomConsecutiveSkip); - WritePrivateProfileString("Interface", "CustomConsecutiveSkip", szValue, szIniFile); - - // Plugins are saved from the winConfig struct. - // It contains the user config settings and not the - // runtime cmdline overrides. - - sprintf(szValue,"%s",winConfig.GS); - WritePrivateProfileString("Plugins","GS",szValue,szIniFile); - sprintf(szValue,"%s",winConfig.SPU2); - WritePrivateProfileString("Plugins","SPU2",szValue,szIniFile); - sprintf(szValue,"%s",winConfig.CDVD); - WritePrivateProfileString("Plugins","CDVD",szValue,szIniFile); - sprintf(szValue,"%s",winConfig.PAD1); - WritePrivateProfileString("Plugins","PAD1",szValue,szIniFile); - sprintf(szValue,"%s",winConfig.PAD2); - WritePrivateProfileString("Plugins","PAD2",szValue,szIniFile); - sprintf(szValue,"%s",winConfig.DEV9); - WritePrivateProfileString("Plugins","DEV9",szValue,szIniFile); - sprintf(szValue,"%s",winConfig.USB); - WritePrivateProfileString("Plugins","USB",szValue,szIniFile); - sprintf(szValue,"%s",winConfig.FW); - WritePrivateProfileString("Plugins","FW",szValue,szIniFile); - - //cpu - sprintf(szValue,"%u", Conf.Options); - WritePrivateProfileString("Cpu Options","Options",szValue,szIniFile); - sprintf(szValue,"%u",Conf.sseMXCSR); - WritePrivateProfileString("Cpu Options","sseMXCSR",szValue,szIniFile); - sprintf(szValue,"%u",Conf.sseVUMXCSR); - WritePrivateProfileString("Cpu Options","sseVUMXCSR",szValue,szIniFile); - sprintf(szValue,"%u",Conf.eeOptions); - WritePrivateProfileString("Cpu Options","eeOptions",szValue,szIniFile); - sprintf(szValue,"%u",Conf.vuOptions); - WritePrivateProfileString("Cpu Options","vuOptions",szValue,szIniFile); - - //Misc - sprintf(szValue,"%u",(int)Conf.Patch); - WritePrivateProfileString("Misc","Patch",szValue,szIniFile); - sprintf(szValue,"%x",varLog); - WritePrivateProfileString("Misc","varLog",szValue,szIniFile); - sprintf(szValue,"%u",Conf.Hacks); - WritePrivateProfileString("Misc","Hacks",szValue,szIniFile); - sprintf(szValue,"%u",Conf.GameFixes); - WritePrivateProfileString("Misc","GameFixes",szValue,szIniFile); + strcpy( tmpConf.GS, winConfig.GS ); + strcpy( tmpConf.SPU2, winConfig.SPU2 ); + strcpy( tmpConf.CDVD, winConfig.CDVD ); + strcpy( tmpConf.PAD1, winConfig.PAD1 ); + strcpy( tmpConf.PAD2, winConfig.PAD2 ); + strcpy( tmpConf.DEV9, winConfig.DEV9 ); + strcpy( tmpConf.USB, winConfig.USB ); + strcpy( tmpConf.FW, winConfig.FW ); + IniFileSaver().DoConfig( tmpConf ); } diff --git a/pcsx2/windows/resource.h b/pcsx2/windows/resource.h index a8548e498c..9481954f93 100644 --- a/pcsx2/windows/resource.h +++ b/pcsx2/windows/resource.h @@ -714,6 +714,7 @@ #define ID_HELP_HELP 40063 #define ID_PROFILER 40066 #define ID_CDVDPRINT 40067 +#define ID_CLOSEGS 40070 #define ID_CHEAT_FINDER_SHOW 40100 #define ID_CHEAT_BROWSER_SHOW 40101 #define ID_HACKS 40102 @@ -728,6 +729,6 @@ #define _APS_NEXT_RESOURCE_VALUE 141 #define _APS_NEXT_COMMAND_VALUE 40018 #define _APS_NEXT_CONTROL_VALUE 1314 -#define _APS_NEXT_SYMED_VALUE 103 +#define _APS_NEXT_SYMED_VALUE 104 #endif #endif diff --git a/pcsx2/x86/fast_routines.cpp b/pcsx2/x86/fast_routines.cpp index d0f5de2595..aa8f457bc4 100644 --- a/pcsx2/x86/fast_routines.cpp +++ b/pcsx2/x86/fast_routines.cpp @@ -31,7 +31,7 @@ 3dsdk.support@amd.com ******************************************************************************/ -#include +#include "PrecompiledHeader.h" #ifdef _MSC_VER #pragma warning(disable:4414) @@ -72,12 +72,10 @@ MEMCPY_AMD.CPP // This is faster than using software prefetch. The technique is great for // getting maximum read bandwidth, especially in DDR memory systems. -//#include +#include "Misc.h" // Inline assembly syntax for use with Visual C++ -#include "Misc.h" - #if defined(_MSC_VER) #ifdef _DEBUG diff --git a/pcsx2/x86/iCOP2.cpp b/pcsx2/x86/iCOP2.cpp index fac402cfde..3d60062d04 100644 --- a/pcsx2/x86/iCOP2.cpp +++ b/pcsx2/x86/iCOP2.cpp @@ -81,12 +81,12 @@ void recV##f( s32 info ) { \ void rec_C2UNK( s32 info ) { - Console::Error("Cop2 bad opcode: %x",cpuRegs.code); + Console::Error("Cop2 bad opcode: %x", params cpuRegs.code); } void _vuRegs_C2UNK(VURegs * VU, _VURegsNum *VUregsn) { - Console::Error("Cop2 bad _vuRegs code:%x",cpuRegs.code); + Console::Error("Cop2 bad _vuRegs code:%x", params cpuRegs.code); } void recCOP2(s32 info); diff --git a/pcsx2/x86/iHw.cpp b/pcsx2/x86/iHw.cpp index fc9216d40b..8de6679629 100644 --- a/pcsx2/x86/iHw.cpp +++ b/pcsx2/x86/iHw.cpp @@ -40,7 +40,7 @@ extern int sio_count; int hwConstRead8(u32 x86reg, u32 mem, u32 sign) { if( mem >= 0x10000000 && mem < 0x10008000 ) - DevCon::WriteLn("hwRead8 to %x", mem); + DevCon::WriteLn("hwRead8 to %x", params mem); if ((mem & 0xffffff0f) == 0x1000f200) { if(mem == 0x1000f260) { @@ -81,10 +81,10 @@ static u32 s_regreads[3] = {0x010200000, 0xbfff0000, 0xF0000102}; int hwConstRead16(u32 x86reg, u32 mem, u32 sign) { if( mem >= 0x10002000 && mem < 0x10008000 ) - DevCon::WriteLn("hwRead16 to %x", mem); + DevCon::WriteLn("hwRead16 to %x", params mem); if( mem >= 0x10000000 && mem < 0x10002000 ) - EECNT_LOG("cnt read to %x\n", mem); + EECNT_LOG("cnt read to %x\n", params mem); switch (mem) { case 0x10000000: @@ -487,7 +487,7 @@ static void __fastcall PrintDebug(u8 value) if (value == '\n') { sio_buffer[sio_count] = 0; - Console::MsgLn( Color_Cyan, sio_buffer ); + Console::WriteLn( Color_Cyan, sio_buffer ); sio_count = 0; } else { if (sio_count < 1023) { diff --git a/pcsx2/x86/iPsxHw.cpp b/pcsx2/x86/iPsxHw.cpp index 550e7602eb..f84bf4b73c 100644 --- a/pcsx2/x86/iPsxHw.cpp +++ b/pcsx2/x86/iPsxHw.cpp @@ -1149,7 +1149,7 @@ int psxHw4ConstRead8(u32 x86reg, u32 add, u32 sign) { case 0x1f402039: CONSTREAD8_CALL((uptr)cdvdRead39); return 1; case 0x1f40203A: CONSTREAD8_CALL((uptr)cdvdRead3A); return 1; default: - Console::Notice("*Unknown 8bit read at address %lx\n", add); + Console::Notice("*Unknown 8bit read at address %lx", params add); XOR32RtoR(x86reg, x86reg); return 0; } @@ -1173,7 +1173,7 @@ void psxHw4ConstWrite8(u32 add, int mmreg) { case 0x1f402018: CONSTWRITE_CALL(cdvdWrite18); return; case 0x1f40203A: CONSTWRITE_CALL(cdvdWrite3A); return; default: - Console::Notice("*Unknown 8bit write at address %lx\n", add); + Console::Notice("*Unknown 8bit write at address %lx", params add); return; } } diff --git a/pcsx2/x86/iR3000A.cpp b/pcsx2/x86/iR3000A.cpp index a049526637..d711888338 100644 --- a/pcsx2/x86/iR3000A.cpp +++ b/pcsx2/x86/iR3000A.cpp @@ -568,7 +568,7 @@ static int recInit() { if( recRAM == NULL || recROM == NULL || recROM1 == NULL || psxRecLUT == NULL || recBlocks == NULL || s_pInstCache == NULL ) { - Console::Alert("Error allocating memory"); + Msgbox::Alert("Error allocating memory"); return -1; } @@ -596,7 +596,7 @@ static int recInit() { static void recReset() { - DevCon::MsgLn("IOP Recompiler data reset"); + DevCon::WriteLn("IOP Recompiler data reset"); memset(recRAM, 0, sizeof(BASEBLOCK)/4*0x200000); memset(recROM, 0, sizeof(BASEBLOCK)/4*0x400000); diff --git a/pcsx2/x86/iVUzerorec.cpp b/pcsx2/x86/iVUzerorec.cpp index 65010e3b85..a644d2c8ff 100644 --- a/pcsx2/x86/iVUzerorec.cpp +++ b/pcsx2/x86/iVUzerorec.cpp @@ -352,7 +352,7 @@ void SuperVUInit(int vuindex) if( s_recVUMem == NULL ) { - Console::Error( "SuperVU Error > failed to allocate recompiler memory (addr: 0x%x)", (u32)s_recVUMem ); + Console::Error( "SuperVU Error > failed to allocate recompiler memory (addr: 0x%x)", params (u32)s_recVUMem ); throw Exception::OutOfMemory( "Could not reserve memory for the SuperVU." ); } @@ -1150,7 +1150,7 @@ static VuBaseBlock* SuperVUBuildBlocks(VuBaseBlock* parent, u32 startpc, const V ((ppprevinst->regs[0].VIwrite & pinst->regs[0].VIread) & 0xffff) == ((ppprevinst->regs[0].VIwrite & pprevinst->regs[0].VIread) & 0xffff) && !(ppprevinst->regs[0].VIread&((1<startpc); + Console::WriteLn("supervu: 2 cycle branch delay detected: %x %x", params pc, s_pFnHeader->startpc); // ignore if prev instruction is ILW or ILWR (xenosaga 2) lowercode = *(int*)&VU->Micro[pc-24]; @@ -2533,7 +2533,7 @@ void svudispfntemp() { //static int curesp; //__asm mov curesp, esp - Console::WriteLn("tVU: %x %x %x", s_svulast, s_vucount, s_vufnheader); + //Console::WriteLn("tVU: %x %x %x", s_svulast, s_vucount, s_vufnheader); if( g_curdebugvu ) iDumpVU1Registers(); else iDumpVU0Registers(); s_vucount++; diff --git a/pcsx2/x86/ir5900tables.cpp b/pcsx2/x86/ir5900tables.cpp index 6df7be347f..e1abcea1f9 100644 --- a/pcsx2/x86/ir5900tables.cpp +++ b/pcsx2/x86/ir5900tables.cpp @@ -40,7 +40,7 @@ //////////////////////////////////////////////////// void recNULL( void ) { - Console::Error("EE: Unimplemented op %x", cpuRegs.code); + Console::Error("EE: Unimplemented op %x", params cpuRegs.code); } namespace EE { namespace Dynarec @@ -70,13 +70,13 @@ namespace OpcodeImpl void recUnknown() { // TODO : Unknown ops should throw an exception. - Console::Error("EE: Unrecognized op %x", cpuRegs.code); + Console::Error("EE: Unrecognized op %x", params cpuRegs.code); } void recMMI_Unknown() { // TODO : Unknown ops should throw an exception. - Console::Error("EE: Unrecognized MMI op %x", cpuRegs.code); + Console::Error("EE: Unrecognized MMI op %x", params cpuRegs.code); } //////////////////////////////////////////////////// diff --git a/pcsx2/x86/ix86-32/iR5900-32.cpp b/pcsx2/x86/ix86-32/iR5900-32.cpp index 3528074d8e..7fc34d8322 100644 --- a/pcsx2/x86/ix86-32/iR5900-32.cpp +++ b/pcsx2/x86/ix86-32/iR5900-32.cpp @@ -143,7 +143,7 @@ static void iDumpBlock( int startpc, u8 * ptr ) u8 fpuused[33]; int numused, count, fpunumused; - Console::Status( "dump1 %x:%x, %x\n", startpc, pc, cpuRegs.cycle ); + Console::Status( "dump1 %x:%x, %x", params startpc, pc, cpuRegs.cycle ); #ifdef _WIN32 CreateDirectory("dumps", NULL); sprintf_s( filename, g_MaxPath, "dumps\\dump%.8X.txt", startpc); @@ -1441,7 +1441,7 @@ u32 g_sseVUMXCSR = DEFAULT_sseVUMXCSR; void SetCPUState(u32 sseMXCSR, u32 sseVUMXCSR) { - //Console::Alert("SetCPUState: Config.sseMXCSR = %x; Config.sseVUMXCSR = %x \n", Config.sseMXCSR, Config.sseVUMXCSR); + //Msgbox::Alert("SetCPUState: Config.sseMXCSR = %x; Config.sseVUMXCSR = %x \n", Config.sseMXCSR, Config.sseVUMXCSR); // SSE STATE // // WARNING: do not touch unless you know what you are doing @@ -1499,11 +1499,23 @@ static void recInit() // ... then why don't we care to check if they are or not? (air) if( recMem == NULL ) - recMem = (u8*)SysMmap(0x0d000000, REC_CACHEMEM+0x1000); + { + const uint cachememsize = REC_CACHEMEM+0x1000; - // This is ugly, but GCC is asking for a cast. - if( recMem == NULL ) - throw Exception::OutOfMemory("R5900-32 failed to allocate recompiler memory."); + // try an arbitrary address first, and if it doesn't work, try NULL. + recMem = (u8*)SysMmap(0x0d000000, cachememsize ); + if( recMem == NULL || ((uptr)recMem > 0x80000000) ) + { + SysMunmap( recMem, cachememsize ); + recMem = (u8*)SysMmap( NULL, REC_CACHEMEM+0x1000 ); + + if( recMem == NULL || ((uptr)recMem > 0x80000000) ) + { + SysMunmap( recMem, cachememsize ); + throw Exception::OutOfMemory( "R5900-32 failed to allocate recompiler memory." ); + } + } + } // 32 alignment necessary if( recRAM == NULL ) @@ -1570,14 +1582,14 @@ static void recInit() SuperVUInit(-1); - //Console::Alert("recInit: Config.sseMXCSR = %x; Config.sseVUMXCSR = %x \n", Config.sseMXCSR, Config.sseVUMXCSR); + //Msgbox::Alert("recInit: Config.sseMXCSR = %x; Config.sseVUMXCSR = %x \n", Config.sseMXCSR, Config.sseVUMXCSR); SetCPUState(Config.sseMXCSR, Config.sseVUMXCSR); } //////////////////////////////////////////////////// static void recReset( void ) { - DevCon::MsgLn( "EE Recompiler data reset" ); + DevCon::WriteLn( "EE Recompiler data reset" ); s_nNextBlock = 0; maxrecmem = 0; @@ -2459,7 +2471,7 @@ static void checkcodefn() __asm__("movl %%eax, %0" : "=m"(pctemp) ); #endif - Console::Error("code changed! %x", pctemp); + Console::Error("code changed! %x", params pctemp); assert(0); } @@ -2528,7 +2540,7 @@ void recompileNextInstruction(int delayslot) recClearMem(pblock); x86Ptr = oldX86; if( delayslot ) - Console::Notice("delay slot %x", pc); + Console::Notice("delay slot %x", params pc); } } } @@ -2635,7 +2647,7 @@ void recompileNextInstruction(int delayslot) case 1: switch(_Rt_) { case 0: case 1: case 2: case 3: case 0x10: case 0x11: case 0x12: case 0x13: - Console::Notice("branch %x in delay slot!", cpuRegs.code); + Console::Notice("branch %x in delay slot!", params cpuRegs.code); _clearNeededX86regs(); _clearNeededMMXregs(); _clearNeededXMMregs(); @@ -2644,7 +2656,7 @@ void recompileNextInstruction(int delayslot) break; case 2: case 3: case 4: case 5: case 6: case 7: case 0x14: case 0x15: case 0x16: case 0x17: - Console::Notice("branch %x in delay slot!", cpuRegs.code); + Console::Notice("branch %x in delay slot!", params cpuRegs.code); _clearNeededX86regs(); _clearNeededMMXregs(); _clearNeededXMMregs(); @@ -2808,7 +2820,7 @@ void __fastcall dyna_block_discard(u32 start,u32 sz) #else __asm__("push %ebp\n"); #endif - Console::WriteLn("dyna_block_discard %08X , count %d",start,sz); + Console::WriteLn("dyna_block_discard %08X , count %d", params start,sz); Cpu->Clear(start,sz); #ifdef _MSC_VER __asm pop ebp; @@ -2838,7 +2850,7 @@ void recRecompile( u32 startpc ) recReset(); } if ( ( (uptr)recStackPtr - (uptr)recStack ) >= RECSTACK_SIZE-0x100 ) { - DevCon::MsgLn("stack reset"); + DevCon::WriteLn("stack reset"); recReset(); } @@ -3273,7 +3285,7 @@ StartRecomp: stg-=4; lpc+=4; } - DbgCon::WriteLn("Manual block @ %08X : %08X %d %d %d %d", + DbgCon::WriteLn("Manual block @ %08X : %08X %d %d %d %d", params startpc,inpage_ptr,pgsz,0x1000-inpage_offs,inpage_sz,sz*4); } } diff --git a/pcsx2/x86/ix86-32/iR5900LoadStore.cpp b/pcsx2/x86/ix86-32/iR5900LoadStore.cpp index a14178d54f..72c300da4c 100644 --- a/pcsx2/x86/ix86-32/iR5900LoadStore.cpp +++ b/pcsx2/x86/ix86-32/iR5900LoadStore.cpp @@ -191,7 +191,7 @@ void assertmem() { __asm mov s_tempaddr, ecx __asm mov s_bCachingMem, edx - Console::Error("%x(%x) not mem write!", s_tempaddr, s_bCachingMem); + Console::Error("%x(%x) not mem write!", params s_tempaddr, s_bCachingMem); assert(0); } diff --git a/pcsx2/xmlpatchloader.cpp b/pcsx2/xmlpatchloader.cpp index 46f0dd73d1..06727c626e 100644 --- a/pcsx2/xmlpatchloader.cpp +++ b/pcsx2/xmlpatchloader.cpp @@ -15,10 +15,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ -#include -#include -#include -#include +#include "PrecompiledHeader.h" using namespace std; @@ -78,10 +75,10 @@ Patch Patch::operator =(const Patch&p) vector groups; vector patches; -int LoadPatch(char *crc) +int LoadPatch( const string& crc) { char pfile[256]; - sprintf(pfile,"patches\\%s.xml",crc); + sprintf(pfile,"patches\\%S.xml",&crc); patchnumber=0;