Initial commit
[qquiz] / src / quiz.cpp
diff --git a/src/quiz.cpp b/src/quiz.cpp
new file mode 100644 (file)
index 0000000..76d5ac8
--- /dev/null
@@ -0,0 +1,366 @@
+/*
+ *  Copyright (C) 2010 Charles Clement <caratorn _at_ gmail.com>
+ *
+ *  This file is part of qquiz.
+ *
+ *  qquiz is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ *  02110-1301  USA
+ *
+ */
+
+#include "quiz.h"
+
+question::question(QString h, QString r) : hint(h), answer(r), answered(0) {
+}
+
+question::~question() {
+       delete(label);
+}
+
+quiz::quiz() : current(NULL), correct(0) {
+       QAction *choose;
+
+       window = new QWidget();
+       window->setWindowTitle(QApplication::translate("Qtquiz", "Qtquiz"));
+
+       menu = new QMenuBar(window);
+       choose = new QAction("Open", window);
+       QObject::connect(choose, SIGNAL(triggered()), this, SLOT(choose_quiz()));
+
+       menu->addAction(choose);
+       window->show();
+
+       retrieve_quizzes();
+
+       choose_quiz();
+};
+
+void quiz::retrieve_quizzes() {
+       QDir dir;
+       QFileInfoList list;
+       quiz_file *q;
+       QString path("");
+       QString buf;
+       QString datadir(PKGDATADIR);
+
+       if(dir.cd(datadir)) {
+               list = dir.entryInfoList(QDir::Files);
+       } else {
+               cerr << "Can't find directory " << datadir.toStdString() << endl;
+       }
+       path.append(dir.homePath());
+       path.append("/.");
+       path.append(APP_NAME);
+       if (dir.cd(path)) {
+               list.append(dir.entryInfoList(QDir::Files));
+       } else {
+               cerr << "Can't find directory " << path.toStdString() << endl;
+       }
+       for (int i = 0; i < list.size(); ++i) {
+               q = new quiz_file();
+
+               QFileInfo fileInfo = list.at(i);
+               q->path = fileInfo.absoluteFilePath();
+               QFile file(fileInfo.absoluteFilePath());
+               file.open(QFile::ReadOnly);
+               QTextStream stream(&file);
+               do {
+                       buf = stream.readLine();
+               } while (buf[0] == '#');
+               q->title = buf;
+               q->id = i;
+               files.push_back(q);
+       }
+}
+
+void quiz::choose_quiz() {
+    QStringList items;
+       vector<quiz_file *>::iterator itr;
+    bool ok;
+
+       for (itr = files.begin(); itr != files.end() ; itr++) {
+               items << (*itr)->title;
+       }
+
+    //QString item = QInputDialog::getItem(window, tr("Choose quiz"),
+       //                                        tr("Available quizzes:"), items, 0, false, &ok, QInputDialog::UseListViewForComboBoxItems);
+    QString item = QInputDialog::getItem(window, tr("Choose quiz"),
+                                                 tr("Available quizzes:"), items, 0, false, &ok);
+
+    if (ok && !item.isEmpty()) {
+               if (current) {
+                       vector<question *>::iterator itrq;
+
+                       index.clear();
+                       for ( itrq = questions.begin() ; itrq != questions.end() ; itrq++) {
+                               (*itrq)->label->hide();
+                               grid->removeWidget((*itrq)->label);
+                       }
+                       delete(timer);
+                       questions.clear();
+                       correct = 0;
+               } else {
+                       init_gui();
+               }
+               current = files.at(items.indexOf(item));
+               if(read_quiz(current->path.absolutePath().toStdString().c_str())) {
+                       menu->addAction(give_up);
+                       display_score();
+                       display_grid();
+                       if (total_time) {
+                               current_time = total_time;
+                               timer = new QTimer(this);
+                               connect(timer, SIGNAL(timeout()), this, SLOT(update_timer()));
+                               timer->start(1000);
+                       }
+               }
+       }
+}
+
+
+int quiz::read_quiz(const char *filename) {
+       string parse_line, hint, answer;
+       string buffer;
+       string::size_type loc, mloc;
+       QString qanswer;
+       question *q;
+       ifstream ifs (filename);
+       max_label_length = 0;
+       int i = 0;
+
+       total_time = 0;
+       if (!ifs) {
+               cerr << "Failed to open file " << filename << endl;
+               return 0;
+       } else {
+               do {
+                       getline(ifs, buffer);
+               } while (buffer[0] == '#');
+               title = QString::fromStdString(buffer);
+               do {
+                       getline(ifs, buffer);
+               } while (buffer[0] == '#');
+               total_time = atoi(buffer.c_str());
+               /* convert minutes to seconds */
+               total_time *= 60;
+               while (getline(ifs, parse_line)){
+                       if (parse_line[0] == '#')
+                               continue;
+
+                       loc = parse_line.find(CHAR_DELIM);
+                       if (loc == string::npos) {
+                               cerr << "Wrong format in file " << filename << endl;
+                               return 0 ;
+                       }
+
+                       hint = parse_line.substr(0, loc);
+                       if (hint.length() > max_label_length)
+                               max_label_length = hint.length();
+                       parse_line = parse_line.substr(loc);
+                       mloc = parse_line.find(ANSWER_DELIM);
+
+                       if (mloc == string::npos) {
+                               answer = parse_line.substr(1);
+                       } else {
+                               answer = parse_line.substr(1, mloc - 1);
+                       }
+                       if (answer.length() > max_label_length )
+                               max_label_length = answer.length();
+                       qanswer = QString::fromStdString(answer);
+                       qanswer = qanswer.trimmed();
+                       q = new question(QString::fromStdString(hint), qanswer );
+                       questions.push_back(q);
+                       index[qanswer.toLower()] = i;
+
+                       while (mloc != string::npos) {
+                               parse_line = parse_line.substr(mloc + 1);
+                               mloc = parse_line.find(ANSWER_DELIM);
+                               if (mloc != string::npos) {
+                                       answer = parse_line.substr(0, mloc);
+                               } else {
+                                       answer = parse_line.substr(0);
+                               }
+                               qanswer = QString::fromStdString(answer);
+                               qanswer = qanswer.trimmed();
+                               index[qanswer.toLower()] = i;
+                               mloc = parse_line.find(ANSWER_DELIM);
+                       }
+                       i++;
+               }
+               ifs.close();
+               total = i;
+       }
+       return 1;
+}
+
+void quiz::init_gui() {
+       QHBoxLayout *menu_layout;
+
+       line = new QLineEdit(window);
+       score = new QLabel("", window);
+       timer_label = new QLabel("0:00", window);
+
+       /* Disable auto-completion
+        */
+       //line->setCompleter((QCompleter *)0);
+       //line->setCompleter(0);
+
+#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
+       // supposed to work in Qt 4.6
+       line->setInputMethodHints(Qt::ImhNoPredictiveText);
+#endif
+
+       //line->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
+       line->setMinimumWidth(window->width() / 2);
+       score->setAlignment(Qt::AlignHCenter);
+       timer_label->setAlignment(Qt::AlignHCenter);
+
+       layout = new QVBoxLayout();
+       menu_layout = new QHBoxLayout();
+
+       score->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
+       line->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
+       timer_label->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
+
+       menu_layout->addWidget(score);
+       menu_layout->addWidget(line);
+       menu_layout->addWidget(timer_label);
+
+       menu_layout->setSizeConstraint(QLayout::SetFixedSize);
+       layout->addLayout(menu_layout);
+
+       scrollArea = new QScrollArea();
+       sub_window = new QWidget(scrollArea);
+       grid = new QGridLayout();
+
+       sub_window->setLayout(grid);
+       scrollArea->setWidget(sub_window);
+
+       scrollArea->setWidgetResizable(true);
+       scrollArea->setProperty("FingerScrollable", true);
+       scrollArea->setFocusPolicy(Qt::NoFocus);
+
+       layout->addWidget(scrollArea);
+       window->setLayout(layout);
+
+       QObject::connect(line, SIGNAL(textChanged(const QString&)), this, SLOT(buzz(const QString&)));
+
+       give_up = new QAction("Give up", window);
+       QObject::connect(give_up, SIGNAL(triggered()), this, SLOT(end()));
+}
+
+void quiz::buzz(const QString& buffer) {
+       map <QString, int>::iterator itr;
+       question *q;
+
+       itr = index.find(buffer.toLower());
+       if (itr != index.end()) {
+               q = questions.at(itr->second);
+
+               if (q->answered) {
+                       return ;
+               } else {
+                       q->label->setStyleSheet("QLabel { color: green }");
+                       q->label->setText(q->answer);
+                       correct++;
+                       line->clear();
+                       display_score();
+                       q->answered = 1;
+                       if (correct == total) {
+                               end();
+                       }
+               }
+       }
+}
+
+quiz::~quiz() {
+       index.clear();
+       questions.clear();
+}
+
+void quiz::display_score() {
+       QString score_text, ext;
+
+       score_text.setNum(correct);
+       score_text.append('/');
+       ext.setNum(total);
+       score_text.append(ext);
+
+       score->setText(score_text);
+}
+
+void quiz::display_grid() {
+       vector<question *>::iterator itrq;
+       int i,j, nr_columns, nr_col_padding;
+       int padding = 3;
+       int pixelsWide ;
+       QFont font;
+       string example;
+
+       QFontMetrics qfm = QFontMetrics(font);
+       example.append(max_label_length + 2, 'C');
+       pixelsWide = qfm.width(QString::fromStdString(example));
+
+       if (pixelsWide) {
+               nr_columns = window->width() / pixelsWide;
+               nr_col_padding = (window->width() -
+                               (2 * padding + nr_columns * 2 * padding) ) / pixelsWide;
+               nr_columns = nr_col_padding;
+       }
+       if (!nr_columns) {
+               nr_columns = DEFAULT_NR_COL;
+       }
+
+       itrq = questions.begin();
+       for ( i = 0; itrq != questions.end() ; i++) {
+
+               for ( j = 0 ; j < nr_columns && itrq != questions.end() ; j++) {
+                       (*itrq)->label = new QLabel((*itrq)->hint);
+                       // Doesn't do anything on maemo
+                       //(*itrq)->label->setFrameStyle(QFrame::Panel | QFrame::Raised);
+
+                       grid->addWidget((*itrq)->label, i, j);
+                       itrq++;
+               }
+       }
+
+}
+
+void quiz::update_timer() {
+
+       current_time--;
+       QTime t(0, current_time / 60, current_time % 60);
+       timer_label->setText(t.toString("m:ss"));
+       if (current_time == 0) {
+               end();
+       }
+}
+
+void quiz::end() {
+       vector<question *>::iterator itrq;
+
+       if(!current)
+               return;
+
+       timer->stop();
+
+       menu->removeAction(give_up);
+       for ( itrq = questions.begin() ; itrq != questions.end() ; itrq++) {
+               if (!(*itrq)->answered) {
+                       (*itrq)->label->setStyleSheet("QLabel { color: red }");
+                       (*itrq)->label->setText((*itrq)->answer);
+               }
+       }
+}