Skip to content

Commit

Permalink
Codechange: Convert some more FIO functions to take std::string.
Browse files Browse the repository at this point in the history
  • Loading branch information
michicc committed Dec 27, 2020
1 parent f3326d3 commit 65f65ad
Show file tree
Hide file tree
Showing 14 changed files with 62 additions and 68 deletions.
44 changes: 20 additions & 24 deletions src/fileio.cpp
Expand Up @@ -270,9 +270,9 @@ bool IsValidSearchPath(Searchpath sp)
* @param subdir the subdirectory to look in
* @return true if and only if the file can be opened
*/
bool FioCheckFileExists(const char *filename, Subdirectory subdir)
bool FioCheckFileExists(const std::string &filename, Subdirectory subdir)
{
FILE *f = FioFOpenFile(filename, "rb", subdir);
FILE *f = FioFOpenFile(filename.c_str(), "rb", subdir);
if (f == nullptr) return false;

FioFCloseFile(f);
Expand All @@ -284,9 +284,9 @@ bool FioCheckFileExists(const char *filename, Subdirectory subdir)
* @param filename the file to test.
* @return true if and only if the file exists.
*/
bool FileExists(const char *filename)
bool FileExists(const std::string &filename)
{
return access(OTTD2FS(filename), 0) == 0;
return access(OTTD2FS(filename.c_str()), 0) == 0;
}

/**
Expand All @@ -311,12 +311,12 @@ std::string FioFindFullPath(Subdirectory subdir, const char *filename)
FOR_ALL_SEARCHPATHS(sp) {
std::string buf = FioGetDirectory(sp, subdir);
buf += filename;
if (FileExists(buf.c_str())) return buf;
if (FileExists(buf)) return buf;
#if !defined(_WIN32)
/* Be, as opening files, aware that sometimes the filename
* might be in uppercase when it is in lowercase on the
* disk. Of course Windows doesn't care about casing. */
if (strtolower(buf, _searchpaths[sp].size() - 1) && FileExists(buf.c_str())) return buf;
if (strtolower(buf, _searchpaths[sp].size() - 1) && FileExists(buf)) return buf;
#endif
}

Expand All @@ -338,7 +338,7 @@ std::string FioFindDirectory(Subdirectory subdir)
/* Find and return the first valid directory */
FOR_ALL_SEARCHPATHS(sp) {
std::string ret = FioGetDirectory(sp, subdir);
if (FileExists(ret.c_str())) return ret;
if (FileExists(ret)) return ret;
}

