URL decode file paths

This commit is contained in:
Zachary Hall 2023-07-20 09:53:19 -07:00
parent a8c18d8586
commit 099ed4eb80

View file

@ -1,6 +1,7 @@
#include "file_browser.h"
#include "imfilebrowser.h"
#include <sstream>
#include <iomanip>
#include <cctype>
FileBrowser::FileBrowser(bool save, ImGuiFileBrowserFlags extra_fallback_flags) {
#ifdef PORTALS
@ -82,6 +83,26 @@ void FileBrowser::Open() {
#endif
}
#ifdef PORTALS
path url_decode(string str) {
static const string file_proto = "file://";
if (str.starts_with(file_proto)) {
str = str.substr(file_proto.length());
}
string ret;
int len = str.length();
for (int i = 0; i < len; i++) {
if (str[i] != '%') {
// Don't decode '+' as a space as libportal doesn't encode space as '+', and encodes '+' in a file path verbatim
ret += str[i];
} else {
unsigned int ch_int;
sscanf(str.substr(i + 1, 2).c_str(), "%x", &ch_int);
ret += static_cast<char>(ch_int);
i = i + 2;
}
}
return ret;
}
void FileBrowser::FileBrowserOpenCallback(GObject *src, GAsyncResult *res, gpointer data) {
(void)src;
FileBrowser *self = (FileBrowser*)data;
@ -102,12 +123,9 @@ void FileBrowser::FileBrowserOpenCallback(GObject *src, GAsyncResult *res, gpoin
c_str_vec.push_back('\0');
const char *c_str = c_str_vec.data();
printf("Selected file %s\n", c_str);
string str = c_str;
if (str.starts_with("file://")) {
str = str.substr(string("file://").length());
}
path path = url_decode(c_str);
self->open = false;
self->selected.emplace(path(str));
self->selected.emplace(path);
}
void FileBrowser::FileBrowserSaveCallback(GObject *src, GAsyncResult *res, gpointer data) {
@ -130,12 +148,9 @@ void FileBrowser::FileBrowserSaveCallback(GObject *src, GAsyncResult *res, gpoin
c_str_vec.push_back('\0');
const char *c_str = c_str_vec.data();
printf("Selected file %s\n", c_str);
string str = c_str;
if (str.starts_with("file://")) {
str = str.substr(string("file://").length());
}
path path = url_decode(c_str);
self->open = false;
self->selected.emplace(path(str));
self->selected.emplace(path);
}
#endif