diff --git a/xbox1/RetroLaunch/Debug.cpp b/xbox1/RetroLaunch/Debug.cpp new file mode 100644 index 0000000000..1f94d72466 --- /dev/null +++ b/xbox1/RetroLaunch/Debug.cpp @@ -0,0 +1,83 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#include "Global.h" +#include "Debug.h" + +CDebug g_debug; + +CDebug::CDebug(void) +{ + iLine = 1; + m_bFileOpen = false; +} + +CDebug::~CDebug(void) +{ +} + +void CDebug::Print(char *szMessage, ...) +{ + char szMsg[512]; + va_list vaArgList; + string szDebugFile ("D:\\debug.log");//(FixPath(PathRoot() + "debug.log")); + + va_start(vaArgList, szMessage); + vsprintf(szMsg, szMessage, vaArgList); + va_end(vaArgList); + + OutputDebugStringA(IntToString(iLine).c_str()); + OutputDebugStringA(": "); + OutputDebugStringA(szMsg); + OutputDebugStringA("\n\n"); + +#ifdef WIN32 + cout << IntToString(iLine)<< ": " << szMsg << endl << endl; +#endif + +//#ifdef _LOG + //Open the log file, create one if it does not exist, append the data + if(!m_bFileOpen) + { + fp = fopen(szDebugFile.c_str(), "w+"); + m_bFileOpen = true; + } + else + { + fp = fopen(szDebugFile.c_str(), "a+"); + } + + //print the data to the log file + fprintf(fp, IntToString(iLine).c_str()); + fprintf(fp, ": "); + fprintf(fp, szMsg); + fprintf(fp, "\r\n\r\n"); + + //close the file + fclose(fp); +//#endif //_LOG + + iLine ++; +} + + +string CDebug::IntToString(int value) +{ + stringstream ss; + + ss << value; + + return ss.str(); +} diff --git a/xbox1/RetroLaunch/Debug.h b/xbox1/RetroLaunch/Debug.h new file mode 100644 index 0000000000..5506100f44 --- /dev/null +++ b/xbox1/RetroLaunch/Debug.h @@ -0,0 +1,41 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#ifndef _DEBUG_H__DASH_ +#define _DEBUG_H__DASH_ + +#if _MSC_VER > 1000 +#pragma once +#endif //_MSC_VER > 1000 + +class CDebug +{ +public: + CDebug(); + ~CDebug(); + + void Print(char *szMessage, ...); + string IntToString(int value); + +private: + int iLine; + FILE *fp; + bool m_bFileOpen; + +}; + +extern CDebug g_debug; + +#endif //_DEBUG_H__DASH_ \ No newline at end of file diff --git a/xbox1/RetroLaunch/Font.cpp b/xbox1/RetroLaunch/Font.cpp new file mode 100644 index 0000000000..e217735a8f --- /dev/null +++ b/xbox1/RetroLaunch/Font.cpp @@ -0,0 +1,229 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + + +#ifdef _XBOX +#include "Font.h" + +#include + +Font g_font; + +Font::Font(void) +{ + m_pFont = NULL; +} + +Font::~Font(void) +{ + if (m_pFont) + m_pFont->Release(); +} + +bool Font::Create() +{ //Hardcoded + return Create("D:\\Media\\arial.ttf"); +} + +bool Font::Create(const string &szTTFFilename) +{ + if (m_pFont) + m_pFont->Release(); + + word *wcPathBuf = StringToWChar(szTTFFilename); + g_hResult = XFONT_OpenTrueTypeFont(wcPathBuf, 256 * 1024, &m_pFont); + + delete [] wcPathBuf; + + if (FAILED(g_hResult)) + return false; + + return true; +} + +void Font::Render(const string &str, int x, int y, dword height, dword style, D3DXCOLOR color, int maxWidth, bool fade, Align alignment) +{ + CSurface texture; + RenderToTexture(texture, str, height, style, color, maxWidth, fade); + + if (alignment != Left) + { + word *wcBuf = StringToWChar(str); + dword dwRequiredWidth; + m_pFont->GetTextExtent(wcBuf, -1, &dwRequiredWidth); + delete [] wcBuf; + + if (alignment == Center) + { + x -= (dwRequiredWidth / 2); + } + else if (alignment == Right) + { + x -= dwRequiredWidth; + } + } + + texture.Render(x, y); +} + +void Font::RenderToTexture(CSurface &texture, const string &str, dword height, dword style, D3DXCOLOR color, int maxWidth, bool fade) +{ + if (m_pFont == NULL) + return; + + m_pFont->SetTextHeight(height); + m_pFont->SetTextStyle(style); + m_pFont->SetTextColor(color); + + dword dwMaxWidth = (maxWidth <= 0) ? 1000 : maxWidth; + + // get the exact width and height required to display the string + dword dwRequiredWidth = GetRequiredWidth(str, height, style); + dword dwRequiredHeight = GetRequiredHeight(str, height, style);; + + // calculate the texture width and height needed to display the font + dword dwTextureWidth = dwRequiredWidth * 2; + dword dwTextureHeight = dwRequiredHeight * 2; + { + // because the textures are swizzled we make sure + // the dimensions are a power of two + for(dword wmask = 1; dwTextureWidth &(dwTextureWidth - 1); wmask = (wmask << 1 ) + 1) + { + dwTextureWidth = (dwTextureWidth + wmask) & ~wmask; + } + for(dword hmask = 1; dwTextureHeight &(dwTextureHeight - 1); hmask = (hmask << 1) + 1) + { + dwTextureHeight = ( dwTextureHeight + hmask ) & ~hmask; + } + + // also enforce a minimum pitch of 64 bytes + dwTextureWidth = max(64 / XGBytesPerPixelFromFormat(D3DFMT_A8R8G8B8), dwTextureWidth); + } + + // create an temporary image surface to render to + D3DSurface *pTempSurface; + g_video.m_pD3DDevice->CreateImageSurface(dwTextureWidth, dwTextureHeight, D3DFMT_LIN_A8R8G8B8, &pTempSurface); + + // clear the temporary surface + { + D3DLOCKED_RECT tmpLr; + pTempSurface->LockRect(&tmpLr, NULL, 0); + memset(tmpLr.pBits, 0, dwTextureWidth * dwTextureHeight * XGBytesPerPixelFromFormat(D3DFMT_A8R8G8B8)); + pTempSurface->UnlockRect(); + } + + // render the text to the temporary surface + word *wcBuf = StringToWChar(str); + m_pFont->TextOut(pTempSurface, wcBuf, -1, 0, 0); + delete [] wcBuf; + + // create the texture that will be drawn to the screen + texture.Destroy(); + texture.Create(dwTextureWidth, dwTextureHeight); + + // copy from the temporary surface to the final texture + { + D3DLOCKED_RECT tmpLr; + D3DLOCKED_RECT txtLr; + + pTempSurface->LockRect(&tmpLr, NULL, 0); + texture.GetTexture()->LockRect(0, &txtLr, NULL, 0); + + if (fade) + { + // draw the last 35 pixels of the string fading out to max width or texture width + dword dwMinFadeDistance = min(static_cast(dwTextureWidth * 0.35), 35); + dword dwFadeStart = min(dwTextureWidth, dwMaxWidth - dwMinFadeDistance); + dword dwFadeEnd = min(dwTextureWidth, dwMaxWidth); + dword dwFadeDistance = dwFadeEnd - dwFadeStart; + + for (dword h = 0; h < dwTextureHeight; h++) + { + for (dword w = 0; w < dwFadeDistance; w++) + { + dword *pColor = reinterpret_cast(tmpLr.pBits); + dword offset = (h * dwTextureWidth) + (dwFadeStart + w); + + D3DXCOLOR color = D3DXCOLOR(pColor[offset]); + color.a = color.a * (1.0f - static_cast(w) / static_cast(dwFadeDistance)); + pColor[offset] = color; + } + } + } + + // dont draw anything > than max width + for (dword h = 0; h < dwTextureHeight; h++) + { + for (dword w = min(dwTextureWidth, dwMaxWidth); w < dwTextureWidth; w++) + { + dword *pColor = reinterpret_cast(tmpLr.pBits); + dword offset = (h * dwTextureWidth) + w; + + D3DXCOLOR color = D3DXCOLOR(pColor[offset]); + color.a = 0.0; + pColor[offset] = color; + } + } + + // copy and swizzle the linear surface to the swizzled texture + XGSwizzleRect(tmpLr.pBits, tmpLr.Pitch, NULL, txtLr.pBits, dwTextureWidth, dwTextureHeight, NULL, 4); + + texture.GetTexture()->UnlockRect(0); + pTempSurface->UnlockRect(); + } + + pTempSurface->Release(); +} + +int Font::GetRequiredWidth(const string &str, dword height, dword style) +{ + word *wcBuf = StringToWChar(str); + dword reqWidth; + + m_pFont->SetTextHeight(height); + m_pFont->SetTextStyle(style); + m_pFont->GetTextExtent(wcBuf, -1, &reqWidth); + + delete [] wcBuf; + + return reqWidth; +} + +int Font::GetRequiredHeight(const string &str, dword height, dword style) +{ + word *wcBuf = StringToWChar(str); + dword reqHeight; + + m_pFont->SetTextHeight(height); + m_pFont->SetTextStyle(style); + m_pFont->GetFontMetrics(&reqHeight, NULL); + + delete [] wcBuf; + + return reqHeight; +} + + +word *Font::StringToWChar(const string &str) +{ + word *retVal = new word[(str.length() + 1) * 2]; + memset(retVal, 0, (str.length() + 1) * 2 * sizeof(word)); + + if (str.length() > 0) + mbstowcs(retVal, str.c_str(), str.length()); + + return retVal; +} +#endif \ No newline at end of file diff --git a/xbox1/RetroLaunch/Font.h b/xbox1/RetroLaunch/Font.h new file mode 100644 index 0000000000..3126ee2c9d --- /dev/null +++ b/xbox1/RetroLaunch/Font.h @@ -0,0 +1,53 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#pragma once +#ifdef _XBOX +#include "Global.h" +#include "Surface.h" + +#define XFONT_TRUETYPE // use true type fonts +#include + +enum Align +{ + Left, + Center, + Right +}; + +class Font +{ +public: + Font(void); + ~Font(void); + + bool Create(); + bool Create(const string &szTTFFilename); + + void Render(const string &str, int x, int y, dword height, dword style = XFONT_NORMAL, D3DXCOLOR color = D3DCOLOR_XRGB(0, 0, 0), int dwMaxWidth = -1, bool fade = false, Align alignment = Left); + void RenderToTexture(CSurface &texture, const string &str, dword height, dword style = XFONT_NORMAL, D3DXCOLOR color = D3DCOLOR_XRGB(0, 0, 0), int maxWidth = -1, bool fade = false); + + int GetRequiredWidth(const string &str, dword height, dword style); + int GetRequiredHeight(const string &str, dword height, dword style); + + word *StringToWChar(const string &str); + +private: + XFONT *m_pFont; +}; + +extern Font g_font; +#endif \ No newline at end of file diff --git a/xbox1/RetroLaunch/Global.h b/xbox1/RetroLaunch/Global.h new file mode 100644 index 0000000000..f84ba2529f --- /dev/null +++ b/xbox1/RetroLaunch/Global.h @@ -0,0 +1,53 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _XBOX + #include + #include +#else + #pragma comment(lib,"d3d8.lib") + #pragma comment(lib,"d3dx8.lib") + #pragma comment(lib,"DxErr8.lib") + #define WIN32_LEAN_AND_MEAN + #include + #include + #include + #include +#endif + + +using namespace std; + +#define XBUILD "Launcher CE" + +typedef unsigned __int8 byte; +typedef unsigned __int16 word; +typedef unsigned __int32 dword; +typedef unsigned __int64 qword; + + diff --git a/xbox1/RetroLaunch/IniFile.cpp b/xbox1/RetroLaunch/IniFile.cpp new file mode 100644 index 0000000000..cfa7e04bbc --- /dev/null +++ b/xbox1/RetroLaunch/IniFile.cpp @@ -0,0 +1,152 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#include "SimpleIni.h" +#include "IniFile.h" + + +IniFile g_iniFile; + +//FIXME: SCREEN XPOS, YPOS, XSCALE, YSCALE should be floats! +//FIXME: Path for WIN32 + +IniFile::IniFile(void) +{ +} + +IniFile::~IniFile(void) +{ +} + +bool IniFile::Save(const string &szIniFileName) +{ + CSimpleIniA ini; + SI_Error rc; + ini.SetUnicode(true); + ini.SetMultiKey(true); + ini.SetMultiLine(true); + + //GENERAL SETTINGS + ini.SetBoolValue("GENERAL SETTINGS", "SHOW DEBUG INFO", m_currentIniEntry.bShowDebugInfo); + + //VIDEO SETTINGS + ini.SetBoolValue("VIDEO SETTINGS", "AUTOMATIC FRAME SKIP", m_currentIniEntry.bAutomaticFrameSkip); + + rc = ini.SaveFile(szIniFileName.c_str()); + + OutputDebugStringA(szIniFileName.c_str()); + + if (rc < 0) + { + OutputDebugStringA(" failed to save!\n"); + return false; + } + + OutputDebugStringA(" saved successfully!\n"); + return true; +} + +bool IniFile::Load(const string &szIniFileName) +{ + CSimpleIniA ini; + SI_Error rc; + ini.SetUnicode(true); + ini.SetMultiKey(true); + ini.SetMultiLine(true); + + rc = ini.LoadFile(szIniFileName.c_str()); + + if (rc < 0) + { + OutputDebugString("Failed to load "); + OutputDebugString(szIniFileName.c_str()); + OutputDebugString("\n"); + return false; + } + + OutputDebugStringA("Successfully loaded "); + OutputDebugString(szIniFileName.c_str()); + OutputDebugString("\n"); + + //GENERAL SETTINGS + m_currentIniEntry.bShowDebugInfo = ini.GetBoolValue("GENERAL SETTINGS", "SHOW DEBUG INFO", NULL ); + + //VIDEO SETTINGS + m_currentIniEntry.bAutomaticFrameSkip = ini.GetBoolValue("VIDEO SETTINGS", "AUTOMATIC FRAME SKIP", NULL ); + + return true; +} + +bool IniFile::CreateAndSaveDefaultIniEntry() +{ + //GENERAL SETTINGS + m_defaultIniEntry.bShowDebugInfo = false; + + //VIDEO SETTINGS + m_defaultIniEntry.bAutomaticFrameSkip = true; + + // our current ini is now the default ini + m_currentIniEntry = m_defaultIniEntry; + + // save the default ini + // FIXME! -> CD/DVD -> utility drive X: + Save("D:\\retrolaunch.ini"); + + return true; +} + + +bool IniFile::CheckForIniEntry() +{ + // try to load our ini file + if(!Load("D:\\retrolaunch.ini")) + { + // create a new one, if it doesn't exist + CreateAndSaveDefaultIniEntry(); + } + + return true; +} + + +bool IniFile::SaveTempRomFileName(const string &szFileName) +{ + CSimpleIniA ini; + SI_Error rc; + ini.SetUnicode(true); + ini.SetMultiKey(true); + ini.SetMultiLine(true); + + ini.SetValue("LAUNCHER", "ROM", szFileName.c_str()); + + DeleteFile("T:\\tmp.retro"); + rc = ini.SaveFile("T:\\tmp.retro"); + + OutputDebugStringA("T:\\tmp.retro"); + + if (rc < 0) + { + OutputDebugStringA(" failed to save!\n"); + return false; + } + + OutputDebugStringA(" saved successfully!\n"); + return true; + +} + + + + diff --git a/xbox1/RetroLaunch/IniFile.h b/xbox1/RetroLaunch/IniFile.h new file mode 100644 index 0000000000..dcc28505e7 --- /dev/null +++ b/xbox1/RetroLaunch/IniFile.h @@ -0,0 +1,98 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#pragma once +#include "Global.h" + +struct IniFileEntry +{ + //debug output + bool bShowDebugInfo; + + //automatic frame skip method + bool bAutomaticFrameSkip; + + //manual frame skip method (throttlespeed) + bool bManualFrameSkip; + + //number of frames to skip + dword dwNumFrameSkips; + + //sync audio to video + bool bSyncAudioToVideo; + + //vertical synchronization + bool bVSync; + + //flicker filter + dword dwFlickerFilter; + + //soft display filter + bool bSoftDisplayFilter; + + //texture filter + DWORD dwTextureFilter; + + //screen xpos + dword dwXPOS; + //screen ypos + dword dwYPOS; + //screen xscale + dword dwXWIDTH; + //screen yscale + dword dwYHEIGHT; + + //hide normal scroll 0 + bool bHideNBG0; + //hide normal scroll 1 + bool bHideNBG1; + //hide normal scroll 2 + bool bHideNBG2; + //hide normal scroll 3 + bool bHideNBG3; + //hide rotation scroll 0 + bool bHideRBG0; + //hide VDP1 + bool bHideVDP1; +}; + + +class IniFile +{ +public: + IniFile(); + ~IniFile(); + + bool Save(const string &szIniFileName); + bool SaveTempRomFileName(const string &szFileName); + bool Load(const string &szIniFileName); + bool CreateAndSaveDefaultIniEntry(); + bool CheckForIniEntry(); + + IniFileEntry m_currentIniEntry; + +private: + IniFileEntry m_defaultIniEntry; + + string szRomFileName; + +}; + +extern IniFile g_iniFile; + + + + + diff --git a/xbox1/RetroLaunch/Input.cpp b/xbox1/RetroLaunch/Input.cpp new file mode 100644 index 0000000000..fc79b5357c --- /dev/null +++ b/xbox1/RetroLaunch/Input.cpp @@ -0,0 +1,328 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#ifdef _XBOX +#include "Input.h" + +Input g_input; + +Input::Input(void) +{ + m_pollingParameters.fAutoPoll = TRUE; + m_pollingParameters.fInterruptOut = TRUE; + m_pollingParameters.bInputInterval = 8; + m_pollingParameters.bOutputInterval = 8; + m_lastTick = GetTickCount(); + m_buttonDelay = XBINPUT_PRESS_BUTTON_DELAY; + m_triggerDelay = XBINPUT_PRESS_TRIGGER_DELAY; + m_buttonPressed = false; +} + +Input::~Input(void) +{ +} + +bool Input::Create() +{ + XInitDevices(0, NULL); + + // get a mask of all currently available devices + dword dwDeviceMask = XGetDevices(XDEVICE_TYPE_GAMEPAD); + + // open the devices + for(dword i = 0; i < XGetPortCount(); i++) + { + ZeroMemory(&m_inputStates[i], sizeof(XINPUT_STATE)); + ZeroMemory(&m_gamepads[i], sizeof(XBGAMEPAD)); + + if(dwDeviceMask & (1 << i)) + { + // get a handle to the device + m_gamepads[i].hDevice = XInputOpen(XDEVICE_TYPE_GAMEPAD, i, + XDEVICE_NO_SLOT, &m_pollingParameters); + + // store capabilities of the device + XInputGetCapabilities(m_gamepads[i].hDevice, &m_gamepads[i].caps); + + // initialize last pressed buttons + XInputGetState(m_gamepads[i].hDevice, &m_inputStates[i]); + + m_gamepads[i].wLastButtons = m_inputStates[i].Gamepad.wButtons; + + for(dword b = 0; b < 8; b++) + { + m_gamepads[i].bLastAnalogButtons[b] = + // Turn the 8-bit polled value into a boolean value + (m_inputStates[i].Gamepad.bAnalogButtons[b] > XINPUT_GAMEPAD_MAX_CROSSTALK); + } + } + } + + return true; +} + +void Input::RefreshDevices() +{ + dword dwInsertions, dwRemovals; + + XGetDeviceChanges(XDEVICE_TYPE_GAMEPAD, reinterpret_cast(&dwInsertions), reinterpret_cast(&dwRemovals)); + + // loop through all gamepads + for(dword i = 0; i < XGetPortCount(); i++) + { + // handle removed devices + m_gamepads[i].bRemoved = (dwRemovals & (1 << i)) ? true : false; + + if(m_gamepads[i].bRemoved) + { + // if the controller was removed after XGetDeviceChanges but before + // XInputOpen, the device handle will be NULL + if(m_gamepads[i].hDevice) + XInputClose(m_gamepads[i].hDevice); + + m_gamepads[i].hDevice = NULL; + m_gamepads[i].Feedback.Rumble.wLeftMotorSpeed = 0; + m_gamepads[i].Feedback.Rumble.wRightMotorSpeed = 0; + } + + // handle inserted devices + m_gamepads[i].bInserted = (dwInsertions & (1 << i)) ? true : false; + + if(m_gamepads[i].bInserted) + { + m_gamepads[i].hDevice = XInputOpen(XDEVICE_TYPE_GAMEPAD, i, + XDEVICE_NO_SLOT, &m_pollingParameters ); + + // if the controller is removed after XGetDeviceChanges but before + // XInputOpen, the device handle will be NULL + if(m_gamepads[i].hDevice) + { + XInputGetCapabilities(m_gamepads[i].hDevice, &m_gamepads[i].caps); + + // initialize last pressed buttons + XInputGetState(m_gamepads[i].hDevice, &m_inputStates[i]); + + m_gamepads[i].wLastButtons = m_inputStates[i].Gamepad.wButtons; + + for(dword b = 0; b < 8; b++) + { + m_gamepads[i].bLastAnalogButtons[b] = + // Turn the 8-bit polled value into a boolean value + (m_inputStates[i].Gamepad.bAnalogButtons[b] > XINPUT_GAMEPAD_MAX_CROSSTALK); + } + } + } + } +} + +void Input::GetInput() +{ + RefreshDevices(); + + if (m_buttonPressed) + { + m_lastTick = GetTickCount(); + m_buttonPressed = false; + } + + // loop through all gamepads + for(dword i = 0; i < XGetPortCount(); i++) + { + // if we have a valid device, poll it's state and track button changes + if(m_gamepads[i].hDevice) + { + // read the input state + XInputGetState(m_gamepads[i].hDevice, &m_inputStates[i]); + + // copy gamepad to local structure + memcpy(&m_gamepads[i], &m_inputStates[i].Gamepad, sizeof(XINPUT_GAMEPAD)); + + // put xbox device input for the gamepad into our custom format + float fX1 = (m_gamepads[i].sThumbLX + 0.5f) / 32767.5f; + m_gamepads[i].fX1 = (fX1 >= 0.0f ? 1.0f : -1.0f) * + max(0.0f, (fabsf(fX1) - XBINPUT_DEADZONE) / (1.0f - XBINPUT_DEADZONE)); + + float fY1 = (m_gamepads[i].sThumbLY + 0.5f) / 32767.5f; + m_gamepads[i].fY1 = (fY1 >= 0.0f ? 1.0f : -1.0f) * + max(0.0f, (fabsf(fY1) - XBINPUT_DEADZONE) / (1.0f - XBINPUT_DEADZONE)); + + float fX2 = (m_gamepads[i].sThumbRX + 0.5f) / 32767.5f; + m_gamepads[i].fX2 = (fX2 >= 0.0f ? 1.0f : -1.0f) * + max(0.0f, (fabsf(fX2) - XBINPUT_DEADZONE) / (1.0f - XBINPUT_DEADZONE)); + + float fY2 = (m_gamepads[i].sThumbRY + 0.5f) / 32767.5f; + m_gamepads[i].fY2 = (fY2 >= 0.0f ? 1.0f : -1.0f) * + max(0.0f, (fabsf(fY2) - XBINPUT_DEADZONE) / (1.0f - XBINPUT_DEADZONE)); + + // get the boolean buttons that have been pressed since the last + // call. each button is represented by one bit. + m_gamepads[i].wPressedButtons = (m_gamepads[i].wLastButtons ^ m_gamepads[i].wButtons) & m_gamepads[i].wButtons; + m_gamepads[i].wLastButtons = m_gamepads[i].wButtons; + + // get the analog buttons that have been pressed or released since + // the last call. + for(dword b = 0; b < 8; b++) + { + // turn the 8-bit polled value into a boolean value + bool bPressed = (m_gamepads[i].bAnalogButtons[b] > XINPUT_GAMEPAD_MAX_CROSSTALK); + + if(bPressed) + m_gamepads[i].bPressedAnalogButtons[b] = !m_gamepads[i].bLastAnalogButtons[b]; + else + m_gamepads[i].bPressedAnalogButtons[b] = false; + + // store the current state for the next time + m_gamepads[i].bLastAnalogButtons[b] = bPressed; + } + } + } +} + +bool Input::IsButtonPressed(XboxButton button) +{ + if (m_lastTick + m_buttonDelay > GetTickCount()) + return false; + + bool buttonDown = false; + + switch (button) + { + case XboxLeftThumbLeft: + buttonDown = (m_gamepads[0].fX1 < -0.5); + break; + case XboxLeftThumbRight: + buttonDown = (m_gamepads[0].fX1 > 0.5); + break; + case XboxLeftThumbUp: + buttonDown = (m_gamepads[0].fY1 > 0.5); + break; + case XboxLeftThumbDown: + buttonDown = (m_gamepads[0].fY1 < -0.5); + break; + case XboxRightThumbLeft: + buttonDown = (m_gamepads[0].fX2 < -0.5); + break; + case XboxRightThumbRight: + buttonDown = (m_gamepads[0].fX2 > 0.5); + break; + case XboxRightThumbUp: + buttonDown = (m_gamepads[0].fY2 > 0.5); + break; + case XboxRightThumbDown: + buttonDown = (m_gamepads[0].fY2 < -0.5); + break; + case XboxDPadLeft: + buttonDown = ((m_gamepads[0].wButtons & XINPUT_GAMEPAD_DPAD_LEFT) != 0); + break; + case XboxDPadRight: + buttonDown = ((m_gamepads[0].wButtons & XINPUT_GAMEPAD_DPAD_RIGHT) != 0); + break; + case XboxDPadUp: + buttonDown = ((m_gamepads[0].wButtons & XINPUT_GAMEPAD_DPAD_UP) != 0); + break; + case XboxDPadDown: + buttonDown = ((m_gamepads[0].wButtons & XINPUT_GAMEPAD_DPAD_DOWN) != 0); + break; + case XboxStart: + buttonDown = ((m_gamepads[0].wButtons & XINPUT_GAMEPAD_START) != 0); + break; + case XboxBack: + buttonDown = ((m_gamepads[0].wButtons & XINPUT_GAMEPAD_BACK) != 0); + break; + case XboxA: + buttonDown = (m_gamepads[0].bAnalogButtons[XINPUT_GAMEPAD_A] > 30); + break; + case XboxB: + buttonDown = (m_gamepads[0].bAnalogButtons[XINPUT_GAMEPAD_B] > 30); + break; + case XboxX: + buttonDown = (m_gamepads[0].bAnalogButtons[XINPUT_GAMEPAD_X] > 30); + break; + case XboxY: + buttonDown = (m_gamepads[0].bAnalogButtons[XINPUT_GAMEPAD_Y] > 30); + break; + case XboxWhite: + buttonDown = (m_gamepads[0].bAnalogButtons[XINPUT_GAMEPAD_WHITE] > 30); + break; + case XboxBlack: + buttonDown = (m_gamepads[0].bAnalogButtons[XINPUT_GAMEPAD_BLACK] > 30); + break; + case XboxLeftThumbButton: + buttonDown = ((m_gamepads[0].wButtons & XINPUT_GAMEPAD_LEFT_THUMB) != 0); + break; + case XboxRightThumbButton: + buttonDown = ((m_gamepads[0].wButtons & XINPUT_GAMEPAD_RIGHT_THUMB) != 0); + break; + default: + return false; + } + + if (buttonDown) + { + m_buttonPressed = true; + return true; + } + + return false; +} + +byte Input::IsLTriggerPressed() +{ + if (m_lastTick + m_triggerDelay > GetTickCount()) + return 0; + + if (m_gamepads[0].bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER] < 30) + return 0; + else + { + m_buttonPressed = true; + return m_gamepads[0].bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER]; + } +} + +byte Input::IsRTriggerPressed() +{ + if (m_lastTick + m_triggerDelay > GetTickCount()) + return 0; + + if (m_gamepads[0].bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER] < 30) + return 0; + else + { + m_buttonPressed = true; + return m_gamepads[0].bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER]; + } +} + +DWORD Input::GetButtonDelay() +{ + return m_buttonDelay; +} + +void Input::SetButtonDelay(DWORD milliseconds) +{ + m_buttonDelay = milliseconds; +} + +DWORD Input::GetTriggerDelay() +{ + return m_triggerDelay; +} + +void Input::SetTriggerDelay(DWORD milliseconds) +{ + m_triggerDelay = milliseconds; +} +#endif \ No newline at end of file diff --git a/xbox1/RetroLaunch/Input.h b/xbox1/RetroLaunch/Input.h new file mode 100644 index 0000000000..c20ae81868 --- /dev/null +++ b/xbox1/RetroLaunch/Input.h @@ -0,0 +1,171 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#pragma once +#ifdef _XBOX +#include "Global.h" + +#define XBINPUT_DEADZONE 0.24f +#define XBINPUT_PRESS_BUTTON_DELAY 200 +#define XBINPUT_PRESS_TRIGGER_DELAY 100 + +struct XBGAMEPAD : public XINPUT_GAMEPAD +{ + // thumb stick values converted to range [-1,+1] + float fX1; + float fY1; + float fX2; + float fY2; + + // state of buttons tracked since last poll + word wLastButtons; + bool bLastAnalogButtons[8]; + word wPressedButtons; + bool bPressedAnalogButtons[8]; + + // rumble properties + XINPUT_RUMBLE Rumble; + XINPUT_FEEDBACK Feedback; + + // device properties + XINPUT_CAPABILITIES caps; + HANDLE hDevice; + + // flags for whether game pad was just inserted or removed + bool bInserted; + bool bRemoved; +}; + +#define XBOX_BUTTON_COUNT 23 + +enum XboxButton +{ + XboxLeftThumbLeft, + XboxLeftThumbRight, + XboxLeftThumbUp, + XboxLeftThumbDown, + + XboxRightThumbLeft, + XboxRightThumbRight, + XboxRightThumbUp, + XboxRightThumbDown, + + XboxDPadLeft, + XboxDPadRight, + XboxDPadUp, + XboxDPadDown, + + XboxStart, + XboxBack, + + XboxLeftThumbButton, + XboxRightThumbButton, + + XboxA, + XboxB, + XboxX, + XboxY, + + XboxBlack, + XboxWhite, + + XboxLeftTrigger, + XboxRightTrigger, +}; + +enum N64Button +{ + N64ThumbLeft, + N64ThumbRight, + N64ThumbUp, + N64ThumbDown, + + N64DPadLeft, + N64DPadRight, + N64DPadUp, + N64DPadDown, + + N64CButtonLeft, + N64CButtonRight, + N64CButtonUp, + N64CButtonDown, + + N64Start, + + N64A, + N64B, + + N64ZTrigger, + N64LeftTrigger, + N64RightTrigger +}; + + +enum SATURNButton +{ + SATURNDPadLeft, + SATURNDPadRight, + SATURNDPadUp, + SATURNDPadDown, + + SATURNA, + SATURNB, + SATURNX, + SATURNY, + SATURNC, + SATURNZ, + + SATURNStart, + + SATURNRightTrigger, + SATURNLeftTrigger +}; + +class Input +{ +public: + Input(void); + ~Input(void); + + bool Create(); + void GetInput(); + + bool IsButtonPressed(XboxButton button); + + byte IsLTriggerPressed(); + byte IsRTriggerPressed(); + + DWORD GetButtonDelay(); + void SetButtonDelay(DWORD milliseconds); + + DWORD GetTriggerDelay(); + void SetTriggerDelay(DWORD milliseconds); + +private: + void RefreshDevices(); + +private: + XINPUT_POLLING_PARAMETERS m_pollingParameters; + XINPUT_STATE m_inputStates[4]; + XBGAMEPAD m_gamepads[4]; + + bool m_buttonPressed; + DWORD m_buttonDelay; + DWORD m_triggerDelay; + DWORD m_lastTick; +}; + +extern Input g_input; +#endif \ No newline at end of file diff --git a/xbox1/RetroLaunch/IoSupport.cpp b/xbox1/RetroLaunch/IoSupport.cpp new file mode 100644 index 0000000000..0885ed76c2 --- /dev/null +++ b/xbox1/RetroLaunch/IoSupport.cpp @@ -0,0 +1,261 @@ +// IoSupport.cpp: implementation of the CIoSupport class. +// +////////////////////////////////////////////////////////////////////// +#ifdef _XBOX +#include "iosupport.h" +#include "undocumented.h" + +#include + +#define CTLCODE(DeviceType, Function, Method, Access) ( ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) ) +#define FSCTL_DISMOUNT_VOLUME CTLCODE( FILE_DEVICE_FILE_SYSTEM, 0x08, METHOD_BUFFERED, FILE_ANY_ACCESS ) + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// + +CIoSupport g_IOSupport; + +CIoSupport::CIoSupport() +{ + m_dwLastTrayState = 0; +} + +CIoSupport::~CIoSupport() +{ + +} + +// szDrive e.g. "D:" +// szDevice e.g. "Cdrom0" or "Harddisk0\Partition6" + +HRESULT CIoSupport::Mount(CHAR* szDrive, CHAR* szDevice) +{ + CHAR szSourceDevice[48]; + CHAR szDestinationDrive[16]; + + sprintf(szSourceDevice, "\\Device\\%s", szDevice); + sprintf(szDestinationDrive, "\\??\\%s", szDrive); + + STRING DeviceName = + { + strlen(szSourceDevice), + strlen(szSourceDevice) + 1, + szSourceDevice + }; + + STRING LinkName = + { + strlen(szDestinationDrive), + strlen(szDestinationDrive) + 1, + szDestinationDrive + }; + + IoCreateSymbolicLink(&LinkName, &DeviceName); + + return S_OK; +} + + + +// szDrive e.g. "D:" + +HRESULT CIoSupport::Unmount(CHAR* szDrive) +{ + char szDestinationDrive[16]; + sprintf(szDestinationDrive, "\\??\\%s", szDrive); + + STRING LinkName = + { + strlen(szDestinationDrive), + strlen(szDestinationDrive) + 1, + szDestinationDrive + }; + + IoDeleteSymbolicLink(&LinkName); + + return S_OK; +} + + + + + +HRESULT CIoSupport::Remount(CHAR* szDrive, CHAR* szDevice) +{ + CHAR szSourceDevice[48]; + sprintf(szSourceDevice, "\\Device\\%s", szDevice); + + Unmount(szDrive); + + ANSI_STRING filename; + OBJECT_ATTRIBUTES attributes; + IO_STATUS_BLOCK status; + HANDLE hDevice; + NTSTATUS error; + DWORD dummy; + + RtlInitAnsiString(&filename, szSourceDevice); + InitializeObjectAttributes(&attributes, &filename, OBJ_CASE_INSENSITIVE, NULL); + + if (!NT_SUCCESS(error = NtCreateFile(&hDevice, GENERIC_READ | + SYNCHRONIZE | FILE_READ_ATTRIBUTES, &attributes, &status, NULL, 0, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_OPEN, + FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT))) + { + return E_FAIL; + } + + if (!DeviceIoControl(hDevice, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &dummy, NULL)) + { + CloseHandle(hDevice); + return E_FAIL; + } + + CloseHandle(hDevice); + Mount(szDrive, szDevice); + + return S_OK; +} + +HRESULT CIoSupport::Remap(CHAR* szMapping) +{ + char szMap[32]; + strcpy(szMap, szMapping ); + + char* pComma = strstr(szMap, ","); + if (pComma) + { + *pComma = 0; + + // map device to drive letter + Unmount(szMap); + Mount(szMap, &pComma[1]); + return S_OK; + } + + return E_FAIL; +} + + +HRESULT CIoSupport::EjectTray() +{ + HalWriteSMBusValue(0x20, 0x0C, FALSE, 0); // eject tray + return S_OK; +} + +HRESULT CIoSupport::CloseTray() +{ + HalWriteSMBusValue(0x20, 0x0C, FALSE, 1); // close tray + return S_OK; +} + +DWORD CIoSupport::GetTrayState() +{ + HalReadSMCTrayState(&m_dwTrayState, &m_dwTrayCount); + + if(m_dwTrayState == TRAY_CLOSED_MEDIA_PRESENT) + { + if (m_dwLastTrayState != TRAY_CLOSED_MEDIA_PRESENT) + { + m_dwLastTrayState = m_dwTrayState; + return DRIVE_CLOSED_MEDIA_PRESENT; + } + else + { + return DRIVE_READY; + } + } + else if(m_dwTrayState == TRAY_CLOSED_NO_MEDIA) + { + m_dwLastTrayState = m_dwTrayState; + return DRIVE_CLOSED_NO_MEDIA; + } + else if(m_dwTrayState == TRAY_OPEN) + { + m_dwLastTrayState = m_dwTrayState; + return DRIVE_OPEN; + } + else + { + m_dwLastTrayState = m_dwTrayState; + } + + return DRIVE_NOT_READY; +} + +HRESULT CIoSupport::Shutdown() +{ + HalInitiateShutdown(); + return S_OK; +} + +HANDLE CIoSupport::CreateFile() +{ + ANSI_STRING filename; + OBJECT_ATTRIBUTES attributes; + IO_STATUS_BLOCK status; + HANDLE hDevice; + NTSTATUS error; + + RtlInitAnsiString(&filename, "\\Device\\Cdrom0"); + InitializeObjectAttributes(&attributes, &filename, OBJ_CASE_INSENSITIVE, NULL); + + if (!NT_SUCCESS(error = NtCreateFile(&hDevice, GENERIC_READ | + SYNCHRONIZE | FILE_READ_ATTRIBUTES, &attributes, &status, NULL, 0, + FILE_SHARE_READ, FILE_OPEN, FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT))) + { + return NULL; + } + + return hDevice; +} + +BOOL CIoSupport::GetFirstFile(CHAR* szFilename) +{ + ANSI_STRING filename; + OBJECT_ATTRIBUTES attributes; + IO_STATUS_BLOCK status; + HANDLE hDevice; + NTSTATUS error; + + RtlInitAnsiString(&filename, "\\Device\\Cdrom0"); + InitializeObjectAttributes(&attributes, &filename, OBJ_CASE_INSENSITIVE, NULL); + + if (!NT_SUCCESS(error = NtCreateFile(&hDevice, GENERIC_READ | + SYNCHRONIZE | FILE_READ_ATTRIBUTES, &attributes, &status, NULL, 0, + FILE_SHARE_READ, FILE_OPEN, FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT))) + { + OutputDebugString("Unable to open Cdrom0.\n"); + return FALSE; + } + + + CHAR* szBuffer = new CHAR[2048]; + DWORD dwRead = 0; + + SetFilePointer(hDevice, 19 * 2048, NULL, FILE_BEGIN); + if (!ReadFile(hDevice, szBuffer, 2048, &dwRead, NULL)) + { + OutputDebugString("Unable to read ISO9660 root directory.\n"); + CloseHandle(hDevice); + return FALSE; + } + + CloseHandle(hDevice); + szBuffer[2047] = 0; + + int offset = 0; + while (szBuffer[offset] == 0x22) offset += 0x22; + offset += 33; // jump to start of filename + + strcpy(szFilename, "#"); + strcat(szFilename, &szBuffer[offset]); + + if (szBuffer) + delete [] szBuffer; + + return TRUE; +} + +#endif \ No newline at end of file diff --git a/xbox1/RetroLaunch/IoSupport.h b/xbox1/RetroLaunch/IoSupport.h new file mode 100644 index 0000000000..2319c1b3ed --- /dev/null +++ b/xbox1/RetroLaunch/IoSupport.h @@ -0,0 +1,53 @@ +// IoSupport.h: interface for the CIoSupport class. +// +////////////////////////////////////////////////////////////////////// + +#if !defined(AFX_IOSUPPORT_H__F084A488_BD6E_49D5_8CD3_0BE62149DB40__INCLUDED_) +#define AFX_IOSUPPORT_H__F084A488_BD6E_49D5_8CD3_0BE62149DB40__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +#ifdef _XBOX +#include +#include "global.h" + +#define TRAY_OPEN 16 +#define TRAY_CLOSED_NO_MEDIA 64 +#define TRAY_CLOSED_MEDIA_PRESENT 96 + +#define DRIVE_OPEN 0 // Open... +#define DRIVE_NOT_READY 1 // Opening.. Closing... +#define DRIVE_READY 2 +#define DRIVE_CLOSED_NO_MEDIA 3 // CLOSED...but no media in drive +#define DRIVE_CLOSED_MEDIA_PRESENT 4 // Will be send once when the drive just have closed + +class CIoSupport +{ +public: + CIoSupport(); + virtual ~CIoSupport(); + + HRESULT Mount(CHAR* szDrive, CHAR* szDevice); + HRESULT Unmount(CHAR* szDrive); + + HRESULT Remount(CHAR* szDrive, CHAR* szDevice); + HRESULT Remap(CHAR* szMapping); + + DWORD GetTrayState(); + HRESULT EjectTray(); + HRESULT CloseTray(); + HRESULT Shutdown(); + + HANDLE CreateFile(); + BOOL GetFirstFile(CHAR* szFilename); + +private: + DWORD m_dwTrayState; + DWORD m_dwTrayCount; + DWORD m_dwLastTrayState; +}; + +extern CIoSupport g_IOSupport; +#endif +#endif // !defined(AFX_IOSUPPORT_H__F084A488_BD6E_49D5_8CD3_0BE62149DB40__INCLUDED_) diff --git a/xbox1/RetroLaunch/Launcher.cpp b/xbox1/RetroLaunch/Launcher.cpp new file mode 100644 index 0000000000..4b28736f7b --- /dev/null +++ b/xbox1/RetroLaunch/Launcher.cpp @@ -0,0 +1,72 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#include "Global.h" +#include "Video.h" +#include "IniFile.h" +#include "IoSupport.h" +#include "Input.h" +#include "Debug.h" +#include "Font.h" +#include "MenuManager.h" +#include "RomList.h" + +bool g_bExit = false; + +void __cdecl main() +{ + g_debug.Print("Starting Launcher CE\n"); + + // Set file cache size + XSetFileCacheSize(8 * 1024 * 1024); + + // Mount drives + g_IOSupport.Mount("A:", "cdrom0"); + g_IOSupport.Mount("E:", "Harddisk0\\Partition1"); + g_IOSupport.Mount("Z:", "Harddisk0\\Partition2"); + g_IOSupport.Mount("F:", "Harddisk0\\Partition6"); + g_IOSupport.Mount("G:", "Harddisk0\\Partition7"); + + + // Initialize Direct3D + if (!g_video.Create(NULL, false)) + return; + + // Parse ini file for settings + g_iniFile.CheckForIniEntry(); + + // Load the rom list if it isn't already loaded + if (!g_romList.IsLoaded()) { + g_romList.Load(); + } + + // Init input here + g_input.Create(); + + // Load the font here + g_font.Create(); + + // Build menu here (Menu state -> Main Menu) + g_menuManager.Create(); + + // Loop the app + while (!g_bExit) + { + g_video.BeginRender(); + g_input.GetInput(); + g_menuManager.Update(); + g_video.EndRender(); + } +} diff --git a/xbox1/RetroLaunch/MenuMain.cpp b/xbox1/RetroLaunch/MenuMain.cpp new file mode 100644 index 0000000000..5ee4114d5e --- /dev/null +++ b/xbox1/RetroLaunch/MenuMain.cpp @@ -0,0 +1,241 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#include "MenuMain.h" +#include "Debug.h" +#include "Font.h" +#include "RomList.h" +#include "Input.h" + + +CMenuMain g_menuMain; + +CMenuMain::CMenuMain() +{ + // we think that the rom list is unloaded until we know otherwise + m_bRomListLoadedState = false; + + ifstream stateFile; + stateFile.open("T:\\RomlistState.dat"); + + if (stateFile.is_open()) + { + int baseIndex; + int romListMode; + + stateFile >> baseIndex; + stateFile >> romListMode; + stateFile >> m_displayMode; + + g_romList.SetRomListMode(romListMode); + g_romList.m_iBaseIndex = baseIndex; + + stateFile.close(); + } + else + { + m_displayMode = List; + } +} + +CMenuMain::~CMenuMain() +{ + ofstream stateFile; + stateFile.open("T:\\RomlistState.dat"); + + stateFile << g_romList.GetBaseIndex() << endl; + stateFile << g_romList.GetRomListMode() << endl; + stateFile << m_displayMode << endl; + + stateFile.close(); +} + +bool CMenuMain::Create() +{ + g_debug.Print("CMenuMain::Create()"); + + // Title coords with color + m_menuMainTitle_x = 305; + m_menuMainTitle_y = 30; + m_menuMainTitle_c = 0xFFFFFFFF; + + // Load background image + m_menuMainBG.Create("Media\\menuMainBG.png"); + m_menuMainBG_x = 0; + m_menuMainBG_y = 0; + m_menuMainBG_w = 640; + m_menuMainBG_h = 480; + + // Init rom list coords + m_menuMainRomListPos_x = 100; + m_menuMainRomListPos_y = 100; + m_menuMainRomListSpacing = 20; + + // Load rom selector panel + m_menuMainRomSelectPanel.Create("Media\\menuMainRomSelectPanel.png"); + m_menuMainRomSelectPanel_x = m_menuMainRomListPos_x - 5; + m_menuMainRomSelectPanel_y = m_menuMainRomListPos_y - 2; + m_menuMainRomSelectPanel_w = 440; + m_menuMainRomSelectPanel_h = 20; + + m_romListSelectedRom = 0; + + //The first element in the romlist to render + m_romListBeginRender = 0; + + //The last element in the romlist to render + m_romListEndRender = 18; + + //The offset in the romlist + m_romListOffset = 0; + + if(m_romListEndRender > g_romList.GetRomListSize() - 1) + { + m_romListEndRender = g_romList.GetRomListSize() - 1; + } + + //Generate the rom list textures only once + vector::iterator i; + dword y = 0; + for (i = g_romList.m_romList.begin(); i != g_romList.m_romList.end(); i++) + { + Rom *rom = *i; + g_font.RenderToTexture(rom->GetTexture(), rom->GetFileName(), 18, XFONT_BOLD, 0xff808080, -1, false); + } + + return true; +} + + +void CMenuMain::Render() +{ + //CheckRomListState(); + + //Render background image + m_menuMainBG.Render(m_menuMainBG_x, m_menuMainBG_y); + + //Display some text + //g_font.Render("Retro Arch", m_menuMainTitle_x, m_menuMainTitle_y, 20, XFONT_NORMAL, m_menuMainTitle_c); + g_font.Render("Press RIGHT ANALOG STICK to exit. Press START to launch a rom.", 65, 450, 16, XFONT_NORMAL, m_menuMainTitle_c); + + //Begin with the rom selector panel + //FIXME: Width/Height needs to be current Rom texture width/height (or should we just leave it at a fixed size?) + m_menuMainRomSelectPanel.Render(m_menuMainRomSelectPanel_x, m_menuMainRomSelectPanel_y, m_menuMainRomSelectPanel_w, m_menuMainRomSelectPanel_h); + + dword dwSpacing = 0; + + for (int i = m_romListBeginRender; i <= m_romListEndRender; i++) + { + g_romList.GetRomAt(i + m_romListOffset)->GetTexture().Render(m_menuMainRomListPos_x, m_menuMainRomListPos_y + dwSpacing); + dwSpacing += m_menuMainRomListSpacing; + } +} + + +void CMenuMain::ProcessInput() +{ + //FIXME: The calculations might be wrong :-/ + if(g_input.IsButtonPressed(XboxDPadDown) || g_input.IsButtonPressed(XboxLeftThumbDown) || g_input.IsRTriggerPressed()) + { + + if(m_romListSelectedRom < g_romList.GetRomListSize()) + { + + if(m_menuMainRomSelectPanel_y < (m_menuMainRomListPos_y + (m_menuMainRomListSpacing * m_romListEndRender))) + { + m_menuMainRomSelectPanel_y += m_menuMainRomListSpacing; + m_romListSelectedRom++; + g_debug.Print("SELECTED ROM: "); g_debug.Print("%d", m_romListSelectedRom); + } + + if(m_menuMainRomSelectPanel_y > (m_menuMainRomListPos_y + (m_menuMainRomListSpacing * (m_romListEndRender)))) + { + m_menuMainRomSelectPanel_y -= m_menuMainRomListSpacing; + m_romListSelectedRom++; + if(m_romListSelectedRom > g_romList.GetRomListSize() - 1) + { + m_romListSelectedRom = g_romList.GetRomListSize() - 1; + } + + + g_debug.Print("SELECTED ROM AFTER CORRECTION: "); g_debug.Print("%d", m_romListSelectedRom); + + if(m_romListSelectedRom < g_romList.GetRomListSize() - 1 && m_romListOffset < g_romList.GetRomListSize() - 1 - m_romListEndRender - 1) { + m_romListOffset++; + g_debug.Print("OFFSET: "); g_debug.Print("%d", m_romListOffset); + } + } + +///////////////////////////////////////////// + + } + } + + // Go up and stop if less than 0 (item 0) + if(g_input.IsButtonPressed(XboxDPadUp) || g_input.IsButtonPressed(XboxLeftThumbUp) || g_input.IsLTriggerPressed()) + { + if(m_romListSelectedRom > -1) + { + if(m_menuMainRomSelectPanel_y > (m_menuMainRomListPos_y - m_menuMainRomListSpacing)) + { + m_menuMainRomSelectPanel_y -= m_menuMainRomListSpacing; + m_romListSelectedRom--; + g_debug.Print("SELECTED ROM: "); g_debug.Print("%d", m_romListSelectedRom); + } + + if(m_menuMainRomSelectPanel_y < (m_menuMainRomListPos_y - m_menuMainRomListSpacing)) + { + m_menuMainRomSelectPanel_y += m_menuMainRomListSpacing; + m_romListSelectedRom--; + if(m_romListSelectedRom < 0) + { + m_romListSelectedRom = 0; + } + + + g_debug.Print("SELECTED ROM AFTER CORRECTION: "); g_debug.Print("%d", m_romListSelectedRom); + + if(m_romListSelectedRom > 0 && m_romListOffset > 0) { + m_romListOffset--; + g_debug.Print("OFFSET: "); g_debug.Print("%d", m_romListOffset); + } + } + } + + + + } + + // Press A to launch, selected rom filename is saved into T:\\tmp.retro + if(g_input.IsButtonPressed(XboxA)) + { + //OutputDebugString(g_romList.GetRomAt(m_romListSelectedRom)->GetFileName().c_str()); + //OutputDebugString("\n"); + g_iniFile.SaveTempRomFileName(g_romList.GetRomAt(m_romListSelectedRom)->GetFileName()); + XLaunchNewImage("D:\\core.xbe", NULL); + } + + if (g_input.IsButtonPressed(XboxStart)) + { + XLaunchNewImage("D:\\core.xbe", NULL); + } + + if (g_input.IsButtonPressed(XboxRightThumbButton)) + { + LD_LAUNCH_DASHBOARD LaunchData = { XLD_LAUNCH_DASHBOARD_MAIN_MENU }; + XLaunchNewImage( NULL, (LAUNCH_DATA*)&LaunchData ); + } +} + diff --git a/xbox1/RetroLaunch/MenuMain.h b/xbox1/RetroLaunch/MenuMain.h new file mode 100644 index 0000000000..c8d9135fbd --- /dev/null +++ b/xbox1/RetroLaunch/MenuMain.h @@ -0,0 +1,99 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#pragma once +#include "Global.h" +#include "Surface.h" + +enum DisplayMode +{ + Box, + List +}; + +class CMenuMain +{ +public: +CMenuMain(); +~CMenuMain(); + +bool Create(); + +void Render(); + +void ProcessInput(); + +private: +/* +Texture, +_x = xpos, +_y = ypos, +_w = width, +_h = height, +_c = color, +*/ + +// Background image with coords +CSurface m_menuMainBG; +int m_menuMainBG_x; +int m_menuMainBG_y; +dword m_menuMainBG_w; +dword m_menuMainBG_h; + +// Rom selector panel with coords +CSurface m_menuMainRomSelectPanel; +int m_menuMainRomSelectPanel_x; +int m_menuMainRomSelectPanel_y; +dword m_menuMainRomSelectPanel_w; +dword m_menuMainRomSelectPanel_h; + +// Title coords with color +int m_menuMainTitle_x; +int m_menuMainTitle_y; +dword m_menuMainTitle_c; + +// Rom list coords +int m_menuMainRomListPos_x; +int m_menuMainRomListPos_y; +int m_menuMainRomListSpacing; + + + + +/** +* The Rom List menu buttons. The size can be variable so we use a list +*/ +//list m_romListButtons;//list +//no menu buttons, we will use plain textures +list m_romListButtons; + +/** +* The current mode the rom list is in +*/ +int m_displayMode; + +/** +* The current loaded state the rom list is in +*/ +bool m_bRomListLoadedState; + +int m_romListBeginRender; +int m_romListEndRender; +int m_romListSelectedRom; +int m_romListOffset; + +}; + +extern CMenuMain g_menuMain; diff --git a/xbox1/RetroLaunch/MenuManager.cpp b/xbox1/RetroLaunch/MenuManager.cpp new file mode 100644 index 0000000000..ef0853003f --- /dev/null +++ b/xbox1/RetroLaunch/MenuManager.cpp @@ -0,0 +1,98 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#include "MenuManager.h" +#include "MenuMain.h" +#include "Debug.h" +#include "Input.h" + + +CMenuManager g_menuManager; + +CMenuManager::CMenuManager() +{ +} + +CMenuManager::~CMenuManager() +{ +} + +bool CMenuManager::Create() +{ + //Create the MenuManager, set to Main Menu + g_debug.Print("Create MenuManager, set state to MENU_MAIN"); + SetMenuState(MENU_MAIN); + + return true; +} + +bool CMenuManager::SetMenuState(int nMenuID) +{ + m_pMenuID = nMenuID; + + switch (m_pMenuID) { + case MENU_MAIN: + //Create the Main Menu + g_menuMain.Create(); + break; + } + return true; +} + +void CMenuManager::Update() +{ + //Process overall input + ProcessInput(); + + switch (m_pMenuID) { + case MENU_MAIN: + + // Process menu specific input + g_menuMain.ProcessInput(); + + // Render the Main Menu + g_menuMain.Render(); + break; + } + +} + + +void CMenuManager::ProcessInput() +{ + //ADD: ProcessTarget -> switch to another menu + + //Return to Dashboard + if(g_input.IsLTriggerPressed() && + g_input.IsRTriggerPressed() && + g_input.IsButtonPressed(XboxBlack) && + g_input.IsButtonPressed(XboxWhite) && + g_input.IsButtonPressed(XboxBack) && + g_input.IsButtonPressed(XboxStart)) + { + + LD_LAUNCH_DASHBOARD LaunchData = { XLD_LAUNCH_DASHBOARD_MAIN_MENU }; + XLaunchNewImage( NULL, (LAUNCH_DATA*)&LaunchData ); + + } +} + + + +int CMenuManager::GetMenuState() +{ + return m_pMenuID; +} + diff --git a/xbox1/RetroLaunch/MenuManager.h b/xbox1/RetroLaunch/MenuManager.h new file mode 100644 index 0000000000..0e888299aa --- /dev/null +++ b/xbox1/RetroLaunch/MenuManager.h @@ -0,0 +1,50 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#pragma once + +#include "Global.h" + +enum eMenuState +{ + MENU_MAIN = 0, + MENU_SETTINGS_SELECT, + MENU_SETTINGS_EMU, + MENU_SETTINGS_AUDIO, + MENU_SETTINGS_SKIN, + MENU_LAUNCHER +}; + + +class CMenuManager +{ +public: +CMenuManager(); +~CMenuManager(); + +bool Create(); +bool SetMenuState(int nMenuID); +int GetMenuState(); +bool Destroy(); +void Update(); +void ProcessInput(); + + +private: +int m_pMenuID; + +}; + +extern CMenuManager g_menuManager; \ No newline at end of file diff --git a/xbox1/RetroLaunch/RetroLaunch.sln b/xbox1/RetroLaunch/RetroLaunch.sln new file mode 100644 index 0000000000..d2b910dcca --- /dev/null +++ b/xbox1/RetroLaunch/RetroLaunch.sln @@ -0,0 +1,33 @@ +Microsoft Visual Studio Solution File, Format Version 8.00 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RetroLaunch", "RetroLaunch.vcproj", "{14134C4E-7FD3-46F0-AD16-C32D952978EA}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + Debug = Debug + Profile = Profile + Profile_FastCap = Profile_FastCap + Release = Release + Release_LTCG = Release_LTCG + ReleaseTest = ReleaseTest + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {14134C4E-7FD3-46F0-AD16-C32D952978EA}.Debug.ActiveCfg = Debug|Xbox + {14134C4E-7FD3-46F0-AD16-C32D952978EA}.Debug.Build.0 = Debug|Xbox + {14134C4E-7FD3-46F0-AD16-C32D952978EA}.Profile.ActiveCfg = Profile|Xbox + {14134C4E-7FD3-46F0-AD16-C32D952978EA}.Profile.Build.0 = Profile|Xbox + {14134C4E-7FD3-46F0-AD16-C32D952978EA}.Profile_FastCap.ActiveCfg = Profile_FastCap|Xbox + {14134C4E-7FD3-46F0-AD16-C32D952978EA}.Profile_FastCap.Build.0 = Profile_FastCap|Xbox + {14134C4E-7FD3-46F0-AD16-C32D952978EA}.Release.ActiveCfg = Release|Xbox + {14134C4E-7FD3-46F0-AD16-C32D952978EA}.Release.Build.0 = Release|Xbox + {14134C4E-7FD3-46F0-AD16-C32D952978EA}.Release_LTCG.ActiveCfg = Release_LTCG|Xbox + {14134C4E-7FD3-46F0-AD16-C32D952978EA}.Release_LTCG.Build.0 = Release_LTCG|Xbox + {14134C4E-7FD3-46F0-AD16-C32D952978EA}.ReleaseTest.ActiveCfg = ReleaseTest|Xbox + {14134C4E-7FD3-46F0-AD16-C32D952978EA}.ReleaseTest.Build.0 = ReleaseTest|Xbox + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/xbox1/RetroLaunch/RetroLaunch.vcproj b/xbox1/RetroLaunch/RetroLaunch.vcproj new file mode 100644 index 0000000000..f2f561e265 --- /dev/null +++ b/xbox1/RetroLaunch/RetroLaunch.vcproj @@ -0,0 +1,447 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/xbox1/RetroLaunch/Rom.cpp b/xbox1/RetroLaunch/Rom.cpp new file mode 100644 index 0000000000..c05c93818c --- /dev/null +++ b/xbox1/RetroLaunch/Rom.cpp @@ -0,0 +1,76 @@ +/** + * Surreal 64 Launcher (C) 2003 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: email: buttza@hotmail.com, lantus@lantus-x.com + */ + +#include "Rom.h" +//#include "BoxArtTable.h" + +Rom::Rom() +{ + m_bLoaded = false; +} + +Rom::~Rom(void) +{ +} + +bool Rom::Load(const string &szFilename) +{ + if (m_bLoaded) + return true; + + m_szFilename = szFilename; + + // get the filename for the box art image + //FIXME: Add BoxArtTable.cpp/h, open iso file, grab header, extract ID ie. T-6003G, use for boxartfilename + { + m_szBoxArtFilename = "D:\\boxart\\default.jpg"; //g_boxArtTable.GetBoxArtFilename(m_dwCrc1); + } + + m_bLoaded = true; + + return true; +} + +bool Rom::LoadFromCache(const string &szFilename, const string &szBoxArtFilename) +{ + m_szFilename = szFilename; + m_szBoxArtFilename = szBoxArtFilename; + + m_bLoaded = true; + + return true; +} + +string Rom::GetFileName() +{ + return m_szFilename; +} + +string Rom::GetBoxArtFilename() +{ + return m_szBoxArtFilename; +} + +string Rom::GetComments() +{ + //return string(m_iniEntry->szComments); + return "blah"; +} + + +CSurface &Rom::GetTexture() +{ + return m_texture; +} \ No newline at end of file diff --git a/xbox1/RetroLaunch/Rom.h b/xbox1/RetroLaunch/Rom.h new file mode 100644 index 0000000000..11dce13713 --- /dev/null +++ b/xbox1/RetroLaunch/Rom.h @@ -0,0 +1,44 @@ +/** + * Surreal 64 Launcher (C) 2003 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: email: buttza@hotmail.com, lantus@lantus-x.com + */ + +#pragma once + +#include "Global.h" +#include "IniFile.h" +#include "Surface.h" + +class Rom +{ +public: + Rom(); + ~Rom(); + + bool Load(const string &szFilename); + bool LoadFromCache(const string &szFilename, const string &szBoxArtFilename); + + string GetFileName(); + string GetBoxArtFilename(); + string GetComments(); + + CSurface &GetTexture(); + +private: + string m_szFilename; + string m_szBoxArtFilename; + + bool m_bLoaded; + + CSurface m_texture; +}; diff --git a/xbox1/RetroLaunch/RomList.cpp b/xbox1/RetroLaunch/RomList.cpp new file mode 100644 index 0000000000..b22381959a --- /dev/null +++ b/xbox1/RetroLaunch/RomList.cpp @@ -0,0 +1,309 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#include "RomList.h" + +RomList g_romList; + +bool RLessThan(Rom *elem1, Rom *elem2) +{ + return (elem1->GetFileName() < elem2->GetFileName()); +} + +RomList::RomList(void) +{ + m_romListMode = All; + m_iBaseIndex = 0; + m_bLoaded = false; + m_szRomPath = "D:\\Roms\\"; +} + +RomList::~RomList(void) +{ + Destroy(); +} + +void RomList::Load() +{ + ifstream cacheFile; + + cacheFile.open("T:\\RomlistCache.dat"); + + // try and open the cache file, if it doesnt exist, generate the rom list + if (!cacheFile.is_open()) + { + Build(); + } + else + { + while (!cacheFile.eof()) + { + string szFilename; + string szBoxArtFilename; + + getline(cacheFile, szFilename); + getline(cacheFile, szBoxArtFilename); + + Rom *rom = new Rom(); + + bool bSuccess = rom->LoadFromCache(szFilename, szBoxArtFilename); + + if (bSuccess) + m_romList.push_back(rom); + else + delete rom; + } + + cacheFile.close(); + } + + m_bLoaded = true; +} + +void RomList::Save() +{ + vector::iterator i; + ofstream cacheFile; + + // open/overwrite the rom cache + cacheFile.open("T:\\RomlistCache.dat"); + + for (i = m_romList.begin(); i != m_romList.end(); i++) + { + Rom *rom = *i; + + cacheFile << rom->GetFileName() << endl; + cacheFile << rom->GetBoxArtFilename() << endl; + } + + cacheFile.close(); +} + +void RomList::Refresh() +{ + Destroy(); + DeleteFile("T:\\RomlistCache.dat"); + DeleteFile("T:\\RomlistState.dat"); +} + +bool RomList::IsLoaded() +{ + return m_bLoaded; +} + +void RomList::SetRomListMode(int mode) +{ + m_iBaseIndex = 0; + m_romListMode = mode; +} + +int RomList::GetRomListMode() +{ + return m_romListMode; +} + +void RomList::AddRomToList(Rom *rom, int mode) +{ + vector *pList; + + switch (mode) + { + case All: + pList = &m_romList; + break; + default: + return; + } + + // look to see if the rom is already in the list, we dont want duplicates + for (int i = 0; i < static_cast(pList->size()); i++) + { + if (rom == (*pList)[i]) + return; + } + + pList->push_back(rom); + sort(pList->begin(), pList->end(), RLessThan); +} + +void RomList::RemoveRomFromList(Rom *rom, int mode) +{ + vector *pList; + + switch (mode) + { + case All: + pList = &m_romList; + break; + default: + return; + } + + vector::iterator i; + + // look to see if the rom is already in the list, we dont want duplicates + for (i = pList->begin(); i != pList->end(); i++) + { + if (rom == *i) + { + pList->erase(i); + return; + } + } +} + +int RomList::GetBaseIndex() +{ + if (m_iBaseIndex > GetRomListSize() - 1) + m_iBaseIndex = GetRomListSize() - 1; + if (m_iBaseIndex < 0) + m_iBaseIndex = 0; + + return m_iBaseIndex; +} + +void RomList::SetBaseIndex(int index) +{ + if (index > GetRomListSize() - 1) + index = GetRomListSize() - 1; + if (index < 0) + index = 0; + + m_iBaseIndex = index; +} + +int RomList::GetRomListSize() +{ + switch (m_romListMode) + { + case All: + return m_romList.size(); + } + + return 0; +} + +Rom *RomList::GetRomAt(int index) +{ + switch (m_romListMode) + { + case All: + return m_romList[index]; + } + + return 0; +} + +int RomList::FindRom(Rom *rom, int mode) +{ + vector *pList; + + switch (mode) + { + case All: + pList = &m_romList; + break; + default: + return -1; + } + + for (int i = 0; i < static_cast(pList->size()); i++) + { + if (rom == (*pList)[i]) + return i; + } + + return -1; +} + +void RomList::CleanUpTextures() +{ + if (!IsLoaded()) + return; + + // keep the 25 textures above and below the base index + for (int i = 0; i < m_iBaseIndex - 25; i++) + { + m_romList[i]->GetTexture().Destroy(); + } + + for (int i = m_iBaseIndex + 25; i < GetRomListSize(); i++) + { + m_romList[i]->GetTexture().Destroy(); + } +} + +void RomList::DestroyAllTextures() +{ + vector::iterator i; + + for (i = m_romList.begin(); i != m_romList.end(); i++) + { + Rom *rom = *i; + rom->GetTexture().Destroy(); + } +} + +void RomList::Build() +{ + WIN32_FIND_DATA fd; + + HANDLE hFF = FindFirstFile((m_szRomPath + "*.*").c_str(), &fd); + + do + { + char ext[_MAX_EXT]; + + // get the filename extension + _splitpath((m_szRomPath + fd.cFileName).c_str(), + NULL, NULL, NULL, ext); + + if ( + stricmp(ext, ".bin") == 0 + || stricmp(ext, ".cue") == 0 + || stricmp(ext, ".iso") == 0 + || stricmp(ext, ".mdf") == 0 + || stricmp(ext, ".gba") == 0 + ) + { + Rom *rom = new Rom(); + bool bSuccess = rom->Load((m_szRomPath + fd.cFileName).c_str()); + + if (bSuccess) + m_romList.push_back(rom); + else + delete rom; + } + } while (FindNextFile(hFF, &fd)); + + sort(m_romList.begin(), m_romList.end(), RLessThan); + + m_bLoaded = true; +} + +void RomList::Destroy() +{ + m_bLoaded = false; + m_iBaseIndex = 0; + + vector::iterator i; + + for (i = m_romList.begin(); i != m_romList.end(); i++) + { + delete *i; + } + + m_romList.clear(); +} diff --git a/xbox1/RetroLaunch/RomList.h b/xbox1/RetroLaunch/RomList.h new file mode 100644 index 0000000000..3fa19615d4 --- /dev/null +++ b/xbox1/RetroLaunch/RomList.h @@ -0,0 +1,72 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#pragma once + +#include "Global.h" +#include "Rom.h" + +enum RomListMode +{ + All +}; + +class RomList +{ +public: + RomList(void); + virtual ~RomList(void); + + void Load(); + void Save(); + void Refresh(); + + bool IsLoaded(); + + void SetRomListMode(int mode); + int GetRomListMode(); + + void AddRomToList(Rom *rom, int mode); + void RemoveRomFromList(Rom *rom, int mode); + + int GetBaseIndex(); + void SetBaseIndex(int index); + + int GetRomListSize(); + + Rom *GetRomAt(int index); + int FindRom(Rom *rom, int mode); + + void CleanUpTextures(); + void DestroyAllTextures(); + + int m_iBaseIndex; + + vector m_romList; + +private: + void Build(); + void Destroy(); + +private: + + bool m_bLoaded; + + int m_romListMode; + + string m_szRomPath; +}; + +extern RomList g_romList; \ No newline at end of file diff --git a/xbox1/RetroLaunch/SimpleIni.h b/xbox1/RetroLaunch/SimpleIni.h new file mode 100644 index 0000000000..882289f6fc --- /dev/null +++ b/xbox1/RetroLaunch/SimpleIni.h @@ -0,0 +1,3262 @@ +/** @mainpage + + +
Library SimpleIni +
File SimpleIni.h +
Author Brodie Thiesfield [code at jellycan dot com] +
Source http://code.jellycan.com/simpleini/ +
Version 4.13 +
+ + Jump to the @link CSimpleIniTempl CSimpleIni @endlink interface documentation. + + @section intro INTRODUCTION + + This component allows an INI-style configuration file to be used on both + Windows and Linux/Unix. It is fast, simple and source code using this + component will compile unchanged on either OS. + + + @section features FEATURES + + - MIT Licence allows free use in all software (including GPL and commercial) + - multi-platform (Windows 95/98/ME/NT/2K/XP/2003, Windows CE, Linux, Unix) + - loading and saving of INI-style configuration files + - configuration files can have any newline format on all platforms + - liberal acceptance of file format + - key/values with no section + - removal of whitespace around sections, keys and values + - support for multi-line values (values with embedded newline characters) + - optional support for multiple keys with the same name + - optional case-insensitive sections and keys (for ASCII characters only) + - saves files with sections and keys in the same order as they were loaded + - preserves comments on the file, section and keys where possible. + - supports both char or wchar_t programming interfaces + - supports both MBCS (system locale) and UTF-8 file encodings + - system locale does not need to be UTF-8 on Linux/Unix to load UTF-8 file + - support for non-ASCII characters in section, keys, values and comments + - support for non-standard character types or file encodings + via user-written converter classes + - support for adding/modifying values programmatically + - compiles cleanly in the following compilers: + - Windows/VC6 (warning level 3) + - Windows/VC.NET 2003 (warning level 4) + - Windows/VC 2005 (warning level 4) + - Linux/gcc (-Wall) + + + @section usage USAGE SUMMARY + + -# Define the appropriate symbol for the converter you wish to use and + include the SimpleIni.h header file. If no specific converter is defined + then the default converter is used. The default conversion mode uses + SI_CONVERT_WIN32 on Windows and SI_CONVERT_GENERIC on all other + platforms. If you are using ICU then SI_CONVERT_ICU is supported on all + platforms. + -# Declare an instance the appropriate class. Note that the following + definitions are just shortcuts for commonly used types. Other types + (PRUnichar, unsigned short, unsigned char) are also possible. + +
Interface Case-sensitive Load UTF-8 Load MBCS Typedef +
SI_CONVERT_GENERIC +
char No Yes Yes #1 CSimpleIniA +
char Yes Yes Yes CSimpleIniCaseA +
wchar_t No Yes Yes CSimpleIniW +
wchar_t Yes Yes Yes CSimpleIniCaseW +
SI_CONVERT_WIN32 +
char No No #2 Yes CSimpleIniA +
char Yes Yes Yes CSimpleIniCaseA +
wchar_t No Yes Yes CSimpleIniW +
wchar_t Yes Yes Yes CSimpleIniCaseW +
SI_CONVERT_ICU +
char No Yes Yes CSimpleIniA +
char Yes Yes Yes CSimpleIniCaseA +
UChar No Yes Yes CSimpleIniW +
UChar Yes Yes Yes CSimpleIniCaseW +
+ #1 On Windows you are better to use CSimpleIniA with SI_CONVERT_WIN32.
+ #2 Only affects Windows. On Windows this uses MBCS functions and + so may fold case incorrectly leading to uncertain results. + -# Call Load() or LoadFile() to load and parse the INI configuration file + -# Access and modify the data of the file using the following functions + +
GetAllSections Return all section names +
GetAllKeys Return all key names within a section +
GetAllValues Return all values within a section & key +
GetSection Return all key names and values in a section +
GetSectionSize Return the number of keys in a section +
GetValue Return a value for a section & key +
SetValue Add or update a value for a section & key +
Delete Remove a section, or a key from a section +
+ -# Call Save() or SaveFile() to save the INI configuration data + + @section iostreams IO STREAMS + + SimpleIni supports reading from and writing to STL IO streams. Enable this + by defining SI_SUPPORT_IOSTREAMS before including the SimpleIni.h header + file. Ensure that if the streams are backed by a file (e.g. ifstream or + ofstream) then the flag ios_base::binary has been used when the file was + opened. + + @section multiline MULTI-LINE VALUES + + Values that span multiple lines are created using the following format. + +
+        key = <<
+
+    Note the following:
+    - The text used for ENDTAG can be anything and is used to find
+      where the multi-line text ends.
+    - The newline after ENDTAG in the start tag, and the newline
+      before ENDTAG in the end tag is not included in the data value.
+    - The ending tag must be on it's own line with no whitespace before
+      or after it.
+    - The multi-line value is modified at load so that each line in the value
+      is delimited by a single '\\n' character on all platforms. At save time
+      it will be converted into the newline format used by the current
+      platform.
+
+    @section comments COMMENTS
+
+    Comments are preserved in the file within the following restrictions:
+    - Every file may have a single "file comment". It must start with the
+      first character in the file, and will end with the first non-comment
+      line in the file.
+    - Every section may have a single "section comment". It will start
+      with the first comment line following the file comment, or the last
+      data entry. It ends at the beginning of the section.
+    - Every key may have a single "key comment". This comment will start
+      with the first comment line following the section start, or the file
+      comment if there is no section name.
+    - Comments are set at the time that the file, section or key is first
+      created. The only way to modify a comment on a section or a key is to
+      delete that entry and recreate it with the new comment. There is no
+      way to change the file comment.
+
+    @section save SAVE ORDER
+
+    The sections and keys are written out in the same order as they were
+    read in from the file. Sections and keys added to the data after the
+    file has been loaded will be added to the end of the file when it is
+    written. There is no way to specify the location of a section or key
+    other than in first-created, first-saved order.
+
+    @section notes NOTES
+
+    - To load UTF-8 data on Windows 95, you need to use Microsoft Layer for
+      Unicode, or SI_CONVERT_GENERIC, or SI_CONVERT_ICU.
+    - When using SI_CONVERT_GENERIC, ConvertUTF.c must be compiled and linked.
+    - When using SI_CONVERT_ICU, ICU header files must be on the include
+      path and icuuc.lib must be linked in.
+    - To load a UTF-8 file on Windows AND expose it with SI_CHAR == char,
+      you should use SI_CONVERT_GENERIC.
+    - The collation (sorting) order used for sections and keys returned from
+      iterators is NOT DEFINED. If collation order of the text is important
+      then it should be done yourself by either supplying a replacement
+      SI_STRLESS class, or by sorting the strings external to this library.
+    - Usage of the  header on Windows can be disabled by defining
+      SI_NO_MBCS. This is defined automatically on Windows CE platforms.
+
+
+    @section licence MIT LICENCE
+
+    The licence text below is the boilerplate "MIT Licence" used from:
+    http://www.opensource.org/licenses/mit-license.php
+
+    Copyright (c) 2006-2008, Brodie Thiesfield
+
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to deal
+    in the Software without restriction, including without limitation the rights
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the Software is furnished
+    to do so, subject to the following conditions:
+
+    The above copyright notice and this permission notice shall be included in
+    all copies or substantial portions of the Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+    FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+    COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+    IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+    CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+#ifndef INCLUDED_SimpleIni_h
+#define INCLUDED_SimpleIni_h
+
+#if defined(_MSC_VER) && (_MSC_VER >= 1020)
+# pragma once
+#endif
+
+// Disable these warnings in MSVC:
+//  4127 "conditional expression is constant" as the conversion classes trigger
+//  it with the statement if (sizeof(SI_CHAR) == sizeof(char)). This test will
+//  be optimized away in a release build.
+//  4503 'insert' : decorated name length exceeded, name was truncated
+//  4702 "unreachable code" as the MS STL header causes it in release mode.
+//  Again, the code causing the warning will be cleaned up by the compiler.
+//  4786 "identifier truncated to 256 characters" as this is thrown hundreds
+//  of times VC6 as soon as STL is used.
+#ifdef _MSC_VER
+# pragma warning (push)
+# pragma warning (disable: 4127 4503 4702 4786)
+#endif
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#ifdef SI_SUPPORT_IOSTREAMS
+# include 
+#endif // SI_SUPPORT_IOSTREAMS
+
+#ifdef _DEBUG
+# ifndef assert
+#  include 
+# endif
+# define SI_ASSERT(x)   assert(x)
+#else
+# define SI_ASSERT(x)
+#endif
+
+enum SI_Error {
+    SI_OK       =  0,   //!< No error
+    SI_UPDATED  =  1,   //!< An existing value was updated
+    SI_INSERTED =  2,   //!< A new value was inserted
+
+    // note: test for any error with (retval < 0)
+    SI_FAIL     = -1,   //!< Generic failure
+    SI_NOMEM    = -2,   //!< Out of memory error
+    SI_FILE     = -3    //!< File error (see errno for detail error)
+};
+
+#define SI_UTF8_SIGNATURE     "\xEF\xBB\xBF"
+
+#ifdef _WIN32
+# define SI_NEWLINE_A   "\r\n"
+# define SI_NEWLINE_W   L"\r\n"
+#else // !_WIN32
+# define SI_NEWLINE_A   "\n"
+# define SI_NEWLINE_W   L"\n"
+#endif // _WIN32
+
+#if defined(SI_CONVERT_ICU)
+# include 
+#endif
+
+#if defined(_WIN32)
+# define SI_HAS_WIDE_FILE
+# define SI_WCHAR_T     wchar_t
+#elif defined(SI_CONVERT_ICU)
+# define SI_HAS_WIDE_FILE
+# define SI_WCHAR_T     UChar
+#endif
+
+
+// ---------------------------------------------------------------------------
+//                              MAIN TEMPLATE CLASS
+// ---------------------------------------------------------------------------
+
+/** Simple INI file reader.
+
+    This can be instantiated with the choice of unicode or native characterset,
+    and case sensitive or insensitive comparisons of section and key names.
+    The supported combinations are pre-defined with the following typedefs:
+
+    
+        
Interface Case-sensitive Typedef +
char No CSimpleIniA +
char Yes CSimpleIniCaseA +
wchar_t No CSimpleIniW +
wchar_t Yes CSimpleIniCaseW +
+ + Note that using other types for the SI_CHAR is supported. For instance, + unsigned char, unsigned short, etc. Note that where the alternative type + is a different size to char/wchar_t you may need to supply new helper + classes for SI_STRLESS and SI_CONVERTER. + */ +template +class CSimpleIniTempl +{ +public: + /** key entry */ + struct Entry { + const SI_CHAR * pItem; + const SI_CHAR * pComment; + int nOrder; + + Entry(const SI_CHAR * a_pszItem = NULL, int a_nOrder = 0) + : pItem(a_pszItem) + , pComment(NULL) + , nOrder(a_nOrder) + { } + Entry(const SI_CHAR * a_pszItem, const SI_CHAR * a_pszComment, int a_nOrder) + : pItem(a_pszItem) + , pComment(a_pszComment) + , nOrder(a_nOrder) + { } + Entry(const Entry & rhs) { operator=(rhs); } + Entry & operator=(const Entry & rhs) { + pItem = rhs.pItem; + pComment = rhs.pComment; + nOrder = rhs.nOrder; + return *this; + } + +#if defined(_MSC_VER) && _MSC_VER <= 1200 + /** STL of VC6 doesn't allow me to specify my own comparator for list::sort() */ + bool operator<(const Entry & rhs) const { return LoadOrder()(*this, rhs); } + bool operator>(const Entry & rhs) const { return LoadOrder()(rhs, *this); } +#endif + + /** Strict less ordering by name of key only */ + struct KeyOrder : std::binary_function { + bool operator()(const Entry & lhs, const Entry & rhs) const { + const static SI_STRLESS isLess = SI_STRLESS(); + return isLess(lhs.pItem, rhs.pItem); + } + }; + + /** Strict less ordering by order, and then name of key */ + struct LoadOrder : std::binary_function { + bool operator()(const Entry & lhs, const Entry & rhs) const { + if (lhs.nOrder != rhs.nOrder) { + return lhs.nOrder < rhs.nOrder; + } + return KeyOrder()(lhs.pItem, rhs.pItem); + } + }; + }; + + /** map keys to values */ + typedef std::multimap TKeyVal; + + /** map sections to key/value map */ + typedef std::map TSection; + + /** set of dependent string pointers. Note that these pointers are + dependent on memory owned by CSimpleIni. + */ + typedef std::list TNamesDepend; + + /** interface definition for the OutputWriter object to pass to Save() + in order to output the INI file data. + */ + class OutputWriter { + public: + OutputWriter() { } + virtual ~OutputWriter() { } + virtual void Write(const char * a_pBuf) = 0; + private: + OutputWriter(const OutputWriter &); // disable + OutputWriter & operator=(const OutputWriter &); // disable + }; + + /** OutputWriter class to write the INI data to a file */ + class FileWriter : public OutputWriter { + FILE * m_file; + public: + FileWriter(FILE * a_file) : m_file(a_file) { } + void Write(const char * a_pBuf) { + fputs(a_pBuf, m_file); + } + private: + FileWriter(const FileWriter &); // disable + FileWriter & operator=(const FileWriter &); // disable + }; + + /** OutputWriter class to write the INI data to a string */ + class StringWriter : public OutputWriter { + std::string & m_string; + public: + StringWriter(std::string & a_string) : m_string(a_string) { } + void Write(const char * a_pBuf) { + m_string.append(a_pBuf); + } + private: + StringWriter(const StringWriter &); // disable + StringWriter & operator=(const StringWriter &); // disable + }; + +#ifdef SI_SUPPORT_IOSTREAMS + /** OutputWriter class to write the INI data to an ostream */ + class StreamWriter : public OutputWriter { + std::ostream & m_ostream; + public: + StreamWriter(std::ostream & a_ostream) : m_ostream(a_ostream) { } + void Write(const char * a_pBuf) { + m_ostream << a_pBuf; + } + private: + StreamWriter(const StreamWriter &); // disable + StreamWriter & operator=(const StreamWriter &); // disable + }; +#endif // SI_SUPPORT_IOSTREAMS + + /** Characterset conversion utility class to convert strings to the + same format as is used for the storage. + */ + class Converter : private SI_CONVERTER { + public: + Converter(bool a_bStoreIsUtf8) : SI_CONVERTER(a_bStoreIsUtf8) { + m_scratch.resize(1024); + } + Converter(const Converter & rhs) { operator=(rhs); } + Converter & operator=(const Converter & rhs) { + m_scratch = rhs.m_scratch; + return *this; + } + bool ConvertToStore(const SI_CHAR * a_pszString) { + size_t uLen = SizeToStore(a_pszString); + if (uLen == (size_t)(-1)) { + return false; + } + while (uLen > m_scratch.size()) { + m_scratch.resize(m_scratch.size() * 2); + } + return SI_CONVERTER::ConvertToStore( + a_pszString, + const_cast(m_scratch.data()), + m_scratch.size()); + } + const char * Data() { return m_scratch.data(); } + private: + std::string m_scratch; + }; + +public: + /*-----------------------------------------------------------------------*/ + + /** Default constructor. + + @param a_bIsUtf8 See the method SetUnicode() for details. + @param a_bMultiKey See the method SetMultiKey() for details. + @param a_bMultiLine See the method SetMultiLine() for details. + */ + CSimpleIniTempl( + bool a_bIsUtf8 = false, + bool a_bMultiKey = false, + bool a_bMultiLine = false + ); + + /** Destructor */ + ~CSimpleIniTempl(); + + /** Deallocate all memory stored by this object */ + void Reset(); + + /*-----------------------------------------------------------------------*/ + /** @{ @name Settings */ + + /** Set the storage format of the INI data. This affects both the loading + and saving of the INI data using all of the Load/Save API functions. + This value cannot be changed after any INI data has been loaded. + + If the file is not set to Unicode (UTF-8), then the data encoding is + assumed to be the OS native encoding. This encoding is the system + locale on Linux/Unix and the legacy MBCS encoding on Windows NT/2K/XP. + If the storage format is set to Unicode then the file will be loaded + as UTF-8 encoded data regardless of the native file encoding. If + SI_CHAR == char then all of the char* parameters take and return UTF-8 + encoded data regardless of the system locale. + + \param a_bIsUtf8 Assume UTF-8 encoding for the source? + */ + void SetUnicode(bool a_bIsUtf8 = true) { + if (!m_pData) m_bStoreIsUtf8 = a_bIsUtf8; + } + + /** Get the storage format of the INI data. */ + bool IsUnicode() const { return m_bStoreIsUtf8; } + + /** Should multiple identical keys be permitted in the file. If set to false + then the last value encountered will be used as the value of the key. + If set to true, then all values will be available to be queried. For + example, with the following input: + +
+        [section]
+        test=value1
+        test=value2
+        
+ + Then with SetMultiKey(true), both of the values "value1" and "value2" + will be returned for the key test. If SetMultiKey(false) is used, then + the value for "test" will only be "value2". This value may be changed + at any time. + + \param a_bAllowMultiKey Allow multi-keys in the source? + */ + void SetMultiKey(bool a_bAllowMultiKey = true) { + m_bAllowMultiKey = a_bAllowMultiKey; + } + + /** Get the storage format of the INI data. */ + bool IsMultiKey() const { return m_bAllowMultiKey; } + + /** Should data values be permitted to span multiple lines in the file. If + set to false then the multi-line construct << + SI_CHAR FORMAT + char same format as when loaded (MBCS or UTF-8) + wchar_t UTF-8 + other UTF-8 + + + Note that comments from the original data is preserved as per the + documentation on comments. The order of the sections and values + from the original file will be preserved. + + Any data prepended or appended to the output device must use the the + same format (MBCS or UTF-8). You may use the GetConverter() method to + convert text to the correct format regardless of the output format + being used by SimpleIni. + + To add a BOM to UTF-8 data, write it out manually at the very beginning + like is done in SaveFile when a_bUseBOM is true. + + @param a_oOutput Output writer to write the data to. + + @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in + UTF-8 format. If it is not UTF-8 then this value is + ignored. Do not set this to true if anything has + already been written to the OutputWriter. + + @return SI_Error See error definitions + */ + SI_Error Save( + OutputWriter & a_oOutput, + bool a_bAddSignature = false + ) const; + +#ifdef SI_SUPPORT_IOSTREAMS + /** Save the INI data to an ostream. See Save() for details. + + @param a_ostream String to have the INI data appended to. + + @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in + UTF-8 format. If it is not UTF-8 then this value is + ignored. Do not set this to true if anything has + already been written to the stream. + + @return SI_Error See error definitions + */ + SI_Error Save( + std::ostream & a_ostream, + bool a_bAddSignature = false + ) const + { + StreamWriter writer(a_ostream); + return Save(writer, a_bAddSignature); + } +#endif // SI_SUPPORT_IOSTREAMS + + /** Append the INI data to a string. See Save() for details. + + @param a_sBuffer String to have the INI data appended to. + + @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in + UTF-8 format. If it is not UTF-8 then this value is + ignored. Do not set this to true if anything has + already been written to the string. + + @return SI_Error See error definitions + */ + SI_Error Save( + std::string & a_sBuffer, + bool a_bAddSignature = false + ) const + { + StringWriter writer(a_sBuffer); + return Save(writer, a_bAddSignature); + } + + /*-----------------------------------------------------------------------*/ + /** @} + @{ @name Accessing INI Data */ + + /** Retrieve all section names. The list is returned as an STL vector of + names and can be iterated or searched as necessary. Note that the + sort order of the returned strings is NOT DEFINED. You can sort + the names into the load order if desired. Search this file for ".sort" + for an example. + + NOTE! This structure contains only pointers to strings. The actual + string data is stored in memory owned by CSimpleIni. Ensure that the + CSimpleIni object is not destroyed or Reset() while these pointers + are in use! + + @param a_names Vector that will receive all of the section + names. See note above! + */ + void GetAllSections( + TNamesDepend & a_names + ) const; + + /** Retrieve all unique key names in a section. The sort order of the + returned strings is NOT DEFINED. You can sort the names into the load + order if desired. Search this file for ".sort" for an example. Only + unique key names are returned. + + NOTE! This structure contains only pointers to strings. The actual + string data is stored in memory owned by CSimpleIni. Ensure that the + CSimpleIni object is not destroyed or Reset() while these strings + are in use! + + @param a_pSection Section to request data for + @param a_names List that will receive all of the key + names. See note above! + + @return true Section was found. + @return false Matching section was not found. + */ + bool GetAllKeys( + const SI_CHAR * a_pSection, + TNamesDepend & a_names + ) const; + + /** Retrieve all values for a specific key. This method can be used when + multiple keys are both enabled and disabled. Note that the sort order + of the returned strings is NOT DEFINED. You can sort the names into + the load order if desired. Search this file for ".sort" for an example. + + NOTE! The returned values are pointers to string data stored in memory + owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed + or Reset while you are using this pointer! + + @param a_pSection Section to search + @param a_pKey Key to search for + @param a_values List to return if the key is not found + + @return true Key was found. + @return false Matching section/key was not found. + */ + bool GetAllValues( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + TNamesDepend & a_values + ) const; + + /** Query the number of keys in a specific section. Note that if multiple + keys are enabled, then this value may be different to the number of + keys returned by GetAllKeys. + + @param a_pSection Section to request data for + + @return -1 Section does not exist in the file + @return >=0 Number of keys in the section + */ + int GetSectionSize( + const SI_CHAR * a_pSection + ) const; + + /** Retrieve all key and value pairs for a section. The data is returned + as a pointer to an STL map and can be iterated or searched as + desired. Note that multiple entries for the same key may exist when + multiple keys have been enabled. + + NOTE! This structure contains only pointers to strings. The actual + string data is stored in memory owned by CSimpleIni. Ensure that the + CSimpleIni object is not destroyed or Reset() while these strings + are in use! + + @param a_pSection Name of the section to return + @return boolean Was a section matching the supplied + name found. + */ + const TKeyVal * GetSection( + const SI_CHAR * a_pSection + ) const; + + /** Retrieve the value for a specific key. If multiple keys are enabled + (see SetMultiKey) then only the first value associated with that key + will be returned, see GetAllValues for getting all values with multikey. + + NOTE! The returned value is a pointer to string data stored in memory + owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed + or Reset while you are using this pointer! + + @param a_pSection Section to search + @param a_pKey Key to search for + @param a_pDefault Value to return if the key is not found + @param a_pHasMultiple Optionally receive notification of if there are + multiple entries for this key. + + @return a_pDefault Key was not found in the section + @return other Value of the key + */ + const SI_CHAR * GetValue( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + const SI_CHAR * a_pDefault = NULL, + bool * a_pHasMultiple = NULL + ) const; + + /** Retrieve a numeric value for a specific key. If multiple keys are enabled + (see SetMultiKey) then only the first value associated with that key + will be returned, see GetAllValues for getting all values with multikey. + + @param a_pSection Section to search + @param a_pKey Key to search for + @param a_nDefault Value to return if the key is not found + @param a_pHasMultiple Optionally receive notification of if there are + multiple entries for this key. + + @return a_nDefault Key was not found in the section + @return other Value of the key + */ + long GetLongValue( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + long a_nDefault = 0, + bool * a_pHasMultiple = NULL + ) const; + + /** Retrieve a boolean value for a specific key. If multiple keys are enabled + (see SetMultiKey) then only the first value associated with that key + will be returned, see GetAllValues for getting all values with multikey. + + Strings starting with "t", "y", "on" or "1" are returned as logically true. + Strings starting with "f", "n", "of" or "0" are returned as logically false. + For all other values the default is returned. Character comparisons are + case-insensitive. + + @param a_pSection Section to search + @param a_pKey Key to search for + @param a_bDefault Value to return if the key is not found + @param a_pHasMultiple Optionally receive notification of if there are + multiple entries for this key. + + @return a_nDefault Key was not found in the section + @return other Value of the key + */ + bool GetBoolValue( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + bool a_bDefault = false, + bool * a_pHasMultiple = NULL + ) const; + + /** Add or update a section or value. This will always insert + when multiple keys are enabled. + + @param a_pSection Section to add or update + @param a_pKey Key to add or update. Set to NULL to + create an empty section. + @param a_pValue Value to set. Set to NULL to create an + empty section. + @param a_pComment Comment to be associated with the section or the + key. If a_pKey is NULL then it will be associated + with the section, otherwise the key. Note that a + comment may be set ONLY when the section or key is + first created (i.e. when this function returns the + value SI_INSERTED). If you wish to create a section + with a comment then you need to create the section + separately to the key. The comment string must be + in full comment form already (have a comment + character starting every line). + @param a_bForceReplace Should all existing values in a multi-key INI + file be replaced with this entry. This option has + no effect if not using multi-key files. The + difference between Delete/SetValue and SetValue + with a_bForceReplace = true, is that the load + order and comment will be preserved this way. + + @return SI_Error See error definitions + @return SI_UPDATED Value was updated + @return SI_INSERTED Value was inserted + */ + SI_Error SetValue( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + const SI_CHAR * a_pValue, + const SI_CHAR * a_pComment = NULL, + bool a_bForceReplace = false + ) + { + return AddEntry(a_pSection, a_pKey, a_pValue, a_pComment, a_bForceReplace, true); + } + + /** Add or update a numeric value. This will always insert + when multiple keys are enabled. + + @param a_pSection Section to add or update + @param a_pKey Key to add or update. + @param a_nValue Value to set. + @param a_pComment Comment to be associated with the key. See the + notes on SetValue() for comments. + @param a_bUseHex By default the value will be written to the file + in decimal format. Set this to true to write it + as hexadecimal. + @param a_bForceReplace Should all existing values in a multi-key INI + file be replaced with this entry. This option has + no effect if not using multi-key files. The + difference between Delete/SetLongValue and + SetLongValue with a_bForceReplace = true, is that + the load order and comment will be preserved this + way. + + @return SI_Error See error definitions + @return SI_UPDATED Value was updated + @return SI_INSERTED Value was inserted + */ + SI_Error SetLongValue( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + long a_nValue, + const SI_CHAR * a_pComment = NULL, + bool a_bUseHex = false, + bool a_bForceReplace = false + ); + + /** Add or update a boolean value. This will always insert + when multiple keys are enabled. + + @param a_pSection Section to add or update + @param a_pKey Key to add or update. + @param a_bValue Value to set. + @param a_pComment Comment to be associated with the key. See the + notes on SetValue() for comments. + @param a_bForceReplace Should all existing values in a multi-key INI + file be replaced with this entry. This option has + no effect if not using multi-key files. The + difference between Delete/SetBoolValue and + SetBoolValue with a_bForceReplace = true, is that + the load order and comment will be preserved this + way. + + @return SI_Error See error definitions + @return SI_UPDATED Value was updated + @return SI_INSERTED Value was inserted + */ + SI_Error SetBoolValue( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + bool a_bValue, + const SI_CHAR * a_pComment = NULL, + bool a_bForceReplace = false + ); + + /** Delete an entire section, or a key from a section. Note that the + data returned by GetSection is invalid and must not be used after + anything has been deleted from that section using this method. + Note when multiple keys is enabled, this will delete all keys with + that name; there is no way to selectively delete individual key/values + in this situation. + + @param a_pSection Section to delete key from, or if + a_pKey is NULL, the section to remove. + @param a_pKey Key to remove from the section. Set to + NULL to remove the entire section. + @param a_bRemoveEmpty If the section is empty after this key has + been deleted, should the empty section be + removed? + + @return true Key or section was deleted. + @return false Key or section was not found. + */ + bool Delete( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + bool a_bRemoveEmpty = false + ); + + /*-----------------------------------------------------------------------*/ + /** @} + @{ @name Converter */ + + /** Return a conversion object to convert text to the same encoding + as is used by the Save(), SaveFile() and SaveString() functions. + Use this to prepare the strings that you wish to append or prepend + to the output INI data. + */ + Converter GetConverter() const { + return Converter(m_bStoreIsUtf8); + } + + /*-----------------------------------------------------------------------*/ + /** @} */ + +private: + // copying is not permitted + CSimpleIniTempl(const CSimpleIniTempl &); // disabled + CSimpleIniTempl & operator=(const CSimpleIniTempl &); // disabled + + /** Parse the data looking for a file comment and store it if found. + */ + SI_Error FindFileComment( + SI_CHAR *& a_pData, + bool a_bCopyStrings + ); + + /** Parse the data looking for the next valid entry. The memory pointed to + by a_pData is modified by inserting NULL characters. The pointer is + updated to the current location in the block of text. + */ + bool FindEntry( + SI_CHAR *& a_pData, + const SI_CHAR *& a_pSection, + const SI_CHAR *& a_pKey, + const SI_CHAR *& a_pVal, + const SI_CHAR *& a_pComment + ) const; + + /** Add the section/key/value to our data. + + @param a_pSection Section name. Sections will be created if they + don't already exist. + @param a_pKey Key name. May be NULL to create an empty section. + Existing entries will be updated. New entries will + be created. + @param a_pValue Value for the key. + @param a_pComment Comment to be associated with the section or the + key. If a_pKey is NULL then it will be associated + with the section, otherwise the key. This must be + a string in full comment form already (have a + comment character starting every line). + @param a_bForceReplace Should all existing values in a multi-key INI + file be replaced with this entry. This option has + no effect if not using multi-key files. The + difference between Delete/AddEntry and AddEntry + with a_bForceReplace = true, is that the load + order and comment will be preserved this way. + @param a_bCopyStrings Should copies of the strings be made or not. + If false then the pointers will be used as is. + */ + SI_Error AddEntry( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + const SI_CHAR * a_pValue, + const SI_CHAR * a_pComment, + bool a_bForceReplace, + bool a_bCopyStrings + ); + + /** Is the supplied character a whitespace character? */ + inline bool IsSpace(SI_CHAR ch) const { + return (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'); + } + + /** Does the supplied character start a comment line? */ + inline bool IsComment(SI_CHAR ch) const { + return (ch == ';' || ch == '#'); + } + + + /** Skip over a newline character (or characters) for either DOS or UNIX */ + inline void SkipNewLine(SI_CHAR *& a_pData) const { + a_pData += (*a_pData == '\r' && *(a_pData+1) == '\n') ? 2 : 1; + } + + /** Make a copy of the supplied string, replacing the original pointer */ + SI_Error CopyString(const SI_CHAR *& a_pString); + + /** Delete a string from the copied strings buffer if necessary */ + void DeleteString(const SI_CHAR * a_pString); + + /** Internal use of our string comparison function */ + bool IsLess(const SI_CHAR * a_pLeft, const SI_CHAR * a_pRight) const { + const static SI_STRLESS isLess = SI_STRLESS(); + return isLess(a_pLeft, a_pRight); + } + + bool IsMultiLineTag(const SI_CHAR * a_pData) const; + bool IsMultiLineData(const SI_CHAR * a_pData) const; + bool LoadMultiLineText( + SI_CHAR *& a_pData, + const SI_CHAR *& a_pVal, + const SI_CHAR * a_pTagName, + bool a_bAllowBlankLinesInComment = false + ) const; + bool IsNewLineChar(SI_CHAR a_c) const; + + bool OutputMultiLineText( + OutputWriter & a_oOutput, + Converter & a_oConverter, + const SI_CHAR * a_pText + ) const; + +private: + /** Copy of the INI file data in our character format. This will be + modified when parsed to have NULL characters added after all + interesting string entries. All of the string pointers to sections, + keys and values point into this block of memory. + */ + SI_CHAR * m_pData; + + /** Length of the data that we have stored. Used when deleting strings + to determine if the string is stored here or in the allocated string + buffer. + */ + size_t m_uDataLen; + + /** File comment for this data, if one exists. */ + const SI_CHAR * m_pFileComment; + + /** Parsed INI data. Section -> (Key -> Value). */ + TSection m_data; + + /** This vector stores allocated memory for copies of strings that have + been supplied after the file load. It will be empty unless SetValue() + has been called. + */ + TNamesDepend m_strings; + + /** Is the format of our datafile UTF-8 or MBCS? */ + bool m_bStoreIsUtf8; + + /** Are multiple values permitted for the same key? */ + bool m_bAllowMultiKey; + + /** Are data values permitted to span multiple lines? */ + bool m_bAllowMultiLine; + + /** Should spaces be written out surrounding the equals sign? */ + bool m_bSpaces; + + /** Next order value, used to ensure sections and keys are output in the + same order that they are loaded/added. + */ + int m_nOrder; +}; + +// --------------------------------------------------------------------------- +// IMPLEMENTATION +// --------------------------------------------------------------------------- + +template +CSimpleIniTempl::CSimpleIniTempl( + bool a_bIsUtf8, + bool a_bAllowMultiKey, + bool a_bAllowMultiLine + ) + : m_pData(0) + , m_uDataLen(0) + , m_pFileComment(NULL) + , m_bStoreIsUtf8(a_bIsUtf8) + , m_bAllowMultiKey(a_bAllowMultiKey) + , m_bAllowMultiLine(a_bAllowMultiLine) + , m_bSpaces(true) + , m_nOrder(0) +{ } + +template +CSimpleIniTempl::~CSimpleIniTempl() +{ + Reset(); +} + +template +void +CSimpleIniTempl::Reset() +{ + // remove all data + delete[] m_pData; + m_pData = NULL; + m_uDataLen = 0; + m_pFileComment = NULL; + if (!m_data.empty()) { + m_data.erase(m_data.begin(), m_data.end()); + } + + // remove all strings + if (!m_strings.empty()) { + typename TNamesDepend::iterator i = m_strings.begin(); + for (; i != m_strings.end(); ++i) { + delete[] const_cast(i->pItem); + } + m_strings.erase(m_strings.begin(), m_strings.end()); + } +} + +template +SI_Error +CSimpleIniTempl::LoadFile( + const char * a_pszFile + ) +{ + FILE * fp = NULL; +#if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE + fopen_s(&fp, a_pszFile, "rb"); +#else // !__STDC_WANT_SECURE_LIB__ + fp = fopen(a_pszFile, "rb"); +#endif // __STDC_WANT_SECURE_LIB__ + if (!fp) { + return SI_FILE; + } + SI_Error rc = LoadFile(fp); + fclose(fp); + return rc; +} + +#ifdef SI_HAS_WIDE_FILE +template +SI_Error +CSimpleIniTempl::LoadFile( + const SI_WCHAR_T * a_pwszFile + ) +{ +#ifdef _WIN32 + FILE * fp = NULL; +#if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE + _wfopen_s(&fp, a_pwszFile, L"rb"); +#else // !__STDC_WANT_SECURE_LIB__ + fp = _wfopen(a_pwszFile, L"rb"); +#endif // __STDC_WANT_SECURE_LIB__ + if (!fp) return SI_FILE; + SI_Error rc = LoadFile(fp); + fclose(fp); + return rc; +#else // !_WIN32 (therefore SI_CONVERT_ICU) + char szFile[256]; + u_austrncpy(szFile, a_pwszFile, sizeof(szFile)); + return LoadFile(szFile); +#endif // _WIN32 +} +#endif // SI_HAS_WIDE_FILE + +template +SI_Error +CSimpleIniTempl::LoadFile( + FILE * a_fpFile + ) +{ + // load the raw file data + int retval = fseek(a_fpFile, 0, SEEK_END); + if (retval != 0) { + return SI_FILE; + } + long lSize = ftell(a_fpFile); + if (lSize < 0) { + return SI_FILE; + } + if (lSize == 0) { + return SI_OK; + } + char * pData = new char[lSize]; + if (!pData) { + return SI_NOMEM; + } + fseek(a_fpFile, 0, SEEK_SET); + size_t uRead = fread(pData, sizeof(char), lSize, a_fpFile); + if (uRead != (size_t) lSize) { + delete[] pData; + return SI_FILE; + } + + // convert the raw data to unicode + SI_Error rc = Load(pData, uRead); + delete[] pData; + return rc; +} + +template +SI_Error +CSimpleIniTempl::Load( + const char * a_pData, + size_t a_uDataLen + ) +{ + SI_CONVERTER converter(m_bStoreIsUtf8); + + if (a_uDataLen == 0) { + return SI_OK; + } + + // consume the UTF-8 BOM if it exists + if (m_bStoreIsUtf8 && a_uDataLen >= 3) { + if (memcmp(a_pData, SI_UTF8_SIGNATURE, 3) == 0) { + a_pData += 3; + a_uDataLen -= 3; + } + } + + // determine the length of the converted data + size_t uLen = converter.SizeFromStore(a_pData, a_uDataLen); + if (uLen == (size_t)(-1)) { + return SI_FAIL; + } + + // allocate memory for the data, ensure that there is a NULL + // terminator wherever the converted data ends + SI_CHAR * pData = new SI_CHAR[uLen+1]; + if (!pData) { + return SI_NOMEM; + } + memset(pData, 0, sizeof(SI_CHAR)*(uLen+1)); + + // convert the data + if (!converter.ConvertFromStore(a_pData, a_uDataLen, pData, uLen)) { + delete[] pData; + return SI_FAIL; + } + + // parse it + const static SI_CHAR empty = 0; + SI_CHAR * pWork = pData; + const SI_CHAR * pSection = ∅ + const SI_CHAR * pItem = NULL; + const SI_CHAR * pVal = NULL; + const SI_CHAR * pComment = NULL; + + // We copy the strings if we are loading data into this class when we + // already have stored some. + bool bCopyStrings = (m_pData != NULL); + + // find a file comment if it exists, this is a comment that starts at the + // beginning of the file and continues until the first blank line. + SI_Error rc = FindFileComment(pWork, bCopyStrings); + if (rc < 0) return rc; + + // add every entry in the file to the data table + while (FindEntry(pWork, pSection, pItem, pVal, pComment)) { + rc = AddEntry(pSection, pItem, pVal, pComment, false, bCopyStrings); + if (rc < 0) return rc; + } + + // store these strings if we didn't copy them + if (bCopyStrings) { + delete[] pData; + } + else { + m_pData = pData; + m_uDataLen = uLen+1; + } + + return SI_OK; +} + +#ifdef SI_SUPPORT_IOSTREAMS +template +SI_Error +CSimpleIniTempl::Load( + std::istream & a_istream + ) +{ + std::string strData; + char szBuf[512]; + do { + a_istream.get(szBuf, sizeof(szBuf), '\0'); + strData.append(szBuf); + } + while (a_istream.good()); + return Load(strData); +} +#endif // SI_SUPPORT_IOSTREAMS + +template +SI_Error +CSimpleIniTempl::FindFileComment( + SI_CHAR *& a_pData, + bool a_bCopyStrings + ) +{ + // there can only be a single file comment + if (m_pFileComment) { + return SI_OK; + } + + // Load the file comment as multi-line text, this will modify all of + // the newline characters to be single \n chars + if (!LoadMultiLineText(a_pData, m_pFileComment, NULL, false)) { + return SI_OK; + } + + // copy the string if necessary + if (a_bCopyStrings) { + SI_Error rc = CopyString(m_pFileComment); + if (rc < 0) return rc; + } + + return SI_OK; +} + +template +bool +CSimpleIniTempl::FindEntry( + SI_CHAR *& a_pData, + const SI_CHAR *& a_pSection, + const SI_CHAR *& a_pKey, + const SI_CHAR *& a_pVal, + const SI_CHAR *& a_pComment + ) const +{ + a_pComment = NULL; + + SI_CHAR * pTrail = NULL; + while (*a_pData) { + // skip spaces and empty lines + while (*a_pData && IsSpace(*a_pData)) { + ++a_pData; + } + if (!*a_pData) { + break; + } + + // skip processing of comment lines but keep a pointer to + // the start of the comment. + if (IsComment(*a_pData)) { + LoadMultiLineText(a_pData, a_pComment, NULL, true); + continue; + } + + // process section names + if (*a_pData == '[') { + // skip leading spaces + ++a_pData; + while (*a_pData && IsSpace(*a_pData)) { + ++a_pData; + } + + // find the end of the section name (it may contain spaces) + // and convert it to lowercase as necessary + a_pSection = a_pData; + while (*a_pData && *a_pData != ']' && !IsNewLineChar(*a_pData)) { + ++a_pData; + } + + // if it's an invalid line, just skip it + if (*a_pData != ']') { + continue; + } + + // remove trailing spaces from the section + pTrail = a_pData - 1; + while (pTrail >= a_pSection && IsSpace(*pTrail)) { + --pTrail; + } + ++pTrail; + *pTrail = 0; + + // skip to the end of the line + ++a_pData; // safe as checked that it == ']' above + while (*a_pData && !IsNewLineChar(*a_pData)) { + ++a_pData; + } + + a_pKey = NULL; + a_pVal = NULL; + return true; + } + + // find the end of the key name (it may contain spaces) + // and convert it to lowercase as necessary + a_pKey = a_pData; + while (*a_pData && *a_pData != '=' && !IsNewLineChar(*a_pData)) { + ++a_pData; + } + + // if it's an invalid line, just skip it + if (*a_pData != '=') { + continue; + } + + // empty keys are invalid + if (a_pKey == a_pData) { + while (*a_pData && !IsNewLineChar(*a_pData)) { + ++a_pData; + } + continue; + } + + // remove trailing spaces from the key + pTrail = a_pData - 1; + while (pTrail >= a_pKey && IsSpace(*pTrail)) { + --pTrail; + } + ++pTrail; + *pTrail = 0; + + // skip leading whitespace on the value + ++a_pData; // safe as checked that it == '=' above + while (*a_pData && !IsNewLineChar(*a_pData) && IsSpace(*a_pData)) { + ++a_pData; + } + + // find the end of the value which is the end of this line + a_pVal = a_pData; + while (*a_pData && !IsNewLineChar(*a_pData)) { + ++a_pData; + } + + // remove trailing spaces from the value + pTrail = a_pData - 1; + if (*a_pData) { // prepare for the next round + SkipNewLine(a_pData); + } + while (pTrail >= a_pVal && IsSpace(*pTrail)) { + --pTrail; + } + ++pTrail; + *pTrail = 0; + + // check for multi-line entries + if (m_bAllowMultiLine && IsMultiLineTag(a_pVal)) { + // skip the "<<<" to get the tag that will end the multiline + const SI_CHAR * pTagName = a_pVal + 3; + return LoadMultiLineText(a_pData, a_pVal, pTagName); + } + + // return the standard entry + return true; + } + + return false; +} + +template +bool +CSimpleIniTempl::IsMultiLineTag( + const SI_CHAR * a_pVal + ) const +{ + // check for the "<<<" prefix for a multi-line entry + if (*a_pVal++ != '<') return false; + if (*a_pVal++ != '<') return false; + if (*a_pVal++ != '<') return false; + return true; +} + +template +bool +CSimpleIniTempl::IsMultiLineData( + const SI_CHAR * a_pData + ) const +{ + // data is multi-line if it has any of the following features: + // * whitespace prefix + // * embedded newlines + // * whitespace suffix + + // empty string + if (!*a_pData) { + return false; + } + + // check for prefix + if (IsSpace(*a_pData)) { + return true; + } + + // embedded newlines + while (*a_pData) { + if (IsNewLineChar(*a_pData)) { + return true; + } + ++a_pData; + } + + // check for suffix + if (IsSpace(*--a_pData)) { + return true; + } + + return false; +} + +template +bool +CSimpleIniTempl::IsNewLineChar( + SI_CHAR a_c + ) const +{ + return (a_c == '\n' || a_c == '\r'); +} + +template +bool +CSimpleIniTempl::LoadMultiLineText( + SI_CHAR *& a_pData, + const SI_CHAR *& a_pVal, + const SI_CHAR * a_pTagName, + bool a_bAllowBlankLinesInComment + ) const +{ + // we modify this data to strip all newlines down to a single '\n' + // character. This means that on Windows we need to strip out some + // characters which will make the data shorter. + // i.e. LINE1-LINE1\r\nLINE2-LINE2\0 will become + // LINE1-LINE1\nLINE2-LINE2\0 + // The pDataLine entry is the pointer to the location in memory that + // the current line needs to start to run following the existing one. + // This may be the same as pCurrLine in which case no move is needed. + SI_CHAR * pDataLine = a_pData; + SI_CHAR * pCurrLine; + + // value starts at the current line + a_pVal = a_pData; + + // find the end tag. This tag must start in column 1 and be + // followed by a newline. No whitespace removal is done while + // searching for this tag. + SI_CHAR cEndOfLineChar = *a_pData; + for(;;) { + // if we are loading comments then we need a comment character as + // the first character on every line + if (!a_pTagName && !IsComment(*a_pData)) { + // if we aren't allowing blank lines then we're done + if (!a_bAllowBlankLinesInComment) { + break; + } + + // if we are allowing blank lines then we only include them + // in this comment if another comment follows, so read ahead + // to find out. + SI_CHAR * pCurr = a_pData; + int nNewLines = 0; + while (IsSpace(*pCurr)) { + if (IsNewLineChar(*pCurr)) { + ++nNewLines; + SkipNewLine(pCurr); + } + else { + ++pCurr; + } + } + + // we have a comment, add the blank lines to the output + // and continue processing from here + if (IsComment(*pCurr)) { + for (; nNewLines > 0; --nNewLines) *pDataLine++ = '\n'; + a_pData = pCurr; + continue; + } + + // the comment ends here + break; + } + + // find the end of this line + pCurrLine = a_pData; + while (*a_pData && !IsNewLineChar(*a_pData)) ++a_pData; + + // move this line down to the location that it should be if necessary + if (pDataLine < pCurrLine) { + size_t nLen = (size_t) (a_pData - pCurrLine); + memmove(pDataLine, pCurrLine, nLen * sizeof(SI_CHAR)); + pDataLine[nLen] = '\0'; + } + + // end the line with a NULL + cEndOfLineChar = *a_pData; + *a_pData = 0; + + // if are looking for a tag then do the check now. This is done before + // checking for end of the data, so that if we have the tag at the end + // of the data then the tag is removed correctly. + if (a_pTagName && + (!IsLess(pDataLine, a_pTagName) && !IsLess(a_pTagName, pDataLine))) + { + break; + } + + // if we are at the end of the data then we just automatically end + // this entry and return the current data. + if (!cEndOfLineChar) { + return true; + } + + // otherwise we need to process this newline to ensure that it consists + // of just a single \n character. + pDataLine += (a_pData - pCurrLine); + *a_pData = cEndOfLineChar; + SkipNewLine(a_pData); + *pDataLine++ = '\n'; + } + + // if we didn't find a comment at all then return false + if (a_pVal == a_pData) { + a_pVal = NULL; + return false; + } + + // the data (which ends at the end of the last line) needs to be + // null-terminated BEFORE before the newline character(s). If the + // user wants a new line in the multi-line data then they need to + // add an empty line before the tag. + *--pDataLine = '\0'; + + // if looking for a tag and if we aren't at the end of the data, + // then move a_pData to the start of the next line. + if (a_pTagName && cEndOfLineChar) { + SI_ASSERT(IsNewLineChar(cEndOfLineChar)); + *a_pData = cEndOfLineChar; + SkipNewLine(a_pData); + } + + return true; +} + +template +SI_Error +CSimpleIniTempl::CopyString( + const SI_CHAR *& a_pString + ) +{ + size_t uLen = 0; + if (sizeof(SI_CHAR) == sizeof(char)) { + uLen = strlen((const char *)a_pString); + } + else if (sizeof(SI_CHAR) == sizeof(wchar_t)) { + uLen = wcslen((const wchar_t *)a_pString); + } + else { + for ( ; a_pString[uLen]; ++uLen) /*loop*/ ; + } + ++uLen; // NULL character + SI_CHAR * pCopy = new SI_CHAR[uLen]; + if (!pCopy) { + return SI_NOMEM; + } + memcpy(pCopy, a_pString, sizeof(SI_CHAR)*uLen); + m_strings.push_back(pCopy); + a_pString = pCopy; + return SI_OK; +} + +template +SI_Error +CSimpleIniTempl::AddEntry( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + const SI_CHAR * a_pValue, + const SI_CHAR * a_pComment, + bool a_bForceReplace, + bool a_bCopyStrings + ) +{ + SI_Error rc; + bool bInserted = false; + + SI_ASSERT(!a_pComment || IsComment(*a_pComment)); + + // if we are copying strings then make a copy of the comment now + // because we will need it when we add the entry. + if (a_bCopyStrings && a_pComment) { + rc = CopyString(a_pComment); + if (rc < 0) return rc; + } + + // create the section entry if necessary + typename TSection::iterator iSection = m_data.find(a_pSection); + if (iSection == m_data.end()) { + // if the section doesn't exist then we need a copy as the + // string needs to last beyond the end of this function + if (a_bCopyStrings) { + rc = CopyString(a_pSection); + if (rc < 0) return rc; + } + + // only set the comment if this is a section only entry + Entry oSection(a_pSection, ++m_nOrder); + if (a_pComment && (!a_pKey || !a_pValue)) { + oSection.pComment = a_pComment; + } + + typename TSection::value_type oEntry(oSection, TKeyVal()); + typedef typename TSection::iterator SectionIterator; + std::pair i = m_data.insert(oEntry); + iSection = i.first; + bInserted = true; + } + if (!a_pKey || !a_pValue) { + // section only entries are specified with pItem and pVal as NULL + return bInserted ? SI_INSERTED : SI_UPDATED; + } + + // check for existence of the key + TKeyVal & keyval = iSection->second; + typename TKeyVal::iterator iKey = keyval.find(a_pKey); + + // remove all existing entries but save the load order and + // comment of the first entry + int nLoadOrder = ++m_nOrder; + if (iKey != keyval.end() && m_bAllowMultiKey && a_bForceReplace) { + const SI_CHAR * pComment = NULL; + while (iKey != keyval.end() && !IsLess(a_pKey, iKey->first.pItem)) { + if (iKey->first.nOrder < nLoadOrder) { + nLoadOrder = iKey->first.nOrder; + pComment = iKey->first.pComment; + } + ++iKey; + } + if (pComment) { + DeleteString(a_pComment); + a_pComment = pComment; + CopyString(a_pComment); + } + Delete(a_pSection, a_pKey); + iKey = keyval.end(); + } + + // make string copies if necessary + bool bForceCreateNewKey = m_bAllowMultiKey && !a_bForceReplace; + if (a_bCopyStrings) { + if (bForceCreateNewKey || iKey == keyval.end()) { + // if the key doesn't exist then we need a copy as the + // string needs to last beyond the end of this function + // because we will be inserting the key next + rc = CopyString(a_pKey); + if (rc < 0) return rc; + } + + // we always need a copy of the value + rc = CopyString(a_pValue); + if (rc < 0) return rc; + } + + // create the key entry + if (iKey == keyval.end() || bForceCreateNewKey) { + Entry oKey(a_pKey, nLoadOrder); + if (a_pComment) { + oKey.pComment = a_pComment; + } + typename TKeyVal::value_type oEntry(oKey, (const SI_CHAR *) NULL); + iKey = keyval.insert(oEntry); + bInserted = true; + } + iKey->second = a_pValue; + return bInserted ? SI_INSERTED : SI_UPDATED; +} + +template +const SI_CHAR * +CSimpleIniTempl::GetValue( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + const SI_CHAR * a_pDefault, + bool * a_pHasMultiple + ) const +{ + if (a_pHasMultiple) { + *a_pHasMultiple = false; + } + if (!a_pSection || !a_pKey) { + return a_pDefault; + } + typename TSection::const_iterator iSection = m_data.find(a_pSection); + if (iSection == m_data.end()) { + return a_pDefault; + } + typename TKeyVal::const_iterator iKeyVal = iSection->second.find(a_pKey); + if (iKeyVal == iSection->second.end()) { + return a_pDefault; + } + + // check for multiple entries with the same key + if (m_bAllowMultiKey && a_pHasMultiple) { + typename TKeyVal::const_iterator iTemp = iKeyVal; + if (++iTemp != iSection->second.end()) { + if (!IsLess(a_pKey, iTemp->first.pItem)) { + *a_pHasMultiple = true; + } + } + } + + return iKeyVal->second; +} + +template +long +CSimpleIniTempl::GetLongValue( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + long a_nDefault, + bool * a_pHasMultiple + ) const +{ + // return the default if we don't have a value + const SI_CHAR * pszValue = GetValue(a_pSection, a_pKey, NULL, a_pHasMultiple); + if (!pszValue || !*pszValue) return a_nDefault; + + // convert to UTF-8/MBCS which for a numeric value will be the same as ASCII + char szValue[64] = { 0 }; + SI_CONVERTER c(m_bStoreIsUtf8); + if (!c.ConvertToStore(pszValue, szValue, sizeof(szValue))) { + return a_nDefault; + } + + // handle the value as hex if prefaced with "0x" + long nValue = a_nDefault; + char * pszSuffix = szValue; + if (szValue[0] == '0' && (szValue[1] == 'x' || szValue[1] == 'X')) { + if (!szValue[2]) return a_nDefault; + nValue = strtol(&szValue[2], &pszSuffix, 16); + } + else { + nValue = strtol(szValue, &pszSuffix, 10); + } + + // any invalid strings will return the default value + if (*pszSuffix) { + return a_nDefault; + } + + return nValue; +} + +template +SI_Error +CSimpleIniTempl::SetLongValue( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + long a_nValue, + const SI_CHAR * a_pComment, + bool a_bUseHex, + bool a_bForceReplace + ) +{ + // use SetValue to create sections + if (!a_pSection || !a_pKey) return SI_FAIL; + + // convert to an ASCII string + char szInput[64]; +#if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE + sprintf_s(szInput, a_bUseHex ? "0x%lx" : "%ld", a_nValue); +#else // !__STDC_WANT_SECURE_LIB__ + sprintf(szInput, a_bUseHex ? "0x%lx" : "%ld", a_nValue); +#endif // __STDC_WANT_SECURE_LIB__ + + // convert to output text + SI_CHAR szOutput[64]; + SI_CONVERTER c(m_bStoreIsUtf8); + c.ConvertFromStore(szInput, strlen(szInput) + 1, + szOutput, sizeof(szOutput) / sizeof(SI_CHAR)); + + // actually add it + return AddEntry(a_pSection, a_pKey, szOutput, a_pComment, a_bForceReplace, true); +} + +template +bool +CSimpleIniTempl::GetBoolValue( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + bool a_bDefault, + bool * a_pHasMultiple + ) const +{ + // return the default if we don't have a value + const SI_CHAR * pszValue = GetValue(a_pSection, a_pKey, NULL, a_pHasMultiple); + if (!pszValue || !*pszValue) return a_bDefault; + + // we only look at the minimum number of characters + switch (pszValue[0]) { + case 't': case 'T': // true + case 'y': case 'Y': // yes + case '1': // 1 (one) + return true; + + case 'f': case 'F': // false + case 'n': case 'N': // no + case '0': // 0 (zero) + return false; + + case 'o': case 'O': + if (pszValue[1] == 'n' || pszValue[1] == 'N') return true; // on + if (pszValue[1] == 'f' || pszValue[1] == 'F') return false; // off + break; + } + + // no recognized value, return the default + return a_bDefault; +} + +template +SI_Error +CSimpleIniTempl::SetBoolValue( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + bool a_bValue, + const SI_CHAR * a_pComment, + bool a_bForceReplace + ) +{ + // use SetValue to create sections + if (!a_pSection || !a_pKey) return SI_FAIL; + + // convert to an ASCII string + const char * pszInput = a_bValue ? "true" : "false"; + + // convert to output text + SI_CHAR szOutput[64]; + SI_CONVERTER c(m_bStoreIsUtf8); + c.ConvertFromStore(pszInput, strlen(pszInput) + 1, + szOutput, sizeof(szOutput) / sizeof(SI_CHAR)); + + // actually add it + return AddEntry(a_pSection, a_pKey, szOutput, a_pComment, a_bForceReplace, true); +} + +template +bool +CSimpleIniTempl::GetAllValues( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + TNamesDepend & a_values + ) const +{ + a_values.clear(); + + if (!a_pSection || !a_pKey) { + return false; + } + typename TSection::const_iterator iSection = m_data.find(a_pSection); + if (iSection == m_data.end()) { + return false; + } + typename TKeyVal::const_iterator iKeyVal = iSection->second.find(a_pKey); + if (iKeyVal == iSection->second.end()) { + return false; + } + + // insert all values for this key + a_values.push_back(Entry(iKeyVal->second, iKeyVal->first.pComment, iKeyVal->first.nOrder)); + if (m_bAllowMultiKey) { + ++iKeyVal; + while (iKeyVal != iSection->second.end() && !IsLess(a_pKey, iKeyVal->first.pItem)) { + a_values.push_back(Entry(iKeyVal->second, iKeyVal->first.pComment, iKeyVal->first.nOrder)); + ++iKeyVal; + } + } + + return true; +} + +template +int +CSimpleIniTempl::GetSectionSize( + const SI_CHAR * a_pSection + ) const +{ + if (!a_pSection) { + return -1; + } + + typename TSection::const_iterator iSection = m_data.find(a_pSection); + if (iSection == m_data.end()) { + return -1; + } + const TKeyVal & section = iSection->second; + + // if multi-key isn't permitted then the section size is + // the number of keys that we have. + if (!m_bAllowMultiKey || section.empty()) { + return (int) section.size(); + } + + // otherwise we need to count them + int nCount = 0; + const SI_CHAR * pLastKey = NULL; + typename TKeyVal::const_iterator iKeyVal = section.begin(); + for (int n = 0; iKeyVal != section.end(); ++iKeyVal, ++n) { + if (!pLastKey || IsLess(pLastKey, iKeyVal->first.pItem)) { + ++nCount; + pLastKey = iKeyVal->first.pItem; + } + } + return nCount; +} + +template +const typename CSimpleIniTempl::TKeyVal * +CSimpleIniTempl::GetSection( + const SI_CHAR * a_pSection + ) const +{ + if (a_pSection) { + typename TSection::const_iterator i = m_data.find(a_pSection); + if (i != m_data.end()) { + return &(i->second); + } + } + return 0; +} + +template +void +CSimpleIniTempl::GetAllSections( + TNamesDepend & a_names + ) const +{ + a_names.clear(); + typename TSection::const_iterator i = m_data.begin(); + for (int n = 0; i != m_data.end(); ++i, ++n ) { + a_names.push_back(i->first); + } +} + +template +bool +CSimpleIniTempl::GetAllKeys( + const SI_CHAR * a_pSection, + TNamesDepend & a_names + ) const +{ + a_names.clear(); + + if (!a_pSection) { + return false; + } + + typename TSection::const_iterator iSection = m_data.find(a_pSection); + if (iSection == m_data.end()) { + return false; + } + + const TKeyVal & section = iSection->second; + const SI_CHAR * pLastKey = NULL; + typename TKeyVal::const_iterator iKeyVal = section.begin(); + for (int n = 0; iKeyVal != section.end(); ++iKeyVal, ++n ) { + if (!pLastKey || IsLess(pLastKey, iKeyVal->first.pItem)) { + a_names.push_back(iKeyVal->first); + pLastKey = iKeyVal->first.pItem; + } + } + + return true; +} + +template +SI_Error +CSimpleIniTempl::SaveFile( + const char * a_pszFile, + bool a_bAddSignature + ) const +{ + FILE * fp = NULL; +#if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE + fopen_s(&fp, a_pszFile, "wb"); +#else // !__STDC_WANT_SECURE_LIB__ + fp = fopen(a_pszFile, "wb"); +#endif // __STDC_WANT_SECURE_LIB__ + if (!fp) return SI_FILE; + SI_Error rc = SaveFile(fp, a_bAddSignature); + fclose(fp); + return rc; +} + +#ifdef SI_HAS_WIDE_FILE +template +SI_Error +CSimpleIniTempl::SaveFile( + const SI_WCHAR_T * a_pwszFile, + bool a_bAddSignature + ) const +{ +#ifdef _WIN32 + FILE * fp = NULL; +#if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE + _wfopen_s(&fp, a_pwszFile, L"wb"); +#else // !__STDC_WANT_SECURE_LIB__ + fp = _wfopen(a_pwszFile, L"wb"); +#endif // __STDC_WANT_SECURE_LIB__ + if (!fp) return SI_FILE; + SI_Error rc = SaveFile(fp, a_bAddSignature); + fclose(fp); + return rc; +#else // !_WIN32 (therefore SI_CONVERT_ICU) + char szFile[256]; + u_austrncpy(szFile, a_pwszFile, sizeof(szFile)); + return SaveFile(szFile, a_bAddSignature); +#endif // _WIN32 +} +#endif // SI_HAS_WIDE_FILE + +template +SI_Error +CSimpleIniTempl::SaveFile( + FILE * a_pFile, + bool a_bAddSignature + ) const +{ + FileWriter writer(a_pFile); + return Save(writer, a_bAddSignature); +} + +template +SI_Error +CSimpleIniTempl::Save( + OutputWriter & a_oOutput, + bool a_bAddSignature + ) const +{ + Converter convert(m_bStoreIsUtf8); + + // add the UTF-8 signature if it is desired + if (m_bStoreIsUtf8 && a_bAddSignature) { + a_oOutput.Write(SI_UTF8_SIGNATURE); + } + + // get all of the sections sorted in load order + TNamesDepend oSections; + GetAllSections(oSections); +#if defined(_MSC_VER) && _MSC_VER <= 1200 + oSections.sort(); +#elif defined(__BORLANDC__) + oSections.sort(Entry::LoadOrder()); +#else + oSections.sort(typename Entry::LoadOrder()); +#endif + + // write the file comment if we have one + bool bNeedNewLine = false; + if (m_pFileComment) { + if (!OutputMultiLineText(a_oOutput, convert, m_pFileComment)) { + return SI_FAIL; + } + bNeedNewLine = true; + } + + // iterate through our sections and output the data + typename TNamesDepend::const_iterator iSection = oSections.begin(); + for ( ; iSection != oSections.end(); ++iSection ) { + // write out the comment if there is one + if (iSection->pComment) { + if (bNeedNewLine) { + a_oOutput.Write(SI_NEWLINE_A); + a_oOutput.Write(SI_NEWLINE_A); + } + if (!OutputMultiLineText(a_oOutput, convert, iSection->pComment)) { + return SI_FAIL; + } + bNeedNewLine = false; + } + + if (bNeedNewLine) { + a_oOutput.Write(SI_NEWLINE_A); + a_oOutput.Write(SI_NEWLINE_A); + bNeedNewLine = false; + } + + // write the section (unless there is no section name) + if (*iSection->pItem) { + if (!convert.ConvertToStore(iSection->pItem)) { + return SI_FAIL; + } + a_oOutput.Write("["); + a_oOutput.Write(convert.Data()); + a_oOutput.Write("]"); + a_oOutput.Write(SI_NEWLINE_A); + } + + // get all of the keys sorted in load order + TNamesDepend oKeys; + GetAllKeys(iSection->pItem, oKeys); +#if defined(_MSC_VER) && _MSC_VER <= 1200 + oKeys.sort(); +#elif defined(__BORLANDC__) + oKeys.sort(Entry::LoadOrder()); +#else + oKeys.sort(typename Entry::LoadOrder()); +#endif + + // write all keys and values + typename TNamesDepend::const_iterator iKey = oKeys.begin(); + for ( ; iKey != oKeys.end(); ++iKey) { + // get all values for this key + TNamesDepend oValues; + GetAllValues(iSection->pItem, iKey->pItem, oValues); + + typename TNamesDepend::const_iterator iValue = oValues.begin(); + for ( ; iValue != oValues.end(); ++iValue) { + // write out the comment if there is one + if (iValue->pComment) { + a_oOutput.Write(SI_NEWLINE_A); + if (!OutputMultiLineText(a_oOutput, convert, iValue->pComment)) { + return SI_FAIL; + } + } + + // write the key + if (!convert.ConvertToStore(iKey->pItem)) { + return SI_FAIL; + } + a_oOutput.Write(convert.Data()); + + // write the value + if (!convert.ConvertToStore(iValue->pItem)) { + return SI_FAIL; + } + a_oOutput.Write(m_bSpaces ? " = " : "="); + if (m_bAllowMultiLine && IsMultiLineData(iValue->pItem)) { + // multi-line data needs to be processed specially to ensure + // that we use the correct newline format for the current system + a_oOutput.Write("<<pItem)) { + return SI_FAIL; + } + a_oOutput.Write("SI-END-OF-MULTILINE-TEXT"); + } + else { + a_oOutput.Write(convert.Data()); + } + a_oOutput.Write(SI_NEWLINE_A); + } + } + + bNeedNewLine = true; + } + + return SI_OK; +} + +template +bool +CSimpleIniTempl::OutputMultiLineText( + OutputWriter & a_oOutput, + Converter & a_oConverter, + const SI_CHAR * a_pText + ) const +{ + const SI_CHAR * pEndOfLine; + SI_CHAR cEndOfLineChar = *a_pText; + while (cEndOfLineChar) { + // find the end of this line + pEndOfLine = a_pText; + for (; *pEndOfLine && *pEndOfLine != '\n'; ++pEndOfLine) /*loop*/ ; + cEndOfLineChar = *pEndOfLine; + + // temporarily null terminate, convert and output the line + *const_cast(pEndOfLine) = 0; + if (!a_oConverter.ConvertToStore(a_pText)) { + return false; + } + *const_cast(pEndOfLine) = cEndOfLineChar; + a_pText += (pEndOfLine - a_pText) + 1; + a_oOutput.Write(a_oConverter.Data()); + a_oOutput.Write(SI_NEWLINE_A); + } + return true; +} + +template +bool +CSimpleIniTempl::Delete( + const SI_CHAR * a_pSection, + const SI_CHAR * a_pKey, + bool a_bRemoveEmpty + ) +{ + if (!a_pSection) { + return false; + } + + typename TSection::iterator iSection = m_data.find(a_pSection); + if (iSection == m_data.end()) { + return false; + } + + // remove a single key if we have a keyname + if (a_pKey) { + typename TKeyVal::iterator iKeyVal = iSection->second.find(a_pKey); + if (iKeyVal == iSection->second.end()) { + return false; + } + + // remove any copied strings and then the key + typename TKeyVal::iterator iDelete; + do { + iDelete = iKeyVal++; + + DeleteString(iDelete->first.pItem); + DeleteString(iDelete->second); + iSection->second.erase(iDelete); + } + while (iKeyVal != iSection->second.end() + && !IsLess(a_pKey, iKeyVal->first.pItem)); + + // done now if the section is not empty or we are not pruning away + // the empty sections. Otherwise let it fall through into the section + // deletion code + if (!a_bRemoveEmpty || !iSection->second.empty()) { + return true; + } + } + else { + // delete all copied strings from this section. The actual + // entries will be removed when the section is removed. + typename TKeyVal::iterator iKeyVal = iSection->second.begin(); + for ( ; iKeyVal != iSection->second.end(); ++iKeyVal) { + DeleteString(iKeyVal->first.pItem); + DeleteString(iKeyVal->second); + } + } + + // delete the section itself + DeleteString(iSection->first.pItem); + m_data.erase(iSection); + + return true; +} + +template +void +CSimpleIniTempl::DeleteString( + const SI_CHAR * a_pString + ) +{ + // strings may exist either inside the data block, or they will be + // individually allocated and stored in m_strings. We only physically + // delete those stored in m_strings. + if (a_pString < m_pData || a_pString >= m_pData + m_uDataLen) { + typename TNamesDepend::iterator i = m_strings.begin(); + for (;i != m_strings.end(); ++i) { + if (a_pString == i->pItem) { + delete[] const_cast(i->pItem); + m_strings.erase(i); + break; + } + } + } +} + +// --------------------------------------------------------------------------- +// CONVERSION FUNCTIONS +// --------------------------------------------------------------------------- + +// Defines the conversion classes for different libraries. Before including +// SimpleIni.h, set the converter that you wish you use by defining one of the +// following symbols. +// +// SI_CONVERT_GENERIC Use the Unicode reference conversion library in +// the accompanying files ConvertUTF.h/c +// SI_CONVERT_ICU Use the IBM ICU conversion library. Requires +// ICU headers on include path and icuuc.lib +// SI_CONVERT_WIN32 Use the Win32 API functions for conversion. + +#if !defined(SI_CONVERT_GENERIC) && !defined(SI_CONVERT_WIN32) && !defined(SI_CONVERT_ICU) +# ifdef _WIN32 +# define SI_CONVERT_WIN32 +# else +# define SI_CONVERT_GENERIC +# endif +#endif + +/** + * Generic case-sensitive less than comparison. This class returns numerically + * ordered ASCII case-sensitive text for all possible sizes and types of + * SI_CHAR. + */ +template +struct SI_GenericCase { + bool operator()(const SI_CHAR * pLeft, const SI_CHAR * pRight) const { + long cmp; + for ( ;*pLeft && *pRight; ++pLeft, ++pRight) { + cmp = (long) *pLeft - (long) *pRight; + if (cmp != 0) { + return cmp < 0; + } + } + return *pRight != 0; + } +}; + +/** + * Generic ASCII case-insensitive less than comparison. This class returns + * numerically ordered ASCII case-insensitive text for all possible sizes + * and types of SI_CHAR. It is not safe for MBCS text comparison where + * ASCII A-Z characters are used in the encoding of multi-byte characters. + */ +template +struct SI_GenericNoCase { + inline SI_CHAR locase(SI_CHAR ch) const { + return (ch < 'A' || ch > 'Z') ? ch : (ch - 'A' + 'a'); + } + bool operator()(const SI_CHAR * pLeft, const SI_CHAR * pRight) const { + long cmp; + for ( ;*pLeft && *pRight; ++pLeft, ++pRight) { + cmp = (long) locase(*pLeft) - (long) locase(*pRight); + if (cmp != 0) { + return cmp < 0; + } + } + return *pRight != 0; + } +}; + +/** + * Null conversion class for MBCS/UTF-8 to char (or equivalent). + */ +template +class SI_ConvertA { + bool m_bStoreIsUtf8; +protected: + SI_ConvertA() { } +public: + SI_ConvertA(bool a_bStoreIsUtf8) : m_bStoreIsUtf8(a_bStoreIsUtf8) { } + + /* copy and assignment */ + SI_ConvertA(const SI_ConvertA & rhs) { operator=(rhs); } + SI_ConvertA & operator=(const SI_ConvertA & rhs) { + m_bStoreIsUtf8 = rhs.m_bStoreIsUtf8; + return *this; + } + + /** Calculate the number of SI_CHAR required for converting the input + * from the storage format. The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData Data in storage format to be converted to SI_CHAR. + * @param a_uInputDataLen Length of storage format data in bytes. This + * must be the actual length of the data, including + * NULL byte if NULL terminated string is required. + * @return Number of SI_CHAR required by the string when + * converted. If there are embedded NULL bytes in the + * input data, only the string up and not including + * the NULL byte will be converted. + * @return -1 cast to size_t on a conversion error. + */ + size_t SizeFromStore( + const char * a_pInputData, + size_t a_uInputDataLen) + { + (void)a_pInputData; + SI_ASSERT(a_uInputDataLen != (size_t) -1); + + // ASCII/MBCS/UTF-8 needs no conversion + return a_uInputDataLen; + } + + /** Convert the input string from the storage format to SI_CHAR. + * The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData Data in storage format to be converted to SI_CHAR. + * @param a_uInputDataLen Length of storage format data in bytes. This + * must be the actual length of the data, including + * NULL byte if NULL terminated string is required. + * @param a_pOutputData Pointer to the output buffer to received the + * converted data. + * @param a_uOutputDataSize Size of the output buffer in SI_CHAR. + * @return true if all of the input data was successfully + * converted. + */ + bool ConvertFromStore( + const char * a_pInputData, + size_t a_uInputDataLen, + SI_CHAR * a_pOutputData, + size_t a_uOutputDataSize) + { + // ASCII/MBCS/UTF-8 needs no conversion + if (a_uInputDataLen > a_uOutputDataSize) { + return false; + } + memcpy(a_pOutputData, a_pInputData, a_uInputDataLen); + return true; + } + + /** Calculate the number of char required by the storage format of this + * data. The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData NULL terminated string to calculate the number of + * bytes required to be converted to storage format. + * @return Number of bytes required by the string when + * converted to storage format. This size always + * includes space for the terminating NULL character. + * @return -1 cast to size_t on a conversion error. + */ + size_t SizeToStore( + const SI_CHAR * a_pInputData) + { + // ASCII/MBCS/UTF-8 needs no conversion + return strlen((const char *)a_pInputData) + 1; + } + + /** Convert the input string to the storage format of this data. + * The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData NULL terminated source string to convert. All of + * the data will be converted including the + * terminating NULL character. + * @param a_pOutputData Pointer to the buffer to receive the converted + * string. + * @param a_uOutputDataSize Size of the output buffer in char. + * @return true if all of the input data, including the + * terminating NULL character was successfully + * converted. + */ + bool ConvertToStore( + const SI_CHAR * a_pInputData, + char * a_pOutputData, + size_t a_uOutputDataSize) + { + // calc input string length (SI_CHAR type and size independent) + size_t uInputLen = strlen((const char *)a_pInputData) + 1; + if (uInputLen > a_uOutputDataSize) { + return false; + } + + // ascii/UTF-8 needs no conversion + memcpy(a_pOutputData, a_pInputData, uInputLen); + return true; + } +}; + + +// --------------------------------------------------------------------------- +// SI_CONVERT_GENERIC +// --------------------------------------------------------------------------- +#ifdef SI_CONVERT_GENERIC + +#define SI_Case SI_GenericCase +#define SI_NoCase SI_GenericNoCase + +#include +#include "ConvertUTF.h" + +/** + * Converts UTF-8 to a wchar_t (or equivalent) using the Unicode reference + * library functions. This can be used on all platforms. + */ +template +class SI_ConvertW { + bool m_bStoreIsUtf8; +protected: + SI_ConvertW() { } +public: + SI_ConvertW(bool a_bStoreIsUtf8) : m_bStoreIsUtf8(a_bStoreIsUtf8) { } + + /* copy and assignment */ + SI_ConvertW(const SI_ConvertW & rhs) { operator=(rhs); } + SI_ConvertW & operator=(const SI_ConvertW & rhs) { + m_bStoreIsUtf8 = rhs.m_bStoreIsUtf8; + return *this; + } + + /** Calculate the number of SI_CHAR required for converting the input + * from the storage format. The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData Data in storage format to be converted to SI_CHAR. + * @param a_uInputDataLen Length of storage format data in bytes. This + * must be the actual length of the data, including + * NULL byte if NULL terminated string is required. + * @return Number of SI_CHAR required by the string when + * converted. If there are embedded NULL bytes in the + * input data, only the string up and not including + * the NULL byte will be converted. + * @return -1 cast to size_t on a conversion error. + */ + size_t SizeFromStore( + const char * a_pInputData, + size_t a_uInputDataLen) + { + SI_ASSERT(a_uInputDataLen != (size_t) -1); + + if (m_bStoreIsUtf8) { + // worst case scenario for UTF-8 to wchar_t is 1 char -> 1 wchar_t + // so we just return the same number of characters required as for + // the source text. + return a_uInputDataLen; + } + else { + return mbstowcs(NULL, a_pInputData, a_uInputDataLen); + } + } + + /** Convert the input string from the storage format to SI_CHAR. + * The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData Data in storage format to be converted to SI_CHAR. + * @param a_uInputDataLen Length of storage format data in bytes. This + * must be the actual length of the data, including + * NULL byte if NULL terminated string is required. + * @param a_pOutputData Pointer to the output buffer to received the + * converted data. + * @param a_uOutputDataSize Size of the output buffer in SI_CHAR. + * @return true if all of the input data was successfully + * converted. + */ + bool ConvertFromStore( + const char * a_pInputData, + size_t a_uInputDataLen, + SI_CHAR * a_pOutputData, + size_t a_uOutputDataSize) + { + if (m_bStoreIsUtf8) { + // This uses the Unicode reference implementation to do the + // conversion from UTF-8 to wchar_t. The required files are + // ConvertUTF.h and ConvertUTF.c which should be included in + // the distribution but are publically available from unicode.org + // at http://www.unicode.org/Public/PROGRAMS/CVTUTF/ + ConversionResult retval; + const UTF8 * pUtf8 = (const UTF8 *) a_pInputData; + if (sizeof(wchar_t) == sizeof(UTF32)) { + UTF32 * pUtf32 = (UTF32 *) a_pOutputData; + retval = ConvertUTF8toUTF32( + &pUtf8, pUtf8 + a_uInputDataLen, + &pUtf32, pUtf32 + a_uOutputDataSize, + lenientConversion); + } + else if (sizeof(wchar_t) == sizeof(UTF16)) { + UTF16 * pUtf16 = (UTF16 *) a_pOutputData; + retval = ConvertUTF8toUTF16( + &pUtf8, pUtf8 + a_uInputDataLen, + &pUtf16, pUtf16 + a_uOutputDataSize, + lenientConversion); + } + return retval == conversionOK; + } + else { + size_t retval = mbstowcs(a_pOutputData, + a_pInputData, a_uOutputDataSize); + return retval != (size_t)(-1); + } + } + + /** Calculate the number of char required by the storage format of this + * data. The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData NULL terminated string to calculate the number of + * bytes required to be converted to storage format. + * @return Number of bytes required by the string when + * converted to storage format. This size always + * includes space for the terminating NULL character. + * @return -1 cast to size_t on a conversion error. + */ + size_t SizeToStore( + const SI_CHAR * a_pInputData) + { + if (m_bStoreIsUtf8) { + // worst case scenario for wchar_t to UTF-8 is 1 wchar_t -> 6 char + size_t uLen = 0; + while (a_pInputData[uLen]) { + ++uLen; + } + return (6 * uLen) + 1; + } + else { + size_t uLen = wcstombs(NULL, a_pInputData, 0); + if (uLen == (size_t)(-1)) { + return uLen; + } + return uLen + 1; // include NULL terminator + } + } + + /** Convert the input string to the storage format of this data. + * The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData NULL terminated source string to convert. All of + * the data will be converted including the + * terminating NULL character. + * @param a_pOutputData Pointer to the buffer to receive the converted + * string. + * @param a_uOutputDataSize Size of the output buffer in char. + * @return true if all of the input data, including the + * terminating NULL character was successfully + * converted. + */ + bool ConvertToStore( + const SI_CHAR * a_pInputData, + char * a_pOutputData, + size_t a_uOutputDataSize + ) + { + if (m_bStoreIsUtf8) { + // calc input string length (SI_CHAR type and size independent) + size_t uInputLen = 0; + while (a_pInputData[uInputLen]) { + ++uInputLen; + } + ++uInputLen; // include the NULL char + + // This uses the Unicode reference implementation to do the + // conversion from wchar_t to UTF-8. The required files are + // ConvertUTF.h and ConvertUTF.c which should be included in + // the distribution but are publically available from unicode.org + // at http://www.unicode.org/Public/PROGRAMS/CVTUTF/ + ConversionResult retval; + UTF8 * pUtf8 = (UTF8 *) a_pOutputData; + if (sizeof(wchar_t) == sizeof(UTF32)) { + const UTF32 * pUtf32 = (const UTF32 *) a_pInputData; + retval = ConvertUTF32toUTF8( + &pUtf32, pUtf32 + uInputLen, + &pUtf8, pUtf8 + a_uOutputDataSize, + lenientConversion); + } + else if (sizeof(wchar_t) == sizeof(UTF16)) { + const UTF16 * pUtf16 = (const UTF16 *) a_pInputData; + retval = ConvertUTF16toUTF8( + &pUtf16, pUtf16 + uInputLen, + &pUtf8, pUtf8 + a_uOutputDataSize, + lenientConversion); + } + return retval == conversionOK; + } + else { + size_t retval = wcstombs(a_pOutputData, + a_pInputData, a_uOutputDataSize); + return retval != (size_t) -1; + } + } +}; + +#endif // SI_CONVERT_GENERIC + + +// --------------------------------------------------------------------------- +// SI_CONVERT_ICU +// --------------------------------------------------------------------------- +#ifdef SI_CONVERT_ICU + +#define SI_Case SI_GenericCase +#define SI_NoCase SI_GenericNoCase + +#include + +/** + * Converts MBCS/UTF-8 to UChar using ICU. This can be used on all platforms. + */ +template +class SI_ConvertW { + const char * m_pEncoding; + UConverter * m_pConverter; +protected: + SI_ConvertW() : m_pEncoding(NULL), m_pConverter(NULL) { } +public: + SI_ConvertW(bool a_bStoreIsUtf8) : m_pConverter(NULL) { + m_pEncoding = a_bStoreIsUtf8 ? "UTF-8" : NULL; + } + + /* copy and assignment */ + SI_ConvertW(const SI_ConvertW & rhs) { operator=(rhs); } + SI_ConvertW & operator=(const SI_ConvertW & rhs) { + m_pEncoding = rhs.m_pEncoding; + m_pConverter = NULL; + return *this; + } + ~SI_ConvertW() { if (m_pConverter) ucnv_close(m_pConverter); } + + /** Calculate the number of UChar required for converting the input + * from the storage format. The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData Data in storage format to be converted to UChar. + * @param a_uInputDataLen Length of storage format data in bytes. This + * must be the actual length of the data, including + * NULL byte if NULL terminated string is required. + * @return Number of UChar required by the string when + * converted. If there are embedded NULL bytes in the + * input data, only the string up and not including + * the NULL byte will be converted. + * @return -1 cast to size_t on a conversion error. + */ + size_t SizeFromStore( + const char * a_pInputData, + size_t a_uInputDataLen) + { + SI_ASSERT(a_uInputDataLen != (size_t) -1); + + UErrorCode nError; + + if (!m_pConverter) { + nError = U_ZERO_ERROR; + m_pConverter = ucnv_open(m_pEncoding, &nError); + if (U_FAILURE(nError)) { + return (size_t) -1; + } + } + + nError = U_ZERO_ERROR; + ucnv_resetToUnicode(m_pConverter); + int32_t nLen = ucnv_toUChars(m_pConverter, NULL, 0, + a_pInputData, (int32_t) a_uInputDataLen, &nError); + if (nError != U_BUFFER_OVERFLOW_ERROR) { + return (size_t) -1; + } + + return (size_t) nLen; + } + + /** Convert the input string from the storage format to UChar. + * The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData Data in storage format to be converted to UChar. + * @param a_uInputDataLen Length of storage format data in bytes. This + * must be the actual length of the data, including + * NULL byte if NULL terminated string is required. + * @param a_pOutputData Pointer to the output buffer to received the + * converted data. + * @param a_uOutputDataSize Size of the output buffer in UChar. + * @return true if all of the input data was successfully + * converted. + */ + bool ConvertFromStore( + const char * a_pInputData, + size_t a_uInputDataLen, + UChar * a_pOutputData, + size_t a_uOutputDataSize) + { + UErrorCode nError; + + if (!m_pConverter) { + nError = U_ZERO_ERROR; + m_pConverter = ucnv_open(m_pEncoding, &nError); + if (U_FAILURE(nError)) { + return false; + } + } + + nError = U_ZERO_ERROR; + ucnv_resetToUnicode(m_pConverter); + ucnv_toUChars(m_pConverter, + a_pOutputData, (int32_t) a_uOutputDataSize, + a_pInputData, (int32_t) a_uInputDataLen, &nError); + if (U_FAILURE(nError)) { + return false; + } + + return true; + } + + /** Calculate the number of char required by the storage format of this + * data. The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData NULL terminated string to calculate the number of + * bytes required to be converted to storage format. + * @return Number of bytes required by the string when + * converted to storage format. This size always + * includes space for the terminating NULL character. + * @return -1 cast to size_t on a conversion error. + */ + size_t SizeToStore( + const UChar * a_pInputData) + { + UErrorCode nError; + + if (!m_pConverter) { + nError = U_ZERO_ERROR; + m_pConverter = ucnv_open(m_pEncoding, &nError); + if (U_FAILURE(nError)) { + return (size_t) -1; + } + } + + nError = U_ZERO_ERROR; + ucnv_resetFromUnicode(m_pConverter); + int32_t nLen = ucnv_fromUChars(m_pConverter, NULL, 0, + a_pInputData, -1, &nError); + if (nError != U_BUFFER_OVERFLOW_ERROR) { + return (size_t) -1; + } + + return (size_t) nLen + 1; + } + + /** Convert the input string to the storage format of this data. + * The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData NULL terminated source string to convert. All of + * the data will be converted including the + * terminating NULL character. + * @param a_pOutputData Pointer to the buffer to receive the converted + * string. + * @param a_pOutputDataSize Size of the output buffer in char. + * @return true if all of the input data, including the + * terminating NULL character was successfully + * converted. + */ + bool ConvertToStore( + const UChar * a_pInputData, + char * a_pOutputData, + size_t a_uOutputDataSize) + { + UErrorCode nError; + + if (!m_pConverter) { + nError = U_ZERO_ERROR; + m_pConverter = ucnv_open(m_pEncoding, &nError); + if (U_FAILURE(nError)) { + return false; + } + } + + nError = U_ZERO_ERROR; + ucnv_resetFromUnicode(m_pConverter); + ucnv_fromUChars(m_pConverter, + a_pOutputData, (int32_t) a_uOutputDataSize, + a_pInputData, -1, &nError); + if (U_FAILURE(nError)) { + return false; + } + + return true; + } +}; + +#endif // SI_CONVERT_ICU + + +// --------------------------------------------------------------------------- +// SI_CONVERT_WIN32 +// --------------------------------------------------------------------------- +#ifdef SI_CONVERT_WIN32 + +#define SI_Case SI_GenericCase + +// Windows CE doesn't have errno or MBCS libraries +#ifdef _WIN32_WCE +# ifndef SI_NO_MBCS +# define SI_NO_MBCS +# endif +#endif +#ifdef _XBOX +#include +#else +#include +#endif + +#ifdef SI_NO_MBCS +# define SI_NoCase SI_GenericNoCase +#else // !SI_NO_MBCS +/** + * Case-insensitive comparison class using Win32 MBCS functions. This class + * returns a case-insensitive semi-collation order for MBCS text. It may not + * be safe for UTF-8 text returned in char format as we don't know what + * characters will be folded by the function! Therefore, if you are using + * SI_CHAR == char and SetUnicode(true), then you need to use the generic + * SI_NoCase class instead. + */ +#include +template +struct SI_NoCase { + bool operator()(const SI_CHAR * pLeft, const SI_CHAR * pRight) const { + if (sizeof(SI_CHAR) == sizeof(char)) { + return _mbsicmp((const unsigned char *)pLeft, + (const unsigned char *)pRight) < 0; + } + if (sizeof(SI_CHAR) == sizeof(wchar_t)) { + return _wcsicmp((const wchar_t *)pLeft, + (const wchar_t *)pRight) < 0; + } + return SI_GenericNoCase()(pLeft, pRight); + } +}; +#endif // SI_NO_MBCS + +/** + * Converts MBCS and UTF-8 to a wchar_t (or equivalent) on Windows. This uses + * only the Win32 functions and doesn't require the external Unicode UTF-8 + * conversion library. It will not work on Windows 95 without using Microsoft + * Layer for Unicode in your application. + */ +template +class SI_ConvertW { + UINT m_uCodePage; +protected: + SI_ConvertW() { } +public: + SI_ConvertW(bool a_bStoreIsUtf8) { + m_uCodePage = a_bStoreIsUtf8 ? CP_UTF8 : CP_ACP; + } + + /* copy and assignment */ + SI_ConvertW(const SI_ConvertW & rhs) { operator=(rhs); } + SI_ConvertW & operator=(const SI_ConvertW & rhs) { + m_uCodePage = rhs.m_uCodePage; + return *this; + } + + /** Calculate the number of SI_CHAR required for converting the input + * from the storage format. The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData Data in storage format to be converted to SI_CHAR. + * @param a_uInputDataLen Length of storage format data in bytes. This + * must be the actual length of the data, including + * NULL byte if NULL terminated string is required. + * @return Number of SI_CHAR required by the string when + * converted. If there are embedded NULL bytes in the + * input data, only the string up and not including + * the NULL byte will be converted. + * @return -1 cast to size_t on a conversion error. + */ + size_t SizeFromStore( + const char * a_pInputData, + size_t a_uInputDataLen) + { + SI_ASSERT(a_uInputDataLen != (size_t) -1); + + int retval = MultiByteToWideChar( + m_uCodePage, 0, + a_pInputData, (int) a_uInputDataLen, + 0, 0); + return (size_t)(retval > 0 ? retval : -1); + } + + /** Convert the input string from the storage format to SI_CHAR. + * The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData Data in storage format to be converted to SI_CHAR. + * @param a_uInputDataLen Length of storage format data in bytes. This + * must be the actual length of the data, including + * NULL byte if NULL terminated string is required. + * @param a_pOutputData Pointer to the output buffer to received the + * converted data. + * @param a_uOutputDataSize Size of the output buffer in SI_CHAR. + * @return true if all of the input data was successfully + * converted. + */ + bool ConvertFromStore( + const char * a_pInputData, + size_t a_uInputDataLen, + SI_CHAR * a_pOutputData, + size_t a_uOutputDataSize) + { + int nSize = MultiByteToWideChar( + m_uCodePage, 0, + a_pInputData, (int) a_uInputDataLen, + (wchar_t *) a_pOutputData, (int) a_uOutputDataSize); + return (nSize > 0); + } + + /** Calculate the number of char required by the storage format of this + * data. The storage format is always UTF-8. + * + * @param a_pInputData NULL terminated string to calculate the number of + * bytes required to be converted to storage format. + * @return Number of bytes required by the string when + * converted to storage format. This size always + * includes space for the terminating NULL character. + * @return -1 cast to size_t on a conversion error. + */ + size_t SizeToStore( + const SI_CHAR * a_pInputData) + { + int retval = WideCharToMultiByte( + m_uCodePage, 0, + (const wchar_t *) a_pInputData, -1, + 0, 0, 0, 0); + return (size_t) (retval > 0 ? retval : -1); + } + + /** Convert the input string to the storage format of this data. + * The storage format is always UTF-8 or MBCS. + * + * @param a_pInputData NULL terminated source string to convert. All of + * the data will be converted including the + * terminating NULL character. + * @param a_pOutputData Pointer to the buffer to receive the converted + * string. + * @param a_pOutputDataSize Size of the output buffer in char. + * @return true if all of the input data, including the + * terminating NULL character was successfully + * converted. + */ + bool ConvertToStore( + const SI_CHAR * a_pInputData, + char * a_pOutputData, + size_t a_uOutputDataSize) + { + int retval = WideCharToMultiByte( + m_uCodePage, 0, + (const wchar_t *) a_pInputData, -1, + a_pOutputData, (int) a_uOutputDataSize, 0, 0); + return retval > 0; + } +}; + +#endif // SI_CONVERT_WIN32 + + +// --------------------------------------------------------------------------- +// TYPE DEFINITIONS +// --------------------------------------------------------------------------- + +typedef CSimpleIniTempl,SI_ConvertA > CSimpleIniA; +typedef CSimpleIniTempl,SI_ConvertA > CSimpleIniCaseA; + +#if defined(SI_CONVERT_ICU) +typedef CSimpleIniTempl,SI_ConvertW > CSimpleIniW; +typedef CSimpleIniTempl,SI_ConvertW > CSimpleIniCaseW; +#else +typedef CSimpleIniTempl,SI_ConvertW > CSimpleIniW; +typedef CSimpleIniTempl,SI_ConvertW > CSimpleIniCaseW; +#endif + +#ifdef _UNICODE +# define CSimpleIni CSimpleIniW +# define CSimpleIniCase CSimpleIniCaseW +# define SI_NEWLINE SI_NEWLINE_W +#else // !_UNICODE +# define CSimpleIni CSimpleIniA +# define CSimpleIniCase CSimpleIniCaseA +# define SI_NEWLINE SI_NEWLINE_A +#endif // _UNICODE + +#ifdef _MSC_VER +# pragma warning (pop) +#endif + +#endif // INCLUDED_SimpleIni_h + diff --git a/xbox1/RetroLaunch/Surface.cpp b/xbox1/RetroLaunch/Surface.cpp new file mode 100644 index 0000000000..f4ca398534 --- /dev/null +++ b/xbox1/RetroLaunch/Surface.cpp @@ -0,0 +1,255 @@ +/** + * Surreal 64 Launcher (C) 2003 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: email: buttza@hotmail.com, lantus@lantus-x.com + * + * Additional code and cleanups: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#include "Surface.h" +#include "Debug.h" + +CSurface::CSurface() +{ + m_pTexture = NULL; + m_pVertexBuffer = NULL; + m_byOpacity = 255; + m_byR = 255; + m_byG = 255; + m_byB = 255; + m_bLoaded = false; + m_x = 0; + m_y = 0; +} + +CSurface::CSurface(const string &szFilename) +{ + CSurface(); + Create(szFilename); +} + +CSurface::~CSurface() +{ + Destroy(); +} + +bool CSurface::Create(const string &szFilename) +{ + if (m_bLoaded) + Destroy(); + + g_hResult = D3DXCreateTextureFromFileExA(g_video.m_pD3DDevice, // d3d device + ("D:\\" + szFilename).c_str(), // filename + D3DX_DEFAULT, D3DX_DEFAULT, // width/height + D3DX_DEFAULT, // mipmaps + 0, // usage + D3DFMT_A8R8G8B8, // format + D3DPOOL_MANAGED, // memory class + D3DX_DEFAULT, // texture filter + D3DX_DEFAULT, // mipmapping + 0, // colorkey + &m_imageInfo, // image info + NULL, // pallete + &m_pTexture); // texture + + if (FAILED(g_hResult)) + { + g_debug.Print("Failed: D3DXCreateTextureFromFileExA()\n"); + return false; + } + + // create a vertex buffer for the quad that will display the texture + g_hResult = g_video.m_pD3DDevice->CreateVertexBuffer(4 * sizeof(CustomVertex), + D3DUSAGE_WRITEONLY, + D3DFVF_CUSTOMVERTEX, + D3DPOOL_MANAGED, &m_pVertexBuffer); + if (FAILED(g_hResult)) + { + g_debug.Print("Failed: CreateVertexBuffer()\n"); + m_pTexture->Release(); + return false; + } + + m_bLoaded = true; + + return true; +} + +bool CSurface::Create(dword width, dword height) +{ + if (m_bLoaded) + Destroy(); + + g_hResult = g_video.m_pD3DDevice->CreateTexture(width, height, 1, 0, + D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, + &m_pTexture); + + if (FAILED(g_hResult)) + { + g_debug.Print("Failed: CreateTexture()\n"); + return false; + } + + m_imageInfo.Width = width; + m_imageInfo.Height = height; + m_imageInfo.Format = D3DFMT_A8R8G8B8; + + // create a vertex buffer for the quad that will display the texture + g_hResult = g_video.m_pD3DDevice->CreateVertexBuffer(4 * sizeof(CustomVertex), + D3DUSAGE_WRITEONLY, + D3DFVF_CUSTOMVERTEX, + D3DPOOL_MANAGED, &m_pVertexBuffer); + if (FAILED(g_hResult)) + { + g_debug.Print("Failed: CreateVertexBuffer()\n"); + m_pTexture->Release(); + return false; + } + + m_bLoaded = true; + + return true; +} + +void CSurface::Destroy() +{ + // free the vertex buffer + if (m_pVertexBuffer) + { + m_pVertexBuffer->Release(); + m_pVertexBuffer = NULL; + } + + // free the texture + if (m_pTexture) + { + m_pTexture->Release(); + m_pTexture = NULL; + } + + m_bLoaded = false; +} + +bool CSurface::IsLoaded() +{ + return m_bLoaded; +} + +bool CSurface::Render() +{ + return Render(m_x, m_y); +} + +bool CSurface::Render(int x, int y) +{ + return Render(x, y, m_imageInfo.Width, m_imageInfo.Height); +} + +bool CSurface::Render(int x, int y, dword w, dword h) +{ + if (m_pTexture == NULL || m_pVertexBuffer == NULL || m_bLoaded == false) + return false; + + float fX = static_cast(x); + float fY = static_cast(y); + + // create the new vertices + CustomVertex newVerts[] = + { + // x, y, z, color, u ,v + {fX, fY, 0.0f, D3DCOLOR_ARGB(m_byOpacity, m_byR, m_byG, m_byB), 0, 0}, + {fX + w, fY, 0.0f, D3DCOLOR_ARGB(m_byOpacity, m_byR, m_byG, m_byB), 1, 0}, + {fX + w, fY + h, 0.0f, D3DCOLOR_ARGB(m_byOpacity, m_byR, m_byG, m_byB), 1, 1}, + {fX, fY + h, 0.0f, D3DCOLOR_ARGB(m_byOpacity, m_byR, m_byG, m_byB), 0, 1} + }; + + // load the existing vertices + CustomVertex *pCurVerts; + + g_hResult = m_pVertexBuffer->Lock(0, 0, (byte **)&pCurVerts, 0); + + if (FAILED(g_hResult)) + { + g_debug.Print("Failed: m_pVertexBuffer->Lock()\n"); + return false; + } + // copy the new verts over the old verts + memcpy(pCurVerts, newVerts, 4 * sizeof(CustomVertex)); + + m_pVertexBuffer->Unlock(); + + + g_video.m_pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); + g_video.m_pD3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); + g_video.m_pD3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); + + // also blend the texture with the set alpha value + g_video.m_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); + g_video.m_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE); + g_video.m_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_TEXTURE); + + // draw the quad + g_video.m_pD3DDevice->SetTexture(0, m_pTexture); + g_video.m_pD3DDevice->SetStreamSource(0, m_pVertexBuffer, sizeof(CustomVertex)); + g_video.m_pD3DDevice->SetVertexShader(D3DFVF_CUSTOMVERTEX); +#ifdef _XBOX + g_video.m_pD3DDevice->DrawPrimitive(D3DPT_QUADLIST, 0, 1); +#else + //FIXME: vertices order ! + g_video.m_pD3DDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 2); +#endif + return true; +} + +void CSurface::SetOpacity(byte opacity) +{ + m_byOpacity = opacity; +} + +void CSurface::SetTint(byte r, byte g, byte b) +{ + m_byR = r; + m_byG = g; + m_byB = b; +} + +void CSurface::MoveTo(int x, int y) +{ + m_x = x; + m_y = y; +} + +dword CSurface::GetWidth() +{ + if (m_pTexture == NULL || m_pVertexBuffer == NULL) + return 0; + + return m_imageInfo.Width; +} + +dword CSurface::GetHeight() +{ + if (m_pTexture == NULL || m_pVertexBuffer == NULL) + return 0; + + return m_imageInfo.Height; +} + +byte CSurface::GetOpacity() +{ + return m_byOpacity; +} + +IDirect3DTexture8 *CSurface::GetTexture() +{ + return m_pTexture; +} diff --git a/xbox1/RetroLaunch/Surface.h b/xbox1/RetroLaunch/Surface.h new file mode 100644 index 0000000000..752ee12f93 --- /dev/null +++ b/xbox1/RetroLaunch/Surface.h @@ -0,0 +1,90 @@ +/** + * Surreal 64 Launcher (C) 2003 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: email: buttza@hotmail.com, lantus@lantus-x.com + * + * Additional code and cleanups: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#pragma once + +#include "Global.h" +#include "Video.h" + +class CSurface +{ +public: + CSurface(); + CSurface(const string &szFilename); + ~CSurface(); + + /** + * Do functions + */ + bool Create(const string &szFilename); + bool Create(dword width, dword height); + void Destroy(); + + bool IsLoaded(); + + bool Render(); + bool Render(int x, int y); + bool Render(int x, int y, dword w, dword h); + + /** + * Set functions + */ + void SetOpacity(byte opacity); + void SetTint(byte r, byte g, byte b); + + void MoveTo(int x, int y); + + /** + * Get functions + */ + dword GetWidth(); + dword GetHeight(); + + byte GetOpacity(); + + IDirect3DTexture8 *GetTexture(); + +private: + /** + * A d3d texture object that will contain the loaded texture + * and a d3d vertex buffer object that will contain the vertex + * buffer for the quad which will display the texture + */ + IDirect3DTexture8 *m_pTexture; + IDirect3DVertexBuffer8 *m_pVertexBuffer; + + /** + * The default render position of the texture + */ + int m_x, m_y; + + /** + * The width and height of the texture + */ + D3DXIMAGE_INFO m_imageInfo; + + /** + * The opacity of the texture + */ + byte m_byOpacity; + byte m_byR, m_byG, m_byB; + + /** + * Whether the texture has been created or not + */ + bool m_bLoaded; +}; diff --git a/xbox1/RetroLaunch/Undocumented.h b/xbox1/RetroLaunch/Undocumented.h new file mode 100644 index 0000000000..927280241d --- /dev/null +++ b/xbox1/RetroLaunch/Undocumented.h @@ -0,0 +1,1373 @@ +// Thanks and credit to everlame, Team Evox, and Woodoo. +// +// This file contains declarations for accessing the internal NT API. +// Some calls have changed from NT, so be careful! +// +// For the most part, all NT calls use ANSI instead of Unicode strings now. +// +// It is not known which flags work. You will have to experiment. + +#ifndef __XBOX_INTERNAL_H__ +#define __XBOX_INTERNAL_H__ + +#include + +// Do extern "C" for C++ +#if defined(__cplusplus) && !defined(XBOXINTERNAL_NO_EXTERN_C) +extern "C" { +#endif // __cplusplus + + +// Don't do __declspec(dllimport) for things like emulators +#if defined(NTSYSAPI) && defined(DONT_IMPORT_INTERNAL) +#undef NTSYSAPI +#endif +#ifdef DONT_IMPORT_INTERNAL +#define NTSYSAPI +#endif + +// The normal headers don't have this...? +#define FASTCALL __fastcall + +// The usual NTSTATUS +typedef LONG NTSTATUS; + +// The usual NT_SUCCESS +#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0) + +// Just for documentation +#define EXPORTNUM(x) + + +// Needed for object structures and related things +typedef CONST SHORT CSHORT; + + +// String types +typedef CHAR *PSZ; +typedef CONST CHAR *PCSZ; + +// ANSI_STRING +// Differences from NT: None. +typedef struct _STRING { + USHORT Length; + USHORT MaximumLength; + PCHAR Buffer; +} STRING; +typedef STRING *PSTRING; + +typedef STRING ANSI_STRING; +typedef PSTRING PANSI_STRING; + + +// IO Status Block type (UNVERIFIED) +// Differences from NT: None. +typedef struct _IO_STATUS_BLOCK { + union { + NTSTATUS Status; + PVOID Pointer; + }; + + ULONG_PTR Information; +} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK; + +// APC routine +typedef +VOID +(NTAPI *PIO_APC_ROUTINE) ( + IN PVOID ApcContext, + IN PIO_STATUS_BLOCK IoStatusBlock, + IN ULONG Reserved + ); + + +// Header for dispatcher objects +// Differences from NT: None. +typedef struct _DISPATCHER_HEADER { + UCHAR Type; + UCHAR Absolute; + UCHAR Size; + UCHAR Inserted; + LONG SignalState; + LIST_ENTRY WaitListHead; +} DISPATCHER_HEADER; + + +// Object types +#define NotificationTimerObject 8 +#define SynchronizationTimerObject 9 +#define DpcObject 19 + + +// Object Attributes type +// Differences from NT: There are no Length, SecurityDescriptor, or +// SecurityQualityOfService fields. Also, ObjectName is ANSI, not +// Unicode. +typedef struct _OBJECT_ATTRIBUTES { + HANDLE RootDirectory; + PANSI_STRING ObjectName; + ULONG Attributes; +} OBJECT_ATTRIBUTES; +typedef OBJECT_ATTRIBUTES *POBJECT_ATTRIBUTES; + +// Flags for OBJECT_ATTRIBUTES::Attributes +#define OBJ_INHERIT 0x00000002L +#define OBJ_PERMANENT 0x00000010L +#define OBJ_EXCLUSIVE 0x00000020L +#define OBJ_CASE_INSENSITIVE 0x00000040L +#define OBJ_OPENIF 0x00000080L +#define OBJ_OPENLINK 0x00000100L +#define OBJ_KERNEL_HANDLE 0x00000200L +#define OBJ_VALID_ATTRIBUTES 0x000003F2L + +// Initializes an OBJECT_ATTRIBUTES. +// Works as if it were this function: +// VOID +// InitializeObjectAttributes( +// OUT POBJECT_ATTRIBUTES p, +// IN PANSI_STRING n, +// IN ULONG a, +// IN HANDLE r +// ) +// Differences from NT: SECURITY_DESCRIPTOR support is gone. +#define InitializeObjectAttributes( p, n, a, r ) { \ + (p)->RootDirectory = r; \ + (p)->Attributes = a; \ + (p)->ObjectName = n; \ + } + + +// CreateDisposition values for NtCreateFile() +#define FILE_SUPERSEDE 0x00000000 +#define FILE_OPEN 0x00000001 +#define FILE_CREATE 0x00000002 +#define FILE_OPEN_IF 0x00000003 +#define FILE_OVERWRITE 0x00000004 +#define FILE_OVERWRITE_IF 0x00000005 +#define FILE_MAXIMUM_DISPOSITION 0x00000005 + +// CreateOption values for NtCreateFile() +// FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT is what CreateFile +// uses for most things when translating to NtCreateFile. +#define FILE_DIRECTORY_FILE 0x00000001 +#define FILE_WRITE_THROUGH 0x00000002 +#define FILE_SEQUENTIAL_ONLY 0x00000004 +#define FILE_NO_INTERMEDIATE_BUFFERING 0x00000008 +#define FILE_SYNCHRONOUS_IO_ALERT 0x00000010 +#define FILE_SYNCHRONOUS_IO_NONALERT 0x00000020 +#define FILE_NON_DIRECTORY_FILE 0x00000040 +#define FILE_CREATE_TREE_CONNECTION 0x00000080 +#define FILE_COMPLETE_IF_OPLOCKED 0x00000100 +#define FILE_NO_EA_KNOWLEDGE 0x00000200 +#define FILE_OPEN_FOR_RECOVERY 0x00000400 +#define FILE_RANDOM_ACCESS 0x00000800 +#define FILE_DELETE_ON_CLOSE 0x00001000 +#define FILE_OPEN_BY_FILE_ID 0x00002000 +#define FILE_OPEN_FOR_BACKUP_INTENT 0x00004000 +#define FILE_NO_COMPRESSION 0x00008000 +#define FILE_RESERVE_OPFILTER 0x00100000 +#define FILE_OPEN_REPARSE_POINT 0x00200000 +#define FILE_OPEN_NO_RECALL 0x00400000 +#define FILE_OPEN_FOR_FREE_SPACE_QUERY 0x00800000 +#define FILE_COPY_STRUCTURED_STORAGE 0x00000041 +#define FILE_STRUCTURED_STORAGE 0x00000441 +#define FILE_VALID_OPTION_FLAGS 0x00ffffff +#define FILE_VALID_PIPE_OPTION_FLAGS 0x00000032 +#define FILE_VALID_MAILSLOT_OPTION_FLAGS 0x00000032 +#define FILE_VALID_SET_FLAGS 0x00000036 + + +// NtQueryVolumeInformation / NtSetVolumeInformation stuff +// Type of information to retrieve; FileFsSizeInformation and +// FileFsDeviceInformation are the only ones confirmed to work. +typedef enum _FSINFOCLASS { + FileFsVolumeInformation = 1, + FileFsLabelInformation, + FileFsSizeInformation, + FileFsDeviceInformation, + FileFsAttributeInformation, + FileFsControlInformation, + FileFsFullSizeInformation, + FileFsObjectInformation +} FS_INFORMATION_CLASS, *PFS_INFORMATION_CLASS; + +// Structure of FileFsSizeInformation +typedef struct _FILE_FS_SIZE_INFORMATION { + LARGE_INTEGER TotalAllocationUnits; + LARGE_INTEGER AvailableAllocationUnits; + ULONG SectorsPerAllocationUnit; + ULONG BytesPerSector; +} FILE_FS_SIZE_INFORMATION, *PFILE_FS_SIZE_INFORMATION; + +#define DEVICE_TYPE ULONG + +// Structure of FileFsDeviceInformation +typedef struct _FILE_FS_DEVICE_INFORMATION { + DEVICE_TYPE DeviceType; + ULONG Characteristics; +} FILE_FS_DEVICE_INFORMATION, *PFILE_FS_DEVICE_INFORMATION; + +// DEVICE_TYPEs (I took a guess as to which the XBOX might have.) +#define FILE_DEVICE_CD_ROM 0x00000002 +#define FILE_DEVICE_CD_ROM_FILE_SYSTEM 0x00000003 +#define FILE_DEVICE_CONTROLLER 0x00000004 +#define FILE_DEVICE_DISK 0x00000007 +#define FILE_DEVICE_DISK_FILE_SYSTEM 0x00000008 +#define FILE_DEVICE_FILE_SYSTEM 0x00000009 +#define FILE_DEVICE_NULL 0x00000015 +#define FILE_DEVICE_SCREEN 0x0000001c +#define FILE_DEVICE_SOUND 0x0000001d +#define FILE_DEVICE_UNKNOWN 0x00000022 +#define FILE_DEVICE_VIDEO 0x00000023 +#define FILE_DEVICE_VIRTUAL_DISK 0x00000024 +#define FILE_DEVICE_FULLSCREEN_VIDEO 0x00000034 + +// Characteristics +#define FILE_REMOVABLE_MEDIA 0x00000001 +#define FILE_READ_ONLY_DEVICE 0x00000002 +#define FILE_FLOPPY_DISKETTE 0x00000004 +#define FILE_WRITE_ONCE_MEDIA 0x00000008 +#define FILE_REMOTE_DEVICE 0x00000010 +#define FILE_DEVICE_IS_MOUNTED 0x00000020 +#define FILE_VIRTUAL_VOLUME 0x00000040 +#define FILE_AUTOGENERATED_DEVICE_NAME 0x00000080 +#define FILE_DEVICE_SECURE_OPEN 0x00000100 + + + +// Physical address +// Differences from NT: 32 bit address instead of 64. +typedef ULONG PHYSICAL_ADDRESS, *PPHYSICAL_ADDRESS; + + +// NtCreateFile/NtOpenFile stuff +#define FILE_SUPERSEDED 0x00000000 +#define FILE_OPENED 0x00000001 +#define FILE_CREATED 0x00000002 +#define FILE_OVERWRITTEN 0x00000003 +#define FILE_EXISTS 0x00000004 +#define FILE_DOES_NOT_EXIST 0x00000005 + +// NtReadFile/NtWriteFile stuff +#define FILE_WRITE_TO_END_OF_FILE 0xffffffff +#define FILE_USE_FILE_POINTER_POSITION 0xfffffffe + + + +// DeviceIoControl stuff + +// Device types +#define FILE_DEVICE_CD_ROM 0x00000002 +#define FILE_DEVICE_CD_ROM_FILE_SYSTEM 0x00000003 +#define FILE_DEVICE_CONTROLLER 0x00000004 +#define FILE_DEVICE_SCSI FILE_DEVICE_CONTROLLER +#define IOCTL_SCSI_BASE FILE_DEVICE_CONTROLLER +#define FILE_DEVICE_DISK 0x00000007 +#define FILE_DEVICE_DISK_FILE_SYSTEM 0x00000008 +#define FILE_DEVICE_DVD 0x00000033 + +// Access types +#define FILE_ANY_ACCESS 0 +#define FILE_READ_ACCESS ( 0x0001 ) // file & pipe +#define FILE_WRITE_ACCESS ( 0x0002 ) // file & pipe + +// Method types +#define METHOD_BUFFERED 0 +#define METHOD_IN_DIRECT 1 +#define METHOD_OUT_DIRECT 2 +#define METHOD_NEITHER 3 + +// The all-important CTL_CODE +#define CTL_CODE( DeviceType, Function, Method, Access ) ( \ + ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \ +) + +// IDE/SCSI codes +// IOCTL_SCSI_PASS_THROUGH_DIRECT is the only one known to be used. +// Differences from NT: None. +#define IOCTL_SCSI_PASS_THROUGH CTL_CODE(IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) +#define IOCTL_SCSI_MINIPORT CTL_CODE(IOCTL_SCSI_BASE, 0x0402, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) +#define IOCTL_SCSI_GET_INQUIRY_DATA CTL_CODE(IOCTL_SCSI_BASE, 0x0403, METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE(IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE(IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) +#define IOCTL_SCSI_GET_ADDRESS CTL_CODE(IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_SCSI_RESCAN_BUS CTL_CODE(IOCTL_SCSI_BASE, 0x0407, METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_SCSI_GET_DUMP_POINTERS CTL_CODE(IOCTL_SCSI_BASE, 0x0408, METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_SCSI_FREE_DUMP_POINTERS CTL_CODE(IOCTL_SCSI_BASE, 0x0409, METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_IDE_PASS_THROUGH CTL_CODE(IOCTL_SCSI_BASE, 0x040a, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// Special XBOX code? +#define IOCTL_CDROM_AUTHENTICATE_DISK CTL_CODE(FILE_DEVICE_CD_ROM, 0x0020, METHOD_BUFFERED, FILE_READ_ACCESS) + +// Structure for IOCTL_SCSI_PASS_THROUGH_DIRECT +// Differences from NT: None, believe it or not. +typedef struct _SCSI_PASS_THROUGH_DIRECT { + /*000*/ USHORT Length; + /*002*/ UCHAR ScsiStatus; + /*003*/ UCHAR PathId; + /*004*/ UCHAR TargetId; + /*005*/ UCHAR Lun; + /*006*/ UCHAR CdbLength; + /*007*/ UCHAR SenseInfoLength; + /*008*/ UCHAR DataIn; + /*00C*/ ULONG DataTransferLength; + /*010*/ ULONG TimeOutValue; + /*014*/ PVOID DataBuffer; + /*018*/ ULONG SenseInfoOffset; + /*01C*/ UCHAR Cdb[16]; +}SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT; + +// DataIn fields for IOCTL_SCSI_PASS_THROUGH_DIRECT +#define SCSI_IOCTL_DATA_OUT 0 +#define SCSI_IOCTL_DATA_IN 1 +#define SCSI_IOCTL_DATA_UNSPECIFIED 2 + +// Kernel object type (unsure about the structure...) +typedef struct _OBJECT_TYPE +{ + // Same prototype as ExAllocatePoolWithTag, because that's the usual one + PVOID + (NTAPI *AllocationFunction)( + SIZE_T NumberOfBytes, + ULONG Tag + ); + + // Same prototype as ExFreePool, because that's the usual one + VOID + (NTAPI *FreeFunction)( + IN PVOID P + ); + + // The prototypes of these are unknown + void *CloseFunction; + void *DeleteFunction; + void *ParseFunction; + + // Unknown DWORD... Size of this object type maybe? + void *DefaultObjectMaybe; + + // 4 letter tag for this object type + CHAR Tag[4]; +} OBJECT_TYPE; +typedef OBJECT_TYPE *POBJECT_TYPE; + +// Object types +extern POBJECT_TYPE IoFileObjectType; +extern POBJECT_TYPE ExEventObjectType; +extern POBJECT_TYPE ExSemaphoreObjectType; +extern POBJECT_TYPE IoCompletionObjectType; +extern POBJECT_TYPE IoDeviceObjectType; + + +// *_OBJECT and related structures (mostly opaque since I'm lazy) +typedef struct _DRIVER_OBJECT { + CSHORT Type; + CSHORT Size; + struct _DEVICE_OBJECT *DeviceObject; + // ... +} DRIVER_OBJECT; +typedef DRIVER_OBJECT *PDRIVER_OBJECT; + +typedef struct _DEVICE_OBJECT { + CSHORT Type; + USHORT Size; + LONG ReferenceCount; + PDRIVER_OBJECT DriverObject; + // ... +} DEVICE_OBJECT; +typedef DEVICE_OBJECT *PDEVICE_OBJECT; + +typedef struct _FILE_OBJECT { + CSHORT Type; + CSHORT Size; + PDEVICE_OBJECT DeviceObject; + // ... +} FILE_OBJECT; +typedef FILE_OBJECT *PFILE_OBJECT; + + +// Thread information structures + +// IRQL +typedef UCHAR KIRQL, *PKIRQL; +#define PASSIVE_LEVEL 0 // Passive release level +#define LOW_LEVEL 0 // Lowest interrupt level +#define APC_LEVEL 1 // APC interrupt level +#define DISPATCH_LEVEL 2 // Dispatcher level + +// Thread entry point +// NOTE: This is not a standard call! You can't call this function from C code! +// You push registers like stdcall, but ebp + 4 must point to the first argument before the call! +// +// Differences from NT: 2 parameters instead of 1; strange calling convention +typedef +VOID +(NTAPI *PKSTART_ROUTINE) ( + IN PVOID StartContext1, + IN PVOID StartContext2 + ); + +// Structure of a critical section +// Same as the XBOX's RTL_CRITICAL_SECTION, but with the more explicit header +typedef struct _KCRITICAL_SECTION +{ + // 000 Dispatcher header + DISPATCHER_HEADER Header; + // 010 Lock count of the critical section + LONG LockCount; + // 014 Recursion count of the critical section + LONG RecursionCount; + // 018 Thread ID of the thread that currently owns this critical section + ULONG OwningThread; +} KCRITICAL_SECTION, *PKCRITICAL_SECTION; + +// Structure of a thread object +typedef struct _KTHREAD +{ + // 000 Dispatcher header + DISPATCHER_HEADER Header; + // 010 Unknown + BYTE unknown[0x18]; + // 028 Pointer to TLS data + PVOID TlsData; + // ??? just padding - real size is unknown + BYTE unknown2[0x100]; +} KTHREAD, *PKTHREAD; + +// Structure of the data at FS +typedef struct _FS_STRUCTURE +{ + // 000 Current exception handler information + PVOID *ExceptionFrame; + // 004 Pointer to current TLS data top + PVOID TlsDataTop; + // 008 + BYTE unknown2[0x1C]; + // 024 Current IRQL of the OS + KIRQL CurrentIrql; + // 028 Thread structure of the current thread + PKTHREAD ThreadObject; + // ??? just padding - real size is unknown + BYTE unknown3[0x100]; +} FS_STRUCTURE, *PFS_STRUCTURE; + +// DPC routine +typedef +VOID +(*PKDEFERRED_ROUTINE) ( + IN struct _KDPC *Dpc, + IN PVOID DeferredContext, + IN PVOID SystemArgument1, + IN PVOID SystemArgument2 + ); + +// DPC information +// It's not known which of these fields are used on XBOX. +typedef struct _KDPC { + CSHORT Type; + UCHAR Number; + UCHAR Importance; + LIST_ENTRY DpcListEntry; + PKDEFERRED_ROUTINE DeferredRoutine; + PVOID DeferredContext; + PVOID SystemArgument1; + PVOID SystemArgument2; + PULONG_PTR Lock; +} KDPC, *PKDPC; + + +// Timers +typedef enum _TIMER_TYPE { + NotificationTimer, + SynchronizationTimer + } TIMER_TYPE; + +typedef struct _KTIMER { + DISPATCHER_HEADER Header; + ULARGE_INTEGER DueTime; + LIST_ENTRY TimerListEntry; + struct _KDPC *Dpc; + LONG Period; +} KTIMER, *PKTIMER; + + + +// XBE stuff +// Not used in any exported kernel calls, but still useful. + + +// XBE header information +typedef struct _XBE_HEADER { + // 000 "XBEH" + CHAR Magic[4]; + // 004 RSA digital signature of the entire header area + UCHAR HeaderSignature[256]; + // 104 Base address of XBE image (must be 0x00010000?) + PVOID BaseAddress; + // 108 Size of all headers combined - other headers must be within this + ULONG HeaderSize; + // 10C Size of entire image + ULONG ImageSize; + // 110 Size of this header (always 0x178?) + ULONG XbeHeaderSize; + // 114 Image timestamp - unknown format + ULONG Timestamp; + // 118 Pointer to certificate data (must be within HeaderSize) + struct _XBE_CERTIFICATE *Certificate; + // 11C Number of sections + DWORD NumSections; + // 120 Pointer to section headers (must be within HeaderSize) + struct _XBE_SECTION *Sections; + // 124 Initialization flags + ULONG InitFlags; + // 128 Entry point (XOR'd; see xboxhacker.net) + PVOID EntryPoint; + // 12C Pointer to TLS directory + struct _XBE_TLS_DIRECTORY *TlsDirectory; + // 130 Stack commit size + ULONG StackCommit; + // 134 Heap reserve size + ULONG HeapReserve; + // 138 Heap commit size + ULONG HeapCommit; + // 13C PE base address (?) + PVOID PeBaseAddress; + // 140 PE image size (?) + ULONG PeImageSize; + // 144 PE checksum (?) + ULONG PeChecksum; + // 148 PE timestamp (?) + ULONG PeTimestamp; + // 14C PC path and filename to EXE file from which XBE is derived + PCSZ PcExePath; + // 150 PC filename (last part of PcExePath) from which XBE is derived + PCSZ PcExeFilename; + // 154 PC filename (Unicode version of PcExeFilename) + PWSTR PcExeFilenameUnicode; + // 158 Pointer to kernel thunk table (XOR'd; EFB1F152 debug) + ULONG_PTR *KernelThunkTable; + // 15C Non-kernel import table (debug only) + PVOID DebugImportTable; + // 160 Number of library headers + ULONG NumLibraries; + // 164 Pointer to library headers + struct _XBE_LIBRARY *Libraries; + // 168 Pointer to kernel library header + struct _XBE_LIBRARY *KernelLibrary; + // 16C Pointer to XAPI library + struct _XBE_LIBRARY *XapiLibrary; + // 170 Pointer to logo bitmap (NULL = use default of Microsoft) + PVOID LogoBitmap; + // 174 Size of logo bitmap + ULONG LogoBitmapSize; + // 178 +} XBE_HEADER, *PXBE_HEADER; + +// Certificate structure +typedef struct _XBE_CERTIFICATE { + // 000 Size of certificate + ULONG Size; + // 004 Certificate timestamp (unknown format) + ULONG Timestamp; + // 008 Title ID + ULONG TitleId; + // 00C Name of the game (Unicode) + WCHAR TitleName[40]; + // 05C Alternate title ID's (0-terminated) + ULONG AlternateTitleIds[16]; + // 09C Allowed media types - 1 bit match between XBE and media = boots + ULONG MediaTypes; + // 0A0 Allowed game regions - 1 bit match between this and XBOX = boots + ULONG GameRegion; + // 0A4 Allowed game ratings - 1 bit match between this and XBOX = boots + ULONG GameRating; + // 0A8 Disk number (?) + ULONG DiskNumber; + // 0AC Version (?) + ULONG Version; + // 0B0 LAN key for this game + UCHAR LanKey[16]; + // 0C0 Signature key for this game + UCHAR SignatureKey[16]; + // 0D0 Signature keys for the alternate title ID's + UCHAR AlternateSignatureKeys[16][16]; + // 1D0 +} XBE_CERTIFICATE, *PXBE_CERTIFICATE; + +// Section headers +typedef struct _XBE_SECTION { + // 000 Flags + ULONG Flags; + // 004 Virtual address (where this section loads in RAM) + PVOID VirtualAddress; + // 008 Virtual size (size of section in RAM; after FileSize it's 00'd) + ULONG VirtualSize; + // 00C File address (where in the file from which this section comes) + ULONG FileAddress; + // 010 File size (size of the section in the XBE file) + ULONG FileSize; + // 014 Pointer to section name + PCSZ SectionName; + // 018 Section reference count - when >= 1, section is loaded + LONG SectionReferenceCount; + // 01C Pointer to head shared page reference count + WORD *HeadReferenceCount; + // 020 Pointer to tail shared page reference count + WORD *TailReferenceCount; + // 024 SHA hash. Hash DWORD containing FileSize, then hash section. + DWORD ShaHash[5]; + // 038 +} XBE_SECTION, *PXBE_SECTION; + +// TLS directory information needed later +// Library version data needed later + +// Initialization flags +#define XBE_INIT_MOUNT_UTILITY 0x00000001 +#define XBE_INIT_FORMAT_UTILITY 0x00000002 +#define XBE_INIT_64M_RAM_ONLY 0x00000004 +#define XBE_INIT_DONT_SETUP_HDD 0x00000008 + +// Region codes +#define XBE_REGION_US_CANADA 0x00000001 +#define XBE_REGION_JAPAN 0x00000002 +#define XBE_REGION_ELSEWHERE 0x00000004 +#define XBE_REGION_DEBUG 0x80000000 + +// Media types +#define XBE_MEDIA_HDD 0x00000001 +#define XBE_MEDIA_XBOX_DVD 0x00000002 +#define XBE_MEDIA_ANY_CD_OR_DVD 0x00000004 +#define XBE_MEDIA_CD 0x00000008 +#define XBE_MEDIA_1LAYER_DVDROM 0x00000010 +#define XBE_MEDIA_2LAYER_DVDROM 0x00000020 +#define XBE_MEDIA_1LAYER_DVDR 0x00000040 +#define XBE_MEDIA_2LAYER_DVDR 0x00000080 +#define XBE_MEDIA_USB 0x00000100 +#define XBE_MEDIA_ALLOW_UNLOCKED_HDD 0x40000000 + +// Section flags +#define XBE_SEC_WRITABLE 0x00000001 +#define XBE_SEC_PRELOAD 0x00000002 +#define XBE_SEC_EXECUTABLE 0x00000004 +#define XBE_SEC_INSERTED_FILE 0x00000008 +#define XBE_SEC_RO_HEAD_PAGE 0x00000010 +#define XBE_SEC_RO_TAIL_PAGE 0x00000020 + + +// x86 page size +#define PAGE_SIZE 0x1000 + + +// Native NT API calls on the XBOX + + +// PAGE_ALIGN: +// Returns an address rounded down to the nearest page boundary. +// +// Differences from NT: None. +#define PAGE_ALIGN(Va) ((PVOID)((ULONG_PTR)(Va) & ~(PAGE_SIZE - 1))) + + +// RtlInitAnsiString: +// Fills an ANSI_STRING structure to use the specified string. +// +// Differences from NT: None. +NTSYSAPI +EXPORTNUM(289) +VOID +NTAPI +RtlInitAnsiString( + OUT PANSI_STRING DestinationString, + IN PCSZ SourceString + ); + + +// NtCreateFile: +// Creates or opens a file or device object. +// +// Differences from NT: The EaBuffer and EaLength options are gone. +// OBJECT_ATTRIBUTES uses ANSI_STRING, so only ANSI filenames work. +NTSYSAPI +EXPORTNUM(190) +NTSTATUS +NTAPI +NtCreateFile( + OUT PHANDLE FileHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN PLARGE_INTEGER AllocationSize OPTIONAL, + IN ULONG FileAttributes, + IN ULONG ShareAccess, + IN ULONG CreateDisposition, + IN ULONG CreateOptions + ); + +// NtOpenFile: +// Opens a file or device object. Same as calling: +// NtCreateFile(FileHandle, DesiredAccess, ObjectAttributes, +// IoStatusBlock, NULL, 0, ShareAccess, OPEN_EXISTING, OpenOptions); +// +// Differences from NT: See NtCreateFile. +NTSYSAPI +EXPORTNUM(202) +NTSTATUS +NTAPI +NtOpenFile( + OUT PHANDLE FileHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN ULONG ShareAccess, + IN ULONG OpenOptions + ); + +// NtReadFile: +// Reads a file. +// +// Differences from NT: There is no Key parameter. +NTSYSAPI +EXPORTNUM(219) +NTSTATUS +NTAPI +NtReadFile( + IN HANDLE FileHandle, + IN HANDLE Event OPTIONAL, + IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, + IN PVOID ApcContext OPTIONAL, + OUT PIO_STATUS_BLOCK IoStatusBlock, + OUT PVOID Buffer, + IN ULONG Length, + IN PLARGE_INTEGER ByteOffset + ); + +// NtWriteFile: +// Writes a file. +// +// Differences from NT: There is no Key parameter. +NTSYSAPI +EXPORTNUM(236) +NTSTATUS +NTAPI +NtWriteFile( + IN HANDLE FileHandle, + IN HANDLE Event OPTIONAL, + IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, + IN PVOID ApcContext OPTIONAL, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN PVOID Buffer, + IN ULONG Length, + IN PLARGE_INTEGER ByteOffset + ); + +// NtQueryVolumeInformation: +// Queries information about a file system. This is not documented by +// Microsoft even under NT. +// +// Differences from NT: None known. +NTSYSAPI +EXPORTNUM(218) +NTSTATUS +NTAPI +NtQueryVolumeInformationFile( + IN HANDLE FileHandle, + OUT PIO_STATUS_BLOCK IoStatusBlock, + OUT PVOID VolumeInformation, + IN ULONG VolumeInformationLength, + IN FS_INFORMATION_CLASS VolumeInformationClass + ); + +// NtDeviceIoControl: +// Does an IOCTL on a device. +// +// Differences from NT: None known. +NTSYSAPI +EXPORTNUM(196) +NTSTATUS +NTAPI +NtDeviceIoControlFile( + IN HANDLE FileHandle, + IN HANDLE Event OPTIONAL, + IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, + IN PVOID ApcContext OPTIONAL, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN ULONG IoControlCode, + IN PVOID InputBuffer OPTIONAL, + IN ULONG InputBufferLength, + OUT PVOID OutputBuffer OPTIONAL, + IN ULONG OutputBufferLength + ); + +// NtClose: +// Closes a file or other handle. +// +// Differences from NT: None. +NTSYSAPI +EXPORTNUM(187) +NTSTATUS +NTAPI +NtClose( + IN HANDLE Handle + ); + +// NtAllocateVirtualMemory: +// Allocates virtual memory. +// +// Differences from NT: There is no ProcessHandle parameter. +NTSYSAPI +EXPORTNUM(184) +NTSTATUS +NTAPI +NtAllocateVirtualMemory( + IN OUT PVOID *BaseAddress, + IN ULONG ZeroBits, + IN OUT PULONG AllocationSize, + IN ULONG AllocationType, + IN ULONG Protect + ); + +// NtFreeVirtualMemory: +// Frees virtual memory. +// +// Differences from NT: There is no ProcessHandle parameter. +NTSYSAPI +EXPORTNUM(199) +NTSTATUS +NTAPI +NtFreeVirtualMemory( + IN OUT PVOID *BaseAddress, + IN OUT PULONG FreeSize, + IN ULONG FreeType + ); + + +// Kernel-level routines + + +// KeBugCheck: +// Bug checks the kernel. +// Same as KeBugCheckEx(BugCheckCode, 0, 0, 0, 0); +// +// Differences from NT: None, other than the reaction. +NTSYSAPI +EXPORTNUM(95) +VOID +NTAPI +KeBugCheck( + IN ULONG BugCheckCode + ); + +// KeBugCheckEx: +// Bug checks the kernel. +// +// Differences from NT: None, other than the reaction. +NTSYSAPI +EXPORTNUM(96) +VOID +NTAPI +KeBugCheckEx( + IN ULONG BugCheckCode, + IN ULONG_PTR BugCheckParameter1, + IN ULONG_PTR BugCheckParameter2, + IN ULONG_PTR BugCheckParameter3, + IN ULONG_PTR BugCheckParameter4 + ); + +// KeInitializeDpc: +// Initializes a DPC structure. +// +// Differences from NT: This function sets less fields than the NT version. +NTSYSAPI +EXPORTNUM(107) +VOID +NTAPI +KeInitializeDpc( + IN PKDPC Dpc, + IN PKDEFERRED_ROUTINE DeferredRoutine, + IN PVOID DeferredContext + ); + +// KeInitializeTimerEx: +// Initializes a timer. +// +// Differences from NT: None. +NTSYSAPI +EXPORTNUM(113) +VOID +KeInitializeTimerEx( + IN OUT PKTIMER Timer, + IN TIMER_TYPE Type + ); + +// KeRaiseIrql: +// Raises IRQL to some value. +// +// Differences from NT: None. +#define KeRaiseIrql KfRaiseIrql +NTSYSAPI +EXPORTNUM(190) +VOID +__fastcall +KfRaiseIrql( + IN KIRQL NewIrql, + OUT PKIRQL OldIrql + ); + +// KeRaiseIrqlToDpcLevel: +// Raises IRQL to DISPATCH_LEVEL. Like KeRaiseIrql except returns old level directly. +// +// Differences from NT: None. +NTSYSAPI +EXPORTNUM(129) +KIRQL +NTAPI +KeRaiseIrqlToDpcLevel( + VOID + ); + +// KeLowerIrql: +// Lowers IRQL. +#define KeLowerIrql KfLowerIrql +NTSYSAPI +EXPORTNUM(161) +VOID +__fastcall +KfLowerIrql( + IN KIRQL NewIrql + ); + + +// MmMapIoSpace: +// Maps a physical address area into the virtual address space. +// DO NOT USE MEMORY MAPPED WITH THIS AS A BUFFER TO OTHER CALLS. For +// example, don't WriteFile or NtWriteFile these buffers. Copy them first. +// +// Differences from NT: PhysicalAddress is 32 bit, not 64. ProtectionType +// specifies the page protections, but it's a Win32 PAGE_ macro instead +// of the normal NT enumeration. PAGE_READWRITE is probably what you +// want... +NTSYSAPI +EXPORTNUM(177) +PVOID +NTAPI +MmMapIoSpace( + IN PHYSICAL_ADDRESS PhysicalAddress, + IN ULONG NumberOfBytes, + IN ULONG ProtectionType + ); + +// MmGetPhysicalAddress: +// Translates a virtual address into a physical address. +// +// Differences from NT: PhysicalAddress is 32 bit, not 64. +NTSYSAPI +EXPORTNUM(173) +PHYSICAL_ADDRESS +NTAPI +MmGetPhysicalAddress( + IN PVOID BaseAddress + ); + +// MmUnmapIoSpace: +// Unmaps a virtual address mapping made by MmMapIoSpace. +// +// Differences from NT: None. +NTSYSAPI +EXPORTNUM(183) +PVOID +NTAPI +MmUnmapIoSpace( + IN PVOID BaseAddress, + IN ULONG NumberOfBytes + ); + +// MmAllocateContiguousMemory: +// Allocates a range of physically contiguous, cache-aligned memory from the +// non-paged pool (= main pool on XBOX). +// +// Differences from NT: HighestAcceptableAddress was deleted, opting instead +// to not care about the highest address. +NTSYSAPI +EXPORTNUM(165) +PVOID +NTAPI +MmAllocateContiguousMemory( + IN ULONG NumberOfBytes + ); + +// MmFreeContiguousMemory: +// Frees memory allocated with MmAllocateContiguousMemory. +// +// Differences from NT: None. +NTSYSAPI +EXPORTNUM(171) +VOID +NTAPI +MmFreeContiguousMemory( + IN PVOID BaseAddress + ); + + +// DbgPrint +// Displays a message on the debugger. +// +// Differences from NT: Only how this information is displayed changed. +NTSYSAPI +EXPORTNUM(8) +ULONG +__cdecl +DbgPrint( + IN PCSZ Format, + ... + ); + + +// ExAllocatePoolWithTag: +// Allocates memory from the memory pool. The Tag parameter is a 4-letter +// character constant to which to associate the allocation. +// +// Differences from NT: There is no PoolType field, as the XBOX only has 1 +// pool, the non-paged pool. +NTSYSAPI +EXPORTNUM(15) +PVOID +NTAPI +ExAllocatePoolWithTag( + IN SIZE_T NumberOfBytes, + IN ULONG Tag + ); + +// ExFreePool: +// Frees memory allocated by ExAllocatePool* functions. +// +// Differences from NT: None. +NTSYSAPI +EXPORTNUM(17) +VOID +NTAPI +ExFreePool( + IN PVOID P + ); + + +// IoCreateSymbolicLink: +// Creates a symbolic link in the object namespace. +// NtCreateSymbolicLinkObject is much harder to use than this simple +// function, so just use this one. +// +// Differences from NT: Uses ANSI_STRING instead of UNICODE_STRING. +NTSYSAPI +EXPORTNUM(67) +NTSTATUS +NTAPI +IoCreateSymbolicLink( + IN PANSI_STRING SymbolicLinkName, + IN PANSI_STRING DeviceName + ); + +// IoDeleteSymbolicLink: +// Creates a symbolic link in the object namespace. Deleting symbolic links +// through the Nt* functions is a pain, so use this instead. +// +// Differences from NT: Uses ANSI_STRING instead of UNICODE_STRING. +NTSYSAPI +EXPORTNUM(69) +NTSTATUS +NTAPI +IoDeleteSymbolicLink( + IN PANSI_STRING SymbolicLinkName + ); + + +// ObReferenceObjectByHandle: +// Turns a handle into a kernel object pointer. The ObjectType parameter +// specifies what type of object it is. This function also increments the +// object's reference count. +// +// Differences from NT: There are no DesiredAccess, AccessMode, or +// HandleInformation parameters. +NTSYSAPI +EXPORTNUM(246) +NTSTATUS +NTAPI +ObReferenceObjectByHandle( + IN HANDLE Handle, + IN POBJECT_TYPE ObjectType OPTIONAL, + OUT PVOID *Object + ); + +// ObfReferenceObject/ObReferenceObject: +// Increments the object's reference count. +// +// Differences from NT: None. +#define ObReferenceObject(Object) ObfReferenceObject(Object) +NTSYSAPI +EXPORTNUM(251) +VOID +FASTCALL +ObfReferenceObject( + IN PVOID Object + ); + +// ObfDereferenceObject/ObDereferenceObject: +// Decrements the object's reference count, deleting it if it is now unused. +// +// Differences from NT: None. +#define ObDereferenceObject(a) ObfDereferenceObject(a) +NTSYSAPI +EXPORTNUM(250) +VOID +FASTCALL +ObfDereferenceObject( + IN PVOID Object + ); + + +// PsTerminateSystemThread: +// Exits the current system thread. Must be called from a system thread. +// +// Differences from NT: None. +NTSYSAPI +EXPORTNUM(258) +__declspec(noreturn) +NTSTATUS +PsTerminateSystemThread( + NTSTATUS ExitCode + ); + + + +// Kernel routines only in the XBOX + +// IoSynchronousDeviceIoControlRequest: +// NICE. Makes kernel driver stuff sooooo much easier. This does a +// blocking IOCTL on the specified device. +// +// New to the XBOX. +NTSYSAPI +EXPORTNUM(84) +NTSTATUS +NTAPI +IoSynchronousDeviceIoControlRequest( + IN ULONG IoControlCode, + IN PDEVICE_OBJECT DeviceObject, + IN PVOID InputBuffer OPTIONAL, + IN ULONG InputBufferLength, + OUT PVOID OutputBuffer OPTIONAL, + IN ULONG OutputBufferLength, + OUT PDWORD unknown_use_zero OPTIONAL, + IN BOOLEAN InternalDeviceIoControl + ); + +// ExQueryNonVolatileSettings +// Queries saved information, such as the region code. +// +// New to the XBOX. +NTSYSAPI +EXPORTNUM(24) +NTSTATUS +NTAPI +ExQueryNonVolatileSetting( + IN ULONG ValueIndex, + OUT PULONG Type, + OUT PVOID Value, + IN ULONG ValueLength, + OUT PULONG ResultLength OPTIONAL + ); + +// ExSaveNonVolatileSettings +// Writes saved information, such as the region code. +// +// New to the XBOX. +NTSYSAPI +EXPORTNUM(29) +NTSTATUS +NTAPI +ExSaveNonVolatileSetting( + IN ULONG ValueIndex, + IN PULONG Type OPTIONAL, + IN PVOID Value, + IN ULONG ValueLength + ); + +// HalEnableSecureTrayEject: +// Notifies the SMBUS that ejecting the DVD-ROM should not reset the system. +// Note that this function can't really be called directly... +// +// New to the XBOX. +NTSYSAPI +EXPORTNUM(365) +VOID +NTAPI +HalEnableSecureTrayEject( + VOID + ); + +// XeLoadSection: +// Adds one to the reference count of the specified section and loads if the +// count is now above zero. +// +// New to the XBOX. +NTSYSAPI +EXPORTNUM(327) +NTSTATUS +NTAPI +XeLoadSection( + IN OUT PXBE_SECTION section + ); + +// XeUnloadSection: +// Subtracts one from the reference count of the specified section and loads +// if the count is now below zero. +// +// New to the XBOX. +NTSYSAPI +EXPORTNUM(328) +NTSTATUS +NTAPI +XeUnloadSection( + IN OUT PXBE_SECTION section + ); + +// RtlRip: +// Traps to the debugger with a certain message, then crashes. +// +// New to the XBOX. +NTSYSAPI +EXPORTNUM(352) +VOID +NTAPI +RtlRip( + IN PCSZ Part1, + IN PCSZ Part2, + IN PCSZ Part3 + ); + +// PsCreateSystemThread: +// Creates a system thread. Same as: +// PsCreateSystemThreadEx(ThreadHandle, NULL, 0x3000, 0, ThreadId, StartContext1, +// StartContext2, FALSE, DebugStack, PspSystemThreadStartup); +// +// New to the XBOX. (It is too different from NT to be considered the same) +NTSYSAPI +EXPORTNUM(254) +NTSTATUS +NTAPI +PsCreateSystemThread( + OUT PHANDLE ThreadHandle, + OUT PULONG ThreadId OPTIONAL, + IN PVOID StartContext1, + IN PVOID StartContext2, + IN BOOLEAN DebugStack + ); + +// PsCreateSystemThreadEx: +// Creates a system thread. +// ThreadHandle: Receives the thread handle +// ObjectAttributes: Unsure how this works (everything I've seen uses NULL) +// KernelStackSize: Size of the allocation for both stack and TLS data +// TlsDataSize: Size within KernelStackSize to use as TLS data +// ThreadId: Receives the thread ID number +// StartContext1: Parameter 1 to StartRoutine +// StartContext2: Parameter 2 to StartRoutine +// CreateSuspended: TRUE to create the thread as a suspended thread +// DebugStack: TRUE to allocate the stack from Debug Kit memory +// StartRoutine: Called when the thread is created +// +// New to the XBOX. +NTSYSAPI +EXPORTNUM(255) +NTSTATUS +NTAPI +PsCreateSystemThreadEx( + OUT PHANDLE ThreadHandle, + IN PVOID ObjectAttributes OPTIONAL, + IN ULONG KernelStackSize, + IN ULONG TlsDataSize, + OUT PULONG ThreadId OPTIONAL, + IN PVOID StartContext1, + IN PVOID StartContext2, + IN BOOLEAN CreateSuspended, + IN BOOLEAN DebugStack, + IN PKSTART_ROUTINE StartRoutine + ); + + + +// Error codes +#define STATUS_SUCCESS 0x00000000 +#define STATUS_UNSUCCESSFUL 0xC0000001 +#define STATUS_UNRECOGNIZED_MEDIA 0xC0000014 +// The SCSI input buffer was too large (not necessarily an error!) +#define STATUS_DATA_OVERRUN 0xC000003C +#define STATUS_INVALID_IMAGE_FORMAT 0xC000007B +#define STATUS_INSUFFICIENT_RESOURCES 0xC000009A +#define STATUS_TOO_MANY_SECRETS 0xC0000156 +#define STATUS_REGION_MISMATCH 0xC0050001 + +// End extern "C" for C++ +#if defined(__cplusplus) && !defined(XBOXINTERNAL_NO_EXTERN_C) +}; +#endif // __cplusplus + +#include + +// Thanks and credit go to Team Evox +typedef struct +{ + DWORD Data_00; // Check Block Start + DWORD Data_04; + DWORD Data_08; + DWORD Data_0c; + DWORD Data_10; // Check Block End + + DWORD V1_IP; // 0x14 + DWORD V1_Subnetmask; // 0x18 + DWORD V1_Defaultgateway; // 0x1c + DWORD V1_DNS1; // 0x20 + DWORD V1_DNS2; // 0x24 + + DWORD Data_28; // Check Block Start + DWORD Data_2c; + DWORD Data_30; + DWORD Data_34; + DWORD Data_38; // Check Block End + + DWORD V2_Tag; // V2 Tag "XBV2" + + DWORD Flag; // 0x40 + DWORD Data_44; + + DWORD V2_IP; // 0x48 + DWORD V2_Subnetmask; // 0x4c + DWORD V2_Defaultgateway; // 0x50 + DWORD V2_DNS1; // 0x54 + DWORD V2_DNS2; // 0x58 + + DWORD Data_xx[0x200-0x5c]; + +} TXNetConfigParams,*PTXNetConfigParams; + + +extern "C" +{ + // Thanks and credit go to Woodoo + extern VOID WINAPI HalInitiateShutdown(VOID); + extern VOID WINAPI HalWriteSMBusValue(BYTE, BYTE, BOOL, BYTE); + extern VOID WINAPI HalReadSMCTrayState(DWORD* state, DWORD* count); + + // Thanks and credit go to Team Evox + extern VOID WINAPI HalReturnToFirmware(DWORD); + + extern INT WINAPI XNetLoadConfigParams(LPBYTE); + extern INT WINAPI XNetSaveConfigParams(LPBYTE); + + extern INT WINAPI XWriteTitleInfoNoReboot(LPVOID,LPVOID,DWORD,DWORD,LPVOID); + + extern DWORD* LaunchDataPage; +} + + + +#endif // __XBOX_INTERNAL_H__ diff --git a/xbox1/RetroLaunch/Video.cpp b/xbox1/RetroLaunch/Video.cpp new file mode 100644 index 0000000000..04dfbd8e2a --- /dev/null +++ b/xbox1/RetroLaunch/Video.cpp @@ -0,0 +1,138 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + + +#include "Video.h" +#include "IniFile.h" +#include "Debug.h" + +CVideo g_video; +HRESULT g_hResult; + +CVideo::CVideo(void) +{ +} + +CVideo::~CVideo(void) +{ +} + +bool CVideo::Create(HWND hDeviceWindow, bool bWindowed) +{ + // Create the Direct3D object (leave it DX8 or should we try DX9 for WIN32 ?) + m_pD3D = Direct3DCreate8(D3D_SDK_VERSION); + + if (m_pD3D == NULL) + return false; + + // set up the structure used to create the d3d device + D3DPRESENT_PARAMETERS d3dpp; + ZeroMemory(&d3dpp, sizeof(d3dpp)); + + d3dpp.BackBufferWidth = 640; + d3dpp.BackBufferHeight = 480; + d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8; + d3dpp.BackBufferCount = 1; + //d3dpp.AutoDepthStencilFormat = D3DFMT_D16; + //d3dpp.EnableAutoDepthStencil = false; + d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; + + //Fullscreen only + if(!bWindowed) + { + if(!g_iniFile.m_currentIniEntry.bVSync) { + d3dpp.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; + }else{ + d3dpp.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_ONE; + } + } + + +#ifdef _XBOX + g_hResult = m_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, NULL, + D3DCREATE_HARDWARE_VERTEXPROCESSING, + &d3dpp, &m_pD3DDevice); +#else //WIN32 + + D3DDISPLAYMODE d3ddm; + g_hResult = m_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm ); + d3dpp.BackBufferFormat = d3ddm.Format; + d3dpp.Windowed = bWindowed; + d3dpp.hDeviceWindow = hDeviceWindow; + + g_hResult = m_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hDeviceWindow, + D3DCREATE_HARDWARE_VERTEXPROCESSING, + &d3dpp, &m_pD3DDevice); +#endif //#ifdef _XBOX + + if (FAILED(g_hResult)) + { + g_debug.Print("Error: D3DCreate(), CreateDevice()"); +#ifndef _XBOX + DXTrace(__FILE__, __LINE__, g_hResult, "D3DCreate(), CreateDevice()", TRUE); +#endif + return false; + } + // use an orthogonal matrix for the projection matrix + D3DXMATRIX mat; + + D3DXMatrixOrthoOffCenterLH(&mat, 0.0f, 640.0f, 480.0f, 0.0f, 0.0f, 1.0f); + + m_pD3DDevice->SetTransform(D3DTS_PROJECTION, &mat); + + // use an identity matrix for the world and view matrices + D3DXMatrixIdentity(&mat); + m_pD3DDevice->SetTransform(D3DTS_WORLD, &mat); + m_pD3DDevice->SetTransform(D3DTS_VIEW, &mat); + + // disable lighting + m_pD3DDevice->SetRenderState(D3DRS_LIGHTING, FALSE); + + // disable z-buffer (see autodepthstencil) + m_pD3DDevice->SetRenderState(D3DRS_ZENABLE, FALSE ); + + return true; +} + + +void CVideo::BeginRender() +{ + m_pD3DDevice->Clear(0, NULL, D3DCLEAR_TARGET, + D3DCOLOR_XRGB(0, 0, 0), + 1.0f, 0); + + m_pD3DDevice->BeginScene(); +#ifdef _XBOX + m_pD3DDevice->SetFlickerFilter(g_iniFile.m_currentIniEntry.dwFlickerFilter); + m_pD3DDevice->SetSoftDisplayFilter(g_iniFile.m_currentIniEntry.bSoftDisplayFilter); +#endif +} + +void CVideo::EndRender() +{ + m_pD3DDevice->EndScene(); + + m_pD3DDevice->Present(NULL, NULL, NULL, NULL); + +} + +void CVideo::CleanUp() +{ + if( m_pD3DDevice != NULL) + m_pD3DDevice->Release(); + + if( m_pD3D != NULL) + m_pD3D->Release(); +} diff --git a/xbox1/RetroLaunch/Video.h b/xbox1/RetroLaunch/Video.h new file mode 100644 index 0000000000..500a2d205b --- /dev/null +++ b/xbox1/RetroLaunch/Video.h @@ -0,0 +1,53 @@ +/** + * RetroLaunch 2012 + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. To contact the + * authors: Surreal64 CE Team (http://www.emuxtras.net) + */ + +#pragma once + +#include "Global.h" + +#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1) + +typedef struct CustomVertex +{ + float x, y, z; + dword color; + float u, v; + //float rhw; +}CustomVertex; + + +class CVideo +{ +public: + CVideo(void); + ~CVideo(void); + + bool Create(HWND hDeviceWindow, bool bWindowed); //Device creation + + void BeginRender(); + void EndRender(); + void CleanUp(); + +public: + /*Direct3D*/IDirect3D8 *m_pD3D; //D3D object + /*D3DDevice*/IDirect3DDevice8 *m_pD3DDevice; //D3D device + +private: + + //nothing +}; + +extern CVideo g_video; +extern HRESULT g_hResult; diff --git a/xbox1/RetroLaunch/dist/Media/arial.ttf b/xbox1/RetroLaunch/dist/Media/arial.ttf new file mode 100644 index 0000000000..25769bbf1b Binary files /dev/null and b/xbox1/RetroLaunch/dist/Media/arial.ttf differ diff --git a/xbox1/RetroLaunch/dist/Media/menuMainBG.png b/xbox1/RetroLaunch/dist/Media/menuMainBG.png new file mode 100644 index 0000000000..8e6d54eee7 Binary files /dev/null and b/xbox1/RetroLaunch/dist/Media/menuMainBG.png differ diff --git a/xbox1/RetroLaunch/dist/Media/menuMainRomSelectPanel.png b/xbox1/RetroLaunch/dist/Media/menuMainRomSelectPanel.png new file mode 100644 index 0000000000..377a9bae5b Binary files /dev/null and b/xbox1/RetroLaunch/dist/Media/menuMainRomSelectPanel.png differ diff --git a/xbox1/RetroLaunch/dist/Roms/Add roms here.txt b/xbox1/RetroLaunch/dist/Roms/Add roms here.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xbox1/RetroLaunch/retroarch.h b/xbox1/RetroLaunch/retroarch.h new file mode 100644 index 0000000000..a751129251 --- /dev/null +++ b/xbox1/RetroLaunch/retroarch.h @@ -0,0 +1,5 @@ +// Automatically generated by the bundler tool from retroarch.jpg + +#define retroarch_NUM_RESOURCES 1UL + +#define retroarch_OFFSET 0UL diff --git a/xbox1/RetroLaunch/titleimage.jpg b/xbox1/RetroLaunch/titleimage.jpg new file mode 100644 index 0000000000..1b0bc9586d Binary files /dev/null and b/xbox1/RetroLaunch/titleimage.jpg differ