目录
前言
前几节中实现了加载script与scene的功能,为了方便使用,增添了最近访问目录以便快速读取。
主要工作
了解底层的功能函数,编写记录与访问最近访问文件的功能。
一、具体实现
最近访问script选项
首先,使用 mpRenderer 父对象的 getAppData函数 获取当前的应用数据对象,该对象拥有成员函数getRecentScripts 函数,由于在每次加载函数时使用appData.addRecentScript函数,将访问过的文件路径写入json文件中。
每次生成渲染器的过程中,appData都会中都会读入RecentScripts信息,并使用path类型的向量储存。
其间,使用menu函数生成menu组件,参数为菜单名称。为了让菜单的每一个选项都是可点击的文件路径,于是遍历访问RecentScripts的路径向量,每成功读取一个路径,使用item生成一个选项,if语句成功执行,调用加载函数,并使用appData.addRecentScript函数重新载入。
此处需要注意,RecentScripts返回的类型为path向量,需要转化为string才能被传入item函数。
{
auto &appData = mpRenderer->getAppData();
auto recentScripts = file.menu("Recent Scripts");
for (auto path : appData.getRecentScripts())
{
if (recentScripts.item(path.string()))
{
mpRenderer->loadScriptDeferred(path);
appData.addRecentScript(path);
}
}
}
在appData.addRecentScript函数中,路径向量会检查所有元素,删除相同元素并插入新元素,并存入磁盘文件中。
void AppData::addRecentPath(std::vector<std::filesystem::path>& paths, const std::filesystem::path& path)
{
if (!std::filesystem::exists(path)) return;
std::filesystem::path fullPath = std::filesystem::canonical(path);
paths.erase(std::remove(paths.begin(), paths.end(), fullPath), paths.end());
paths.insert(paths.begin(), fullPath);
if (paths.size() > kMaxRecentFiles) paths.resize(kMaxRecentFiles);
save();
}
最近访问scene选项
本段的功能的实现与上文类似,只需替换对应额的函数与变量名即可。
{
auto &appData = mpRenderer->getAppData();
auto recentScenes = file.menu("Recent Scenes");
for (auto path : appData.getRecentScenes())
{
if (recentScenes.item(path.string()))
{
mpRenderer->loadScene(path);
appData.addRecentScene(path);
}
}
}