looper/util.cpp

99 lines
2.6 KiB
C++
Raw Normal View History

#include "util.hpp"
2024-04-25 11:23:38 -07:00
#ifdef __ANDROID__
#include <SDL.h>
#endif
2024-08-08 13:12:37 -07:00
#include <unistd.h>
#include <stdlib.h>
#include <stddef.h>
std::string PadZeros(std::string input, size_t required_length) {
return std::string(required_length - std::min(required_length, input.length()), '0') + input;
}
uint8_t TimeToComponentCount(double time_code) {
int seconds = (int)time_code;
int minutes = seconds / 60;
seconds -= minutes * 60;
int hours = minutes / 60;
minutes -= hours * 60;
if (hours > 0) {
return 3;
} else if (minutes > 0) {
return 2;
} else {
return 1;
}
}
std::string TimeToString(double time_code, uint8_t min_components) {
uint8_t components = std::max(TimeToComponentCount(time_code), min_components);
int seconds = (int)time_code;
int minutes = seconds / 60;
seconds -= minutes * 60;
int hours = minutes / 60;
minutes -= hours * 60;
std::string output = PadZeros(std::to_string(seconds), components < 2 ? 1 : 2);
if (components >= 2) {
output = PadZeros(std::to_string(minutes), components == 2 ? 1 : 2) + ":" + output;
}
if (components >= 3) {
output = PadZeros(std::to_string(hours), components == 3 ? 1 : 2) + ":" + output;
}
return output;
}
#ifdef _WIN32
#include <windows.h>
#include <shlobj.h>
#else
#include <unistd.h>
#endif
std::string get_prefs_path() {
std::string path;
2024-04-25 11:23:38 -07:00
#ifdef __ANDROID__
path = SDL_AndroidGetInternalStoragePath();
#elif defined(_WIN32)
PWSTR str;
if (SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, NULL, &str) != S_OK) {
CoTaskMemFree(str);
path = ".";
} else {
path = std::string(str);
CoTaskMemFree(str);
}
path = path + "\\";
#else
const char *str = getenv("XDG_CONFIG_HOME");
if (str == NULL) {
str = getenv("HOME");
if (str == NULL) {
path = ".";
} else {
path = std::string(str) + "/.config";
}
} else {
path = std::string(str);
}
path = path + "/";
#endif
return path;
2024-08-08 13:12:37 -07:00
}
int launch(std::vector<std::string> args) {
char **argv;
bool err = false;
argv = (char**)calloc(args.size() + 1, sizeof(char*));
for (size_t i = 0; i < args.size(); i++) {
argv[i] = strdup(args[i].c_str());
}
int pid = fork();
if (pid < 0) {
err = true;
} else if (pid == 0) {
execvp(argv[0], argv);
}
for (size_t i = 0; i < args.size(); i++) {
free(argv[i]);
}
free(argv);
if (err) {
throw std::exception();
}
return pid;
}