yaze 0.3.2
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
recent_files_menu_model.cc
Go to the documentation of this file.
2
3#include <filesystem>
4#include <map>
5#include <set>
6#include <string>
7#include <system_error>
8#include <vector>
9
10namespace yaze {
11namespace editor {
12
13namespace {
14
15bool DefaultExists(const std::string& path) {
16 std::error_code ec;
17 return std::filesystem::exists(std::filesystem::path(path), ec) && !ec;
18}
19
20std::string FileNameOf(const std::string& path) {
21 const std::string name = std::filesystem::path(path).filename().string();
22 return name.empty() ? path : name;
23}
24
25std::string ParentNameOf(const std::string& path) {
26 return std::filesystem::path(path).parent_path().filename().string();
27}
28
29} // namespace
30
31std::vector<RecentFileMenuEntry> BuildRecentFileMenuEntries(
32 const std::vector<std::string>& recent_paths, size_t max_entries,
33 const RecentFileExistsFn& exists) {
34 std::vector<RecentFileMenuEntry> entries;
35 std::set<std::string> seen_paths;
36 for (const std::string& path : recent_paths) {
37 if (entries.size() >= max_entries) {
38 break;
39 }
40 if (path.empty() || !seen_paths.insert(path).second) {
41 continue;
42 }
44 entry.path = path;
45 entry.label = FileNameOf(path);
46 entry.exists = exists ? exists(path) : DefaultExists(path);
47 entries.push_back(std::move(entry));
48 }
49
50 // Disambiguate duplicate file names with the parent directory name.
51 std::map<std::string, int> name_counts;
52 for (const auto& entry : entries) {
53 ++name_counts[entry.label];
54 }
55 for (auto& entry : entries) {
56 if (name_counts[entry.label] > 1) {
57 const std::string parent = ParentNameOf(entry.path);
58 if (!parent.empty()) {
59 entry.label = entry.label + " (" + parent + ")";
60 }
61 }
62 }
63
64 // Any label that still collides falls back to the full (unique) path.
65 std::map<std::string, int> label_counts;
66 for (const auto& entry : entries) {
67 ++label_counts[entry.label];
68 }
69 for (auto& entry : entries) {
70 if (label_counts[entry.label] > 1) {
71 entry.label = entry.path;
72 }
73 }
74 return entries;
75}
76
77} // namespace editor
78} // namespace yaze
std::vector< RecentFileMenuEntry > BuildRecentFileMenuEntries(const std::vector< std::string > &recent_paths, size_t max_entries, const RecentFileExistsFn &exists)
std::function< bool(const std::string &)> RecentFileExistsFn