update dict
[QFreeRecite.git] / src / core / Scanner.cpp
blob5f7ce318a765ae434b301abee493246fb1248e7c
1 #include <fstream>
2 #include <algorithm>
3 #include <ctime>
4 #include <sstream>
5 #include <set>
6 #include "Debug.h"
7 #include "ConfigHolder.h"
8 #include "Reciter.h"
9 #include "WordList.h"
10 #include "Scanner.h"
12 namespace freeRecite {
14 Scanner::~Scanner() {
15 D_OUTPUT("~Scanner()");
16 if(wordList != 0)
17 delete wordList;
20 const std::string Scanner::getTaskFileName(time_t initID) {
21 std::ostringstream oss;
22 oss << static_cast<unsigned>(initID);
23 return (configHolder.tasksDir() + oss.str() + ".tkwd");
26 bool Scanner::loadWords(time_t initID,bool Random) {
27 taskFileName = getTaskFileName(initID);
28 taskID = initID;
29 std::ifstream ifs(taskFileName.c_str());
30 if(!ifs.is_open())
31 return false;
32 std::string tmpWord;
33 while(ifs.good()) {
34 std::getline(ifs,tmpWord);
35 while(tmpWord[tmpWord.size()-1] == ' ')
36 tmpWord.erase(tmpWord.size()-1);
37 if(!tmpWord.empty())
38 words.push_back(tmpWord);
40 //If Random is false, then do not call makeRandom().
41 return Random ? makeRandom() : true;
44 bool Scanner::loadWords(const char *fileName, bool Random) {
45 taskFileName = fileName;
46 std::ifstream ifs(fileName);
47 if(!ifs.is_open())
48 return false;
49 std::string tmpWord;
50 std::set<std::string> wordFilter;
51 while(ifs.good()) {
52 std::getline(ifs,tmpWord);
53 while(tmpWord[tmpWord.size()-1] == ' ')
54 tmpWord.erase(tmpWord.size()-1);
55 if(!tmpWord.empty())
56 wordFilter.insert(tmpWord);
58 std::set<std::string>::const_iterator itr = wordFilter.begin();
59 while(itr != wordFilter.end()) {
60 words.push_back(*itr);
61 ++itr;
64 if(Random == true)
65 makeRandom();
66 return save();
70 //Add a word to the current task.
71 bool Scanner::add(const std::string &word) {
72 words.push_back(word);
73 wordList->add();
74 return save();
77 //Remove a word from the current task.
78 bool Scanner::remove(const std::string &word) {
79 unsigned index = 0;
80 while( index < words.size() ) {
81 if(words[index] == word)
82 break;
83 else
84 ++index;
86 if(index == words.size()) //Can't find this word.
87 return false;
89 words[index] = words[words.size()-1];
90 words.pop_back();
91 wordList->remove();
92 return save();
95 bool Scanner::save() {
96 std::set<std::string> wordSet;
97 for(size_t i = 0; i < words.size(); ++i)
98 if( !wordSet.insert(words[i]).second)
99 return false;
101 std::ofstream ofs(taskFileName.c_str());
102 if(!ofs.is_open())
103 return false;
105 std::set<std::string>::iterator itr = wordSet.begin();
106 while(itr != wordSet.end()) {
107 if(!ofs.good())
108 return false;
109 else{
110 ofs << *itr << std::endl;
111 ++itr;
114 ofs.close();
115 return true;
118 bool Scanner::makeRandom() {
119 if(words.empty())
120 return false;
121 Random rd;
122 srand(time(0));
123 std::random_shuffle(words.begin(),words.end(),rd);
124 return true;
128 } //End of namespace freeRecite