3d199a1281c0151026b5ded23f8068926cb0aa9e
[quassel.git] / src / common / util.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "util.h"
22
23 #include <algorithm>
24 #include <array>
25 #include <utility>
26
27 #include <QCoreApplication>
28 #include <QDateTime>
29 #include <QDebug>
30 #include <QTextCodec>
31 #include <QVector>
32
33 #include "quassel.h"
34
35 // MIBenum values from http://www.iana.org/assignments/character-sets/character-sets.xml#table-character-sets-1
36 static QList<int> utf8DetectionBlacklist = QList<int>()
37     << 39 /* ISO-2022-JP */;
38
39 QString nickFromMask(const QString &mask)
40 {
41     return mask.left(mask.indexOf('!'));
42 }
43
44
45 QString userFromMask(const QString &mask)
46 {
47     const int offset = mask.indexOf('!') + 1;
48     if (offset <= 0)
49         return {};
50     const int length = mask.indexOf('@', offset) - offset;
51     return mask.mid(offset, length >= 0 ? length : -1);
52 }
53
54
55 QString hostFromMask(const QString &mask)
56 {
57     const int excl = mask.indexOf('!');
58     if (excl < 0)
59         return {};
60     const int offset = mask.indexOf('@', excl + 1) + 1;
61     return offset > 0 && offset < mask.size() ? mask.mid(offset) : QString{};
62 }
63
64
65 bool isChannelName(const QString &str)
66 {
67     static constexpr std::array<quint8, 4> prefixes{{'#', '&', '!', '+'}};
68     return std::any_of(prefixes.cbegin(), prefixes.cend(), [&str](quint8 c) { return c == str[0]; });
69 }
70
71
72 QString stripFormatCodes(QString message)
73 {
74     static QRegExp regEx{"\x03(\\d\\d?(,\\d\\d?)?)?|[\x02\x0f\x12\x16\x1d\x1f]"};
75     return message.remove(regEx);
76 }
77
78
79 QString stripAcceleratorMarkers(const QString &label_)
80 {
81     QString label = label_;
82     int p = 0;
83     forever {
84         p = label.indexOf('&', p);
85         if (p < 0 || p + 1 >= label.length())
86             break;
87
88         if (label.at(p + 1).isLetterOrNumber() || label.at(p + 1) == '&')
89             label.remove(p, 1);
90
91         ++p;
92     }
93     return label;
94 }
95
96
97 QString decodeString(const QByteArray &input, QTextCodec *codec)
98 {
99     if (codec && utf8DetectionBlacklist.contains(codec->mibEnum()))
100         return codec->toUnicode(input);
101
102     // First, we check if it's utf8. It is very improbable to encounter a string that looks like
103     // valid utf8, but in fact is not. This means that if the input string passes as valid utf8, it
104     // is safe to assume that it is.
105     // Q_ASSERT(sizeof(const char) == sizeof(quint8));  // In God we trust...
106     bool isUtf8 = true;
107     int cnt = 0;
108     for (int i = 0; i < input.size(); i++) {
109         if (cnt) {
110             // We check a part of a multibyte char. These need to be of the form 10yyyyyy.
111             if ((input[i] & 0xc0) != 0x80) { isUtf8 = false; break; }
112             cnt--;
113             continue;
114         }
115         if ((input[i] & 0x80) == 0x00) continue;  // 7 bit is always ok
116         if ((input[i] & 0xf8) == 0xf0) { cnt = 3; continue; } // 4-byte char 11110xxx 10yyyyyy 10zzzzzz 10vvvvvv
117         if ((input[i] & 0xf0) == 0xe0) { cnt = 2; continue; } // 3-byte char 1110xxxx 10yyyyyy 10zzzzzz
118         if ((input[i] & 0xe0) == 0xc0) { cnt = 1; continue; } // 2-byte char 110xxxxx 10yyyyyy
119         isUtf8 = false; break; // 8 bit char, but not utf8!
120     }
121     if (isUtf8 && cnt == 0) {
122         QString s = QString::fromUtf8(input);
123         //qDebug() << "Detected utf8:" << s;
124         return s;
125     }
126     //QTextCodec *codec = QTextCodec::codecForName(encoding.toLatin1());
127     if (!codec) return QString::fromLatin1(input);
128     return codec->toUnicode(input);
129 }
130
131
132 uint editingDistance(const QString &s1, const QString &s2)
133 {
134     uint n = s1.size()+1;
135     uint m = s2.size()+1;
136     QVector<QVector<uint> > matrix(n, QVector<uint>(m, 0));
137
138     for (uint i = 0; i < n; i++)
139         matrix[i][0] = i;
140
141     for (uint i = 0; i < m; i++)
142         matrix[0][i] = i;
143
144     uint min;
145     for (uint i = 1; i < n; i++) {
146         for (uint j = 1; j < m; j++) {
147             uint deleteChar = matrix[i-1][j] + 1;
148             uint insertChar = matrix[i][j-1] + 1;
149
150             if (deleteChar < insertChar)
151                 min = deleteChar;
152             else
153                 min = insertChar;
154
155             if (s1[i-1] == s2[j-1]) {
156                 uint inheritChar = matrix[i-1][j-1];
157                 if (inheritChar < min)
158                     min = inheritChar;
159             }
160
161             matrix[i][j] = min;
162         }
163     }
164     return matrix[n-1][m-1];
165 }
166
167
168 QString secondsToString(int timeInSeconds)
169 {
170     static QVector<std::pair<int, QString>> timeUnit {
171         std::make_pair(365*24*60*60, QCoreApplication::translate("Quassel::secondsToString()", "year")),
172         std::make_pair(24*60*60, QCoreApplication::translate("Quassel::secondsToString()", "day")),
173         std::make_pair(60*60, QCoreApplication::translate("Quassel::secondsToString()", "h")),
174         std::make_pair(60, QCoreApplication::translate("Quassel::secondsToString()", "min")),
175         std::make_pair(1, QCoreApplication::translate("Quassel::secondsToString()", "sec"))
176     };
177
178     if (timeInSeconds != 0) {
179         QStringList returnString;
180         for (int i = 0; i < timeUnit.size(); i++) {
181             int n = timeInSeconds / timeUnit[i].first;
182             if (n > 0) {
183                 returnString += QString("%1 %2").arg(QString::number(n), timeUnit[i].second);
184             }
185             timeInSeconds = timeInSeconds % timeUnit[i].first;
186         }
187         return returnString.join(", ");
188     }
189     else {
190         return QString("%1 %2").arg(QString::number(timeInSeconds), timeUnit.last().second);
191     }
192 }
193
194
195 QByteArray prettyDigest(const QByteArray &digest)
196 {
197     QByteArray hexDigest = digest.toHex().toUpper();
198     QByteArray prettyDigest;
199     prettyDigest.fill(':', hexDigest.count() + (hexDigest.count() / 2) - 1);
200
201     for (int i = 0; i * 2 < hexDigest.count(); i++) {
202         prettyDigest.replace(i * 3, 2, hexDigest.mid(i * 2, 2));
203     }
204     return prettyDigest;
205 }
206
207
208 QString formatCurrentDateTimeInString(const QString &formatStr)
209 {
210     // Work on a copy of the string to avoid modifying the input string
211     QString formattedStr = QString(formatStr);
212
213     // Exit early if there's nothing to format
214     if (formattedStr.isEmpty())
215         return formattedStr;
216
217     // Find %%<text>%% in string. Replace inside text formatted to QDateTime with the current
218     // timestamp, using %%%% as an escape for multiple %% signs.
219     // For example:
220     // Simple:   "All Quassel clients vanished from the face of the earth... %%hh:mm:ss%%"
221     // > Result:  "All Quassel clients vanished from the face of the earth... 23:20:34"
222     // Complex:  "Away since %%hh:mm%% on %%dd.MM%% - %%%% not here %%%%"
223     // > Result:  "Away since 23:20 on 21.05 - %% not here %%"
224     //
225     // Match groups of double % signs - Some text %%inside here%%, and even %%%%:
226     //   %%(.*)%%
227     //   (...)    marks a capturing group
228     //   .*       matches zero or more characters, not including newlines
229     // Note that '\' must be escaped as '\\'
230     // Helpful interactive website for debugging and explaining:  https://regex101.com/
231     QRegExp regExpMatchTime("%%(.*)%%");
232
233     // Preserve the smallest groups possible to allow for multiple %%blocks%%
234     regExpMatchTime.setMinimal(true);
235
236     // NOTE: Move regExpMatchTime to a static regular expression if used anywhere that performance
237     // matters.
238
239     // Don't allow a runaway regular expression to loop for too long.  This might not happen.. but
240     // when dealing with user input, better to be safe..?
241     int numIterations = 0;
242
243     // Find each group of %%text here%% starting from the beginning
244     int index = regExpMatchTime.indexIn(formattedStr);
245     int matchLength;
246     QString matchedFormat;
247     while (index >= 0 && numIterations < 512) {
248         // Get the total length of the matched expression
249         matchLength = regExpMatchTime.cap(0).length();
250         // Get the format string, e.g. "this text here" from "%%this text here%%"
251         matchedFormat = regExpMatchTime.cap(1);
252         // Check that there's actual characters inside.  A quadruple % (%%%%) represents two %%
253         // signs.
254         if (matchedFormat.length() > 0) {
255             // Format the string according to the current date and time.  Invalid time format
256             // strings are ignored.
257             formattedStr.replace(index, matchLength,
258                                  QDateTime::currentDateTime().toString(matchedFormat));
259             // Subtract the length of the removed % signs
260             // E.g. "%%h:mm ap%%" turns into "h:mm ap", removing four % signs, thus -4.  This is
261             // used below to determine how far to advance when looking for the next formatting code.
262             matchLength -= 4;
263         } else if (matchLength == 4) {
264             // Remove two of the four percent signs, so '%%%%' escapes to '%%'
265             formattedStr.remove(index, 2);
266             // Subtract the length of the removed % signs, this time removing two % signs, thus -2.
267             matchLength -= 2;
268         } else {
269             // If neither of these match, something went wrong.  Don't modify it to be safe.
270             qDebug() << "Unexpected time format when parsing string, no matchedFormat, matchLength "
271                         "should be 4, actually is" << matchLength;
272         }
273
274         // Find the next group of %%text here%% starting from where the last group ended
275         index = regExpMatchTime.indexIn(formattedStr, index + matchLength);
276         numIterations++;
277     }
278
279     return formattedStr;
280 }