summaryrefslogtreecommitdiffstats
path: root/src/namereplace.cpp
blob: cc930252a974691295d91e5cdb31984e6f36f4e5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include "namereplace.h"
#include <QString>
#include <QRegularExpression>
#include <QFile>
#include <QTextStream>
#include <QDebug>

#define SOURCE_FILE "/opt/openslx/lightdm/login-regexp"

static QList< QPair< QRegularExpression, QString > > list;

static inline int find(QChar c, int start, const QString& line)
{
	do {
		int next = line.indexOf(c, start);
		if (next == -1)
			return -1;
		if (line.at(next - 1) != '\\')
			return next;
		start = next + 1;
	} while (true);
}

void NameReplace::loadSubs()
{
	int idx = 0;
	QFile inputFile(SOURCE_FILE);
	if (!inputFile.open(QIODevice::ReadOnly))
		return;
	QTextStream in(&inputFile);
	in.setCodec("UTF-8");
	while (!in.atEnd()) {
		QString line = in.readLine();
		idx++;
		if (line.isEmpty())
			continue;
		QChar delim = line.at(0);
		int first = find(delim, 1, line);
		if (first == -1)
			continue;
		int second = find(delim, first + 1, line);
		if (second == -1)
			continue;
		QString regex = line.mid(1, first - 1).replace(QString("\\") + delim, QString(delim));
		QString replace = line.mid(first + 1, second - first - 1).replace(QString("\\") + delim, QString(delim));
		QString flags = line.mid(second + 1);
		// ...
		QRegularExpression::PatternOptions opts = QRegularExpression::NoPatternOption;
		if (flags.contains("i")) {
			opts |= QRegularExpression::CaseInsensitiveOption;
		}
		QRegularExpression re(regex, opts);
		if (!re.isValid()) {
			qWarning() << "Invalid regex:" << regex << "on line" << idx;
			continue;
		}
		list.append(QPair<QRegularExpression, QString>(re, replace));
	}
	inputFile.close();
}

void NameReplace::replace(QString& input)
{
	if (list.isEmpty())
		return;
	for (auto &brumm : list) {
		input = input.replace(brumm.first, brumm.second);
	}
}