| 38 | namespace DFHack |
| 39 | { |
| 40 | class CommandHistory |
| 41 | { |
| 42 | public: |
| 43 | CommandHistory(std::size_t capacity = 5000) |
| 44 | { |
| 45 | this->capacity = capacity; |
| 46 | } |
| 47 | bool load (std::filesystem::path filename) |
| 48 | { |
| 49 | std::string reader; |
| 50 | std::ifstream infile(filename); |
| 51 | if(infile.bad()) |
| 52 | return false; |
| 53 | std::string s; |
| 54 | while(std::getline(infile, s)) |
| 55 | { |
| 56 | if(s.empty()) |
| 57 | continue; |
| 58 | history.push_back(s); |
| 59 | } |
| 60 | return true; |
| 61 | } |
| 62 | bool save (std::filesystem::path filename) |
| 63 | { |
| 64 | if (!history.size()) |
| 65 | return true; |
| 66 | std::ofstream outfile (filename); |
| 67 | //fprintf(stderr,"Save: Initialized stream\n"); |
| 68 | if(outfile.bad()) |
| 69 | return false; |
| 70 | //fprintf(stderr,"Save: Iterating...\n"); |
| 71 | for(auto iter = history.begin();iter < history.end(); iter++) |
| 72 | { |
| 73 | //fprintf(stderr,"Save: Dumping %s\n",(*iter).c_str()); |
| 74 | outfile << *iter << std::endl; |
| 75 | //fprintf(stderr,"Save: Flushing\n"); |
| 76 | outfile.flush(); |
| 77 | } |
| 78 | //fprintf(stderr,"Save: Closing\n"); |
| 79 | outfile.close(); |
| 80 | //fprintf(stderr,"Save: Done\n"); |
| 81 | return true; |
| 82 | } |
| 83 | /// add a command to the history |
| 84 | void add(const std::string& command) |
| 85 | { |
| 86 | // if current command = last in history -> do not add. Always add if history is empty. |
| 87 | if(!history.empty() && history.front() == command) |
| 88 | return; |
| 89 | history.push_front(command); |
| 90 | if(history.size() > capacity) |
| 91 | history.pop_back(); |
| 92 | } |
| 93 | /// clear the command history |
| 94 | void clear() |
| 95 | { |
| 96 | history.clear(); |
| 97 | } |