UI: Add functions to create safe file names

Adds functions to generate safe file names from potentially unsafe
names.  Also a function to ensure that a particular filename isn't
duplicated.
This commit is contained in:
jp9000 2015-06-23 18:52:26 -07:00
parent d1e9b9d66a
commit a781c5bdea
2 changed files with 63 additions and 0 deletions

View file

@ -17,6 +17,7 @@
#include <time.h>
#include <stdio.h>
#include <wchar.h>
#include <sstream>
#include <util/bmem.h>
#include <util/dstr.h>
@ -847,6 +848,65 @@ char *GetConfigPathPtr(const char *name)
}
}
bool GetFileSafeName(const char *name, std::string &file)
{
size_t base_len = strlen(name);
size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
std::wstring wfile;
if (!len)
return false;
wfile.resize(len);
os_utf8_to_wcs(name, base_len, &wfile[0], len);
for (size_t i = wfile.size(); i > 0; i--) {
size_t im1 = i - 1;
if (iswspace(wfile[im1])) {
wfile[im1] = '_';
} else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
wfile.erase(im1, 1);
}
}
if (wfile.size() == 0)
wfile = L"characters_only";
len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
if (!len)
return false;
file.resize(len);
os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len);
return true;
}
bool GetClosestUnusedFileName(std::string &path, const char *extension)
{
size_t len = path.size();
if (extension) {
path += ".";
path += extension;
}
if (!os_file_exists(path.c_str()))
return true;
int index = 1;
do {
path.resize(len);
path += std::to_string(++index);
if (extension) {
path += ".";
path += extension;
}
} while (os_file_exists(path.c_str()));
return true;
}
static inline bool arg_is(const char *arg,
const char *long_form, const char *short_form)
{

View file

@ -112,3 +112,6 @@ inline config_t *GetGlobalConfig() {return App()->GlobalConfig();}
std::vector<std::pair<std::string, std::string>> GetLocaleNames();
inline const char *Str(const char *lookup) {return App()->GetString(lookup);}
#define QTStr(lookupVal) QString::fromUtf8(Str(lookupVal))
bool GetFileSafeName(const char *name, std::string &file);
bool GetClosestUnusedFileName(std::string &path, const char *extension);