From ff27d694242c2de2d85ccfbed953186bb38a0628 Mon Sep 17 00:00:00 2001 From: mniip Date: Mon, 30 Apr 2018 21:13:24 +0300 Subject: [PATCH] Switch from std::string to String/ByteString in most of the code Also switch SimulationData from weird arrays to std::vector --- src/Format.cpp | 16 +- src/Format.h | 32 +- src/Misc.h | 2 - src/Platform.cpp | 8 +- src/Platform.h | 6 +- src/PowderToy.h | 5 +- src/PowderToyRenderer.cpp | 25 +- src/PowderToySDL.cpp | 74 ++-- src/Update.cpp | 10 +- src/client/Client.cpp | 385 ++++++++++-------- src/client/Client.h | 106 ++--- src/client/ClientListener.h | 2 +- src/client/Download.cpp | 16 +- src/client/Download.h | 22 +- src/client/GameSave.cpp | 35 +- src/client/GameSave.h | 16 +- src/client/HTTP.cpp | 25 +- src/client/HTTP.h | 8 +- src/client/SaveFile.cpp | 16 +- src/client/SaveFile.h | 22 +- src/client/SaveInfo.cpp | 26 +- src/client/SaveInfo.h | 30 +- src/client/User.h | 10 +- src/client/UserInfo.h | 12 +- src/client/requestbroker/APIRequest.cpp | 14 +- src/client/requestbroker/APIRequest.h | 8 +- src/client/requestbroker/ImageRequest.cpp | 6 +- src/client/requestbroker/ImageRequest.h | 4 +- src/client/requestbroker/RequestBroker.cpp | 11 +- src/client/requestbroker/RequestBroker.h | 8 +- src/client/requestbroker/WebRequest.cpp | 14 +- src/client/requestbroker/WebRequest.h | 8 +- src/common/String.cpp | 132 ++++++ src/common/String.h | 57 ++- src/debug/DebugLines.cpp | 16 +- src/debug/DebugParts.cpp | 7 +- src/debug/ElementPopulation.cpp | 6 +- src/debug/ParticleDebug.cpp | 5 +- src/graphics/DrawMethodsDef.inc | 7 +- src/graphics/Graphics.cpp | 54 ++- src/graphics/Graphics.h | 29 +- src/graphics/OpenGLDrawMethods.inl | 16 +- src/graphics/RasterDrawMethods.inl | 18 +- src/graphics/Renderer.cpp | 18 +- src/graphics/Renderer.h | 9 +- src/gui/colourpicker/ColourPickerActivity.cpp | 4 +- src/gui/colourpicker/ColourPickerActivity.h | 2 +- src/gui/console/ConsoleCommand.h | 10 +- src/gui/console/ConsoleController.cpp | 4 +- src/gui/console/ConsoleController.h | 6 +- src/gui/console/ConsoleModel.cpp | 4 +- src/gui/dialogues/ConfirmPrompt.cpp | 6 +- src/gui/dialogues/ConfirmPrompt.h | 8 +- src/gui/dialogues/ErrorMessage.cpp | 4 +- src/gui/dialogues/ErrorMessage.h | 4 +- src/gui/dialogues/InformationMessage.cpp | 2 +- src/gui/dialogues/InformationMessage.h | 2 +- src/gui/dialogues/LegacyDialogues.h | 8 +- src/gui/dialogues/TextPrompt.cpp | 12 +- src/gui/dialogues/TextPrompt.h | 6 +- .../elementsearch/ElementSearchActivity.cpp | 17 +- src/gui/elementsearch/ElementSearchActivity.h | 7 +- src/gui/filebrowser/FileBrowserActivity.cpp | 33 +- src/gui/filebrowser/FileBrowserActivity.h | 10 +- src/gui/font/FontEditor.cpp | 35 +- src/gui/font/FontEditor.h | 14 +- src/gui/game/DecorationTool.h | 2 +- src/gui/game/Favorite.cpp | 12 +- src/gui/game/Favorite.h | 12 +- src/gui/game/GameController.cpp | 52 +-- src/gui/game/GameController.h | 14 +- src/gui/game/GameModel.cpp | 36 +- src/gui/game/GameModel.h | 22 +- src/gui/game/GameModelException.h | 9 +- src/gui/game/GameView.cpp | 127 +++--- src/gui/game/GameView.h | 16 +- src/gui/game/Menu.h | 17 +- src/gui/game/Notification.h | 6 +- src/gui/game/PropertyTool.cpp | 39 +- src/gui/game/QuickOption.h | 16 +- src/gui/game/RenderPreset.h | 4 +- src/gui/game/SignTool.cpp | 12 +- src/gui/game/Tool.cpp | 16 +- src/gui/game/Tool.h | 29 +- src/gui/game/ToolButton.cpp | 4 +- src/gui/game/ToolButton.h | 4 +- src/gui/interface/AvatarButton.cpp | 2 +- src/gui/interface/AvatarButton.h | 10 +- src/gui/interface/Button.cpp | 10 +- src/gui/interface/Button.h | 18 +- src/gui/interface/Checkbox.cpp | 6 +- src/gui/interface/Checkbox.h | 12 +- src/gui/interface/Component.cpp | 4 +- src/gui/interface/Component.h | 4 +- src/gui/interface/ContextMenu.cpp | 2 +- src/gui/interface/ContextMenu.h | 6 +- src/gui/interface/CopyTextButton.cpp | 4 +- src/gui/interface/CopyTextButton.h | 2 +- src/gui/interface/DropDown.cpp | 18 +- src/gui/interface/DropDown.h | 14 +- src/gui/interface/Label.cpp | 61 ++- src/gui/interface/Label.h | 24 +- src/gui/interface/ProgressBar.cpp | 10 +- src/gui/interface/ProgressBar.h | 8 +- src/gui/interface/RichLabel.cpp | 30 +- src/gui/interface/RichLabel.h | 16 +- src/gui/interface/SaveButton.cpp | 28 +- src/gui/interface/SaveButton.h | 10 +- src/gui/interface/Textbox.cpp | 66 +-- src/gui/interface/Textbox.h | 14 +- src/gui/interface/Window.h | 4 +- .../localbrowser/LocalBrowserController.cpp | 18 +- src/gui/localbrowser/LocalBrowserController.h | 2 +- src/gui/localbrowser/LocalBrowserModel.cpp | 4 +- src/gui/localbrowser/LocalBrowserModel.h | 12 +- .../localbrowser/LocalBrowserModelException.h | 9 +- src/gui/localbrowser/LocalBrowserView.cpp | 9 +- src/gui/login/LoginController.cpp | 2 +- src/gui/login/LoginController.h | 4 +- src/gui/login/LoginModel.cpp | 4 +- src/gui/login/LoginModel.h | 8 +- src/gui/login/LoginView.cpp | 4 +- src/gui/options/OptionsView.cpp | 34 +- src/gui/preview/Comment.h | 10 +- src/gui/preview/PreviewController.cpp | 9 +- src/gui/preview/PreviewController.h | 4 +- src/gui/preview/PreviewModel.cpp | 30 +- src/gui/preview/PreviewModelException.h | 8 +- src/gui/preview/PreviewView.cpp | 27 +- src/gui/preview/PreviewView.h | 10 +- src/gui/profile/ProfileActivity.cpp | 6 +- src/gui/profile/ProfileActivity.h | 6 +- src/gui/render/RenderView.cpp | 4 +- src/gui/render/RenderView.h | 4 +- src/gui/save/LocalSaveActivity.cpp | 10 +- src/gui/save/LocalSaveActivity.h | 2 +- src/gui/save/ServerSaveActivity.cpp | 12 +- src/gui/save/ServerSaveActivity.h | 2 +- src/gui/search/SearchController.cpp | 33 +- src/gui/search/SearchController.h | 6 +- src/gui/search/SearchModel.cpp | 10 +- src/gui/search/SearchModel.h | 22 +- src/gui/search/SearchView.cpp | 24 +- src/gui/search/SearchView.h | 2 +- src/gui/tags/TagsController.cpp | 4 +- src/gui/tags/TagsController.h | 4 +- src/gui/tags/TagsModel.cpp | 12 +- src/gui/tags/TagsModel.h | 6 +- src/gui/tags/TagsModelException.h | 8 +- src/gui/tags/TagsView.cpp | 16 +- src/gui/update/UpdateActivity.cpp | 9 +- src/lua/CommandInterface.cpp | 11 +- src/lua/CommandInterface.h | 14 +- src/lua/LegacyLuaAPI.cpp | 69 ++-- src/lua/LuaButton.cpp | 10 +- src/lua/LuaCheckbox.cpp | 8 +- src/lua/LuaLabel.cpp | 6 +- src/lua/LuaProgressBar.cpp | 6 +- src/lua/LuaScriptHelper.h | 4 +- src/lua/LuaScriptInterface.cpp | 179 ++++---- src/lua/LuaScriptInterface.h | 6 +- src/lua/LuaSlider.cpp | 2 +- src/lua/LuaTextbox.cpp | 10 +- src/lua/LuaWindow.cpp | 28 +- src/lua/TPTSTypes.cpp | 17 +- src/lua/TPTSTypes.h | 20 +- src/lua/TPTScriptInterface.cpp | 106 +++-- src/lua/TPTScriptInterface.h | 24 +- src/powdertoyjava/PowderToyJava.cpp | 2 - src/simulation/GOLMenu.h | 4 +- src/simulation/MenuSection.h | 4 +- src/simulation/Sign.cpp | 11 +- src/simulation/Sign.h | 12 +- src/simulation/Simulation.cpp | 36 +- src/simulation/Simulation.h | 14 +- src/simulation/SimulationData.cpp | 48 +-- src/simulation/SimulationData.h | 13 +- src/simulation/StorageClasses.h | 1 - src/simulation/StructProperty.h | 6 +- src/simulation/WallType.h | 7 +- src/simulation/elements/Element.h | 6 +- src/simulation/elements/LIFE.cpp | 6 +- src/simulation/simtools/SimTool.h | 6 +- src/tasks/Task.cpp | 24 +- src/tasks/Task.h | 18 +- src/tasks/TaskWindow.cpp | 9 +- src/tasks/TaskWindow.h | 7 +- 187 files changed, 1837 insertions(+), 1713 deletions(-) diff --git a/src/Format.cpp b/src/Format.cpp index 5ab9764f5..d06fc253e 100644 --- a/src/Format.cpp +++ b/src/Format.cpp @@ -1,6 +1,6 @@ #include -#include +#include "common/String.h" #include #include #include @@ -9,7 +9,7 @@ #include "Format.h" #include "graphics/Graphics.h" -std::string format::URLEncode(std::string source) +ByteString format::URLEncode(ByteString source) { char * src = (char *)source.c_str(); char * dst = new char[(source.length()*3)+2]; @@ -33,12 +33,12 @@ std::string format::URLEncode(std::string source) } *d = 0; - std::string finalString(dst); + ByteString finalString(dst); delete[] dst; return finalString; } -std::string format::UnixtimeToDate(time_t unixtime, std::string dateFormat) +ByteString format::UnixtimeToDate(time_t unixtime, ByteString dateFormat) { struct tm * timeData; char buffer[128]; @@ -46,10 +46,10 @@ std::string format::UnixtimeToDate(time_t unixtime, std::string dateFormat) timeData = localtime(&unixtime); strftime(buffer, 128, dateFormat.c_str(), timeData); - return std::string(buffer); + return ByteString(buffer); } -std::string format::UnixtimeToDateMini(time_t unixtime) +ByteString format::UnixtimeToDateMini(time_t unixtime) { time_t currentTime = time(NULL); struct tm currentTimeData = *localtime(¤tTime); @@ -69,7 +69,7 @@ std::string format::UnixtimeToDateMini(time_t unixtime) } } -std::string format::CleanString(std::string dirtyString, bool ascii, bool color, bool newlines, bool numeric) +String format::CleanString(String dirtyString, bool ascii, bool color, bool newlines, bool numeric) { for (size_t i = 0; i < dirtyString.size(); i++) { @@ -226,7 +226,7 @@ struct PNGChunk //char[4] CRC(); - PNGChunk(int length, std::string name) + PNGChunk(int length, ByteString name) { if (name.length()!=4) throw std::runtime_error("Invalid chunk name"); diff --git a/src/Format.h b/src/Format.h index 388f82463..19cecf848 100644 --- a/src/Format.h +++ b/src/Format.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "common/String.h" #include class VideoBuffer; @@ -9,24 +9,38 @@ namespace format { const static char hex[] = "0123456789ABCDEF"; - template std::string NumberToString(T number) + template ByteString NumberToByteString(T number) { - std::stringstream ss; + ByteString::Stream ss; ss << number; return ss.str(); } - template T StringToNumber(const std::string & text) + template String NumberToString(T number) { - std::stringstream ss(text); + String::Stream ss; + ss << number; + return ss.str(); + } + + template T ByteStringToNumber(const ByteString & text) + { + ByteString::Stream ss(text); T number; return (ss >> number)?number:0; } - std::string URLEncode(std::string value); - std::string UnixtimeToDate(time_t unixtime, std::string dateFomat = "%d %b %Y"); - std::string UnixtimeToDateMini(time_t unixtime); - std::string CleanString(std::string dirtyString, bool ascii, bool color, bool newlines, bool numeric = false); + template T StringToNumber(const String & text) + { + String::Stream ss(text); + T number; + return (ss >> number)?number:0; + } + + ByteString URLEncode(ByteString value); + ByteString UnixtimeToDate(time_t unixtime, ByteString dateFomat = "%d %b %Y"); + ByteString UnixtimeToDateMini(time_t unixtime); + String CleanString(String dirtyString, bool ascii, bool color, bool newlines, bool numeric = false); std::vector VideoBufferToPNG(const VideoBuffer & vidBuf); std::vector VideoBufferToBMP(const VideoBuffer & vidBuf); std::vector VideoBufferToPPM(const VideoBuffer & vidBuf); diff --git a/src/Misc.h b/src/Misc.h index 9ea14f160..9b876af62 100644 --- a/src/Misc.h +++ b/src/Misc.h @@ -2,8 +2,6 @@ #define UTILS_H #include #include -#include -#include #include //Linear interpolation diff --git a/src/Platform.cpp b/src/Platform.cpp index e6c50a714..0b1f37a6a 100644 --- a/src/Platform.cpp +++ b/src/Platform.cpp @@ -20,9 +20,9 @@ namespace Platform { -std::string ExecutableName() +ByteString ExecutableName() { - std::string ret; + ByteString ret; #if defined(WIN) char *name = (char *)malloc(64); DWORD max = 64, res; @@ -73,7 +73,7 @@ std::string ExecutableName() void DoRestart() { - std::string exename = ExecutableName(); + ByteString exename = ExecutableName(); if (exename.length()) { #ifdef WIN @@ -85,7 +85,7 @@ void DoRestart() exit(-1); } -void OpenURI(std::string uri) +void OpenURI(ByteString uri) { #if defined(WIN) ShellExecute(0, "OPEN", uri.c_str(), NULL, NULL, 0); diff --git a/src/Platform.h b/src/Platform.h index ecbdbf115..3bceb1438 100644 --- a/src/Platform.h +++ b/src/Platform.h @@ -1,14 +1,14 @@ #ifndef PLATFORM_H #define PLATFORM_H -#include +#include "common/String.h" namespace Platform { - std::string ExecutableName(); + ByteString ExecutableName(); void DoRestart(); - void OpenURI(std::string uri); + void OpenURI(ByteString uri); void Millisleep(long int t); long unsigned int GetTime(); diff --git a/src/PowderToy.h b/src/PowderToy.h index a76a95b50..aa20e943d 100644 --- a/src/PowderToy.h +++ b/src/PowderToy.h @@ -1,9 +1,8 @@ #pragma once -#include void EngineProcess(); -void ClipboardPush(std::string text); -std::string ClipboardPull(); +void ClipboardPush(ByteString text); +ByteString ClipboardPull(); int GetModifiers(); bool LoadWindowPosition(int scale); void SetCursorEnabled(int enabled); diff --git a/src/PowderToyRenderer.cpp b/src/PowderToyRenderer.cpp index c019beeb3..aaf5176dc 100644 --- a/src/PowderToyRenderer.cpp +++ b/src/PowderToyRenderer.cpp @@ -2,11 +2,10 @@ #include #include -#include -#include #include #include +#include "common/String.h" #include "Config.h" #include "Format.h" #include "gui/interface/Engine.h" @@ -18,16 +17,16 @@ void EngineProcess() {} -void ClipboardPush(std::string) {} -std::string ClipboardPull() { return ""; } +void ClipboardPush(ByteString) {} +ByteString ClipboardPull() { return ""; } int GetModifiers() { return 0; } void SetCursorEnabled(int enabled) {} unsigned int GetTicks() { return 0; } -void readFile(std::string filename, std::vector & storage) +void readFile(ByteString filename, std::vector & storage) { std::ifstream fileStream; - fileStream.open(std::string(filename).c_str(), std::ios::binary); + fileStream.open(filename.c_str(), std::ios::binary); if(fileStream.is_open()) { fileStream.seekg(0, std::ios::end); @@ -45,10 +44,10 @@ void readFile(std::string filename, std::vector & storage) } } -void writeFile(std::string filename, std::vector & fileData) +void writeFile(ByteString filename, std::vector & fileData) { std::ofstream fileStream; - fileStream.open(std::string(filename).c_str(), std::ios::binary); + fileStream.open(filename.c_str(), std::ios::binary); if(fileStream.is_open()) { fileStream.write(&fileData[0], fileData.size()); @@ -59,13 +58,13 @@ void writeFile(std::string filename, std::vector & fileData) int main(int argc, char *argv[]) { ui::Engine * engine; - std::string outputPrefix, inputFilename; + ByteString outputPrefix, inputFilename; std::vector inputFile; - std::string ppmFilename, ptiFilename, ptiSmallFilename, pngFilename, pngSmallFilename; + ByteString ppmFilename, ptiFilename, ptiSmallFilename, pngFilename, pngSmallFilename; std::vector ppmFile, ptiFile, ptiSmallFile, pngFile, pngSmallFile; - inputFilename = std::string(argv[1]); - outputPrefix = std::string(argv[2]); + inputFilename = argv[1]; + outputPrefix = argv[2]; ppmFilename = outputPrefix+".ppm"; ptiFilename = outputPrefix+".pti"; @@ -88,7 +87,7 @@ int main(int argc, char *argv[]) catch (ParseException e) { //Render the save again later or something? I don't know - if (e.what() == "Save from newer version") + if (ByteString(e.what()).FromUtf8() == "Save from newer version") throw e; } diff --git a/src/PowderToySDL.cpp b/src/PowderToySDL.cpp index 45d3fed79..086dda513 100644 --- a/src/PowderToySDL.cpp +++ b/src/PowderToySDL.cpp @@ -1,7 +1,7 @@ #ifdef USE_SDL #include -#include +#include "common/String.h" #include #include #ifdef WIN @@ -18,9 +18,9 @@ #endif #include -#include -#include +#include "common/String.h" #include "Config.h" +#include "common/String.h" #include "graphics/Graphics.h" #if defined(LIN) #include "icon.h" @@ -68,7 +68,7 @@ SDL_SysWMinfo sdl_wminfo; Atom XA_CLIPBOARD, XA_TARGETS, XA_UTF8_STRING; #endif -std::string clipboardText = ""; +ByteString clipboardText = ""; int desktopWidth = 1280, desktopHeight = 1024; @@ -76,7 +76,7 @@ SDL_Surface * sdl_scrn; int scale = 1; bool fullscreen = false; -void ClipboardPush(std::string text) +void ClipboardPush(ByteString text) { clipboardText = text; #ifdef MACOSX @@ -110,11 +110,11 @@ void ClipboardPush(std::string text) void EventProcess(SDL_Event event); -std::string ClipboardPull() +ByteString ClipboardPull() { #ifdef MACOSX const char *text = readClipboard(); - return text ? std::string(text) : ""; + return text ? ByteString(text).FromUtf8() : ""; #elif defined(WIN) if (OpenClipboard(NULL)) { @@ -125,10 +125,10 @@ std::string ClipboardPull() glbuffer = (char*)GlobalLock(cbuffer); GlobalUnlock(cbuffer); CloseClipboard(); - return glbuffer ? std::string(glbuffer) : ""; + return glbuffer ? ByteString(glbuffer) : ""; } #elif defined(LIN) && defined(SDL_VIDEO_DRIVER_X11) - std::string text = ""; + ByteString text = ""; Window selectionOwner; sdl_wminfo.info.x11.lock_func(); selectionOwner = XGetSelectionOwner(sdl_wminfo.info.x11.display, XA_CLIPBOARD); @@ -168,7 +168,7 @@ std::string ClipboardPull() result = XGetWindowProperty(sdl_wminfo.info.x11.display, sdl_wminfo.info.x11.window, XA_CLIPBOARD, 0, bytesLeft, 0, AnyPropertyType, &type, &format, &len, &bytesLeft, &data); if (result == Success) { - text = data ? (const char*)data : ""; + text = data ? ByteString((char const *)data) : ""; XFree(data); } else @@ -526,9 +526,9 @@ unsigned int GetTicks() return SDL_GetTicks(); } -std::map readArguments(int argc, char * argv[]) +std::map readArguments(int argc, char * argv[]) { - std::map arguments; + std::map arguments; //Defaults arguments["scale"] = ""; @@ -545,12 +545,12 @@ std::map readArguments(int argc, char * argv[]) { if (!strncmp(argv[i], "scale:", 6) && argv[i]+6) { - arguments["scale"] = std::string(argv[i]+6); + arguments["scale"] = argv[i]+6; } else if (!strncmp(argv[i], "proxy:", 6)) { if(argv[i]+6) - arguments["proxy"] = std::string(argv[i]+6); + arguments["proxy"] = argv[i]+6; else arguments["proxy"] = "false"; } @@ -572,17 +572,17 @@ std::map readArguments(int argc, char * argv[]) } else if (!strncmp(argv[i], "open", 5) && i+1g->fillrect(0, 0, engine->GetWidth(), engine->GetHeight(), 17, 114, 169, 210); - std::string errorTitle = "ERROR"; - std::string errorDetails = "Details: " + std::string(detailMessage); - std::string errorHelp = "An unrecoverable fault has occurred, please report the error by visiting the website below\n" + String errorTitle = "ERROR"; + String errorDetails = "Details: " + detailMessage; + String errorHelp = "An unrecoverable fault has occurred, please report the error by visiting the website below\n" "http://" SERVER; int currentY = 0, width, height; int errorWidth = 0; - Graphics::textsize(errorHelp.c_str(), errorWidth, height); + Graphics::textsize(errorHelp, errorWidth, height); engine->g->drawtext((engine->GetWidth()/2)-(errorWidth/2), ((engine->GetHeight()/2)-100) + currentY, errorTitle.c_str(), 255, 255, 255, 255); - Graphics::textsize(errorTitle.c_str(), width, height); + Graphics::textsize(errorTitle, width, height); currentY += height + 4; engine->g->drawtext((engine->GetWidth()/2)-(errorWidth/2), ((engine->GetHeight()/2)-100) + currentY, errorDetails.c_str(), 255, 255, 255, 255); - Graphics::textsize(errorTitle.c_str(), width, height); + Graphics::textsize(errorTitle, width, height); currentY += height + 4; engine->g->drawtext((engine->GetWidth()/2)-(errorWidth/2), ((engine->GetHeight()/2)-100) + currentY, errorHelp.c_str(), 255, 255, 255, 255); - Graphics::textsize(errorTitle.c_str(), width, height); + Graphics::textsize(errorTitle, width, height); currentY += height + 4; //Death loop @@ -985,7 +985,7 @@ int main(int argc, char * argv[]) currentHeight = WINDOWH; - std::map arguments = readArguments(argc, argv); + std::map arguments = readArguments(argc, argv); if(arguments["ddir"].length()) #ifdef WIN @@ -1009,11 +1009,11 @@ int main(int argc, char * argv[]) if(arguments["scale"].length()) { - tempScale = format::StringToNumber(arguments["scale"]); + tempScale = format::ByteStringToNumber(arguments["scale"]); Client::Ref().SetPref("Scale", tempScale); } - std::string proxyString = ""; + ByteString proxyString = ""; if(arguments["proxy"].length()) { if(arguments["proxy"] == "false") @@ -1029,7 +1029,7 @@ int main(int argc, char * argv[]) } else if(Client::Ref().GetPrefString("Proxy", "").length()) { - proxyString = (Client::Ref().GetPrefString("Proxy", "")); + proxyString = (Client::Ref().GetPrefByteString("Proxy", "")); } Client::Ref().Initialise(proxyString); @@ -1140,7 +1140,7 @@ int main(int argc, char * argv[]) } catch(std::exception & e) { - new ErrorMessage("Error", "Could not open save file:\n"+std::string(e.what())) ; + new ErrorMessage("Error", "Could not open save file:\n" + ByteString(e.what()).FromUtf8()) ; } } else @@ -1163,16 +1163,16 @@ int main(int argc, char * argv[]) else blit(engine->g->vid); #endif - std::string ptsaveArg = arguments["ptsave"]; + ByteString ptsaveArg = arguments["ptsave"]; try { if (ptsaveArg.find("ptsave:")) throw std::runtime_error("Invalid save link"); - std::string saveIdPart = ""; + ByteString saveIdPart = ""; int saveId; size_t hashPos = ptsaveArg.find('#'); - if (hashPos != std::string::npos) + if (hashPos != ByteString::npos) { saveIdPart = ptsaveArg.substr(7, hashPos-7); } @@ -1185,7 +1185,7 @@ int main(int argc, char * argv[]) #ifdef DEBUG std::cout << "Got Ptsave: id: " << saveIdPart << std::endl; #endif - saveId = format::StringToNumber(saveIdPart); + saveId = format::ByteStringToNumber(saveIdPart); if (!saveId) throw std::runtime_error("Invalid Save ID"); @@ -1194,7 +1194,7 @@ int main(int argc, char * argv[]) throw std::runtime_error("Could not load save info"); std::vector saveData = Client::Ref().GetSaveData(saveId, 0); if (!saveData.size()) - throw std::runtime_error("Could not load save\n" + Client::Ref().GetLastError()); + throw std::runtime_error(("Could not load save\n" + Client::Ref().GetLastError()).ToUtf8()); GameSave * newGameSave = new GameSave(saveData); newSave->SetGameSave(newGameSave); @@ -1203,7 +1203,7 @@ int main(int argc, char * argv[]) } catch (std::exception & e) { - new ErrorMessage("Error", e.what()); + new ErrorMessage("Error", ByteString(e.what()).FromUtf8()); } } diff --git a/src/Update.cpp b/src/Update.cpp index 853b3d395..a00827f0f 100644 --- a/src/Update.cpp +++ b/src/Update.cpp @@ -26,7 +26,7 @@ // returns 1 on failure, 0 on success int update_start(char *data, unsigned int len) { - std::string exeName = Platform::ExecutableName(), updName; + ByteString exeName = Platform::ExecutableName(), updName; FILE *f; if (!exeName.length()) @@ -34,7 +34,7 @@ int update_start(char *data, unsigned int len) #ifdef WIN updName = exeName; - std::string extension = exeName.substr(exeName.length() - 4); + ByteString extension = exeName.substr(exeName.length() - 4); if (extension == ".exe") updName = exeName.substr(0, exeName.length() - 4); updName = updName + "_upd.exe"; @@ -95,7 +95,7 @@ int update_start(char *data, unsigned int len) int update_finish() { #ifdef WIN - std::string exeName = Platform::ExecutableName(), updName; + ByteString exeName = Platform::ExecutableName(), updName; int timeout = 5, err; #ifdef DEBUG @@ -103,7 +103,7 @@ int update_finish() #endif updName = exeName; - std::string extension = exeName.substr(exeName.length() - 4); + ByteString extension = exeName.substr(exeName.length() - 4); if (extension == ".exe") updName = exeName.substr(0, exeName.length() - 4); updName = updName + "_upd.exe"; @@ -122,7 +122,7 @@ int update_finish() #endif // Old versions of powder toy name their update files with _update.exe, delete that upgrade file here updName = exeName; - std::string extension = exeName.substr(exeName.length() - 4); + ByteString extension = exeName.substr(exeName.length() - 4); if (extension == ".exe") updName = exeName.substr(0, exeName.length() - 4); updName = updName + "_update.exe"; diff --git a/src/client/Client.cpp b/src/client/Client.cpp index f2bccb381..3b7eaf44b 100644 --- a/src/client/Client.cpp +++ b/src/client/Client.cpp @@ -1,7 +1,5 @@ #include #include -#include -#include #include #include #include @@ -26,6 +24,7 @@ #include #endif +#include "common/String.h" #include "Config.h" #include "Format.h" #include "Client.h" @@ -92,10 +91,10 @@ Client::Client(): preferences.clear(); configFile >> preferences; int ID = preferences["User"]["ID"].asInt(); - std::string Username = preferences["User"]["Username"].asString(); - std::string SessionID = preferences["User"]["SessionID"].asString(); - std::string SessionKey = preferences["User"]["SessionKey"].asString(); - std::string Elevation = preferences["User"]["Elevation"].asString(); + ByteString Username = preferences["User"]["Username"].asString(); + ByteString SessionID = preferences["User"]["SessionID"].asString(); + ByteString SessionKey = preferences["User"]["SessionKey"].asString(); + ByteString Elevation = preferences["User"]["Elevation"].asString(); authUser.UserID = ID; authUser.Username = Username; @@ -119,7 +118,7 @@ Client::Client(): firstRun = true; } -void Client::Initialise(std::string proxyString) +void Client::Initialise(ByteString proxyString) { if (GetPrefBool("version.update", false)) { @@ -151,7 +150,7 @@ void Client::Initialise(std::string proxyString) if (authUser.UserID) { - std::string idTempString = format::NumberToString(authUser.UserID); + ByteString idTempString = format::NumberToByteString(authUser.UserID); char *id = new char[idTempString.length() + 1]; std::strcpy (id, idTempString.c_str()); char *session = new char[authUser.SessionID.length() + 1]; @@ -183,7 +182,7 @@ bool Client::DoInstallation() int returnval; LONG rresult; HKEY newkey; - std::string currentfilename2 = Platform::ExecutableName(); + ByteString currentfilename2 = Platform::ExecutableName(); // this isn't necessary but I don't feel like c++ifying this code right now const char *currentfilename = currentfilename2.c_str(); char *iconname = NULL; @@ -350,7 +349,7 @@ bool Client::DoInstallation() #include "icondoc.h" int success = 1; - std::string filename = Platform::ExecutableName(), pathname = filename.substr(0, filename.rfind('/')); + ByteString filename = Platform::ExecutableName(), pathname = filename.substr(0, filename.rfind('/')); for (size_t i = 0; i < filename.size(); i++) { if (filename[i] == '\'') @@ -387,7 +386,7 @@ bool Client::DoInstallation() "NoDisplay=true\n" "Categories=Game;Simulation\n" "Icon=powdertoy.png\n"; - std::stringstream protocolfiledata; + ByteString::Stream protocolfiledata; protocolfiledata << protocolfiledata_tmp << "Exec=" << filename << " ptsave %u\nPath=" << pathname << "\n"; f = fopen("powdertoy-tpt-ptsave.desktop", "wb"); if (!f) @@ -405,7 +404,7 @@ bool Client::DoInstallation() "NoDisplay=true\n" "Categories=Game;Simulation\n" "Icon=powdertoy.png\n"; - std::stringstream desktopopenfiledata; + ByteString::Stream desktopopenfiledata; desktopopenfiledata << desktopopenfiledata_tmp << "Exec=" << filename << " open %f\nPath=" << pathname << "\n"; f = fopen("powdertoy-tpt-open.desktop", "wb"); if (!f) @@ -424,7 +423,7 @@ bool Client::DoInstallation() "Comment=Physics sandbox game\n" "Categories=Game;Simulation\n" "Icon=powdertoy.png\n"; - std::stringstream desktopfiledata; + ByteString::Stream desktopfiledata; desktopfiledata << desktopfiledata_tmp << "Exec=" << filename << "\nPath=" << pathname << "\n"; f = fopen("powdertoy-tpt.desktop", "wb"); if (!f) @@ -467,7 +466,7 @@ bool Client::DoInstallation() #endif } -void Client::SetProxy(std::string proxy) +void Client::SetProxy(ByteString proxy) { http_done(); if(proxy.length()) @@ -476,38 +475,38 @@ void Client::SetProxy(std::string proxy) http_init(NULL); } -std::vector Client::DirectorySearch(std::string directory, std::string search, std::string extension) +std::vector Client::DirectorySearch(ByteString directory, ByteString search, ByteString extension) { - std::vector extensions; + std::vector extensions; extensions.push_back(extension); - for (std::string::iterator iter = search.begin(); iter != search.end(); ++iter) + for (ByteString::iterator iter = search.begin(); iter != search.end(); ++iter) *iter = toupper(*iter); return DirectorySearch(directory, search, extensions); } -std::vector Client::DirectorySearch(std::string directory, std::string search, std::vector extensions) +std::vector Client::DirectorySearch(ByteString directory, ByteString search, std::vector extensions) { //Get full file listing //Normalise directory string, ensure / or \ is present if(*directory.rbegin() != '/' && *directory.rbegin() != '\\') directory += PATH_SEP; - std::vector directoryList; + std::vector directoryList; #if defined(WIN) && !defined(__GNUC__) //Windows struct _finddata_t currentFile; intptr_t findFileHandle; - std::string fileMatch = directory + "*.*"; + ByteString fileMatch = directory + "*.*"; findFileHandle = _findfirst(fileMatch.c_str(), ¤tFile); if (findFileHandle == -1L) { #ifdef DEBUG printf("Unable to open directory: %s\n", directory.c_str()); #endif - return std::vector(); + return std::vector(); } do { - std::string currentFileName = std::string(currentFile.name); + ByteString currentFileName = ByteString(currentFile.name); if(currentFileName.length()>4) directoryList.push_back(directory+currentFileName); } @@ -522,23 +521,23 @@ std::vector Client::DirectorySearch(std::string directory, std::str #ifdef DEBUG printf("Unable to open directory: %s\n", directory.c_str()); #endif - return std::vector(); + return std::vector(); } while ((directoryEntry = readdir(directoryHandle))) { - std::string currentFileName = std::string(directoryEntry->d_name); + ByteString currentFileName = ByteString(directoryEntry->d_name); if(currentFileName.length()>4) directoryList.push_back(directory+currentFileName); } closedir(directoryHandle); #endif - std::vector searchResults; - for(std::vector::iterator iter = directoryList.begin(), end = directoryList.end(); iter != end; ++iter) + std::vector searchResults; + for(std::vector::iterator iter = directoryList.begin(), end = directoryList.end(); iter != end; ++iter) { - std::string filename = *iter, tempfilename = *iter; + ByteString filename = *iter, tempfilename = *iter; bool extensionMatch = !extensions.size(); - for(std::vector::iterator extIter = extensions.begin(), extEnd = extensions.end(); extIter != extEnd; ++extIter) + for(std::vector::iterator extIter = extensions.begin(), extEnd = extensions.end(); extIter != extEnd; ++extIter) { size_t filenameLength = filename.length()-(*extIter).length(); if(filename.find(*extIter, filenameLength) == filenameLength) @@ -548,10 +547,10 @@ std::vector Client::DirectorySearch(std::string directory, std::str break; } } - for (std::string::iterator iter = tempfilename.begin(); iter != tempfilename.end(); ++iter) + for (ByteString::iterator iter = tempfilename.begin(); iter != tempfilename.end(); ++iter) *iter = toupper(*iter); bool searchMatch = !search.size(); - if(search.size() && tempfilename.find(search)!=std::string::npos) + if(search.size() && tempfilename.find(search)!=ByteString::npos) searchMatch = true; if(searchMatch && extensionMatch) @@ -571,13 +570,13 @@ int Client::MakeDirectory(const char * dirName) #endif } -bool Client::WriteFile(std::vector fileData, std::string filename) +bool Client::WriteFile(std::vector fileData, ByteString filename) { bool saveError = false; try { std::ofstream fileStream; - fileStream.open(std::string(filename).c_str(), std::ios::binary); + fileStream.open(filename, std::ios::binary); if(fileStream.is_open()) { fileStream.write((char*)&fileData[0], fileData.size()); @@ -594,13 +593,13 @@ bool Client::WriteFile(std::vector fileData, std::string filename return saveError; } -bool Client::FileExists(std::string filename) +bool Client::FileExists(ByteString filename) { bool exists = false; try { std::ifstream fileStream; - fileStream.open(std::string(filename).c_str(), std::ios::binary); + fileStream.open(filename, std::ios::binary); if(fileStream.is_open()) { exists = true; @@ -614,13 +613,13 @@ bool Client::FileExists(std::string filename) return exists; } -bool Client::WriteFile(std::vector fileData, std::string filename) +bool Client::WriteFile(std::vector fileData, ByteString filename) { bool saveError = false; try { std::ofstream fileStream; - fileStream.open(std::string(filename).c_str(), std::ios::binary); + fileStream.open(filename, std::ios::binary); if(fileStream.is_open()) { fileStream.write(&fileData[0], fileData.size()); @@ -637,12 +636,12 @@ bool Client::WriteFile(std::vector fileData, std::string filename) return saveError; } -std::vector Client::ReadFile(std::string filename) +std::vector Client::ReadFile(ByteString filename) { try { std::ifstream fileStream; - fileStream.open(std::string(filename).c_str(), std::ios::binary); + fileStream.open(filename, std::ios::binary); if(fileStream.is_open()) { fileStream.seekg(0, std::ios::end); @@ -671,24 +670,24 @@ std::vector Client::ReadFile(std::string filename) } } -void Client::SetMessageOfTheDay(std::string message) +void Client::SetMessageOfTheDay(String message) { messageOfTheDay = message; notifyMessageOfTheDay(); } -std::string Client::GetMessageOfTheDay() +String Client::GetMessageOfTheDay() { return messageOfTheDay; } -void Client::AddServerNotification(std::pair notification) +void Client::AddServerNotification(std::pair notification) { serverNotifications.push_back(notification); notifyNewNotification(notification); } -std::vector > Client::GetServerNotifications() +std::vector > Client::GetServerNotifications() { return serverNotifications; } @@ -705,7 +704,7 @@ RequestStatus Client::ParseServerReturn(char *result, int status, bool json) return RequestOkay; if (status != 200) { - std::stringstream httperror; + String::Stream httperror; httperror << "HTTP Error " << status << ": " << http_ret_text(status); lastError = httperror.str(); return RequestFailure; @@ -727,7 +726,7 @@ RequestStatus Client::ParseServerReturn(char *result, int status, bool json) int status = root.get("Status", 1).asInt(); if (status != 1) { - lastError = root.get("Error", "Unspecified Error").asString(); + lastError = ByteString(root.get("Error", "Unspecified Error").asString()).FromUtf8(); return RequestFailure; } } @@ -737,12 +736,12 @@ RequestStatus Client::ParseServerReturn(char *result, int status, bool json) if (!strncmp((const char *)result, "Error: ", 7)) { status = atoi(result+7); - std::stringstream httperror; + String::Stream httperror; httperror << "HTTP Error " << status << ": " << http_ret_text(status); lastError = httperror.str(); return RequestFailure; } - lastError = std::string("Could not read response: ") + e.what(); + lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); return RequestFailure; } } @@ -750,7 +749,7 @@ RequestStatus Client::ParseServerReturn(char *result, int status, bool json) { if (strncmp((const char *)result, "OK", 2)) { - lastError = std::string(result); + lastError = ByteString(result).FromUtf8(); return RequestFailure; } } @@ -808,10 +807,10 @@ bool Client::CheckUpdate(void *updateRequest, bool checkSession) Json::Value notificationsArray = objDocument["Notifications"]; for (Json::UInt j = 0; j < notificationsArray.size(); j++) { - std::string notificationLink = notificationsArray[j]["Link"].asString(); - std::string notificationText = notificationsArray[j]["Text"].asString(); + ByteString notificationLink = notificationsArray[j]["Link"].asString(); + String notificationText = ByteString(notificationsArray[j]["Text"].asString()).FromUtf8(); - std::pair item = std::pair(notificationText, notificationLink); + std::pair item = std::pair(notificationText, notificationLink); AddServerNotification(item); } @@ -819,7 +818,7 @@ bool Client::CheckUpdate(void *updateRequest, bool checkSession) //MOTD if (!usingAltUpdateServer || !checkSession) { - this->messageOfTheDay = objDocument["MessageOfTheDay"].asString(); + this->messageOfTheDay = ByteString(objDocument["MessageOfTheDay"].asString()).FromUtf8(); notifyMessageOfTheDay(); #ifndef IGNORE_UPDATES @@ -830,8 +829,8 @@ bool Client::CheckUpdate(void *updateRequest, bool checkSession) int stableMajor = stableVersion["Major"].asInt(); int stableMinor = stableVersion["Minor"].asInt(); int stableBuild = stableVersion["Build"].asInt(); - std::string stableFile = stableVersion["File"].asString(); - std::string stableChangelog = stableVersion["Changelog"].asString(); + ByteString stableFile = stableVersion["File"].asString(); + String stableChangelog = ByteString(stableVersion["Changelog"].asString()).FromUtf8(); if (stableBuild > BUILD_NUM) { updateAvailable = true; @@ -845,8 +844,8 @@ bool Client::CheckUpdate(void *updateRequest, bool checkSession) int betaMajor = betaVersion["Major"].asInt(); int betaMinor = betaVersion["Minor"].asInt(); int betaBuild = betaVersion["Build"].asInt(); - std::string betaFile = betaVersion["File"].asString(); - std::string betaChangelog = betaVersion["Changelog"].asString(); + ByteString betaFile = betaVersion["File"].asString(); + String betaChangelog = ByteString(betaVersion["Changelog"].asString()).FromUtf8(); if (betaBuild > BUILD_NUM) { updateAvailable = true; @@ -857,8 +856,8 @@ bool Client::CheckUpdate(void *updateRequest, bool checkSession) #if defined(SNAPSHOT) || MOD_ID > 0 Json::Value snapshotVersion = versions["Snapshot"]; int snapshotSnapshot = snapshotVersion["Snapshot"].asInt(); - std::string snapshotFile = snapshotVersion["File"].asString(); - std::string snapshotChangelog = snapshotVersion["Changelog"].asString(); + ByteString snapshotFile = snapshotVersion["File"].asString(); + String snapshotChangelog = ByteString(snapshotVersion["Changelog"].asString()).FromUtf8(); if (snapshotSnapshot > SNAPSHOT_ID) { updateAvailable = true; @@ -914,7 +913,7 @@ void Client::notifyAuthUserChanged() } } -void Client::notifyNewNotification(std::pair notification) +void Client::notifyNewNotification(std::pair notification) { for (std::vector::iterator iterator = listeners.begin(), end = listeners.end(); iterator != end; ++iterator) { @@ -1003,7 +1002,7 @@ RequestStatus Client::UploadSave(SaveInfo & save) int dataStatus; char * data; int dataLength = 0; - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; if (authUser.UserID) { @@ -1031,9 +1030,9 @@ RequestStatus Client::UploadSave(SaveInfo & save) #endif char *saveName = new char[save.GetName().length() + 1]; - std::strcpy (saveName, save.GetName().c_str()); + std::strcpy (saveName, save.GetName().ToUtf8().c_str()); char *saveDescription = new char[save.GetDescription().length() + 1]; - std::strcpy (saveDescription, save.GetDescription().c_str()); + std::strcpy (saveDescription, save.GetDescription().ToUtf8().c_str()); char *userid = new char[userIDStream.str().length() + 1]; std::strcpy (userid, userIDStream.str().c_str()); char *session = new char[authUser.SessionID.length() + 1]; @@ -1058,7 +1057,7 @@ RequestStatus Client::UploadSave(SaveInfo & save) RequestStatus ret = ParseServerReturn(data, dataStatus, false); if (ret == RequestOkay) { - int saveID = format::StringToNumber(data+3); + int saveID = format::ByteStringToNumber(data+3); if (!saveID) { lastError = "Server did not return Save ID"; @@ -1072,9 +1071,9 @@ RequestStatus Client::UploadSave(SaveInfo & save) return ret; } -void Client::MoveStampToFront(std::string stampID) +void Client::MoveStampToFront(ByteString stampID) { - for (std::list::iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator) + for (std::list::iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator) { if((*iterator) == stampID) { @@ -1086,9 +1085,9 @@ void Client::MoveStampToFront(std::string stampID) updateStamps(); } -SaveFile * Client::GetStamp(std::string stampID) +SaveFile * Client::GetStamp(ByteString stampID) { - std::string stampFile = std::string(STAMPS_DIR PATH_SEP + stampID + ".stm"); + ByteString stampFile = ByteString(STAMPS_DIR PATH_SEP + stampID + ".stm"); SaveFile * file = new SaveFile(stampID); if (!FileExists(stampFile)) stampFile = stampID; @@ -1101,20 +1100,20 @@ SaveFile * Client::GetStamp(std::string stampID) } catch (ParseException & e) { - std::cerr << "Client: Invalid stamp file, " << stampID << " " << std::string(e.what()) << std::endl; - file->SetLoadingError(e.what()); + std::cerr << "Client: Invalid stamp file, " << stampID << " " << e.what() << std::endl; + file->SetLoadingError(ByteString(e.what()).FromUtf8()); } } return file; } -void Client::DeleteStamp(std::string stampID) +void Client::DeleteStamp(ByteString stampID) { - for (std::list::iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator) + for (std::list::iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator) { if((*iterator) == stampID) { - std::stringstream stampFilename; + ByteString::Stream stampFilename; stampFilename << STAMPS_DIR; stampFilename << PATH_SEP; stampFilename << stampID; @@ -1128,7 +1127,7 @@ void Client::DeleteStamp(std::string stampID) updateStamps(); } -std::string Client::AddStamp(GameSave * saveData) +ByteString Client::AddStamp(GameSave * saveData) { unsigned t=(unsigned)time(NULL); if (lastStampTime!=t) @@ -1138,12 +1137,12 @@ std::string Client::AddStamp(GameSave * saveData) } else lastStampName++; - std::stringstream saveID; + ByteString::Stream saveID; //sprintf(saveID, "%08x%02x", lastStampTime, lastStampName); saveID << std::setw(8) << std::setfill('0') << std::hex << lastStampTime << std::setw(2) << std::setfill('0') << std::hex << lastStampName; - std::string filename = std::string(STAMPS_DIR PATH_SEP + saveID.str()+".stm").c_str(); + ByteString filename = STAMPS_DIR PATH_SEP + saveID.str() + ".stm"; MakeDirectory(STAMPS_DIR); @@ -1183,8 +1182,8 @@ void Client::updateStamps() MakeDirectory(STAMPS_DIR); std::ofstream stampsStream; - stampsStream.open(std::string(STAMPS_DIR PATH_SEP "stamps.def").c_str(), std::ios::binary); - for (std::list::const_iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator) + stampsStream.open(ByteString(STAMPS_DIR PATH_SEP "stamps.def").c_str(), std::ios::binary); + for (std::list::const_iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator) { stampsStream.write((*iterator).c_str(), 10); } @@ -1205,7 +1204,7 @@ void Client::RescanStamps() { if(strncmp(entry->d_name, "..", 3) && strncmp(entry->d_name, ".", 2) && strstr(entry->d_name, ".stm") && strlen(entry->d_name) == 14) { - stampIDs.push_front(std::string(entry->d_name).substr(0, 10)); + stampIDs.push_front(ByteString(entry->d_name).substr(0, 10)); } } closedir(directory); @@ -1218,19 +1217,19 @@ int Client::GetStampsCount() return stampIDs.size(); } -std::vector Client::GetStamps(int start, int count) +std::vector Client::GetStamps(int start, int count) { int size = (int)stampIDs.size(); if (start+count > size) { if(start > size) - return std::vector(); + return std::vector(); count = size-start; } - std::vector stampRange; + std::vector stampRange; int index = 0; - for (std::list::const_iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator, ++index) + for (std::list::const_iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator, ++index) { if(index>=start && index < start+count) stampRange.push_back(*iterator); @@ -1248,8 +1247,8 @@ RequestStatus Client::ExecVote(int saveID, int direction) if (authUser.UserID) { char * directionText = (char*)(direction==1?"Up":"Down"); - std::string saveIDText = format::NumberToString(saveID); - std::string userIDText = format::NumberToString(authUser.UserID); + ByteString saveIDText = format::NumberToByteString(saveID); + ByteString userIDText = format::NumberToByteString(authUser.UserID); char *id = new char[saveIDText.length() + 1]; std::strcpy(id, saveIDText.c_str()); @@ -1282,7 +1281,7 @@ unsigned char * Client::GetSaveData(int saveID, int saveDate, int & dataLength) int dataStatus; char *data; dataLength = 0; - std::stringstream urlStream; + ByteString::Stream urlStream; if (saveDate) urlStream << "http://" << STATICSERVER << "/" << saveID << "_" << saveDate << ".cps"; else @@ -1315,7 +1314,7 @@ std::vector Client::GetSaveData(int saveID, int saveDate) RequestBroker::Request * Client::GetSaveDataAsync(int saveID, int saveDate) { - std::stringstream urlStream; + ByteString::Stream urlStream; if(saveDate){ urlStream << "http://" << STATICSERVER << "/" << saveID << "_" << saveDate << ".cps"; } else { @@ -1348,13 +1347,13 @@ RequestBroker::Request * Client::SaveUserInfoAsync(UserInfo info) } virtual ~StatusParser() { } }; - std::map postData; - postData.insert(std::pair("Location", info.location)); - postData.insert(std::pair("Biography", info.biography)); + std::map postData; + postData.insert(std::pair("Location", info.location.ToUtf8())); + postData.insert(std::pair("Biography", info.biography.ToUtf8())); return new APIRequest("http://" SERVER "/Profile.json", postData, new StatusParser()); } -RequestBroker::Request * Client::GetUserInfoAsync(std::string username) +RequestBroker::Request * Client::GetUserInfoAsync(ByteString username) { class UserInfoParser: public APIResultParser { @@ -1369,8 +1368,8 @@ RequestBroker::Request * Client::GetUserInfoAsync(std::string username) return new UserInfo(tempUser["ID"].asInt(), tempUser["Age"].asInt(), tempUser["Username"].asString(), - tempUser["Biography"].asString(), - tempUser["Location"].asString(), + ByteString(tempUser["Biography"].asString()).FromUtf8(), + ByteString(tempUser["Location"].asString()).FromUtf8(), tempUser["Website"].asString(), tempUser["Saves"]["Count"].asInt(), tempUser["Saves"]["AverageScore"].asInt(), @@ -1393,10 +1392,10 @@ RequestBroker::Request * Client::GetUserInfoAsync(std::string username) return new APIRequest("http://" SERVER "/User.json?Name=" + username, new UserInfoParser()); } -LoginStatus Client::Login(std::string username, std::string password, User & user) +LoginStatus Client::Login(ByteString username, ByteString password, User & user) { lastError = ""; - std::stringstream hashStream; + ByteString::Stream hashStream; char passwordHash[33]; char totalHash[33]; @@ -1429,17 +1428,17 @@ LoginStatus Client::Login(std::string username, std::string password, User & use free(data); int userIDTemp = objDocument["UserID"].asInt(); - std::string sessionIDTemp = objDocument["SessionID"].asString(); - std::string sessionKeyTemp = objDocument["SessionKey"].asString(); - std::string userElevationTemp = objDocument["Elevation"].asString(); + ByteString sessionIDTemp = objDocument["SessionID"].asString(); + ByteString sessionKeyTemp = objDocument["SessionKey"].asString(); + ByteString userElevationTemp = objDocument["Elevation"].asString(); Json::Value notificationsArray = objDocument["Notifications"]; for (Json::UInt j = 0; j < notificationsArray.size(); j++) { - std::string notificationLink = notificationsArray[j]["Link"].asString(); - std::string notificationText = notificationsArray[j]["Text"].asString(); + ByteString notificationLink = notificationsArray[j]["Link"].asString(); + String notificationText = ByteString(notificationsArray[j]["Text"].asString()).FromUtf8(); - std::pair item = std::pair(notificationText, notificationLink); + std::pair item = std::pair(notificationText, notificationLink); AddServerNotification(item); } @@ -1447,7 +1446,7 @@ LoginStatus Client::Login(std::string username, std::string password, User & use user.UserID = userIDTemp; user.SessionID = sessionIDTemp; user.SessionKey = sessionKeyTemp; - std::string userElevation = userElevationTemp; + ByteString userElevation = userElevationTemp; if(userElevation == "Admin") user.UserElevation = User::ElevationAdmin; else if(userElevation == "Mod") @@ -1458,7 +1457,7 @@ LoginStatus Client::Login(std::string username, std::string password, User & use } catch (std::exception &e) { - lastError = std::string("Could not read response: ") + e.what(); + lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); return LoginError; } } @@ -1469,13 +1468,13 @@ LoginStatus Client::Login(std::string username, std::string password, User & use RequestStatus Client::DeleteSave(int saveID) { lastError = ""; - std::stringstream urlStream; + ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/Delete.json?ID=" << saveID << "&Mode=Delete&Key=" << authUser.SessionKey; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); } @@ -1489,16 +1488,16 @@ RequestStatus Client::DeleteSave(int saveID) return ret; } -RequestStatus Client::AddComment(int saveID, std::string comment) +RequestStatus Client::AddComment(int saveID, String comment) { lastError = ""; - std::stringstream urlStream; + ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/Comments.json?ID=" << saveID; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; const char *const postNames[] = { "Comment", NULL }; @@ -1519,7 +1518,7 @@ RequestStatus Client::AddComment(int saveID, std::string comment) RequestStatus Client::FavouriteSave(int saveID, bool favourite) { lastError = ""; - std::stringstream urlStream; + ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/Favourite.json?ID=" << saveID << "&Key=" << authUser.SessionKey; @@ -1527,7 +1526,7 @@ RequestStatus Client::FavouriteSave(int saveID, bool favourite) urlStream << "&Mode=Remove"; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); } @@ -1541,16 +1540,16 @@ RequestStatus Client::FavouriteSave(int saveID, bool favourite) return ret; } -RequestStatus Client::ReportSave(int saveID, std::string message) +RequestStatus Client::ReportSave(int saveID, String message) { lastError = ""; - std::stringstream urlStream; + ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/Report.json?ID=" << saveID << "&Key=" << authUser.SessionKey; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; const char *const postNames[] = { "Reason", NULL }; @@ -1571,13 +1570,13 @@ RequestStatus Client::ReportSave(int saveID, std::string message) RequestStatus Client::UnpublishSave(int saveID) { lastError = ""; - std::stringstream urlStream; + ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/Delete.json?ID=" << saveID << "&Mode=Unpublish&Key=" << authUser.SessionKey; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); } @@ -1594,13 +1593,13 @@ RequestStatus Client::UnpublishSave(int saveID) RequestStatus Client::PublishSave(int saveID) { lastError = ""; - std::stringstream urlStream; + ByteString::Stream urlStream; char *data; int dataStatus; urlStream << "http://" << SERVER << "/Browse/View.json?ID=" << saveID << "&Key=" << authUser.SessionKey; if (authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; const char *const postNames[] = { "ActionPublish", NULL }; const char *const postDatas[] = { "" }; @@ -1619,7 +1618,7 @@ RequestStatus Client::PublishSave(int saveID) SaveInfo * Client::GetSave(int saveID, int saveDate) { lastError = ""; - std::stringstream urlStream; + ByteString::Stream urlStream; urlStream << "http://" << SERVER << "/Browse/View.json?ID=" << saveID; if(saveDate) { @@ -1629,7 +1628,7 @@ SaveInfo * Client::GetSave(int saveID, int saveDate) int dataStatus, dataLength; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); } @@ -1649,9 +1648,9 @@ SaveInfo * Client::GetSave(int saveID, int saveDate) int tempScoreUp = objDocument["ScoreUp"].asInt(); int tempScoreDown = objDocument["ScoreDown"].asInt(); int tempMyScore = objDocument["ScoreMine"].asInt(); - std::string tempUsername = objDocument["Username"].asString(); - std::string tempName = objDocument["Name"].asString(); - std::string tempDescription = objDocument["Description"].asString(); + ByteString tempUsername = objDocument["Username"].asString(); + String tempName = ByteString(objDocument["Name"].asString()).FromUtf8(); + String tempDescription = ByteString(objDocument["Description"].asString()).FromUtf8(); int tempCreatedDate = objDocument["DateCreated"].asInt(); int tempUpdatedDate = objDocument["Date"].asInt(); bool tempPublished = objDocument["Published"].asBool(); @@ -1661,7 +1660,7 @@ SaveInfo * Client::GetSave(int saveID, int saveDate) int tempVersion = objDocument["Version"].asInt(); Json::Value tagsArray = objDocument["Tags"]; - std::list tempTags; + std::list tempTags; for (Json::UInt j = 0; j < tagsArray.size(); j++) tempTags.push_back(tagsArray[j].asString()); @@ -1677,7 +1676,7 @@ SaveInfo * Client::GetSave(int saveID, int saveDate) } catch (std::exception & e) { - lastError = std::string("Could not read response: ") + e.what(); + lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); free(data); return NULL; } @@ -1685,14 +1684,14 @@ SaveInfo * Client::GetSave(int saveID, int saveDate) else { free(data); - lastError = http_ret_text(dataStatus); + lastError = ByteString(http_ret_text(dataStatus)).FromUtf8(); } return NULL; } RequestBroker::Request * Client::GetSaveAsync(int saveID, int saveDate) { - std::stringstream urlStream; + ByteString::Stream urlStream; urlStream << "http://" << SERVER << "/Browse/View.json?ID=" << saveID; if(saveDate) { @@ -1713,9 +1712,9 @@ RequestBroker::Request * Client::GetSaveAsync(int saveID, int saveDate) int tempScoreUp = objDocument["ScoreUp"].asInt(); int tempScoreDown = objDocument["ScoreDown"].asInt(); int tempMyScore = objDocument["ScoreMine"].asInt(); - std::string tempUsername = objDocument["Username"].asString(); - std::string tempName = objDocument["Name"].asString(); - std::string tempDescription = objDocument["Description"].asString(); + ByteString tempUsername = objDocument["Username"].asString(); + String tempName = ByteString(objDocument["Name"].asString()).FromUtf8(); + String tempDescription = ByteString(objDocument["Description"].asString()).FromUtf8(); int tempCreatedDate = objDocument["DateCreated"].asInt(); int tempUpdatedDate = objDocument["Date"].asInt(); bool tempPublished = objDocument["Published"].asBool(); @@ -1725,7 +1724,7 @@ RequestBroker::Request * Client::GetSaveAsync(int saveID, int saveDate) int tempVersion = objDocument["Version"].asInt(); Json::Value tagsArray = objDocument["Tags"]; - std::list tempTags; + std::list tempTags; for (Json::UInt j = 0; j < tagsArray.size(); j++) tempTags.push_back(tagsArray[j].asString()); @@ -1767,12 +1766,12 @@ RequestBroker::Request * Client::GetCommentsAsync(int saveID, int start, int cou for (Json::UInt j = 0; j < commentsArray.size(); j++) { - int userID = format::StringToNumber(commentsArray[j]["UserID"].asString()); - std::string username = commentsArray[j]["Username"].asString(); - std::string formattedUsername = commentsArray[j]["FormattedUsername"].asString(); + int userID = format::ByteStringToNumber(commentsArray[j]["UserID"].asString()); + ByteString username = commentsArray[j]["Username"].asString(); + ByteString formattedUsername = commentsArray[j]["FormattedUsername"].asString(); if (formattedUsername == "jacobot") formattedUsername = "\bt" + formattedUsername; - std::string comment = commentsArray[j]["Text"].asString(); + String comment = ByteString(commentsArray[j]["Text"].asString()).FromUtf8(); commentArray->push_back(new SaveComment(userID, username, formattedUsername, comment)); } return commentArray; @@ -1790,17 +1789,17 @@ RequestBroker::Request * Client::GetCommentsAsync(int saveID, int start, int cou virtual ~CommentsParser() { } }; - std::stringstream urlStream; + ByteString::Stream urlStream; urlStream << "http://" << SERVER << "/Browse/Comments.json?ID=" << saveID << "&Start=" << start << "&Count=" << count; return new APIRequest(urlStream.str(), new CommentsParser()); } -std::vector > * Client::GetTags(int start, int count, std::string query, int & resultCount) +std::vector > * Client::GetTags(int start, int count, String query, int & resultCount) { lastError = ""; resultCount = 0; - std::vector > * tagArray = new std::vector >(); - std::stringstream urlStream; + std::vector > * tagArray = new std::vector >(); + ByteString::Stream urlStream; char * data; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/Tags.json?Start=" << start << "&Count=" << count; @@ -1808,7 +1807,7 @@ std::vector > * Client::GetTags(int start, int count { urlStream << "&Search_Query="; if(query.length()) - urlStream << format::URLEncode(query); + urlStream << format::URLEncode(query.ToUtf8()); } data = http_simple_get((char *)urlStream.str().c_str(), &dataStatus, &dataLength); @@ -1825,29 +1824,29 @@ std::vector > * Client::GetTags(int start, int count for (Json::UInt j = 0; j < tagsArray.size(); j++) { int tagCount = tagsArray[j]["Count"].asInt(); - std::string tag = tagsArray[j]["Tag"].asString(); - tagArray->push_back(std::pair(tag, tagCount)); + ByteString tag = tagsArray[j]["Tag"].asString(); + tagArray->push_back(std::pair(tag, tagCount)); } } catch (std::exception & e) { - lastError = std::string("Could not read response: ") + e.what(); + lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); } } else { - lastError = http_ret_text(dataStatus); + lastError = ByteString(http_ret_text(dataStatus)).FromUtf8(); } free(data); return tagArray; } -std::vector * Client::SearchSaves(int start, int count, std::string query, std::string sort, std::string category, int & resultCount) +std::vector * Client::SearchSaves(int start, int count, String query, ByteString sort, ByteString category, int & resultCount) { lastError = ""; resultCount = 0; std::vector * saveArray = new std::vector(); - std::stringstream urlStream; + ByteString::Stream urlStream; char * data; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse.json?Start=" << start << "&Count=" << count; @@ -1855,7 +1854,7 @@ std::vector * Client::SearchSaves(int start, int count, std::string q { urlStream << "&Search_Query="; if(query.length()) - urlStream << format::URLEncode(query); + urlStream << format::URLEncode(query.ToUtf8()); if(sort == "date") { if(query.length()) @@ -1869,7 +1868,7 @@ std::vector * Client::SearchSaves(int start, int count, std::string q } if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); } @@ -1895,8 +1894,8 @@ std::vector * Client::SearchSaves(int start, int count, std::string q int tempUpdatedDate = savesArray[j]["Updated"].asInt(); int tempScoreUp = savesArray[j]["ScoreUp"].asInt(); int tempScoreDown = savesArray[j]["ScoreDown"].asInt(); - std::string tempUsername = savesArray[j]["Username"].asString(); - std::string tempName = savesArray[j]["Name"].asString(); + ByteString tempUsername = savesArray[j]["Username"].asString(); + String tempName = ByteString(savesArray[j]["Name"].asString()).FromUtf8(); int tempVersion = savesArray[j]["Version"].asInt(); bool tempPublished = savesArray[j]["Published"].asBool(); SaveInfo * tempSaveInfo = new SaveInfo(tempID, tempCreatedDate, tempUpdatedDate, tempScoreUp, tempScoreDown, tempUsername, tempName); @@ -1907,7 +1906,7 @@ std::vector * Client::SearchSaves(int start, int count, std::string q } catch (std::exception &e) { - lastError = std::string("Could not read response: ") + e.what(); + lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); } } free(data); @@ -1928,17 +1927,17 @@ void Client::ClearThumbnailRequests() } } -std::list * Client::RemoveTag(int saveID, std::string tag) +std::list * Client::RemoveTag(int saveID, ByteString tag) { lastError = ""; - std::list * tags = NULL; - std::stringstream urlStream; + std::list * tags = NULL; + ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/EditTag.json?Op=delete&ID=" << saveID << "&Tag=" << tag << "&Key=" << authUser.SessionKey; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); } @@ -1957,30 +1956,30 @@ std::list * Client::RemoveTag(int saveID, std::string tag) dataStream >> responseObject; Json::Value tagsArray = responseObject["Tags"]; - tags = new std::list(); + tags = new std::list(); for (Json::UInt j = 0; j < tagsArray.size(); j++) tags->push_back(tagsArray[j].asString()); } catch (std::exception &e) { - lastError = std::string("Could not read response: ") + e.what(); + lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); } } free(data); return tags; } -std::list * Client::AddTag(int saveID, std::string tag) +std::list * Client::AddTag(int saveID, ByteString tag) { lastError = ""; - std::list * tags = NULL; - std::stringstream urlStream; + std::list * tags = NULL; + ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/EditTag.json?Op=add&ID=" << saveID << "&Tag=" << tag << "&Key=" << authUser.SessionKey; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); } @@ -1999,13 +1998,13 @@ std::list * Client::AddTag(int saveID, std::string tag) dataStream >> responseObject; Json::Value tagsArray = responseObject["Tags"]; - tags = new std::list(); + tags = new std::list(); for (Json::UInt j = 0; j < tagsArray.size(); j++) tags->push_back(tagsArray[j].asString()); } catch (std::exception & e) { - lastError = std::string("Could not read response: ") + e.what(); + lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); } } free(data); @@ -2081,7 +2080,7 @@ void Client::SaveAuthorInfo(Json::Value *saveInto) // powder.pref preference getting / setting functions // Recursively go down the json to get the setting we want -Json::Value Client::GetPref(Json::Value root, std::string prop, Json::Value defaultValue) +Json::Value Client::GetPref(Json::Value root, ByteString prop, Json::Value defaultValue) { try { @@ -2097,7 +2096,7 @@ Json::Value Client::GetPref(Json::Value root, std::string prop, Json::Value defa } } -std::string Client::GetPrefString(std::string prop, std::string defaultValue) +ByteString Client::GetPrefByteString(ByteString prop, ByteString defaultValue) { try { @@ -2109,7 +2108,19 @@ std::string Client::GetPrefString(std::string prop, std::string defaultValue) } } -double Client::GetPrefNumber(std::string prop, double defaultValue) +String Client::GetPrefString(ByteString prop, String defaultValue) +{ + try + { + return ByteString(GetPref(preferences, prop, defaultValue.ToUtf8()).asString()).FromUtf8(false); + } + catch (std::exception & e) + { + return defaultValue; + } +} + +double Client::GetPrefNumber(ByteString prop, double defaultValue) { try { @@ -2121,7 +2132,7 @@ double Client::GetPrefNumber(std::string prop, double defaultValue) } } -int Client::GetPrefInteger(std::string prop, int defaultValue) +int Client::GetPrefInteger(ByteString prop, int defaultValue) { try { @@ -2133,7 +2144,7 @@ int Client::GetPrefInteger(std::string prop, int defaultValue) } } -unsigned int Client::GetPrefUInteger(std::string prop, unsigned int defaultValue) +unsigned int Client::GetPrefUInteger(ByteString prop, unsigned int defaultValue) { try { @@ -2145,7 +2156,7 @@ unsigned int Client::GetPrefUInteger(std::string prop, unsigned int defaultValue } } -bool Client::GetPrefBool(std::string prop, bool defaultValue) +bool Client::GetPrefBool(ByteString prop, bool defaultValue) { try { @@ -2157,11 +2168,11 @@ bool Client::GetPrefBool(std::string prop, bool defaultValue) } } -std::vector Client::GetPrefStringArray(std::string prop) +std::vector Client::GetPrefByteStringArray(ByteString prop) { try { - std::vector ret; + std::vector ret; Json::Value arr = GetPref(preferences, prop); for (int i = 0; i < (int)arr.size(); i++) ret.push_back(arr[i].asString()); @@ -2171,10 +2182,27 @@ std::vector Client::GetPrefStringArray(std::string prop) { } - return std::vector(); + return std::vector(); } -std::vector Client::GetPrefNumberArray(std::string prop) +std::vector Client::GetPrefStringArray(ByteString prop) +{ + try + { + std::vector ret; + Json::Value arr = GetPref(preferences, prop); + for (int i = 0; i < (int)arr.size(); i++) + ret.push_back(ByteString(arr[i].asString()).FromUtf8(false)); + return ret; + } + catch (std::exception & e) + { + + } + return std::vector(); +} + +std::vector Client::GetPrefNumberArray(ByteString prop) { try { @@ -2191,7 +2219,7 @@ std::vector Client::GetPrefNumberArray(std::string prop) return std::vector(); } -std::vector Client::GetPrefIntegerArray(std::string prop) +std::vector Client::GetPrefIntegerArray(ByteString prop) { try { @@ -2208,7 +2236,7 @@ std::vector Client::GetPrefIntegerArray(std::string prop) return std::vector(); } -std::vector Client::GetPrefUIntegerArray(std::string prop) +std::vector Client::GetPrefUIntegerArray(ByteString prop) { try { @@ -2225,7 +2253,7 @@ std::vector Client::GetPrefUIntegerArray(std::string prop) return std::vector(); } -std::vector Client::GetPrefBoolArray(std::string prop) +std::vector Client::GetPrefBoolArray(ByteString prop) { try { @@ -2247,7 +2275,7 @@ std::vector Client::GetPrefBoolArray(std::string prop) // any other way will set the value of a copy of preferences, not the original // This function will recursively go through and create an object with the property we wanted set, // and return it to SetPref to do the actual setting -Json::Value Client::SetPrefHelper(Json::Value root, std::string prop, Json::Value value) +Json::Value Client::SetPrefHelper(Json::Value root, ByteString prop, Json::Value value) { size_t dot = prop.find("."); if (dot == prop.npos) @@ -2261,7 +2289,7 @@ Json::Value Client::SetPrefHelper(Json::Value root, std::string prop, Json::Valu return root; } -void Client::SetPref(std::string prop, Json::Value value) +void Client::SetPref(ByteString prop, Json::Value value) { try { @@ -2279,7 +2307,7 @@ void Client::SetPref(std::string prop, Json::Value value) } } -void Client::SetPref(std::string prop, std::vector value) +void Client::SetPref(ByteString prop, std::vector value) { try { @@ -2295,3 +2323,8 @@ void Client::SetPref(std::string prop, std::vector value) } } + +void Client::SetPrefUnicode(ByteString prop, String value) +{ + SetPref(prop, value.ToUtf8()); +} diff --git a/src/client/Client.h b/src/client/Client.h index 2f3a0b0ed..533122a09 100644 --- a/src/client/Client.h +++ b/src/client/Client.h @@ -5,6 +5,7 @@ #include #include +#include "common/String.h" #include "Config.h" #include "common/Singleton.h" @@ -34,24 +35,24 @@ class UpdateInfo { public: enum BuildType { Stable, Beta, Snapshot }; - std::string File; - std::string Changelog; + ByteString File; + String Changelog; int Major; int Minor; int Build; int Time; BuildType Type; UpdateInfo() : File(""), Changelog(""), Major(0), Minor(0), Build(0), Time(0), Type(Stable) {} - UpdateInfo(int major, int minor, int build, std::string file, std::string changelog, BuildType type) : File(file), Changelog(changelog), Major(major), Minor(minor), Build(build), Time(0), Type(type) {} - UpdateInfo(int time, std::string file, std::string changelog, BuildType type) : File(file), Changelog(changelog), Major(0), Minor(0), Build(0), Time(time), Type(type) {} + UpdateInfo(int major, int minor, int build, ByteString file, String changelog, BuildType type) : File(file), Changelog(changelog), Major(major), Minor(minor), Build(build), Time(0), Type(type) {} + UpdateInfo(int time, ByteString file, String changelog, BuildType type) : File(file), Changelog(changelog), Major(0), Minor(0), Build(0), Time(time), Type(type) {} }; class RequestListener; class ClientListener; class Client: public Singleton { private: - std::string messageOfTheDay; - std::vector > serverNotifications; + String messageOfTheDay; + std::vector > serverNotifications; void * versionCheckRequest; void * alternateVersionCheckRequest; @@ -59,10 +60,10 @@ private: bool updateAvailable; UpdateInfo updateInfo; - std::string lastError; + String lastError; bool firstRun; - std::list stampIDs; + std::list stampIDs; unsigned lastStampTime; int lastStampName; @@ -75,16 +76,16 @@ private: void * activeThumbRequests[IMGCONNS]; int activeThumbRequestTimes[IMGCONNS]; int activeThumbRequestCompleteTimes[IMGCONNS]; - std::string activeThumbRequestIDs[IMGCONNS]; + ByteString activeThumbRequestIDs[IMGCONNS]; void notifyUpdateAvailable(); void notifyAuthUserChanged(); void notifyMessageOfTheDay(); - void notifyNewNotification(std::pair notification); + void notifyNewNotification(std::pair notification); // internal preferences handling Json::Value preferences; - Json::Value GetPref(Json::Value root, std::string prop, Json::Value defaultValue = Json::nullValue); - Json::Value SetPrefHelper(Json::Value root, std::string prop, Json::Value value); + Json::Value GetPref(Json::Value root, ByteString prop, Json::Value defaultValue = Json::nullValue); + Json::Value SetPrefHelper(Json::Value root, ByteString prop, Json::Value value); // Save stealing info Json::Value authors; @@ -107,30 +108,30 @@ public: Client(); ~Client(); - std::vector DirectorySearch(std::string directory, std::string search, std::vector extensions); - std::vector DirectorySearch(std::string directory, std::string search, std::string extension); + std::vector DirectorySearch(ByteString directory, ByteString search, std::vector extensions); + std::vector DirectorySearch(ByteString directory, ByteString search, ByteString extension); - std::string FileOpenDialogue(); + ByteString FileOpenDialogue(); //std::string FileSaveDialogue(); bool DoInstallation(); - std::vector ReadFile(std::string filename); + std::vector ReadFile(ByteString filename); - void AddServerNotification(std::pair notification); - std::vector > GetServerNotifications(); + void AddServerNotification(std::pair notification); + std::vector > GetServerNotifications(); - void SetMessageOfTheDay(std::string message); - std::string GetMessageOfTheDay(); + void SetMessageOfTheDay(String message); + String GetMessageOfTheDay(); - void Initialise(std::string proxyString); - void SetProxy(std::string proxy); + void Initialise(ByteString proxyString); + void SetProxy(ByteString proxy); bool IsFirstRun(); int MakeDirectory(const char * dirname); - bool WriteFile(std::vector fileData, std::string filename); - bool WriteFile(std::vector fileData, std::string filename); - bool FileExists(std::string filename); + bool WriteFile(std::vector fileData, ByteString filename); + bool WriteFile(std::vector fileData, ByteString filename); + bool FileExists(ByteString filename); void AddListener(ClientListener * listener); void RemoveListener(ClientListener * listener); @@ -138,30 +139,30 @@ public: RequestStatus ExecVote(int saveID, int direction); RequestStatus UploadSave(SaveInfo & save); - SaveFile * GetStamp(std::string stampID); - void DeleteStamp(std::string stampID); - std::string AddStamp(GameSave * saveData); - std::vector GetStamps(int start, int count); + SaveFile * GetStamp(ByteString stampID); + void DeleteStamp(ByteString stampID); + ByteString AddStamp(GameSave * saveData); + std::vector GetStamps(int start, int count); void RescanStamps(); int GetStampsCount(); SaveFile * GetFirstStamp(); - void MoveStampToFront(std::string stampID); + void MoveStampToFront(ByteString stampID); void updateStamps(); - RequestStatus AddComment(int saveID, std::string comment); + RequestStatus AddComment(int saveID, String comment); //Retrieves a "UserInfo" object - RequestBroker::Request * GetUserInfoAsync(std::string username); + RequestBroker::Request * GetUserInfoAsync(ByteString username); RequestBroker::Request * SaveUserInfoAsync(UserInfo info); RequestBroker::Request * GetSaveDataAsync(int saveID, int saveDate); unsigned char * GetSaveData(int saveID, int saveDate, int & dataLength); std::vector GetSaveData(int saveID, int saveDate); - LoginStatus Login(std::string username, std::string password, User & user); + LoginStatus Login(ByteString username, ByteString password, User & user); void ClearThumbnailRequests(); - std::vector * SearchSaves(int start, int count, std::string query, std::string sort, std::string category, int & resultCount); - std::vector > * GetTags(int start, int count, std::string query, int & resultCount); + std::vector * SearchSaves(int start, int count, String query, ByteString sort, ByteString category, int & resultCount); + std::vector > * GetTags(int start, int count, String query, int & resultCount); RequestBroker::Request * GetCommentsAsync(int saveID, int start, int count); @@ -169,15 +170,15 @@ public: RequestBroker::Request * GetSaveAsync(int saveID, int saveDate); RequestStatus DeleteSave(int saveID); - RequestStatus ReportSave(int saveID, std::string message); + RequestStatus ReportSave(int saveID, String message); RequestStatus UnpublishSave(int saveID); RequestStatus PublishSave(int saveID); RequestStatus FavouriteSave(int saveID, bool favourite); void SetAuthUser(User user); User GetAuthUser(); - std::list * RemoveTag(int saveID, std::string tag); //TODO RequestStatus - std::list * AddTag(int saveID, std::string tag); - std::string GetLastError() { + std::list * RemoveTag(int saveID, ByteString tag); //TODO RequestStatus + std::list * AddTag(int saveID, ByteString tag); + String GetLastError() { return lastError; } RequestStatus ParseServerReturn(char *result, int status, bool json); @@ -188,19 +189,22 @@ public: // preferences functions void WritePrefs(); - std::string GetPrefString(std::string prop, std::string defaultValue); - double GetPrefNumber(std::string prop, double defaultValue); - int GetPrefInteger(std::string prop, int defaultValue); - unsigned int GetPrefUInteger(std::string prop, unsigned int defaultValue); - bool GetPrefBool(std::string prop, bool defaultValue); - std::vector GetPrefStringArray(std::string prop); - std::vector GetPrefNumberArray(std::string prop); - std::vector GetPrefIntegerArray(std::string prop); - std::vector GetPrefUIntegerArray(std::string prop); - std::vector GetPrefBoolArray(std::string prop); + ByteString GetPrefByteString(ByteString prop, ByteString defaultValue); + String GetPrefString(ByteString prop, String defaultValue); + double GetPrefNumber(ByteString prop, double defaultValue); + int GetPrefInteger(ByteString prop, int defaultValue); + unsigned int GetPrefUInteger(ByteString prop, unsigned int defaultValue); + bool GetPrefBool(ByteString prop, bool defaultValue); + std::vector GetPrefByteStringArray(ByteString prop); + std::vector GetPrefStringArray(ByteString prop); + std::vector GetPrefNumberArray(ByteString prop); + std::vector GetPrefIntegerArray(ByteString prop); + std::vector GetPrefUIntegerArray(ByteString prop); + std::vector GetPrefBoolArray(ByteString prop); - void SetPref(std::string prop, Json::Value value); - void SetPref(std::string property, std::vector value); + void SetPref(ByteString prop, Json::Value value); + void SetPref(ByteString property, std::vector value); + void SetPrefUnicode(ByteString prop, String value); }; #endif // CLIENT_H diff --git a/src/client/ClientListener.h b/src/client/ClientListener.h index e04572e5f..0d3345fa9 100644 --- a/src/client/ClientListener.h +++ b/src/client/ClientListener.h @@ -11,7 +11,7 @@ public: virtual void NotifyUpdateAvailable(Client * sender) {} virtual void NotifyAuthUserChanged(Client * sender) {} virtual void NotifyMessageOfTheDay(Client * sender) {} - virtual void NotifyNewNotification(Client * sender, std::pair notification) {} + virtual void NotifyNewNotification(Client * sender, std::pair notification) {} }; diff --git a/src/client/Download.cpp b/src/client/Download.cpp index b2534501b..da11c4c10 100644 --- a/src/client/Download.cpp +++ b/src/client/Download.cpp @@ -3,7 +3,7 @@ #include "DownloadManager.h" #include "HTTP.h" -Download::Download(std::string uri_, bool keepAlive): +Download::Download(ByteString uri_, bool keepAlive): http(NULL), keepAlive(keepAlive), downloadData(NULL), @@ -17,7 +17,7 @@ Download::Download(std::string uri_, bool keepAlive): downloadCanceled(false), downloadStarted(false) { - uri = std::string(uri_); + uri = ByteString(uri_); DownloadManager::Ref().AddDownload(this); } @@ -31,20 +31,20 @@ Download::~Download() } // add post data to a request -void Download::AddPostData(std::map data) +void Download::AddPostData(std::map data) { postDataBoundary = FindBoundary(data, ""); postData = GetMultipartMessage(data, postDataBoundary); } -void Download::AddPostData(std::pair data) +void Download::AddPostData(std::pair data) { - std::map postData; + std::map postData; postData.insert(data); AddPostData(postData); } // add userID and sessionID headers to the download. Must be done after download starts for some reason -void Download::AuthHeaders(std::string ID, std::string session) +void Download::AuthHeaders(ByteString ID, ByteString session) { if (ID != "0") userID = ID; @@ -68,13 +68,13 @@ void Download::Start() } // for persistent connections (keepAlive = true), reuse the open connection to make another request -bool Download::Reuse(std::string newuri) +bool Download::Reuse(ByteString newuri) { if (!keepAlive || !CheckDone() || CheckCanceled()) { return false; } - uri = std::string(newuri); + uri = newuri; DownloadManager::Ref().Lock(); downloadFinished = false; DownloadManager::Ref().Unlock(); diff --git a/src/client/Download.h b/src/client/Download.h index 9db636a7e..d925f3a46 100644 --- a/src/client/Download.h +++ b/src/client/Download.h @@ -1,12 +1,12 @@ #ifndef DOWNLOAD_H #define DOWNLOAD_H #include -#include +#include "common/String.h" class DownloadManager; class Download { - std::string uri; + ByteString uri; void *http; bool keepAlive; @@ -14,25 +14,25 @@ class Download int downloadSize; int downloadStatus; - std::string postData; - std::string postDataBoundary; + ByteString postData; + ByteString postDataBoundary; - std::string userID; - std::string userSession; + ByteString userID; + ByteString userSession; volatile bool downloadFinished; volatile bool downloadCanceled; volatile bool downloadStarted; public: - Download(std::string uri, bool keepAlive = false); + Download(ByteString uri, bool keepAlive = false); ~Download(); - void AddPostData(std::map data); - void AddPostData(std::pair data); - void AuthHeaders(std::string ID, std::string session); + void AddPostData(std::map data); + void AddPostData(std::pair data); + void AuthHeaders(ByteString ID, ByteString session); void Start(); - bool Reuse(std::string newuri); + bool Reuse(ByteString newuri); char* Finish(int *length, int *status); void Cancel(); diff --git a/src/client/GameSave.cpp b/src/client/GameSave.cpp index 34e188e5d..cedba9f4e 100644 --- a/src/client/GameSave.cpp +++ b/src/client/GameSave.cpp @@ -1,6 +1,5 @@ #include "common/tpt-minmax.h" #include -#include #include #include #include @@ -633,7 +632,7 @@ void GameSave::readOPS(char * data, int dataLength) throw ParseException(ParseException::Corrupt, "Unable to decompress (ret " + format::NumberToString(bz2ret) + ")"); } - set_bson_err_handler([](const char* err) { throw ParseException(ParseException::Corrupt, "BSON error when parsing save: " + std::string(err)); }); + set_bson_err_handler([](const char* err) { throw ParseException(ParseException::Corrupt, "BSON error when parsing save: " + ByteString(err).FromUtf8()); }); bson_init_data_size(&b, (char*)bsonData, bsonDataLen); bson_iterator_init(&iter, &b); @@ -679,7 +678,7 @@ void GameSave::readOPS(char * data, int dataLength) { if (!strcmp(bson_iterator_key(&signiter), "text") && bson_iterator_type(&signiter) == BSON_STRING) { - tempSign.text = format::CleanString(bson_iterator_string(&signiter), true, true, true).substr(0, 45); + tempSign.text = format::CleanString(ByteString(bson_iterator_string(&signiter)).FromUtf8(), true, true, true).substr(0, 45); } else if (!strcmp(bson_iterator_key(&signiter), "justification") && bson_iterator_type(&signiter) == BSON_INT) { @@ -764,7 +763,7 @@ void GameSave::readOPS(char * data, int dataLength) { if (bson_iterator_type(&subiter) == BSON_INT) { - std::string id = std::string(bson_iterator_key(&subiter)); + ByteString id = bson_iterator_key(&subiter); int num = bson_iterator_int(&subiter); palette.push_back(PaletteItem(id, num)); } @@ -806,7 +805,7 @@ void GameSave::readOPS(char * data, int dataLength) if (major > SAVE_VERSION || (major == SAVE_VERSION && minor > MINOR_VERSION)) #endif { - std::stringstream errorMessage; + String::Stream errorMessage; #ifdef RENDERER errorMessage << "Save from a newer version: Requires render version " << renderMajor << "." << renderMinor; #else @@ -1333,18 +1332,8 @@ void GameSave::readPSv(char * saveDataChar, int dataLength) sign tempSign("", 0, 0, sign::Left); //Gol data used to read older saves - int goltype[NGOL]; - int grule[NGOL+1][10]; - - int golRulesCount; - int * golRulesT = LoadGOLRules(golRulesCount); - memcpy(grule, golRulesT, sizeof(int) * (golRulesCount*10)); - free(golRulesT); - - int golTypesCount; - int * golTypesT = LoadGOLTypes(golTypesCount); - memcpy(goltype, golTypesT, sizeof(int) * (golTypesCount)); - free(golTypesT); + std::vector goltype = LoadGOLTypes(); + std::vector > grule = LoadGOLRules(); std::vector elements = GetElements(); @@ -1419,7 +1408,7 @@ void GameSave::readPSv(char * saveDataChar, int dataLength) int bzStatus = 0; if ((bzStatus = BZ2_bzBuffToBuffDecompress((char *)data, (unsigned *)&size, (char *)(saveData+12), dataLength-12, 0, 0))) { - std::stringstream bzStatusStr; + String::Stream bzStatusStr; bzStatusStr << bzStatus; throw ParseException(ParseException::Corrupt, "Cannot decompress: " + bzStatusStr.str()); } @@ -2399,7 +2388,7 @@ char * GameSave::serialiseOPS(unsigned int & dataLength) // Use unique_ptr with a custom deleter to ensure that bson_destroy is called even when an exception is thrown std::unique_ptr b_ptr(&b, bson_deleter); - set_bson_err_handler([](const char* err) { throw BuildException("BSON error when parsing save: " + std::string(err)); }); + set_bson_err_handler([](const char* err) { throw BuildException("BSON error when parsing save: " + ByteString(err).FromUtf8()); }); bson_init(&b); bson_append_start_object(&b, "origin"); bson_append_int(&b, "majorVersion", SAVE_VERSION); @@ -2504,7 +2493,7 @@ char * GameSave::serialiseOPS(unsigned int & dataLength) if(signs[i].text.length() && signs[i].x>=0 && signs[i].x<=fullW && signs[i].y>=0 && signs[i].y<=fullH) { bson_append_start_object(&b, "sign"); - bson_append_string(&b, "text", signs[i].text.c_str()); + bson_append_string(&b, "text", signs[i].text.ToUtf8().c_str()); bson_append_int(&b, "justification", signs[i].ju); bson_append_int(&b, "x", signs[i].x); bson_append_int(&b, "y", signs[i].y); @@ -2563,7 +2552,7 @@ void GameSave::ConvertBsonToJson(bson_iterator *iter, Json::Value *j, int depth) bson_iterator_subiterator(iter, &subiter); while (bson_iterator_next(&subiter)) { - std::string key = bson_iterator_key(&subiter); + ByteString key = bson_iterator_key(&subiter); if (bson_iterator_type(&subiter) == BSON_STRING) (*j)[key] = bson_iterator_string(&subiter); else if (bson_iterator_type(&subiter) == BSON_BOOL) @@ -2604,7 +2593,7 @@ std::set GetNestedSaveIDs(Json::Value j) std::set saveIDs = std::set(); for (Json::Value::Members::iterator iter = members.begin(), end = members.end(); iter != end; ++iter) { - std::string member = *iter; + ByteString member = *iter; if (member == "id" && j[member].isInt()) saveIDs.insert(j[member].asInt()); else if (j[member].isArray()) @@ -2633,7 +2622,7 @@ void GameSave::ConvertJsonToBson(bson *b, Json::Value j, int depth) Json::Value::Members members = j.getMemberNames(); for (Json::Value::Members::iterator iter = members.begin(), end = members.end(); iter != end; ++iter) { - std::string member = *iter; + ByteString member = *iter; if (j[member].isString()) bson_append_string(b, member.c_str(), j[member].asCString()); else if (j[member].isBool()) diff --git a/src/client/GameSave.h b/src/client/GameSave.h index 2e3fa092a..de59763ba 100644 --- a/src/client/GameSave.h +++ b/src/client/GameSave.h @@ -2,7 +2,7 @@ #define The_Powder_Toy_GameSave_h #include -#include +#include "common/String.h" #include "Config.h" #include "Misc.h" @@ -15,24 +15,24 @@ struct ParseException: public std::exception { enum ParseResult { OK = 0, Corrupt, WrongVersion, InvalidDimensions, InternalError, MissingElement }; - std::string message; + String message; ParseResult result; public: - ParseException(ParseResult result, std::string message_): message(message_), result(result) {} + ParseException(ParseResult result, String message_): message(message_), result(result) {} const char * what() const throw() { - return message.c_str(); + return message.ToUtf8().c_str(); } ~ParseException() throw() {} }; struct BuildException: public std::exception { - std::string message; + String message; public: - BuildException(std::string message_): message(message_) {} + BuildException(String message_): message(message_) {} const char * what() const throw() { - return message.c_str(); + return message.ToUtf8().c_str(); } ~BuildException() throw() {} }; @@ -104,7 +104,7 @@ public: StkmData stkm; //Element palette - typedef std::pair PaletteItem; + typedef std::pair PaletteItem; std::vector palette; // author information diff --git a/src/client/HTTP.cpp b/src/client/HTTP.cpp index 6f28a069f..afd21508b 100644 --- a/src/client/HTTP.cpp +++ b/src/client/HTTP.cpp @@ -20,8 +20,7 @@ */ -#include -#include +#include "common/String.h" #include #include #include @@ -193,11 +192,11 @@ void http_init(char *proxy) free(host); free(port); } - std::stringstream userAgentBuilder; + ByteString::Stream userAgentBuilder; userAgentBuilder << "PowderToy/" << SAVE_VERSION << "." << MINOR_VERSION << " "; userAgentBuilder << "(" << IDENT_PLATFORM << "; " << IDENT_BUILD << "; M" << MOD_ID << ") "; userAgentBuilder << "TPTPP/" << SAVE_VERSION << "." << MINOR_VERSION << "." << BUILD_NUM << IDENT_RELTYPE << "." << SNAPSHOT_ID; - std::string newUserAgent = userAgentBuilder.str(); + ByteString newUserAgent = userAgentBuilder.str(); userAgent = new char[newUserAgent.length()+1]; std::copy(newUserAgent.begin(), newUserAgent.end(), userAgent); userAgent[newUserAgent.length()] = 0; @@ -938,13 +937,13 @@ const char *http_ret_text(int ret) // Find the boundary used in the multipart POST request // the boundary is a string that never appears in any of the parts, ex. 'A92' // keeps looking recursively until it finds one -std::string FindBoundary(std::map parts, std::string boundary) +ByteString FindBoundary(std::map parts, ByteString boundary) { // we only look for a-zA-Z0-9 chars unsigned int map[62]; size_t blen = boundary.length(); std::fill(&map[0], &map[62], 0); - for (std::map::iterator iter = parts.begin(); iter != parts.end(); iter++) + for (std::map::iterator iter = parts.begin(); iter != parts.end(); iter++) { // loop through every character in each part and search for the substring, adding 1 to map for every character found (character after the substring) for (ssize_t j = 0; j < (ssize_t)((*iter).second.length()-blen); j++) @@ -986,15 +985,15 @@ std::string FindBoundary(std::map parts, std::string b // Generates a MIME multipart message to be used in POST requests // see https://en.wikipedia.org/wiki/MIME#Multipart_messages // this function used in Download class, and eventually all http requests -std::string GetMultipartMessage(std::map parts, std::string boundary) +ByteString GetMultipartMessage(std::map parts, ByteString boundary) { - std::stringstream data; + ByteString::Stream data; // loop through each part, adding it - for (std::map::iterator iter = parts.begin(); iter != parts.end(); iter++) + for (std::map::iterator iter = parts.begin(); iter != parts.end(); iter++) { - std::string name = (*iter).first; - std::string value = (*iter).second; + ByteString name = (*iter).first; + ByteString value = (*iter).second; data << "--" << boundary << "\r\n"; data << "Content-transfer-encoding: binary" << "\r\n"; @@ -1020,9 +1019,9 @@ std::string GetMultipartMessage(std::map parts, std::s } // add the header needed to make POSTS work -void http_add_multipart_header(void *ctx, std::string boundary) +void http_add_multipart_header(void *ctx, ByteString boundary) { - std::string header = "multipart/form-data; boundary=" + boundary; + ByteString header = "multipart/form-data; boundary=" + boundary; http_async_add_header(ctx, "Content-type", header.c_str()); } diff --git a/src/client/HTTP.h b/src/client/HTTP.h index 1149bd6cd..531342ad2 100644 --- a/src/client/HTTP.h +++ b/src/client/HTTP.h @@ -21,7 +21,7 @@ #define HTTP_H #include -#include +#include "common/String.h" static const char hexChars[] = "0123456789abcdef"; static const long http_timeout = 15; @@ -43,9 +43,9 @@ char *http_async_req_stop(void *ctx, int *ret, int *len); void http_async_req_close(void *ctx); void http_force_close(void *ctx); -std::string FindBoundary(std::map, std::string boundary); -std::string GetMultipartMessage(std::map, std::string boundary); -void http_add_multipart_header(void *ctx, std::string boundary); +ByteString FindBoundary(std::map, ByteString boundary); +ByteString GetMultipartMessage(std::map, ByteString boundary); +void http_add_multipart_header(void *ctx, ByteString boundary); char *http_multipart_post(const char *uri, const char *const *names, const char *const *parts, size_t *plens, const char *user, const char *pass, const char * session_id, int *ret, int *len); void *http_multipart_post_async(const char *uri, const char *const *names, const char *const *parts, int *plens, const char *user, const char *pass, const char *session_id); diff --git a/src/client/SaveFile.cpp b/src/client/SaveFile.cpp index 215d9bf88..b66861657 100644 --- a/src/client/SaveFile.cpp +++ b/src/client/SaveFile.cpp @@ -26,11 +26,11 @@ void SaveFile::SetThumbnail(Thumbnail * thumb) thumbnail = thumb; } -SaveFile::SaveFile(std::string filename): +SaveFile::SaveFile(ByteString filename): thumbnail(NULL), gameSave(NULL), filename(filename), - displayName(filename), + displayName(filename.FromUtf8()), loadingError("") { @@ -46,32 +46,32 @@ void SaveFile::SetGameSave(GameSave * save) gameSave = save; } -std::string SaveFile::GetName() +ByteString SaveFile::GetName() { return filename; } -void SaveFile::SetFileName(std::string fileName) +void SaveFile::SetFileName(ByteString fileName) { this->filename = fileName; } -std::string SaveFile::GetDisplayName() +String SaveFile::GetDisplayName() { return displayName; } -void SaveFile::SetDisplayName(std::string displayName) +void SaveFile::SetDisplayName(String displayName) { this->displayName = displayName; } -std::string SaveFile::GetError() +String SaveFile::GetError() { return loadingError; } -void SaveFile::SetLoadingError(std::string error) +void SaveFile::SetLoadingError(String error) { loadingError = error; } diff --git a/src/client/SaveFile.h b/src/client/SaveFile.h index 23d986e11..ba211ee10 100644 --- a/src/client/SaveFile.h +++ b/src/client/SaveFile.h @@ -1,7 +1,7 @@ #ifndef SAVEFILE_H_ #define SAVEFILE_H_ -#include +#include "common/String.h" class GameSave; class Thumbnail; @@ -9,26 +9,26 @@ class Thumbnail; class SaveFile { public: SaveFile(SaveFile & save); - SaveFile(std::string filename); + SaveFile(ByteString filename); Thumbnail * GetThumbnail(); GameSave * GetGameSave(); void SetThumbnail(Thumbnail * thumb); void SetGameSave(GameSave * save); - std::string GetDisplayName(); - void SetDisplayName(std::string displayName); - std::string GetName(); - void SetFileName(std::string fileName); - std::string GetError(); - void SetLoadingError(std::string error); + String GetDisplayName(); + void SetDisplayName(String displayName); + ByteString GetName(); + void SetFileName(ByteString fileName); + String GetError(); + void SetLoadingError(String error); virtual ~SaveFile(); private: Thumbnail * thumbnail; GameSave * gameSave; - std::string filename; - std::string displayName; - std::string loadingError; + ByteString filename; + String displayName; + String loadingError; }; #endif /* SAVEFILE_H_ */ diff --git a/src/client/SaveInfo.cpp b/src/client/SaveInfo.cpp index 97ba49464..83c35a960 100644 --- a/src/client/SaveInfo.cpp +++ b/src/client/SaveInfo.cpp @@ -19,14 +19,14 @@ SaveInfo::SaveInfo(SaveInfo & save): Published(save.Published), gameSave(NULL) { - std::list tagsSorted = save.tags; + std::list tagsSorted = save.tags; tagsSorted.sort(); tags = tagsSorted; if (save.gameSave) gameSave = new GameSave(*save.gameSave); } -SaveInfo::SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, std::string _userName, std::string _name): +SaveInfo::SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, ByteString _userName, String _name): id(_id), createdDate(_createdDate), updatedDate(_updatedDate), @@ -47,7 +47,7 @@ SaveInfo::SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, in } -SaveInfo::SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, int _vote, std::string _userName, std::string _name, std::string description_, bool published_, std::list tags_): +SaveInfo::SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, int _vote, ByteString _userName, String _name, String description_, bool published_, std::list tags_): id(_id), createdDate(_createdDate), updatedDate(_updatedDate), @@ -65,7 +65,7 @@ SaveInfo::SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, in tags(), gameSave(NULL) { - std::list tagsSorted = tags_; + std::list tagsSorted = tags_; tagsSorted.sort(); tags=tagsSorted; } @@ -78,20 +78,20 @@ SaveInfo::~SaveInfo() } } -void SaveInfo::SetName(std::string name) +void SaveInfo::SetName(String name) { this->name = name; } -std::string SaveInfo::GetName() +String SaveInfo::GetName() { return name; } -void SaveInfo::SetDescription(std::string description) +void SaveInfo::SetDescription(String description) { Description = description; } -std::string SaveInfo::GetDescription() +String SaveInfo::GetDescription() { return Description; } @@ -114,12 +114,12 @@ int SaveInfo::GetVote() return vote; } -void SaveInfo::SetUserName(std::string userName) +void SaveInfo::SetUserName(ByteString userName) { this->userName = userName; } -std::string SaveInfo::GetUserName() +ByteString SaveInfo::GetUserName() { return userName; } @@ -160,14 +160,14 @@ int SaveInfo::GetVersion() return Version; } -void SaveInfo::SetTags(std::list tags) +void SaveInfo::SetTags(std::list tags) { - std::list tagsSorted = tags; + std::list tagsSorted = tags; tagsSorted.sort(); this->tags=tagsSorted; } -std::list SaveInfo::GetTags() +std::list SaveInfo::GetTags() { return tags; } diff --git a/src/client/SaveInfo.h b/src/client/SaveInfo.h index e366858c8..18f75932d 100644 --- a/src/client/SaveInfo.h +++ b/src/client/SaveInfo.h @@ -3,7 +3,7 @@ #include #include -#include +#include "common/String.h" #include #include @@ -23,34 +23,34 @@ public: int Views; int Version; - std::string userName; + ByteString userName; - std::string name; - std::string Description; + String name; + String Description; bool Published; - std::list tags; + std::list tags; GameSave * gameSave; SaveInfo(SaveInfo & save); - SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, std::string _userName, std::string _name); + SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, ByteString _userName, String _name); - SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, int _vote, std::string _userName, std::string _name, std::string description_, bool published_, std::list tags); + SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, int _vote, ByteString _userName, String _name, String description_, bool published_, std::list tags); ~SaveInfo(); - void SetName(std::string name); - std::string GetName(); + void SetName(String name); + String GetName(); - void SetDescription(std::string description); - std::string GetDescription(); + void SetDescription(String description); + String GetDescription(); void SetPublished(bool published); bool GetPublished(); - void SetUserName(std::string userName); - std::string GetUserName(); + void SetUserName(ByteString userName); + ByteString GetUserName(); void SetID(int id); int GetID(); @@ -67,8 +67,8 @@ public: void SetVersion(int version); int GetVersion(); - void SetTags(std::list tags); - std::list GetTags(); + void SetTags(std::list tags); + std::list GetTags(); GameSave * GetGameSave(); void SetGameSave(GameSave * gameSave); diff --git a/src/client/User.h b/src/client/User.h index 3bc8f926c..3d9aab469 100644 --- a/src/client/User.h +++ b/src/client/User.h @@ -1,7 +1,7 @@ #ifndef USER_H_ #define USER_H_ -#include +#include "common/String.h" class User @@ -12,11 +12,11 @@ public: ElevationAdmin, ElevationModerator, ElevationNone }; int UserID; - std::string Username; - std::string SessionID; - std::string SessionKey; + ByteString Username; + ByteString SessionID; + ByteString SessionKey; Elevation UserElevation; - User(int id, std::string username): + User(int id, ByteString username): UserID(id), Username(username), SessionID(""), diff --git a/src/client/UserInfo.h b/src/client/UserInfo.h index 0c808a7a4..080f95136 100644 --- a/src/client/UserInfo.h +++ b/src/client/UserInfo.h @@ -1,17 +1,17 @@ #ifndef USERINFO_H_ #define USERINFO_H_ -#include +#include "common/String.h" class UserInfo { public: int UserID; int age; - std::string username; - std::string biography; - std::string location; - std::string website; + ByteString username; + String biography; + String location; + ByteString website; int saveCount; float averageScore; @@ -21,7 +21,7 @@ public: int topicReplies; int reputation; - UserInfo(int id, int age, std::string username, std::string biography, std::string location, std::string website, int saveCount, float averageScore, int highestScore, int topicCount, int topicReplies, int reputation): + UserInfo(int id, int age, ByteString username, String biography, String location, ByteString website, int saveCount, float averageScore, int highestScore, int topicCount, int topicReplies, int reputation): UserID(id), age(age), username(username), diff --git a/src/client/requestbroker/APIRequest.cpp b/src/client/requestbroker/APIRequest.cpp index 2103ade34..dcd2e143a 100644 --- a/src/client/requestbroker/APIRequest.cpp +++ b/src/client/requestbroker/APIRequest.cpp @@ -9,7 +9,7 @@ #include "client/HTTP.h" #include "APIResultParser.h" -APIRequest::APIRequest(std::string url, APIResultParser * parser, ListenerHandle listener, int identifier): +APIRequest::APIRequest(ByteString url, APIResultParser * parser, ListenerHandle listener, int identifier): RequestBroker::Request(API, listener, identifier) { Post = false; @@ -18,7 +18,7 @@ APIRequest::APIRequest(std::string url, APIResultParser * parser, ListenerHandle URL = url; } -APIRequest::APIRequest(std::string url, std::map postData, APIResultParser * parser, ListenerHandle listener, int identifier): +APIRequest::APIRequest(ByteString url, std::map postData, APIResultParser * parser, ListenerHandle listener, int identifier): RequestBroker::Request(API, listener, identifier) { Post = true; @@ -81,11 +81,11 @@ RequestBroker::ProcessResponse APIRequest::Process(RequestBroker & rb) int * postLength = new int[PostData.size()]; int i = 0; - std::map::iterator iter = PostData.begin(); + std::map::iterator iter = PostData.begin(); while(iter != PostData.end()) { - std::string name = iter->first; - std::string data = iter->second; + ByteString name = iter->first; + ByteString data = iter->second; char * cName = new char[name.length() + 1]; char * cData = new char[data.length() + 1]; std::strcpy(cName, name.c_str()); @@ -103,7 +103,7 @@ RequestBroker::ProcessResponse APIRequest::Process(RequestBroker & rb) User user = Client::Ref().GetAuthUser(); char userName[12]; char *userSession = new char[user.SessionID.length() + 1]; - std::strcpy(userName, format::NumberToString(user.UserID).c_str()); + std::strcpy(userName, format::NumberToByteString(user.UserID).c_str()); std::strcpy(userSession, user.SessionID.c_str()); HTTPContext = http_multipart_post_async((char*)URL.c_str(), postNames, postData, postLength, userName, NULL, userSession); delete[] userSession; @@ -122,7 +122,7 @@ RequestBroker::ProcessResponse APIRequest::Process(RequestBroker & rb) User user = Client::Ref().GetAuthUser(); char userName[12]; char *userSession = new char[user.SessionID.length() + 1]; - std::strcpy(userName, format::NumberToString(user.UserID).c_str()); + std::strcpy(userName, format::NumberToByteString(user.UserID).c_str()); std::strcpy(userSession, user.SessionID.c_str()); http_auth_headers(HTTPContext, userName, NULL, userSession); delete[] userSession; diff --git a/src/client/requestbroker/APIRequest.h b/src/client/requestbroker/APIRequest.h index b555d61f4..cebfe1c99 100644 --- a/src/client/requestbroker/APIRequest.h +++ b/src/client/requestbroker/APIRequest.h @@ -7,11 +7,11 @@ class APIRequest: public RequestBroker::Request public: bool Post; APIResultParser * Parser; - std::string URL; - std::map PostData; + ByteString URL; + std::map PostData; void * HTTPContext; - APIRequest(std::string url, APIResultParser * parser, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); - APIRequest(std::string url, std::map, APIResultParser * parser, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); + APIRequest(ByteString url, APIResultParser * parser, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); + APIRequest(ByteString url, std::map, APIResultParser * parser, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); virtual RequestBroker::ProcessResponse Process(RequestBroker & rb); virtual ~APIRequest(); virtual void Cleanup(); diff --git a/src/client/requestbroker/ImageRequest.cpp b/src/client/requestbroker/ImageRequest.cpp index 482e0346c..b8a3a7f5e 100644 --- a/src/client/requestbroker/ImageRequest.cpp +++ b/src/client/requestbroker/ImageRequest.cpp @@ -5,7 +5,7 @@ #include "graphics/Graphics.h" #include "client/HTTP.h" -ImageRequest::ImageRequest(std::string url, int width, int height, ListenerHandle listener, int identifier): +ImageRequest::ImageRequest(ByteString url, int width, int height, ListenerHandle listener, int identifier): Request(Image, listener, identifier) { URL = url; @@ -24,7 +24,7 @@ RequestBroker::ProcessResponse ImageRequest::Process(RequestBroker & rb) VideoBuffer * image = NULL; //Have a look at the thumbnail cache - for(std::deque >::iterator iter = rb.imageCache.begin(), end = rb.imageCache.end(); iter != end; ++iter) + for(std::deque >::iterator iter = rb.imageCache.begin(), end = rb.imageCache.end(); iter != end; ++iter) { if((*iter).first == URL) { @@ -71,7 +71,7 @@ RequestBroker::ProcessResponse ImageRequest::Process(RequestBroker & rb) delete rb.imageCache.front().second; rb.imageCache.pop_front(); } - rb.imageCache.push_back(std::pair(URL, image)); + rb.imageCache.push_back(std::pair(URL, image)); } else { diff --git a/src/client/requestbroker/ImageRequest.h b/src/client/requestbroker/ImageRequest.h index 22a7342c3..c900a1c22 100644 --- a/src/client/requestbroker/ImageRequest.h +++ b/src/client/requestbroker/ImageRequest.h @@ -4,11 +4,11 @@ class ImageRequest: public RequestBroker::Request { public: int Width, Height; - std::string URL; + ByteString URL; int RequestTime; void * HTTPContext; bool started = false; - ImageRequest(std::string url, int width, int height, ListenerHandle listener, int identifier = 0); + ImageRequest(ByteString url, int width, int height, ListenerHandle listener, int identifier = 0); virtual RequestBroker::ProcessResponse Process(RequestBroker & rb); virtual ~ImageRequest(); virtual void Cleanup(); diff --git a/src/client/requestbroker/RequestBroker.cpp b/src/client/requestbroker/RequestBroker.cpp index 7c59dbb05..b3395e78e 100644 --- a/src/client/requestbroker/RequestBroker.cpp +++ b/src/client/requestbroker/RequestBroker.cpp @@ -1,7 +1,6 @@ #include #include #include -#include #include #include "RequestBroker.h" #include "RequestListener.h" @@ -35,7 +34,7 @@ RequestBroker::RequestBroker() RequestBroker::~RequestBroker() { - for(std::deque >::iterator iter = imageCache.begin(), end = imageCache.end(); iter != end; ++iter) + for(std::deque >::iterator iter = imageCache.begin(), end = imageCache.end(); iter != end; ++iter) { delete (*iter).second; } @@ -98,7 +97,7 @@ void RequestBroker::RenderThumbnail(GameSave * gameSave, bool decorations, bool void RequestBroker::RetrieveThumbnail(int saveID, int saveDate, int width, int height, RequestListener * tListener) { - std::stringstream urlStream; + ByteString::Stream urlStream; urlStream << "http://" << STATICSERVER << "/" << saveID; if(saveDate) { @@ -109,9 +108,9 @@ void RequestBroker::RetrieveThumbnail(int saveID, int saveDate, int width, int h RetrieveImage(urlStream.str(), width, height, tListener); } -void RequestBroker::RetrieveAvatar(std::string username, int width, int height, RequestListener * tListener) +void RequestBroker::RetrieveAvatar(ByteString username, int width, int height, RequestListener * tListener) { - std::stringstream urlStream; + ByteString::Stream urlStream; urlStream << "http://" << STATICSERVER << "/avatars/" << username << ".pti"; RetrieveImage(urlStream.str(), width, height, tListener); @@ -130,7 +129,7 @@ void RequestBroker::Start(Request * request, RequestListener * tListener, int id assureRunning(); } -void RequestBroker::RetrieveImage(std::string imageUrl, int width, int height, RequestListener * tListener) +void RequestBroker::RetrieveImage(ByteString imageUrl, int width, int height, RequestListener * tListener) { ListenerHandle handle = AttachRequestListener(tListener); diff --git a/src/client/requestbroker/RequestBroker.h b/src/client/requestbroker/RequestBroker.h index 23fd381eb..6cee30852 100644 --- a/src/client/requestbroker/RequestBroker.h +++ b/src/client/requestbroker/RequestBroker.h @@ -3,7 +3,7 @@ #include #include #include -#include +#include "common/String.h" #include "common/tpt-thread.h" #include "Config.h" @@ -33,7 +33,7 @@ private: std::vector validListeners; - std::deque > imageCache; + std::deque > imageCache; std::queue completeQueue; std::vector requestQueue; @@ -51,12 +51,12 @@ public: void Shutdown(); void FlushThumbQueue(); - void RetrieveImage(std::string imageUrl, int width, int height, RequestListener * tListener); + void RetrieveImage(ByteString imageUrl, int width, int height, RequestListener * tListener); void RenderThumbnail(GameSave * gameSave, bool decorations, bool fire, int width, int height, RequestListener * tListener); void RenderThumbnail(GameSave * gameSave, int width, int height, RequestListener * tListener); void RetrieveThumbnail(int saveID, int saveDate, int width, int height, RequestListener * tListener); void RetrieveThumbnail(int saveID, int width, int height, RequestListener * tListener); - void RetrieveAvatar(std::string username, int width, int height, RequestListener * tListener); + void RetrieveAvatar(ByteString username, int width, int height, RequestListener * tListener); void Start(Request * request, RequestListener * tLIstener, int identifier = 0); bool CheckRequestListener(ListenerHandle handle); diff --git a/src/client/requestbroker/WebRequest.cpp b/src/client/requestbroker/WebRequest.cpp index 62e96dcb3..bd8b99ea9 100644 --- a/src/client/requestbroker/WebRequest.cpp +++ b/src/client/requestbroker/WebRequest.cpp @@ -10,7 +10,7 @@ #include "client/HTTP.h" #include "APIResultParser.h" -WebRequest::WebRequest(std::string url, ListenerHandle listener, int identifier): +WebRequest::WebRequest(ByteString url, ListenerHandle listener, int identifier): RequestBroker::Request(API, listener, identifier) { Post = false; @@ -18,7 +18,7 @@ WebRequest::WebRequest(std::string url, ListenerHandle listener, int identifier) URL = url; } -WebRequest::WebRequest(std::string url, std::map postData, ListenerHandle listener, int identifier): +WebRequest::WebRequest(ByteString url, std::map postData, ListenerHandle listener, int identifier): RequestBroker::Request(API, listener, identifier) { Post = true; @@ -81,11 +81,11 @@ RequestBroker::ProcessResponse WebRequest::Process(RequestBroker & rb) int * postLength = new int[PostData.size()]; int i = 0; - std::map::iterator iter = PostData.begin(); + std::map::iterator iter = PostData.begin(); while(iter != PostData.end()) { - std::string name = iter->first; - std::string data = iter->second; + ByteString name = iter->first; + ByteString data = iter->second; char * cName = new char[name.length() + 1]; char * cData = new char[data.length() + 1]; std::strcpy(cName, name.c_str()); @@ -106,7 +106,7 @@ RequestBroker::ProcessResponse WebRequest::Process(RequestBroker & rb) User user = Client::Ref().GetAuthUser(); char userName[12]; char *userSession = new char[user.SessionID.length() + 1]; - std::strcpy(userName, format::NumberToString(user.UserID).c_str()); + std::strcpy(userName, format::NumberToByteString(user.UserID).c_str()); std::strcpy(userSession, user.SessionID.c_str()); HTTPContext = http_multipart_post_async((char*)URL.c_str(), postNames, postData, postLength, userName, NULL, userSession); delete[] userSession; @@ -125,7 +125,7 @@ RequestBroker::ProcessResponse WebRequest::Process(RequestBroker & rb) User user = Client::Ref().GetAuthUser(); char userName[12]; char *userSession = new char[user.SessionID.length() + 1]; - std::strcpy(userName, format::NumberToString(user.UserID).c_str()); + std::strcpy(userName, format::NumberToByteString(user.UserID).c_str()); std::strcpy(userSession, user.SessionID.c_str()); http_auth_headers(HTTPContext, userName, NULL, userSession); delete[] userSession; diff --git a/src/client/requestbroker/WebRequest.h b/src/client/requestbroker/WebRequest.h index 255b060e7..a0568220a 100644 --- a/src/client/requestbroker/WebRequest.h +++ b/src/client/requestbroker/WebRequest.h @@ -5,11 +5,11 @@ class WebRequest: public RequestBroker::Request { public: bool Post; - std::string URL; - std::map PostData; + ByteString URL; + std::map PostData; void * HTTPContext; - WebRequest(std::string url, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); - WebRequest(std::string url, std::map, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); + WebRequest(ByteString url, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); + WebRequest(ByteString url, std::map, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); virtual RequestBroker::ProcessResponse Process(RequestBroker & rb); virtual ~WebRequest(); virtual void Cleanup(); diff --git a/src/common/String.cpp b/src/common/String.cpp index 0dc4a3426..a197d17a6 100644 --- a/src/common/String.cpp +++ b/src/common/String.cpp @@ -87,3 +87,135 @@ ByteString String::ToUtf8() const } } } + +template<> std::ctype::~ctype() +{ +} +template<> std::numpunct::numpunct(size_t ref): std::locale::facet(ref) +{ +} +template<> std::numpunct::~numpunct() +{ +} + +static struct Locale32Impl +{ + std::ctype const &ctype16; + std::numpunct const &numpunct16; + Locale32Impl(): + ctype16(std::use_facet >(std::locale())), + numpunct16(std::use_facet >(std::locale())) + { + std::locale::global(std::locale(std::locale(), new std::ctype())); + std::locale::global(std::locale(std::locale(), new std::numpunct())); + std::locale::global(std::locale(std::locale(), new std::num_put())); + } +} +Locale32Impl; + +template<> bool std::ctype::do_is(mask m, char32_t ch) const +{ + return ch <= 0xFFFF ? Locale32Impl.ctype16.is(m, ch) : (m & print); +} +template<> char32_t const *std::ctype::do_is(char32_t const *low, char32_t const *high, mask *vec) const +{ + while(low < high) + { + if(*low <= 0xFFFF) + { + wchar_t l = *low; + Locale32Impl.ctype16.is(&l, &l + 1, vec); + } + else + *vec = print; + low++; + } + return high; +} +template<> char32_t const *std::ctype::do_scan_is(mask m, char32_t const *beg, char32_t const *end) const +{ + while(beg < end) + if(do_is(m, *beg)) + return beg; + else + beg++; + return end; +} +template<> char32_t const *std::ctype::do_scan_not(mask m, char32_t const *beg, char32_t const *end) const +{ + while(beg < end) + if(!do_is(m, *beg)) + return beg; + else + beg++; + return end; +} +template<> char32_t std::ctype::do_toupper(char32_t ch) const +{ + return ch <= 0xFFFF ? Locale32Impl.ctype16.toupper(ch) : ch; +} +template<> char32_t const *std::ctype::do_toupper(char32_t *beg, char32_t const *end) const +{ + while(beg < end) + { + *beg = do_toupper(*beg); + beg++; + } + return end; +} +template<> char32_t std::ctype::do_tolower(char32_t ch) const +{ + return ch <= 0xFFFF ? Locale32Impl.ctype16.tolower(ch) : ch; +} +template<> char32_t const *std::ctype::do_tolower(char32_t *beg, char32_t const *end) const +{ + while(beg < end) + { + *beg = do_tolower(*beg); + beg++; + } + return end; +} +template<> char32_t std::ctype::do_widen(char ch) const +{ + return Locale32Impl.ctype16.widen(ch); +} +template<> char const *std::ctype::do_widen(char const *beg, char const *end, char32_t *dst) const +{ + while(beg < end) + *(dst++) = do_widen(*(beg++)); + return end; +} +template<> char std::ctype::do_narrow(char32_t ch, char dflt) const +{ + return ch <= 0xFFFF ? Locale32Impl.ctype16.narrow(ch, dflt) : dflt; +} +template<> char32_t const *std::ctype::do_narrow(char32_t const *beg, char32_t const *end, char dflt, char *dst) const +{ + while(beg < end) + *(dst++) = do_narrow(*(beg++), dflt); + return end; +} + +template<> char32_t std::numpunct::do_decimal_point() const +{ + return Locale32Impl.numpunct16.decimal_point(); +} +template<> char32_t std::numpunct::do_thousands_sep() const +{ + return Locale32Impl.numpunct16.thousands_sep(); +} +template<> std::string std::numpunct::do_grouping() const +{ + return Locale32Impl.numpunct16.grouping(); +} +template<> std::basic_string std::numpunct::do_truename() const +{ + std::basic_string name = Locale32Impl.numpunct16.truename(); + return std::basic_string(name.begin(), name.end()); +} +template<> std::basic_string std::numpunct::do_falsename() const +{ + std::basic_string name = Locale32Impl.numpunct16.falsename(); + return std::basic_string(name.begin(), name.end()); +} diff --git a/src/common/String.h b/src/common/String.h index 2d452eae3..0da29b864 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -1,6 +1,8 @@ #ifndef TPT_STRING #define TPT_STRING +#include +#include #include class String; @@ -13,11 +15,18 @@ public: inline ByteString(value_type const *ch, size_type count): std::basic_string(ch, count) {} inline ByteString(value_type const *ch): std::basic_string(ch) {} template inline ByteString(It first, It last): std::basic_string(first, last) {} + inline ByteString(std::basic_string const &other): std::basic_string(other) {} + inline ByteString(std::basic_string &&other): std::basic_string(std::move(other)) {} inline ByteString(ByteString const &other): std::basic_string(other) {} inline ByteString(ByteString &&other): std::basic_string(std::move(other)) {} - ByteString &operator=(ByteString const &other) { std::basic_string::operator=(other); return *this; } - ByteString &operator=(ByteString &&other) { std::basic_string::operator=(std::move(other)); return *this; } + inline ByteString &operator=(ByteString const &other) { std::basic_string::operator=(other); return *this; } + inline ByteString &operator=(ByteString &&other) { std::basic_string::operator=(std::move(other)); return *this; } + + template ByteString &operator+=(T &&other) { std::basic_string::operator+=(std::forward(other)); return *this; } + template inline ByteString operator+(T &&other) const { ByteString tmp = *this; tmp += std::forward(other); return tmp; } + template ByteString substr(Ts&&... args) const { return std::basic_string::substr(std::forward(args)...); } + template ByteString &insert(Ts&&... args) { std::basic_string::insert(std::forward(args)...); return *this; } class ConversionError : public std::runtime_error { @@ -29,8 +38,14 @@ public: String FromUtf8(bool ignoreError = true) const; inline String FromAscii() const; + + using Stream = std::basic_stringstream; }; +inline ByteString operator+(ByteString::value_type const *ch, ByteString const &str) { return ByteString(ch) + str; } +inline ByteString operator+(std::basic_string const &other, ByteString const &str) { return ByteString(other) + str; } +inline ByteString operator+(std::basic_string &&other, ByteString const &str) { return ByteString(std::move(other)) + str; } + class String : public std::basic_string { public: @@ -39,22 +54,52 @@ public: inline String(value_type const *ch, size_type count): std::basic_string(ch, count) {} inline String(value_type const *ch): std::basic_string(ch) {} template inline String(It first, It last): std::basic_string(first, last) {} + inline String(std::basic_string const &other): std::basic_string(other) {} + inline String(std::basic_string &&other): std::basic_string(std::move(other)) {} inline String(String const &other): std::basic_string(other) {} inline String(String &&other): std::basic_string(std::move(other)) {} + template inline String(ByteString::value_type const (&ch)[N]): std::basic_string(ByteString(ch, N - 1).FromAscii()) {} - String &operator=(String const &other) { std::basic_string::operator=(other); return *this; } - String &operator=(String &&other) { std::basic_string::operator=(std::move(other)); return *this; } + inline String &operator=(String const &other) { std::basic_string::operator=(other); return *this; } + inline String &operator=(String &&other) { std::basic_string::operator=(other); return *this; } + + template inline String &operator+=(T &&other) { std::basic_string::operator+=(std::forward(other)); return *this; } + template inline String &operator+=(ByteString::value_type const (&ch)[N]) { std::basic_string::operator+=(ByteString(ch, N - 1).FromAscii()); return *this; } + template inline String operator+(T &&other) const { String tmp = *this; tmp += std::forward(other); return tmp; } + template inline String substr(Ts&&... args) const { return std::basic_string::substr(std::forward(args)...); } + inline String &insert(size_t pos, String &str) { std::basic_string::insert(pos, str); return *this; } + inline String &insert(size_t pos, size_t n, value_type ch) { std::basic_string::insert(pos, n, ch); return *this; } + template inline String &insert(size_t pos, ByteString::value_type const (&ch)[N]) { std::basic_string::insert(pos, ByteString(ch, N - 1).FromAscii()); return *this; } + inline size_t find(String const &str, size_t pos = 0) { return std::basic_string::find(str, pos); } + inline size_t find(value_type ch, size_t pos = 0) { return std::basic_string::find(ch, pos); } - template inline String(ByteString::value_type const (&ch)[N]): std::basic_string(ByteString(ch, N).FromAscii()) {} + inline bool operator==(String const &other) { return std::basic_string(*this) == other; } ByteString ToUtf8() const; + ByteString ToAscii() const; + + using Stream = std::basic_stringstream; }; +inline String operator+(String::value_type const *ch, String const &str) { return String(ch) + str; } +inline String operator+(std::basic_string const &other, String const &str) { return String(other) + str; } +inline String operator+(std::basic_string &&other, String const &str) { return String(std::move(other)) + str; } +template inline String operator+(ByteString::value_type const (&ch)[N], String const &str) { return String(ch) + str; } + + inline String ByteString::FromAscii() const { String destination = String(size(), String::value_type()); for(size_t i = 0; i < size(); i++) - destination[i] = typename String::value_type(operator[](i)); + destination[i] = String::value_type(std::make_unsigned::type(operator[](i))); + return destination; +} + +inline ByteString String::ToAscii() const +{ + ByteString destination = ByteString(size(), ByteString::value_type()); + for(size_t i = 0; i < size(); i++) + destination[i] = ByteString::value_type(operator[](i)); return destination; } #endif diff --git a/src/debug/DebugLines.cpp b/src/debug/DebugLines.cpp index 69992dc66..5a42928a1 100644 --- a/src/debug/DebugLines.cpp +++ b/src/debug/DebugLines.cpp @@ -27,21 +27,21 @@ void DebugLines::Draw() g->draw_line(0, drawPoint2.Y, XRES, drawPoint2.Y, 255, 255, 255, 120); g->draw_line(drawPoint2.X, 0, drawPoint2.X, YRES, 255, 255, 255, 120); - std::stringstream info; + String::Stream info; info << drawPoint2.X << " x " << drawPoint2.Y; - g->drawtext_outline(drawPoint2.X+(drawPoint2.X>drawPoint1.X?3:-g->textwidth(info.str().c_str())-3), drawPoint2.Y+(drawPoint2.Ydrawtext_outline(drawPoint2.X+(drawPoint2.X>drawPoint1.X?3:-g->textwidth(info.str())-3), drawPoint2.Y+(drawPoint2.Ydrawtext_outline(drawPoint1.X+(drawPoint2.Xtextwidth(info.str().c_str())-2), drawPoint1.Y+(drawPoint2.Y>drawPoint1.Y?-10:3), info.str().c_str(), 255, 255, 255, 200); + g->drawtext_outline(drawPoint1.X+(drawPoint2.Xtextwidth(info.str())-2), drawPoint1.Y+(drawPoint2.Y>drawPoint1.Y?-10:3), info.str(), 255, 255, 255, 200); - info.str(""); + info.str(String()); info << std::abs(drawPoint2.X-drawPoint1.X); - g->drawtext_outline((drawPoint1.X+drawPoint2.X)/2-g->textwidth(info.str().c_str())/2, drawPoint1.Y+(drawPoint2.Y>drawPoint1.Y?-10:3), info.str().c_str(), 255, 255, 255, 200); + g->drawtext_outline((drawPoint1.X+drawPoint2.X)/2-g->textwidth(info.str())/2, drawPoint1.Y+(drawPoint2.Y>drawPoint1.Y?-10:3), info.str(), 255, 255, 255, 200); - info.str(""); + info.str(String()); info << std::abs(drawPoint2.Y-drawPoint1.Y); - g->drawtext_outline(drawPoint1.X+(drawPoint2.Xtextwidth(info.str().c_str())-2), (drawPoint1.Y+drawPoint2.Y)/2-3, info.str().c_str(), 255, 255, 255, 200); + g->drawtext_outline(drawPoint1.X+(drawPoint2.Xtextwidth(info.str())-2), (drawPoint1.Y+drawPoint2.Y)/2-3, info.str(), 255, 255, 255, 200); } } diff --git a/src/debug/DebugParts.cpp b/src/debug/DebugParts.cpp index fd14ddd2c..9c2ef55d2 100644 --- a/src/debug/DebugParts.cpp +++ b/src/debug/DebugParts.cpp @@ -1,5 +1,4 @@ #include -#include #include "DebugParts.h" #include "gui/interface/Engine.h" #include "simulation/Simulation.h" @@ -16,7 +15,7 @@ void DebugParts::Draw() Graphics * g = ui::Engine::Ref().g; int x = 0, y = 0, lpx = 0, lpy = 0; - std::stringstream info; + String::Stream info; info << sim->parts_lastActiveIndex << "/" << NPART << " (" << std::fixed << std::setprecision(2) << (float)sim->parts_lastActiveIndex/(NPART)*100.0f << "%)"; for (int i = 0; i < NPART; i++) { @@ -46,8 +45,8 @@ void DebugParts::Draw() g->addpixel(lpx, lpy+1, 255, 50, 50, 120); g->addpixel(lpx, lpy-1, 255, 50, 50, 120); - g->fillrect(7, YRES-26, g->textwidth(info.str().c_str())+5, 14, 0, 0, 0, 180); - g->drawtext(10, YRES-22, info.str().c_str(), 255, 255, 255, 255); + g->fillrect(7, YRES-26, g->textwidth(info.str())+5, 14, 0, 0, 0, 180); + g->drawtext(10, YRES-22, info.str(), 255, 255, 255, 255); } DebugParts::~DebugParts() diff --git a/src/debug/ElementPopulation.cpp b/src/debug/ElementPopulation.cpp index f2cbfb05d..3de462a11 100644 --- a/src/debug/ElementPopulation.cpp +++ b/src/debug/ElementPopulation.cpp @@ -18,8 +18,8 @@ void ElementPopulationDebug::Draw() int yBottom = YRES-10; int xStart = 10; - std::string maxValString; - std::string halfValString; + String maxValString; + String halfValString; float maxVal = 255; @@ -41,7 +41,7 @@ void ElementPopulationDebug::Draw() halfValString = format::NumberToString(maxAverage/2); - g->fillrect(xStart-5, yBottom - 263, bars+10+Graphics::textwidth(maxValString.c_str())+10, 255 + 13, 0, 0, 0, 180); + g->fillrect(xStart-5, yBottom - 263, bars+10+Graphics::textwidth(maxValString)+10, 255 + 13, 0, 0, 0, 180); bars = 0; for(int i = 0; i < PT_NUM; i++) diff --git a/src/debug/ParticleDebug.cpp b/src/debug/ParticleDebug.cpp index c838cc64d..a9fd3ebfe 100644 --- a/src/debug/ParticleDebug.cpp +++ b/src/debug/ParticleDebug.cpp @@ -1,4 +1,3 @@ -#include #include "ParticleDebug.h" #include "gui/interface/Engine.h" #include "gui/game/GameView.h" @@ -16,7 +15,7 @@ void ParticleDebug::Debug(int mode, int x, int y) { int debug_currentParticle = sim->debug_currentParticle; int i = 0; - std::stringstream logmessage; + String::Stream logmessage; if (mode == 0) { @@ -90,7 +89,7 @@ bool ParticleDebug::KeyPress(int key, Uint16 character, bool shift, bool ctrl, b { sim->UpdateParticles(sim->debug_currentParticle, NPART); sim->AfterSim(); - std::stringstream logmessage; + String::Stream logmessage; logmessage << "Updated particles from #" << sim->debug_currentParticle << " to end, updated sim"; model->Log(logmessage.str(), false); sim->debug_currentParticle = 0; diff --git a/src/graphics/DrawMethodsDef.inc b/src/graphics/DrawMethodsDef.inc index 31fbb6869..663f4bbe0 100644 --- a/src/graphics/DrawMethodsDef.inc +++ b/src/graphics/DrawMethodsDef.inc @@ -1,7 +1,6 @@ - int drawtext(int x, int y, const char *s, int r, int g, int b, int a); - int drawtext(int x, int y, std::string s, int r, int g, int b, int a); - int drawchar(int x, int y, int c, int r, int g, int b, int a); - int addchar(int x, int y, int c, int r, int g, int b, int a); + int drawtext(int x, int y, String s, int r, int g, int b, int a); + int drawchar(int x, int y, String::value_type c, int r, int g, int b, int a); + int addchar(int x, int y, String::value_type c, int r, int g, int b, int a); void xor_pixel(int x, int y); void xor_line(int x, int y, int x2, int y2); diff --git a/src/graphics/Graphics.cpp b/src/graphics/Graphics.cpp index f16b8a347..3e86925ea 100644 --- a/src/graphics/Graphics.cpp +++ b/src/graphics/Graphics.cpp @@ -1,7 +1,7 @@ #include #include #include -#include +#include "common/String.h" #include "Config.h" #include "Misc.h" #include "Graphics.h" @@ -566,9 +566,10 @@ pixel *Graphics::rescale_img(pixel *src, int sw, int sh, int *qw, int *qh, int f return q; } -int Graphics::textwidth(const char *s) +int Graphics::textwidth(String str) { int x = 0; + String::value_type const *s = str.c_str(); for (; *s; s++) { if(((char)*s)=='\b') @@ -581,19 +582,20 @@ int Graphics::textwidth(const char *s) s+=3; continue; } - x += font_data[font_ptrs[(int)(*(unsigned char *)s)]]; + x += font_data[font_ptrs[*s]]; } return x-1; } -int Graphics::CharWidth(unsigned char c) +int Graphics::CharWidth(String::value_type c) { return font_data[font_ptrs[(int)c]]; } -int Graphics::textnwidth(char *s, int n) +int Graphics::textnwidth(String str, int n) { int x = 0; + String::value_type const *s = str.c_str(); for (; *s; s++) { if (!n) @@ -608,20 +610,23 @@ int Graphics::textnwidth(char *s, int n) s+=3; continue; } - x += font_data[font_ptrs[(int)(*(unsigned char *)s)]]; + x += font_data[font_ptrs[*s]]; n--; } return x-1; } -void Graphics::textnpos(char *s, int n, int w, int *cx, int *cy) +void Graphics::textnpos(String str, int n, int w, int *cx, int *cy) { int x = 0; int y = 0; int wordlen, charspace; + String::value_type const *s = str.c_str(); while (*s&&n) { - wordlen = strcspn(s," .,!?\n"); + wordlen = 0; + while(*s && String(" .,!?\n").find(*s) != String::npos) + s++; charspace = textwidthx(s, w-x); if (charspace=w) { x = 0; @@ -646,9 +651,10 @@ void Graphics::textnpos(char *s, int n, int w, int *cx, int *cy) *cy = y; } -int Graphics::textwidthx(char *s, int w) +int Graphics::textwidthx(String str, int w) { int x=0,n=0,cw; + String::value_type const *s = str.c_str(); for (; *s; s++) { if((char)*s == '\b') @@ -662,7 +668,7 @@ int Graphics::textwidthx(char *s, int w) s+=3; continue; } - cw = font_data[font_ptrs[(int)(*(unsigned char *)s)]]; + cw = font_data[font_ptrs[*s]]; if (x+(cw/2) >= w) break; x += cw; @@ -671,9 +677,10 @@ int Graphics::textwidthx(char *s, int w) return n; } -int Graphics::PositionAtCharIndex(char *s, int charIndex, int & positionX, int & positionY) +int Graphics::PositionAtCharIndex(String str, int charIndex, int & positionX, int & positionY) { int x = 0, y = 0, lines = 1; + String::value_type const *s = str.c_str(); for (; *s; s++) { if (!charIndex) @@ -695,7 +702,7 @@ int Graphics::PositionAtCharIndex(char *s, int charIndex, int & positionX, int & charIndex-=4; continue; } - x += font_data[font_ptrs[(int)(*(unsigned char *)s)]]; + x += font_data[font_ptrs[*s]]; charIndex--; } positionX = x; @@ -703,9 +710,10 @@ int Graphics::PositionAtCharIndex(char *s, int charIndex, int & positionX, int & return lines; } -int Graphics::CharIndexAtPosition(char *s, int positionX, int positionY) +int Graphics::CharIndexAtPosition(String str, int positionX, int positionY) { int x=0, y=-2,charIndex=0,cw; + String::value_type const *s = str.c_str(); for (; *s; s++) { if(*s == '\n') { @@ -724,7 +732,7 @@ int Graphics::CharIndexAtPosition(char *s, int positionX, int positionY) charIndex+=4; continue; } - cw = font_data[font_ptrs[(int)(*(unsigned char *)s)]]; + cw = font_data[font_ptrs[*s]]; if ((x+(cw/2) >= positionX && y+FONT_H >= positionY) || y > positionY) break; x += cw; @@ -734,14 +742,17 @@ int Graphics::CharIndexAtPosition(char *s, int positionX, int positionY) } -int Graphics::textwrapheight(char *s, int width) +int Graphics::textwrapheight(String str, int width) { int x=0, height=FONT_H, cw; int wordlen; int charspace; + String::value_type const *s = str.c_str(); while (*s) { - wordlen = strcspn(s," .,!?\n"); + wordlen = 0; + while(*s && String(" .,!?\n").find(*s) != String::npos) + s++; charspace = textwidthx(s, width-x); if (charspace=width) { x = 0; @@ -780,9 +791,9 @@ int Graphics::textwrapheight(char *s, int width) return height; } -void Graphics::textsize(const char * s, int & width, int & height) +void Graphics::textsize(String str, int & width, int & height) { - if(!strlen(s)) + if(!str.size()) { width = 0; height = FONT_H-2; @@ -790,6 +801,7 @@ void Graphics::textsize(const char * s, int & width, int & height) } int cHeight = FONT_H-2, cWidth = 0, lWidth = 0; + String::value_type const *s = str.c_str(); for (; *s; s++) { if (*s == '\n') @@ -809,7 +821,7 @@ void Graphics::textsize(const char * s, int & width, int & height) } else { - cWidth += font_data[font_ptrs[(int)(*(unsigned char *)s)]]; + cWidth += font_data[font_ptrs[*s]]; if(cWidth>lWidth) lWidth = cWidth; } diff --git a/src/graphics/Graphics.h b/src/graphics/Graphics.h index 5c1e6adc9..aa961dd12 100644 --- a/src/graphics/Graphics.h +++ b/src/graphics/Graphics.h @@ -1,7 +1,7 @@ #ifndef GRAPHICS_H #define GRAPHICS_H -#include +#include "common/String.h" #include #include #include @@ -116,15 +116,15 @@ public: static pixel *render_packed_rgb(void *image, int width, int height, int cmp_size); //Font/text metrics - static int CharIndexAtPosition(char *s, int positionX, int positionY); - static int PositionAtCharIndex(char *s, int charIndex, int & positionX, int & positionY); - static int CharWidth(unsigned char c); - static int textnwidth(char *s, int n); - static void textnpos(char *s, int n, int w, int *cx, int *cy); - static int textwidthx(char *s, int w); - static int textwrapheight(char *s, int width); - static int textwidth(const char *s); - static void textsize(const char * s, int & width, int & height); + static int CharIndexAtPosition(String s, int positionX, int positionY); + static int PositionAtCharIndex(String s, int charIndex, int & positionX, int & positionY); + static int CharWidth(String::value_type c); + static int textnwidth(String s, int n); + static void textnpos(String s, int n, int w, int *cx, int *cy); + static int textwidthx(String s, int w); + static int textwrapheight(String s, int width); + static int textwidth(String s); + static void textsize(String s, int & width, int & height); VideoBuffer DumpFrame(); @@ -139,11 +139,10 @@ public: void Clear(); void Finalise(); // - int drawtext_outline(int x, int y, const char *s, int r, int g, int b, int a); - int drawtext(int x, int y, const char *s, int r, int g, int b, int a); - int drawtext(int x, int y, std::string s, int r, int g, int b, int a); - int drawchar(int x, int y, int c, int r, int g, int b, int a); - int addchar(int x, int y, int c, int r, int g, int b, int a); + int drawtext_outline(int x, int y, String s, int r, int g, int b, int a); + int drawtext(int x, int y, String s, int r, int g, int b, int a); + int drawchar(int x, int y, String::value_type c, int r, int g, int b, int a); + int addchar(int x, int y, String::value_type c, int r, int g, int b, int a); void xor_pixel(int x, int y); void xor_line(int x, int y, int x2, int y2); diff --git a/src/graphics/OpenGLDrawMethods.inl b/src/graphics/OpenGLDrawMethods.inl index 9487fcfc6..1d01c7e0e 100644 --- a/src/graphics/OpenGLDrawMethods.inl +++ b/src/graphics/OpenGLDrawMethods.inl @@ -1,7 +1,7 @@ #include "../data/font.h" #include -int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, const char *s, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, String s, int r, int g, int b, int a) { drawtext(x-1, y-1, s, 0, 0, 0, 120); drawtext(x+1, y+1, s, 0, 0, 0, 120); @@ -12,7 +12,7 @@ int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, const char *s, int r, int return drawtext(x, y, s, r, g, b, a); } -int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::drawtext(int x, int y, String str, int r, int g, int b, int a) { bool invert = false; if(!strlen(s)) @@ -23,6 +23,7 @@ int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int VideoBuffer texture(width, height); int characterX = 0, characterY = 0; int startX = characterX; + String::value_type *s = str.c_str(); for (; *s; s++) { if (*s == '\n') @@ -98,7 +99,7 @@ int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int } else { - characterX = texture.SetCharacter(characterX, characterY, *(unsigned char *)s, r, g, b, a); + characterX = texture.SetCharacter(characterX, characterY, *s, r, g, b, a); } } glEnable(GL_TEXTURE_2D); @@ -128,12 +129,7 @@ int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int return x; } -int PIXELMETHODS_CLASS::drawtext(int x, int y, std::string s, int r, int g, int b, int a) -{ - return drawtext(x, y, s.c_str(), r, g, b, a); -} - -int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::drawchar(int x, int y, String::value_type c, int r, int g, int b, int a) { unsigned char *rp = font_data + font_ptrs[c]; int w = *(rp++); @@ -162,7 +158,7 @@ int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a return x + w; } -int PIXELMETHODS_CLASS::addchar(int x, int y, int c, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::addchar(int x, int y, String::value_type c, int r, int g, int b, int a) { unsigned char *rp = font_data + font_ptrs[c]; int w = *(rp++); diff --git a/src/graphics/RasterDrawMethods.inl b/src/graphics/RasterDrawMethods.inl index 0cdca0e4e..4bb1469bc 100644 --- a/src/graphics/RasterDrawMethods.inl +++ b/src/graphics/RasterDrawMethods.inl @@ -1,7 +1,7 @@ #include "font.h" #include -int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, const char *s, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, String s, int r, int g, int b, int a) { drawtext(x-1, y-1, s, 0, 0, 0, 120); drawtext(x+1, y+1, s, 0, 0, 0, 120); @@ -12,15 +12,16 @@ int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, const char *s, int r, int return drawtext(x, y, s, r, g, b, a); } -int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::drawtext(int x, int y, String str, int r, int g, int b, int a) { - if(!strlen(s)) + if(!str.size()) return 0; int invert = 0; int oR = r, oG = g, oB = b; int characterX = x, characterY = y; int startX = characterX; + String::value_type const *s = str.c_str(); for (; *s; s++) { if (*s == '\n') @@ -96,18 +97,13 @@ int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int } else { - characterX = drawchar(characterX, characterY, *(unsigned char *)s, r, g, b, a); + characterX = drawchar(characterX, characterY, *s, r, g, b, a); } } return x; } -int PIXELMETHODS_CLASS::drawtext(int x, int y, std::string s, int r, int g, int b, int a) -{ - return drawtext(x, y, s.c_str(), r, g, b, a); -} - -int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::drawchar(int x, int y, String::value_type c, int r, int g, int b, int a) { int i, j, w, bn = 0, ba = 0; unsigned char *rp = font_data + font_ptrs[c]; @@ -127,7 +123,7 @@ int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a return x + w; } -int PIXELMETHODS_CLASS::addchar(int x, int y, int c, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::addchar(int x, int y, String::value_type c, int r, int g, int b, int a) { int i, j, w, bn = 0, ba = 0; unsigned char *rp = font_data + font_ptrs[c]; diff --git a/src/graphics/Renderer.cpp b/src/graphics/Renderer.cpp index 085b8e54d..57ffeb2cd 100644 --- a/src/graphics/Renderer.cpp +++ b/src/graphics/Renderer.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -519,17 +520,16 @@ void Renderer::RenderZoom() #endif } -int Renderer_wtypesCount; -wall_type * Renderer_wtypes = LoadWalls(Renderer_wtypesCount); +std::vector Renderer_wtypes = LoadWalls(); VideoBuffer * Renderer::WallIcon(int wallID, int width, int height) { int i, j; int wt = wallID; - if (wt<0 || wt>=Renderer_wtypesCount) + if (wt<0 || wt>=(int)Renderer_wtypes.size()) return 0; - wall_type *wtypes = Renderer_wtypes; + wall_type *wtypes = Renderer_wtypes.data(); pixel pc = wtypes[wt].colour; pixel gc = wtypes[wt].eglow; VideoBuffer * newTexture = new VideoBuffer(width, height); @@ -985,8 +985,8 @@ void Renderer::DrawSigns() for (size_t i = 0; i < signs.size(); i++) if (signs[i].text.length()) { - char type = 0; - std::string text = signs[i].getText(sim); + String::value_type type = 0; + String text = signs[i].getText(sim); sign::splitsign(signs[i].text, &type); signs[i].pos(text, x, y, w, h); clearrect(x, y, w+1, h); @@ -1496,9 +1496,9 @@ void Renderer::render_parts() if (mousePos.X>(nx-3) && mousePos.X<(nx+3) && mousePos.Y<(ny+3) && mousePos.Y>(ny-3)) //If mouse is in the head { - char buff[12]; //Buffer for HP - sprintf(buff, "%3d", sim->parts[i].life); //Show HP - drawtext(mousePos.X-8-2*(sim->parts[i].life<100)-2*(sim->parts[i].life<10), mousePos.Y-12, buff, 255, 255, 255, 255); + String::Stream hp; + hp << std::setw(3) << sim->parts[i].life; + drawtext(mousePos.X-8-2*(sim->parts[i].life<100)-2*(sim->parts[i].life<10), mousePos.Y-12, hp.str(), 255, 255, 255, 255); } if (findingElement == t) diff --git a/src/graphics/Renderer.h b/src/graphics/Renderer.h index 42afd9d07..b14143b7b 100644 --- a/src/graphics/Renderer.h +++ b/src/graphics/Renderer.h @@ -113,11 +113,10 @@ public: void draw_icon(int x, int y, Icon icon); - int drawtext_outline(int x, int y, const char *s, int r, int g, int b, int a); - int drawtext(int x, int y, const char *s, int r, int g, int b, int a); - int drawtext(int x, int y, std::string s, int r, int g, int b, int a); - int drawchar(int x, int y, int c, int r, int g, int b, int a); - int addchar(int x, int y, int c, int r, int g, int b, int a); + int drawtext_outline(int x, int y, String s, int r, int g, int b, int a); + int drawtext(int x, int y, String s, int r, int g, int b, int a); + int drawchar(int x, int y, String::value_type c, int r, int g, int b, int a); + int addchar(int x, int y, String::value_type c, int r, int g, int b, int a); void xor_pixel(int x, int y); void xor_line(int x, int y, int x2, int y2); diff --git a/src/gui/colourpicker/ColourPickerActivity.cpp b/src/gui/colourpicker/ColourPickerActivity.cpp index c83966d96..85d051030 100644 --- a/src/gui/colourpicker/ColourPickerActivity.cpp +++ b/src/gui/colourpicker/ColourPickerActivity.cpp @@ -108,8 +108,8 @@ void ColourPickerActivity::UpdateTextboxes(int r, int g, int b, int a) gValue->SetText(format::NumberToString(g)); bValue->SetText(format::NumberToString(b)); aValue->SetText(format::NumberToString(a)); - std::stringstream hex; - hex << std::hex << "0x" << std::setfill('0') << std::setw(2) << std::uppercase << a << std::setw(2) << r << std::setw(2) << g << std::setw(2) << b; + String::Stream hex; + hex << std::hex << "0x" << std::setfill(String::value_type('0')) << std::setw(2) << std::uppercase << a << std::setw(2) << r << std::setw(2) << g << std::setw(2) << b; hexValue->SetText(hex.str()); } void ColourPickerActivity::OnTryExit(ExitMethod method) diff --git a/src/gui/colourpicker/ColourPickerActivity.h b/src/gui/colourpicker/ColourPickerActivity.h index e837cc147..f8213885b 100644 --- a/src/gui/colourpicker/ColourPickerActivity.h +++ b/src/gui/colourpicker/ColourPickerActivity.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include "common/String.h" #include "Activity.h" #include "gui/interface/Window.h" #include "gui/interface/Textbox.h" diff --git a/src/gui/console/ConsoleCommand.h b/src/gui/console/ConsoleCommand.h index 31e41b05f..87e85e406 100644 --- a/src/gui/console/ConsoleCommand.h +++ b/src/gui/console/ConsoleCommand.h @@ -4,18 +4,18 @@ class ConsoleCommand { public: - ConsoleCommand(std::string command, int returnStatus, std::string returnValue): + ConsoleCommand(String command, int returnStatus, String returnValue): Command(command), ReturnStatus(returnStatus), ReturnValue(returnValue) { } - std::string Command; + String Command; int ReturnStatus; - std::string ReturnValue; + String ReturnValue; - operator std::string() const + operator ByteString() const { - return Command; + return Command.ToUtf8(); } }; diff --git a/src/gui/console/ConsoleController.cpp b/src/gui/console/ConsoleController.cpp index ed49319a1..e56968032 100644 --- a/src/gui/console/ConsoleController.cpp +++ b/src/gui/console/ConsoleController.cpp @@ -13,7 +13,7 @@ ConsoleController::ConsoleController(ControllerCallback * callback, CommandInter this->commandInterface = commandInterface; } -void ConsoleController::EvaluateCommand(std::string command) +void ConsoleController::EvaluateCommand(String command) { if(command.length()) { @@ -31,7 +31,7 @@ void ConsoleController::CloseConsole() consoleView->CloseActiveWindow(); } -std::string ConsoleController::FormatCommand(std::string command) +String ConsoleController::FormatCommand(String command) { return commandInterface->FormatCommand(command); } diff --git a/src/gui/console/ConsoleController.h b/src/gui/console/ConsoleController.h index 03c2fa78d..26f61acbe 100644 --- a/src/gui/console/ConsoleController.h +++ b/src/gui/console/ConsoleController.h @@ -1,7 +1,7 @@ #ifndef CONSOLECONTROLLER_H_ #define CONSOLECONTROLLER_H_ -#include +#include "common/String.h" #include "Controller.h" #include "ConsoleView.h" #include "ConsoleModel.h" @@ -18,8 +18,8 @@ class ConsoleController { public: bool HasDone; ConsoleController(ControllerCallback * callback, CommandInterface * commandInterface); - std::string FormatCommand(std::string command); - void EvaluateCommand(std::string command); + String FormatCommand(String command); + void EvaluateCommand(String command); void NextCommand(); void PreviousCommand(); void Exit(); diff --git a/src/gui/console/ConsoleModel.cpp b/src/gui/console/ConsoleModel.cpp index e05fe5949..bd516a84b 100644 --- a/src/gui/console/ConsoleModel.cpp +++ b/src/gui/console/ConsoleModel.cpp @@ -2,8 +2,8 @@ #include "ConsoleModel.h" ConsoleModel::ConsoleModel() { - std::vector previousHistory = Client::Ref().GetPrefStringArray("Console.History"); - for(std::vector::reverse_iterator iter = previousHistory.rbegin(), end = previousHistory.rend(); iter != end; ++iter) + std::vector previousHistory = Client::Ref().GetPrefStringArray("Console.History"); + for(std::vector::reverse_iterator iter = previousHistory.rbegin(), end = previousHistory.rend(); iter != end; ++iter) { if(previousCommands.size()<25) { diff --git a/src/gui/dialogues/ConfirmPrompt.cpp b/src/gui/dialogues/ConfirmPrompt.cpp index 0fa00ff1c..f7ea37f8b 100644 --- a/src/gui/dialogues/ConfirmPrompt.cpp +++ b/src/gui/dialogues/ConfirmPrompt.cpp @@ -6,7 +6,7 @@ #include "gui/interface/ScrollPanel.h" #include "PowderToy.h" -ConfirmPrompt::ConfirmPrompt(std::string title, std::string message, ConfirmDialogueCallback * callback_): +ConfirmPrompt::ConfirmPrompt(String title, String message, ConfirmDialogueCallback * callback_): ui::Window(ui::Point(-1, -1), ui::Point(250, 35)), callback(callback_) { @@ -68,7 +68,7 @@ ConfirmPrompt::ConfirmPrompt(std::string title, std::string message, ConfirmDial MakeActiveWindow(); } -ConfirmPrompt::ConfirmPrompt(std::string title, std::string message, std::string buttonText, ConfirmDialogueCallback * callback_): +ConfirmPrompt::ConfirmPrompt(String title, String message, String buttonText, ConfirmDialogueCallback * callback_): ui::Window(ui::Point(-1, -1), ui::Point(250, 50)), callback(callback_) { @@ -130,7 +130,7 @@ ConfirmPrompt::ConfirmPrompt(std::string title, std::string message, std::string MakeActiveWindow(); } -bool ConfirmPrompt::Blocking(std::string title, std::string message, std::string buttonText) +bool ConfirmPrompt::Blocking(String title, String message, String buttonText) { class BlockingPromptCallback: public ConfirmDialogueCallback { public: diff --git a/src/gui/dialogues/ConfirmPrompt.h b/src/gui/dialogues/ConfirmPrompt.h index 62aff7fd2..0e39f3450 100644 --- a/src/gui/dialogues/ConfirmPrompt.h +++ b/src/gui/dialogues/ConfirmPrompt.h @@ -1,16 +1,16 @@ #ifndef CONFIRMPROMPT_H_ #define CONFIRMPROMPT_H_ -#include +#include "common/String.h" #include "gui/interface/Window.h" class ConfirmDialogueCallback; class ConfirmPrompt: public ui::Window { public: enum DialogueResult { ResultCancel, ResultOkay }; - ConfirmPrompt(std::string title, std::string message, ConfirmDialogueCallback * callback_ = NULL); - ConfirmPrompt(std::string title, std::string message, std::string buttonText, ConfirmDialogueCallback * callback_ = NULL); - static bool Blocking(std::string title, std::string message, std::string buttonText = "Confirm"); + ConfirmPrompt(String title, String message, ConfirmDialogueCallback * callback_ = NULL); + ConfirmPrompt(String title, String message, String buttonText, ConfirmDialogueCallback * callback_ = NULL); + static bool Blocking(String title, String message, String buttonText = "Confirm"); virtual void OnDraw(); virtual ~ConfirmPrompt(); ConfirmDialogueCallback * callback; diff --git a/src/gui/dialogues/ErrorMessage.cpp b/src/gui/dialogues/ErrorMessage.cpp index 35b0a2dd2..394a9aa08 100644 --- a/src/gui/dialogues/ErrorMessage.cpp +++ b/src/gui/dialogues/ErrorMessage.cpp @@ -5,7 +5,7 @@ #include "gui/interface/Label.h" #include "PowderToy.h" -ErrorMessage::ErrorMessage(std::string title, std::string message, ErrorMessageCallback * callback_): +ErrorMessage::ErrorMessage(String title, String message, ErrorMessageCallback * callback_): ui::Window(ui::Point(-1, -1), ui::Point(200, 35)), callback(callback_) { @@ -50,7 +50,7 @@ ErrorMessage::ErrorMessage(std::string title, std::string message, ErrorMessage MakeActiveWindow(); } -void ErrorMessage::Blocking(std::string title, std::string message) +void ErrorMessage::Blocking(String title, String message) { class BlockingDismissCallback: public ErrorMessageCallback { public: diff --git a/src/gui/dialogues/ErrorMessage.h b/src/gui/dialogues/ErrorMessage.h index a7281b281..b5468ac27 100644 --- a/src/gui/dialogues/ErrorMessage.h +++ b/src/gui/dialogues/ErrorMessage.h @@ -7,8 +7,8 @@ class ErrorMessageCallback; class ErrorMessage: public ui::Window { ErrorMessageCallback * callback; public: - ErrorMessage(std::string title, std::string message, ErrorMessageCallback * callback_ = NULL); - static void Blocking(std::string title, std::string message); + ErrorMessage(String title, String message, ErrorMessageCallback * callback_ = NULL); + static void Blocking(String title, String message); virtual void OnDraw(); virtual ~ErrorMessage(); }; diff --git a/src/gui/dialogues/InformationMessage.cpp b/src/gui/dialogues/InformationMessage.cpp index c097c4f64..8e29d5c55 100644 --- a/src/gui/dialogues/InformationMessage.cpp +++ b/src/gui/dialogues/InformationMessage.cpp @@ -5,7 +5,7 @@ #include "gui/interface/Label.h" #include "gui/interface/ScrollPanel.h" -InformationMessage::InformationMessage(std::string title, std::string message, bool large): +InformationMessage::InformationMessage(String title, String message, bool large): ui::Window(ui::Point(-1, -1), ui::Point(200, 35)) { if (large) //Maybe also use this large mode for changelogs eventually, or have it as a customizable size? diff --git a/src/gui/dialogues/InformationMessage.h b/src/gui/dialogues/InformationMessage.h index 6a26b384a..2f13a9419 100644 --- a/src/gui/dialogues/InformationMessage.h +++ b/src/gui/dialogues/InformationMessage.h @@ -5,7 +5,7 @@ class InformationMessage: public ui::Window { public: - InformationMessage(std::string title, std::string message, bool large); + InformationMessage(String title, String message, bool large); virtual void OnDraw(); virtual ~InformationMessage(); }; diff --git a/src/gui/dialogues/LegacyDialogues.h b/src/gui/dialogues/LegacyDialogues.h index a60490500..ddde28a79 100644 --- a/src/gui/dialogues/LegacyDialogues.h +++ b/src/gui/dialogues/LegacyDialogues.h @@ -2,10 +2,10 @@ //Legacy blocking prompts //This are not implemented here, but rather in the engine bootstrapper -bool ConfirmUI(std::string title, std::string message, std::string confirmText) {} +bool ConfirmUI(String title, String message, String confirmText) {} -void ErrorUI(std::string title, std::string message) {} +void ErrorUI(String title, String message) {} -void InformationUI(std::string title, std::string message) {} +void InformationUI(String title, String message) {} -std::string MessagePromptUI(std::string title, std::string message, std::string text, std::string placeholder) {} +String MessagePromptUI(String title, String message, String text, String placeholder) {} diff --git a/src/gui/dialogues/TextPrompt.cpp b/src/gui/dialogues/TextPrompt.cpp index 4e0b5c066..24febf2ea 100644 --- a/src/gui/dialogues/TextPrompt.cpp +++ b/src/gui/dialogues/TextPrompt.cpp @@ -21,7 +21,7 @@ public: } }; -TextPrompt::TextPrompt(std::string title, std::string message, std::string text, std::string placeholder, bool multiline, TextDialogueCallback * callback_): +TextPrompt::TextPrompt(String title, String message, String text, String placeholder, bool multiline, TextDialogueCallback * callback_): ui::Window(ui::Point(-1, -1), ui::Point(200, 65)), callback(callback_) { @@ -77,15 +77,15 @@ TextPrompt::TextPrompt(std::string title, std::string message, std::string text, MakeActiveWindow(); } -std::string TextPrompt::Blocking(std::string title, std::string message, std::string text, std::string placeholder, bool multiline) +String TextPrompt::Blocking(String title, String message, String text, String placeholder, bool multiline) { - std::string returnString = ""; + String returnString = ""; class BlockingTextCallback: public TextDialogueCallback { - std::string & outputString; + String & outputString; public: - BlockingTextCallback(std::string & output) : outputString(output) {} - virtual void TextCallback(TextPrompt::DialogueResult result, std::string resultText) { + BlockingTextCallback(String & output) : outputString(output) {} + virtual void TextCallback(TextPrompt::DialogueResult result, String resultText) { if(result == ResultOkay) outputString = resultText; else diff --git a/src/gui/dialogues/TextPrompt.h b/src/gui/dialogues/TextPrompt.h index e88c977df..5b99d4ac5 100644 --- a/src/gui/dialogues/TextPrompt.h +++ b/src/gui/dialogues/TextPrompt.h @@ -11,8 +11,8 @@ protected: public: friend class CloseAction; enum DialogueResult { ResultCancel, ResultOkay }; - TextPrompt(std::string title, std::string message, std::string text, std::string placeholder, bool multiline, TextDialogueCallback * callback_); - static std::string Blocking(std::string title, std::string message, std::string text, std::string placeholder, bool multiline); + TextPrompt(String title, String message, String text, String placeholder, bool multiline, TextDialogueCallback * callback_); + static String Blocking(String title, String message, String text, String placeholder, bool multiline); virtual void OnDraw(); virtual ~TextPrompt(); TextDialogueCallback * callback; @@ -21,7 +21,7 @@ public: class TextDialogueCallback { public: - virtual void TextCallback(TextPrompt::DialogueResult result, std::string resultText) {} + virtual void TextCallback(TextPrompt::DialogueResult result, String resultText) {} virtual ~TextDialogueCallback() {} }; diff --git a/src/gui/elementsearch/ElementSearchActivity.cpp b/src/gui/elementsearch/ElementSearchActivity.cpp index 33cabfd03..9bad0fd5e 100644 --- a/src/gui/elementsearch/ElementSearchActivity.cpp +++ b/src/gui/elementsearch/ElementSearchActivity.cpp @@ -1,4 +1,5 @@ #include +#include "common/String.h" #include "ElementSearchActivity.h" #include "gui/interface/Textbox.h" #include "gui/interface/Label.h" @@ -91,7 +92,7 @@ ElementSearchActivity::ElementSearchActivity(GameController * gameController, st searchTools(""); } -void ElementSearchActivity::searchTools(std::string query) +void ElementSearchActivity::searchTools(String query) { firstResult = NULL; for(std::vector::iterator iter = toolButtons.begin(), end = toolButtons.end(); iter != end; ++iter) { @@ -103,7 +104,7 @@ void ElementSearchActivity::searchTools(std::string query) ui::Point viewPosition = searchField->Position + ui::Point(2+0, searchField->Size.Y+2+8); ui::Point current = ui::Point(0, 0); - std::string queryLower = std::string(query); + ByteString queryLower = query.ToAscii(); std::transform(queryLower.begin(), queryLower.end(), queryLower.begin(), ::tolower); std::vector matches; @@ -112,13 +113,13 @@ void ElementSearchActivity::searchTools(std::string query) for(std::vector::const_iterator iter = tools.begin(), end = tools.end(); iter != end; ++iter) { - std::string nameLower = std::string((*iter)->GetName()); + ByteString nameLower = (*iter)->GetName(); std::transform(nameLower.begin(), nameLower.end(), nameLower.begin(), ::tolower); - if(!strcmp(nameLower.c_str(), queryLower.c_str())) + if(nameLower == queryLower) exactmatches.push_back(*iter); - else if(!strncmp(nameLower.c_str(), queryLower.c_str(), queryLower.length())) + else if(!nameLower.compare(0, queryLower.length(), queryLower)) frontmatches.push_back(*iter); - else if(strstr(nameLower.c_str(), queryLower.c_str())) + else if(nameLower.find(queryLower) != String::npos) matches.push_back(*iter); } @@ -198,7 +199,7 @@ void ElementSearchActivity::OnDraw() g->drawrect(Position.X+searchField->Position.X, Position.Y+searchField->Position.Y+searchField->Size.Y+8, searchField->Size.X, Size.Y-(searchField->Position.Y+searchField->Size.Y+8)-23, 255, 255, 255, 180); if (toolTipPresence && toolTip.length()) { - g->drawtext(10, Size.Y+70, (char*)toolTip.c_str(), 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); + g->drawtext(10, Size.Y+70, toolTip, 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); } } @@ -265,7 +266,7 @@ void ElementSearchActivity::OnKeyRelease(int key, Uint16 character, bool shift, } } -void ElementSearchActivity::ToolTip(ui::Point senderPosition, std::string toolTip) +void ElementSearchActivity::ToolTip(ui::Point senderPosition, String toolTip) { this->toolTip = toolTip; this->isToolTipFadingIn = true; diff --git a/src/gui/elementsearch/ElementSearchActivity.h b/src/gui/elementsearch/ElementSearchActivity.h index bf9af235a..a4dfb46e0 100644 --- a/src/gui/elementsearch/ElementSearchActivity.h +++ b/src/gui/elementsearch/ElementSearchActivity.h @@ -2,7 +2,6 @@ #define ELEMENTSEARCHACTIVITY_H_ #include -#include #include "Activity.h" #include "gui/interface/Window.h" #include "gui/interface/Textbox.h" @@ -18,13 +17,13 @@ class ElementSearchActivity: public WindowActivity std::vector tools; ui::Textbox * searchField; std::vector toolButtons; - std::string toolTip; + String toolTip; int toolTipPresence; bool shiftPressed; bool ctrlPressed; bool altPressed; bool isToolTipFadingIn; - void searchTools(std::string query); + void searchTools(String query); public: class ToolAction; @@ -37,7 +36,7 @@ public: virtual void OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool alt); virtual void OnKeyRelease(int key, Uint16 character, bool shift, bool ctrl, bool alt); virtual void OnDraw(); - virtual void ToolTip(ui::Point senderPosition, std::string ToolTip); + virtual void ToolTip(ui::Point senderPosition, String ToolTip); }; #endif /* ELEMENTSEARCHACTIVITY_H_ */ diff --git a/src/gui/filebrowser/FileBrowserActivity.cpp b/src/gui/filebrowser/FileBrowserActivity.cpp index 4a84291dd..bfcc128fb 100644 --- a/src/gui/filebrowser/FileBrowserActivity.cpp +++ b/src/gui/filebrowser/FileBrowserActivity.cpp @@ -1,4 +1,3 @@ -#include #include #include #include "FileBrowserActivity.h" @@ -42,8 +41,8 @@ public: //Currently, reading is done on another thread, we can't render outside the main thread due to some bullshit with OpenGL class LoadFilesTask: public Task { - std::string directory; - std::string search; + ByteString directory; + ByteString search; std::vector saveFiles; virtual void before() @@ -58,15 +57,15 @@ class LoadFilesTask: public Task virtual bool doWork() { - std::vector files = Client::Ref().DirectorySearch(directory, search, ".cps"); - std::sort(files.rbegin(), files.rend(), [](std::string a, std::string b) { + std::vector files = Client::Ref().DirectorySearch(directory, search, ".cps"); + std::sort(files.rbegin(), files.rend(), [](ByteString a, ByteString b) { std::transform(a.begin(), a.end(), a.begin(), ::tolower); std::transform(b.begin(), b.end(), b.begin(), ::tolower); return a < b; }); notifyProgress(-1); - for(std::vector::iterator iter = files.begin(), end = files.end(); iter != end; ++iter) + for(std::vector::iterator iter = files.begin(), end = files.end(); iter != end; ++iter) { SaveFile * saveFile = new SaveFile(*iter); try @@ -76,18 +75,18 @@ class LoadFilesTask: public Task saveFile->SetGameSave(tempSave); saveFiles.push_back(saveFile); - std::string filename = *iter; + ByteString filename = *iter; size_t folderPos = filename.rfind(PATH_SEP); - if(folderPos!=std::string::npos && folderPos+1 < filename.size()) + if(folderPos!=ByteString::npos && folderPos+1 < filename.size()) { filename = filename.substr(folderPos+1); } size_t extPos = filename.rfind("."); - if(extPos!=std::string::npos) + if(extPos!=ByteString::npos) { filename = filename.substr(0, extPos); } - saveFile->SetDisplayName(filename); + saveFile->SetDisplayName(filename.FromUtf8()); } catch(std::exception & e) { @@ -103,7 +102,7 @@ public: return saveFiles; } - LoadFilesTask(std::string directory, std::string search): + LoadFilesTask(ByteString directory, ByteString search): directory(directory), search(search) { @@ -117,11 +116,11 @@ public: FileBrowserActivity * a; SearchAction(FileBrowserActivity * a) : a(a) {} virtual void TextChangedCallback(ui::Textbox * sender) { - a->DoSearch(sender->GetText()); + a->DoSearch(sender->GetText().ToUtf8()); } }; -FileBrowserActivity::FileBrowserActivity(std::string directory, FileSelectedCallback * callback): +FileBrowserActivity::FileBrowserActivity(ByteString directory, FileSelectedCallback * callback): WindowActivity(ui::Point(-1, -1), ui::Point(450, 300)), callback(callback), directory(directory), @@ -167,7 +166,7 @@ FileBrowserActivity::FileBrowserActivity(std::string directory, FileSelectedCall loadDirectory(directory, ""); } -void FileBrowserActivity::DoSearch(std::string search) +void FileBrowserActivity::DoSearch(ByteString search) { if(!loadFiles) { @@ -184,7 +183,7 @@ void FileBrowserActivity::SelectSave(SaveFile * file) void FileBrowserActivity::DeleteSave(SaveFile * file) { - std::string deleteMessage = "Are you sure you want to delete " + file->GetDisplayName() + ".cps?"; + String deleteMessage = "Are you sure you want to delete " + file->GetDisplayName() + ".cps?"; if (ConfirmPrompt::Blocking("Delete Save", deleteMessage)) { remove(file->GetName().c_str()); @@ -194,7 +193,7 @@ void FileBrowserActivity::DeleteSave(SaveFile * file) void FileBrowserActivity::RenameSave(SaveFile * file) { - std::string newName = TextPrompt::Blocking("Rename", "Change save name", file->GetDisplayName(), "", 0); + ByteString newName = TextPrompt::Blocking("Rename", "Change save name", file->GetDisplayName(), "", 0).ToUtf8(); if (newName.length()) { newName = directory + PATH_SEP + newName + ".cps"; @@ -208,7 +207,7 @@ void FileBrowserActivity::RenameSave(SaveFile * file) ErrorMessage::Blocking("Error", "No save name given"); } -void FileBrowserActivity::loadDirectory(std::string directory, std::string search) +void FileBrowserActivity::loadDirectory(ByteString directory, ByteString search) { for (size_t i = 0; i < components.size(); i++) { diff --git a/src/gui/filebrowser/FileBrowserActivity.h b/src/gui/filebrowser/FileBrowserActivity.h index 3696ba753..2cfe0d339 100644 --- a/src/gui/filebrowser/FileBrowserActivity.h +++ b/src/gui/filebrowser/FileBrowserActivity.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include "common/String.h" #include "Activity.h" #include "gui/interface/Window.h" #include "tasks/TaskListener.h" @@ -33,7 +33,7 @@ class FileBrowserActivity: public TaskListener, public WindowActivity std::vector files; std::vector components; std::vector componentsQueue; - std::string directory; + ByteString directory; ui::ProgressBar * progressBar; @@ -46,16 +46,16 @@ class FileBrowserActivity: public TaskListener, public WindowActivity class SearchAction; void populateList(); public: - FileBrowserActivity(std::string directory, FileSelectedCallback * callback); + FileBrowserActivity(ByteString directory, FileSelectedCallback * callback); virtual void OnDraw(); virtual void OnTick(float dt); virtual void OnTryExit(ExitMethod method); virtual void OnMouseDown(int x, int y, unsigned button); - void loadDirectory(std::string directory, std::string search); + void loadDirectory(ByteString directory, ByteString search); void SelectSave(SaveFile * file); void DeleteSave(SaveFile * file); void RenameSave(SaveFile * file); - void DoSearch(std::string search); + void DoSearch(ByteString search); virtual ~FileBrowserActivity(); virtual void NotifyDone(Task * task); diff --git a/src/gui/font/FontEditor.cpp b/src/gui/font/FontEditor.cpp index c66f85931..03c74a7e7 100644 --- a/src/gui/font/FontEditor.cpp +++ b/src/gui/font/FontEditor.cpp @@ -1,5 +1,4 @@ #include -#include #include #include #include @@ -19,7 +18,7 @@ unsigned char *font_data; short *font_ptrs; -void FontEditor::ReadHeader(std::string header) +void FontEditor::ReadHeader(ByteString header) { std::fstream file; file.open(header, std::ios_base::in); @@ -27,7 +26,7 @@ void FontEditor::ReadHeader(std::string header) throw std::runtime_error("Could not open " + header); file >> std::skipws; - std::string word; + ByteString word; while(word != "font_data[]") file >> word; @@ -82,24 +81,24 @@ void FontEditor::ReadHeader(std::string header) size_t eof = file.tellg(); file.seekg(0); - beforeFontData = std::string(startFontData, 0); + beforeFontData = ByteString(startFontData, 0); file.read(&beforeFontData[0], startFontData); file.seekg(endFontData); - afterFontData = std::string(startFontPtrs - endFontData, 0); + afterFontData = ByteString(startFontPtrs - endFontData, 0); file.read(&afterFontData[0], startFontPtrs - endFontData); file.seekg(endFontData); - afterFontData = std::string(startFontPtrs - endFontData, 0); + afterFontData = ByteString(startFontPtrs - endFontData, 0); file.read(&afterFontData[0], startFontPtrs - endFontData); file.seekg(endFontPtrs); - afterFontPtrs = std::string(eof - endFontPtrs, 0); + afterFontPtrs = ByteString(eof - endFontPtrs, 0); file.read(&afterFontPtrs[0], eof - endFontPtrs); file.close(); } -void FontEditor::WriteHeader(std::string header, std::vector const &fontData, std::vector const &fontPtrs) +void FontEditor::WriteHeader(ByteString header, std::vector const &fontData, std::vector const &fontPtrs) { std::fstream file; file.open(header, std::ios_base::out | std::ios_base::trunc); @@ -189,7 +188,7 @@ void FontEditor::PackData( } #define FONT_SCALE 16 -FontEditor::FontEditor(std::string _header): +FontEditor::FontEditor(ByteString _header): ui::Window(ui::Point(0, 0), ui::Point(WINDOWW, WINDOWH)), header(_header), currentChar(0x80), @@ -228,7 +227,7 @@ FontEditor::FontEditor(std::string _header): void TextChangedCallback(ui::Textbox *) { unsigned int number; - std::stringstream ss(v->currentCharTextbox->GetText()); + String::Stream ss(v->currentCharTextbox->GetText()); ss >> std::hex >> number; if(number < 256) v->currentChar = number; @@ -320,14 +319,14 @@ FontEditor::FontEditor(std::string _header): ColorComponentAction(int &_color): color(_color) {} void TextChangedCallback(ui::Textbox *box) { - std::stringstream ss(box->GetText()); + String::Stream ss(box->GetText()); ss >> color; } }; int *refs[6] = {&fgR, &fgG, &fgB, &bgR, &bgG, &bgB}; for(int i = 0; i < 6; i++) { - std::stringstream ss; + String::Stream ss; ss << *refs[i]; ui::Textbox *colorComponent = new ui::Textbox(ui::Point(currentX, baseline), ui::Point(27, 17), ss.str()); currentX += 28; @@ -385,8 +384,8 @@ FontEditor::FontEditor(std::string _header): PreviewAction(FontEditor *_v): v(_v) {} void TextChangedCallback(ui::Textbox *box) { - std::stringstream ss(box->GetText()); - std::string text; + String::Stream ss(box->GetText()); + String text; while(!ss.eof()) { if(ss.peek() == '\n') @@ -399,12 +398,12 @@ FontEditor::FontEditor(std::string _header): if(ss.fail()) { ss.clear(); - char ch = ss.get(); + String::value_type ch = ss.get(); if(!ss.eof()) text.push_back(ch); continue; } - text.push_back((char)ch); + text.push_back(ch); } v->outputPreview->SetText(text); } @@ -416,7 +415,7 @@ FontEditor::FontEditor(std::string _header): inputPreview->Appearance.VerticalAlign = ui::Appearance::AlignTop; inputPreview->SetActionCallback(new PreviewAction(this)); - std::stringstream input; + String::Stream input; for(unsigned int ch = 0x20; ch <= 0xFF; ch++) { if(!(ch & 0x3F)) @@ -493,7 +492,7 @@ void FontEditor::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bo void FontEditor::UpdateCharNumber() { - std::stringstream ss; + String::Stream ss; ss << std::hex << currentChar; currentCharTextbox->SetText(ss.str()); } diff --git a/src/gui/font/FontEditor.h b/src/gui/font/FontEditor.h index bc781e01c..5353da856 100644 --- a/src/gui/font/FontEditor.h +++ b/src/gui/font/FontEditor.h @@ -13,19 +13,19 @@ class FontEditor: public ui::Window { private: - std::string header; + ByteString header; std::array fontWidths; std::array, FONT_H>, 256> fontPixels; std::vector fontData; std::vector fontPtrs; - std::string beforeFontData; - std::string afterFontData; - std::string afterFontPtrs; + ByteString beforeFontData; + ByteString afterFontData; + ByteString afterFontPtrs; - void ReadHeader(std::string header); - void WriteHeader(std::string header, std::vector const &fontData, std::vector const &fontPtrs); + void ReadHeader(ByteString header); + void WriteHeader(ByteString header, std::vector const &fontData, std::vector const &fontPtrs); static void PackData( std::array const &fontWidths, std::array, FONT_H>, 256> const &fontPixels, @@ -57,7 +57,7 @@ private: void Save(); public: - FontEditor(std::string header); + FontEditor(ByteString header); void OnDraw(); void OnMouseDown(int x, int y, unsigned button); diff --git a/src/gui/game/DecorationTool.h b/src/gui/game/DecorationTool.h index a7d5fbe2e..dbfc07e88 100644 --- a/src/gui/game/DecorationTool.h +++ b/src/gui/game/DecorationTool.h @@ -58,7 +58,7 @@ public: return newTexture; } - DecorationTool(Renderer *ren_, int decoMode, string name, string description, int r, int g, int b, std::string identifier): + DecorationTool(Renderer *ren_, int decoMode, ByteString name, String description, int r, int g, int b, ByteString identifier): Tool(decoMode, name, description, r, g, b, identifier), Red(0), Green(0), diff --git a/src/gui/game/Favorite.cpp b/src/gui/game/Favorite.cpp index 56d629075..2a721bf3b 100644 --- a/src/gui/game/Favorite.cpp +++ b/src/gui/game/Favorite.cpp @@ -4,16 +4,16 @@ #include Favorite::Favorite(): - favoritesList(std::vector()) + favoritesList(std::vector()) {} -std::vector Favorite::GetFavoritesList() +std::vector Favorite::GetFavoritesList() { return favoritesList; } -bool Favorite::IsFavorite(std::string identifier) +bool Favorite::IsFavorite(ByteString identifier) { return std::find(favoritesList.begin(), favoritesList.end(), identifier) != favoritesList.end(); } @@ -23,7 +23,7 @@ bool Favorite::AnyFavorites() return favoritesList.size() == 0; } -void Favorite::AddFavorite(std::string identifier) +void Favorite::AddFavorite(ByteString identifier) { if (!IsFavorite(identifier)) { @@ -31,7 +31,7 @@ void Favorite::AddFavorite(std::string identifier) } } -void Favorite::RemoveFavorite(std::string identifier) +void Favorite::RemoveFavorite(ByteString identifier) { favoritesList.erase(std::remove(favoritesList.begin(), favoritesList.end(), identifier), favoritesList.end()); } @@ -43,5 +43,5 @@ void Favorite::SaveFavoritesToPrefs() void Favorite::LoadFavoritesFromPrefs() { - favoritesList = Client::Ref().GetPrefStringArray("Favorites"); + favoritesList = Client::Ref().GetPrefByteStringArray("Favorites"); } diff --git a/src/gui/game/Favorite.h b/src/gui/game/Favorite.h index 1a469ed5d..1b5963160 100644 --- a/src/gui/game/Favorite.h +++ b/src/gui/game/Favorite.h @@ -1,23 +1,23 @@ #ifndef FAVORITE_H #define FAVORITE_H -#include +#include "common/String.h" #include #include "common/Singleton.h" class Favorite : public Singleton { - std::vector favoritesList; + std::vector favoritesList; public: Favorite(); - std::vector GetFavoritesList(); - bool IsFavorite(std::string identifier); + std::vector GetFavoritesList(); + bool IsFavorite(ByteString identifier); bool AnyFavorites(); - void AddFavorite(std::string identifier); - void RemoveFavorite(std::string identifier); + void AddFavorite(ByteString identifier); + void RemoveFavorite(ByteString identifier); void SaveFavoritesToPrefs(); void LoadFavoritesFromPrefs(); diff --git a/src/gui/game/GameController.cpp b/src/gui/game/GameController.cpp index 70eaad07f..6b27e065d 100644 --- a/src/gui/game/GameController.cpp +++ b/src/gui/game/GameController.cpp @@ -57,7 +57,7 @@ public: } catch(GameModelException & ex) { - new ErrorMessage("Cannot open save", ex.what()); + new ErrorMessage("Cannot open save", ByteString(ex.what()).FromUtf8()); } } } @@ -79,7 +79,7 @@ public: } catch(GameModelException & ex) { - new ErrorMessage("Cannot open save", ex.what()); + new ErrorMessage("Cannot open save", ByteString(ex.what()).FromUtf8()); } } } @@ -322,7 +322,7 @@ int GameController::GetSignAt(int x, int y) } // assumed to already be a valid sign -std::string GameController::GetSignText(int signID) +String GameController::GetSignText(int signID) { return gameModel->GetSimulation()->signs[signID].text; } @@ -573,7 +573,7 @@ void GameController::ToolClick(int toolSelection, ui::Point point) activeTool->Click(sim, cBrush, point); } -std::string GameController::StampRegion(ui::Point point1, ui::Point point2, bool includePressure) +ByteString GameController::StampRegion(ui::Point point1, ui::Point point2, bool includePressure) { bool incPressure = Client::Ref().GetPrefBool("Simulation.IncludePressure", true); if (!incPressure) @@ -583,7 +583,7 @@ std::string GameController::StampRegion(ui::Point point1, ui::Point point2, bool if(newSave) { newSave->paused = gameModel->GetPaused(); - std::string stampName = Client::Ref().AddStamp(newSave); + ByteString stampName = Client::Ref().AddStamp(newSave); delete newSave; if (stampName.length() == 0) new ErrorMessage("Could not create stamp", "Error serializing save file"); @@ -666,15 +666,15 @@ bool GameController::MouseUp(int x, int y, unsigned button, char type) if (foundSignID != -1) { sign foundSign = gameModel->GetSimulation()->signs[foundSignID]; - std::string str = foundSign.text; - char type; + String str = foundSign.text; + String::value_type type; int pos = sign::splitsign(str, &type); if (pos) { ret = false; if (type == 'c' || type == 't' || type == 's') { - std::string link = str.substr(3, pos-3); + String link = str.substr(3, pos-3); switch (type) { case 'c': @@ -687,8 +687,8 @@ bool GameController::MouseUp(int x, int y, unsigned button, char type) case 't': { // buff is already confirmed to be a number by sign::splitsign - std::stringstream uri; - uri << "http://powdertoy.co.uk/Discussions/Thread/View.html?Thread=" << link; + ByteString::Stream uri; + uri << "http://powdertoy.co.uk/Discussions/Thread/View.html?Thread=" << link.ToUtf8(); Platform::OpenURI(uri.str()); break; } @@ -1175,7 +1175,7 @@ void GameController::SetActiveTool(int toolSelection, Tool * tool) ((PropertyTool *)tool)->OpenWindow(gameModel->GetSimulation()); } -void GameController::SetActiveTool(int toolSelection, std::string identifier) +void GameController::SetActiveTool(int toolSelection, ByteString identifier) { Tool *tool = gameModel->GetToolFromIdentifier(identifier); if (!tool) @@ -1198,7 +1198,7 @@ void GameController::SetReplaceModeFlags(int flags) gameModel->GetSimulation()->replaceModeFlags = flags; } -void GameController::OpenSearch(std::string searchText) +void GameController::OpenSearch(String searchText) { if(!search) search = new SearchController(new SearchCallback(this)); @@ -1524,7 +1524,7 @@ void GameController::Vote(int direction) } catch(GameModelException & ex) { - new ErrorMessage("Error while voting", ex.what()); + new ErrorMessage("Error while voting", ByteString(ex.what()).FromUtf8()); } } } @@ -1555,14 +1555,14 @@ void GameController::ReloadSim() } } -std::string GameController::ElementResolve(int type, int ctype) +ByteString GameController::ElementResolve(int type, int ctype) { if(gameModel && gameModel->GetSimulation()) { if (type == PT_LIFE && ctype >= 0 && ctype < NGOL) return gameModel->GetSimulation()->gmenu[ctype].name; else if (type >= 0 && type < PT_NUM) - return std::string(gameModel->GetSimulation()->elements[type].Name); + return gameModel->GetSimulation()->elements[type].Name; } return ""; } @@ -1577,10 +1577,10 @@ bool GameController::IsValidElement(int type) return false; } -std::string GameController::WallName(int type) +String GameController::WallName(int type) { if(gameModel && gameModel->GetSimulation() && type >= 0 && type < UI_WALLCOUNT) - return std::string(gameModel->GetSimulation()->wtypes[type].name); + return gameModel->GetSimulation()->wtypes[type].name; else return ""; } @@ -1596,13 +1596,13 @@ void GameController::NotifyAuthUserChanged(Client * sender) gameModel->SetUser(newUser); } -void GameController::NotifyNewNotification(Client * sender, std::pair notification) +void GameController::NotifyNewNotification(Client * sender, std::pair notification) { class LinkNotification : public Notification { - std::string link; + ByteString link; public: - LinkNotification(std::string link_, std::string message) : Notification(message), link(link_) {} + LinkNotification(ByteString link_, String message) : Notification(message), link(link_) {} virtual ~LinkNotification() {} virtual void Action() @@ -1632,13 +1632,13 @@ void GameController::NotifyUpdateAvailable(Client * sender) { GameController * c; public: - UpdateNotification(GameController * c, std::string message) : Notification(message), c(c) {} + UpdateNotification(GameController * c, String message) : Notification(message), c(c) {} virtual ~UpdateNotification() {} virtual void Action() { UpdateInfo info = Client::Ref().GetUpdateInfo(); - std::stringstream updateMessage; + String::Stream updateMessage; updateMessage << "Are you sure you want to run the updater? Please save any changes before updating.\n\nCurrent version:\n "; #ifdef SNAPSHOT @@ -1674,16 +1674,16 @@ void GameController::NotifyUpdateAvailable(Client * sender) { case UpdateInfo::Snapshot: #if MOD_ID > 0 - gameModel->AddNotification(new UpdateNotification(this, std::string("A new mod update is available - click here to update"))); + gameModel->AddNotification(new UpdateNotification(this, "A new mod update is available - click here to update")); #else - gameModel->AddNotification(new UpdateNotification(this, std::string("A new snapshot is available - click here to update"))); + gameModel->AddNotification(new UpdateNotification(this, "A new snapshot is available - click here to update")); #endif break; case UpdateInfo::Stable: - gameModel->AddNotification(new UpdateNotification(this, std::string("A new version is available - click here to update"))); + gameModel->AddNotification(new UpdateNotification(this, "A new version is available - click here to update")); break; case UpdateInfo::Beta: - gameModel->AddNotification(new UpdateNotification(this, std::string("A new beta is available - click here to update"))); + gameModel->AddNotification(new UpdateNotification(this, "A new beta is available - click here to update")); break; } } diff --git a/src/gui/game/GameController.h b/src/gui/game/GameController.h index 48560190d..8449cc089 100644 --- a/src/gui/game/GameController.h +++ b/src/gui/game/GameController.h @@ -58,7 +58,7 @@ public: ~GameController(); GameView * GetView(); int GetSignAt(int x, int y); - std::string GetSignText(int signID); + String GetSignText(int signID); bool MouseMove(int x, int y, int dx, int dy); bool MouseDown(int x, int y, unsigned button); @@ -89,7 +89,7 @@ public: void DrawRect(int toolSelection, ui::Point point1, ui::Point point2); void DrawLine(int toolSelection, ui::Point point1, ui::Point point2); void DrawFill(int toolSelection, ui::Point point); - std::string StampRegion(ui::Point point1, ui::Point point2, bool includePressure); + ByteString StampRegion(ui::Point point1, ui::Point point2, bool includePressure); void CopyRegion(ui::Point point1, ui::Point point2, bool includePressure); void CutRegion(ui::Point point1, ui::Point point2, bool includePressure); void Update(); @@ -109,7 +109,7 @@ public: void RebuildFavoritesMenu(); Tool * GetActiveTool(int selection); void SetActiveTool(int toolSelection, Tool * tool); - void SetActiveTool(int toolSelection, std::string identifier); + void SetActiveTool(int toolSelection, ByteString identifier); void SetLastTool(Tool * tool); int GetReplaceModeFlags(); void SetReplaceModeFlags(int flags); @@ -119,7 +119,7 @@ public: void SetToolStrength(float value); void LoadSaveFile(SaveFile * file); void LoadSave(SaveInfo * save); - void OpenSearch(std::string searchText); + void OpenSearch(String searchText); void OpenLogin(); void OpenProfile(); void OpenTags(); @@ -147,9 +147,9 @@ public: bool MouseInZoom(ui::Point position); ui::Point PointTranslate(ui::Point point); ui::Point NormaliseBlockCoord(ui::Point point); - std::string ElementResolve(int type, int ctype); + ByteString ElementResolve(int type, int ctype); bool IsValidElement(int type); - std::string WallName(int type); + String WallName(int type); int Record(bool record); void ResetAir(); @@ -167,7 +167,7 @@ public: virtual void NotifyUpdateAvailable(Client * sender); virtual void NotifyAuthUserChanged(Client * sender); - virtual void NotifyNewNotification(Client * sender, std::pair notification); + virtual void NotifyNewNotification(Client * sender, std::pair notification); void RunUpdater(); }; diff --git a/src/gui/game/GameModel.cpp b/src/gui/game/GameModel.cpp index db00386e9..e312a10c7 100644 --- a/src/gui/game/GameModel.cpp +++ b/src/gui/game/GameModel.cpp @@ -105,7 +105,7 @@ GameModel::GameModel(): brushList.push_back(new TriangleBrush(ui::Point(4, 4))); //Load more from brushes folder - std::vector brushFiles = Client::Ref().DirectorySearch(BRUSH_DIR, "", ".ptb"); + std::vector brushFiles = Client::Ref().DirectorySearch(BRUSH_DIR, "", ".ptb"); for (size_t i = 0; i < brushFiles.size(); i++) { std::vector brushData = Client::Ref().ReadFile(brushFiles[i]); @@ -234,7 +234,7 @@ void GameModel::BuildMenus() if(activeMenu != -1) lastMenu = activeMenu; - std::string activeToolIdentifiers[4]; + ByteString activeToolIdentifiers[4]; if(regularToolset[0]) activeToolIdentifiers[0] = regularToolset[0]->GetIdentifier(); if(regularToolset[1]) @@ -264,7 +264,7 @@ void GameModel::BuildMenus() //Create menus for (int i = 0; i < SC_TOTAL; i++) { - menuList.push_back(new Menu((const char)sim->msections[i].icon[0], sim->msections[i].name, sim->msections[i].doshow)); + menuList.push_back(new Menu(sim->msections[i].icon[0], sim->msections[i].name, sim->msections[i].doshow)); } //Build menus from Simulation elements @@ -305,14 +305,14 @@ void GameModel::BuildMenus() //Build menu for GOL types for(int i = 0; i < NGOL; i++) { - Tool * tempTool = new ElementTool(PT_LIFE|PMAPID(i), sim->gmenu[i].name, std::string(sim->gmenu[i].description), PIXR(sim->gmenu[i].colour), PIXG(sim->gmenu[i].colour), PIXB(sim->gmenu[i].colour), "DEFAULT_PT_LIFE_"+std::string(sim->gmenu[i].name)); + Tool * tempTool = new ElementTool(PT_LIFE|PMAPID(i), sim->gmenu[i].name, sim->gmenu[i].description, PIXR(sim->gmenu[i].colour), PIXG(sim->gmenu[i].colour), PIXB(sim->gmenu[i].colour), "DEFAULT_PT_LIFE_"+sim->gmenu[i].name); menuList[SC_LIFE]->AddTool(tempTool); } //Build other menus from wall data for(int i = 0; i < UI_WALLCOUNT; i++) { - Tool * tempTool = new WallTool(i, "", std::string(sim->wtypes[i].descs), PIXR(sim->wtypes[i].colour), PIXG(sim->wtypes[i].colour), PIXB(sim->wtypes[i].colour), sim->wtypes[i].identifier, sim->wtypes[i].textureGen); + Tool * tempTool = new WallTool(i, "", sim->wtypes[i].descs, PIXR(sim->wtypes[i].colour), PIXG(sim->wtypes[i].colour), PIXB(sim->wtypes[i].colour), sim->wtypes[i].identifier, sim->wtypes[i].textureGen); menuList[SC_WALL]->AddTool(tempTool); //sim->wtypes[i] } @@ -386,7 +386,7 @@ void GameModel::BuildFavoritesMenu() { menuList[SC_FAVORITES]->ClearTools(); - std::vector favList = Favorite::Ref().GetFavoritesList(); + std::vector favList = Favorite::Ref().GetFavoritesList(); for (size_t i = 0; i < favList.size(); i++) { Tool *tool = GetToolFromIdentifier(favList[i]); @@ -403,7 +403,7 @@ void GameModel::BuildFavoritesMenu() notifyLastToolChanged(); } -Tool * GameModel::GetToolFromIdentifier(std::string identifier) +Tool * GameModel::GetToolFromIdentifier(ByteString identifier) { for (std::vector::iterator iter = menuList.begin(), end = menuList.end(); iter != end; ++iter) { @@ -657,8 +657,8 @@ void GameModel::SetSave(SaveInfo * newSave) saveData->authors["type"] = "save"; saveData->authors["id"] = newSave->id; saveData->authors["username"] = newSave->userName; - saveData->authors["title"] = newSave->name; - saveData->authors["description"] = newSave->Description; + saveData->authors["title"] = newSave->name.ToUtf8(); + saveData->authors["description"] = newSave->Description.ToUtf8(); saveData->authors["published"] = (int)newSave->Published; saveData->authors["date"] = newSave->updatedDate; } @@ -912,7 +912,7 @@ void GameModel::SetPaused(bool pauseState) { if (!pauseState && sim->debug_currentParticle > 0) { - std::stringstream logmessage; + String::Stream logmessage; logmessage << "Updated particles from #" << sim->debug_currentParticle << " to end due to unpause"; sim->UpdateParticles(sim->debug_currentParticle, NPART); sim->AfterSim(); @@ -1048,17 +1048,17 @@ GameSave * GameModel::GetPlaceSave() return placeSave; } -void GameModel::Log(string message, bool printToFile) +void GameModel::Log(String message, bool printToFile) { consoleLog.push_front(message); if(consoleLog.size()>100) consoleLog.pop_back(); notifyLogChanged(message); if (printToFile) - std::cout << message << std::endl; + std::cout << message.ToUtf8() << std::endl; } -deque GameModel::GetLog() +deque GameModel::GetLog() { return consoleLog; } @@ -1088,24 +1088,24 @@ void GameModel::RemoveNotification(Notification * notification) notifyNotificationsChanged(); } -void GameModel::SetToolTip(std::string text) +void GameModel::SetToolTip(String text) { toolTip = text; notifyToolTipChanged(); } -void GameModel::SetInfoTip(std::string text) +void GameModel::SetInfoTip(String text) { infoTip = text; notifyInfoTipChanged(); } -std::string GameModel::GetToolTip() +String GameModel::GetToolTip() { return toolTip; } -std::string GameModel::GetInfoTip() +String GameModel::GetInfoTip() { return infoTip; } @@ -1246,7 +1246,7 @@ void GameModel::notifyPlaceSaveChanged() } } -void GameModel::notifyLogChanged(string entry) +void GameModel::notifyLogChanged(String entry) { for (size_t i = 0; i < observers.size(); i++) { diff --git a/src/gui/game/GameModel.h b/src/gui/game/GameModel.h index f9ca40b95..0e97ed1c2 100644 --- a/src/gui/game/GameModel.h +++ b/src/gui/game/GameModel.h @@ -41,7 +41,7 @@ private: //unsigned char * clipboardData; GameSave * clipboard; GameSave * placeSave; - deque consoleLog; + deque consoleLog; vector observers; vector toolList; @@ -77,8 +77,8 @@ private: int edgeMode; - std::string infoTip; - std::string toolTip; + String infoTip; + String toolTip; //bool zoomEnabled; void notifyRendererChanged(); void notifySimulationChanged(); @@ -98,7 +98,7 @@ private: void notifyColourPresetsChanged(); void notifyColourActivePresetChanged(); void notifyNotificationsChanged(); - void notifyLogChanged(string entry); + void notifyLogChanged(String entry); void notifyInfoTipChanged(); void notifyToolTipChanged(); void notifyQuickOptionsChanged(); @@ -123,10 +123,10 @@ public: void SetColourSelectorColour(ui::Colour colour); ui::Colour GetColourSelectorColour(); - void SetToolTip(std::string text); - void SetInfoTip(std::string text); - std::string GetToolTip(); - std::string GetInfoTip(); + void SetToolTip(String text); + void SetInfoTip(String text); + String GetToolTip(); + String GetInfoTip(); void BuildMenus(); void BuildFavoritesMenu(); @@ -149,7 +149,7 @@ public: float GetToolStrength(); Tool * GetLastTool(); void SetLastTool(Tool * newTool); - Tool * GetToolFromIdentifier(std::string identifier); + Tool * GetToolFromIdentifier(ByteString identifier); Tool * GetElementTool(int elementID); vector GetToolList(); vector GetUnlistedTools(); @@ -200,8 +200,8 @@ public: ui::Point GetZoomWindowPosition(); void SetClipboard(GameSave * save); void SetPlaceSave(GameSave * save); - void Log(string message, bool printToFile); - deque GetLog(); + void Log(String message, bool printToFile); + deque GetLog(); GameSave * GetClipboard(); GameSave * GetPlaceSave(); diff --git a/src/gui/game/GameModelException.h b/src/gui/game/GameModelException.h index c95f7e60a..30961901a 100644 --- a/src/gui/game/GameModelException.h +++ b/src/gui/game/GameModelException.h @@ -1,17 +1,16 @@ #ifndef GAMEMODELEXCEPTION_H_ #define GAMEMODELEXCEPTION_H_ -#include +#include "common/String.h" #include -using namespace std; struct GameModelException: public exception { - string message; + String message; public: - GameModelException(string message_): message(message_) {} + GameModelException(String message_): message(message_) {} const char * what() const throw() { - return message.c_str(); + return message.ToUtf8().c_str(); } ~GameModelException() throw() {}; }; diff --git a/src/gui/game/GameView.cpp b/src/gui/game/GameView.cpp index c1916b9f9..0039d6c3b 100644 --- a/src/gui/game/GameView.cpp +++ b/src/gui/game/GameView.cpp @@ -1,4 +1,3 @@ -#include #include #include #include "GameView.h" @@ -40,10 +39,10 @@ private: bool leftDown; bool showSplit; int splitPosition; - std::string toolTip2; + String toolTip2; SplitButtonAction * splitActionCallback; public: - SplitButton(ui::Point position, ui::Point size, std::string buttonText, std::string toolTip, std::string toolTip2, int split) : + SplitButton(ui::Point position, ui::Point size, String buttonText, String toolTip, String toolTip2, int split) : Button(position, size, buttonText, toolTip), showSplit(true), splitPosition(split), @@ -52,7 +51,7 @@ public: { } - void SetRightToolTip(std::string tooltip) { toolTip2 = tooltip; } + void SetRightToolTip(String tooltip) { toolTip2 = tooltip; } bool GetShowSplit() { return showSplit; } void SetShowSplit(bool split) { showSplit = split; } SplitButtonAction * GetSplitActionCallback() { return splitActionCallback; } @@ -101,12 +100,12 @@ public: return; SetToolTip(x, y); } - virtual void TextPosition(std::string ButtonText) + virtual void TextPosition(String ButtonText) { ui::Button::TextPosition(ButtonText); textPosition.X += 3; } - void SetToolTips(std::string newToolTip1, std::string newToolTip2) + void SetToolTips(String newToolTip1, String newToolTip2) { toolTip = newToolTip1; toolTip2 = newToolTip2; @@ -183,7 +182,7 @@ GameView::GameView(): buttonTip(""), isButtonTipFadingIn(false), introText(2048), - introTextMessage(introTextData), + introTextMessage(ByteString(introTextData).FromAscii()), doScreenshot(false), screenshotIndex(0), @@ -610,9 +609,9 @@ void GameView::NotifyMenuListChanged(GameModel * sender) { if (menuList[i]->GetVisible()) { - std::string tempString = ""; + String tempString = ""; tempString += menuList[i]->GetIcon(); - std::string description = menuList[i]->GetDescription(); + String description = menuList[i]->GetDescription(); if (i == SC_FAVORITES && Favorite::Ref().AnyFavorites()) description += " (Use ctrl+shift+click to favorite an element)"; ui::Button * tempButton = new ui::Button(ui::Point(WINDOWW-16, currentY), ui::Point(15, 15), tempString, description); @@ -912,7 +911,7 @@ void GameView::NotifyUserChanged(GameModel * sender) } else { - loginButton->SetText(sender->GetUser().Username); + loginButton->SetText(sender->GetUser().Username.FromUtf8()); ((SplitButton*)loginButton)->SetShowSplit(true); ((SplitButton*)loginButton)->SetRightToolTip("Edit profile"); } @@ -978,15 +977,15 @@ void GameView::NotifySaveChanged(GameModel * sender) tagSimulationButton->Enabled = sender->GetSave()->GetID(); if (sender->GetSave()->GetID()) { - std::stringstream tagsStream; - std::list tags = sender->GetSave()->GetTags(); + String::Stream tagsStream; + std::list tags = sender->GetSave()->GetTags(); if (tags.size()) { - for (std::list::const_iterator iter = tags.begin(), begin = tags.begin(), end = tags.end(); iter != end; iter++) + for (std::list::const_iterator iter = tags.begin(), begin = tags.begin(), end = tags.end(); iter != end; iter++) { if (iter != begin) tagsStream << " "; - tagsStream << *iter; + tagsStream << iter->FromUtf8(); } tagSimulationButton->SetText(tagsStream.str()); } @@ -1067,7 +1066,7 @@ int GameView::Record(bool record) { time_t startTime = time(NULL); recordingFolder = startTime; - std::stringstream recordingDir; + ByteString::Stream recordingDir; recordingDir << "recordings" << PATH_SEP << recordingFolder; Client::Ref().MakeDirectory("recordings"); Client::Ref().MakeDirectory(recordingDir.str().c_str()); @@ -1327,7 +1326,7 @@ void GameView::OnMouseUp(int x, int y, unsigned button) UpdateDrawMode(); } -void GameView::ToolTip(ui::Point senderPosition, std::string toolTip) +void GameView::ToolTip(ui::Point senderPosition, String toolTip) { // buttom button tooltips if (senderPosition.Y > Size.Y-17) @@ -1342,16 +1341,16 @@ void GameView::ToolTip(ui::Point senderPosition, std::string toolTip) else if(senderPosition.X > Size.X-BARSIZE)// < Size.Y-(quickOptionButtons.size()+1)*16) { this->toolTip = toolTip; - toolTipPosition = ui::Point(Size.X-27-Graphics::textwidth((char*)toolTip.c_str()), senderPosition.Y+3); + toolTipPosition = ui::Point(Size.X-27-Graphics::textwidth(toolTip), senderPosition.Y+3); if(toolTipPosition.Y+10 > Size.Y-MENUSIZE) - toolTipPosition = ui::Point(Size.X-27-Graphics::textwidth((char*)toolTip.c_str()), Size.Y-MENUSIZE-10); + toolTipPosition = ui::Point(Size.X-27-Graphics::textwidth(toolTip), Size.Y-MENUSIZE-10); isToolTipFadingIn = true; } // element tooltips else { this->toolTip = toolTip; - toolTipPosition = ui::Point(Size.X-27-Graphics::textwidth((char*)toolTip.c_str()), Size.Y-MENUSIZE-10); + toolTipPosition = ui::Point(Size.X-27-Graphics::textwidth(toolTip), Size.Y-MENUSIZE-10); isToolTipFadingIn = true; } } @@ -1490,8 +1489,8 @@ void GameView::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool if ((Client::Ref().GetAuthUser().UserElevation == User::ElevationModerator || Client::Ref().GetAuthUser().UserElevation == User::ElevationAdmin) && ctrl) { - std::string authorString = Client::Ref().GetAuthorInfo().toStyledString(); - new InformationMessage("Save authorship info", authorString, true); + ByteString authorString = Client::Ref().GetAuthorInfo().toStyledString(); + new InformationMessage("Save authorship info", authorString.FromUtf8(), true); } break; case 'r': @@ -1609,7 +1608,7 @@ void GameView::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool break; case 'l': { - std::vector stampList = Client::Ref().GetStamps(0, 1); + std::vector stampList = Client::Ref().GetStamps(0, 1); if (stampList.size()) { SaveFile *saveFile = Client::Ref().GetStamp(stampList[0]); @@ -1735,13 +1734,13 @@ void GameView::OnTick(float dt) int foundSignID = c->GetSignAt(mousePosition.X, mousePosition.Y); if (foundSignID != -1) { - std::string str = c->GetSignText(foundSignID); - char type = '\0'; + String str = c->GetSignText(foundSignID); + String::value_type type = '\0'; int pos = sign::splitsign(str, &type); if (type == 'c' || type == 't' || type == 's') { - std::string linkSign = str.substr(3, pos-3); - std::stringstream tooltip; + String linkSign = str.substr(3, pos-3); + String::Stream tooltip; switch (type) { case 'c': @@ -1903,7 +1902,7 @@ void GameView::NotifyNotificationsChanged(GameModel * sender) int currentY = YRES-23; for(std::vector::iterator iter = notifications.begin(), end = notifications.end(); iter != end; ++iter) { - int width = (Graphics::textwidth((*iter)->Message.c_str()))+8; + int width = (Graphics::textwidth((*iter)->Message))+8; ui::Button * tempButton = new ui::Button(ui::Point(XRES-width-22, currentY), ui::Point(width, 15), (*iter)->Message); tempButton->SetActionCallback(new NotificationButtonAction(*iter)); tempButton->Appearance.BorderInactive = style::Colour::WarningTitle; @@ -1934,9 +1933,9 @@ void GameView::NotifyZoomChanged(GameModel * sender) zoomEnabled = sender->GetZoomEnabled(); } -void GameView::NotifyLogChanged(GameModel * sender, string entry) +void GameView::NotifyLogChanged(GameModel * sender, String entry) { - logEntries.push_front(std::pair(entry, 600)); + logEntries.push_front(std::pair(entry, 600)); if (logEntries.size() > 20) logEntries.pop_back(); } @@ -2218,7 +2217,7 @@ void GameView::OnDraw() VideoBuffer screenshot(ren->DumpFrame()); std::vector data = format::VideoBufferToPNG(screenshot); - std::stringstream filename; + ByteString::Stream filename; filename << "screenshot_"; filename << std::setfill('0') << std::setw(6) << (screenshotIndex++); filename << ".png"; @@ -2232,7 +2231,7 @@ void GameView::OnDraw() VideoBuffer screenshot(ren->DumpFrame()); std::vector data = format::VideoBufferToPPM(screenshot); - std::stringstream filename; + ByteString::Stream filename; filename << "recordings" << PATH_SEP << recordingFolder << PATH_SEP; filename << "frame_"; filename << std::setfill('0') << std::setw(6) << (recordingIndex++); @@ -2245,10 +2244,10 @@ void GameView::OnDraw() { int startX = 20; int startY = YRES-20; - deque >::iterator iter; + deque >::iterator iter; for(iter = logEntries.begin(); iter != logEntries.end(); iter++) { - string message = (*iter).first; + String message = (*iter).first; int alpha = std::min((*iter).second, 255); if (alpha <= 0) //erase this and everything older { @@ -2256,8 +2255,8 @@ void GameView::OnDraw() break; } startY -= 14; - g->fillrect(startX-3, startY-3, Graphics::textwidth((char*)message.c_str())+6, 14, 0, 0, 0, 100); - g->drawtext(startX, startY, message.c_str(), 255, 255, 255, alpha); + g->fillrect(startX-3, startY-3, Graphics::textwidth(message)+6, 14, 0, 0, 0, 100); + g->drawtext(startX, startY, message, 255, 255, 255, alpha); (*iter).second -= 3; } } @@ -2265,13 +2264,13 @@ void GameView::OnDraw() if(recording) { - std::stringstream sampleInfo; + String::Stream sampleInfo; sampleInfo << recordingIndex; sampleInfo << ". \x8E REC"; - int textWidth = Graphics::textwidth((char*)sampleInfo.str().c_str()); + int textWidth = Graphics::textwidth(sampleInfo.str()); g->fillrect(XRES-20-textWidth, 12, textWidth+8, 15, 0, 0, 0, 255*0.5); - g->drawtext(XRES-16-textWidth, 16, (const char*)sampleInfo.str().c_str(), 255, 50, 20, 255); + g->drawtext(XRES-16-textWidth, 16, sampleInfo.str(), 255, 50, 20, 255); } else if(showHud) { @@ -2281,7 +2280,7 @@ void GameView::OnDraw() alpha = 255-toolTipPresence*3; if (alpha < 50) alpha = 50; - std::stringstream sampleInfo; + String::Stream sampleInfo; sampleInfo.precision(2); int type = sample.particle.type; @@ -2295,15 +2294,15 @@ void GameView::OnDraw() if (showDebug) { if (type == PT_LAVA && c->IsValidElement(ctype)) - sampleInfo << "Molten " << c->ElementResolve(ctype, -1); + sampleInfo << "Molten " << c->ElementResolve(ctype, -1).FromAscii(); else if ((type == PT_PIPE || type == PT_PPIP) && c->IsValidElement(ctype)) - sampleInfo << c->ElementResolve(type, -1) << " with " << c->ElementResolve(ctype, (int)sample.particle.pavg[1]); + sampleInfo << c->ElementResolve(type, -1).FromAscii() << " with " << c->ElementResolve(ctype, (int)sample.particle.pavg[1]).FromAscii(); else if (type == PT_LIFE) - sampleInfo << c->ElementResolve(type, ctype); + sampleInfo << c->ElementResolve(type, ctype).FromAscii(); else if (type == PT_FILT) { - sampleInfo << c->ElementResolve(type, ctype); - const char* filtModes[] = {"set colour", "AND", "OR", "subtract colour", "red shift", "blue shift", "no effect", "XOR", "NOT", "old QRTZ scattering", "variable red shift", "variable blue shift"}; + sampleInfo << c->ElementResolve(type, ctype).FromAscii(); + String filtModes[] = {"set colour", "AND", "OR", "subtract colour", "red shift", "blue shift", "no effect", "XOR", "NOT", "old QRTZ scattering", "variable red shift", "variable blue shift"}; if (sample.particle.tmp>=0 && sample.particle.tmp<=11) sampleInfo << " (" << filtModes[sample.particle.tmp] << ")"; else @@ -2311,14 +2310,14 @@ void GameView::OnDraw() } else { - sampleInfo << c->ElementResolve(type, ctype); + sampleInfo << c->ElementResolve(type, ctype).FromAscii(); if (wavelengthGfx) sampleInfo << " (" << ctype << ")"; // Some elements store extra LIFE info in upper bits of ctype, instead of tmp/tmp2 else if (type == PT_CRAY || type == PT_DRAY || type == PT_CONV) - sampleInfo << " (" << c->ElementResolve(TYP(ctype), ID(ctype)) << ")"; + sampleInfo << " (" << c->ElementResolve(TYP(ctype), ID(ctype)).FromAscii() << ")"; else if (c->IsValidElement(ctype)) - sampleInfo << " (" << c->ElementResolve(ctype, -1) << ")"; + sampleInfo << " (" << c->ElementResolve(ctype, -1).FromAscii() << ")"; else sampleInfo << " ()"; } @@ -2336,13 +2335,13 @@ void GameView::OnDraw() else { if (type == PT_LAVA && c->IsValidElement(ctype)) - sampleInfo << "Molten " << c->ElementResolve(ctype, -1); + sampleInfo << "Molten " << c->ElementResolve(ctype, -1).FromAscii(); else if ((type == PT_PIPE || type == PT_PPIP) && c->IsValidElement(ctype)) - sampleInfo << c->ElementResolve(type, -1) << " with " << c->ElementResolve(ctype, (int)sample.particle.pavg[1]); + sampleInfo << c->ElementResolve(type, -1).FromAscii() << " with " << c->ElementResolve(ctype, (int)sample.particle.pavg[1]).FromAscii(); else if (type == PT_LIFE) - sampleInfo << c->ElementResolve(type, ctype); + sampleInfo << c->ElementResolve(type, ctype).FromAscii(); else - sampleInfo << c->ElementResolve(type, ctype); + sampleInfo << c->ElementResolve(type, ctype).FromAscii(); sampleInfo << ", Temp: " << std::fixed << sample.particle.temp - 273.15f << " C"; sampleInfo << ", Pressure: " << std::fixed << sample.AirPressure; } @@ -2361,9 +2360,9 @@ void GameView::OnDraw() sampleInfo << "Empty"; } - int textWidth = Graphics::textwidth((char*)sampleInfo.str().c_str()); + int textWidth = Graphics::textwidth(sampleInfo.str()); g->fillrect(XRES-20-textWidth, 12, textWidth+8, 15, 0, 0, 0, alpha*0.5f); - g->drawtext(XRES-16-textWidth, 16, (const char*)sampleInfo.str().c_str(), 255, 255, 255, alpha*0.75f); + g->drawtext(XRES-16-textWidth, 16, sampleInfo.str(), 255, 255, 255, alpha*0.75f); #ifndef OGLI if (wavelengthGfx) @@ -2404,7 +2403,7 @@ void GameView::OnDraw() if (showDebug) { - sampleInfo.str(std::string()); + sampleInfo.str(String()); if (type) sampleInfo << "#" << sample.ParticleID << ", "; @@ -2417,16 +2416,16 @@ void GameView::OnDraw() if (c->GetAHeatEnable()) sampleInfo << ", AHeat: " << std::fixed << sample.AirTemperature -273.15f << " C"; - textWidth = Graphics::textwidth((char*)sampleInfo.str().c_str()); + textWidth = Graphics::textwidth(sampleInfo.str()); g->fillrect(XRES-20-textWidth, 27, textWidth+8, 14, 0, 0, 0, alpha*0.5f); - g->drawtext(XRES-16-textWidth, 30, (const char*)sampleInfo.str().c_str(), 255, 255, 255, alpha*0.75f); + g->drawtext(XRES-16-textWidth, 30, sampleInfo.str(), 255, 255, 255, alpha*0.75f); } } if(showHud && introText < 51) { //FPS and some version info - std::stringstream fpsInfo; + String::Stream fpsInfo; fpsInfo.precision(2); fpsInfo << "FPS: " << std::fixed << ui::Engine::Ref().GetFps(); #ifdef DEBUG @@ -2449,37 +2448,37 @@ void GameView::OnDraw() if (ren && ren->findingElement) fpsInfo << " [FIND]"; - int textWidth = Graphics::textwidth((char*)fpsInfo.str().c_str()); + int textWidth = Graphics::textwidth(fpsInfo.str()); int alpha = 255-introText*5; g->fillrect(12, 12, textWidth+8, 15, 0, 0, 0, alpha*0.5); - g->drawtext(16, 16, (const char*)fpsInfo.str().c_str(), 32, 216, 255, alpha*0.75); + g->drawtext(16, 16, fpsInfo.str(), 32, 216, 255, alpha*0.75); } //Tooltips if(infoTipPresence) { int infoTipAlpha = (infoTipPresence>50?50:infoTipPresence)*5; - g->drawtext_outline((XRES-Graphics::textwidth((char*)infoTip.c_str()))/2, (YRES/2)-2, (char*)infoTip.c_str(), 255, 255, 255, infoTipAlpha); + g->drawtext_outline((XRES-Graphics::textwidth(infoTip))/2, (YRES/2)-2, infoTip, 255, 255, 255, infoTipAlpha); } if(toolTipPresence && toolTipPosition.X!=-1 && toolTipPosition.Y!=-1 && toolTip.length()) { if (toolTipPosition.Y == Size.Y-MENUSIZE-10) - g->drawtext_outline(toolTipPosition.X, toolTipPosition.Y, (char*)toolTip.c_str(), 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); + g->drawtext_outline(toolTipPosition.X, toolTipPosition.Y, toolTip, 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); else - g->drawtext(toolTipPosition.X, toolTipPosition.Y, (char*)toolTip.c_str(), 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); + g->drawtext(toolTipPosition.X, toolTipPosition.Y, toolTip, 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); } if(buttonTipShow > 0) { - g->drawtext(16, Size.Y-MENUSIZE-24, (char*)buttonTip.c_str(), 255, 255, 255, buttonTipShow>51?255:buttonTipShow*5); + g->drawtext(16, Size.Y-MENUSIZE-24, buttonTip, 255, 255, 255, buttonTipShow>51?255:buttonTipShow*5); } //Introduction text if(introText) { g->fillrect(0, 0, WINDOWW, WINDOWH, 0, 0, 0, introText>51?102:introText*2); - g->drawtext(16, 20, (char*)introTextMessage.c_str(), 255, 255, 255, introText>51?255:introText*5); + g->drawtext(16, 20, introTextMessage, 255, 255, 255, introText>51?255:introText*5); } // Clear menu areas, to ensure particle graphics don't overlap diff --git a/src/gui/game/GameView.h b/src/gui/game/GameView.h index d94b927cb..7c25341ba 100644 --- a/src/gui/game/GameView.h +++ b/src/gui/game/GameView.h @@ -4,7 +4,7 @@ #include #include #include -#include +#include "common/String.h" #include "GameController.h" #include "GameModel.h" #include "gui/interface/Window.h" @@ -54,16 +54,16 @@ private: int lastMenu; int toolTipPresence; - std::string toolTip; + String toolTip; bool isToolTipFadingIn; ui::Point toolTipPosition; int infoTipPresence; - std::string infoTip; + String infoTip; int buttonTipShow; - std::string buttonTip; + String buttonTip; bool isButtonTipFadingIn; int introText; - std::string introTextMessage; + String introTextMessage; bool doScreenshot; int screenshotIndex; @@ -80,7 +80,7 @@ private: vector menuButtons; vector toolButtons; vector notificationComponents; - deque > logEntries; + deque > logEntries; ui::Button * scrollBar; ui::Button * searchButton; ui::Button * reloadButton; @@ -178,14 +178,14 @@ public: void NotifyColourActivePresetChanged(GameModel * sender); void NotifyPlaceSaveChanged(GameModel * sender); void NotifyNotificationsChanged(GameModel * sender); - void NotifyLogChanged(GameModel * sender, string entry); + void NotifyLogChanged(GameModel * sender, String entry); void NotifyToolTipChanged(GameModel * sender); void NotifyInfoTipChanged(GameModel * sender); void NotifyQuickOptionsChanged(GameModel * sender); void NotifyLastToolChanged(GameModel * sender); - virtual void ToolTip(ui::Point senderPosition, std::string toolTip); + virtual void ToolTip(ui::Point senderPosition, String toolTip); virtual void OnMouseMove(int x, int y, int dx, int dy); virtual void OnMouseDown(int x, int y, unsigned button); diff --git a/src/gui/game/Menu.h b/src/gui/game/Menu.h index 0b6292bea..66543b7ef 100644 --- a/src/gui/game/Menu.h +++ b/src/gui/game/Menu.h @@ -1,19 +1,20 @@ #ifndef MENU_H_ #define MENU_H_ +#include "common/String.h" #include "Tool.h" class Menu { - char icon; - string description; - vector tools; + String::value_type icon; + String description; + std::vector tools; bool visible; public: - Menu(char icon_, string description_, int visible_): + Menu(String::value_type icon_, String description_, int visible_): icon(icon_), description(description_), - tools(vector()), + tools(std::vector()), visible(visible_ ? true : false) { @@ -28,17 +29,17 @@ public: tools.clear(); } - vector GetToolList() + std::vector GetToolList() { return tools; } - char GetIcon() + String::value_type GetIcon() { return icon; } - string GetDescription() + String GetDescription() { return description; } diff --git a/src/gui/game/Notification.h b/src/gui/game/Notification.h index b2bf6f81f..dfa21d604 100644 --- a/src/gui/game/Notification.h +++ b/src/gui/game/Notification.h @@ -1,14 +1,14 @@ #ifndef NOTIFICATION_H_ #define NOTIFICATION_H_ -#include +#include "common/String.h" class Notification { public: - Notification(std::string message) : Message(message) {} + Notification(String message) : Message(message) {} virtual ~Notification() {}; - std::string Message; + String Message; virtual void Action() { } }; diff --git a/src/gui/game/PropertyTool.cpp b/src/gui/game/PropertyTool.cpp index 5e7175e93..2491cb906 100644 --- a/src/gui/game/PropertyTool.cpp +++ b/src/gui/game/PropertyTool.cpp @@ -1,5 +1,4 @@ #include -#include #include "Tool.h" #include "client/Client.h" #include "gui/Style.h" @@ -69,7 +68,7 @@ sim(sim_) PropertyWindow * w; public: PropertyChanged(PropertyWindow * w): w(w) { } - virtual void OptionChanged(ui::DropDown * sender, std::pair option) + virtual void OptionChanged(ui::DropDown * sender, std::pair option) { w->FocusComponent(w->textField); } @@ -79,7 +78,7 @@ sim(sim_) AddComponent(property); for (size_t i = 0; i < properties.size(); i++) { - property->AddOption(std::pair(properties[i].Name, i)); + property->AddOption(std::pair(properties[i].Name.FromAscii(), i)); } property->SetOption(Client::Ref().GetPrefInteger("Prop.Type", 0)); @@ -97,7 +96,7 @@ void PropertyWindow::SetProperty() { if(property->GetOption().second!=-1 && textField->GetText().length() > 0) { - std::string value = textField->GetText(); + String value = textField->GetText(); try { switch(properties[property->GetOption().second].Type) { @@ -108,23 +107,23 @@ void PropertyWindow::SetProperty() if(value.length() > 2 && value.substr(0, 2) == "0x") { //0xC0FFEE - std::stringstream buffer; - buffer.exceptions(std::stringstream::failbit | std::stringstream::badbit); + String::Stream buffer; + buffer.exceptions(String::Stream::failbit | String::Stream::badbit); buffer << std::hex << value.substr(2); buffer >> v; } else if(value.length() > 1 && value[0] == '#') { //#C0FFEE - std::stringstream buffer; - buffer.exceptions(std::stringstream::failbit | std::stringstream::badbit); + String::Stream buffer; + buffer.exceptions(String::Stream::failbit | String::Stream::badbit); buffer << std::hex << value.substr(1); buffer >> v; } else { int type; - if (properties[property->GetOption().second].Type == StructProperty::ParticleType && (type = sim->GetParticleType(value)) != -1) + if (properties[property->GetOption().second].Type == StructProperty::ParticleType && (type = sim->GetParticleType(value.ToUtf8())) != -1) { v = type; @@ -134,8 +133,8 @@ void PropertyWindow::SetProperty() } else { - std::stringstream buffer(value); - buffer.exceptions(std::stringstream::failbit | std::stringstream::badbit); + String::Stream buffer(value); + buffer.exceptions(String::Stream::failbit | String::Stream::badbit); buffer >> v; } } @@ -159,23 +158,23 @@ void PropertyWindow::SetProperty() if(value.length() > 2 && value.substr(0, 2) == "0x") { //0xC0FFEE - std::stringstream buffer; - buffer.exceptions(std::stringstream::failbit | std::stringstream::badbit); + String::Stream buffer; + buffer.exceptions(String::Stream::failbit | String::Stream::badbit); buffer << std::hex << value.substr(2); buffer >> v; } else if(value.length() > 1 && value[0] == '#') { //#C0FFEE - std::stringstream buffer; - buffer.exceptions(std::stringstream::failbit | std::stringstream::badbit); + String::Stream buffer; + buffer.exceptions(String::Stream::failbit | String::Stream::badbit); buffer << std::hex << value.substr(1); buffer >> v; } else { - std::stringstream buffer(value); - buffer.exceptions(std::stringstream::failbit | std::stringstream::badbit); + String::Stream buffer(value); + buffer.exceptions(String::Stream::failbit | String::Stream::badbit); buffer >> v; } #ifdef DEBUG @@ -186,8 +185,8 @@ void PropertyWindow::SetProperty() } case StructProperty::Float: { - std::stringstream buffer(value); - buffer.exceptions(std::stringstream::failbit | std::stringstream::badbit); + String::Stream buffer(value); + buffer.exceptions(String::Stream::failbit | String::Stream::badbit); buffer >> tool->propValue.Float; if (properties[property->GetOption().second].Name == "temp" && value.length()) { @@ -212,7 +211,7 @@ void PropertyWindow::SetProperty() return; } Client::Ref().SetPref("Prop.Type", property->GetOption().second); - Client::Ref().SetPref("Prop.Value", textField->GetText()); + Client::Ref().SetPrefUnicode("Prop.Value", textField->GetText()); } } diff --git a/src/gui/game/QuickOption.h b/src/gui/game/QuickOption.h index fd896d6b8..688acc784 100644 --- a/src/gui/game/QuickOption.h +++ b/src/gui/game/QuickOption.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "common/String.h" #include class GameModel; @@ -23,9 +23,9 @@ protected: std::vector listeners; GameModel * m; Type type; - std::string icon; - std::string description; - QuickOption(std::string icon, std::string description, GameModel * m, Type type) : + String icon; + String description; + QuickOption(String icon, String description, GameModel * m, Type type) : m(m), type(type), icon(icon), @@ -57,10 +57,10 @@ public: virtual int GetMutli() { return 0;} virtual int GetMultiCount() { return 0;} - std::string GetIcon() { return icon; } - void SetIcon(std::string icon) { this->icon = icon; } - std::string GetDescription() { return description; } - void SetDescription(std::string description) { this->description = description; } + String GetIcon() { return icon; } + void SetIcon(String icon) { this->icon = icon; } + String GetDescription() { return description; } + void SetDescription(String description) { this->description = description; } void Perform() { perform(); diff --git a/src/gui/game/RenderPreset.h b/src/gui/game/RenderPreset.h index 91689c7ad..301d16ea5 100644 --- a/src/gui/game/RenderPreset.h +++ b/src/gui/game/RenderPreset.h @@ -3,13 +3,13 @@ class RenderPreset { public: - std::string Name; + String Name; std::vector RenderModes; std::vector DisplayModes; unsigned int ColourMode; RenderPreset(): Name(""), ColourMode(0) {} - RenderPreset(std::string name, std::vector renderModes, std::vector displayModes, unsigned int colourMode): + RenderPreset(String name, std::vector renderModes, std::vector displayModes, unsigned int colourMode): Name(name), RenderModes(renderModes), DisplayModes(displayModes), diff --git a/src/gui/game/SignTool.cpp b/src/gui/game/SignTool.cpp index 50a6de564..011923356 100644 --- a/src/gui/game/SignTool.cpp +++ b/src/gui/game/SignTool.cpp @@ -128,10 +128,10 @@ SignWindow::SignWindow(SignTool * tool_, Simulation * sim_, int signID_, ui::Poi justification = new ui::DropDown(ui::Point(52, 48), ui::Point(50, 16)); AddComponent(justification); - justification->AddOption(std::pair("\xA0 Left", (int)sign::Left)); - justification->AddOption(std::pair("\x9E Middle", (int)sign::Middle)); - justification->AddOption(std::pair("\x9F Right", (int)sign::Right)); - justification->AddOption(std::pair("\x9D None", (int)sign::None)); + justification->AddOption(std::pair("\xA0 Left", (int)sign::Left)); + justification->AddOption(std::pair("\x9E Middle", (int)sign::Middle)); + justification->AddOption(std::pair("\x9F Right", (int)sign::Right)); + justification->AddOption(std::pair("\x9D None", (int)sign::None)); justification->SetOption(1); justification->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; @@ -181,9 +181,9 @@ void SignWindow::DoDraw() { sign & currentSign = *iter; int x, y, w, h, dx, dy; - char type = 0; + String::value_type type = 0; Graphics * g = GetGraphics(); - std::string text = currentSign.getText(sim); + String text = currentSign.getText(sim); sign::splitsign(currentSign.text, &type); currentSign.pos(text, x, y, w, h); g->clearrect(x, y, w+1, h); diff --git a/src/gui/game/Tool.cpp b/src/gui/game/Tool.cpp index 399a518a6..a28d73c91 100644 --- a/src/gui/game/Tool.cpp +++ b/src/gui/game/Tool.cpp @@ -1,4 +1,4 @@ -#include +#include "common/String.h" #include "Tool.h" #include "gui/game/Brush.h" @@ -6,7 +6,7 @@ using namespace std; -Tool::Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int)): +Tool::Tool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int)): textureGen(textureGen), toolID(id), toolName(name), @@ -32,9 +32,9 @@ void Tool::SetTextureGen(VideoBuffer * (*textureGen)(int, int, int)) { this->textureGen = textureGen; } -std::string Tool::GetIdentifier() { return identifier; } -string Tool::GetName() { return toolName; } -string Tool::GetDescription() { return toolDescription; } +ByteString Tool::GetIdentifier() { return identifier; } +ByteString Tool::GetName() { return toolName; } +String Tool::GetDescription() { return toolDescription; } Tool::~Tool() {} void Tool::Click(Simulation * sim, Brush * brush, ui::Point position) { } @@ -50,7 +50,7 @@ void Tool::DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Po void Tool::DrawFill(Simulation * sim, Brush * brush, ui::Point position) {} -ElementTool::ElementTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int)): +ElementTool::ElementTool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int)): Tool(id, name, description, r, g, b, identifier, textureGen) { } @@ -69,7 +69,7 @@ void ElementTool::DrawFill(Simulation * sim, Brush * brush, ui::Point position) } -WallTool::WallTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int)): +WallTool::WallTool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int)): Tool(id, name, description, r, g, b, identifier, textureGen) { blocky = true; @@ -110,7 +110,7 @@ void WallTool::DrawFill(Simulation * sim, Brush * brush, ui::Point position) { sim->FloodWalls(position.X, position.Y, toolID, -1); } -WindTool::WindTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int)): +WindTool::WindTool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int)): Tool(id, name, description, r, g, b, identifier, textureGen) { } diff --git a/src/gui/game/Tool.h b/src/gui/game/Tool.h index 84fb38e85..f0224bf87 100644 --- a/src/gui/game/Tool.h +++ b/src/gui/game/Tool.h @@ -3,8 +3,7 @@ #include -using namespace std; - +#include "common/String.h" #include "gui/interface/Point.h" #include "simulation/StructProperty.h" @@ -17,19 +16,19 @@ class Tool protected: VideoBuffer * (*textureGen)(int, int, int); int toolID; - string toolName; - string toolDescription; + ByteString toolName; + String toolDescription; float strength; bool blocky; - std::string identifier; + ByteString identifier; public: int colRed, colGreen, colBlue; - Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); + Tool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); int GetToolID() { return toolID; } - string GetName(); - string GetDescription(); - std::string GetIdentifier(); + ByteString GetName(); + String GetDescription(); + ByteString GetIdentifier(); int GetBlocky() { return blocky; } void SetStrength(float value) { strength = value; } float GetStrength() { return strength; } @@ -106,7 +105,7 @@ public: class ElementTool: public Tool { public: - ElementTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); + ElementTool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); virtual ~ElementTool(); virtual void Draw(Simulation * sim, Brush * brush, ui::Point position); virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false); @@ -117,7 +116,7 @@ public: class Element_LIGH_Tool: public ElementTool { public: - Element_LIGH_Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL): + Element_LIGH_Tool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL): ElementTool(id, name, description, r, g, b, identifier, textureGen) { } virtual ~Element_LIGH_Tool() { } @@ -130,7 +129,7 @@ public: class Element_TESC_Tool: public ElementTool { public: - Element_TESC_Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL): + Element_TESC_Tool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL): ElementTool(id, name, description, r, g, b, identifier, textureGen) { } virtual ~Element_TESC_Tool() {} @@ -141,7 +140,7 @@ public: class PlopTool: public ElementTool { public: - PlopTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL): + PlopTool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL): ElementTool(id, name, description, r, g, b, identifier, textureGen) { } virtual ~PlopTool() { } @@ -155,7 +154,7 @@ public: class WallTool: public Tool { public: - WallTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); + WallTool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); virtual ~WallTool(); virtual void Draw(Simulation * sim, Brush * brush, ui::Point position); virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false); @@ -166,7 +165,7 @@ public: class WindTool: public Tool { public: - WindTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); + WindTool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); virtual ~WindTool() { } virtual void Draw(Simulation * sim, Brush * brush, ui::Point position) { } virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false); diff --git a/src/gui/game/ToolButton.cpp b/src/gui/game/ToolButton.cpp index 3557dc717..1514d7f4d 100644 --- a/src/gui/game/ToolButton.cpp +++ b/src/gui/game/ToolButton.cpp @@ -4,8 +4,8 @@ #include "gui/interface/Mouse.h" #include "Favorite.h" -ToolButton::ToolButton(ui::Point position, ui::Point size, std::string text_, std::string toolIdentifier, std::string toolTip): - ui::Button(position, size, text_, toolTip), +ToolButton::ToolButton(ui::Point position, ui::Point size, ByteString text_, ByteString toolIdentifier, String toolTip): + ui::Button(position, size, text_.FromAscii(), toolTip), toolIdentifier(toolIdentifier) { SetSelectionState(-1); diff --git a/src/gui/game/ToolButton.h b/src/gui/game/ToolButton.h index d2a8abccb..8953e1dd4 100644 --- a/src/gui/game/ToolButton.h +++ b/src/gui/game/ToolButton.h @@ -6,9 +6,9 @@ class ToolButton: public ui::Button { int currentSelection; - std::string toolIdentifier; + ByteString toolIdentifier; public: - ToolButton(ui::Point position, ui::Point size, std::string text_, std::string toolIdentifier, std::string toolTip = ""); + ToolButton(ui::Point position, ui::Point size, ByteString text_, ByteString toolIdentifier, String toolTip = ""); virtual void OnMouseUnclick(int x, int y, unsigned int button); virtual void OnMouseUp(int x, int y, unsigned int button); virtual void OnMouseClick(int x, int y, unsigned int button); diff --git a/src/gui/interface/AvatarButton.cpp b/src/gui/interface/AvatarButton.cpp index ebe1e572c..cc5da256d 100644 --- a/src/gui/interface/AvatarButton.cpp +++ b/src/gui/interface/AvatarButton.cpp @@ -12,7 +12,7 @@ namespace ui { -AvatarButton::AvatarButton(Point position, Point size, std::string username): +AvatarButton::AvatarButton(Point position, Point size, ByteString username): Component(position, size), avatar(NULL), name(username), diff --git a/src/gui/interface/AvatarButton.h b/src/gui/interface/AvatarButton.h index fcb2e7155..67edfdbbf 100644 --- a/src/gui/interface/AvatarButton.h +++ b/src/gui/interface/AvatarButton.h @@ -1,7 +1,7 @@ #ifndef AVATARBUTTON_H_ #define AVATARBUTTON_H_ -#include +#include "common/String.h" #include "Component.h" #include "graphics/Graphics.h" @@ -21,10 +21,10 @@ public: class AvatarButton : public Component, public RequestListener { VideoBuffer * avatar; - std::string name; + ByteString name; bool tried; public: - AvatarButton(Point position, Point size, std::string username); + AvatarButton(Point position, Point size, ByteString username); virtual ~AvatarButton(); virtual void OnMouseClick(int x, int y, unsigned int button); @@ -42,8 +42,8 @@ public: virtual void DoAction(); - void SetUsername(std::string username) { name = username; } - std::string GetUsername() { return name; } + void SetUsername(ByteString username) { name = username; } + ByteString GetUsername() { return name; } void SetActionCallback(AvatarButtonAction * action); protected: bool isMouseInside, isButtonDown; diff --git a/src/gui/interface/Button.cpp b/src/gui/interface/Button.cpp index 72f44777f..aa7061b25 100644 --- a/src/gui/interface/Button.cpp +++ b/src/gui/interface/Button.cpp @@ -6,7 +6,7 @@ namespace ui { -Button::Button(Point position, Point size, std::string buttonText, std::string toolTip): +Button::Button(Point position, Point size, String buttonText, String toolTip): Component(position, size), ButtonText(buttonText), toolTip(toolTip), @@ -19,14 +19,14 @@ Button::Button(Point position, Point size, std::string buttonText, std::string t TextPosition(ButtonText); } -void Button::TextPosition(std::string ButtonText) +void Button::TextPosition(String ButtonText) { buttonDisplayText = ButtonText; if(buttonDisplayText.length()) { - if(Graphics::textwidth((char *)buttonDisplayText.c_str()) > Size.X - (Appearance.icon? 22 : 0)) + if(Graphics::textwidth(buttonDisplayText) > Size.X - (Appearance.icon? 22 : 0)) { - int position = Graphics::textwidthx((char *)buttonDisplayText.c_str(), Size.X - (Appearance.icon? 38 : 22)); + int position = Graphics::textwidthx(buttonDisplayText, Size.X - (Appearance.icon? 38 : 22)); buttonDisplayText = buttonDisplayText.erase(position, buttonDisplayText.length()-position); buttonDisplayText += "..."; } @@ -41,7 +41,7 @@ void Button::SetIcon(Icon icon) TextPosition(ButtonText); } -void Button::SetText(std::string buttonText) +void Button::SetText(String buttonText) { ButtonText = buttonText; TextPosition(ButtonText); diff --git a/src/gui/interface/Button.h b/src/gui/interface/Button.h index 0cd669ebc..681d43517 100644 --- a/src/gui/interface/Button.h +++ b/src/gui/interface/Button.h @@ -1,7 +1,7 @@ #ifndef BUTTON_H_ #define BUTTON_H_ -#include +#include "common/String.h" #include "Misc.h" #include "Component.h" #include "Colour.h" @@ -21,7 +21,7 @@ public: class Button : public Component { public: - Button(Point position = Point(0, 0), Point size = Point(0, 0), std::string buttonText = "", std::string toolTip = ""); + Button(Point position = Point(0, 0), Point size = Point(0, 0), String buttonText = "", String toolTip = ""); virtual ~Button(); virtual void OnMouseClick(int x, int y, unsigned int button); @@ -34,7 +34,7 @@ public: virtual void Draw(const Point& screenPos); - virtual void TextPosition(std::string); + virtual void TextPosition(String); inline bool GetState() { return state; } virtual void DoAction(); //action of button what ever it may be virtual void DoAltAction(); //action of button what ever it may be @@ -44,15 +44,15 @@ public: void SetToggleState(bool state); void SetActionCallback(ButtonAction * action); ButtonAction * GetActionCallback() { return actionCallback; } - void SetText(std::string buttonText); + void SetText(String buttonText); void SetIcon(Icon icon); - inline std::string GetText() { return ButtonText; } - void SetToolTip(std::string newToolTip) { toolTip = newToolTip; } + inline String GetText() { return ButtonText; } + void SetToolTip(String newToolTip) { toolTip = newToolTip; } protected: - std::string ButtonText; - std::string toolTip; - std::string buttonDisplayText; + String ButtonText; + String toolTip; + String buttonDisplayText; bool isButtonDown, isAltButtonDown, state, isMouseInside, isTogglable, toggle; ButtonAction * actionCallback; diff --git a/src/gui/interface/Checkbox.cpp b/src/gui/interface/Checkbox.cpp index 8dc1737b8..36db2e90e 100644 --- a/src/gui/interface/Checkbox.cpp +++ b/src/gui/interface/Checkbox.cpp @@ -4,7 +4,7 @@ using namespace ui; -Checkbox::Checkbox(ui::Point position, ui::Point size, std::string text, std::string toolTip): +Checkbox::Checkbox(ui::Point position, ui::Point size, String text, String toolTip): Component(position, size), text(text), toolTip(toolTip), @@ -15,12 +15,12 @@ Checkbox::Checkbox(ui::Point position, ui::Point size, std::string text, std::st } -void Checkbox::SetText(std::string text) +void Checkbox::SetText(String text) { this->text = text; } -std::string Checkbox::GetText() +String Checkbox::GetText() { return text; } diff --git a/src/gui/interface/Checkbox.h b/src/gui/interface/Checkbox.h index 4877ade1b..5d016ae86 100644 --- a/src/gui/interface/Checkbox.h +++ b/src/gui/interface/Checkbox.h @@ -1,7 +1,7 @@ #ifndef CHECKBOX_H_ #define CHECKBOX_H_ -#include +#include "common/String.h" #include "Component.h" namespace ui { @@ -13,15 +13,15 @@ public: virtual ~CheckboxAction() {} }; class Checkbox: public ui::Component { - std::string text; - std::string toolTip; + String text; + String toolTip; bool checked; bool isMouseOver; CheckboxAction * actionCallback; public: - Checkbox(ui::Point position, ui::Point size, std::string text, std::string toolTip); - void SetText(std::string text); - std::string GetText(); + Checkbox(ui::Point position, ui::Point size, String text, String toolTip); + void SetText(String text); + String GetText(); void SetIcon(Icon icon); void Draw(const Point& screenPos); virtual void OnMouseEnter(int x, int y); diff --git a/src/gui/interface/Component.cpp b/src/gui/interface/Component.cpp index 2678f1b2c..e70373d70 100644 --- a/src/gui/interface/Component.cpp +++ b/src/gui/interface/Component.cpp @@ -62,13 +62,13 @@ void Component::Refresh() drawn = false; } -void Component::TextPosition(std::string displayText) +void Component::TextPosition(String displayText) { textPosition = ui::Point(0, 0); int textWidth, textHeight = 10; - Graphics::textsize((char*)displayText.c_str(), textWidth, textHeight); + Graphics::textsize(displayText, textWidth, textHeight); textSize.X = textWidth; textSize.Y = textHeight; textHeight-=3; textWidth-=1; diff --git a/src/gui/interface/Component.h b/src/gui/interface/Component.h index c33e06f29..b4848ddfc 100644 --- a/src/gui/interface/Component.h +++ b/src/gui/interface/Component.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "common/String.h" #include "common/tpt-compat.h" #include "Appearance.h" #include "Point.h" @@ -49,7 +49,7 @@ namespace ui ui::Appearance Appearance; //virtual void SetAppearance(ui::Appearance); //ui::Appearance GetAppearance(); - virtual void TextPosition(std::string); + virtual void TextPosition(String); void Refresh(); diff --git a/src/gui/interface/ContextMenu.cpp b/src/gui/interface/ContextMenu.cpp index 32faecba1..d4b89c78e 100644 --- a/src/gui/interface/ContextMenu.cpp +++ b/src/gui/interface/ContextMenu.cpp @@ -70,7 +70,7 @@ void ContextMenu::OnMouseDown(int x, int y, unsigned button) CloseActiveWindow(); } -void ContextMenu::SetItem(int id, std::string text) +void ContextMenu::SetItem(int id, String text) { for (size_t i = 0; i < items.size(); i++) { diff --git a/src/gui/interface/ContextMenu.h b/src/gui/interface/ContextMenu.h index bc6a51004..64b6d8109 100644 --- a/src/gui/interface/ContextMenu.h +++ b/src/gui/interface/ContextMenu.h @@ -12,9 +12,9 @@ class ContextMenuItem { public: int ID; - std::string Text; + String Text; bool Enabled; - ContextMenuItem(std::string text, int id, bool enabled) : ID(id), Text(text), Enabled(enabled) {} + ContextMenuItem(String text, int id, bool enabled) : ID(id), Text(text), Enabled(enabled) {} }; class ContextMenu: public ui::Window, public ButtonAction { @@ -28,7 +28,7 @@ public: virtual void ActionCallbackItem(ui::Button *sender, int item); virtual void AddItem(ContextMenuItem item); virtual void RemoveItem(int id); - virtual void SetItem(int id, std::string text); + virtual void SetItem(int id, String text); virtual void Show(ui::Point position); virtual void OnDraw(); virtual void OnMouseDown(int x, int y, unsigned button); diff --git a/src/gui/interface/CopyTextButton.cpp b/src/gui/interface/CopyTextButton.cpp index dda5f20b7..bf96d8724 100644 --- a/src/gui/interface/CopyTextButton.cpp +++ b/src/gui/interface/CopyTextButton.cpp @@ -5,7 +5,7 @@ namespace ui { - CopyTextButton::CopyTextButton(Point position, Point size, std::string buttonText, Label *copyTextLabel_): + CopyTextButton::CopyTextButton(Point position, Point size, String buttonText, Label *copyTextLabel_): Button(position, size, buttonText) { copyTextLabel = copyTextLabel_; @@ -20,7 +20,7 @@ namespace ui void CopyTextButton::OnMouseClick(int x, int y, unsigned int button) { ui::Button::OnMouseClick(x, y, button); - ClipboardPush(ButtonText); + ClipboardPush(ButtonText.ToUtf8()); copyTextLabel->SetText("Copied!"); diff --git a/src/gui/interface/CopyTextButton.h b/src/gui/interface/CopyTextButton.h index 39e42802e..4002b19ef 100644 --- a/src/gui/interface/CopyTextButton.h +++ b/src/gui/interface/CopyTextButton.h @@ -10,7 +10,7 @@ class CopyTextButton : public Button { ui::Label *copyTextLabel; public: - CopyTextButton(Point position, Point size, std::string buttonText, Label *copyTextLabel_); + CopyTextButton(Point position, Point size, String buttonText, Label *copyTextLabel_); virtual void OnMouseClick(int x, int y, unsigned int button); diff --git a/src/gui/interface/DropDown.cpp b/src/gui/interface/DropDown.cpp index 879bea8ca..f91ba5891 100644 --- a/src/gui/interface/DropDown.cpp +++ b/src/gui/interface/DropDown.cpp @@ -18,9 +18,9 @@ public: class ItemSelectedAction: public ButtonAction { DropDownWindow * window; - std::string option; + String option; public: - ItemSelectedAction(DropDownWindow * window, std::string option): window(window), option(option) { } + ItemSelectedAction(DropDownWindow * window, String option): window(window), option(option) { } virtual void ActionCallback(ui::Button *sender) { window->CloseActiveWindow(); @@ -50,7 +50,7 @@ public: Graphics * g = GetGraphics(); g->clearrect(Position.X, Position.Y, Size.X, Size.Y); } - void setOption(std::string option) + void setOption(String option) { dropDown->SetOption(option); if (dropDown->callback) @@ -129,16 +129,16 @@ void DropDown::OnMouseLeave(int x, int y) { isMouseInside = false; } - std::pair DropDown::GetOption() + std::pair DropDown::GetOption() { if(optionIndex!=-1) { return options[optionIndex]; } - return std::pair("", -1); + return std::pair("", -1); } - void DropDown::SetOption(std::string option) + void DropDown::SetOption(String option) { for (size_t i = 0; i < options.size(); i++) { @@ -162,7 +162,7 @@ void DropDown::OnMouseLeave(int x, int y) } } } - void DropDown::AddOption(std::pair option) + void DropDown::AddOption(std::pair option) { for (size_t i = 0; i < options.size(); i++) { @@ -171,7 +171,7 @@ void DropDown::OnMouseLeave(int x, int y) } options.push_back(option); } - void DropDown::RemoveOption(std::string option) + void DropDown::RemoveOption(String option) { start: for (size_t i = 0; i < options.size(); i++) @@ -185,7 +185,7 @@ void DropDown::OnMouseLeave(int x, int y) } } } - void DropDown::SetOptions(std::vector > options) + void DropDown::SetOptions(std::vector > options) { this->options = options; } diff --git a/src/gui/interface/DropDown.h b/src/gui/interface/DropDown.h index c13fdf624..8dddd0481 100644 --- a/src/gui/interface/DropDown.h +++ b/src/gui/interface/DropDown.h @@ -12,7 +12,7 @@ class DropDownWindow; class DropDownAction { public: - virtual void OptionChanged(DropDown * sender, std::pair newOption) {} + virtual void OptionChanged(DropDown * sender, std::pair newOption) {} virtual ~DropDownAction() {} }; class DropDown: public ui::Component { @@ -20,15 +20,15 @@ class DropDown: public ui::Component { bool isMouseInside; int optionIndex; DropDownAction * callback; - std::vector > options; + std::vector > options; public: DropDown(Point position, Point size); - std::pair GetOption(); + std::pair GetOption(); void SetOption(int option); - void SetOption(std::string option); - void AddOption(std::pair option); - void RemoveOption(std::string option); - void SetOptions(std::vector > options); + void SetOption(String option); + void AddOption(std::pair option); + void RemoveOption(String option); + void SetOptions(std::vector > options); void SetActionCallback(DropDownAction * action) { callback = action;} virtual void Draw(const Point& screenPos); virtual void OnMouseClick(int x, int y, unsigned int button); diff --git a/src/gui/interface/Label.cpp b/src/gui/interface/Label.cpp index e80bd77bc..a790ed718 100644 --- a/src/gui/interface/Label.cpp +++ b/src/gui/interface/Label.cpp @@ -1,4 +1,3 @@ -#include #include "Config.h" #include "Format.h" #include "Point.h" @@ -11,7 +10,7 @@ using namespace ui; -Label::Label(Point position, Point size, std::string labelText): +Label::Label(Point position, Point size, String labelText): Component(position, size), text(labelText), textColour(255, 255, 255), @@ -47,7 +46,7 @@ void Label::SetMultiline(bool status) } } -void Label::SetText(std::string text) +void Label::SetText(String text) { this->text = text; if(multiline) @@ -75,16 +74,16 @@ void Label::updateMultiline() int lines = 1; if (text.length()>0) { - char * rawText = new char[text.length()+1]; + String::value_type *rawText = new String::value_type[text.length()+1]; std::copy(text.begin(), text.end(), rawText); rawText[text.length()] = 0; - char c, pc = 0; + String::value_type c, pc = 0; int charIndex = 0; int wordWidth = 0; int lineWidth = 0; - char * wordStart = NULL; + String::value_type *wordStart = NULL; while ((c = rawText[charIndex++])) { switch(c) @@ -129,7 +128,7 @@ void Label::updateMultiline() { Size.Y = lines*12+3; } - textLines = std::string(rawText); + textLines = rawText; delete[] rawText; /*int currentWidth = 0; char * lastSpace = NULL; @@ -170,11 +169,11 @@ void Label::updateMultiline() { Size.Y = 15; } - textLines = std::string(""); + textLines = ""; } } -std::string Label::GetText() +String Label::GetText() { return this->text; } @@ -200,9 +199,9 @@ void Label::OnMouseClick(int x, int y, unsigned button) { selecting = true; if(multiline) - selectionIndex0 = Graphics::CharIndexAtPosition((char*)textLines.c_str(), x-textPosition.X, y-textPosition.Y); + selectionIndex0 = Graphics::CharIndexAtPosition(textLines, x-textPosition.X, y-textPosition.Y); else - selectionIndex0 = Graphics::CharIndexAtPosition((char*)text.c_str(), x-textPosition.X, y-textPosition.Y); + selectionIndex0 = Graphics::CharIndexAtPosition(text, x-textPosition.X, y-textPosition.Y); selectionIndex1 = selectionIndex0; updateSelection(); @@ -211,8 +210,8 @@ void Label::OnMouseClick(int x, int y, unsigned button) void Label::copySelection() { - std::string currentText = text; - std::string copyText; + String currentText = text; + String copyText; if (selectionIndex1 > selectionIndex0) copyText = currentText.substr(selectionIndex0, selectionIndex1-selectionIndex0).c_str(); @@ -222,7 +221,7 @@ void Label::copySelection() return; else copyText = currentText.c_str(); - ClipboardPush(format::CleanString(copyText, false, true, false)); + ClipboardPush(format::CleanString(copyText, false, true, false).ToUtf8()); } void Label::OnMouseUp(int x, int y, unsigned button) @@ -248,9 +247,9 @@ void Label::OnMouseMoved(int localx, int localy, int dx, int dy) if(selecting) { if(multiline) - selectionIndex1 = Graphics::CharIndexAtPosition((char*)textLines.c_str(), localx-textPosition.X, localy-textPosition.Y); + selectionIndex1 = Graphics::CharIndexAtPosition(textLines, localx-textPosition.X, localy-textPosition.Y); else - selectionIndex1 = Graphics::CharIndexAtPosition((char*)text.c_str(), localx-textPosition.X, localy-textPosition.Y); + selectionIndex1 = Graphics::CharIndexAtPosition(text, localx-textPosition.X, localy-textPosition.Y); updateSelection(); } } @@ -297,7 +296,7 @@ void Label::selectAll() void Label::updateSelection() { - std::string currentText; + String currentText; if (selectionIndex0 < 0) selectionIndex0 = 0; if (selectionIndex0 > (int)text.length()) selectionIndex0 = text.length(); @@ -309,7 +308,7 @@ void Label::updateSelection() selectionXH = -1; selectionXL = -1; - textFragments = std::string(currentText); + textFragments = currentText; return; } @@ -319,19 +318,19 @@ void Label::updateSelection() currentText = text; if(selectionIndex1 > selectionIndex0) { - selectionLineH = Graphics::PositionAtCharIndex((char*)currentText.c_str(), selectionIndex1, selectionXH, selectionYH); - selectionLineL = Graphics::PositionAtCharIndex((char*)currentText.c_str(), selectionIndex0, selectionXL, selectionYL); + selectionLineH = Graphics::PositionAtCharIndex(currentText, selectionIndex1, selectionXH, selectionYH); + selectionLineL = Graphics::PositionAtCharIndex(currentText, selectionIndex0, selectionXL, selectionYL); - textFragments = std::string(currentText); + textFragments = currentText; //textFragments.insert(selectionIndex1, "\x0E"); //textFragments.insert(selectionIndex0, "\x0F\x01\x01\x01"); textFragments.insert(selectionIndex1, "\x01"); textFragments.insert(selectionIndex0, "\x01"); } else if(selectionIndex0 > selectionIndex1) { - selectionLineH = Graphics::PositionAtCharIndex((char*)currentText.c_str(), selectionIndex0, selectionXH, selectionYH); - selectionLineL = Graphics::PositionAtCharIndex((char*)currentText.c_str(), selectionIndex1, selectionXL, selectionYL); + selectionLineH = Graphics::PositionAtCharIndex(currentText, selectionIndex0, selectionXH, selectionYH); + selectionLineL = Graphics::PositionAtCharIndex(currentText, selectionIndex1, selectionXL, selectionYL); - textFragments = std::string(currentText); + textFragments = currentText; //textFragments.insert(selectionIndex0, "\x0E"); //textFragments.insert(selectionIndex1, "\x0F\x01\x01\x01"); textFragments.insert(selectionIndex0, "\x01"); @@ -340,21 +339,21 @@ void Label::updateSelection() selectionXH = -1; selectionXL = -1; - textFragments = std::string(currentText); + textFragments = currentText; } if(displayText.length()) { displayText = tDisplayText; if(selectionIndex1 > selectionIndex0) { - int tSelectionIndex1 = Graphics::CharIndexAtPosition((char*)displayText.c_str(), selectionXH, selectionYH); - int tSelectionIndex0 = Graphics::CharIndexAtPosition((char*)displayText.c_str(), selectionXL, selectionYL); + int tSelectionIndex1 = Graphics::CharIndexAtPosition(displayText, selectionXH, selectionYH); + int tSelectionIndex0 = Graphics::CharIndexAtPosition(displayText, selectionXL, selectionYL); displayText.insert(tSelectionIndex1, "\x01"); displayText.insert(tSelectionIndex0, "\x01"); } else if(selectionIndex0 > selectionIndex1) { - int tSelectionIndex0 = Graphics::CharIndexAtPosition((char*)displayText.c_str(), selectionXH, selectionYH); - int tSelectionIndex1 = Graphics::CharIndexAtPosition((char*)displayText.c_str(), selectionXL, selectionYL); + int tSelectionIndex0 = Graphics::CharIndexAtPosition(displayText, selectionXH, selectionYH); + int tSelectionIndex1 = Graphics::CharIndexAtPosition(displayText, selectionXL, selectionYL); displayText.insert(tSelectionIndex0, "\x01"); displayText.insert(tSelectionIndex1, "\x01"); @@ -362,7 +361,7 @@ void Label::updateSelection() } } -void Label::SetDisplayText(std::string newText) +void Label::SetDisplayText(String newText) { ClearSelection(); displayText = tDisplayText = newText; @@ -384,7 +383,7 @@ void Label::Draw(const Point& screenPos) } Graphics * g = GetGraphics(); - std::string cDisplayText = displayText; + String cDisplayText = displayText; if(!cDisplayText.length()) { diff --git a/src/gui/interface/Label.h b/src/gui/interface/Label.h index db276426a..0d3338b84 100644 --- a/src/gui/interface/Label.h +++ b/src/gui/interface/Label.h @@ -1,7 +1,7 @@ #ifndef LABEL_H #define LABEL_H -#include +#include "common/String.h" #include "Component.h" #include "Colour.h" @@ -11,12 +11,12 @@ namespace ui class Label : public Component { protected: - std::string textFragments; - std::string textLines; - std::string displayText; - std::string tDisplayText; + String textFragments; + String textLines; + String displayText; + String tDisplayText; - std::string text; + String text; Colour textColour; int selectionIndex0; int selectionIndex1; @@ -40,16 +40,16 @@ namespace ui virtual void copySelection(); public: - //Label(Window* parent_state, std::string labelText); - Label(Point position, Point size, std::string labelText); - //Label(std::string labelText); + //Label(Window* parent_state, String labelText); + Label(Point position, Point size, String labelText); + //Label(String labelText); virtual ~Label(); virtual void SetMultiline(bool status); - virtual void SetText(std::string text); - virtual void SetDisplayText(std::string newText); - virtual std::string GetText(); + virtual void SetText(String text); + virtual void SetDisplayText(String newText); + virtual String GetText(); virtual bool HasSelection(); virtual void ClearSelection(); diff --git a/src/gui/interface/ProgressBar.cpp b/src/gui/interface/ProgressBar.cpp index 87cc7584a..fb55e7d4b 100644 --- a/src/gui/interface/ProgressBar.cpp +++ b/src/gui/interface/ProgressBar.cpp @@ -5,7 +5,7 @@ using namespace ui; -ProgressBar::ProgressBar(Point position, Point size, int startProgress, std::string startStatus): +ProgressBar::ProgressBar(Point position, Point size, int startProgress, String startStatus): Component(position, size), progress(0), intermediatePos(0.0f), @@ -27,12 +27,12 @@ int ProgressBar::GetProgress() return progress; } -void ProgressBar::SetStatus(std::string status) +void ProgressBar::SetStatus(String status) { progressStatus = status; } -std::string ProgressBar::GetStatus() +String ProgressBar::GetStatus() { return progressStatus; } @@ -70,9 +70,9 @@ void ProgressBar::Draw(const Point & screenPos) } } if(progress<50) - g->drawtext(screenPos.X + ((Size.X-Graphics::textwidth(progressStatus.c_str()))/2), screenPos.Y + (Size.Y-8)/2, progressStatus, 255, 255, 255, 255); + g->drawtext(screenPos.X + ((Size.X-Graphics::textwidth(progressStatus))/2), screenPos.Y + (Size.Y-8)/2, progressStatus, 255, 255, 255, 255); else - g->drawtext(screenPos.X + ((Size.X-Graphics::textwidth(progressStatus.c_str()))/2), screenPos.Y + (Size.Y-8)/2, progressStatus, 0, 0, 0, 255); + g->drawtext(screenPos.X + ((Size.X-Graphics::textwidth(progressStatus))/2), screenPos.Y + (Size.Y-8)/2, progressStatus, 0, 0, 0, 255); } void ProgressBar::Tick(float dt) diff --git a/src/gui/interface/ProgressBar.h b/src/gui/interface/ProgressBar.h index 0efd049d8..855504d77 100644 --- a/src/gui/interface/ProgressBar.h +++ b/src/gui/interface/ProgressBar.h @@ -8,13 +8,13 @@ namespace ui { int progress; float intermediatePos; - std::string progressStatus; + String progressStatus; public: - ProgressBar(Point position, Point size, int startProgress = 0, std::string startStatus = ""); + ProgressBar(Point position, Point size, int startProgress = 0, String startStatus = ""); virtual void SetProgress(int progress); virtual int GetProgress(); - virtual void SetStatus(std::string status); - virtual std::string GetStatus(); + virtual void SetStatus(String status); + virtual String GetStatus(); virtual void Draw(const Point & screenPos); virtual void Tick(float dt); }; diff --git a/src/gui/interface/RichLabel.cpp b/src/gui/interface/RichLabel.cpp index bc6914352..5f9261700 100644 --- a/src/gui/interface/RichLabel.cpp +++ b/src/gui/interface/RichLabel.cpp @@ -10,17 +10,17 @@ using namespace ui; struct RichTextParseException: public std::exception { - std::string message; + String message; public: - RichTextParseException(std::string message_ = "Parse error"): message(message_) {} + RichTextParseException(String message_ = "Parse error"): message(message_) {} const char * what() const throw() { - return message.c_str(); + return message.ToUtf8().c_str(); } ~RichTextParseException() throw() {}; }; -RichLabel::RichLabel(Point position, Point size, std::string labelText): +RichLabel::RichLabel(Point position, Point size, String labelText): Component(position, size), textSource(labelText), displayText("") @@ -45,15 +45,15 @@ void RichLabel::updateRichText() State state = ReadText; int currentDataPos = 0; - char * currentData = new char[textSource.length()+1]; + String::value_type * currentData = new String::value_type[textSource.length()+1]; std::fill(currentData, currentData+textSource.length()+1, 0); int finalTextPos = 0; - char * finalText = new char[textSource.length()+1]; + String::value_type * finalText = new String::value_type[textSource.length()+1]; std::fill(finalText, finalText+textSource.length()+1, 0); int originalTextPos = 0; - char * originalText = new char[textSource.length()+1]; + String::value_type * originalText = new String::value_type[textSource.length()+1]; std::copy(textSource.begin(), textSource.end(), originalText); originalText[textSource.length()] = 0; @@ -82,7 +82,7 @@ void RichLabel::updateRichText() if(stackPos >= 0) { currentData[currentDataPos] = 0; - regionsStack[stackPos].actionData = std::string(currentData); + regionsStack[stackPos].actionData = String(currentData); regions.push_back(regionsStack[stackPos]); stackPos--; } @@ -142,11 +142,11 @@ void RichLabel::updateRichText() throw RichTextParseException("Unclosed region"); finalText[finalTextPos] = 0; - displayText = std::string(finalText); + displayText = String(finalText); } catch (const RichTextParseException & e) { - displayText = "\br[Parse exception: " + std::string(e.what()) + "]"; + displayText = "\br[Parse exception: " + ByteString(e.what()).FromUtf8() + "]"; regions.clear(); } delete[] currentData; @@ -157,18 +157,18 @@ void RichLabel::updateRichText() TextPosition(displayText); } -void RichLabel::SetText(std::string text) +void RichLabel::SetText(String text) { textSource = text; updateRichText(); } -std::string RichLabel::GetDisplayText() +String RichLabel::GetDisplayText() { return displayText; } -std::string RichLabel::GetText() +String RichLabel::GetText() { return textSource; } @@ -182,7 +182,7 @@ void RichLabel::Draw(const Point& screenPos) void RichLabel::OnMouseClick(int x, int y, unsigned button) { - int cursorPosition = Graphics::CharIndexAtPosition((char*)displayText.c_str(), x-textPosition.X, y-textPosition.Y); + int cursorPosition = Graphics::CharIndexAtPosition(displayText, x-textPosition.X, y-textPosition.Y); for(std::vector::iterator iter = regions.begin(), end = regions.end(); iter != end; ++iter) { if((*iter).start <= cursorPosition && (*iter).finish >= cursorPosition) @@ -190,7 +190,7 @@ void RichLabel::OnMouseClick(int x, int y, unsigned button) switch((*iter).action) { case 'a': - Platform::OpenURI((*iter).actionData); + Platform::OpenURI((*iter).actionData.ToUtf8()); break; } } diff --git a/src/gui/interface/RichLabel.h b/src/gui/interface/RichLabel.h index d9682f23b..3a99adf7d 100644 --- a/src/gui/interface/RichLabel.h +++ b/src/gui/interface/RichLabel.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "common/String.h" #include "Component.h" #include "Colour.h" @@ -15,22 +15,22 @@ namespace ui int start; int finish; int action; - std::string actionData; + String actionData; }; - RichLabel(Point position, Point size, std::string richText); + RichLabel(Point position, Point size, String richText); virtual ~RichLabel(); - virtual void SetText(std::string text); - virtual std::string GetDisplayText(); - virtual std::string GetText(); + virtual void SetText(String text); + virtual String GetDisplayText(); + virtual String GetText(); virtual void Draw(const Point& screenPos); virtual void OnMouseClick(int x, int y, unsigned button); protected: - std::string textSource; - std::string displayText; + String textSource; + String displayText; std::vector regions; diff --git a/src/gui/interface/SaveButton.cpp b/src/gui/interface/SaveButton.cpp index da52369a1..813dcb53d 100644 --- a/src/gui/interface/SaveButton.cpp +++ b/src/gui/interface/SaveButton.cpp @@ -31,14 +31,14 @@ SaveButton::SaveButton(Point position, Point size, SaveInfo * save): if(save) { name = save->name; - if(Graphics::textwidth((char *)name.c_str()) > Size.X) + if(Graphics::textwidth(name) > Size.X) { - int position = Graphics::textwidthx((char *)name.c_str(), Size.X - 22); + int position = Graphics::textwidthx(name, Size.X - 22); name = name.erase(position, name.length()-position); name += "..."; } - std::string votes, icon; + String votes, icon; votes = format::NumberToString(save->GetVotesUp()-save->GetVotesDown()); icon += 0xBB; @@ -49,12 +49,12 @@ SaveButton::SaveButton(Point position, Point size, SaveInfo * save): votesBackground = icon; - for (std::string::iterator iter = icon.begin(), end = icon.end(); iter != end; ++iter) + for (String::iterator iter = icon.begin(), end = icon.end(); iter != end; ++iter) *iter -= 14; votesBackground2 = icon; - for (std::string::iterator iter = votes.begin(), end = votes.end(); iter != end; ++iter) + for (String::iterator iter = votes.begin(), end = votes.end(); iter != end; ++iter) if(*iter != '-') *iter += 127; @@ -105,9 +105,9 @@ SaveButton::SaveButton(Point position, Point size, SaveFile * file): if(file) { name = file->GetDisplayName(); - if(Graphics::textwidth((char *)name.c_str()) > Size.X) + if(Graphics::textwidth(name) > Size.X) { - int position = Graphics::textwidthx((char *)name.c_str(), Size.X - 22); + int position = Graphics::textwidthx(name, Size.X - 22); name = name.erase(position, name.length()-position); name += "..."; } @@ -217,17 +217,17 @@ void SaveButton::Draw(const Point& screenPos) } if(isMouseInside && !isMouseInsideAuthor) - g->drawtext(screenPos.X+(Size.X-Graphics::textwidth((char *)name.c_str()))/2, screenPos.Y+Size.Y - 21, name, 255, 255, 255, 255); + g->drawtext(screenPos.X+(Size.X-Graphics::textwidth(name))/2, screenPos.Y+Size.Y - 21, name, 255, 255, 255, 255); else - g->drawtext(screenPos.X+(Size.X-Graphics::textwidth((char *)name.c_str()))/2, screenPos.Y+Size.Y - 21, name, 180, 180, 180, 255); + g->drawtext(screenPos.X+(Size.X-Graphics::textwidth(name))/2, screenPos.Y+Size.Y - 21, name, 180, 180, 180, 255); if(isMouseInsideAuthor) - g->drawtext(screenPos.X+(Size.X-Graphics::textwidth((char *)save->userName.c_str()))/2, screenPos.Y+Size.Y - 10, save->userName, 200, 230, 255, 255); + g->drawtext(screenPos.X+(Size.X-Graphics::textwidth(save->userName.FromUtf8()))/2, screenPos.Y+Size.Y - 10, save->userName.FromUtf8(), 200, 230, 255, 255); else - g->drawtext(screenPos.X+(Size.X-Graphics::textwidth((char *)save->userName.c_str()))/2, screenPos.Y+Size.Y - 10, save->userName, 100, 130, 160, 255); + g->drawtext(screenPos.X+(Size.X-Graphics::textwidth(save->userName.FromUtf8()))/2, screenPos.Y+Size.Y - 10, save->userName.FromUtf8(), 100, 130, 160, 255); if (showVotes)// && !isMouseInside) { - int x = screenPos.X-7+(Size.X-thumbBoxSize.X)/2+thumbBoxSize.X-Graphics::textwidth(votesBackground.c_str()); + int x = screenPos.X-7+(Size.X-thumbBoxSize.X)/2+thumbBoxSize.X-Graphics::textwidth(votesBackground); int y = screenPos.Y-23+(Size.Y-thumbBoxSize.Y)/2+thumbBoxSize.Y; g->drawtext(x, y, votesBackground, 16, 72, 16, 255); g->drawtext(x, y, votesBackground2, 192, 192, 192, 255); @@ -259,11 +259,11 @@ void SaveButton::Draw(const Point& screenPos) if (isMouseInside) { - g->drawtext(screenPos.X+(Size.X-Graphics::textwidth((char *)name.c_str()))/2, screenPos.Y+Size.Y - 21, name, 255, 255, 255, 255); + g->drawtext(screenPos.X+(Size.X-Graphics::textwidth(name))/2, screenPos.Y+Size.Y - 21, name, 255, 255, 255, 255); } else { - g->drawtext(screenPos.X+(Size.X-Graphics::textwidth((char *)name.c_str()))/2, screenPos.Y+Size.Y - 21, name, 180, 180, 180, 255); + g->drawtext(screenPos.X+(Size.X-Graphics::textwidth(name))/2, screenPos.Y+Size.Y - 21, name, 180, 180, 180, 255); } } diff --git a/src/gui/interface/SaveButton.h b/src/gui/interface/SaveButton.h index 4b9682af2..8105ab6e3 100644 --- a/src/gui/interface/SaveButton.h +++ b/src/gui/interface/SaveButton.h @@ -1,7 +1,7 @@ #ifndef SAVEBUTTON_H_ #define SAVEBUTTON_H_ -#include +#include "common/String.h" #include "Component.h" #include "client/SaveFile.h" @@ -28,10 +28,10 @@ class SaveButton : public Component, public RequestListener SaveFile * file; SaveInfo * save; VideoBuffer * thumbnail; - std::string name; - std::string votesString; - std::string votesBackground; - std::string votesBackground2; + String name; + String votesString; + String votesBackground; + String votesBackground2; int voteBarHeightUp; int voteBarHeightDown; bool wantsDraw; diff --git a/src/gui/interface/Textbox.cpp b/src/gui/interface/Textbox.cpp index cd5bb514d..583b3eab4 100644 --- a/src/gui/interface/Textbox.cpp +++ b/src/gui/interface/Textbox.cpp @@ -1,4 +1,4 @@ -#include +#include "common/String.h" #include #include #include "Config.h" @@ -13,11 +13,11 @@ using namespace ui; -Textbox::Textbox(Point position, Point size, std::string textboxText, std::string textboxPlaceholder): +Textbox::Textbox(Point position, Point size, String textboxText, String textboxPlaceholder): Label(position, size, ""), ReadOnly(false), inputType(All), - limit(std::string::npos), + limit(String::npos), keyDown(0), characterDown(0), mouseDown(false), @@ -53,18 +53,18 @@ void Textbox::SetHidden(bool hidden) masked = hidden; } -void Textbox::SetPlaceholder(std::string text) +void Textbox::SetPlaceholder(String text) { placeHolder = text; } -void Textbox::SetText(std::string newText) +void Textbox::SetText(String newText) { backingText = newText; if(masked) { - std::string maskedText = std::string(newText); + String maskedText = newText; std::fill(maskedText.begin(), maskedText.end(), '\x8D'); Label::SetText(maskedText); } @@ -75,7 +75,7 @@ void Textbox::SetText(std::string newText) if(cursor) { - Graphics::PositionAtCharIndex(multiline?((char*)textLines.c_str()):((char*)text.c_str()), cursor, cursorPositionX, cursorPositionY); + Graphics::PositionAtCharIndex(multiline?textLines:text, cursor, cursorPositionX, cursorPositionY); } else { @@ -103,7 +103,7 @@ size_t Textbox::GetLimit() return limit; } -std::string Textbox::GetText() +String Textbox::GetText() { return backingText; } @@ -126,7 +126,7 @@ void Textbox::OnContextMenuAction(int item) void Textbox::resetCursorPosition() { - Graphics::PositionAtCharIndex(multiline?((char*)textLines.c_str()):((char*)text.c_str()), cursor, cursorPositionX, cursorPositionY); + Graphics::PositionAtCharIndex(multiline?textLines:text, cursor, cursorPositionX, cursorPositionY); } void Textbox::TabFocus() @@ -141,8 +141,8 @@ void Textbox::cutSelection() { if (getLowerSelectionBound() < 0 || getHigherSelectionBound() > (int)backingText.length()) return; - std::string toCopy = backingText.substr(getLowerSelectionBound(), getHigherSelectionBound()-getLowerSelectionBound()); - ClipboardPush(format::CleanString(toCopy, false, true, false)); + String toCopy = backingText.substr(getLowerSelectionBound(), getHigherSelectionBound()-getLowerSelectionBound()); + ClipboardPush(format::CleanString(toCopy, false, true, false).ToUtf8()); backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound()); cursor = getLowerSelectionBound(); } @@ -150,7 +150,7 @@ void Textbox::cutSelection() { if (!backingText.length()) return; - ClipboardPush(format::CleanString(backingText, false, true, false)); + ClipboardPush(format::CleanString(backingText, false, true, false).ToUtf8()); backingText.clear(); cursor = 0; } @@ -158,7 +158,7 @@ void Textbox::cutSelection() if(masked) { - std::string maskedText = std::string(backingText); + String maskedText = backingText; std::fill(maskedText.begin(), maskedText.end(), '\x8D'); Label::SetText(maskedText); } @@ -174,7 +174,7 @@ void Textbox::cutSelection() if(cursor) { - Graphics::PositionAtCharIndex(multiline?((char*)textLines.c_str()):((char*)text.c_str()), cursor, cursorPositionX, cursorPositionY); + Graphics::PositionAtCharIndex(multiline?textLines:text, cursor, cursorPositionX, cursorPositionY); } else { @@ -186,7 +186,7 @@ void Textbox::cutSelection() void Textbox::pasteIntoSelection() { - std::string newText = format::CleanString(ClipboardPull(), true, true, inputType != Multiline, inputType == Number || inputType == Numeric); + String newText = format::CleanString(ClipboardPull().FromUtf8(), true, true, inputType != Multiline, inputType == Number || inputType == Numeric); if (HasSelection()) { if (getLowerSelectionBound() < 0 || getHigherSelectionBound() > (int)backingText.length()) @@ -201,14 +201,14 @@ void Textbox::pasteIntoSelection() regionWidth -= Appearance.Margin.Left; regionWidth -= Appearance.Margin.Right; - if (limit != std::string::npos) + if (limit != String::npos) { newText = newText.substr(0, limit-backingText.length()); } - if (!multiline && Graphics::textwidth((char*)std::string(backingText+newText).c_str()) > regionWidth) + if (!multiline && Graphics::textwidth(backingText + newText) > regionWidth) { - int pLimit = regionWidth - Graphics::textwidth((char*)backingText.c_str()); - int cIndex = Graphics::CharIndexAtPosition((char *)newText.c_str(), pLimit, 0); + int pLimit = regionWidth - Graphics::textwidth(backingText); + int cIndex = Graphics::CharIndexAtPosition(newText, pLimit, 0); if (cIndex > 0) newText = newText.substr(0, cIndex); @@ -222,7 +222,7 @@ void Textbox::pasteIntoSelection() if(masked) { - std::string maskedText = std::string(backingText); + String maskedText = backingText; std::fill(maskedText.begin(), maskedText.end(), '\x8D'); Label::SetText(maskedText); } @@ -241,7 +241,7 @@ void Textbox::pasteIntoSelection() if(cursor) { - Graphics::PositionAtCharIndex(multiline?((char*)textLines.c_str()):((char*)text.c_str()), cursor, cursorPositionX, cursorPositionY); + Graphics::PositionAtCharIndex(multiline?textLines:text, cursor, cursorPositionX, cursorPositionY); } else { @@ -362,8 +362,8 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool if (ctrl) { size_t stopChar; - stopChar = backingText.find_first_not_of(" .,!?\n", cursor); - stopChar = backingText.find_first_of(" .,!?\n", stopChar); + stopChar = backingText.find_first_not_of(String(" .,!?\n"), cursor); + stopChar = backingText.find_first_of(String(" .,!?\n"), stopChar); backingText.erase(cursor, stopChar-cursor); } else @@ -388,11 +388,11 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool if (ctrl) { size_t stopChar; - stopChar = backingText.substr(0, cursor).find_last_not_of(" .,!?\n"); + stopChar = backingText.substr(0, cursor).find_last_not_of(String(" .,!?\n")); if (stopChar == backingText.npos) stopChar = -1; else - stopChar = backingText.substr(0, stopChar).find_last_of(" .,!?\n"); + stopChar = backingText.substr(0, stopChar).find_last_of(String(" .,!?\n")); backingText.erase(stopChar+1, cursor-(stopChar+1)); cursor = stopChar+1; } @@ -423,7 +423,7 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool regionWidth -= 13; regionWidth -= Appearance.Margin.Left; regionWidth -= Appearance.Margin.Right; - if ((limit==std::string::npos || backingText.length() < limit) && (Graphics::textwidth((char*)std::string(backingText+char(character)).c_str()) <= regionWidth || multiline)) + if ((limit==String::npos || backingText.length() < limit) && (Graphics::textwidth(backingText + character) <= regionWidth || multiline)) { if (cursor == (int)backingText.length()) { @@ -431,7 +431,7 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool } else { - backingText.insert(cursor, 1, (char)character); + backingText.insert(cursor, 1, String::value_type(character)); } cursor++; } @@ -458,7 +458,7 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool { if (masked) { - std::string maskedText = std::string(backingText); + String maskedText = backingText; std::fill(maskedText.begin(), maskedText.end(), '\x8D'); Label::SetText(maskedText); } @@ -478,7 +478,7 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool if(cursor) { - Graphics::PositionAtCharIndex(multiline?((char*)textLines.c_str()):((char*)text.c_str()), cursor, cursorPositionX, cursorPositionY); + Graphics::PositionAtCharIndex(multiline?textLines:text, cursor, cursorPositionX, cursorPositionY); } else { @@ -494,10 +494,10 @@ void Textbox::OnMouseClick(int x, int y, unsigned button) if (button != SDL_BUTTON_RIGHT) { mouseDown = true; - cursor = Graphics::CharIndexAtPosition(multiline?((char*)textLines.c_str()):((char*)text.c_str()), x-textPosition.X, y-textPosition.Y); + cursor = Graphics::CharIndexAtPosition(multiline?textLines:text, x-textPosition.X, y-textPosition.Y); if(cursor) { - Graphics::PositionAtCharIndex(multiline?((char*)textLines.c_str()):((char*)text.c_str()), cursor, cursorPositionX, cursorPositionY); + Graphics::PositionAtCharIndex(multiline?textLines:text, cursor, cursorPositionX, cursorPositionY); } else { @@ -517,10 +517,10 @@ void Textbox::OnMouseMoved(int localx, int localy, int dx, int dy) { if(mouseDown) { - cursor = Graphics::CharIndexAtPosition(multiline?((char*)textLines.c_str()):((char*)text.c_str()), localx-textPosition.X, localy-textPosition.Y); + cursor = Graphics::CharIndexAtPosition(multiline?textLines:text, localx-textPosition.X, localy-textPosition.Y); if(cursor) { - Graphics::PositionAtCharIndex(multiline?((char*)textLines.c_str()):((char*)text.c_str()), cursor, cursorPositionX, cursorPositionY); + Graphics::PositionAtCharIndex(multiline?textLines:text, cursor, cursorPositionX, cursorPositionY); } else { diff --git a/src/gui/interface/Textbox.h b/src/gui/interface/Textbox.h index f1f62aa1b..f20b8c831 100644 --- a/src/gui/interface/Textbox.h +++ b/src/gui/interface/Textbox.h @@ -1,7 +1,7 @@ #ifndef TEXTBOX_H #define TEXTBOX_H -#include +#include "common/String.h" #include "Label.h" #include "PowderToy.h" @@ -22,13 +22,13 @@ class Textbox : public Label public: bool ReadOnly; enum ValidInput { All, Multiline, Numeric, Number }; // Numeric doesn't delete trailing 0's - Textbox(Point position, Point size, std::string textboxText = "", std::string textboxPlaceholder = ""); + Textbox(Point position, Point size, String textboxText = "", String textboxPlaceholder = ""); virtual ~Textbox(); - virtual void SetText(std::string text); - virtual std::string GetText(); + virtual void SetText(String text); + virtual String GetText(); - virtual void SetPlaceholder(std::string text); + virtual void SetPlaceholder(String text); void SetBorder(bool border) { this->border = border; } void SetHidden(bool hidden); @@ -66,8 +66,8 @@ protected: bool masked, border; int cursor, cursorPositionX, cursorPositionY; TextboxAction *actionCallback; - std::string backingText; - std::string placeHolder; + String backingText; + String placeHolder; virtual void cutSelection(); virtual void pasteIntoSelection(); diff --git a/src/gui/interface/Window.h b/src/gui/interface/Window.h index bb68d438e..200aeb8dd 100644 --- a/src/gui/interface/Window.h +++ b/src/gui/interface/Window.h @@ -1,7 +1,7 @@ #ifndef WINDOW_H #define WINDOW_H -#include +#include "common/String.h" #include #include "common/tpt-compat.h" #include "gui/interface/Point.h" @@ -52,7 +52,7 @@ namespace ui // Remove a component from window. NOTE: This WILL free component from memory. void RemoveComponent(unsigned idx); - virtual void ToolTip(ui::Point senderPosition, std::string toolTip) {} + virtual void ToolTip(ui::Point senderPosition, String toolTip) {} virtual void DoInitialized(); virtual void DoExit(); diff --git a/src/gui/localbrowser/LocalBrowserController.cpp b/src/gui/localbrowser/LocalBrowserController.cpp index eca08222d..709414701 100644 --- a/src/gui/localbrowser/LocalBrowserController.cpp +++ b/src/gui/localbrowser/LocalBrowserController.cpp @@ -1,5 +1,3 @@ -#include - #include "client/Client.h" #include "LocalBrowserController.h" #include "gui/interface/Engine.h" @@ -46,7 +44,7 @@ void LocalBrowserController::RemoveSelected() virtual ~RemoveSelectedConfirmation() { } }; - std::stringstream desc; + String::Stream desc; desc << "Are you sure you want to delete " << browserModel->GetSelected().size() << " stamp"; if(browserModel->GetSelected().size()>1) desc << "s"; @@ -58,16 +56,16 @@ void LocalBrowserController::removeSelectedC() { class RemoveSavesTask : public Task { - std::vector saves; + std::vector saves; LocalBrowserController * c; public: - RemoveSavesTask(LocalBrowserController * c, std::vector saves_) : c(c) { saves = saves_; } + RemoveSavesTask(LocalBrowserController * c, std::vector saves_) : c(c) { saves = saves_; } virtual bool doWork() { for (size_t i = 0; i < saves.size(); i++) { - std::stringstream saveName; - saveName << "Deleting stamp [" << saves[i] << "] ..."; + String::Stream saveName; + saveName << "Deleting stamp [" << saves[i].FromUtf8() << "] ..."; notifyStatus(saveName.str()); Client::Ref().DeleteStamp(saves[i]); notifyProgress((float(i+1)/float(saves.size())*100)); @@ -81,7 +79,7 @@ void LocalBrowserController::removeSelectedC() } }; - std::vector selected = browserModel->GetSelected(); + std::vector selected = browserModel->GetSelected(); new TaskWindow("Removing stamps", new RemoveSavesTask(this, selected)); } @@ -98,7 +96,7 @@ void LocalBrowserController::RescanStamps() virtual ~RescanConfirmation() { } }; - std::stringstream desc; + String::Stream desc; desc << "Rescanning the stamps folder can find stamps added to the stamps folder or recover stamps when the stamps.def file has been lost or damaged. However, be warned that this will mess up the current sorting order"; new ConfirmPrompt("Rescan", desc.str(), new RescanConfirmation(this)); } @@ -146,7 +144,7 @@ void LocalBrowserController::Update() } } -void LocalBrowserController::Selected(std::string saveName, bool selected) +void LocalBrowserController::Selected(ByteString saveName, bool selected) { if(selected) browserModel->SelectSave(saveName); diff --git a/src/gui/localbrowser/LocalBrowserController.h b/src/gui/localbrowser/LocalBrowserController.h index e6f6d76f2..bacef1631 100644 --- a/src/gui/localbrowser/LocalBrowserController.h +++ b/src/gui/localbrowser/LocalBrowserController.h @@ -19,7 +19,7 @@ public: void RemoveSelected(); void removeSelectedC(); void ClearSelection(); - void Selected(std::string stampID, bool selected); + void Selected(ByteString stampID, bool selected); void RescanStamps(); void rescanStampsC(); void RefreshSavesList(); diff --git a/src/gui/localbrowser/LocalBrowserModel.cpp b/src/gui/localbrowser/LocalBrowserModel.cpp index 78955a3b8..e499bd144 100644 --- a/src/gui/localbrowser/LocalBrowserModel.cpp +++ b/src/gui/localbrowser/LocalBrowserModel.cpp @@ -100,7 +100,7 @@ int LocalBrowserModel::GetPageCount() return std::max(1, (int)(std::ceil(float(Client::Ref().GetStampsCount())/20.0f))); } -void LocalBrowserModel::SelectSave(std::string stampID) +void LocalBrowserModel::SelectSave(ByteString stampID) { for (size_t i = 0; i < selected.size(); i++) { @@ -113,7 +113,7 @@ void LocalBrowserModel::SelectSave(std::string stampID) notifySelectedChanged(); } -void LocalBrowserModel::DeselectSave(std::string stampID) +void LocalBrowserModel::DeselectSave(ByteString stampID) { bool changed = false; restart: diff --git a/src/gui/localbrowser/LocalBrowserModel.h b/src/gui/localbrowser/LocalBrowserModel.h index 75167d9ff..c52bf3941 100644 --- a/src/gui/localbrowser/LocalBrowserModel.h +++ b/src/gui/localbrowser/LocalBrowserModel.h @@ -2,16 +2,16 @@ #define STAMPSMODEL_H_ #include -#include +#include "common/String.h" #include class SaveFile; class LocalBrowserView; class LocalBrowserModel { - std::vector selected; + std::vector selected; SaveFile * stamp; - std::vector stampIDs; + std::vector stampIDs; std::vector savesList; std::vector observers; int currentPage; @@ -31,10 +31,10 @@ public: void SetSave(SaveFile * newStamp); bool GetMoveToFront(); void SetMoveToFront(bool move); - std::vector GetSelected() { return selected; } + std::vector GetSelected() { return selected; } void ClearSelected() { selected.clear(); notifySelectedChanged(); } - void SelectSave(std::string stampID); - void DeselectSave(std::string stampID); + void SelectSave(ByteString stampID); + void DeselectSave(ByteString stampID); virtual ~LocalBrowserModel(); }; diff --git a/src/gui/localbrowser/LocalBrowserModelException.h b/src/gui/localbrowser/LocalBrowserModelException.h index 5146c533d..705173b00 100644 --- a/src/gui/localbrowser/LocalBrowserModelException.h +++ b/src/gui/localbrowser/LocalBrowserModelException.h @@ -1,15 +1,14 @@ #ifndef STAMPSMODELEXCEPTION_H_ #define STAMPSMODELEXCEPTION_H_ -#include +#include "common/String.h" #include -using namespace std; class LocalBrowserModelException { - string message; + String message; public: - LocalBrowserModelException(string message_): message(message_) {}; - const char * what() const throw() { return message.c_str(); }; + LocalBrowserModelException(String message_): message(message_) {}; + const char * what() const throw() { return message.ToUtf8().c_str(); }; ~LocalBrowserModelException() throw() {}; }; diff --git a/src/gui/localbrowser/LocalBrowserView.cpp b/src/gui/localbrowser/LocalBrowserView.cpp index 950598603..4f8bef3c1 100644 --- a/src/gui/localbrowser/LocalBrowserView.cpp +++ b/src/gui/localbrowser/LocalBrowserView.cpp @@ -1,4 +1,3 @@ -#include #include "client/Client.h" #include "Format.h" #include "LocalBrowserView.h" @@ -141,7 +140,7 @@ void LocalBrowserView::NotifyPageChanged(LocalBrowserModel * sender) } else { - std::stringstream pageInfo; + String::Stream pageInfo; pageInfo << "of " << pageCount; pageCountLabel->SetText(pageInfo.str()); int width = Graphics::textwidth(pageInfo.str().c_str()); @@ -152,7 +151,7 @@ void LocalBrowserView::NotifyPageChanged(LocalBrowserModel * sender) //pageCountLabel->Position.X = WINDOWW/2+6; pageLabel->Visible = pageCountLabel->Visible = pageTextbox->Visible = true; - pageInfo.str(""); + pageInfo.str(String()); pageInfo << sender->GetPageNum(); pageTextbox->SetText(pageInfo.str()); } @@ -180,7 +179,7 @@ void LocalBrowserView::NotifySavesListChanged(LocalBrowserModel * sender) int buttonWidth, buttonHeight, saveX = 0, saveY = 0, savesX = 5, savesY = 4, buttonPadding = 2; int buttonAreaWidth, buttonAreaHeight, buttonXOffset, buttonYOffset; - vector saves = sender->GetSavesList(); + std::vector saves = sender->GetSavesList(); for (size_t i = 0; i < stampButtons.size(); i++) { RemoveComponent(stampButtons[i]); @@ -236,7 +235,7 @@ void LocalBrowserView::NotifySavesListChanged(LocalBrowserModel * sender) void LocalBrowserView::NotifySelectedChanged(LocalBrowserModel * sender) { - vector selected = sender->GetSelected(); + std::vector selected = sender->GetSelected(); for (size_t j = 0; j < stampButtons.size(); j++) { stampButtons[j]->SetSelected(false); diff --git a/src/gui/login/LoginController.cpp b/src/gui/login/LoginController.cpp index 5e3ae7713..f58e7c1f8 100644 --- a/src/gui/login/LoginController.cpp +++ b/src/gui/login/LoginController.cpp @@ -15,7 +15,7 @@ LoginController::LoginController(ControllerCallback * callback): } -void LoginController::Login(string username, string password) +void LoginController::Login(ByteString username, ByteString password) { loginModel->Login(username, password); } diff --git a/src/gui/login/LoginController.h b/src/gui/login/LoginController.h index b723cb9f7..fbf5236d2 100644 --- a/src/gui/login/LoginController.h +++ b/src/gui/login/LoginController.h @@ -1,7 +1,7 @@ #ifndef LOGINCONTROLLER_H_ #define LOGINCONTROLLER_H_ -#include +#include "common/String.h" #include "LoginView.h" #include "LoginModel.h" #include "Controller.h" @@ -18,7 +18,7 @@ class LoginController { public: bool HasExited; LoginController(ControllerCallback * callback = NULL); - void Login(string username, string password); + void Login(ByteString username, ByteString password); void Exit(); LoginView * GetView() { return loginView; } User GetUser(); diff --git a/src/gui/login/LoginModel.cpp b/src/gui/login/LoginModel.cpp index b14a69cc3..bcfe90531 100644 --- a/src/gui/login/LoginModel.cpp +++ b/src/gui/login/LoginModel.cpp @@ -6,7 +6,7 @@ LoginModel::LoginModel(): } -void LoginModel::Login(string username, string password) +void LoginModel::Login(ByteString username, ByteString password) { if (username.find('@') != username.npos) { @@ -37,7 +37,7 @@ void LoginModel::AddObserver(LoginView * observer) observers.push_back(observer); } -string LoginModel::GetStatusText() +String LoginModel::GetStatusText() { return statusText; } diff --git a/src/gui/login/LoginModel.h b/src/gui/login/LoginModel.h index 8149797e5..d21450678 100644 --- a/src/gui/login/LoginModel.h +++ b/src/gui/login/LoginModel.h @@ -2,7 +2,7 @@ #define LOGINMODEL_H_ #include -#include +#include "common/String.h" #include "LoginView.h" #include "client/Client.h" @@ -11,15 +11,15 @@ using namespace std; class LoginView; class LoginModel { vector observers; - string statusText; + String statusText; bool loginStatus; void notifyStatusChanged(); User currentUser; public: LoginModel(); - void Login(string username, string password); + void Login(ByteString username, ByteString password); void AddObserver(LoginView * observer); - string GetStatusText(); + String GetStatusText(); bool GetStatus(); User GetUser(); virtual ~LoginModel(); diff --git a/src/gui/login/LoginView.cpp b/src/gui/login/LoginView.cpp index 22b74fe1d..e6646ddf0 100644 --- a/src/gui/login/LoginView.cpp +++ b/src/gui/login/LoginView.cpp @@ -14,7 +14,7 @@ public: LoginAction(LoginView * _v) { v = _v; } void ActionCallback(ui::Button * sender) { - v->c->Login(v->usernameField->GetText(), v->passwordField->GetText()); + v->c->Login(v->usernameField->GetText().ToUtf8(), v->passwordField->GetText().ToUtf8()); } }; @@ -35,7 +35,7 @@ LoginView::LoginView(): cancelButton(new ui::Button(ui::Point(0, 87-17), ui::Point(101, 17), "Sign Out")), titleLabel(new ui::Label(ui::Point(4, 5), ui::Point(200-16, 16), "Server login")), infoLabel(new ui::Label(ui::Point(8, 67), ui::Point(200-16, 16), "")), - usernameField(new ui::Textbox(ui::Point(8, 25), ui::Point(200-16, 17), Client::Ref().GetAuthUser().Username, "[username]")), + usernameField(new ui::Textbox(ui::Point(8, 25), ui::Point(200-16, 17), Client::Ref().GetAuthUser().Username.FromUtf8(), "[username]")), passwordField(new ui::Textbox(ui::Point(8, 46), ui::Point(200-16, 17), "", "[password]")), targetSize(0, 0) { diff --git a/src/gui/options/OptionsView.cpp b/src/gui/options/OptionsView.cpp index 477f9d2ac..a40794023 100644 --- a/src/gui/options/OptionsView.cpp +++ b/src/gui/options/OptionsView.cpp @@ -89,15 +89,15 @@ OptionsView::OptionsView(): OptionsView * v; public: AirModeChanged(OptionsView * v): v(v) { } - virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetAirMode(option.second); } + virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetAirMode(option.second); } }; airMode = new ui::DropDown(ui::Point(Size.X-88, 146), ui::Point(80, 16)); AddComponent(airMode); - airMode->AddOption(std::pair("On", 0)); - airMode->AddOption(std::pair("Pressure off", 1)); - airMode->AddOption(std::pair("Velocity off", 2)); - airMode->AddOption(std::pair("Off", 3)); - airMode->AddOption(std::pair("No Update", 4)); + airMode->AddOption(std::pair("On", 0)); + airMode->AddOption(std::pair("Pressure off", 1)); + airMode->AddOption(std::pair("Velocity off", 2)); + airMode->AddOption(std::pair("Off", 3)); + airMode->AddOption(std::pair("No Update", 4)); airMode->SetActionCallback(new AirModeChanged(this)); tempLabel = new ui::Label(ui::Point(8, 146), ui::Point(Size.X-96, 16), "Air Simulation Mode"); @@ -109,14 +109,14 @@ OptionsView::OptionsView(): OptionsView * v; public: GravityModeChanged(OptionsView * v): v(v) { } - virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetGravityMode(option.second); } + virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetGravityMode(option.second); } }; gravityMode = new ui::DropDown(ui::Point(Size.X-88, 166), ui::Point(80, 16)); AddComponent(gravityMode); - gravityMode->AddOption(std::pair("Vertical", 0)); - gravityMode->AddOption(std::pair("Off", 1)); - gravityMode->AddOption(std::pair("Radial", 2)); + gravityMode->AddOption(std::pair("Vertical", 0)); + gravityMode->AddOption(std::pair("Off", 1)); + gravityMode->AddOption(std::pair("Radial", 2)); gravityMode->SetActionCallback(new GravityModeChanged(this)); tempLabel = new ui::Label(ui::Point(8, 166), ui::Point(Size.X-96, 16), "Gravity Simulation Mode"); @@ -128,14 +128,14 @@ OptionsView::OptionsView(): OptionsView * v; public: EdgeModeChanged(OptionsView * v): v(v) { } - virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetEdgeMode(option.second); } + virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetEdgeMode(option.second); } }; edgeMode = new ui::DropDown(ui::Point(Size.X-88, 186), ui::Point(80, 16)); AddComponent(edgeMode); - edgeMode->AddOption(std::pair("Void", 0)); - edgeMode->AddOption(std::pair("Solid", 1)); - edgeMode->AddOption(std::pair("Loop", 2)); + edgeMode->AddOption(std::pair("Void", 0)); + edgeMode->AddOption(std::pair("Solid", 1)); + edgeMode->AddOption(std::pair("Loop", 2)); edgeMode->SetActionCallback(new EdgeModeChanged(this)); tempLabel = new ui::Label(ui::Point(8, 186), ui::Point(Size.X-96, 16), "Edge Mode"); @@ -147,7 +147,7 @@ OptionsView::OptionsView(): OptionsView * v; public: ScaleAction(OptionsView * v): v(v) { } - virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetScale(option.second); } + virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetScale(option.second); } }; scale = new ui::DropDown(ui::Point(8, 210), ui::Point(40, 16)); { @@ -158,12 +158,12 @@ OptionsView::OptionsView(): { if (current_scale == ix_scale) current_scale_valid = true; - scale->AddOption(std::pair(format::NumberToString(ix_scale), ix_scale)); + scale->AddOption(std::pair(format::NumberToString(ix_scale), ix_scale)); ix_scale += 1; } while (ui::Engine::Ref().GetMaxWidth() >= ui::Engine::Ref().GetWidth() * ix_scale && ui::Engine::Ref().GetMaxHeight() >= ui::Engine::Ref().GetHeight() * ix_scale); if (!current_scale_valid) - scale->AddOption(std::pair("current", current_scale)); + scale->AddOption(std::pair("current", current_scale)); } scale->SetActionCallback(new ScaleAction(this)); AddComponent(scale); diff --git a/src/gui/preview/Comment.h b/src/gui/preview/Comment.h index 1d84042d0..197a0da00 100644 --- a/src/gui/preview/Comment.h +++ b/src/gui/preview/Comment.h @@ -1,16 +1,16 @@ #ifndef COMMENT_H_ #define COMMENT_H_ -#include +#include "common/String.h" class SaveComment { public: int authorID; - std::string authorName; - std::string authorNameFormatted; - std::string comment; - SaveComment(int userID, std::string username, std::string usernameFormatted, std::string commentText): + ByteString authorName; + ByteString authorNameFormatted; + String comment; + SaveComment(int userID, ByteString username, ByteString usernameFormatted, String commentText): authorID(userID), authorName(username), authorNameFormatted(usernameFormatted), comment(commentText) { } diff --git a/src/gui/preview/PreviewController.cpp b/src/gui/preview/PreviewController.cpp index 7ecc8d7a7..44870f9d2 100644 --- a/src/gui/preview/PreviewController.cpp +++ b/src/gui/preview/PreviewController.cpp @@ -1,4 +1,3 @@ -#include #include "client/Client.h" #include "PreviewController.h" #include "PreviewView.h" @@ -73,7 +72,7 @@ void PreviewController::Update() } } -bool PreviewController::SubmitComment(std::string comment) +bool PreviewController::SubmitComment(String comment) { if(comment.length() < 4) { @@ -123,7 +122,7 @@ void PreviewController::DoOpen() previewModel->SetDoOpen(true); } -void PreviewController::Report(std::string message) +void PreviewController::Report(String message) { if(Client::Ref().ReportSave(saveId, message) == RequestOkay) { @@ -147,14 +146,14 @@ void PreviewController::FavouriteSave() } catch (PreviewModelException & e) { - new ErrorMessage("Error", e.what()); + new ErrorMessage("Error", ByteString(e.what()).FromUtf8()); } } } void PreviewController::OpenInBrowser() { - std::stringstream uriStream; + ByteString::Stream uriStream; uriStream << "http://" << SERVER << "/Browse/View.html?ID=" << saveId; Platform::OpenURI(uriStream.str()); } diff --git a/src/gui/preview/PreviewController.h b/src/gui/preview/PreviewController.h index 8e148cb1f..2b64157e4 100644 --- a/src/gui/preview/PreviewController.h +++ b/src/gui/preview/PreviewController.h @@ -27,14 +27,14 @@ public: void Exit(); void DoOpen(); void OpenInBrowser(); - void Report(std::string message); + void Report(String message); void ShowLogin(); bool GetDoOpen(); SaveInfo * GetSaveInfo(); PreviewView * GetView() { return previewView; } void Update(); void FavouriteSave(); - bool SubmitComment(std::string comment); + bool SubmitComment(String comment); bool NextCommentPage(); bool PrevCommentPage(); diff --git a/src/gui/preview/PreviewModel.cpp b/src/gui/preview/PreviewModel.cpp index 888dace14..5cc503e15 100644 --- a/src/gui/preview/PreviewModel.cpp +++ b/src/gui/preview/PreviewModel.cpp @@ -70,7 +70,7 @@ void PreviewModel::UpdateSave(int saveID, int saveDate) notifySaveChanged(); notifySaveCommentsChanged(); - std::stringstream urlStream; + ByteString::Stream urlStream; if (saveDate) urlStream << "http://" << STATICSERVER << "/" << saveID << "_" << saveDate << ".cps"; else @@ -83,7 +83,7 @@ void PreviewModel::UpdateSave(int saveID, int saveDate) if (saveDate) urlStream << "&Date=" << saveDate; saveInfoDownload = new Download(urlStream.str()); - saveInfoDownload->AuthHeaders(format::NumberToString(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); + saveInfoDownload->AuthHeaders(format::NumberToByteString(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); saveInfoDownload->Start(); if (!GetDoOpen()) @@ -93,7 +93,7 @@ void PreviewModel::UpdateSave(int saveID, int saveDate) urlStream.str(""); urlStream << "http://" << SERVER << "/Browse/Comments.json?ID=" << saveID << "&Start=" << (commentsPageNumber-1)*20 << "&Count=20"; commentsDownload = new Download(urlStream.str()); - commentsDownload->AuthHeaders(format::NumberToString(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); + commentsDownload->AuthHeaders(format::NumberToByteString(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); commentsDownload->Start(); } } @@ -143,10 +143,10 @@ void PreviewModel::UpdateComments(int pageNumber) commentsPageNumber = pageNumber; if (!GetDoOpen()) { - std::stringstream urlStream; + ByteString::Stream urlStream; urlStream << "http://" << SERVER << "/Browse/Comments.json?ID=" << saveID << "&Start=" << (commentsPageNumber-1)*20 << "&Count=20"; commentsDownload = new Download(urlStream.str()); - commentsDownload->AuthHeaders(format::NumberToString(Client::Ref().GetAuthUser().UserID).c_str(), Client::Ref().GetAuthUser().SessionID.c_str()); + commentsDownload->AuthHeaders(format::NumberToByteString(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); commentsDownload->Start(); } @@ -174,7 +174,7 @@ void PreviewModel::OnSaveReady() } catch(ParseException &e) { - new ErrorMessage("Error", e.what()); + new ErrorMessage("Error", ByteString(e.what()).FromUtf8()); canOpen = false; } notifySaveChanged(); @@ -210,9 +210,9 @@ bool PreviewModel::ParseSaveInfo(char * saveInfoResponse) int tempScoreUp = objDocument["ScoreUp"].asInt(); int tempScoreDown = objDocument["ScoreDown"].asInt(); int tempMyScore = objDocument["ScoreMine"].asInt(); - std::string tempUsername = objDocument["Username"].asString(); - std::string tempName = objDocument["Name"].asString(); - std::string tempDescription = objDocument["Description"].asString(); + ByteString tempUsername = objDocument["Username"].asString(); + String tempName = ByteString(objDocument["Name"].asString()).FromUtf8(); + String tempDescription = ByteString(objDocument["Description"].asString()).FromUtf8(); int tempCreatedDate = objDocument["DateCreated"].asInt(); int tempUpdatedDate = objDocument["Date"].asInt(); bool tempPublished = objDocument["Published"].asBool(); @@ -222,7 +222,7 @@ bool PreviewModel::ParseSaveInfo(char * saveInfoResponse) int tempVersion = objDocument["Version"].asInt(); Json::Value tagsArray = objDocument["Tags"]; - std::list tempTags; + std::list tempTags; for (Json::UInt j = 0; j < tagsArray.size(); j++) tempTags.push_back(tagsArray[j].asString()); @@ -242,7 +242,7 @@ bool PreviewModel::ParseSaveInfo(char * saveInfoResponse) saveDataDownload->Cancel(); delete saveData; saveData = NULL; - std::stringstream urlStream; + ByteString::Stream urlStream; urlStream << "http://" << STATICSERVER << "/2157797.cps"; saveDataDownload = new Download(urlStream.str()); saveDataDownload->Start(); @@ -268,12 +268,12 @@ bool PreviewModel::ParseComments(char *commentsResponse) for (Json::UInt j = 0; j < commentsArray.size(); j++) { - int userID = format::StringToNumber(commentsArray[j]["UserID"].asString()); - std::string username = commentsArray[j]["Username"].asString(); - std::string formattedUsername = commentsArray[j]["FormattedUsername"].asString(); + int userID = format::ByteStringToNumber(commentsArray[j]["UserID"].asString()); + ByteString username = commentsArray[j]["Username"].asString(); + ByteString formattedUsername = commentsArray[j]["FormattedUsername"].asString(); if (formattedUsername == "jacobot") formattedUsername = "\bt" + formattedUsername; - std::string comment = commentsArray[j]["Text"].asString(); + String comment = ByteString(commentsArray[j]["Text"].asString()).FromUtf8(); saveComments->push_back(new SaveComment(userID, username, formattedUsername, comment)); } return true; diff --git a/src/gui/preview/PreviewModelException.h b/src/gui/preview/PreviewModelException.h index 85dce1d18..c84894a26 100644 --- a/src/gui/preview/PreviewModelException.h +++ b/src/gui/preview/PreviewModelException.h @@ -1,17 +1,17 @@ #ifndef PREVIEWMODELEXCEPTION_H_ #define PREVIEWMODELEXCEPTION_H_ -#include +#include "common/String.h" #include using namespace std; struct PreviewModelException: public exception { - string message; + String message; public: - PreviewModelException(string message_): message(message_) {} + PreviewModelException(String message_): message(message_) {} const char * what() const throw() { - return message.c_str(); + return message.ToUtf8().c_str(); } ~PreviewModelException() throw() {}; }; diff --git a/src/gui/preview/PreviewView.cpp b/src/gui/preview/PreviewView.cpp index 425e729b5..e58b27e92 100644 --- a/src/gui/preview/PreviewView.cpp +++ b/src/gui/preview/PreviewView.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -105,7 +104,7 @@ PreviewView::PreviewView(): public: PreviewView * v; ReportPromptCallback(PreviewView * v_) { v = v_; } - virtual void TextCallback(TextPrompt::DialogueResult result, std::string resultText) { + virtual void TextCallback(TextPrompt::DialogueResult result, String resultText) { if (result == TextPrompt::ResultOkay) v->c->Report(resultText); } @@ -278,9 +277,9 @@ void PreviewView::commentBoxAutoHeight() } } -bool PreviewView::CheckSwearing(std::string text) +bool PreviewView::CheckSwearing(String text) { - for (std::set::iterator iter = swearWords.begin(), end = swearWords.end(); iter != end; iter++) + for (std::set::iterator iter = swearWords.begin(), end = swearWords.end(); iter != end; iter++) { if (text.find(*iter) != text.npos) return true; @@ -292,9 +291,9 @@ void PreviewView::CheckComment() { if (!commentWarningLabel) return; - std::string text = addCommentBox->GetText(); + String text = addCommentBox->GetText(); std::transform(text.begin(), text.end(), text.begin(), ::tolower); - if (!userIsAuthor && (text.find("stolen") != text.npos || text.find("copied") != text.npos)) + if (!userIsAuthor && (text.find("stolen") != String::npos || text.find("copied") != String::npos)) { if (!commentHelpText) { @@ -499,7 +498,7 @@ void PreviewView::NotifySaveChanged(PreviewModel * sender) votesUp = save->votesUp; votesDown = save->votesDown; saveNameLabel->SetText(save->name); - std::string dateType; + String dateType; if (save->updatedDate == save->createdDate) dateType = "Created:"; else @@ -507,11 +506,11 @@ void PreviewView::NotifySaveChanged(PreviewModel * sender) if (showAvatars) { avatarButton->SetUsername(save->userName); - authorDateLabel->SetText("\bw" + save->userName + " \bg" + dateType + " \bw" + format::UnixtimeToDateMini(save->updatedDate)); + authorDateLabel->SetText("\bw" + save->userName.FromUtf8() + " \bg" + dateType + " \bw" + format::UnixtimeToDateMini(save->updatedDate).FromAscii()); } else { - authorDateLabel->SetText("\bgAuthor:\bw " + save->userName + " \bg" + dateType + " \bw" + format::UnixtimeToDateMini(save->updatedDate)); + authorDateLabel->SetText("\bgAuthor:\bw " + save->userName.FromUtf8() + " \bg" + dateType + " \bw" + format::UnixtimeToDateMini(save->updatedDate).FromAscii()); } if (Client::Ref().GetAuthUser().UserID && save->userName == Client::Ref().GetAuthUser().Username) userIsAuthor = true; @@ -571,7 +570,7 @@ void PreviewView::submitComment() { if(addCommentBox) { - std::string comment = std::string(addCommentBox->GetText()); + String comment = addCommentBox->GetText(); submitCommentButton->Enabled = false; addCommentBox->SetText(""); addCommentBox->SetPlaceholder("Submitting comment"); //This doesn't appear to ever show since no separate thread is created @@ -632,7 +631,7 @@ void PreviewView::NotifyCommentBoxEnabledChanged(PreviewModel * sender) } } -void PreviewView::SaveLoadingError(std::string errorMessage) +void PreviewView::SaveLoadingError(String errorMessage) { doError = true; doErrorMessage = errorMessage; @@ -640,7 +639,7 @@ void PreviewView::SaveLoadingError(std::string errorMessage) void PreviewView::NotifyCommentsPageChanged(PreviewModel * sender) { - std::stringstream pageInfoStream; + String::Stream pageInfoStream; pageInfoStream << "Page " << sender->GetCommentsPageNum() << " of " << sender->GetCommentsPageCount(); pageInfo->SetText(pageInfoStream.str()); } @@ -683,9 +682,9 @@ void PreviewView::NotifyCommentsChanged(PreviewModel * sender) } if (showAvatars) - tempUsername = new ui::Label(ui::Point(31, currentY+3), ui::Point(Size.X-((XRES/2) + 13 + 26), 16), comments->at(i)->authorNameFormatted); + tempUsername = new ui::Label(ui::Point(31, currentY+3), ui::Point(Size.X-((XRES/2) + 13 + 26), 16), comments->at(i)->authorNameFormatted.FromUtf8()); else - tempUsername = new ui::Label(ui::Point(5, currentY+3), ui::Point(Size.X-((XRES/2) + 13), 16), comments->at(i)->authorNameFormatted); + tempUsername = new ui::Label(ui::Point(5, currentY+3), ui::Point(Size.X-((XRES/2) + 13), 16), comments->at(i)->authorNameFormatted.FromUtf8()); tempUsername->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; tempUsername->Appearance.VerticalAlign = ui::Appearance::AlignBottom; if (Client::Ref().GetAuthUser().UserID && Client::Ref().GetAuthUser().Username == comments->at(i)->authorName) diff --git a/src/gui/preview/PreviewView.h b/src/gui/preview/PreviewView.h index 3581e86cc..fcf6fc1a7 100644 --- a/src/gui/preview/PreviewView.h +++ b/src/gui/preview/PreviewView.h @@ -3,7 +3,7 @@ #include #include -#include +#include "common/String.h" #include "Comment.h" #include "gui/interface/Window.h" #include "gui/preview/PreviewController.h" @@ -53,7 +53,7 @@ class PreviewView: public ui::Window { bool userIsAuthor; bool doOpen; bool doError; - std::string doErrorMessage; + String doErrorMessage; bool showAvatars; bool prevPage; @@ -64,12 +64,12 @@ class PreviewView: public ui::Window { float commentBoxSizeY; bool commentHelpText; - std::set swearWords; + std::set swearWords; void displayComments(); void commentBoxAutoHeight(); void submitComment(); - bool CheckSwearing(std::string text); + bool CheckSwearing(String text); void CheckComment(); public: void AttachController(PreviewController * controller); @@ -78,7 +78,7 @@ public: void NotifyCommentsChanged(PreviewModel * sender); void NotifyCommentsPageChanged(PreviewModel * sender); void NotifyCommentBoxEnabledChanged(PreviewModel * sender); - void SaveLoadingError(std::string errorMessage); + void SaveLoadingError(String errorMessage); virtual void OnDraw(); virtual void DoDraw(); virtual void OnTick(float dt); diff --git a/src/gui/profile/ProfileActivity.cpp b/src/gui/profile/ProfileActivity.cpp index 60327e246..e012e833a 100644 --- a/src/gui/profile/ProfileActivity.cpp +++ b/src/gui/profile/ProfileActivity.cpp @@ -14,7 +14,7 @@ #include "Format.h" #include "Platform.h" -ProfileActivity::ProfileActivity(std::string username) : +ProfileActivity::ProfileActivity(ByteString username) : WindowActivity(ui::Point(-1, -1), ui::Point(236, 300)), loading(false), saving(false), @@ -98,7 +98,7 @@ void ProfileActivity::setUserInfo(UserInfo newInfo) int currentY = 5; // username label - ui::Label * title = new ui::Label(ui::Point(4, currentY), ui::Point(Size.X-8-(40+8+75), 15), info.username); + ui::Label * title = new ui::Label(ui::Point(4, currentY), ui::Point(Size.X-8-(40+8+75), 15), info.username.FromUtf8()); title->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; scrollPanel->AddChild(title); @@ -147,7 +147,7 @@ void ProfileActivity::setUserInfo(UserInfo newInfo) websiteTitle->SetTextColour(ui::Colour(180, 180, 180)); scrollPanel->AddChild(websiteTitle); - ui::Label *website = new ui::Label(ui::Point(8+websiteTitle->Size.X, currentY), ui::Point(Size.X-websiteTitle->Size.X-16, 15), info.website); + ui::Label *website = new ui::Label(ui::Point(8+websiteTitle->Size.X, currentY), ui::Point(Size.X-websiteTitle->Size.X-16, 15), info.website.FromUtf8()); website->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; scrollPanel->AddChild(website); currentY += 2+website->Size.Y; diff --git a/src/gui/profile/ProfileActivity.h b/src/gui/profile/ProfileActivity.h index 48e766324..8e9c72c14 100644 --- a/src/gui/profile/ProfileActivity.h +++ b/src/gui/profile/ProfileActivity.h @@ -1,7 +1,7 @@ #ifndef PROFILEACTIVITY_H_ #define PROFILEACTIVITY_H_ -#include +#include "common/String.h" #include "Activity.h" #include "client/requestbroker/RequestListener.h" #include "client/UserInfo.h" @@ -21,10 +21,10 @@ class ProfileActivity: public WindowActivity, public RequestListener { bool loading; bool saving; bool doError; - std::string doErrorMessage; + String doErrorMessage; void setUserInfo(UserInfo newInfo); public: - ProfileActivity(std::string username); + ProfileActivity(ByteString username); virtual ~ProfileActivity(); virtual void OnResponseReady(void * userDataPtr, int identifier); virtual void OnResponseFailed(int identifier); diff --git a/src/gui/render/RenderView.cpp b/src/gui/render/RenderView.cpp index 8165837c9..fd486b2d2 100644 --- a/src/gui/render/RenderView.cpp +++ b/src/gui/render/RenderView.cpp @@ -381,7 +381,7 @@ void RenderView::OnDraw() g->draw_line(XRES, 0, XRES, WINDOWH, 255, 255, 255, 255); if(toolTipPresence && toolTip.length()) { - g->drawtext(6, Size.Y-MENUSIZE-12, (char*)toolTip.c_str(), 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); + g->drawtext(6, Size.Y-MENUSIZE-12, toolTip, 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); } } @@ -415,7 +415,7 @@ void RenderView::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bo } } -void RenderView::ToolTip(ui::Point senderPosition, std::string toolTip) +void RenderView::ToolTip(ui::Point senderPosition, String toolTip) { this->toolTip = toolTip; this->isToolTipFadingIn = true; diff --git a/src/gui/render/RenderView.h b/src/gui/render/RenderView.h index 83f5207e5..8220b91b8 100644 --- a/src/gui/render/RenderView.h +++ b/src/gui/render/RenderView.h @@ -18,7 +18,7 @@ class RenderView: public ui::Window { std::vector renderModes; std::vector displayModes; std::vector colourModes; - std::string toolTip; + String toolTip; int toolTipPresence; bool isToolTipFadingIn; int line1, line2, line3, line4; @@ -38,7 +38,7 @@ public: virtual void OnDraw(); virtual void OnTick(float dt); virtual void OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool alt); - virtual void ToolTip(ui::Point senderPosition, std::string toolTip); + virtual void ToolTip(ui::Point senderPosition, String toolTip); virtual ~RenderView(); }; diff --git a/src/gui/save/LocalSaveActivity.cpp b/src/gui/save/LocalSaveActivity.cpp index 61cdff6d6..09b17011d 100644 --- a/src/gui/save/LocalSaveActivity.cpp +++ b/src/gui/save/LocalSaveActivity.cpp @@ -76,8 +76,8 @@ void LocalSaveActivity::Save() class FileOverwriteConfirmation: public ConfirmDialogueCallback { public: LocalSaveActivity * a; - std::string filename; - FileOverwriteConfirmation(LocalSaveActivity * a, std::string finalFilename) : a(a), filename(finalFilename) {} + ByteString filename; + FileOverwriteConfirmation(LocalSaveActivity * a, ByteString finalFilename) : a(a), filename(finalFilename) {} virtual void ConfirmCallback(ConfirmPrompt::DialogueResult result) { if (result == ConfirmPrompt::ResultOkay) { @@ -89,12 +89,12 @@ void LocalSaveActivity::Save() if(filenameField->GetText().length()) { - std::string finalFilename = std::string(LOCAL_SAVE_DIR) + std::string(PATH_SEP) + filenameField->GetText() + ".cps"; + ByteString finalFilename = ByteString(LOCAL_SAVE_DIR) + ByteString(PATH_SEP) + filenameField->GetText().ToUtf8() + ".cps"; save.SetDisplayName(filenameField->GetText()); save.SetFileName(finalFilename); if(Client::Ref().FileExists(finalFilename)) { - new ConfirmPrompt("Overwrite file", "Are you sure you wish to overwrite\n"+finalFilename, new FileOverwriteConfirmation(this, finalFilename)); + new ConfirmPrompt("Overwrite file", "Are you sure you wish to overwrite\n"+finalFilename.FromUtf8(), new FileOverwriteConfirmation(this, finalFilename)); } else { @@ -107,7 +107,7 @@ void LocalSaveActivity::Save() } } -void LocalSaveActivity::saveWrite(std::string finalFilename) +void LocalSaveActivity::saveWrite(ByteString finalFilename) { Client::Ref().MakeDirectory(LOCAL_SAVE_DIR); GameSave *gameSave = save.GetGameSave(); diff --git a/src/gui/save/LocalSaveActivity.h b/src/gui/save/LocalSaveActivity.h index 47d3938d1..00801bbae 100644 --- a/src/gui/save/LocalSaveActivity.h +++ b/src/gui/save/LocalSaveActivity.h @@ -31,7 +31,7 @@ class LocalSaveActivity: public WindowActivity, public RequestListener FileSavedCallback * callback; public: LocalSaveActivity(SaveFile save, FileSavedCallback * callback); - void saveWrite(std::string finalFilename); + void saveWrite(ByteString finalFilename); virtual void Save(); virtual void OnDraw(); virtual void OnResponseReady(void * imagePtr, int identifier); diff --git a/src/gui/save/ServerSaveActivity.cpp b/src/gui/save/ServerSaveActivity.cpp index d39d2734e..ac8bb1aba 100644 --- a/src/gui/save/ServerSaveActivity.cpp +++ b/src/gui/save/ServerSaveActivity.cpp @@ -244,7 +244,7 @@ void ServerSaveActivity::Save() { if(Client::Ref().GetAuthUser().Username != save.GetUserName() && publishedCheckbox->GetChecked()) { - new ConfirmPrompt("Publish", "This save was created by " + save.GetUserName() + ", you're about to publish this under your own name; If you haven't been given permission by the author to do so, please uncheck the publish box, otherwise continue", new PublishConfirmation(this)); + new ConfirmPrompt("Publish", "This save was created by " + save.GetUserName().FromUtf8() + ", you're about to publish this under your own name; If you haven't been given permission by the author to do so, please uncheck the publish box, otherwise continue", new PublishConfirmation(this)); } else { @@ -264,8 +264,8 @@ void ServerSaveActivity::AddAuthorInfo() serverSaveInfo["type"] = "save"; serverSaveInfo["id"] = save.GetID(); serverSaveInfo["username"] = Client::Ref().GetAuthUser().Username; - serverSaveInfo["title"] = save.GetName(); - serverSaveInfo["description"] = save.GetDescription(); + serverSaveInfo["title"] = save.GetName().ToUtf8(); + serverSaveInfo["description"] = save.GetDescription().ToUtf8(); serverSaveInfo["published"] = (int)save.GetPublished(); serverSaveInfo["date"] = (Json::Value::UInt64)time(NULL); Client::Ref().SaveAuthorInfo(&serverSaveInfo); @@ -300,7 +300,7 @@ void ServerSaveActivity::Exit() void ServerSaveActivity::ShowPublishingInfo() { - const char *info = + String info = "In The Powder Toy, one can save simulations to their account in two privacy levels: Published and unpublished. You can choose which one by checking or unchecking the 'publish' checkbox. Saves are unpublished by default, so if you do not check publish nobody will be able to see your saves.\n" "\n" "\btPublished saves\bw will appear on the 'By Date' feed and will be seen by many people. These saves also contribute to your Average Score, which is displayed publicly on your profile page on the website. Publish saves that you want people to see so they can comment and vote on.\n" @@ -317,7 +317,7 @@ void ServerSaveActivity::ShowPublishingInfo() void ServerSaveActivity::ShowRules() { - const char *rules = + String rules = "These are the rules you should follow when uploading saves to avoid having them deleted or otherwise hidden from public view. If you fail to follow them, don't be surprised if your saves get lousy votes, unpublished, or removed from the front page should they make it there. These rules may change at any time as new problems arise, and how each rule is handled changes depending on the situation.\n" "\n" "\bt1. No image plotting.\bw If you use a program to draw out pixels from an image outside of TPT without drawing it by hand, don't be surprised when the save gets deleted and you get banned.\n" @@ -343,7 +343,7 @@ void ServerSaveActivity::ShowRules() new InformationMessage("Save Uploading Rules", rules, true); } -void ServerSaveActivity::CheckName(std::string newname) +void ServerSaveActivity::CheckName(String newname) { if (newname.length() && newname == save.GetName() && save.GetUserName() == Client::Ref().GetAuthUser().Username) titleLabel->SetText("Modify simulation properties:"); diff --git a/src/gui/save/ServerSaveActivity.h b/src/gui/save/ServerSaveActivity.h index 6ce8ed4a9..bd0ca1300 100644 --- a/src/gui/save/ServerSaveActivity.h +++ b/src/gui/save/ServerSaveActivity.h @@ -32,7 +32,7 @@ public: virtual void Exit(); virtual void ShowPublishingInfo(); virtual void ShowRules(); - virtual void CheckName(std::string newname); + virtual void CheckName(String newname); virtual void OnDraw(); virtual void OnResponseReady(void * imagePtr, int identifier); virtual void OnTick(float dt); diff --git a/src/gui/search/SearchController.cpp b/src/gui/search/SearchController.cpp index 56282dc7c..196a6d0c9 100644 --- a/src/gui/search/SearchController.cpp +++ b/src/gui/search/SearchController.cpp @@ -1,5 +1,4 @@ -#include -#include +#include "common/String.h" #include "SearchController.h" #include "SearchModel.h" #include "SearchView.h" @@ -104,7 +103,7 @@ SearchController::~SearchController() delete callback; } -void SearchController::DoSearch(std::string query, bool now) +void SearchController::DoSearch(String query, bool now) { nextQuery = query; if (!now) @@ -118,7 +117,7 @@ void SearchController::DoSearch(std::string query, bool now) } } -void SearchController::DoSearch2(std::string query) +void SearchController::DoSearch2(String query) { // calls SearchView function to set textbox text, then calls DoSearch searchView->Search(query); @@ -236,7 +235,7 @@ void SearchController::RemoveSelected() virtual ~RemoveSelectedConfirmation() { } }; - std::stringstream desc; + String::Stream desc; desc << "Are you sure you want to delete " << searchModel->GetSelected().size() << " save"; if(searchModel->GetSelected().size()>1) desc << "s"; @@ -256,12 +255,12 @@ void SearchController::removeSelectedC() { for (size_t i = 0; i < saves.size(); i++) { - std::stringstream saveID; + String::Stream saveID; saveID << "Deleting save [" << saves[i] << "] ..."; notifyStatus(saveID.str()); if (Client::Ref().DeleteSave(saves[i])!=RequestOkay) { - std::stringstream saveIDF; + String::Stream saveIDF; saveIDF << "Failed to delete [" << saves[i] << "]: " << Client::Ref().GetLastError(); notifyError(saveIDF.str()); c->Refresh(); @@ -294,12 +293,12 @@ void SearchController::UnpublishSelected(bool publish) virtual ~UnpublishSelectedConfirmation() { } }; - std::stringstream desc; + String::Stream desc; desc << "Are you sure you want to " << (publish ? "publish " : "unpublish ") << searchModel->GetSelected().size() << " save"; if (searchModel->GetSelected().size() > 1) desc << "s"; desc << "?"; - new ConfirmPrompt((publish ? "Publish Saves" : "Unpublish Saves"), desc.str(), new UnpublishSelectedConfirmation(this, publish)); + new ConfirmPrompt(publish ? String("Publish Saves") : String("Unpublish Saves"), desc.str(), new UnpublishSelectedConfirmation(this, publish)); } void SearchController::unpublishSelectedC(bool publish) @@ -314,7 +313,7 @@ void SearchController::unpublishSelectedC(bool publish) bool PublishSave(int saveID) { - std::stringstream message; + String::Stream message; message << "Publishing save [" << saveID << "]"; notifyStatus(message.str()); if (Client::Ref().PublishSave(saveID) != RequestOkay) @@ -324,7 +323,7 @@ void SearchController::unpublishSelectedC(bool publish) bool UnpublishSave(int saveID) { - std::stringstream message; + String::Stream message; message << "Unpublishing save [" << saveID << "]"; notifyStatus(message.str()); if (Client::Ref().UnpublishSave(saveID) != RequestOkay) @@ -343,7 +342,7 @@ void SearchController::unpublishSelectedC(bool publish) ret = UnpublishSave(saves[i]); if (!ret) { - std::stringstream error; + String::Stream error; if (publish) // uses html page so error message will be spam error << "Failed to publish [" << saves[i] << "], is this save yours?"; else @@ -360,7 +359,7 @@ void SearchController::unpublishSelectedC(bool publish) }; std::vector selected = searchModel->GetSelected(); - new TaskWindow((publish ? "Publishing Saves" : "Unpublishing Saves"), new UnpublishSavesTask(selected, this, publish)); + new TaskWindow(publish ? String("Publishing Saves") : String("Unpublishing Saves"), new UnpublishSavesTask(selected, this, publish)); } void SearchController::FavouriteSelected() @@ -374,12 +373,12 @@ void SearchController::FavouriteSelected() { for (size_t i = 0; i < saves.size(); i++) { - std::stringstream saveID; + String::Stream saveID; saveID << "Favouring save [" << saves[i] << "]"; notifyStatus(saveID.str()); if (Client::Ref().FavouriteSave(saves[i], true)!=RequestOkay) { - std::stringstream saveIDF; + String::Stream saveIDF; saveIDF << "Failed to favourite [" << saves[i] << "]: " + Client::Ref().GetLastError(); notifyError(saveIDF.str()); return false; @@ -399,12 +398,12 @@ void SearchController::FavouriteSelected() { for (size_t i = 0; i < saves.size(); i++) { - std::stringstream saveID; + String::Stream saveID; saveID << "Unfavouring save [" << saves[i] << "]"; notifyStatus(saveID.str()); if (Client::Ref().FavouriteSave(saves[i], false)!=RequestOkay) { - std::stringstream saveIDF; + String::Stream saveIDF; saveIDF << "Failed to unfavourite [" << saves[i] << "]: " + Client::Ref().GetLastError(); notifyError(saveIDF.str()); return false; diff --git a/src/gui/search/SearchController.h b/src/gui/search/SearchController.h index 094100e70..a52236920 100644 --- a/src/gui/search/SearchController.h +++ b/src/gui/search/SearchController.h @@ -19,7 +19,7 @@ private: ControllerCallback * callback; double nextQueryTime; - std::string nextQuery; + String nextQuery; bool nextQueryDone; bool instantOpen; bool doRefresh; @@ -32,8 +32,8 @@ public: ~SearchController(); SearchView * GetView() { return searchView; } void Exit(); - void DoSearch(std::string query, bool now = false); - void DoSearch2(std::string query); + void DoSearch(String query, bool now = false); + void DoSearch2(String query); void Refresh(); void NextPage(); void PrevPage(); diff --git a/src/gui/search/SearchModel.cpp b/src/gui/search/SearchModel.cpp index 620257e93..436112e3f 100644 --- a/src/gui/search/SearchModel.cpp +++ b/src/gui/search/SearchModel.cpp @@ -36,7 +36,7 @@ TH_ENTRY_POINT void * SearchModel::updateSaveListTHelper(void * obj) void * SearchModel::updateSaveListT() { - std::string category = ""; + ByteString category = ""; if(showFavourite) category = "Favourites"; if(showOwn && Client::Ref().GetAuthUser().UserID) @@ -55,13 +55,13 @@ TH_ENTRY_POINT void * SearchModel::updateTagListTHelper(void * obj) void * SearchModel::updateTagListT() { int tagResultCount; - std::vector > * tagList = Client::Ref().GetTags(0, 24, "", tagResultCount); + std::vector > * tagList = Client::Ref().GetTags(0, 24, "", tagResultCount); updateTagListFinished = true; return tagList; } -bool SearchModel::UpdateSaveList(int pageNumber, std::string query) +bool SearchModel::UpdateSaveList(int pageNumber, String query) { //Threading if (!updateSaveListWorking) @@ -122,7 +122,7 @@ vector SearchModel::GetSaveList() return saveList; } -vector > SearchModel::GetTagList() +vector > SearchModel::GetTagList() { return tagList; } @@ -164,7 +164,7 @@ void SearchModel::Update() { updateTagListWorking = false; - vector > * tempTagList; + vector > * tempTagList; pthread_join(updateTagListThread, (void**)&tempTagList); if(tempTagList) diff --git a/src/gui/search/SearchModel.h b/src/gui/search/SearchModel.h index 52dc6b0da..c1ed5673e 100644 --- a/src/gui/search/SearchModel.h +++ b/src/gui/search/SearchModel.h @@ -2,7 +2,7 @@ #define SEARCHMODEL_H #include -#include +#include "common/String.h" #include "common/tpt-minmax.h" #include "common/tpt-thread.h" #include @@ -16,13 +16,13 @@ class SearchModel { private: SaveInfo * loadedSave; - string currentSort; - string lastQuery; - string lastError; + ByteString currentSort; + String lastQuery; + String lastError; vector selected; vector observers; vector saveList; - vector > tagList; + vector > tagList; int currentPage; int resultCount; int thResultCount; @@ -57,10 +57,10 @@ public: void SetShowTags(bool show); bool GetShowTags(); void AddObserver(SearchView * observer); - bool UpdateSaveList(int pageNumber, std::string query); + bool UpdateSaveList(int pageNumber, String query); vector GetSaveList(); - vector > GetTagList(); - string GetLastError() { return lastError; } + vector > GetTagList(); + String GetLastError() { return lastError; } int GetPageCount() { if (!showOwn && !showFavourite && currentSort == "best" && lastQuery == "") @@ -69,9 +69,9 @@ public: return std::max(1, (int)(ceil(resultCount/20.0f))); } int GetPageNum() { return currentPage; } - std::string GetLastQuery() { return lastQuery; } - void SetSort(string sort) { if(!updateSaveListWorking) { currentSort = sort; } notifySortChanged(); } - string GetSort() { return currentSort; } + String GetLastQuery() { return lastQuery; } + void SetSort(ByteString sort) { if(!updateSaveListWorking) { currentSort = sort; } notifySortChanged(); } + ByteString GetSort() { return currentSort; } void SetShowOwn(bool show) { if(!updateSaveListWorking) { if(show!=showOwn) { showOwn = show; } } notifyShowOwnChanged(); } bool GetShowOwn() { return showOwn; } void SetShowFavourite(bool show) { if(show!=showFavourite && !updateSaveListWorking) { showFavourite = show; } notifyShowFavouriteChanged(); } diff --git a/src/gui/search/SearchView.cpp b/src/gui/search/SearchView.cpp index efebe51f2..f6e4dd0a4 100644 --- a/src/gui/search/SearchView.cpp +++ b/src/gui/search/SearchView.cpp @@ -1,5 +1,3 @@ -#include - #include "SearchView.h" #include "client/Client.h" #include "gui/interface/Keys.h" @@ -310,7 +308,7 @@ SearchView::~SearchView() saveButtons.clear(); } -void SearchView::Search(std::string query) +void SearchView::Search(String query) { searchField->SetText(query); c->DoSearch(query, true); @@ -376,7 +374,7 @@ void SearchView::NotifyPageChanged(SearchModel * sender) } else { - std::stringstream pageInfo; + String::Stream pageInfo; pageInfo << "of " << pageCount; pageCountLabel->SetText(pageInfo.str()); int width = Graphics::textwidth(pageInfo.str().c_str()); @@ -387,7 +385,7 @@ void SearchView::NotifyPageChanged(SearchModel * sender) //pageCountLabel->Position.X = WINDOWW/2+6; pageLabel->Visible = pageCountLabel->Visible = pageTextbox->Visible = true; - pageInfo.str(""); + pageInfo.str(String()); pageInfo << sender->GetPageNum(); pageTextbox->SetText(pageInfo.str()); } @@ -469,7 +467,7 @@ void SearchView::NotifyTagListChanged(SearchModel * sender) int tagWidth = 0, tagHeight = 0, tagX = 0, tagY = 0, tagsX = 6, tagsY = 4, tagPadding = 1; int tagAreaWidth, tagAreaHeight, tagXOffset = 0, tagYOffset = 0; - vector > tags = sender->GetTagList(); + vector > tags = sender->GetTagList(); RemoveComponent(motdLabel); motdLabel->SetParentWindow(NULL); @@ -510,12 +508,12 @@ void SearchView::NotifyTagListChanged(SearchModel * sender) class TagAction: public ui::ButtonAction { SearchView * v; - std::string tag; + ByteString tag; public: - TagAction(SearchView * v, std::string tag) : v(v), tag(tag) {} + TagAction(SearchView * v, ByteString tag) : v(v), tag(tag) {} virtual void ActionCallback(ui::Button * sender) { - v->Search(tag); + v->Search(tag.FromUtf8()); } }; if (sender->GetShowTags()) @@ -524,7 +522,7 @@ void SearchView::NotifyTagListChanged(SearchModel * sender) { int maxTagVotes = tags[0].second; - pair tag = tags[i]; + pair tag = tags[i]; if (tagX == tagsX) { @@ -545,7 +543,7 @@ void SearchView::NotifyTagListChanged(SearchModel * sender) tagYOffset + tagPadding + tagY*(tagHeight+tagPadding*2) ), ui::Point(tagWidth, tagHeight), - tag.first + tag.first.FromUtf8() ); tagButton->SetActionCallback(new TagAction(this, tag.first)); tagButton->Appearance.BorderInactive = ui::Colour(0, 0, 0); @@ -673,13 +671,13 @@ void SearchView::NotifySaveListChanged(SearchModel * sender) } virtual void AltActionCallback(ui::SaveButton * sender) { - stringstream search; + String::Stream search; search << "history:" << sender->GetSave()->GetID(); v->Search(search.str()); } virtual void AltActionCallback2(ui::SaveButton * sender) { - v->Search("user:"+sender->GetSave()->GetUserName()); + v->Search("user:"+sender->GetSave()->GetUserName().FromUtf8()); } }; for (size_t i = 0; i < saves.size(); i++) diff --git a/src/gui/search/SearchView.h b/src/gui/search/SearchView.h index 8c32aebb6..93f7a94ff 100644 --- a/src/gui/search/SearchView.h +++ b/src/gui/search/SearchView.h @@ -66,7 +66,7 @@ public: SearchView(); virtual ~SearchView(); void AttachController(SearchController * _c) { c = _c; } - virtual void Search(std::string); + virtual void Search(String); virtual void OnTick(float dt); virtual void OnMouseWheel(int x, int y, int d); virtual void OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool alt); diff --git a/src/gui/tags/TagsController.cpp b/src/gui/tags/TagsController.cpp index 49715aaae..da9cce04f 100644 --- a/src/gui/tags/TagsController.cpp +++ b/src/gui/tags/TagsController.cpp @@ -22,13 +22,13 @@ SaveInfo * TagsController::GetSave() return tagsModel->GetSave(); } -void TagsController::RemoveTag(std::string tag) +void TagsController::RemoveTag(ByteString tag) { tagsModel->RemoveTag(tag); } -void TagsController::AddTag(std::string tag) +void TagsController::AddTag(ByteString tag) { tagsModel->AddTag(tag); } diff --git a/src/gui/tags/TagsController.h b/src/gui/tags/TagsController.h index 8a510983f..788b1532c 100644 --- a/src/gui/tags/TagsController.h +++ b/src/gui/tags/TagsController.h @@ -16,8 +16,8 @@ public: TagsController(ControllerCallback * callback, SaveInfo * save); TagsView * GetView() {return tagsView;} SaveInfo * GetSave(); - void RemoveTag(std::string tag); - void AddTag(std::string tag); + void RemoveTag(ByteString tag); + void AddTag(ByteString tag); void Exit(); virtual ~TagsController(); }; diff --git a/src/gui/tags/TagsModel.cpp b/src/gui/tags/TagsModel.cpp index 8588afb43..2ccbaa531 100644 --- a/src/gui/tags/TagsModel.cpp +++ b/src/gui/tags/TagsModel.cpp @@ -21,14 +21,14 @@ SaveInfo * TagsModel::GetSave() return save; } -void TagsModel::RemoveTag(std::string tag) +void TagsModel::RemoveTag(ByteString tag) { if(save) { - std::list * tags = Client::Ref().RemoveTag(save->GetID(), tag); + std::list * tags = Client::Ref().RemoveTag(save->GetID(), tag); if(tags) { - save->SetTags(std::list(*tags)); + save->SetTags(std::list(*tags)); notifyTagsChanged(); delete tags; } @@ -39,14 +39,14 @@ void TagsModel::RemoveTag(std::string tag) } } -void TagsModel::AddTag(std::string tag) +void TagsModel::AddTag(ByteString tag) { if(save) { - std::list * tags = Client::Ref().AddTag(save->GetID(), tag); + std::list * tags = Client::Ref().AddTag(save->GetID(), tag); if(tags) { - save->SetTags(std::list(*tags)); + save->SetTags(std::list(*tags)); notifyTagsChanged(); delete tags; } diff --git a/src/gui/tags/TagsModel.h b/src/gui/tags/TagsModel.h index 8afe84106..9e66a0757 100644 --- a/src/gui/tags/TagsModel.h +++ b/src/gui/tags/TagsModel.h @@ -2,7 +2,7 @@ #define TAGSMODEL_H_ #include -#include +#include "common/String.h" class SaveInfo; @@ -15,8 +15,8 @@ public: TagsModel(); void AddObserver(TagsView * observer); void SetSave(SaveInfo * save); - void RemoveTag(std::string tag); - void AddTag(std::string tag); + void RemoveTag(ByteString tag); + void AddTag(ByteString tag); SaveInfo * GetSave(); virtual ~TagsModel(); }; diff --git a/src/gui/tags/TagsModelException.h b/src/gui/tags/TagsModelException.h index 671bf3b30..350f6974e 100644 --- a/src/gui/tags/TagsModelException.h +++ b/src/gui/tags/TagsModelException.h @@ -1,14 +1,14 @@ #ifndef TAGSMODELEXCEPTION_H_ #define TAGSMODELEXCEPTION_H_ -#include +#include "common/String.h" #include class TagsModelException { - std::string message; + String message; public: - TagsModelException(std::string message_): message(message_) {}; - const char * what() const throw() { return message.c_str(); }; + TagsModelException(String message_): message(message_) {}; + const char * what() const throw() { return message.ToUtf8().c_str(); }; ~TagsModelException() throw() {}; }; diff --git a/src/gui/tags/TagsView.cpp b/src/gui/tags/TagsView.cpp index 774c3488b..9aca4934d 100644 --- a/src/gui/tags/TagsView.cpp +++ b/src/gui/tags/TagsView.cpp @@ -87,9 +87,9 @@ void TagsView::NotifyTagsChanged(TagsModel * sender) class DeleteTagAction : public ui::ButtonAction { TagsView * v; - std::string tag; + ByteString tag; public: - DeleteTagAction(TagsView * _v, std::string tag) { v = _v; this->tag = tag; } + DeleteTagAction(TagsView * _v, ByteString tag) { v = _v; this->tag = tag; } void ActionCallback(ui::Button * sender) { try @@ -98,18 +98,18 @@ void TagsView::NotifyTagsChanged(TagsModel * sender) } catch(TagsModelException & ex) { - new ErrorMessage("Could not remove tag", ex.what()); + new ErrorMessage("Could not remove tag", ByteString(ex.what()).FromUtf8()); } } }; if(sender->GetSave()) { - std::list Tags = sender->GetSave()->GetTags(); + std::list Tags = sender->GetSave()->GetTags(); int i = 0; - for(std::list::const_iterator iter = Tags.begin(), end = Tags.end(); iter != end; iter++) + for(std::list::const_iterator iter = Tags.begin(), end = Tags.end(); iter != end; iter++) { - ui::Label * tempLabel = new ui::Label(ui::Point(35, 35+(16*i)), ui::Point(120, 16), *iter); + ui::Label * tempLabel = new ui::Label(ui::Point(35, 35+(16*i)), ui::Point(120, 16), (*iter).FromUtf8()); tempLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; tempLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle; tags.push_back(tempLabel); AddComponent(tempLabel); @@ -154,11 +154,11 @@ void TagsView::addTag() } try { - c->AddTag(tagInput->GetText()); + c->AddTag(tagInput->GetText().ToUtf8()); } catch(TagsModelException & ex) { - new ErrorMessage("Could not add tag", ex.what()); + new ErrorMessage("Could not add tag", ByteString(ex.what()).FromUtf8()); } tagInput->SetText(""); } diff --git a/src/gui/update/UpdateActivity.cpp b/src/gui/update/UpdateActivity.cpp index c5b759638..5c1bd32c8 100644 --- a/src/gui/update/UpdateActivity.cpp +++ b/src/gui/update/UpdateActivity.cpp @@ -1,5 +1,4 @@ #include -#include #include "gui/dialogues/ConfirmPrompt.h" #include "gui/interface/Engine.h" #include "UpdateActivity.h" @@ -13,10 +12,10 @@ class UpdateDownloadTask : public Task { public: - UpdateDownloadTask(std::string updateName, UpdateActivity * a) : a(a), updateName(updateName) {} + UpdateDownloadTask(ByteString updateName, UpdateActivity * a) : a(a), updateName(updateName) {} private: UpdateActivity * a; - std::string updateName; + ByteString updateName; virtual void notifyDoneMain(){ a->NotifyDone(this); } @@ -26,7 +25,7 @@ private: } virtual bool doWork() { - std::stringstream errorStream; + String::Stream errorStream; void * request = http_async_req_start(NULL, (char*)updateName.c_str(), NULL, 0, 0); notifyStatus("Downloading update"); notifyProgress(-1); @@ -117,7 +116,7 @@ private: }; UpdateActivity::UpdateActivity() { - std::stringstream file; + ByteString::Stream file; #ifdef UPDATESERVER file << "http://" << UPDATESERVER << Client::Ref().GetUpdateInfo().File; #else diff --git a/src/lua/CommandInterface.cpp b/src/lua/CommandInterface.cpp index 0e455f96b..13d7d1e4c 100644 --- a/src/lua/CommandInterface.cpp +++ b/src/lua/CommandInterface.cpp @@ -1,5 +1,4 @@ #include -#include #include #if !defined(WIN) || defined(__GNUC__) #include @@ -18,23 +17,23 @@ CommandInterface::CommandInterface(GameController * c, GameModel * m) { this->m = m; }*/ -int CommandInterface::Command(std::string command) +int CommandInterface::Command(String command) { lastError = "No interpreter"; return -1; } -std::string CommandInterface::FormatCommand(std::string command) +String CommandInterface::FormatCommand(String command) { return command; } -void CommandInterface::Log(LogType type, std::string message) +void CommandInterface::Log(LogType type, String message) { m->Log(message, type == LogError || type == LogNotice); } -int CommandInterface::GetPropertyOffset(std::string key, FormatType & format) +int CommandInterface::GetPropertyOffset(ByteString key, FormatType & format) { int offset = -1; if (!key.compare("type")) @@ -105,7 +104,7 @@ int CommandInterface::GetPropertyOffset(std::string key, FormatType & format) return offset; } -std::string CommandInterface::GetLastError() +String CommandInterface::GetLastError() { return lastError; } diff --git a/src/lua/CommandInterface.h b/src/lua/CommandInterface.h index 78fdbf8fb..52ca21bd2 100644 --- a/src/lua/CommandInterface.h +++ b/src/lua/CommandInterface.h @@ -1,7 +1,7 @@ #ifndef COMMANDINTERFACE_H_ #define COMMANDINTERFACE_H_ -#include +#include "common/String.h" #include "gui/interface/Engine.h" //#include "game/GameModel.h" @@ -10,15 +10,15 @@ class GameController; class Tool; class CommandInterface { protected: - std::string lastError; + String lastError; GameModel * m; GameController * c; public: enum LogType { LogError, LogWarning, LogNotice }; enum FormatType { FormatInt, FormatString, FormatChar, FormatFloat, FormatElement }; CommandInterface(GameController * c, GameModel * m); - int GetPropertyOffset(std::string key, FormatType & format); - void Log(LogType type, std::string message); + int GetPropertyOffset(ByteString key, FormatType & format); + void Log(LogType type, String message); //void AttachGameModel(GameModel * m); virtual bool OnActiveToolChanged(int toolSelection, Tool * tool) {return true;} virtual bool OnMouseMove(int x, int y, int dx, int dy) {return true;} @@ -29,9 +29,9 @@ public: virtual bool OnKeyRelease(int key, Uint16 character, bool shift, bool ctrl, bool alt) {return true;} virtual bool OnMouseTick() { return true; } virtual void OnTick() { } - virtual int Command(std::string command); - virtual std::string FormatCommand(std::string command); - std::string GetLastError(); + virtual int Command(String command); + virtual String FormatCommand(String command); + String GetLastError(); virtual ~CommandInterface(); }; diff --git a/src/lua/LegacyLuaAPI.cpp b/src/lua/LegacyLuaAPI.cpp index 93ec42734..b72c5a6d5 100644 --- a/src/lua/LegacyLuaAPI.cpp +++ b/src/lua/LegacyLuaAPI.cpp @@ -1,5 +1,4 @@ #ifdef LUACONSOLE -#include #include #include #include @@ -26,7 +25,7 @@ int luacon_partread(lua_State* l) { int tempinteger, i = cIndex; float tempfloat; - std::string key = luaL_optstring(l, 2, ""); + ByteString key = luaL_optstring(l, 2, ""); CommandInterface::FormatType format; int offset = luacon_ci->GetPropertyOffset(key, format); @@ -62,7 +61,7 @@ int luacon_partread(lua_State* l) int luacon_partwrite(lua_State* l) { int i = cIndex; - std::string key = luaL_optstring(l, 2, ""); + ByteString key = luaL_optstring(l, 2, ""); CommandInterface::FormatType format; int offset = luacon_ci->GetPropertyOffset(key, format); @@ -473,7 +472,7 @@ int luacon_keyevent(int key, Uint16 character, int modifier, int event) int callret = lua_pcall(l, 4, 1, 0); if (callret) { - if (!strcmp(luacon_geterror(), "Error: Script not responding")) + if (luacon_geterror() == "Error: Script not responding") { ui::Engine::Ref().LastTick(Platform::GetTime()); for (int j = i; j <= len-1; j++) @@ -527,7 +526,7 @@ int luacon_mouseevent(int mx, int my, int mb, int event, int mouse_wheel) int callret = lua_pcall(l, 5, 1, 0); if (callret) { - if (!strcmp(luacon_geterror(), "Error: Script not responding")) + if (luacon_geterror() == "Error: Script not responding") { ui::Engine::Ref().LastTick(Platform::GetTime()); for (int j = i; j <= len-1; j++) @@ -579,7 +578,7 @@ int luacon_step(int mx, int my) int callret = lua_pcall(l, 0, 0, 0); if (callret) { - if (!strcmp(luacon_geterror(), "Error: Script not responding")) + if (luacon_geterror() == "Error: Script not responding") { ui::Engine::Ref().LastTick(Platform::GetTime()); for (int j = i; j <= len-1; j++) @@ -641,10 +640,10 @@ int luaL_tostring (lua_State *L, int n) return 1; } -const char *luacon_geterror() +String luacon_geterror() { luaL_tostring(luacon_ci->l, -1); - const char* err = luaL_optstring(luacon_ci->l, -1, "failed to execute"); + String err = ByteString(luaL_optstring(luacon_ci->l, -1, "failed to execute")).FromUtf8(); lua_pop(luacon_ci->l, 1); return err; } @@ -666,7 +665,7 @@ int luatpt_getelement(lua_State *l) t = luaL_optint(l, 1, 1); if (t<0 || t>=PT_NUM) return luaL_error(l, "Unrecognised element number '%d'", t); - lua_pushstring(l, luacon_sim->elements[t].Name); + lua_pushstring(l, luacon_sim->elements[t].Name.c_str()); } else { @@ -815,7 +814,7 @@ int luatpt_graphics_func(lua_State *l) int luatpt_error(lua_State* l) { - std::string errorMessage = std::string(luaL_optstring(l, 1, "Error text")); + String errorMessage = ByteString(luaL_optstring(l, 1, "Error text")).FromUtf8(); ErrorMessage::Blocking("Error", errorMessage); return 0; } @@ -842,7 +841,7 @@ int luatpt_drawtext(lua_State* l) if (textalpha<0) textalpha = 0; if (textalpha>255) textalpha = 255; - luacon_g->drawtext(textx, texty, string, textred, textgreen, textblue, textalpha); + luacon_g->drawtext(textx, texty, ByteString(string).FromUtf8(), textred, textgreen, textblue, textalpha); return 0; } @@ -860,7 +859,7 @@ int luatpt_create(lua_State* l) return luaL_error(l, "Unrecognised element number '%d'", t); } else { const char* name = luaL_optstring(l, 3, "dust"); - if ((t = luacon_sim->GetParticleType(std::string(name))) == -1) + if ((t = luacon_sim->GetParticleType(ByteString(name))) == -1) return luaL_error(l,"Unrecognised element '%s'", name); } retid = luacon_sim->create_part(-1, x, y, t); @@ -915,14 +914,14 @@ int luatpt_setconsole(lua_State* l) int luatpt_log(lua_State* l) { int args = lua_gettop(l); - std::string text = ""; + String text = ""; for(int i = 1; i <= args; i++) { luaL_tostring(l, -1); if(text.length()) - text=std::string(luaL_optstring(l, -1, "")) + ", " + text; + text=ByteString(luaL_optstring(l, -1, "")).FromUtf8() + ", " + text; else - text=std::string(luaL_optstring(l, -1, "")); + text=ByteString(luaL_optstring(l, -1, "")).FromUtf8(); lua_pop(l, 2); } if((*luacon_currentCommand)) @@ -1073,7 +1072,7 @@ int luatpt_set_property(lua_State* l) if(!lua_isnumber(l, acount) && lua_isstring(l, acount)) { name = luaL_optstring(l, acount, "none"); - if ((partsel = luacon_sim->GetParticleType(std::string(name))) == -1) + if ((partsel = luacon_sim->GetParticleType(ByteString(name))) == -1) return luaL_error(l, "Unrecognised element '%s'", name); } } @@ -1090,7 +1089,7 @@ int luatpt_set_property(lua_State* l) else { name = luaL_checklstring(l, 2, NULL); - if ((t = luacon_sim->GetParticleType(std::string(name)))==-1) + if ((t = luacon_sim->GetParticleType(ByteString(name)))==-1) return luaL_error(l, "Unrecognised element '%s'", name); } if (!lua_isnumber(l, 3) || acount >= 6) @@ -1276,7 +1275,7 @@ int luatpt_get_elecmap(lua_State* l) int luatpt_get_property(lua_State* l) { - std::string prop = luaL_optstring(l, 1, ""); + ByteString prop = luaL_optstring(l, 1, ""); int i = luaL_optint(l, 2, 0); //x coord or particle index, depending on arguments int y = luaL_optint(l, 3, -1); if (y!=-1 && y=0 && i < XRES && i>=0) @@ -1456,7 +1455,7 @@ int luatpt_textwidth(lua_State* l) { int strwidth = 0; const char* string = luaL_optstring(l, 1, ""); - strwidth = Graphics::textwidth(string); + strwidth = Graphics::textwidth(ByteString(string).FromUtf8()); lua_pushinteger(l, strwidth); return 1; } @@ -1671,22 +1670,22 @@ int luatpt_unregister_mouseclick(lua_State* l) int luatpt_input(lua_State* l) { - std::string prompt, title, result, shadow, text; - title = std::string(luaL_optstring(l, 1, "Title")); - prompt = std::string(luaL_optstring(l, 2, "Enter some text:")); - text = std::string(luaL_optstring(l, 3, "")); - shadow = std::string(luaL_optstring(l, 4, "")); + String prompt, title, result, shadow, text; + title = ByteString(luaL_optstring(l, 1, "Title")).FromUtf8(); + prompt = ByteString(luaL_optstring(l, 2, "Enter some text:")).FromUtf8(); + text = ByteString(luaL_optstring(l, 3, "")).FromUtf8(); + shadow = ByteString(luaL_optstring(l, 4, "")).FromUtf8(); result = TextPrompt::Blocking(title, prompt, text, shadow, false); - lua_pushstring(l, result.c_str()); + lua_pushstring(l, result.ToUtf8().c_str()); return 1; } int luatpt_message_box(lua_State* l) { - std::string title = std::string(luaL_optstring(l, 1, "Title")); - std::string message = std::string(luaL_optstring(l, 2, "Message")); + String title = ByteString(luaL_optstring(l, 1, "Title")).FromUtf8(); + String message = ByteString(luaL_optstring(l, 2, "Message")).FromUtf8(); int large = lua_toboolean(l, 3); new InformationMessage(title, message, large); return 0; @@ -1694,9 +1693,9 @@ int luatpt_message_box(lua_State* l) int luatpt_confirm(lua_State *l) { - std::string title = std::string(luaL_optstring(l, 1, "Title")); - std::string message = std::string(luaL_optstring(l, 2, "Message")); - std::string buttonText = std::string(luaL_optstring(l, 3, "Confirm")); + String title = ByteString(luaL_optstring(l, 1, "Title")).FromUtf8(); + String message = ByteString(luaL_optstring(l, 2, "Message")).FromUtf8(); + String buttonText = ByteString(luaL_optstring(l, 3, "Confirm")).FromUtf8(); bool ret = ConfirmPrompt::Blocking(title, message, buttonText); lua_pushboolean(l, ret ? 1 : 0); return 1; @@ -1915,9 +1914,9 @@ int luatpt_getscript(lua_State* l) int runScript = luaL_optint(l, 3, 0); int confirmPrompt = luaL_optint(l, 4, 1); - std::stringstream url; + ByteString::Stream url; url << "http://starcatcher.us/scripts/main.lua?get=" << scriptID; - if (confirmPrompt && !ConfirmPrompt::Blocking("Do you want to install script?", url.str(), "Install")) + if (confirmPrompt && !ConfirmPrompt::Blocking("Do you want to install script?", ByteString(url.str()).FromUtf8(), "Install")) return 0; int ret, len; @@ -1944,7 +1943,7 @@ int luatpt_getscript(lua_State* l) { fclose(outputfile); outputfile = NULL; - if (!confirmPrompt || ConfirmPrompt::Blocking("File already exists, overwrite?", filename, "Overwrite")) + if (!confirmPrompt || ConfirmPrompt::Blocking("File already exists, overwrite?", ByteString(filename).FromUtf8(), "Overwrite")) { outputfile = fopen(filename, "wb"); } @@ -1969,7 +1968,7 @@ int luatpt_getscript(lua_State* l) outputfile = NULL; if (runScript) { - std::stringstream luaCommand; + ByteString::Stream luaCommand; luaCommand << "dofile('" << filename << "')"; luaL_dostring(l, luaCommand.str().c_str()); } @@ -2019,7 +2018,7 @@ int luatpt_screenshot(lua_State* l) data = format::VideoBufferToPNG(screenshot); } } - std::stringstream filename; + ByteString::Stream filename; filename << "screenshot_"; filename << std::setfill('0') << std::setw(6) << (screenshotIndex++); if(fileType == 1) { diff --git a/src/lua/LuaButton.cpp b/src/lua/LuaButton.cpp index b4adf3b86..e13e83f32 100644 --- a/src/lua/LuaButton.cpp +++ b/src/lua/LuaButton.cpp @@ -26,8 +26,8 @@ LuaButton::LuaButton(lua_State * l) : int posY = luaL_optinteger(l, 2, 0); int sizeX = luaL_optinteger(l, 3, 10); int sizeY = luaL_optinteger(l, 4, 10); - std::string text = luaL_optstring(l, 5, ""); - std::string toolTip = luaL_optstring(l, 6, ""); + String text = ByteString(luaL_optstring(l, 5, "")).FromUtf8(); + String toolTip = ByteString(luaL_optstring(l, 6, "")).FromUtf8(); button = new ui::Button(ui::Point(posX, posY), ui::Point(sizeX, sizeY), text, toolTip); component = button; @@ -81,12 +81,12 @@ int LuaButton::text(lua_State * l) if(args) { luaL_checktype(l, 1, LUA_TSTRING); - button->SetText(lua_tostring(l, 1)); + button->SetText(ByteString(lua_tostring(l, 1)).FromUtf8()); return 0; } else { - lua_pushstring(l, button->GetText().c_str()); + lua_pushstring(l, button->GetText().ToUtf8().c_str()); return 1; } } @@ -99,7 +99,7 @@ void LuaButton::triggerAction() lua_rawgeti(l, LUA_REGISTRYINDEX, UserData); if (lua_pcall(l, 1, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } diff --git a/src/lua/LuaCheckbox.cpp b/src/lua/LuaCheckbox.cpp index 24883e916..6e9453468 100644 --- a/src/lua/LuaCheckbox.cpp +++ b/src/lua/LuaCheckbox.cpp @@ -26,7 +26,7 @@ LuaCheckbox::LuaCheckbox(lua_State * l) : int posY = luaL_optinteger(l, 2, 0); int sizeX = luaL_optinteger(l, 3, 10); int sizeY = luaL_optinteger(l, 4, 10); - std::string text = luaL_optstring(l, 5, ""); + String text = ByteString(luaL_optstring(l, 5, "")).FromUtf8(); checkbox = new ui::Checkbox(ui::Point(posX, posY), ui::Point(sizeX, sizeY), text, ""); component = checkbox; @@ -78,12 +78,12 @@ int LuaCheckbox::text(lua_State * l) int args = lua_gettop(l); if(args) { - checkbox->SetText(lua_tostring(l, 1)); + checkbox->SetText(ByteString(lua_tostring(l, 1)).FromUtf8()); return 0; } else { - lua_pushstring(l, checkbox->GetText().c_str()); + lua_pushstring(l, checkbox->GetText().ToUtf8().c_str()); return 1; } } @@ -97,7 +97,7 @@ void LuaCheckbox::triggerAction() lua_pushboolean(l, checkbox->GetChecked()); if (lua_pcall(l, 2, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } diff --git a/src/lua/LuaLabel.cpp b/src/lua/LuaLabel.cpp index 07ad636ac..53318a147 100644 --- a/src/lua/LuaLabel.cpp +++ b/src/lua/LuaLabel.cpp @@ -24,7 +24,7 @@ LuaLabel::LuaLabel(lua_State * l) : int posY = luaL_optinteger(l, 2, 0); int sizeX = luaL_optinteger(l, 3, 10); int sizeY = luaL_optinteger(l, 4, 10); - std::string text = luaL_optstring(l, 5, ""); + String text = ByteString(luaL_optstring(l, 5, "")).FromUtf8(); label = new ui::Label(ui::Point(posX, posY), ui::Point(sizeX, sizeY), text); component = label; @@ -35,12 +35,12 @@ int LuaLabel::text(lua_State * l) int args = lua_gettop(l); if(args) { - label->SetText(std::string(lua_tostring(l, 1))); + label->SetText(ByteString(lua_tostring(l, 1)).FromUtf8()); return 0; } else { - lua_pushstring(l, label->GetText().c_str()); + lua_pushstring(l, label->GetText().ToUtf8().c_str()); return 1; } } diff --git a/src/lua/LuaProgressBar.cpp b/src/lua/LuaProgressBar.cpp index cb6a9faaa..7a70e608a 100644 --- a/src/lua/LuaProgressBar.cpp +++ b/src/lua/LuaProgressBar.cpp @@ -25,7 +25,7 @@ LuaProgressBar::LuaProgressBar(lua_State * l) : int sizeX = luaL_optinteger(l, 3, 10); int sizeY = luaL_optinteger(l, 4, 10); int value = luaL_optinteger(l, 5, 0); - std::string status = luaL_optstring(l, 6, ""); + String status = ByteString(luaL_optstring(l, 6, "")).FromUtf8(); progressBar = new ui::ProgressBar(ui::Point(posX, posY), ui::Point(sizeX, sizeY), value, status); component = progressBar; @@ -51,12 +51,12 @@ int LuaProgressBar::status(lua_State * l) int args = lua_gettop(l); if(args) { - progressBar->SetStatus(std::string(lua_tostring(l, 1))); + progressBar->SetStatus(ByteString(lua_tostring(l, 1)).FromUtf8()); return 0; } else { - lua_pushstring(l, progressBar->GetStatus().c_str()); + lua_pushstring(l, progressBar->GetStatus().ToUtf8().c_str()); return 1; } } diff --git a/src/lua/LuaScriptHelper.h b/src/lua/LuaScriptHelper.h index 85e3730cd..db2790794 100644 --- a/src/lua/LuaScriptHelper.h +++ b/src/lua/LuaScriptHelper.h @@ -10,7 +10,7 @@ extern Renderer * luacon_ren; extern bool *luacon_currentCommand; extern int luaL_tostring(lua_State* l, int n); -extern std::string *luacon_lastError; +extern String *luacon_lastError; extern int *lua_el_func, *lua_el_mode, *lua_gr_func; @@ -25,7 +25,7 @@ int luacon_step(int mx, int my); int luacon_mouseevent(int mx, int my, int mb, int event, int mouse_wheel); int luacon_keyevent(int key, Uint16 character, int modifier, int event); int luacon_eval(const char *command); -const char *luacon_geterror(); +String luacon_geterror(); void luacon_close(); int luacon_partsread(lua_State* l); int luacon_partswrite(lua_State* l); diff --git a/src/lua/LuaScriptInterface.cpp b/src/lua/LuaScriptInterface.cpp index a89e775ae..6052f83c1 100644 --- a/src/lua/LuaScriptInterface.cpp +++ b/src/lua/LuaScriptInterface.cpp @@ -1,5 +1,4 @@ #ifdef LUACONSOLE -#include #include #include #include @@ -61,8 +60,8 @@ Graphics * luacon_g; Renderer * luacon_ren; bool *luacon_currentCommand; -std::string *luacon_lastError; -std::string lastCode; +String *luacon_lastError; +String lastCode; int *lua_el_func, *lua_el_mode, *lua_gr_func; @@ -74,7 +73,7 @@ int tptParts, tptPartsMeta, tptElementTransitions, tptPartsCData, tptPartMeta, t int atPanic(lua_State *l) { - throw std::runtime_error("Unprotected lua panic: " + std::string(lua_tostring(l, -1))); + throw std::runtime_error("Unprotected lua panic: " + ByteString(lua_tostring(l, -1))); } int TptIndexClosure(lua_State *l) @@ -296,9 +295,9 @@ tpt.partsdata = nil"); tptElements = lua_gettop(l); for (int i = 1; i < PT_NUM; i++) { - for (size_t j = 0; j < strlen(luacon_sim->elements[i].Name); j++) + for (size_t j = 0; j < luacon_sim->elements[i].Name.size(); j++) tmpname[j] = tolower(luacon_sim->elements[i].Name[j]); - tmpname[strlen(luacon_sim->elements[i].Name)] = 0; + tmpname[luacon_sim->elements[i].Name.size()] = 0; lua_newtable(l); currentElement = lua_gettop(l); @@ -321,9 +320,9 @@ tpt.partsdata = nil"); tptElementTransitions = lua_gettop(l); for (int i = 1; i < PT_NUM; i++) { - for (size_t j = 0; j < strlen(luacon_sim->elements[i].Name); j++) + for (size_t j = 0; j < luacon_sim->elements[i].Name.size(); j++) tmpname[j] = tolower(luacon_sim->elements[i].Name[j]); - tmpname[strlen(luacon_sim->elements[i].Name)] = 0; + tmpname[luacon_sim->elements[i].Name.size()] = 0; lua_newtable(l); currentElement = lua_gettop(l); @@ -381,7 +380,7 @@ void LuaScriptInterface::SetWindow(ui::Window * window) int LuaScriptInterface::tpt_index(lua_State *l) { - std::string key = luaL_checkstring(l, 2); + ByteString key = luaL_checkstring(l, 2); if (!key.compare("selectedl")) return lua_pushstring(l, luacon_selectedl.c_str()), 1; if (!key.compare("selectedr")) @@ -403,7 +402,7 @@ int LuaScriptInterface::tpt_index(lua_State *l) int LuaScriptInterface::tpt_newIndex(lua_State *l) { - std::string key = luaL_checkstring(l, 2); + ByteString key = luaL_checkstring(l, 2); if (!key.compare("selectedl")) { Tool *t = m->GetToolFromIdentifier(luaL_checkstring(l, 3)); @@ -543,7 +542,7 @@ int LuaScriptInterface::interface_closeWindow(lua_State * l) int LuaScriptInterface::simulation_signIndex(lua_State *l) { - std::string key = luaL_checkstring(l, 2); + ByteString key = luaL_checkstring(l, 2); //Get Raw Index value for element. Maybe there is a way to get the sign index some other way? lua_pushstring(l, "id"); @@ -561,9 +560,9 @@ int LuaScriptInterface::simulation_signIndex(lua_State *l) } if (!key.compare("text")) - return lua_pushstring(l, luacon_sim->signs[id].text.c_str()), 1; + return lua_pushstring(l, luacon_sim->signs[id].text.ToUtf8().c_str()), 1; else if (!key.compare("displayText")) - return lua_pushstring(l, luacon_sim->signs[id].getText(luacon_sim).c_str()), 1; + return lua_pushstring(l, luacon_sim->signs[id].getText(luacon_sim).ToUtf8().c_str()), 1; else if (!key.compare("justification")) return lua_pushnumber(l, (int)luacon_sim->signs[id].ju), 1; else if (!key.compare("x")) @@ -604,7 +603,7 @@ int LuaScriptInterface::simulation_signIndex(lua_State *l) int LuaScriptInterface::simulation_signNewIndex(lua_State *l) { - std::string key = luaL_checkstring(l, 2); + ByteString key = luaL_checkstring(l, 2); //Get Raw Index value for element. Maybe there is a way to get the sign index some other way? lua_pushstring(l, "id"); @@ -624,7 +623,7 @@ int LuaScriptInterface::simulation_signNewIndex(lua_State *l) if (!key.compare("text")) { const char *temp = luaL_checkstring(l, 3); - std::string cleaned = format::CleanString(temp, false, true, true).substr(0, 45); + String cleaned = format::CleanString(ByteString(temp).FromUtf8(), false, true, true).substr(0, 45); if (!cleaned.empty()) luacon_sim->signs[id].text = cleaned; else @@ -671,7 +670,7 @@ int LuaScriptInterface::simulation_newsign(lua_State *l) if (luacon_sim->signs.size() >= MAXSIGNS) return lua_pushnil(l), 1; - std::string text = format::CleanString(luaL_checkstring(l, 1), false, true, true).substr(0, 45); + String text = format::CleanString(ByteString(luaL_checkstring(l, 1)).FromUtf8(), false, true, true).substr(0, 45); int x = luaL_checkinteger(l, 2); int y = luaL_checkinteger(l, 3); int ju = luaL_optinteger(l, 4, 1); @@ -810,7 +809,7 @@ void LuaScriptInterface::initSimulationAPI() particleProperties = new StructProperty[particlePropertiesV.size()]; for(std::vector::iterator iter = particlePropertiesV.begin(), end = particlePropertiesV.end(); iter != end; ++iter) { - std::string propertyName = (*iter).Name; + ByteString propertyName = (*iter).Name; std::transform(propertyName.begin(), propertyName.end(), propertyName.begin(), ::toupper); lua_pushinteger(l, particlePropertiesCount); lua_setfield(l, -2, ("FIELD_"+propertyName).c_str()); @@ -1018,7 +1017,7 @@ int LuaScriptInterface::simulation_partProperty(lua_State * l) return luaL_error(l, "Invalid field ID (%d)", fieldID); property = &particleProperties[fieldID]; } else if(lua_type(l, 2) == LUA_TSTRING) { - std::string fieldName = lua_tostring(l, 2); + ByteString fieldName = lua_tostring(l, 2); for(int i = particlePropertiesCount-1; i >= 0; i--) { if(particleProperties[i].Name == fieldName) @@ -1687,7 +1686,7 @@ int LuaScriptInterface::simulation_saveStamp(lua_State * l) int w = luaL_optint(l,3,XRES-1); int h = luaL_optint(l,4,YRES-1); int includePressure = luaL_optint(l,5,1); - std::string name = luacon_controller->StampRegion(ui::Point(x, y), ui::Point(x+w, y+h), includePressure); + ByteString name = luacon_controller->StampRegion(ui::Point(x, y), ui::Point(x+w, y+h), includePressure); lua_pushstring(l, name.c_str()); return 1; } @@ -1738,12 +1737,12 @@ int LuaScriptInterface::simulation_loadStamp(lua_State * l) int LuaScriptInterface::simulation_deleteStamp(lua_State * l) { int stampCount = Client::Ref().GetStampsCount(); - std::vector stamps = Client::Ref().GetStamps(0, stampCount); + std::vector stamps = Client::Ref().GetStamps(0, stampCount); if (lua_isstring(l, 1)) //note: lua_isstring returns true on numbers too { const char * filename = luaL_optstring(l, 1, ""); - for (std::vector::const_iterator iterator = stamps.begin(), end = stamps.end(); iterator != end; ++iterator) + for (std::vector::const_iterator iterator = stamps.begin(), end = stamps.end(); iterator != end; ++iterator) { if (*iterator == filename) { @@ -2440,10 +2439,10 @@ void LuaScriptInterface::initElementsAPI() if(luacon_sim->elements[i].Enabled) { lua_pushinteger(l, i); - lua_setfield(l, -2, luacon_sim->elements[i].Identifier); + lua_setfield(l, -2, luacon_sim->elements[i].Identifier.c_str()); char realIdentifier[20]; - sprintf(realIdentifier, "DEFAULT_PT_%s", luacon_sim->elements[i].Name); - if (i != 0 && i != PT_NBHL && i != PT_NWHL && strcmp(luacon_sim->elements[i].Identifier, realIdentifier)) + sprintf(realIdentifier, "DEFAULT_PT_%s", luacon_sim->elements[i].Name.c_str()); + if (i != 0 && i != PT_NBHL && i != PT_NWHL && luacon_sim->elements[i].Identifier != realIdentifier) { lua_pushinteger(l, i); lua_setfield(l, -2, realIdentifier); @@ -2464,7 +2463,7 @@ int LuaScriptInterface::elements_loadDefault(lua_State * l) lua_getglobal(l, "elements"); lua_pushnil(l); - lua_setfield(l, -2, luacon_sim->elements[id].Identifier); + lua_setfield(l, -2, luacon_sim->elements[id].Identifier.c_str()); std::vector elementList = GetElements(); if (id < (int)elementList.size()) @@ -2473,7 +2472,7 @@ int LuaScriptInterface::elements_loadDefault(lua_State * l) luacon_sim->elements[id] = Element(); lua_pushinteger(l, id); - lua_setfield(l, -2, luacon_sim->elements[id].Identifier); + lua_setfield(l, -2, luacon_sim->elements[id].Identifier.c_str()); lua_pop(l, 1); } else @@ -2507,12 +2506,12 @@ int LuaScriptInterface::elements_loadDefault(lua_State * l) int LuaScriptInterface::elements_allocate(lua_State * l) { - std::string group, id, identifier; + ByteString group, id, identifier; luaL_checktype(l, 1, LUA_TSTRING); luaL_checktype(l, 2, LUA_TSTRING); - group = std::string(lua_tostring(l, 1)); + group = ByteString(lua_tostring(l, 1)); std::transform(group.begin(), group.end(), group.begin(), ::toupper); - id = std::string(lua_tostring(l, 2)); + id = ByteString(lua_tostring(l, 2)); std::transform(id.begin(), id.end(), id.begin(), ::toupper); if(group == "DEFAULT") @@ -2522,7 +2521,7 @@ int LuaScriptInterface::elements_allocate(lua_State * l) for(int i = 0; i < PT_NUM; i++) { - if(luacon_sim->elements[i].Enabled && std::string(luacon_sim->elements[i].Identifier) == identifier) + if(luacon_sim->elements[i].Enabled && ByteString(luacon_sim->elements[i].Identifier) == identifier) return luaL_error(l, "Element identifier already in use"); } @@ -2699,7 +2698,7 @@ int LuaScriptInterface::elements_element(lua_State * l) } lua_setfield(l, -2, (*iter).Name.c_str()); } - lua_pushstring(l, luacon_sim->elements[id].Identifier); + lua_pushstring(l, luacon_sim->elements[id].Identifier.c_str()); lua_setfield(l, -2, "Identifier"); return 1; } @@ -2709,11 +2708,11 @@ int LuaScriptInterface::elements_property(lua_State * l) { int args = lua_gettop(l); int id; - std::string propertyName; + ByteString propertyName; luaL_checktype(l, 1, LUA_TNUMBER); id = lua_tointeger(l, 1); luaL_checktype(l, 2, LUA_TSTRING); - propertyName = std::string(lua_tostring(l, 2)); + propertyName = ByteString(lua_tostring(l, 2)); if(id < 0 || id >= PT_NUM || !luacon_sim->elements[id].Enabled) return luaL_error(l, "Invalid element"); @@ -2877,7 +2876,7 @@ int LuaScriptInterface::elements_property(lua_State * l) } else if(propertyName == "Identifier") { - lua_pushstring(l, luacon_sim->elements[id].Identifier); + lua_pushstring(l, luacon_sim->elements[id].Identifier.c_str()); return 1; } else @@ -2894,7 +2893,7 @@ int LuaScriptInterface::elements_free(lua_State * l) if(id < 0 || id >= PT_NUM || !luacon_sim->elements[id].Enabled) return luaL_error(l, "Invalid element"); - std::string identifier = luacon_sim->elements[id].Identifier; + ByteString identifier = luacon_sim->elements[id].Identifier; if(identifier.length()>7 && identifier.substr(0, 7) == "DEFAULT") return luaL_error(l, "Cannot free default elements"); @@ -2937,7 +2936,7 @@ int LuaScriptInterface::graphics_textSize(lua_State * l) { int width, height; const char* text = luaL_optstring(l, 1, ""); - Graphics::textsize(text, width, height); + Graphics::textsize(ByteString(text).FromUtf8(), width, height); lua_pushinteger(l, width); lua_pushinteger(l, height); @@ -2963,7 +2962,7 @@ int LuaScriptInterface::graphics_drawText(lua_State * l) if (a<0) a = 0; else if (a>255) a = 255; - luacon_g->drawtext(x, y, text, r, g, b, a); + luacon_g->drawtext(x, y, ByteString(text).FromUtf8(), r, g, b, a); return 0; } @@ -3379,7 +3378,7 @@ int LuaScriptInterface::platform_releaseType(lua_State * l) int LuaScriptInterface::platform_exeName(lua_State * l) { - std::string name = Platform::ExecutableName(); + ByteString name = Platform::ExecutableName(); if (name.length()) lua_pushstring(l, name.c_str()); else @@ -3415,7 +3414,7 @@ int LuaScriptInterface::platform_clipboardPaste(lua_State * l) bool LuaScriptInterface::OnActiveToolChanged(int toolSelection, Tool * tool) { - std::string identifier; + ByteString identifier; if (tool) identifier = tool->GetIdentifier(); else @@ -3520,7 +3519,7 @@ void LuaScriptInterface::OnTick() luacon_step(luacon_mousex, luacon_mousey); } -int LuaScriptInterface::Command(std::string command) +int LuaScriptInterface::Command(String command) { if (command[0] == '!') { @@ -3532,24 +3531,24 @@ int LuaScriptInterface::Command(std::string command) else { int level = lua_gettop(l), ret = -1; - std::string text = ""; + String text = ""; lastError = ""; currentCommand = true; if (lastCode.length()) lastCode += "\n"; lastCode += command; - std::string tmp = "return " + lastCode; + String tmp = "return " + lastCode; ui::Engine::Ref().LastTick(Platform::GetTime()); - luaL_loadbuffer(l, tmp.c_str(), tmp.length(), "@console"); + luaL_loadbuffer(l, tmp.ToUtf8().c_str(), tmp.length(), "@console"); if (lua_type(l, -1) != LUA_TFUNCTION) { lua_pop(l, 1); - luaL_loadbuffer(l, lastCode.c_str(), lastCode.length(), "@console"); + luaL_loadbuffer(l, lastCode.ToUtf8().c_str(), lastCode.length(), "@console"); } if (lua_type(l, -1) != LUA_TFUNCTION) { lastError = luacon_geterror(); - std::string err = lastError; + String err = lastError; if (err.find("near ''") != err.npos) //the idea stolen from lua-5.1.5/lua.c lastError = "..."; else @@ -3567,9 +3566,9 @@ int LuaScriptInterface::Command(std::string command) { luaL_tostring(l, level); if (text.length()) - text += ", " + std::string(luaL_optstring(l, -1, "")); + text += ", " + ByteString(luaL_optstring(l, -1, "")).FromUtf8(); else - text = std::string(luaL_optstring(l, -1, "")); + text = ByteString(luaL_optstring(l, -1, "")).FromUtf8(); lua_pop(l, 1); } if (text.length()) @@ -3606,39 +3605,39 @@ int strlcmp(const char* a, const char* b, int len) return -1; } -std::string highlight(std::string command) +String highlight(String command) { -#define CMP(X) (!strlcmp(wstart, X, len)) - std::stringstream result; +#define CMP(X) (String(wstart, len) == X) + String::Stream result; int pos = 0; - const char *raw = command.c_str(); - char c; + String::value_type const*raw = command.c_str(); + String::value_type c; while ((c = raw[pos])) { if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_') { int len = 0; - char w; - const char* wstart = raw+pos; + String::value_type w; + String::value_type const* wstart = raw+pos; while((w = wstart[len]) && ((w >= 'A' && w <= 'Z') || (w >= 'a' && w <= 'z') || (w >= '0' && w <= '9') || w == '_')) len++; if(CMP("and") || CMP("break") || CMP("do") || CMP("else") || CMP("elseif") || CMP("end") || CMP("for") || CMP("function") || CMP("if") || CMP("in") || CMP("local") || CMP("not") || CMP("or") || CMP("repeat") || CMP("return") || CMP("then") || CMP("until") || CMP("while")) { - result << "\x0F\xB5\x89\x01"; + result << String("\x0F\xB5\x89\x01"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); } else if(CMP("false") || CMP("nil") || CMP("true")) { - result << "\x0F\xCB\x4B\x16"; + result << String("\x0F\xCB\x4B\x16"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); } else { - result << "\x0F\x2A\xA1\x98"; + result << String("\x0F\x2A\xA1\x98"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); } pos += len; } @@ -3647,20 +3646,20 @@ std::string highlight(std::string command) if(c == '0' && raw[pos + 1] == 'x') { int len = 2; - char w; - const char *wstart = raw + pos; + String::value_type w; + String::value_type const* wstart = raw+pos; while((w = wstart[len]) && ((w >= '0' && w <= '9') || (w >= 'A' && w <= 'F') || (w >= 'a' && w <= 'f'))) len++; - result << "\x0F\xD3\x36\x82"; + result << String("\x0F\xD3\x36\x82"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); pos += len; } else { int len = 0; - char w; - const char *wstart = raw+pos; + String::value_type w; + String::value_type const* wstart = raw+pos; bool seendot = false; while((w = wstart[len]) && ((w >= '0' && w <= '9') || w == '.')) { @@ -3682,9 +3681,9 @@ std::string highlight(std::string command) while((w = wstart[len]) && (w >= '0' && w <= '9')) len++; } - result << "\x0F\xD3\x36\x82"; + result << String("\x0F\xD3\x36\x82"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); pos += len; } } @@ -3693,8 +3692,8 @@ std::string highlight(std::string command) if(c == '[') { int len = 1, eqs=0; - char w; - const char *wstart = raw + pos; + String::value_type w; + String::value_type const* wstart = raw + pos; while((w = wstart[len]) && (w == '=')) { eqs++; @@ -3705,7 +3704,7 @@ std::string highlight(std::string command) if(w == ']') { int nlen = 1; - const char *cstart = wstart + len; + String::value_type const* cstart = wstart + len; while((w = cstart[nlen]) && (w == '=')) nlen++; if(w == ']' && nlen == eqs+1) @@ -3716,16 +3715,16 @@ std::string highlight(std::string command) } len++; } - result << "\x0F\xDC\x32\x2F"; + result << String("\x0F\xDC\x32\x2F"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); pos += len; } else { int len = 1; - char w; - const char *wstart = raw+pos; + String::value_type w; + String::value_type const* wstart = raw+pos; while((w = wstart[len]) && (w != c)) { if(w == '\\' && wstart[len + 1]) @@ -3734,9 +3733,9 @@ std::string highlight(std::string command) } if(w == c) len++; - result << "\x0F\xDC\x32\x2F"; + result << String("\x0F\xDC\x32\x2F"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); pos += len; } } @@ -3745,8 +3744,8 @@ std::string highlight(std::string command) if(raw[pos + 2] == '[') { int len = 3, eqs = 0; - char w; - const char *wstart = raw + pos; + String::value_type w; + String::value_type const* wstart = raw + pos; while((w = wstart[len]) && (w == '=')) { eqs++; @@ -3757,7 +3756,7 @@ std::string highlight(std::string command) if(w == ']') { int nlen = 1; - const char *cstart = wstart + len; + String::value_type const* cstart = wstart + len; while((w = cstart[nlen]) && (w == '=')) nlen++; if(w == ']' && nlen == eqs + 1) @@ -3768,32 +3767,32 @@ std::string highlight(std::string command) } len++; } - result << "\x0F\x85\x99\x01"; + result << String("\x0F\x85\x99\x01"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); pos += len; } else { int len = 2; - char w; - const char *wstart = raw + pos; + String::value_type w; + String::value_type const* wstart = raw + pos; while((w = wstart[len]) && (w != '\n')) len++; - result << "\x0F\x85\x99\x01"; + result << String("\x0F\x85\x99\x01"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); pos += len; } } else if(c == '{' || c == '}') { - result << "\x0F\xCB\x4B\x16" << c; + result << String("\x0F\xCB\x4B\x16") << c; pos++; } else if(c == '.' && raw[pos + 1] == '.' && raw[pos + 2] == '.') { - result << "\x0F\x2A\xA1\x98..."; + result << String("\x0F\x2A\xA1\x98..."); pos += 3; } else @@ -3805,9 +3804,9 @@ std::string highlight(std::string command) return result.str(); } -std::string LuaScriptInterface::FormatCommand(std::string command) +String LuaScriptInterface::FormatCommand(String command) { - if(command != "" && command[0] == '!') + if(command.size() && command[0] == '!') { return "!"+legacy->FormatCommand(command.substr(1)); } diff --git a/src/lua/LuaScriptInterface.h b/src/lua/LuaScriptInterface.h index 175bd3dba..24492731b 100644 --- a/src/lua/LuaScriptInterface.h +++ b/src/lua/LuaScriptInterface.h @@ -37,7 +37,7 @@ class TPTScriptInterface; class LuaScriptInterface: public CommandInterface { int luacon_mousex, luacon_mousey, luacon_mousebutton; - std::string luacon_selectedl, luacon_selectedr, luacon_selectedalt, luacon_selectedreplace; + ByteString luacon_selectedl, luacon_selectedr, luacon_selectedalt, luacon_selectedreplace; bool luacon_mousedown; bool currentCommand; TPTScriptInterface * legacy; @@ -185,8 +185,8 @@ public: virtual void OnTick(); virtual void Init(); virtual void SetWindow(ui::Window * window); - virtual int Command(std::string command); - virtual std::string FormatCommand(std::string command); + virtual int Command(String command); + virtual String FormatCommand(String command); virtual ~LuaScriptInterface(); }; diff --git a/src/lua/LuaSlider.cpp b/src/lua/LuaSlider.cpp index 28b847bfa..1034f9346 100644 --- a/src/lua/LuaSlider.cpp +++ b/src/lua/LuaSlider.cpp @@ -97,7 +97,7 @@ void LuaSlider::triggerOnValueChanged() lua_pushinteger(l, slider->GetValue()); if (lua_pcall(l, 2, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } diff --git a/src/lua/LuaTextbox.cpp b/src/lua/LuaTextbox.cpp index 474c02d00..c3cd6c97a 100644 --- a/src/lua/LuaTextbox.cpp +++ b/src/lua/LuaTextbox.cpp @@ -27,8 +27,8 @@ LuaTextbox::LuaTextbox(lua_State * l) : int posY = luaL_optinteger(l, 2, 0); int sizeX = luaL_optinteger(l, 3, 10); int sizeY = luaL_optinteger(l, 4, 10); - std::string text = luaL_optstring(l, 5, ""); - std::string placeholder = luaL_optstring(l, 6, ""); + String text = ByteString(luaL_optstring(l, 5, "")).FromUtf8(); + String placeholder = ByteString(luaL_optstring(l, 6, "")).FromUtf8(); textbox = new ui::Textbox(ui::Point(posX, posY), ui::Point(sizeX, sizeY), text, placeholder); textbox->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; @@ -85,7 +85,7 @@ void LuaTextbox::triggerOnTextChanged() lua_rawgeti(l, LUA_REGISTRYINDEX, UserData); if (lua_pcall(l, 1, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -95,12 +95,12 @@ int LuaTextbox::text(lua_State * l) int args = lua_gettop(l); if(args) { - textbox->SetText(std::string(lua_tostring(l, 1))); + textbox->SetText(ByteString(lua_tostring(l, 1)).FromUtf8()); return 0; } else { - lua_pushstring(l, textbox->GetText().c_str()); + lua_pushstring(l, textbox->GetText().ToUtf8().c_str()); return 1; } } diff --git a/src/lua/LuaWindow.cpp b/src/lua/LuaWindow.cpp index 4b7204b92..b7e4c79e5 100644 --- a/src/lua/LuaWindow.cpp +++ b/src/lua/LuaWindow.cpp @@ -208,7 +208,7 @@ void LuaWindow::triggerOnInitialized() lua_rawgeti(l, LUA_REGISTRYINDEX, onInitializedFunction); if(lua_pcall(l, 0, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -220,7 +220,7 @@ void LuaWindow::triggerOnExit() lua_rawgeti(l, LUA_REGISTRYINDEX, onExitFunction); if(lua_pcall(l, 0, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -233,7 +233,7 @@ void LuaWindow::triggerOnTick(float dt) lua_pushnumber(l, dt); if(lua_pcall(l, 1, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -245,7 +245,7 @@ void LuaWindow::triggerOnDraw() lua_rawgeti(l, LUA_REGISTRYINDEX, onDrawFunction); if(lua_pcall(l, 0, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -257,7 +257,7 @@ void LuaWindow::triggerOnFocus() lua_rawgeti(l, LUA_REGISTRYINDEX, onFocusFunction); if(lua_pcall(l, 0, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -269,7 +269,7 @@ void LuaWindow::triggerOnBlur() lua_rawgeti(l, LUA_REGISTRYINDEX, onBlurFunction); if(lua_pcall(l, 0, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -281,7 +281,7 @@ void LuaWindow::triggerOnTryExit() lua_rawgeti(l, LUA_REGISTRYINDEX, onTryExitFunction); if(lua_pcall(l, 0, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -293,7 +293,7 @@ void LuaWindow::triggerOnTryOkay() lua_rawgeti(l, LUA_REGISTRYINDEX, onTryOkayFunction); if(lua_pcall(l, 0, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -309,7 +309,7 @@ void LuaWindow::triggerOnMouseMove(int x, int y, int dx, int dy) lua_pushinteger(l, dy); if(lua_pcall(l, 4, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -324,7 +324,7 @@ void LuaWindow::triggerOnMouseDown(int x, int y, unsigned button) lua_pushinteger(l, button); if(lua_pcall(l, 3, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -339,7 +339,7 @@ void LuaWindow::triggerOnMouseUp(int x, int y, unsigned button) lua_pushinteger(l, button); if(lua_pcall(l, 3, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -354,7 +354,7 @@ void LuaWindow::triggerOnMouseWheel(int x, int y, int d) lua_pushinteger(l, d); if(lua_pcall(l, 3, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -371,7 +371,7 @@ void LuaWindow::triggerOnKeyPress(int key, Uint16 character, bool shift, bool ct lua_pushboolean(l, alt); if(lua_pcall(l, 5, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -388,7 +388,7 @@ void LuaWindow::triggerOnKeyRelease(int key, Uint16 character, bool shift, bool lua_pushboolean(l, alt); if(lua_pcall(l, 5, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } diff --git a/src/lua/TPTSTypes.cpp b/src/lua/TPTSTypes.cpp index 0779e02f5..caaa6917a 100644 --- a/src/lua/TPTSTypes.cpp +++ b/src/lua/TPTSTypes.cpp @@ -1,5 +1,4 @@ #include -#include #include #include "TPTSTypes.h" @@ -19,7 +18,7 @@ AnyType::AnyType(const AnyType & v): value(v.value) { if(type == TypeString) - value.str = new std::string(*(value.str)); + value.str = new String(*(value.str)); else if(type == TypePoint) value.pt = new ui::Point(*(value.pt)); } @@ -48,7 +47,7 @@ AnyType::operator StringType() { if(type == TypeNumber) { - std::stringstream numberStream; + String::Stream numberStream; numberStream << ((NumberType *)this)->Value(); return StringType(numberStream.str()); } @@ -59,7 +58,7 @@ AnyType::operator StringType() else if (type == TypePoint && value.pt) { ui::Point thisPoint = *(value.pt); - std::stringstream pointStream; + String::Stream pointStream; pointStream << thisPoint.X << "," << thisPoint.Y; return StringType(pointStream.str()); } @@ -76,9 +75,9 @@ AnyType::operator PointType() } else if(type == TypeString) { - std::stringstream pointStream(*(value.str)); + String::Stream pointStream(*(value.str)); int x, y; - char comma; + String::value_type comma; pointStream >> x >> comma >> y; if (pointStream.fail() || comma != ',') throw InvalidConversionException(type, TypePoint); @@ -122,12 +121,12 @@ float FloatType::Value() //String type -StringType::StringType(std::string string): AnyType(TypeString, ValueValue()) +StringType::StringType(String string): AnyType(TypeString, ValueValue()) { - value.str = new std::string(string); + value.str = new String(string); } -std::string StringType::Value() +String StringType::Value() { return *value.str; } diff --git a/src/lua/TPTSTypes.h b/src/lua/TPTSTypes.h index 12f34d812..93b16fbc5 100644 --- a/src/lua/TPTSTypes.h +++ b/src/lua/TPTSTypes.h @@ -1,22 +1,22 @@ #ifndef TPTSTYPES_H_ #define TPTSTYPES_H_ -#include +#include "common/String.h" #include #include "gui/interface/Point.h" enum ValueType { TypeNumber, TypeFloat, TypePoint, TypeString, TypeNull, TypeFunction }; -typedef union { int num; float numf; std::string* str; ui::Point* pt; } ValueValue; +typedef union { int num; float numf; String* str; ui::Point* pt; } ValueValue; class GeneralException { protected: - std::string exception; + String exception; public: - GeneralException(std::string message){ + GeneralException(String message){ exception = message; } - std::string GetExceptionMessage() { + String GetExceptionMessage() { return exception; } }; @@ -40,7 +40,7 @@ public: operator StringType(); operator PointType(); ValueType GetType(); - std::string TypeName() + ByteString TypeName() { switch(type) { @@ -60,7 +60,7 @@ public: return "Unknown"; } } - static std::string TypeName(ValueType type) + static ByteString TypeName(ValueType type) { switch(type) { @@ -87,7 +87,7 @@ class InvalidConversionException: public GeneralException { public: InvalidConversionException(ValueType from_, ValueType to_): - GeneralException("Invalid conversion from " + AnyType::TypeName(from_) + " to " + AnyType::TypeName(to_)) { + GeneralException("Invalid conversion from " + AnyType::TypeName(from_).FromAscii() + " to " + AnyType::TypeName(to_).FromAscii()) { } }; @@ -108,8 +108,8 @@ public: class StringType: public AnyType { public: - StringType(std::string string); - std::string Value(); + StringType(String string); + String Value(); }; class PointType: public AnyType diff --git a/src/lua/TPTScriptInterface.cpp b/src/lua/TPTScriptInterface.cpp index 8b66d46dc..7e46d8f7b 100644 --- a/src/lua/TPTScriptInterface.cpp +++ b/src/lua/TPTScriptInterface.cpp @@ -1,6 +1,5 @@ #include #include -#include #include #include #ifdef MACOSX @@ -15,26 +14,18 @@ TPTScriptInterface::TPTScriptInterface(GameController * c, GameModel * m): Comma { } -int TPTScriptInterface::Command(std::string command) +int TPTScriptInterface::Command(String command) { lastError = ""; - std::deque words; + std::deque words; std::deque commandWords; int retCode = -1; //Split command into words, put them on the stack - char * rawCommand; - rawCommand = (char*)calloc(command.length()+1, 1); - memcpy(rawCommand, (char*)command.c_str(), command.length()); - char * currentWord = rawCommand; - char * currentCommand = rawCommand; - while((currentCommand = strchr(currentCommand, ' '))) - { - currentCommand[0] = 0; - words.push_back(std::string(currentWord)); - currentWord = ++currentCommand; - } - words.push_back(std::string(currentWord)); + String::Stream ss(command); + String word; + while(std::getline(ss, word, String::value_type(' '))) + words.push_back(word); while(!words.empty()) { try @@ -48,7 +39,6 @@ int TPTScriptInterface::Command(std::string command) break; } } - free(rawCommand); if(commandWords.size()) { retCode = 0; @@ -59,10 +49,10 @@ int TPTScriptInterface::Command(std::string command) return retCode; } -ValueType TPTScriptInterface::testType(std::string word) +ValueType TPTScriptInterface::testType(String word) { size_t i = 0; - char * rawWord = (char *)word.c_str(); + String::value_type const *rawWord = word.c_str(); //Function if (word == "set") return TypeFunction; @@ -129,8 +119,9 @@ parseString: return TypeString; } -int TPTScriptInterface::parseNumber(char * stringData) +int TPTScriptInterface::parseNumber(String str) { + String::value_type const *stringData = str.c_str(); char cc; int base = 10; int currentNumber = 0; @@ -161,17 +152,19 @@ int TPTScriptInterface::parseNumber(char * stringData) } else { - return atoi(stringData); + int number; + String::Stream ss(str); + ss >> number; + return number; } return currentNumber; } -AnyType TPTScriptInterface::eval(std::deque * words) +AnyType TPTScriptInterface::eval(std::deque * words) { if(words->size() < 1) return AnyType(TypeNull, ValueValue()); - std::string word = words->front(); words->pop_front(); - char * rawWord = (char *)word.c_str(); + String word = words->front(); words->pop_front(); ValueType wordType = testType(word); switch(wordType) { @@ -192,14 +185,16 @@ AnyType TPTScriptInterface::eval(std::deque * words) return tptS_quit(words); break; case TypeNumber: - return NumberType(parseNumber(rawWord)); + return NumberType(parseNumber(word)); case TypeFloat: - return FloatType(atof(rawWord)); + return FloatType(atof(word.ToUtf8().c_str())); case TypePoint: { - int pointX, pointY; - sscanf(rawWord, "%d,%d", &pointX, &pointY); - return PointType(pointX, pointY); + String::Stream pointStream(word); + int x, y; + String::value_type comma; + pointStream >> x >> comma >> y; + return PointType(x, y); } case TypeString: return StringType(word); @@ -209,26 +204,17 @@ AnyType TPTScriptInterface::eval(std::deque * words) return StringType(word); } -std::string TPTScriptInterface::FormatCommand(std::string command) +String TPTScriptInterface::FormatCommand(String command) { - std::deque words; + std::deque words; std::deque commandWords; - std::string outputData; + String outputData; //Split command into words, put them on the stack - char * rawCommand; - rawCommand = (char*)calloc(command.length()+1, 1); - memcpy(rawCommand, (char*)command.c_str(), command.length()); - char * currentWord = rawCommand; - char * currentCommand = rawCommand; - while((currentCommand = strchr(currentCommand, ' '))) - { - currentCommand[0] = 0; - words.push_back(std::string(currentWord)); - currentWord = ++currentCommand; - } - words.push_back(std::string(currentWord)); - free(rawCommand); + String::Stream ss(command); + String word; + while(std::getline(ss, word, String::value_type(' '))) + words.push_back(word); while(!words.empty()) { ValueType cType = testType(words.front()); @@ -254,7 +240,7 @@ std::string TPTScriptInterface::FormatCommand(std::string command) return outputData; } -AnyType TPTScriptInterface::tptS_set(std::deque * words) +AnyType TPTScriptInterface::tptS_set(std::deque * words) { //Arguments from stack StringType property = eval(words); @@ -267,7 +253,7 @@ AnyType TPTScriptInterface::tptS_set(std::deque * words) int returnValue = 0; FormatType propertyFormat; - int propertyOffset = GetPropertyOffset(property.Value(), propertyFormat); + int propertyOffset = GetPropertyOffset(property.Value().ToUtf8(), propertyFormat); if (propertyOffset == -1) throw GeneralException("Invalid property"); @@ -286,21 +272,21 @@ AnyType TPTScriptInterface::tptS_set(std::deque * words) { if (property.Value() == "temp") { - std::string newString = ((StringType)value).Value(); + String newString = ((StringType)value).Value(); if (newString.at(newString.length()-1) == 'C') - newValuef = atof(newString.substr(0, newString.length()-1).c_str())+273.15; + newValuef = atof(newString.substr(0, newString.length()-1).ToUtf8().c_str())+273.15; else if (newString.at(newString.length()-1) == 'F') - newValuef = (atof(newString.substr(0, newString.length()-1).c_str())-32.0f)*5/9+273.15f; + newValuef = (atof(newString.substr(0, newString.length()-1).ToUtf8().c_str())-32.0f)*5/9+273.15f; else throw GeneralException("Invalid value for assignment"); } else { - newValue = m->GetSimulation()->GetParticleType(((StringType)value).Value()); + newValue = m->GetSimulation()->GetParticleType(((StringType)value).Value().ToUtf8()); if (newValue < 0 || newValue >= PT_NUM) { // TODO: add element CAKE to invalidate this - if (!strcasecmp(((StringType)value).Value().c_str(),"cake")) + if (!strcasecmp(((StringType)value).Value().ToUtf8().c_str(),"cake")) throw GeneralException("Cake is a lie, not an element"); throw GeneralException("Invalid element"); } @@ -386,7 +372,7 @@ AnyType TPTScriptInterface::tptS_set(std::deque * words) if (selector.GetType() == TypeNumber) type = ((NumberType)selector).Value(); else if (selector.GetType() == TypeString) - type = m->GetSimulation()->GetParticleType(((StringType)selector).Value()); + type = m->GetSimulation()->GetParticleType(((StringType)selector).Value().ToUtf8()); if (type<0 || type>=PT_NUM) throw GeneralException("Invalid particle type"); @@ -433,7 +419,7 @@ AnyType TPTScriptInterface::tptS_set(std::deque * words) return NumberType(returnValue); } -AnyType TPTScriptInterface::tptS_create(std::deque * words) +AnyType TPTScriptInterface::tptS_create(std::deque * words) { //Arguments from stack AnyType createType = eval(words); @@ -445,7 +431,7 @@ AnyType TPTScriptInterface::tptS_create(std::deque * words) if(createType.GetType() == TypeNumber) type = ((NumberType)createType).Value(); else if(createType.GetType() == TypeString) - type = m->GetSimulation()->GetParticleType(((StringType)createType).Value()); + type = m->GetSimulation()->GetParticleType(((StringType)createType).Value().ToUtf8()); else throw GeneralException("Invalid type"); @@ -467,7 +453,7 @@ AnyType TPTScriptInterface::tptS_create(std::deque * words) return NumberType(returnValue); } -AnyType TPTScriptInterface::tptS_delete(std::deque * words) +AnyType TPTScriptInterface::tptS_delete(std::deque * words) { //Arguments from stack AnyType partRef = eval(words); @@ -494,7 +480,7 @@ AnyType TPTScriptInterface::tptS_delete(std::deque * words) return NumberType(0); } -AnyType TPTScriptInterface::tptS_load(std::deque * words) +AnyType TPTScriptInterface::tptS_load(std::deque * words) { //Arguments from stack NumberType saveID = eval(words); @@ -508,7 +494,7 @@ AnyType TPTScriptInterface::tptS_load(std::deque * words) throw GeneralException("Invalid save ID"); } -AnyType TPTScriptInterface::tptS_bubble(std::deque * words) +AnyType TPTScriptInterface::tptS_bubble(std::deque * words) { //Arguments from stack PointType bubblePosA = eval(words); @@ -543,11 +529,11 @@ AnyType TPTScriptInterface::tptS_bubble(std::deque * words) return NumberType(0); } -AnyType TPTScriptInterface::tptS_reset(std::deque * words) +AnyType TPTScriptInterface::tptS_reset(std::deque * words) { //Arguments from stack StringType reset = eval(words); - std::string resetStr = reset.Value(); + String resetStr = reset.Value(); Simulation * sim = m->GetSimulation(); @@ -590,7 +576,7 @@ AnyType TPTScriptInterface::tptS_reset(std::deque * words) return NumberType(0); } -AnyType TPTScriptInterface::tptS_quit(std::deque * words) +AnyType TPTScriptInterface::tptS_quit(std::deque * words) { ui::Engine::Ref().Exit(); diff --git a/src/lua/TPTScriptInterface.h b/src/lua/TPTScriptInterface.h index dea284e73..d8f07ff6d 100644 --- a/src/lua/TPTScriptInterface.h +++ b/src/lua/TPTScriptInterface.h @@ -6,21 +6,21 @@ class TPTScriptInterface: public CommandInterface { protected: - AnyType eval(std::deque * words); - int parseNumber(char * stringData); - AnyType tptS_set(std::deque * words); - AnyType tptS_create(std::deque * words); - AnyType tptS_delete(std::deque * words); - AnyType tptS_load(std::deque * words); - AnyType tptS_reset(std::deque * words); - AnyType tptS_bubble(std::deque * words); - AnyType tptS_quit(std::deque * words); - ValueType testType(std::string word); + AnyType eval(std::deque * words); + int parseNumber(String str); + AnyType tptS_set(std::deque * words); + AnyType tptS_create(std::deque * words); + AnyType tptS_delete(std::deque * words); + AnyType tptS_load(std::deque * words); + AnyType tptS_reset(std::deque * words); + AnyType tptS_bubble(std::deque * words); + AnyType tptS_quit(std::deque * words); + ValueType testType(String word); public: TPTScriptInterface(GameController * c, GameModel * m); virtual void Tick() {} - virtual int Command(std::string command); - virtual std::string FormatCommand(std::string command); + virtual int Command(String command); + virtual String FormatCommand(String command); virtual ~TPTScriptInterface(); }; diff --git a/src/powdertoyjava/PowderToyJava.cpp b/src/powdertoyjava/PowderToyJava.cpp index 7f332f5c5..d11f7c380 100644 --- a/src/powdertoyjava/PowderToyJava.cpp +++ b/src/powdertoyjava/PowderToyJava.cpp @@ -2,8 +2,6 @@ #include #include -#include -#include #include "Config.h" #include "PowderToyJava.h" diff --git a/src/simulation/GOLMenu.h b/src/simulation/GOLMenu.h index 905431374..ef37808e1 100644 --- a/src/simulation/GOLMenu.h +++ b/src/simulation/GOLMenu.h @@ -3,10 +3,10 @@ struct gol_menu { - const char *name; + ByteString name; pixel colour; int goltype; - const char *description; + String description; }; #endif diff --git a/src/simulation/MenuSection.h b/src/simulation/MenuSection.h index 7bd292f74..fc31ed2c3 100644 --- a/src/simulation/MenuSection.h +++ b/src/simulation/MenuSection.h @@ -3,8 +3,8 @@ struct menu_section { - const char *icon; - const char *name; + String icon; + String name; int itemcount; int doshow; }; diff --git a/src/simulation/Sign.cpp b/src/simulation/Sign.cpp index 705ea8aee..02d94ada4 100644 --- a/src/simulation/Sign.cpp +++ b/src/simulation/Sign.cpp @@ -1,10 +1,9 @@ #include -#include #include "Sign.h" #include "graphics/Graphics.h" #include "simulation/Simulation.h" -sign::sign(std::string text_, int x_, int y_, Justification justification_): +sign::sign(String text_, int x_, int y_, Justification justification_): x(x_), y(y_), ju(justification_), @@ -12,9 +11,9 @@ sign::sign(std::string text_, int x_, int y_, Justification justification_): { } -std::string sign::getText(Simulation *sim) +String sign::getText(Simulation *sim) { - std::stringstream signTextNew; + String::Stream signTextNew; if (text[0] && text[0] == '{') { if (text == "{p}") @@ -55,7 +54,7 @@ std::string sign::getText(Simulation *sim) return signTextNew.str(); } -void sign::pos(std::string signText, int & x0, int & y0, int & w, int & h) +void sign::pos(String signText, int & x0, int & y0, int & w, int & h) { w = Graphics::textwidth(signText.c_str()) + 5; h = 15; @@ -64,7 +63,7 @@ void sign::pos(std::string signText, int & x0, int & y0, int & w, int & h) y0 = (y > 18) ? y - 18 : y + 4; } -int sign::splitsign(std::string str, char * type) +int sign::splitsign(String str, String::value_type *type) { if (str[0] == '{' && (str[1] == 'c' || str[1] == 't' || str[1] == 'b' || str[1] == 's')) { diff --git a/src/simulation/Sign.h b/src/simulation/Sign.h index 98b053b58..6eb83db46 100644 --- a/src/simulation/Sign.h +++ b/src/simulation/Sign.h @@ -1,7 +1,7 @@ #ifndef SIGN_H_ #define SIGN_H_ -#include +#include "common/String.h" class Simulation; @@ -9,15 +9,15 @@ class sign { public: enum Justification { Left = 0, Middle = 1, Right = 2, None = 3 }; - sign(std::string text_, int x_, int y_, Justification justification_); + sign(String text_, int x_, int y_, Justification justification_); int x, y; Justification ju; - std::string text; + String text; - std::string getText(Simulation *sim); - void pos(std::string signText, int & x0, int & y0, int & w, int & h); + String getText(Simulation *sim); + void pos(String signText, int & x0, int & y0, int & w, int & h); - static int splitsign(std::string str, char * type = NULL); + static int splitsign(String str, String::value_type *type = NULL); }; #endif diff --git a/src/simulation/Simulation.cpp b/src/simulation/Simulation.cpp index 22f43c708..b5e306608 100644 --- a/src/simulation/Simulation.cpp +++ b/src/simulation/Simulation.cpp @@ -4894,7 +4894,7 @@ movedone: framerender--; } -int Simulation::GetParticleType(std::string type) +int Simulation::GetParticleType(ByteString type) { char * txt = (char*)type.c_str(); @@ -4907,7 +4907,7 @@ int Simulation::GetParticleType(std::string type) return PT_NONE; for (int i = 1; i < PT_NUM; i++) { - if (!strcasecmp(txt, elements[i].Name) && strlen(elements[i].Name) && elements[i].Enabled) + if (!strcasecmp(txt, elements[i].Name.c_str()) && elements[i].Name.size() && elements[i].Enabled) { return i; } @@ -5383,7 +5383,6 @@ void Simulation::AfterSim() Simulation::~Simulation() { - delete[] platent; delete grav; delete air; for (size_t i = 0; i < tools.size(); i++) @@ -5447,21 +5446,11 @@ Simulation::Simulation(): pv = air->pv; hv = air->hv; - int menuCount; - menu_section * msectionsT = LoadMenus(menuCount); - memcpy(msections, msectionsT, menuCount * sizeof(menu_section)); - free(msectionsT); + msections = LoadMenus(); - int wallCount; - wall_type * wtypesT = LoadWalls(wallCount); - memcpy(wtypes, wtypesT, wallCount * sizeof(wall_type)); - free(wtypesT); + wtypes = LoadWalls(); - platent = new unsigned[PT_NUM]; - int latentCount; - unsigned int * platentT = LoadLatent(latentCount); - memcpy(platent, platentT, latentCount * sizeof(unsigned int)); - free(platentT); + platent = LoadLatent(); std::vector elementList = GetElements(); for(int i = 0; i < PT_NUM; i++) @@ -5474,20 +5463,9 @@ Simulation::Simulation(): tools = GetTools(); - int golRulesCount; - int * golRulesT = LoadGOLRules(golRulesCount); - memcpy(grule, golRulesT, sizeof(int) * (golRulesCount*10)); - free(golRulesT); + grule = LoadGOLRules(); - int golTypesCount; - int * golTypesT = LoadGOLTypes(golTypesCount); - memcpy(goltype, golTypesT, sizeof(int) * (golTypesCount)); - free(golTypesT); - - int golMenuCount; - gol_menu * golMenuT = LoadGOLMenu(golMenuCount); - memcpy(gmenu, golMenuT, sizeof(gol_menu) * golMenuCount); - free(golMenuT); + gmenu = LoadGOLMenu(); player.comm = 0; player2.comm = 0; diff --git a/src/simulation/Simulation.h b/src/simulation/Simulation.h index 3ae09fabd..eb6f90414 100644 --- a/src/simulation/Simulation.h +++ b/src/simulation/Simulation.h @@ -41,12 +41,12 @@ public: Element elements[PT_NUM]; //Element * elements; std::vector tools; - unsigned int * platent; - wall_type wtypes[UI_WALLCOUNT]; - gol_menu gmenu[NGOL]; - int goltype[NGOL]; - int grule[NGOL+1][10]; - menu_section msections[SC_TOTAL]; + std::vector platent; + std::vector wtypes; + std::vector gmenu; + std::vector goltype; + std::vector > grule; + std::vector msections; int currentTick; int replaceModeSelected; @@ -199,7 +199,7 @@ public: void GetGravityField(int x, int y, float particleGrav, float newtonGrav, float & pGravX, float & pGravY); - int GetParticleType(std::string type); + int GetParticleType(ByteString type); void orbitalparts_get(int block1, int block2, int resblock1[], int resblock2[]); void orbitalparts_set(int *block1, int *block2, int resblock1[], int resblock2[]); diff --git a/src/simulation/SimulationData.cpp b/src/simulation/SimulationData.cpp index 5f04a2ef8..3a4ff4dd8 100644 --- a/src/simulation/SimulationData.cpp +++ b/src/simulation/SimulationData.cpp @@ -3,9 +3,9 @@ #include "ElementGraphics.h" #include "Elements.h" -gol_menu * LoadGOLMenu(int & golMenuCount) +std::vector LoadGOLMenu() { - gol_menu golMenu[NGOL] = + return { {"GOL", PIXPACK(0x0CAC00), 0, "Game Of Life: Begin 3/Stay 23"}, {"HLIF", PIXPACK(0xFF0000), 1, "High Life: B36/S23"}, @@ -32,15 +32,11 @@ gol_menu * LoadGOLMenu(int & golMenuCount) {"FROG", PIXPACK(0x00AA00), 22, "Frogs: B34/S12/3"}, {"BRAN", PIXPACK(0xCCCC00), 23, "Brian 6: B246/S6/3"} }; - golMenuCount = NGOL; - gol_menu * golMenuT = (gol_menu*)malloc(NGOL*sizeof(gol_menu)); - memcpy(golMenuT, golMenu, NGOL*sizeof(gol_menu)); - return golMenuT; } -int * LoadGOLRules(int & golRuleCount) +std::vector > LoadGOLRules() { - int golRules[NGOL+1][10] = + return { // 0,1,2,3,4,5,6,7,8,STATES live=1 spawn=2 spawn&live=3 States are kind of how long until it dies, normal ones use two states(living,dead) for others the intermediate states live but do nothing {0,0,0,0,0,0,0,0,0,2},//blank @@ -69,15 +65,11 @@ int * LoadGOLRules(int & golRuleCount) {0,1,1,2,2,0,0,0,0,3},//FROG {0,0,2,0,2,0,3,0,0,3},//BRAN }; - golRuleCount = NGOL+1; - int * golRulesT = (int*)malloc((golRuleCount*10)*sizeof(int)); - memcpy(golRulesT, golRules, (golRuleCount*10)*sizeof(int)); - return golRulesT; } -int * LoadGOLTypes(int & golTypeCount) +std::vector LoadGOLTypes() { - int golTypes[NGOL] = + return { GT_GOL, GT_HLIF, @@ -104,15 +96,11 @@ int * LoadGOLTypes(int & golTypeCount) GT_FROG, GT_BRAN, }; - golTypeCount = NGOL; - int * golTypesT = (int*)malloc((golTypeCount)*sizeof(int)); - memcpy(golTypesT, golTypes, (golTypeCount)*sizeof(int)); - return golTypesT; } -wall_type * LoadWalls(int & wallCount) +std::vector LoadWalls() { - wall_type wtypes[] = + return { {PIXPACK(0x808080), PIXPACK(0x000000), 0, Renderer::WallIcon, "ERASE", "DEFAULT_WL_ERASE", "Erases walls."}, {PIXPACK(0xC0C0C0), PIXPACK(0x101010), 0, Renderer::WallIcon, "CONDUCTIVE WALL", "DEFAULT_WL_CNDTW", "Blocks everything. Conductive."}, @@ -134,15 +122,11 @@ wall_type * LoadWalls(int & wallCount) {PIXPACK(0x808080), PIXPACK(0x000000), 0, Renderer::WallIcon, "ERASEALL", "DEFAULT_WL_ERASEA", "Erases walls, particles, and signs."}, {PIXPACK(0x800080), PIXPACK(0x000000), 0, Renderer::WallIcon, "STASIS WALL", "DEFAULT_WL_STASIS", "Freezes particles inside the wall in place until powered."}, }; - wallCount = UI_WALLCOUNT; - wall_type * wtypesT = (wall_type*)malloc(UI_WALLCOUNT*sizeof(wall_type)); - memcpy(wtypesT, wtypes, UI_WALLCOUNT*sizeof(wall_type)); - return wtypesT; } -menu_section * LoadMenus(int & menuCount) +std::vector LoadMenus() { - menu_section msections[] = //doshow does not do anything currently. + return { {"\xC1", "Walls", 0, 1}, {"\xC2", "Electronics", 0, 1}, @@ -163,15 +147,11 @@ menu_section * LoadMenus(int & menuCount) {"\xC8", "Cracker", 0, 0}, {"\xC8", "Cracker!", 0, 0}, }; - menuCount = SC_TOTAL; - menu_section * msectionsT = (menu_section*)malloc(SC_TOTAL*sizeof(menu_section)); - memcpy(msectionsT, msections, SC_TOTAL*sizeof(menu_section)); - return msectionsT; } -unsigned int * LoadLatent(int & elementCount) +std::vector LoadLatent() { - unsigned int platent[PT_NUM] = + return { /* NONE */ 0, /* DUST */ 0, @@ -335,8 +315,4 @@ unsigned int * LoadLatent(int & elementCount) /* FRAY */ 0, /* REPL */ 0, }; - elementCount = PT_NUM; - unsigned int * platentT = (unsigned int*)malloc(PT_NUM*sizeof(unsigned int)); - memcpy(platentT, platent, PT_NUM*sizeof(unsigned int)); - return platentT; } diff --git a/src/simulation/SimulationData.h b/src/simulation/SimulationData.h index 471b7d019..c823b5552 100644 --- a/src/simulation/SimulationData.h +++ b/src/simulation/SimulationData.h @@ -1,4 +1,5 @@ #include +#include #define SC_WALL 0 #define SC_ELEC 1 @@ -142,16 +143,16 @@ struct menu_section; class SimTool; class Element; -gol_menu * LoadGOLMenu(int & golMenuCount); +std::vector LoadGOLMenu(); -int * LoadGOLTypes(int & golTypeCount); +std::vector LoadGOLTypes(); -int * LoadGOLRules(int & golRuleCount); +std::vector > LoadGOLRules(); -wall_type * LoadWalls(int & wallCount); +std::vector LoadWalls(); -menu_section * LoadMenus(int & menuCount); +std::vector LoadMenus(); -unsigned int * LoadLatent(int & elementCount); +std::vector LoadLatent(); #endif /* SIMULATIONDATA_H */ diff --git a/src/simulation/StorageClasses.h b/src/simulation/StorageClasses.h index 7f60b3918..5f493075f 100644 --- a/src/simulation/StorageClasses.h +++ b/src/simulation/StorageClasses.h @@ -1,7 +1,6 @@ #ifndef STORAGECLASSES_H_ #define STORAGECLASSES_H_ -#include #include "Elements.h" class Renderer; diff --git a/src/simulation/StructProperty.h b/src/simulation/StructProperty.h index cd3002e59..59908cdb4 100644 --- a/src/simulation/StructProperty.h +++ b/src/simulation/StructProperty.h @@ -1,17 +1,17 @@ #ifndef STRUCTPROPERTY_H_ #define STRUCTPROPERTY_H_ -#include +#include "common/String.h" #include struct StructProperty { enum PropertyType { ParticleType, Colour, Integer, UInteger, Float, String, Char, UChar, Removed }; - std::string Name; + ByteString Name; PropertyType Type; intptr_t Offset; - StructProperty(std::string name, PropertyType type, intptr_t offset): + StructProperty(ByteString name, PropertyType type, intptr_t offset): Name(name), Type(type), Offset(offset) diff --git a/src/simulation/WallType.h b/src/simulation/WallType.h index b8ec53eb2..79478d5e0 100644 --- a/src/simulation/WallType.h +++ b/src/simulation/WallType.h @@ -1,6 +1,7 @@ #ifndef WALLTYPE_H_ #define WALLTYPE_H_ +#include "common/String.h" #include "graphics/Pixel.h" class VideoBuffer; @@ -10,9 +11,9 @@ struct wall_type pixel eglow; // if emap set, add this to fire glow int drawstyle; VideoBuffer * (*textureGen)(int, int, int); - const char *name; - const char *identifier; - const char *descs; + String name; + ByteString identifier; + String descs; }; #endif diff --git a/src/simulation/elements/Element.h b/src/simulation/elements/Element.h index f726d410f..2b399fb7e 100644 --- a/src/simulation/elements/Element.h +++ b/src/simulation/elements/Element.h @@ -13,8 +13,8 @@ struct Particle; class Element { public: - const char *Identifier; - const char *Name; + ByteString Identifier; + ByteString Name; pixel Colour; int MenuVisible; int MenuSection; @@ -38,7 +38,7 @@ public: int Weight; float Temperature; unsigned char HeatConduct; - const char *Description; + String Description; unsigned int Properties; float LowPressure; diff --git a/src/simulation/elements/LIFE.cpp b/src/simulation/elements/LIFE.cpp index 9ac25b287..310bcc517 100644 --- a/src/simulation/elements/LIFE.cpp +++ b/src/simulation/elements/LIFE.cpp @@ -52,13 +52,11 @@ Element_LIFE::Element_LIFE() { Element_GOL_colourInit = true; - int golMenuCount; - gol_menu * golMenuT = LoadGOLMenu(golMenuCount); - for(int i = 0; i < golMenuCount && i < NGOL; i++) + std::vector golMenuT = LoadGOLMenu(); + for(int i = 0; i < NGOL; i++) { Element_GOL_colour[i] = golMenuT[i].colour; } - free(golMenuT); } } diff --git a/src/simulation/simtools/SimTool.h b/src/simulation/simtools/SimTool.h index 4aa969d2c..66ae865b1 100644 --- a/src/simulation/simtools/SimTool.h +++ b/src/simulation/simtools/SimTool.h @@ -10,10 +10,10 @@ struct Particle; class SimTool { public: - const char *Identifier; - const char *Name; + ByteString Identifier; + ByteString Name; pixel Colour; - const char *Description; + String Description; SimTool(); virtual ~SimTool() {} diff --git a/src/tasks/Task.cpp b/src/tasks/Task.cpp index 9da5edee2..761143e9b 100644 --- a/src/tasks/Task.cpp +++ b/src/tasks/Task.cpp @@ -26,12 +26,12 @@ int Task::GetProgress() return progress; } -std::string Task::GetStatus() +String Task::GetStatus() { return status; } -std::string Task::GetError() +String Task::GetError() { return error; } @@ -53,14 +53,14 @@ void Task::Poll() int newProgress; bool newDone = false; bool newSuccess = false; - std::string newStatus; - std::string newError; + String newStatus; + String newError; pthread_mutex_lock(&taskMutex); newProgress = thProgress; newDone = thDone; newSuccess = thSuccess; - newStatus = std::string(thStatus); - newError = std::string(thError); + newStatus = thStatus; + newError = thError; pthread_mutex_unlock(&taskMutex); success = newSuccess; @@ -71,12 +71,12 @@ void Task::Poll() } if(newError!=error) { - error = std::string(newError); + error = newError; notifyErrorMain(); } if(newStatus!=status) { - status = std::string(newStatus); + status = newStatus; notifyStatusMain(); } @@ -140,17 +140,17 @@ void Task::notifyProgress(int progress) pthread_mutex_unlock(&taskMutex); } -void Task::notifyStatus(std::string status) +void Task::notifyStatus(String status) { pthread_mutex_lock(&taskMutex); - thStatus = std::string(status); + thStatus = status; pthread_mutex_unlock(&taskMutex); } -void Task::notifyError(std::string error) +void Task::notifyError(String error) { pthread_mutex_lock(&taskMutex); - thError = std::string(error); + thError = error; pthread_mutex_unlock(&taskMutex); } diff --git a/src/tasks/Task.h b/src/tasks/Task.h index 52ca39493..5913750ad 100644 --- a/src/tasks/Task.h +++ b/src/tasks/Task.h @@ -1,7 +1,7 @@ #ifndef TASK_H_ #define TASK_H_ -#include +#include "common/String.h" #include "common/tpt-thread.h" #include "TaskListener.h" #include "Config.h" @@ -14,8 +14,8 @@ public: int GetProgress(); bool GetDone(); bool GetSuccess(); - std::string GetError(); - std::string GetStatus(); + String GetError(); + String GetStatus(); void Poll(); Task() : listener(NULL) { progress = 0; thProgress = 0; } virtual ~Task(); @@ -23,14 +23,14 @@ protected: int progress; bool done; bool success; - std::string status; - std::string error; + String status; + String error; int thProgress; bool thDone; bool thSuccess; - std::string thStatus; - std::string thError; + String thStatus; + String thError; TaskListener * listener; pthread_t doWorkThread; @@ -44,8 +44,8 @@ protected: TH_ENTRY_POINT static void * doWork_helper(void * ref); virtual void notifyProgress(int progress); - virtual void notifyError(std::string error); - virtual void notifyStatus(std::string status); + virtual void notifyError(String error); + virtual void notifyStatus(String status); virtual void notifyProgressMain(); virtual void notifyErrorMain(); diff --git a/src/tasks/TaskWindow.cpp b/src/tasks/TaskWindow.cpp index a8eacc4db..3e46ecad3 100644 --- a/src/tasks/TaskWindow.cpp +++ b/src/tasks/TaskWindow.cpp @@ -1,4 +1,3 @@ -#include #include "common/tpt-minmax.h" #include "gui/interface/Label.h" #include "gui/interface/Engine.h" @@ -7,7 +6,7 @@ #include "gui/Style.h" #include "Task.h" -TaskWindow::TaskWindow(std::string title_, Task * task_, bool closeOnDone): +TaskWindow::TaskWindow(String title_, Task * task_, bool closeOnDone): ui::Window(ui::Point(-1, -1), ui::Point(240, 60)), task(task_), title(title_), @@ -63,7 +62,7 @@ void TaskWindow::Exit() void TaskWindow::NotifyProgress(Task * task) { progress = task->GetProgress(); - std::stringstream pStream; + String::Stream pStream; if(progress>-1) { pStream << progress << "%"; @@ -120,9 +119,9 @@ void TaskWindow::OnDraw() } } if(progress<50) - g->drawtext(Position.X + ((Size.X-Graphics::textwidth(progressStatus.c_str()))/2), Position.Y + Size.Y-13, progressStatus, 255, 255, 255, 255); + g->drawtext(Position.X + ((Size.X-Graphics::textwidth(progressStatus))/2), Position.Y + Size.Y-13, progressStatus, 255, 255, 255, 255); else - g->drawtext(Position.X + ((Size.X-Graphics::textwidth(progressStatus.c_str()))/2), Position.Y + Size.Y-13, progressStatus, 0, 0, 0, 255); + g->drawtext(Position.X + ((Size.X-Graphics::textwidth(progressStatus))/2), Position.Y + Size.Y-13, progressStatus, 0, 0, 0, 255); } TaskWindow::~TaskWindow() { diff --git a/src/tasks/TaskWindow.h b/src/tasks/TaskWindow.h index 44acd222e..3b3f872c7 100644 --- a/src/tasks/TaskWindow.h +++ b/src/tasks/TaskWindow.h @@ -1,7 +1,6 @@ #ifndef TASKWINDOW_H_ #define TASKWINDOW_H_ -#include #include "gui/interface/Label.h" #include "gui/interface/Window.h" #include "tasks/TaskListener.h" @@ -9,15 +8,15 @@ class Task; class TaskWindow: public ui::Window, public TaskListener { Task * task; - std::string title; + String title; int progress; float intermediatePos; bool done; bool closeOnDone; ui::Label * statusLabel; - std::string progressStatus; + String progressStatus; public: - TaskWindow(std::string title_, Task * task_, bool closeOnDone = true); + TaskWindow(String title_, Task * task_, bool closeOnDone = true); virtual void NotifyStatus(Task * task); virtual void NotifyDone(Task * task); virtual void NotifyProgress(Task * task);