-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfile-utilities.cpp
309 lines (248 loc) · 9.23 KB
/
file-utilities.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#include "file-utilities.h"
#include <climits>
#include <vector>
#ifdef __EMSCRIPTEN__
#include "libraries/emscripten-browser-file/emscripten_browser_file.h"
#endif
#include "libraries/imgui/imgui.h"
#include "common/core/clowncommon/clowncommon.h"
void FileUtilities::CreateFileDialog([[maybe_unused]] Window &window, const std::string &title, const PopupCallback &callback, const bool save)
{
bool done = false;
if (use_native_file_dialogs)
{
// TODO: According to documentation, the callback may be ran on a different thread, so find some way to ensure that there are no race conditions!
try
{
PopupCallback* const callback_detatched = new PopupCallback(callback);
const auto call_callback = [](void* const user_data, const char* const* const file_list, [[maybe_unused]] const int filter)
{
const std::unique_ptr<PopupCallback> callback(static_cast<PopupCallback*>(user_data));
if (file_list == nullptr || *file_list == nullptr)
return;
(*callback.get())(reinterpret_cast<const char8_t*>(*file_list));
};
const auto properties = SDL_CreateProperties();
SDL_SetPointerProperty(properties, SDL_PROP_FILE_DIALOG_WINDOW_POINTER, window.GetSDLWindow());
SDL_SetStringProperty(properties, SDL_PROP_FILE_DIALOG_TITLE_STRING, title.c_str());
SDL_ShowFileDialogWithProperties(save ? SDL_FILEDIALOG_SAVEFILE : SDL_FILEDIALOG_OPENFILE, call_callback, callback_detatched, properties);
SDL_DestroyProperties(properties);
done = true;
}
catch (const std::bad_alloc&)
{
Frontend::debug_log.Log("FileUtilities::CreateFileDialog: Failed to allocate memory.");
}
}
if (!done)
{
active_file_picker_popup = title;
popup_callback = callback;
is_save_dialog = save;
}
}
void FileUtilities::CreateOpenFileDialog(Window &window, const std::string &title, const PopupCallback &callback)
{
CreateFileDialog(window, title, callback, false);
}
void FileUtilities::CreateSaveFileDialog(Window &window, const std::string &title, const PopupCallback &callback)
{
CreateFileDialog(window, title, callback, true);
}
void FileUtilities::DisplayFileDialog(std::filesystem::path &drag_and_drop_filename)
{
if (active_file_picker_popup.has_value())
{
if (!ImGui::IsPopupOpen(active_file_picker_popup->c_str()))
ImGui::OpenPopup(active_file_picker_popup->c_str());
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
if (ImGui::BeginPopupModal(active_file_picker_popup->c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
const ImGuiInputTextCallback callback = [](ImGuiInputTextCallbackData* const data)
{
FileUtilities* const file_utilities = static_cast<FileUtilities*>(data->UserData);
if (data->EventFlag == ImGuiInputTextFlags_CallbackResize)
{
if (static_cast<std::size_t>(data->BufSize) > file_utilities->text_buffer.size())
{
file_utilities->text_buffer.resize(data->BufSize);
data->Buf = file_utilities->text_buffer.data();
}
}
return 0;
};
/* Make it so that the text box is selected by default,
so that the user doesn't have to click on it first.
If a file is dropped onto the dialog, focus on the
'open' button instead or else the text box won't show
the dropped file's path. */
if (!drag_and_drop_filename.empty())
ImGui::SetKeyboardFocusHere(1);
else if (ImGui::IsWindowAppearing())
ImGui::SetKeyboardFocusHere();
ImGui::TextUnformatted("Filename:");
const bool enter_pressed = ImGui::InputText("##filename", text_buffer.data(), text_buffer.capacity() + 1, ImGuiInputTextFlags_CallbackResize | ImGuiInputTextFlags_CallbackAlways | ImGuiInputTextFlags_EnterReturnsTrue, callback, this);
// Set the text box's contents to the dropped file's path.
if (!drag_and_drop_filename.empty())
{
text_buffer = drag_and_drop_filename.string();
drag_and_drop_filename.clear();
}
const auto centre_buttons = [](const std::vector<const char*> &labels)
{
float width = 0;
width += ImGui::GetStyle().ItemSpacing.x * (labels.size() - 1);
width += ImGui::GetStyle().FramePadding.x * 2 * labels.size();
for (const auto label : labels)
width += ImGui::CalcTextSize(label).x;
ImGui::SetCursorPosX(ImGui::GetStyle().WindowPadding.x + (ImGui::GetContentRegionAvail().x - width) / 2);
};
centre_buttons({is_save_dialog ? "Save" : "Open", "Cancel"});
const bool ok_pressed = ImGui::Button(is_save_dialog ? "Save" : "Open");
ImGui::SameLine();
bool exit = ImGui::Button("Cancel");
bool submit = false;
if (enter_pressed || ok_pressed)
{
if (!is_save_dialog || !FileExists(text_buffer))
submit = true;
else
ImGui::OpenPopup("File Already Exists");
}
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
if (ImGui::BeginPopupModal("File Already Exists", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::TextUnformatted("A file with that name already exists. Overwrite it?");
centre_buttons({"Yes", "No"});
if (ImGui::Button("Yes"))
{
submit = true;
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("No"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
if (submit)
{
if (popup_callback(text_buffer))
exit = true;
else
ImGui::OpenPopup(is_save_dialog ? "Could Not Save File" : "Could Not Open File");
}
if (ImGui::BeginPopupModal("Could Not Open File", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::TextUnformatted("File could not be opened.");
centre_buttons({"OK"});
if (ImGui::Button("OK"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
if (ImGui::BeginPopupModal("Could Not Save File", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::TextUnformatted("File could not be saved.");
centre_buttons({"OK"});
if (ImGui::Button("OK"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
if (exit)
{
ImGui::CloseCurrentPopup();
text_buffer.clear();
text_buffer.shrink_to_fit();
active_file_picker_popup.reset();
}
ImGui::EndPopup();
}
}
}
bool FileUtilities::FileExists(const std::filesystem::path &path)
{
return SDL::GetPathInfo(path, nullptr);
}
std::optional<std::vector<unsigned char>> FileUtilities::LoadFileToBuffer(const std::filesystem::path &path)
{
SDL::IOStream file = SDL::IOFromFile(path, "rb");
if (!file)
{
Frontend::debug_log.Log("SDL_IOFromFile failed with the following message - '{}'", SDL_GetError());
return std::nullopt;
}
return LoadFileToBuffer(file);
}
std::optional<std::vector<unsigned char>> FileUtilities::LoadFileToBuffer(SDL::IOStream &file)
{
const Sint64 size_s64 = SDL_GetIOSize(file);
if (size_s64 < 0)
{
Frontend::debug_log.Log("SDL_GetIOSize failed with the following message - '{}'", SDL_GetError());
}
else
{
const std::size_t size = static_cast<std::size_t>(size_s64);
try
{
std::vector<unsigned char> file_buffer(size);
SDL_ReadIO(file, file_buffer.data(), size);
return file_buffer;
}
catch (const std::bad_alloc&)
{
Frontend::debug_log.Log("Could not allocate memory for file");
}
}
return std::nullopt;
}
void FileUtilities::LoadFile([[maybe_unused]] Window &window, [[maybe_unused]] const std::string &title, const LoadFileCallback &callback)
{
#ifdef __EMSCRIPTEN__
try
{
LoadFileCallback* const callback_detatched = new LoadFileCallback(callback);
const auto call_callback = [](const std::string &filename, const std::string &/*mime_type*/, std::string_view buffer, void* const user_data)
{
const std::unique_ptr<LoadFileCallback> callback(static_cast<LoadFileCallback*>(user_data));
SDL::IOStream file = SDL::IOStream(SDL_IOFromConstMem(buffer.data(), buffer.size()));
if (file)
(*callback.get())(filename, std::move(file));
};
emscripten_browser_file::upload("", call_callback, callback_detatched);
}
catch (const std::bad_alloc&)
{
Frontend::debug_log.Log("FileUtilities::LoadFile: Failed to allocate memory.");
}
#else
CreateOpenFileDialog(window, title, [callback](const std::filesystem::path &path)
{
SDL::IOStream file = SDL::IOFromFile(path, "rb");
if (!file)
return false;
return callback(path, std::move(file));
});
#endif
}
void FileUtilities::SaveFile([[maybe_unused]] Window &window, [[maybe_unused]] const std::string &title, const SaveFileCallback &callback)
{
#ifdef __EMSCRIPTEN__
callback([](const void* const data, const std::size_t data_size)
{
emscripten_browser_file::download("", "application/octet-stream", std::string_view(static_cast<const char*>(data), data_size));
return true;
});
#else
CreateSaveFileDialog(window, title, [callback](const std::filesystem::path &path)
{
const auto save_file = [path](const void* const data, const std::size_t data_size)
{
SDL::IOStream file = SDL::IOFromFile(path, "wb");
if (!file)
return false;
return SDL_WriteIO(file, data, data_size) == data_size;
};
return callback(save_file);
});
#endif
}