Add about dialog
[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), subset(0), correct(0)  {
33         QAction *choose;
34         QAction *about;
35
36         window = new QWidget();
37         window->setWindowTitle(QApplication::translate("Qtquiz", "Qtquiz"));
38
39         menu = new QMenuBar(window);
40         choose = new QAction("Open", window);
41         QObject::connect(choose, SIGNAL(triggered()), this, SLOT(choose_quiz()));
42
43         about = new QAction("About", window);
44         QObject::connect(about, SIGNAL(triggered()), this, SLOT(about()));
45
46         menu->addAction(choose);
47         menu->addAction(about);
48         window->show();
49
50         retrieve_quizzes();
51
52         choose_quiz();
53 };
54
55 void quiz::retrieve_quizzes() {
56         QDir dir;
57         QFileInfoList list;
58         quiz_file *q;
59         QString path("");
60         QString buf;
61         QString datadir(PKGDATADIR);
62
63         if(dir.cd(datadir)) {
64                 list = dir.entryInfoList(QDir::Files);
65         } else {
66                 cerr << "Can't find directory " << datadir.toStdString() << endl;
67         }
68         path.append(dir.homePath());
69         path.append("/.");
70         path.append(APP_NAME);
71         if (dir.cd(path)) {
72                 list.append(dir.entryInfoList(QDir::Files));
73         } else {
74                 cerr << "Can't find directory " << path.toStdString() << endl;
75         }
76         for (int i = 0; i < list.size(); ++i) {
77                 q = new quiz_file();
78
79                 QFileInfo fileInfo = list.at(i);
80                 q->path = fileInfo.absoluteFilePath();
81                 QFile file(fileInfo.absoluteFilePath());
82                 file.open(QFile::ReadOnly);
83                 QTextStream stream(&file);
84                 do {
85                         buf = stream.readLine();
86                 } while (buf[0] == '#');
87                 q->title = buf;
88                 q->id = i;
89                 files.push_back(q);
90         }
91 }
92
93 void quiz::choose_quiz() {
94     QStringList items;
95         vector<quiz_file *>::iterator itr;
96     bool ok;
97
98         for (itr = files.begin(); itr != files.end() ; itr++) {
99                 items << (*itr)->title;
100         }
101
102     //QString item = QInputDialog::getItem(window, tr("Choose quiz"),
103         //                                        tr("Available quizzes:"), items, 0, false, &ok, QInputDialog::UseListViewForComboBoxItems);
104     QString item = QInputDialog::getItem(window, tr("Choose quiz"),
105                                                   tr("Available quizzes:"), items, 0, false, &ok);
106
107     if (ok && !item.isEmpty()) {
108                 if (current) {
109                         vector<question *>::iterator itrq;
110
111                         index.clear();
112                         for ( itrq = questions.begin() ; itrq != questions.end() ; itrq++) {
113                                 (*itrq)->label->hide();
114                                 grid->removeWidget((*itrq)->label);
115                         }
116                         delete(timer);
117                         questions.clear();
118                         subset = 0;
119                         correct = 0;
120                 } else {
121                         init_gui();
122                 }
123                 current = files.at(items.indexOf(item));
124                 if(read_quiz(current->path.absolutePath().toStdString().c_str())) {
125                         if (subset) {
126                                 trim_questions();
127                         }
128                         build_index();
129                         menu->addAction(give_up);
130                         display_score();
131                         display_grid();
132                         current_time = total_time;
133                         display_timer();
134                         start_dialog();
135                         if (total_time) {
136                                 timer = new QTimer(this);
137                                 connect(timer, SIGNAL(timeout()), this, SLOT(update_timer()));
138                                 timer->start(1000);
139                         }
140                 } else {
141                         QString message = "Can't read file :\n";
142
143                         message.append(current->path.absolutePath());
144                         QMessageBox::warning (window, tr("Input file error"), message);
145                 }
146         }
147 }
148
149
150 int quiz::read_quiz(const char *filename) {
151         string parse_line, hint, answer;
152         string buffer;
153         string::size_type loc, mloc;
154         QString qanswer;
155         question *q;
156         ifstream ifs (filename);
157         max_label_length = 0;
158         int i = 0;
159     bool ok;
160
161         total_time = 0;
162         if (!ifs) {
163                 cerr << "Failed to open file " << filename << endl;
164                 return 0;
165         } else {
166                 do {
167                         getline(ifs, buffer);
168                 } while (buffer[0] == '#');
169                 title = QString::fromStdString(buffer);
170                 do {
171                         getline(ifs, buffer);
172                 } while (buffer[0] == '#');
173                 description = QString::fromStdString(buffer);
174                 do {
175                         getline(ifs, buffer);
176                 } while (buffer[0] == '#');
177                 if (! buffer.compare(0, strlen(SUBSET_PATTERN), SUBSET_PATTERN)) {
178                         subset = QString::fromStdString(buffer.substr(strlen(SUBSET_PATTERN))).toInt(&ok);
179                         if (!ok) {
180                                 return 0;
181                         }
182                         do {
183                                 getline(ifs, buffer);
184                         } while (buffer[0] == '#');
185                 }
186                 total_time = QString::fromStdString(buffer).toInt(&ok);
187                 if (!ok) {
188                         return 0;
189                 }
190                 /* convert minutes to seconds */
191                 total_time *= 60;
192                 while (getline(ifs, parse_line)){
193                         if (parse_line[0] == '#')
194                                 continue;
195
196                         loc = parse_line.find(CHAR_DELIM);
197                         if (loc == string::npos) {
198                                 cerr << "Wrong format in file " << filename << endl;
199                                 return 0;
200                         }
201
202                         hint = parse_line.substr(0, loc);
203                         if (hint.length() > max_label_length)
204                                 max_label_length = hint.length();
205                         parse_line = parse_line.substr(loc);
206                         mloc = parse_line.find(ANSWER_DELIM);
207
208                         if (mloc == string::npos) {
209                                 answer = parse_line.substr(1);
210                         } else {
211                                 answer = parse_line.substr(1, mloc - 1);
212                         }
213                         if (answer.length() > max_label_length )
214                                 max_label_length = answer.length();
215                         qanswer = QString::fromStdString(answer);
216                         qanswer = qanswer.trimmed();
217                         q = new question(QString::fromStdString(hint), qanswer );
218                         questions.push_back(q);
219
220                         while (mloc != string::npos) {
221                                 parse_line = parse_line.substr(mloc + 1);
222                                 mloc = parse_line.find(ANSWER_DELIM);
223                                 if (mloc != string::npos) {
224                                         answer = parse_line.substr(0, mloc);
225                                 } else {
226                                         answer = parse_line.substr(0);
227                                 }
228                                 qanswer = QString::fromStdString(answer);
229                                 qanswer = qanswer.trimmed();
230                                 q->alternate_answers.append(qanswer);
231                                 mloc = parse_line.find(ANSWER_DELIM);
232                         }
233                         i++;
234                 }
235                 ifs.close();
236                 total = i;
237         }
238         return 1;
239 }
240
241 void quiz::trim_questions() {
242         vector<question *> new_questions;
243         int number;
244         int nr_questions;
245
246         qsrand(QDateTime::currentDateTime().toTime_t());
247
248         nr_questions = subset;
249         while (nr_questions) {
250                 number = qrand() % questions.size();
251                 new_questions.push_back(questions.at(number));
252                 questions.erase(questions.begin() + number);
253                 nr_questions--;
254         }
255         questions.clear();
256         questions = new_questions;
257         total = subset;
258 }
259
260 void quiz::build_index() {
261         vector<question *>::iterator itr;
262         int position = 0;
263
264         for (itr = questions.begin(); itr != questions.end() ; itr++, position++) {
265                 index[(*itr)->answer.toLower()] = position;
266                 if (!(*itr)->alternate_answers.isEmpty()) {
267                         QList<QString>::iterator list_itr;
268
269                         for (list_itr = (*itr)->alternate_answers.begin();
270                                         list_itr != (*itr)->alternate_answers.end(); list_itr++)
271                                 index[(*list_itr).toLower()] = position;
272                 }
273         }
274 }
275
276 void quiz::init_gui() {
277         QHBoxLayout *menu_layout;
278
279         line = new QLineEdit(window);
280         score = new QLabel("", window);
281         timer_label = new QLabel("0:00", window);
282
283         /* Disable auto-completion
284          */
285         //line->setCompleter((QCompleter *)0);
286         //line->setCompleter(0);
287
288 #if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
289         // supposed to work in Qt 4.6
290         line->setInputMethodHints(Qt::ImhNoPredictiveText);
291 #endif
292
293         //line->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
294         line->setMinimumWidth(window->width() / 2);
295         score->setAlignment(Qt::AlignHCenter);
296         timer_label->setAlignment(Qt::AlignHCenter);
297
298         layout = new QVBoxLayout();
299         menu_layout = new QHBoxLayout();
300
301         score->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
302         line->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
303         timer_label->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
304
305         menu_layout->addWidget(score);
306         menu_layout->addWidget(line);
307         menu_layout->addWidget(timer_label);
308
309         menu_layout->setSizeConstraint(QLayout::SetFixedSize);
310         layout->addLayout(menu_layout);
311
312         scrollArea = new QScrollArea();
313         sub_window = new QWidget(scrollArea);
314         grid = new QGridLayout();
315
316         sub_window->setLayout(grid);
317         scrollArea->setWidget(sub_window);
318
319         scrollArea->setWidgetResizable(true);
320         scrollArea->setProperty("FingerScrollable", true);
321         scrollArea->setFocusPolicy(Qt::NoFocus);
322
323         layout->addWidget(scrollArea);
324         window->setLayout(layout);
325
326         QObject::connect(line, SIGNAL(textChanged(const QString&)), this, SLOT(buzz(const QString&)));
327
328         give_up = new QAction("Give up", window);
329         QObject::connect(give_up, SIGNAL(triggered()), this, SLOT(end()));
330 }
331
332 void quiz::start_dialog() {
333
334      QMessageBox::information(window, tr("Description"), description);
335
336 }
337
338 void quiz::buzz(const QString& buffer) {
339         map <QString, int>::iterator itr;
340         question *q;
341
342         itr = index.find(buffer.toLower());
343         if (itr != index.end()) {
344                 q = questions.at(itr->second);
345
346                 if (q->answered) {
347                         return ;
348                 } else {
349                         q->label->setStyleSheet("QLabel { color: green }");
350                         q->label->setText(q->answer);
351                         correct++;
352                         line->clear();
353                         display_score();
354                         q->answered = 1;
355                         if (correct == total) {
356                                 end();
357                         }
358                 }
359         }
360 }
361
362 quiz::~quiz() {
363         index.clear();
364         questions.clear();
365 }
366
367 void quiz::display_score() {
368         QString score_text, ext;
369
370         score_text.setNum(correct);
371         score_text.append('/');
372         ext.setNum(total);
373         score_text.append(ext);
374
375         score->setText(score_text);
376 }
377
378 void quiz::display_grid() {
379         vector<question *>::iterator itrq;
380         int i,j, nr_col_padding;
381         int nr_columns = 0;
382         int padding = 3;
383         int pixelsWide ;
384         QFont font;
385         string example;
386
387         QFontMetrics qfm = QFontMetrics(font);
388         example.append(max_label_length + 2, 'C');
389         pixelsWide = qfm.width(QString::fromStdString(example));
390
391         if (pixelsWide) {
392                 nr_columns = window->width() / pixelsWide;
393                 nr_col_padding = (window->width() -
394                                 (2 * padding + nr_columns * 2 * padding) ) / pixelsWide;
395                 nr_columns = nr_col_padding;
396         }
397         if (!nr_columns) {
398                 nr_columns = DEFAULT_NR_COL;
399         }
400
401         itrq = questions.begin();
402         for ( i = 0; itrq != questions.end() ; i++) {
403
404                 for ( j = 0 ; j < nr_columns && itrq != questions.end() ; j++) {
405                         (*itrq)->label = new QLabel((*itrq)->hint);
406                         // Doesn't do anything on maemo
407                         //(*itrq)->label->setFrameStyle(QFrame::Panel | QFrame::Raised);
408
409                         grid->addWidget((*itrq)->label, i, j);
410                         itrq++;
411                 }
412         }
413
414 }
415
416 void quiz::update_timer() {
417         current_time--;
418         display_timer();
419 }
420
421 void quiz::display_timer() {
422
423         QTime t(0, current_time / 60, current_time % 60);
424         timer_label->setText(t.toString("m:ss"));
425         if (current_time == 0) {
426                 end();
427         }
428 }
429
430 void quiz::end() {
431         vector<question *>::iterator itrq;
432
433         if(!current)
434                 return;
435
436         timer->stop();
437
438         menu->removeAction(give_up);
439         for ( itrq = questions.begin() ; itrq != questions.end() ; itrq++) {
440                 if (!(*itrq)->answered) {
441                         (*itrq)->label->setStyleSheet("QLabel { color: red }");
442                         (*itrq)->label->setText((*itrq)->answer);
443                 }
444         }
445 }
446
447 void quiz::about() {
448         QString message = "";
449         QString version;
450
451         message.append(APP_NAME);
452         message.append("-");
453         version = version.setNum(APP_VERSION);
454         message.append(version);
455         message.append("\n by ");
456         message.append(AUTHOR);
457         QMessageBox::about ( window, tr("About"), message);
458 }
459