-
Notifications
You must be signed in to change notification settings - Fork 3
/
file-open.cpp
99 lines (90 loc) · 2.65 KB
/
file-open.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
#include "file-open.hpp"
#include <functional>
#include <imgui/imgui.h>
#include <log/log.hpp>
auto FileOpen::draw() -> bool
{
if (!ImGui::BeginPopupModal("FileOpen", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
return false;
auto ret = false;
if (files.empty())
{
// list files and directories in the current directory
const auto cwd = std::filesystem::current_path();
for (auto &entry : std::filesystem::directory_iterator(cwd))
files.push_back(entry.path());
std::sort(files.begin(), files.end());
}
// Populate the files in the list box
if (ImGui::BeginListBox("##files", ImVec2(700, 400)))
{
std::function<void()> postponedAction = nullptr;
if (ImGui::Selectable("..", ".." == selectedFile, ImGuiSelectableFlags_AllowDoubleClick))
if (ImGui::IsMouseDoubleClicked(0))
postponedAction = [this]() {
files.clear();
selectedFile = "";
// Get the current working directory.
const auto cwd = std::filesystem::current_path();
// Go up one directory.
std::filesystem::current_path(cwd.parent_path());
};
for (auto &file : files)
{
const auto isHidden = file.filename().string().front() == '.';
if (isHidden)
continue;
const auto isDirectory = std::filesystem::is_directory(file);
if (ImGui::Selectable(
((isDirectory ? "> " : " ") + file.filename().string()).c_str(), selectedFile == file, ImGuiSelectableFlags_AllowDoubleClick))
{
if (ImGui::IsMouseDoubleClicked(0))
{
if (isDirectory)
{
// change directory
postponedAction = [this, file]() {
std::filesystem::current_path(file);
files.clear();
selectedFile = "";
};
}
else
{
selectedFile = file;
ImGui::CloseCurrentPopup();
ret = true;
}
}
else
{
selectedFile = file;
}
}
}
if (postponedAction)
postponedAction();
ImGui::EndListBox();
}
// Show the selected file
if (!selectedFile.empty())
ImGui::Text("%s", selectedFile.filename().c_str());
else
ImGui::Text("No file selected");
ImGui::SameLine(700 - 2 * 120 - 10);
if (ImGui::Button("Open", ImVec2(120, 0)))
{
ImGui::CloseCurrentPopup();
ret = true;
}
ImGui::SetItemDefaultFocus();
ImGui::SameLine(700 - 120);
if (ImGui::Button("Cancel", ImVec2(120, 0)))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
return ret;
}
auto FileOpen::getSelectedFile() const -> std::filesystem::path
{
return selectedFile;
}