From d20212fe33228bd04a414d57113bfbcf1fccf167 Mon Sep 17 00:00:00 2001 From: /nick haya <74699483+The-SGPT@users.noreply.github.com> Date: Thu, 10 Feb 2022 12:20:56 +0800 Subject: [PATCH] Refactor code --- src/Render.cpp | 21 ++++++--------------- src/Render.hpp | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 15 deletions(-) diff --git a/src/Render.cpp b/src/Render.cpp index 64070ba..926d410 100644 --- a/src/Render.cpp +++ b/src/Render.cpp @@ -207,22 +207,13 @@ bool Render::Init(string window_name) { logFile.open("log.txt", std::ofstream::out | std::ofstream::trunc); logFile.close(); - // "touch" the file first - std::ofstream config; - config.open("conf.toml", std::ios::app); - config.close(); - fstream oFile("conf.toml"); - oFile.seekg(0,std::ios::end); - unsigned int size = oFile.tellg(); - if(!size) { - // if file doesnt actually have anything (which it should when the file doesnt exist... yet) - std::ofstream config; - config.open("conf.toml", std::ios::app); - config << "[config]" << endl - << "soundfont = \"data/gm.sf2\"" << endl; - config.close(); + if (!touchFile("conf.toml")) + { + tomlExport("conf.toml", + { + {"config", {{"soundfont", "data/gm.sf2"}}} + }); } - oFile.close(); SOUNDFONT = tomlParse("conf.toml", "config", "soundfont"); if (se.init() > 0) { log("Render.cpp", 202, "SoLoud", " has failed to load. Is your dll broken?", ERROR_); diff --git a/src/Render.hpp b/src/Render.hpp index 0fc5fe5..580fcb7 100644 --- a/src/Render.hpp +++ b/src/Render.hpp @@ -279,6 +279,8 @@ namespace Render { return FRAMERATE*time; } + // Parse a TOML at a given path with a table and key. + // Setting table name to "" will look for the key without a table. template T tomlParse(string path, string table_name = "", string key = "") { auto parsed = toml::parse(path); @@ -288,5 +290,30 @@ namespace Render { } return toml::find(parsed, key); } + + // "touch" a file at a given path. + // Returns false if file is empty, returns true if not + inline bool touchFile(string path) { + std::ofstream file; + file.open(path, std::ios::app); + file.close(); + fstream oFile(path); + oFile.seekg(0,std::ios::end); + unsigned int size = oFile.tellg(); + if (!size) { + oFile.close(); + return false; + } + return true; + } + + // Export a TOML file to a path from a toml::value. + inline void tomlExport(string path, toml::value values) { + string export_ = toml::format(values, 0, 2); + std::ofstream config; + config.open(path, std::ofstream::out | std::ofstream::trunc); + config << export_ << endl; + config.close(); + } } #endif \ No newline at end of file