a8a38875da75717a41329d8f6cb3bb71c626f456
[quassel.git] / src / common / util.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19  ***************************************************************************/
20
21 #include "util.h"
22
23 #include <QCoreApplication>
24 #include <QDebug>
25 #include <QFile>
26 #include <QLibraryInfo>
27 #include <QTextCodec>
28 #include <QTranslator>
29
30 #include "quassel.h"
31
32 class QMetaMethod;
33
34 QString nickFromMask(QString mask) {
35   return mask.section('!', 0, 0);
36 }
37
38 QString userFromMask(QString mask) {
39   QString userhost = mask.section('!', 1);
40   if(userhost.isEmpty()) return QString();
41   return userhost.section('@', 0, 0);
42 }
43
44 QString hostFromMask(QString mask) {
45   QString userhost = mask.section('!', 1);
46   if(userhost.isEmpty()) return QString();
47   return userhost.section('@', 1);
48 }
49
50 bool isChannelName(QString str) {
51   return QString("#&!+").contains(str[0]);
52 }
53
54 QString stripFormatCodes(QString str) {
55   str.remove(QRegExp("\x03(\\d\\d?(,\\d\\d?)?)?"));
56   str.remove('\x02');
57   str.remove('\x0f');
58   str.remove('\x12');
59   str.remove('\x16');
60   str.remove('\x1d');
61   str.remove('\x1f');
62   return str;
63 }
64
65 QString decodeString(const QByteArray &input, QTextCodec *codec) {
66   // First, we check if it's utf8. It is very improbable to encounter a string that looks like
67   // valid utf8, but in fact is not. This means that if the input string passes as valid utf8, it
68   // is safe to assume that it is.
69   // Q_ASSERT(sizeof(const char) == sizeof(quint8));  // In God we trust...
70   bool isUtf8 = true;
71   int cnt = 0;
72   for(int i = 0; i < input.size(); i++) {
73     if(cnt) {
74       // We check a part of a multibyte char. These need to be of the form 10yyyyyy.
75       if((input[i] & 0xc0) != 0x80) { isUtf8 = false; break; }
76       cnt--;
77       continue;
78     }
79     if((input[i] & 0x80) == 0x00) continue; // 7 bit is always ok
80     if((input[i] & 0xf8) == 0xf0) { cnt = 3; continue; }  // 4-byte char 11110xxx 10yyyyyy 10zzzzzz 10vvvvvv
81     if((input[i] & 0xf0) == 0xe0) { cnt = 2; continue; }  // 3-byte char 1110xxxx 10yyyyyy 10zzzzzz
82     if((input[i] & 0xe0) == 0xc0) { cnt = 1; continue; }  // 2-byte char 110xxxxx 10yyyyyy
83     isUtf8 = false; break;  // 8 bit char, but not utf8!
84   }
85   if(isUtf8 && cnt == 0) {
86     QString s = QString::fromUtf8(input);
87     //qDebug() << "Detected utf8:" << s;
88     return s;
89   }
90   //QTextCodec *codec = QTextCodec::codecForName(encoding.toAscii());
91   if(!codec) return QString::fromAscii(input);
92   return codec->toUnicode(input);
93 }
94
95 /* not needed anymore
96 void writeDataToDevice(QIODevice *dev, const QVariant &item) {
97   QByteArray block;
98   QDataStream out(&block, QIODevice::WriteOnly);
99   out.setVersion(QDataStream::Qt_4_2);
100   out << (quint32)0 << item;
101   out.device()->seek(0);
102   out << (quint32)(block.size() - sizeof(quint32));
103   dev->write(block);
104 }
105
106 bool readDataFromDevice(QIODevice *dev, quint32 &blockSize, QVariant &item) {
107   QDataStream in(dev);
108   in.setVersion(QDataStream::Qt_4_2);
109
110   if(blockSize == 0) {
111     if(dev->bytesAvailable() < (int)sizeof(quint32)) return false;
112     in >> blockSize;
113   }
114   if(dev->bytesAvailable() < blockSize) return false;
115   in >> item;
116   return true;
117 }
118 */
119
120 uint editingDistance(const QString &s1, const QString &s2) {
121   uint n = s1.size()+1;
122   uint m = s2.size()+1;
123   QVector< QVector< uint > >matrix(n,QVector<uint>(m,0));
124
125   for(uint i = 0; i < n; i++)
126     matrix[i][0] = i;
127
128   for(uint i = 0; i < m; i++)
129     matrix[0][i] = i;
130
131   uint min;
132   for(uint i = 1; i < n; i++) {
133     for(uint j = 1; j < m; j++) {
134       uint deleteChar = matrix[i-1][j] + 1;
135       uint insertChar = matrix[i][j-1] + 1;
136
137       if(deleteChar < insertChar)
138         min = deleteChar;
139       else
140         min = insertChar;
141
142       if(s1[i-1] == s2[j-1]) {
143         uint inheritChar = matrix[i-1][j-1];
144         if(inheritChar < min)
145           min = inheritChar;
146       }
147
148       matrix[i][j] = min;
149     }
150   }
151   return matrix[n-1][m-1];
152 }
153
154 QDir quasselDir() {
155   QString quasselDir;
156   if(Quassel::isOptionSet("datadir")) {
157     quasselDir = Quassel::optionValue("datadir");
158   } else {
159     // FIXME use QDesktopServices
160 #ifdef Q_OS_WIN32
161     quasselDir = qgetenv("APPDATA") + "/quassel/";
162 #elif defined Q_WS_MAC
163     quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
164 #else
165     quasselDir = QDir::homePath() + "/.quassel/";
166 #endif
167   }
168
169   QDir qDir(quasselDir);
170   if(!qDir.exists(quasselDir)) {
171     if(!qDir.mkpath(quasselDir)) {
172       qCritical() << "Unable to create Quassel data directory:" << qPrintable(qDir.absolutePath());
173     }
174   }
175
176   return qDir;
177 }
178
179 QStringList dataDirPaths() {
180   QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);
181
182   // Provide a fallback
183 # ifdef Q_OS_UNIX
184   if(dataDirNames.isEmpty()) dataDirNames.append("/usr/share");
185   // on UNIX, we always check our install prefix
186   QString appDir = QCoreApplication::applicationDirPath();
187   int binpos = appDir.lastIndexOf("/bin");
188   if(binpos >= 0) {
189     appDir.replace(binpos, 4, "/share");
190     if(!dataDirNames.contains(appDir)) dataDirNames.append(appDir);
191   }
192 # endif
193
194   return dataDirNames;
195 }
196
197 QString findDataFilePath(const QString &fileName) {
198   QStringList dataDirs = dataDirPaths();
199   foreach(QString dataDir, dataDirs) {
200     QString path = dataDir + "/apps/quassel/" + fileName;
201     if(QFile::exists(path))
202       return path;
203   }
204   return QString();
205 }
206
207 void loadTranslation(const QLocale &locale) {
208   QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
209   QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
210
211   if(!qtTranslator) {
212     qtTranslator = new QTranslator(qApp);
213     qtTranslator->setObjectName("QtTr");
214     qApp->installTranslator(qtTranslator);
215   }
216   if(!quasselTranslator) {
217     quasselTranslator = new QTranslator(qApp);
218     quasselTranslator->setObjectName("QuasselTr");
219     qApp->installTranslator(quasselTranslator);
220   }
221
222   QLocale::setDefault(locale);
223
224   if(locale.language() == QLocale::C)
225     return;
226
227   bool success = qtTranslator->load(QString(":i18n/qt_%1").arg(locale.name()));
228   if(!success)
229     qtTranslator->load(QString("%2/qt_%1").arg(locale.name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)));
230   quasselTranslator->load(QString(":i18n/quassel_%1").arg(locale.name()));
231 }
232
233 QString secondsToString(int timeInSeconds) {
234     QList< QPair<int, QString> > timeUnit;
235     timeUnit.append(qMakePair(365*24*60*60, QCoreApplication::translate("Quassel::secondsToString()", "year")));
236     timeUnit.append(qMakePair(24*60*60, QCoreApplication::translate("Quassel::secondsToString()", "day")));
237     timeUnit.append(qMakePair(60*60, QCoreApplication::translate("Quassel::secondsToString()", "h")));
238     timeUnit.append(qMakePair(60, QCoreApplication::translate("Quassel::secondsToString()", "min")));
239     timeUnit.append(qMakePair(1, QCoreApplication::translate("Quassel::secondsToString()", "sec")));
240
241     QStringList returnString;
242     for(int i=0; i < timeUnit.size(); i++) {
243       int n = timeInSeconds / timeUnit[i].first;
244       if(n > 0) {
245         returnString += QString("%1 %2").arg(QString::number(n), timeUnit[i].second);
246       }
247       timeInSeconds = timeInSeconds % timeUnit[i].first;
248     }
249     return returnString.join(", ");
250 }