forked from AirGuanZ/imgui-filebrowser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimfilebrowser.h
546 lines (453 loc) · 14.9 KB
/
imfilebrowser.h
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
#pragma once
#include <array>
#include <filesystem>
#include <functional>
#include <memory>
#include <string>
#ifndef IMGUI_VERSION
# error "include imgui.h before this header"
#endif
#ifdef _WIN32
#define MAX_DRIVES_LENGTH 256
#include <Windows.h>
#endif
using ImGuiFileBrowserFlags = int;
enum ImGuiFileBrowserFlags_
{
ImGuiFileBrowserFlags_SelectDirectory = 1 << 0, // select directory instead of regular file
ImGuiFileBrowserFlags_EnterNewFilename = 1 << 1, // allow user to enter new filename when selecting regular file
ImGuiFileBrowserFlags_NoModal = 1 << 2, // file browsing window is modal by default. specify this to use a popup window
ImGuiFileBrowserFlags_NoTitleBar = 1 << 3, // hide window title bar
ImGuiFileBrowserFlags_NoStatusBar = 1 << 4, // hide status bar at the bottom of browsing window
ImGuiFileBrowserFlags_CloseOnEsc = 1 << 5, // close file browser when pressing 'ESC'
ImGuiFileBrowserFlags_CreateNewDir = 1 << 6, // allow user to create new directory
ImGuiFileBrowserFlags_SingleClickDir = 1 << 7, // open directory when single click (useful if user is only allowed to select files)
ImGuiFileBrowserFlags_SortIgnoreCase = 1 << 8, // ignore case when sorting files
};
namespace ImGui
{
class FileBrowser
{
public:
// pwd is set to current working directory by default
explicit FileBrowser(ImGuiFileBrowserFlags flags = 0);
FileBrowser(const FileBrowser ©From);
FileBrowser &operator=(const FileBrowser ©From);
// set the window title text
void SetTitle(std::string title);
// sets accepted file type
void SetAcceptableFileTypes(std::string extension);
bool IsAcceptableFileType(std::string filename);
// open the browsing window
void Open();
// close the browsing window
void Close();
// the browsing window is opened or not
bool IsOpened() const noexcept;
// display the browsing window if opened
void Display();
// returns true when there is a selected filename and the "ok" button was clicked
bool HasSelected() const noexcept;
// set current browsing directory
bool SetPwd(const std::filesystem::path &pwd = std::filesystem::current_path());
// returns selected filename. make sense only when HasSelected returns true
std::filesystem::path GetSelected() const;
// set selected filename to empty
void ClearSelected();
#ifdef _WIN32
// get all available Windows drives. Maybe add flags here (network, removable etc..)
std::vector<std::string>* GetDrives();
#endif
private:
class ScopeGuard
{
std::function<void()> func_;
public:
template<typename T>
explicit ScopeGuard(T func) : func_(std::move(func)) { }
~ScopeGuard() { func_(); }
};
void SetPwdUncatched(const std::filesystem::path &pwd);
ImGuiFileBrowserFlags flags_;
std::string title_;
std::string openLabel_;
std::vector<std::string> acceptedFileTypes_;
bool openFlag_;
bool closeFlag_;
bool isOpened_;
bool ok_;
std::string statusStr_;
std::filesystem::path pwd_;
std::string selectedFilename_;
struct FileRecord
{
bool isDir;
std::string name;
std::string showName;
};
std::vector<FileRecord> fileRecords_;
// IMPROVE: overflow when selectedFilename_.length() > inputNameBuf_.size() - 1
static constexpr size_t INPUT_NAME_BUF_SIZE = 512;
std::unique_ptr<std::array<char, INPUT_NAME_BUF_SIZE>> inputNameBuf_;
std::string openNewDirLabel_;
std::unique_ptr<std::array<char, INPUT_NAME_BUF_SIZE>> newDirNameBuf_;
};
} // namespace ImGui
inline ImGui::FileBrowser::FileBrowser(ImGuiFileBrowserFlags flags)
: flags_(flags),
openFlag_(false), closeFlag_(false), isOpened_(false), ok_(false),
inputNameBuf_(std::make_unique<std::array<char, INPUT_NAME_BUF_SIZE>>())
{
if(flags_ & ImGuiFileBrowserFlags_CreateNewDir)
newDirNameBuf_ = std::make_unique<std::array<char, INPUT_NAME_BUF_SIZE>>();
inputNameBuf_->at(0) = '\0';
SetTitle("file browser");
SetPwd(std::filesystem::current_path());
}
inline ImGui::FileBrowser::FileBrowser(const FileBrowser ©From)
: FileBrowser()
{
*this = copyFrom;
}
inline ImGui::FileBrowser &ImGui::FileBrowser::operator=(const FileBrowser ©From)
{
flags_ = copyFrom.flags_;
SetTitle(copyFrom.title_);
openFlag_ = copyFrom.openFlag_;
closeFlag_ = copyFrom.closeFlag_;
isOpened_ = copyFrom.isOpened_;
ok_ = copyFrom.ok_;
statusStr_ = "";
pwd_ = copyFrom.pwd_;
selectedFilename_ = copyFrom.selectedFilename_;
fileRecords_ = copyFrom.fileRecords_;
*inputNameBuf_ = *copyFrom.inputNameBuf_;
if(flags_ & ImGuiFileBrowserFlags_CreateNewDir)
{
newDirNameBuf_ = std::make_unique<std::array<char, INPUT_NAME_BUF_SIZE>>();
*newDirNameBuf_ = *copyFrom.newDirNameBuf_;
}
return *this;
}
inline void ImGui::FileBrowser::SetTitle(std::string title)
{
title_ = std::move(title);
openLabel_ = title_ + "##filebrowser_" + std::to_string(reinterpret_cast<size_t>(this));
openNewDirLabel_ = "new dir##new_dir_" + std::to_string(reinterpret_cast<size_t>(this));
}
inline void ImGui::FileBrowser::Open()
{
ClearSelected();
statusStr_ = std::string();
openFlag_ = true;
closeFlag_ = false;
}
inline void ImGui::FileBrowser::Close()
{
ClearSelected();
statusStr_ = std::string();
closeFlag_ = true;
openFlag_ = false;
}
inline void ImGui::FileBrowser::SetAcceptableFileTypes(std::string extension)
{
acceptedFileTypes_.clear();
size_t pos = 0;
std::string acceptedExtension;
while ((pos = extension.find('|')) != std::string::npos) {
acceptedExtension = extension.substr(0, pos);
acceptedFileTypes_.push_back(acceptedExtension);
extension.erase(0, 1);
}
if (!extension.empty())
{
acceptedFileTypes_.push_back(extension);
}
}
inline bool ImGui::FileBrowser::IsAcceptableFileType(std::string filename)
{
if(filename.find('.') != std::string::npos) //argument is full file name/path name, take extension
filename = filename.substr(filename.rfind(".") + 1);
return acceptedFileTypes_.empty() || std::find(acceptedFileTypes_.begin(), acceptedFileTypes_.end(), filename) != acceptedFileTypes_.end();
}
inline bool ImGui::FileBrowser::IsOpened() const noexcept
{
return isOpened_;
}
inline void ImGui::FileBrowser::Display()
{
PushID(this);
ScopeGuard exitThis([this] { openFlag_ = false; closeFlag_ = false; PopID(); });
if(openFlag_)
OpenPopup(openLabel_.c_str());
isOpened_ = false;
// open the popup window
if(openFlag_ && (flags_ & ImGuiFileBrowserFlags_NoModal))
SetNextWindowSize(ImVec2(700, 450));
else
SetNextWindowSize(ImVec2(700, 450), ImGuiCond_FirstUseEver);
if(flags_ & ImGuiFileBrowserFlags_NoModal)
{
if(!BeginPopup(openLabel_.c_str()))
return;
}
else if(!BeginPopupModal(openLabel_.c_str(), nullptr,
flags_ & ImGuiFileBrowserFlags_NoTitleBar ? ImGuiWindowFlags_NoTitleBar : 0))
{
return;
}
isOpened_ = true;
ScopeGuard endPopup([] { EndPopup(); });
// display elements in pwd
std::filesystem::path newPwd; bool setNewPwd = false;
int secIdx = 0, newPwdLastSecIdx = -1;
for(auto &sec : pwd_)
{
#ifdef _WIN32
if(secIdx == 1)
{
++secIdx;
continue;
}
#endif
PushID(secIdx);
if(secIdx > 0)
SameLine();
#ifdef _WIN32
if (secIdx == 0)
{
ImGui::PushItemWidth(35);
if (ImGui::BeginCombo("##drivecombo", sec.u8string().c_str()))
{
const std::vector<std::string>* drives = GetDrives();
for (int i = 0; i < drives->size(); i++)
{
bool is_selected = sec.compare(drives->at(i)) == 0;
if (ImGui::Selectable(drives->at(i).c_str(), is_selected))
{
setNewPwd = true;
newPwd = drives->at(i);
}
if (is_selected)
{
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
ImGui::PopItemWidth();
}
else
{
#endif
if(SmallButton(sec.u8string().c_str()))
newPwdLastSecIdx = secIdx;
#ifdef _WIN32
}
#endif
PopID();
++secIdx;
}
if(newPwdLastSecIdx >= 0)
{
int i = 0;
std::filesystem::path newPwd;
for(auto &sec : pwd_)
{
if(i++ > newPwdLastSecIdx)
break;
newPwd /= sec;
}
#ifdef _WIN32
if(newPwdLastSecIdx == 0)
newPwd /= "\\";
#endif
SetPwd(newPwd);
}
SameLine();
if(SmallButton("*"))
SetPwd(pwd_);
if(newDirNameBuf_)
{
SameLine();
if(SmallButton("+"))
{
OpenPopup(openNewDirLabel_.c_str());
(*newDirNameBuf_)[0] = '\0';
}
if(BeginPopup(openNewDirLabel_.c_str()))
{
ScopeGuard endNewDirPopup([] { EndPopup(); });
InputText("name", newDirNameBuf_->data(), newDirNameBuf_->size()); SameLine();
if(Button("ok") && (*newDirNameBuf_)[0] != '\0')
{
ScopeGuard closeNewDirPopup([] { CloseCurrentPopup(); });
if(create_directory(pwd_ / newDirNameBuf_->data()))
SetPwd(pwd_);
else
statusStr_ = "failed to create " + std::string(newDirNameBuf_->data());
}
}
}
// browse files in a child window
float reserveHeight = GetItemsLineHeightWithSpacing();
if(!(flags_ & ImGuiFileBrowserFlags_SelectDirectory) && (flags_ & ImGuiFileBrowserFlags_EnterNewFilename))
reserveHeight += GetItemsLineHeightWithSpacing();
{
BeginChild("ch", ImVec2(0, -reserveHeight), true,
(flags_ & ImGuiFileBrowserFlags_NoModal) ? ImGuiWindowFlags_AlwaysHorizontalScrollbar : 0);
ScopeGuard endChild([] { EndChild(); });
for(auto &rsc : fileRecords_)
{
const bool selected = selectedFilename_ == rsc.name;
if(Selectable(rsc.showName.c_str(), selected, ImGuiSelectableFlags_DontClosePopups))
{
if(selected)
{
selectedFilename_ = std::string();
(*inputNameBuf_)[0] = '\0';
}
else if(rsc.name != "..")
{
if((rsc.isDir && (flags_ & ImGuiFileBrowserFlags_SelectDirectory)) ||
(!rsc.isDir && !(flags_ & ImGuiFileBrowserFlags_SelectDirectory)))
{
selectedFilename_ = rsc.name;
if(!(flags_ & ImGuiFileBrowserFlags_SelectDirectory))
std::strcpy(inputNameBuf_->data(), selectedFilename_.c_str());
}
}
}
if(IsItemClicked(0) && ((flags_ & ImGuiFileBrowserFlags_SingleClickDir) || IsMouseDoubleClicked(0)) && rsc.isDir)
{
setNewPwd = true;
newPwd = (rsc.name != "..") ? (pwd_ / rsc.name) : pwd_.parent_path();
}
}
}
if(setNewPwd)
SetPwd(newPwd);
if(!(flags_ & ImGuiFileBrowserFlags_SelectDirectory) && (flags_ & ImGuiFileBrowserFlags_EnterNewFilename))
{
PushID(this);
ScopeGuard popTextID([] { PopID(); });
PushItemWidth(-1);
if(InputText("", inputNameBuf_->data(), inputNameBuf_->size()))
selectedFilename_ = inputNameBuf_->data();
PopItemWidth();
}
if(!(flags_ & ImGuiFileBrowserFlags_SelectDirectory))
{
if(Button(" ok ") && !selectedFilename_.empty())
{
ok_ = true;
CloseCurrentPopup();
}
}
else
{
if(selectedFilename_.empty())
{
if(Button(" ok "))
{
ok_ = true;
CloseCurrentPopup();
}
}
else if(Button("open"))
SetPwd(pwd_ / selectedFilename_);
}
SameLine();
int escIdx = GetIO().KeyMap[ImGuiKey_Escape];
if(Button("cancel") || closeFlag_ ||
((flags_ & ImGuiFileBrowserFlags_CloseOnEsc) && IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && escIdx >= 0 && IsKeyPressed(escIdx)))
CloseCurrentPopup();
if(!statusStr_.empty() && !(flags_ & ImGuiFileBrowserFlags_NoStatusBar))
{
SameLine();
Text("%s", statusStr_.c_str());
}
}
inline bool ImGui::FileBrowser::HasSelected() const noexcept
{
return ok_;
}
inline bool ImGui::FileBrowser::SetPwd(const std::filesystem::path &pwd)
{
try
{
SetPwdUncatched(pwd);
return true;
}
catch(const std::exception &err)
{
statusStr_ = std::string("last error: ") + err.what();
}
catch(...)
{
statusStr_ = "last error: unknown";
}
SetPwdUncatched(std::filesystem::current_path());
return false;
}
inline std::filesystem::path ImGui::FileBrowser::GetSelected() const
{
return pwd_ / selectedFilename_;
}
inline void ImGui::FileBrowser::ClearSelected()
{
selectedFilename_ = std::string();
(*inputNameBuf_)[0] = '\0';
ok_ = false;
}
#ifdef _WIN32
inline std::vector<std::string>* ImGui::FileBrowser::GetDrives()
{
static std::vector<std::string> drives;
if (drives.size() == 0)
{
char drivesBuffer[MAX_DRIVES_LENGTH];
GetLogicalDriveStrings(MAX_DRIVES_LENGTH, drivesBuffer);
char *currentDrive = drivesBuffer;
while (currentDrive != NULL && lstrlen(currentDrive) > 0)
{
drives.push_back(std::string(currentDrive));
currentDrive += lstrlen(currentDrive) + 1;
}
}
return &drives;
}
#endif
inline void ImGui::FileBrowser::SetPwdUncatched(const std::filesystem::path &pwd)
{
fileRecords_ = { FileRecord{ true, "..", "[D] .." } };
for(auto &p : std::filesystem::directory_iterator(pwd))
{
FileRecord rcd;
if(p.is_regular_file())
rcd.isDir = false;
else if(p.is_directory())
rcd.isDir = true;
else
continue;
rcd.name = p.path().filename().string();
if(rcd.name.empty())
continue;
if (!rcd.isDir && !IsAcceptableFileType(rcd.name))
continue;
rcd.showName = (rcd.isDir ? "[D] " : "[F] ") + p.path().filename().u8string();
fileRecords_.push_back(rcd);
}
std::sort(fileRecords_.begin(), fileRecords_.end(),
[flags = flags_](const FileRecord &L, const FileRecord &R)
{
return (L.isDir ^ R.isDir) ? L.isDir : ((flags & ImGuiFileBrowserFlags_SortIgnoreCase) ? (
lexicographical_compare(L.name.begin(), L.name.end(), R.name.begin(), R.name.end(), [](char ai, char bi) {
return tolower(ai) < tolower(bi);
}
)) : (L.name < R.name));
});
pwd_ = absolute(pwd);
selectedFilename_ = std::string();
(*inputNameBuf_)[0] = '\0';
}