File indexing completed on 2024-10-06 03:31:31
0001 /* 0002 SPDX-FileCopyrightText: 2008-2010 Peter Hedlund <peter.hedlund@kdemail.net> 0003 SPDX-License-Identifier: GPL-2.0-or-later 0004 */ 0005 0006 #include "blankanswer.h" 0007 0008 #include <QRegularExpression> 0009 #include <QStringList> 0010 0011 using namespace Qt::Literals::StringLiterals; 0012 0013 QString BlankAnswer::input() const 0014 { 0015 return m_input; 0016 } 0017 0018 void BlankAnswer::setInput(const QString &input) 0019 { 0020 if (input == m_input) { 0021 return; 0022 } 0023 m_input = input; 0024 0025 m_blankResult = blankAnswer(m_input); 0026 0027 Q_EMIT inputChanged(); 0028 } 0029 0030 bool BlankAnswer::hasBlank() const 0031 { 0032 return m_blankResult.correctAnswer.length() > 0; 0033 } 0034 0035 QString BlankAnswer::blankedAnswer() const 0036 { 0037 return m_blankResult.blankedAnswer; 0038 } 0039 0040 QString BlankAnswer::correctAnswer() const 0041 { 0042 return m_blankResult.correctAnswer; 0043 } 0044 0045 BlankAnswer::BlankResult BlankAnswer::blankAnswer(const QString &input) 0046 { 0047 BlankResult result; 0048 static QRegularExpression rx(u"\\[(.*?)\\]"_s); 0049 0050 QRegularExpressionMatchIterator matchIt = rx.globalMatch(input); 0051 0052 // When there is no blank return an empty result 0053 if (!matchIt.hasNext()) { 0054 return result; 0055 } 0056 0057 result.blankedAnswer = input; 0058 result.blankedAnswer.replace(rx, u".........."_s); 0059 0060 QStringList answerParts; 0061 0062 while (matchIt.hasNext()) { 0063 QRegularExpressionMatch match = matchIt.next(); 0064 answerParts << match.captured(1); 0065 } 0066 0067 result.correctAnswer = answerParts.join(u"; "_s); 0068 0069 return result; 0070 } 0071 0072 QString BlankAnswer::yourAnswerResult(const QString &givenAnswer, const QString &blankedAnswer) 0073 { 0074 QString result = givenAnswer; 0075 0076 if (!blankedAnswer.isEmpty()) { 0077 result.clear(); 0078 QStringList ls; 0079 0080 if (givenAnswer.indexOf(QLatin1Char(';')) > 0) 0081 ls = givenAnswer.split(QLatin1Char(';')); 0082 else 0083 ls.append(givenAnswer); 0084 0085 result = QString(blankedAnswer).replace(u".........."_s, u"<u></u>"_s); 0086 0087 int offset = 0, counter = 0; 0088 while (offset >= 0 && counter < ls.size()) { 0089 offset = result.indexOf(u"<u>"_s, offset); 0090 if (offset >= 0) { 0091 result.insert(offset + 3, ls[counter]); 0092 offset++; 0093 counter++; 0094 } 0095 } 0096 result.append(u"</qt>"_s); 0097 result.prepend(u"<qt>"_s); 0098 } 0099 0100 return result; 0101 } 0102 0103 #include "moc_blankanswer.cpp"