Initial commit
[qquiz] / src / quiz.cpp
1 /*
2  *  Copyright (C) 2010 Charles Clement <caratorn _at_ gmail.com>
3  *
4  *  This file is part of qquiz.
5  *
6  *  qquiz is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19  *  02110-1301  USA
20  *
21  */
22
23 #include "quiz.h"
24
25 question::question(QString h, QString r) : hint(h), answer(r), answered(0) {
26 }
27
28 question::~question() {
29         delete(label);
30 }
31
32 quiz::quiz() : current(NULL), correct(0) {
33         QAction *choose;
34
35         window = new QWidget();
36         window->setWindowTitle(QApplication::translate("Qtquiz", "Qtquiz"));
37
38         menu = new QMenuBar(window);
39         choose = new QAction("Open", window);
40         QObject::connect(choose, SIGNAL(triggered()), this, SLOT(choose_quiz()));
41
42         menu->addAction(choose);
43         window->show();
44
45         retrieve_quizzes();
46
47         choose_quiz();
48 };
49
50 void quiz::retrieve_quizzes() {
51         QDir dir;
52         QFileInfoList list;
53         quiz_file *q;
54         QString path("");
55         QString buf;
56         QString datadir(PKGDATADIR);
57
58         if(dir.cd(datadir)) {
59                 list = dir.entryInfoList(QDir::Files);
60         } else {
61                 cerr << "Can't find directory " << datadir.toStdString() << endl;
62         }
63         path.append(dir.homePath());
64         path.append("/.");
65         path.append(APP_NAME);
66         if (dir.cd(path)) {
67                 list.append(dir.entryInfoList(QDir::Files));
68         } else {
69                 cerr << "Can't find directory " << path.toStdString() << endl;
70         }
71         for (int i = 0; i < list.size(); ++i) {
72                 q = new quiz_file();
73
74                 QFileInfo fileInfo = list.at(i);
75                 q->path = fileInfo.absoluteFilePath();
76                 QFile file(fileInfo.absoluteFilePath());
77                 file.open(QFile::ReadOnly);
78                 QTextStream stream(&file);
79                 do {
80                         buf = stream.readLine();
81                 } while (buf[0] == '#');
82                 q->title = buf;
83                 q->id = i;
84                 files.push_back(q);
85         }
86 }
87
88 void quiz::choose_quiz() {
89     QStringList items;
90         vector<quiz_file *>::iterator itr;
91     bool ok;
92
93         for (itr = files.begin(); itr != files.end() ; itr++) {
94                 items << (*itr)->title;
95         }
96
97     //QString item = QInputDialog::getItem(window, tr("Choose quiz"),
98         //                                        tr("Available quizzes:"), items, 0, false, &ok, QInputDialog::UseListViewForComboBoxItems);
99     QString item = QInputDialog::getItem(window, tr("Choose quiz"),
100                                                   tr("Available quizzes:"), items, 0, false, &ok);
101
102     if (ok && !item.isEmpty()) {
103                 if (current) {
104                         vector<question *>::iterator itrq;
105
106                         index.clear();
107                         for ( itrq = questions.begin() ; itrq != questions.end() ; itrq++) {
108                                 (*itrq)->label->hide();
109                                 grid->removeWidget((*itrq)->label);
110                         }
111                         delete(timer);
112                         questions.clear();
113                         correct = 0;
114                 } else {
115                         init_gui();
116                 }
117                 current = files.at(items.indexOf(item));
118                 if(read_quiz(current->path.absolutePath().toStdString().c_str())) {
119                         menu->addAction(give_up);
120                         display_score();
121                         display_grid();
122                         if (total_time) {
123                                 current_time = total_time;
124                                 timer = new QTimer(this);
125                                 connect(timer, SIGNAL(timeout()), this, SLOT(update_timer()));
126                                 timer->start(1000);
127                         }
128                 }
129         }
130 }
131
132
133 int quiz::read_quiz(const char *filename) {
134         string parse_line, hint, answer;
135         string buffer;
136         string::size_type loc, mloc;
137         QString qanswer;
138         question *q;
139         ifstream ifs (filename);
140         max_label_length = 0;
141         int i = 0;
142
143         total_time = 0;
144         if (!ifs) {
145                 cerr << "Failed to open file " << filename << endl;
146                 return 0;
147         } else {
148                 do {
149                         getline(ifs, buffer);
150                 } while (buffer[0] == '#');
151                 title = QString::fromStdString(buffer);
152                 do {
153                         getline(ifs, buffer);
154                 } while (buffer[0] == '#');
155                 total_time = atoi(buffer.c_str());
156                 /* convert minutes to seconds */
157                 total_time *= 60;
158                 while (getline(ifs, parse_line)){
159                         if (parse_line[0] == '#')
160                                 continue;
161
162                         loc = parse_line.find(CHAR_DELIM);
163                         if (loc == string::npos) {
164                                 cerr << "Wrong format in file " << filename << endl;
165                                 return 0 ;
166                         }
167
168                         hint = parse_line.substr(0, loc);
169                         if (hint.length() > max_label_length)
170                                 max_label_length = hint.length();
171                         parse_line = parse_line.substr(loc);
172                         mloc = parse_line.find(ANSWER_DELIM);
173
174                         if (mloc == string::npos) {
175                                 answer = parse_line.substr(1);
176                         } else {
177                                 answer = parse_line.substr(1, mloc - 1);
178                         }
179                         if (answer.length() > max_label_length )
180                                 max_label_length = answer.length();
181                         qanswer = QString::fromStdString(answer);
182                         qanswer = qanswer.trimmed();
183                         q = new question(QString::fromStdString(hint), qanswer );
184                         questions.push_back(q);
185                         index[qanswer.toLower()] = i;
186
187                         while (mloc != string::npos) {
188                                 parse_line = parse_line.substr(mloc + 1);
189                                 mloc = parse_line.find(ANSWER_DELIM);
190                                 if (mloc != string::npos) {
191                                         answer = parse_line.substr(0, mloc);
192                                 } else {
193                                         answer = parse_line.substr(0);
194                                 }
195                                 qanswer = QString::fromStdString(answer);
196                                 qanswer = qanswer.trimmed();
197                                 index[qanswer.toLower()] = i;
198                                 mloc = parse_line.find(ANSWER_DELIM);
199                         }
200                         i++;
201                 }
202                 ifs.close();
203                 total = i;
204         }
205         return 1;
206 }
207
208 void quiz::init_gui() {
209         QHBoxLayout *menu_layout;
210
211         line = new QLineEdit(window);
212         score = new QLabel("", window);
213         timer_label = new QLabel("0:00", window);
214
215         /* Disable auto-completion
216          */
217         //line->setCompleter((QCompleter *)0);
218         //line->setCompleter(0);
219
220 #if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
221         // supposed to work in Qt 4.6
222         line->setInputMethodHints(Qt::ImhNoPredictiveText);
223 #endif
224
225         //line->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
226         line->setMinimumWidth(window->width() / 2);
227         score->setAlignment(Qt::AlignHCenter);
228         timer_label->setAlignment(Qt::AlignHCenter);
229
230         layout = new QVBoxLayout();
231         menu_layout = new QHBoxLayout();
232
233         score->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
234         line->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
235         timer_label->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
236
237         menu_layout->addWidget(score);
238         menu_layout->addWidget(line);
239         menu_layout->addWidget(timer_label);
240
241         menu_layout->setSizeConstraint(QLayout::SetFixedSize);
242         layout->addLayout(menu_layout);
243
244         scrollArea = new QScrollArea();
245         sub_window = new QWidget(scrollArea);
246         grid = new QGridLayout();
247
248         sub_window->setLayout(grid);
249         scrollArea->setWidget(sub_window);
250
251         scrollArea->setWidgetResizable(true);
252         scrollArea->setProperty("FingerScrollable", true);
253         scrollArea->setFocusPolicy(Qt::NoFocus);
254
255         layout->addWidget(scrollArea);
256         window->setLayout(layout);
257
258         QObject::connect(line, SIGNAL(textChanged(const QString&)), this, SLOT(buzz(const QString&)));
259
260         give_up = new QAction("Give up", window);
261         QObject::connect(give_up, SIGNAL(triggered()), this, SLOT(end()));
262 }
263
264 void quiz::buzz(const QString& buffer) {
265         map <QString, int>::iterator itr;
266         question *q;
267
268         itr = index.find(buffer.toLower());
269         if (itr != index.end()) {
270                 q = questions.at(itr->second);
271
272                 if (q->answered) {
273                         return ;
274                 } else {
275                         q->label->setStyleSheet("QLabel { color: green }");
276                         q->label->setText(q->answer);
277                         correct++;
278                         line->clear();
279                         display_score();
280                         q->answered = 1;
281                         if (correct == total) {
282                                 end();
283                         }
284                 }
285         }
286 }
287
288 quiz::~quiz() {
289         index.clear();
290         questions.clear();
291 }
292
293 void quiz::display_score() {
294         QString score_text, ext;
295
296         score_text.setNum(correct);
297         score_text.append('/');
298         ext.setNum(total);
299         score_text.append(ext);
300
301         score->setText(score_text);
302 }
303
304 void quiz::display_grid() {
305         vector<question *>::iterator itrq;
306         int i,j, nr_columns, nr_col_padding;
307         int padding = 3;
308         int pixelsWide ;
309         QFont font;
310         string example;
311
312         QFontMetrics qfm = QFontMetrics(font);
313         example.append(max_label_length + 2, 'C');
314         pixelsWide = qfm.width(QString::fromStdString(example));
315
316         if (pixelsWide) {
317                 nr_columns = window->width() / pixelsWide;
318                 nr_col_padding = (window->width() -
319                                 (2 * padding + nr_columns * 2 * padding) ) / pixelsWide;
320                 nr_columns = nr_col_padding;
321         }
322         if (!nr_columns) {
323                 nr_columns = DEFAULT_NR_COL;
324         }
325
326         itrq = questions.begin();
327         for ( i = 0; itrq != questions.end() ; i++) {
328
329                 for ( j = 0 ; j < nr_columns && itrq != questions.end() ; j++) {
330                         (*itrq)->label = new QLabel((*itrq)->hint);
331                         // Doesn't do anything on maemo
332                         //(*itrq)->label->setFrameStyle(QFrame::Panel | QFrame::Raised);
333
334                         grid->addWidget((*itrq)->label, i, j);
335                         itrq++;
336                 }
337         }
338
339 }
340
341 void quiz::update_timer() {
342
343         current_time--;
344         QTime t(0, current_time / 60, current_time % 60);
345         timer_label->setText(t.toString("m:ss"));
346         if (current_time == 0) {
347                 end();
348         }
349 }
350
351 void quiz::end() {
352         vector<question *>::iterator itrq;
353
354         if(!current)
355                 return;
356
357         timer->stop();
358
359         menu->removeAction(give_up);
360         for ( itrq = questions.begin() ; itrq != questions.end() ; itrq++) {
361                 if (!(*itrq)->answered) {
362                         (*itrq)->label->setStyleSheet("QLabel { color: red }");
363                         (*itrq)->label->setText((*itrq)->answer);
364                 }
365         }
366 }