Merge branch 'rr1-maint'
[lsnes.git] / src / library / recentfiles.cpp
blob564de067b6b840633d557d2d71d0b4bc44462c22
1 #include "recentfiles.hpp"
2 #include "zip.hpp"
3 #include <fstream>
5 recent_files::recent_files(const std::string& _cfgfile, size_t _maxcount)
7 cfgfile = _cfgfile;
8 maxcount = _maxcount;
11 void recent_files::add(const std::string& file)
13 std::list<std::string> ents;
14 //Load the list.
16 std::ifstream in(cfgfile);
17 std::string f;
18 while(in) {
19 std::getline(in, f);
20 if(f != "") {
21 bool exists = true;
22 try {
23 //Probe for existence.
24 delete &open_file_relative(f, "");
25 } catch(std::exception& e) {
26 exists = false;
28 if(exists)
29 ents.push_back(f);
33 //Search for matches. If found, move to front, otherwise push to first.
34 auto itr = ents.begin();
35 for(; itr != ents.end(); itr++)
36 if(*itr == file)
37 break;
38 if(itr != ents.end())
39 ents.erase(itr);
40 ents.push_front(file);
41 //Write up to maxcount entries.
43 size_t i = 0;
44 std::ofstream out(cfgfile);
45 for(itr = ents.begin(); itr != ents.end() && i < maxcount; itr++, i++)
46 out << *itr << std::endl;
48 for(auto i : hooks)
49 (*i)();
52 void recent_files::add_hook(hook& h)
54 hooks.push_back(&h);
57 void recent_files::remove_hook(hook& h)
59 for(auto itr = hooks.begin(); itr != hooks.end(); itr++)
60 if(*itr == &h) {
61 hooks.erase(itr);
62 break;
66 std::list<std::string> recent_files::get()
68 size_t c = 0;
69 std::list<std::string> ents;
70 //Load the list.
72 std::ifstream in(cfgfile);
73 std::string f;
74 while(in) {
75 std::getline(in, f);
76 if(f != "") {
77 if(c < maxcount) {
78 ents.push_back(f);
79 c++;
84 return ents;
87 recent_files::recent_files::hook::~hook()