From a781c5bdea1385ec31d667cccf5270a1baeb1d98 Mon Sep 17 00:00:00 2001 From: jp9000 Date: Tue, 23 Jun 2015 18:52:26 -0700 Subject: [PATCH] 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. --- obs/obs-app.cpp | 60 +++++++++++++++++++++++++++++++++++++++++++++++++ obs/obs-app.hpp | 3 +++ 2 files changed, 63 insertions(+) diff --git a/obs/obs-app.cpp b/obs/obs-app.cpp index 4ac0eb3e9..6d9de5d50 100644 --- a/obs/obs-app.cpp +++ b/obs/obs-app.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -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) { diff --git a/obs/obs-app.hpp b/obs/obs-app.hpp index 0979cb60c..78055cff2 100644 --- a/obs/obs-app.hpp +++ b/obs/obs-app.hpp @@ -112,3 +112,6 @@ inline config_t *GetGlobalConfig() {return App()->GlobalConfig();} std::vector> 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);