/* Could not find the directory, fall back to a base path */
Expand Down Expand Up @@ -502,14 +502,12 @@ FILE *FioFOpenFile(const char *filename, const char *mode, Subdirectory subdir,
* If the parent directory does not exist, it will try to create that as well.
* @param name the new name of the directory
*/
void FioCreateDirectory(const char *name)
void FioCreateDirectory(const std::string &name)
{
char dirname[MAX_PATH];
strecpy(dirname, name, lastof(dirname));
char *p = strrchr(dirname, PATHSEPCHAR);
if (p != nullptr) {
*p = '\0';
DIR *dir = ttd_opendir(dirname);
auto p = name.find_last_of(PATHSEPCHAR);
if (p != std::string::npos) {
std::string dirname = name.substr(0, p);
DIR *dir = ttd_opendir(dirname.c_str());
if (dir == nullptr) {
FioCreateDirectory(dirname); // Try creating the parent directory, if we couldn't open it
} else {
Expand All @@ -520,11 +518,11 @@ void FioCreateDirectory(const char *name)
/* Ignore directory creation errors; they'll surface later on, and most
* of the time they are 'directory already exists' errors anyhow. */
#if defined(_WIN32)
CreateDirectory(OTTD2FS(name), nullptr);
CreateDirectory(OTTD2FS(name.c_str()), nullptr);
#elif defined(OS2) && !defined(__INNOTEK_LIBC__)
mkdir(OTTD2FS(name));
mkdir(OTTD2FS(name.c_str()));
#else
mkdir(OTTD2FS(name), 0755);
mkdir(OTTD2FS(name.c_str()), 0755);
#endif
}

Expand Down Expand Up @@ -1198,9 +1196,9 @@ void DeterminePaths(const char *exe)
}

/* Make the necessary folders */
FioCreateDirectory(config_dir.c_str());
FioCreateDirectory(config_dir);
#if defined(WITH_PERSONAL_DIR)
FioCreateDirectory(_personal_dir.c_str());
FioCreateDirectory(_personal_dir);
#endif

DEBUG(misc, 3, "%s found as personal directory", _personal_dir.c_str());
Expand All @@ -1210,19 +1208,17 @@ void DeterminePaths(const char *exe)
};

for (uint i = 0; i < lengthof(default_subdirs); i++) {
FioCreateDirectory((_personal_dir + _subdirs[default_subdirs[i]]).c_str());
FioCreateDirectory(_personal_dir + _subdirs[default_subdirs[i]]);
}

/* If we have network we make a directory for the autodownloading of content */
_searchpaths[SP_AUTODOWNLOAD_DIR] = _personal_dir + "content_download" PATHSEP;
FioCreateDirectory(_searchpaths[SP_AUTODOWNLOAD_DIR].c_str());
FioCreateDirectory(_searchpaths[SP_AUTODOWNLOAD_DIR]);

/* Create the directory for each of the types of content */
const Subdirectory dirs[] = { SCENARIO_DIR, HEIGHTMAP_DIR, BASESET_DIR, NEWGRF_DIR, AI_DIR, AI_LIBRARY_DIR, GAME_DIR, GAME_LIBRARY_DIR };
for (uint i = 0; i < lengthof(dirs); i++) {
char *tmp = str_fmt("%s%s", _searchpaths[SP_AUTODOWNLOAD_DIR].c_str(), _subdirs[dirs[i]]);
FioCreateDirectory(tmp);
free(tmp);
FioCreateDirectory(FioGetDirectory(SP_AUTODOWNLOAD_DIR, dirs[i]));
}

extern std::string _log_file;
Expand Down
6 changes: 3 additions & 3 deletions src/fileio_func.h
Expand Up @@ -38,19 +38,19 @@ bool IsValidSearchPath(Searchpath sp);

void FioFCloseFile(FILE *f);
FILE *FioFOpenFile(const char *filename, const char *mode, Subdirectory subdir, size_t *filesize = nullptr);
bool FioCheckFileExists(const char *filename, Subdirectory subdir);
bool FioCheckFileExists(const std::string &filename, Subdirectory subdir);
std::string FioFindFullPath(Subdirectory subdir, const char *filename);
std::string FioGetDirectory(Searchpath sp, Subdirectory subdir);
std::string FioFindDirectory(Subdirectory subdir);
void FioCreateDirectory(const char *name);
void FioCreateDirectory(const std::string &name);

const char *FiosGetScreenshotDir();

void SanitizeFilename(char *filename);
void AppendPathSeparator(std::string &buf);
void DeterminePaths(const char *exe);
void *ReadFileToMem(const char *filename, size_t *lenp, size_t maxsize);
bool FileExists(const char *filename);
bool FileExists(const std::string &filename);
bool ExtractTar(const char *tar_filename, Subdirectory subdir);

extern std::string _personal_dir; ///< custom directory for personal settings, saves, newgrf, etc.
Expand Down
37 changes: 17 additions & 20 deletions src/fios.cpp
Expand Up @@ -200,54 +200,53 @@ const char *FiosBrowseTo(const FiosItem *item)

/**
* Construct a filename from its components in destination buffer \a buf.
* @param buf Destination buffer.
* @param path Directory path, may be \c nullptr.
* @param name Filename.
* @param ext Filename extension (use \c "" for no extension).
* @param last Last element of buffer \a buf.
* @return The completed filename.
*/
static void FiosMakeFilename(char *buf, const char *path, const char *name, const char *ext, const char *last)
static std::string FiosMakeFilename(const std::string *path, const char *name, const char *ext)
{
std::string buf;

if (path != nullptr) {
const char *buf_start = buf;
buf = strecpy(buf, path, last);
buf = *path;
/* Remove trailing path separator, if present */
if (buf > buf_start && buf[-1] == PATHSEPCHAR) buf--;
if (!buf.empty() && buf.back() == PATHSEPCHAR) buf.pop_back();
}

/* Don't append the extension if it is already there */
const char *period = strrchr(name, '.');
if (period != nullptr && strcasecmp(period, ext) == 0) ext = "";

seprintf(buf, last, PATHSEP "%s%s", name, ext);
return buf + name + ext;
}

/**
* Make a save game or scenario filename from a name.
* @param buf Destination buffer for saving the filename.
* @param name Name of the file.
* @param last Last element of buffer \a buf.
* @return The completed filename.
*/
void FiosMakeSavegameName(char *buf, const char *name, const char *last)
std::string FiosMakeSavegameName(const char *name)
{
const char *extension = (_game_mode == GM_EDITOR) ? ".scn" : ".sav";

FiosMakeFilename(buf, _fios_path->c_str(), name, extension, last);
return FiosMakeFilename(_fios_path, name, extension);
}

/**
* Construct a filename for a height map.
* @param buf Destination buffer.
* @param name Filename.
* @param last Last element of buffer \a buf.
* @return The completed filename.
*/
void FiosMakeHeightmapName(char *buf, const char *name, const char *last)
std::string FiosMakeHeightmapName(const char *name)
{
char ext[5];
ext[0] = '.';
strecpy(ext + 1, GetCurrentScreenshotExtension(), lastof(ext));
std::string ext(".");
ext += GetCurrentScreenshotExtension();

FiosMakeFilename(buf, _fios_path->c_str(), name, ext, last);
return FiosMakeFilename(_fios_path, name, ext.c_str());
}

/**
Expand All @@ -257,10 +256,8 @@ void FiosMakeHeightmapName(char *buf, const char *name, const char *last)
*/
bool FiosDelete(const char *name)
{
char filename[512];

FiosMakeSavegameName(filename, name, lastof(filename));
return unlink(filename) == 0;
std::string filename = FiosMakeSavegameName(name);
return unlink(filename.c_str()) == 0;
}

typedef FiosType fios_getlist_callback_proc(SaveLoadOperation fop, const char *filename, const char *ext, char *title, const char *last);
Expand Down
4 changes: 2 additions & 2 deletions src/fios.h
Expand Up @@ -220,8 +220,8 @@ const char *FiosBrowseTo(const FiosItem *item);

StringID FiosGetDescText(const char **path, uint64 *total_free);
bool FiosDelete(const char *name);
void FiosMakeHeightmapName(char *buf, const char *name, const char *last);
void FiosMakeSavegameName(char *buf, const char *name, const char *last);
std::string FiosMakeHeightmapName(const char *name);
std::string FiosMakeSavegameName(const char *name);

FiosType FiosGetSavegameListCallback(SaveLoadOperation fop, const char *file, const char *ext, char *title, const char *last);

Expand Down
4 changes: 2 additions & 2 deletions src/fios_gui.cpp
Expand Up @@ -771,14 +771,14 @@ struct SaveLoadWindow : public Window {
}
} else if (this->IsWidgetLowered(WID_SL_SAVE_GAME)) { // Save button clicked
if (this->abstract_filetype == FT_SAVEGAME || this->abstract_filetype == FT_SCENARIO) {
FiosMakeSavegameName(_file_to_saveload.name, this->filename_editbox.text.buf, lastof(_file_to_saveload.name));
_file_to_saveload.name = FiosMakeSavegameName(this->filename_editbox.text.buf);
if (FioCheckFileExists(_file_to_saveload.name, Subdirectory::SAVE_DIR)) {
ShowQuery(STR_SAVELOAD_OVERWRITE_TITLE, STR_SAVELOAD_OVERWRITE_WARNING, this, SaveLoadWindow::SaveGameConfirmationCallback);
} else {
_switch_mode = SM_SAVE_GAME;
}
} else {
FiosMakeHeightmapName(_file_to_saveload.name, this->filename_editbox.text.buf, lastof(_file_to_saveload.name));
_file_to_saveload.name = FiosMakeHeightmapName(this->filename_editbox.text.buf);
if (FioCheckFileExists(_file_to_saveload.name, Subdirectory::SAVE_DIR)) {
ShowQuery(STR_SAVELOAD_OVERWRITE_TITLE, STR_SAVELOAD_OVERWRITE_WARNING, this, SaveLoadWindow::SaveHeightmapConfirmationCallback);
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/genworld_gui.cpp
Expand Up @@ -831,7 +831,7 @@ static void _ShowGenerateLandscape(GenerateLandscapeWindowMode mode)

if (mode == GLWM_HEIGHTMAP) {
/* If the function returns negative, it means there was a problem loading the heightmap */
if (!GetHeightmapDimensions(_file_to_saveload.detail_ftype, _file_to_saveload.name, &x, &y)) return;
if (!GetHeightmapDimensions(_file_to_saveload.detail_ftype, _file_to_saveload.name.c_str(), &x, &y)) return;
}

WindowDesc *desc = (mode == GLWM_HEIGHTMAP) ? &_heightmap_load_desc : &_generate_landscape_desc;
Expand Down
2 changes: 1 addition & 1 deletion src/landscape.cpp
Expand Up @@ -1305,7 +1305,7 @@ void GenerateLandscape(byte mode)

if (mode == GWM_HEIGHTMAP) {
SetGeneratingWorldProgress(GWP_LANDSCAPE, steps + GLS_HEIGHTMAP);
LoadHeightmap(_file_to_saveload.detail_ftype, _file_to_saveload.name);
LoadHeightmap(_file_to_saveload.detail_ftype, _file_to_saveload.name.c_str());
IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
} else if (_settings_game.game_creation.land_generator == LG_TERRAGENESIS) {
SetGeneratingWorldProgress(GWP_LANDSCAPE, steps + GLS_TERRAGENESIS);
Expand Down
4 changes: 2 additions & 2 deletions src/music/midifile.cpp
Expand Up @@ -1078,11 +1078,11 @@ std::string MidiFile::GetSMFFile(const MusicSongInfo &song)
std::string tempdirname = FioGetDirectory(Searchpath::SP_AUTODOWNLOAD_DIR, Subdirectory::BASESET_DIR);
tempdirname += basename;
AppendPathSeparator(tempdirname);
FioCreateDirectory(tempdirname.c_str());
FioCreateDirectory(tempdirname);

std::string output_filename = tempdirname + std::to_string(song.cat_index) + ".mid";

if (FileExists(output_filename.c_str())) {
if (FileExists(output_filename)) {
/* If the file already exists, assume it's the correct decoded data */
return output_filename;
}
Expand Down
4 changes: 2 additions & 2 deletions src/network/network_client.cpp
Expand Up @@ -541,7 +541,7 @@ bool ClientNetworkGameSocketHandler::IsConnected()
* DEF_CLIENT_RECEIVE_COMMAND has parameter: Packet *p
************/

extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr);
extern bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr);

NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FULL(Packet *p)
{
Expand Down Expand Up @@ -867,7 +867,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet

/* The map is done downloading, load it */
ClearErrorMessages();
bool load_success = SafeLoad(nullptr, SLO_LOAD, DFT_GAME_FILE, GM_NORMAL, NO_DIRECTORY, lf);
bool load_success = SafeLoad({}, SLO_LOAD, DFT_GAME_FILE, GM_NORMAL, NO_DIRECTORY, lf);

/* Long savegame loads shouldn't affect the lag calculation! */
this->last_packet = _realtime_tick;
Expand Down
14 changes: 7 additions & 7 deletions src/openttd.cpp
Expand Up @@ -626,9 +626,9 @@ int openttd_main(int argc, char *argv[])
_file_to_saveload.SetMode(SLO_LOAD, is_scenario ? FT_SCENARIO : FT_SAVEGAME, DFT_GAME_FILE);

/* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
const char *t = strrchr(_file_to_saveload.name, '.');
if (t != nullptr) {
FiosType ft = FiosGetSavegameListCallback(SLO_LOAD, _file_to_saveload.name, t, nullptr, nullptr);
auto t = _file_to_saveload.name.find_last_of('.');
if (t != std::string::npos) {
FiosType ft = FiosGetSavegameListCallback(SLO_LOAD, _file_to_saveload.name.c_str(), _file_to_saveload.name.substr(t).c_str(), nullptr, nullptr);
if (ft != FIOS_TYPE_INVALID) _file_to_saveload.SetMode(ft);
}

Expand Down Expand Up @@ -960,15 +960,15 @@ static void MakeNewEditorWorld()
* @param subdir default directory to look for filename, set to 0 if not needed
* @param lf Load filter to use, if nullptr: use filename + subdir.
*/
bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr)
bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr)
{
assert(fop == SLO_LOAD);
assert(dft == DFT_GAME_FILE || (lf == nullptr && dft == DFT_OLD_GAME_FILE));
GameMode ogm = _game_mode;

_game_mode = newgm;

switch (lf == nullptr ? SaveOrLoad(filename, fop, dft, subdir) : LoadWithFilter(lf)) {
switch (lf == nullptr ? SaveOrLoad(filename.c_str(), fop, dft, subdir) : LoadWithFilter(lf)) {
case SL_OK: return true;

case SL_REINIT:
Expand Down Expand Up @@ -1127,7 +1127,7 @@ void SwitchToMode(SwitchMode new_mode)

case SM_SAVE_GAME: // Save game.
/* Make network saved games on pause compatible to singleplayer */
if (SaveOrLoad(_file_to_saveload.name, SLO_SAVE, DFT_GAME_FILE, NO_DIRECTORY) != SL_OK) {
if (SaveOrLoad(_file_to_saveload.name.c_str(), SLO_SAVE, DFT_GAME_FILE, NO_DIRECTORY) != SL_OK) {
SetDParamStr(0, GetSaveLoadErrorString());
ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
} else {
Expand All @@ -1136,7 +1136,7 @@ void SwitchToMode(SwitchMode new_mode)
break;

case SM_SAVE_HEIGHTMAP: // Save heightmap.
MakeHeightmapScreenshot(_file_to_saveload.name);
MakeHeightmapScreenshot(_file_to_saveload.name.c_str());
DeleteWindowById(WC_SAVELOAD, 0);
break;

Expand Down
2 changes: 1 addition & 1 deletion src/saveload/saveload.cpp
Expand Up @@ -2930,7 +2930,7 @@ void FileToSaveLoad::SetMode(SaveLoadOperation fop, AbstractFileType aft, Detail
*/
void FileToSaveLoad::SetName(const char *name)
{
strecpy(this->name, name, lastof(this->name));
this->name = name;
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/saveload/saveload.h
Expand Up @@ -12,6 +12,7 @@

#include "../fileio_type.h"
#include "../strings_type.h"
#include <string>

/** SaveLoad versions
* Previous savegame versions, the trunk revision where they were
Expand Down Expand Up @@ -337,7 +338,7 @@ struct FileToSaveLoad {
SaveLoadOperation file_op; ///< File operation to perform.
DetailedFileType detail_ftype; ///< Concrete file type (PNG, BMP, old save, etc).
AbstractFileType abstract_ftype; ///< Abstract type of file (scenario, heightmap, etc).
char name[MAX_PATH]; ///< Name of the file.
std::string name; ///< Name of the file.
char title[255]; ///< Internal name of the game.

void SetMode(FiosType ft);
Expand Down
2 changes: 1 addition & 1 deletion src/script/script_instance.cpp
Expand Up @@ -120,7 +120,7 @@ bool ScriptInstance::LoadCompatibilityScripts(const char *api_version, Subdirect
FOR_ALL_SEARCHPATHS(sp) {
std::string buf = FioGetDirectory(sp, dir);
buf += script_name;
if (!FileExists(buf.c_str())) continue;
if (!FileExists(buf)) continue;

if (this->engine->LoadScript(buf.c_str())) return true;

Expand Down
2 changes: 1 addition & 1 deletion src/video/dedicated_v.cpp
Expand Up @@ -128,7 +128,7 @@ static void *_dedicated_video_mem;
/* Whether a fork has been done. */
bool _dedicated_forks;

extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr);
extern bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr);

static FVideoDriver_Dedicated iFVideoDriver_Dedicated;

Expand Down

0 comments on commit 65f65ad

Please sign in to comment.