File: fcitx4watcher.cpp

package info (click to toggle)
fcitx5-qt 5.1.10-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,340 kB
  • sloc: cpp: 11,697; xml: 243; ansic: 46; makefile: 14; sh: 9
file content (267 lines) | stat: -rw-r--r-- 6,736 bytes parent folder | download | duplicates (3)
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/*
 * SPDX-FileCopyrightText: 2011~2023 CSSlayer <wengxt@gmail.com>
 *
 * SPDX-License-Identifier: BSD-3-Clause
 *
 */

#include "fcitx4watcher.h"
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusServiceWatcher>
#include <QDebug>
#include <QDir>
#include <QFileSystemWatcher>
#include <errno.h>
#include <signal.h>
#include <unistd.h>

// utils function in fcitx-utils and fcitx-config
bool _pid_exists(pid_t pid) {
    if (pid <= 0)
        return 0;
    return !(kill(pid, 0) && (errno == ESRCH));
}

int displayNumber() {
    QByteArray display(qgetenv("DISPLAY"));
    QByteArray displayNumber("0");
    int pos = display.indexOf(':');

    if (pos >= 0) {
        ++pos;
        int pos2 = display.indexOf('.', pos);
        if (pos2 > 0) {
            displayNumber = display.mid(pos, pos2 - pos);
        } else {
            displayNumber = display.mid(pos);
        }
    }

    bool ok;
    int d = displayNumber.toInt(&ok);
    if (ok) {
        return d;
    }
    return 0;
}

QString socketFile() {
    QString filename =
        QStringLiteral("%1-%2")
            .arg(QString::fromLatin1(QDBusConnection::localMachineId()))
            .arg(displayNumber());

    QString home = QString::fromLocal8Bit(qgetenv("XDG_CONFIG_HOME"));
    if (home.isEmpty()) {
        home = QDir::homePath().append(QLatin1String("/.config"));
    }
    return QStringLiteral("%1/fcitx/dbus/%2").arg(home).arg(filename);
}

namespace fcitx {

QString newUniqueConnectionName() {
    static int idx = 0;
    const auto newIdx = idx++;
    return QStringLiteral("_fcitx4_%1").arg(newIdx);
}

Fcitx4Watcher::Fcitx4Watcher(QDBusConnection sessionBus, QObject *parent)
    : QObject(parent), connection_(nullptr), sessionBus_(sessionBus),
      socketFile_(socketFile()),
      serviceName_(QStringLiteral("org.fcitx.Fcitx-%1").arg(displayNumber())),
      availability_(false), uniqueConnectionName_(newUniqueConnectionName()) {}

Fcitx4Watcher::~Fcitx4Watcher() {
    cleanUpConnection();
    unwatchSocketFile();
}

bool Fcitx4Watcher::availability() const { return availability_; }

QDBusConnection Fcitx4Watcher::connection() const {
    if (connection_) {
        return *connection_;
    }
    return sessionBus_;
}

QString Fcitx4Watcher::service() const {
    if (connection_) {
        return serviceName_;
    }
    if (mainPresent_) {
        return serviceName_;
    }
    return QString();
}

void Fcitx4Watcher::setAvailability(bool availability) {
    if (availability_ != availability) {
        availability_ = availability;
        Q_EMIT availabilityChanged(availability_);
    }
}

void Fcitx4Watcher::watch() {
    if (watched_) {
        return;
    }

    serviceWatcher_ = new QDBusServiceWatcher(this);
    connect(serviceWatcher_, &QDBusServiceWatcher::serviceOwnerChanged, this,
            &Fcitx4Watcher::imChanged);
    serviceWatcher_->setConnection(sessionBus_);
    serviceWatcher_->addWatchedService(serviceName_);

    if (sessionBus_.interface()->isServiceRegistered(serviceName_)) {
        mainPresent_ = true;
    }

    watchSocketFile();
    createConnection();
    updateAvailability();
    watched_ = true;
}

void Fcitx4Watcher::unwatch() {
    if (!watched_) {
        return;
    }

    delete serviceWatcher_;
    serviceWatcher_ = nullptr;
    unwatchSocketFile();
    cleanUpConnection();
    mainPresent_ = false;
    watched_ = false;
    updateAvailability();
}

QString Fcitx4Watcher::address() {
    QString addr;
    QByteArray addrVar = qgetenv("FCITX_DBUS_ADDRESS");
    if (!addrVar.isNull())
        return QString::fromLocal8Bit(addrVar);

    QFile file(socketFile_);
    if (!file.open(QIODevice::ReadOnly))
        return QString();

    const int BUFSIZE = 1024;

    char buffer[BUFSIZE];
    size_t sz = file.read(buffer, BUFSIZE);
    file.close();
    if (sz == 0)
        return QString();
    char *p = buffer;
    while (*p)
        p++;
    size_t addrlen = p - buffer;
    if (sz != addrlen + 2 * sizeof(pid_t) + 1)
        return QString();

    /* skip '\0' */
    p++;
    pid_t *ppid = (pid_t *)p;
    pid_t daemonpid = ppid[0];
    pid_t fcitxpid = ppid[1];

    if (!_pid_exists(daemonpid) || !_pid_exists(fcitxpid))
        return QString();

    addr = QLatin1String(buffer);

    return addr;
}

void Fcitx4Watcher::cleanUpConnection() {
    QDBusConnection::disconnectFromBus(uniqueConnectionName_);
    delete connection_;
    connection_ = nullptr;
}

void Fcitx4Watcher::socketFileChanged() {
    cleanUpConnection();
    createConnection();
}

void Fcitx4Watcher::createConnection() {
    QString addr = address();
    if (!addr.isNull()) {
        QDBusConnection connection(
            QDBusConnection::connectToBus(addr, uniqueConnectionName_));
        if (connection.isConnected()) {
            connection_ = new QDBusConnection(connection);
        } else {
            QDBusConnection::disconnectFromBus(uniqueConnectionName_);
        }
    }

    if (connection_) {
        connection_->connect("org.freedesktop.DBus.Local",
                             "/org/freedesktop/DBus/Local",
                             "org.freedesktop.DBus.Local", "Disconnected", this,
                             SLOT(dbusDisconnected()));
        unwatchSocketFile();
    }
    updateAvailability();
}

void Fcitx4Watcher::dbusDisconnected() {
    cleanUpConnection();
    watchSocketFile();
    // Try recreation immediately to avoid race.
    createConnection();
}

void Fcitx4Watcher::watchSocketFile() {
    if (socketFile_.isEmpty()) {
        return;
    }
    QFileInfo info(socketFile_);
    QDir dir(info.path());
    if (!dir.exists()) {
        QDir rt(QDir::root());
        rt.mkpath(info.path());
    }
    fsWatcher_ = new QFileSystemWatcher(this);
    fsWatcher_->addPath(info.path());
    if (info.exists()) {
        fsWatcher_->addPath(info.filePath());
    }

    connect(fsWatcher_, &QFileSystemWatcher::fileChanged, this,
            &Fcitx4Watcher::socketFileChanged);
    connect(fsWatcher_, &QFileSystemWatcher::directoryChanged, this,
            &Fcitx4Watcher::socketFileChanged);
}

void Fcitx4Watcher::unwatchSocketFile() {
    if (fsWatcher_) {
        fsWatcher_->disconnect(this);
        fsWatcher_->deleteLater();
        fsWatcher_ = nullptr;
    }
}

void Fcitx4Watcher::imChanged(const QString &service, const QString &,
                              const QString &newOwner) {
    if (service == serviceName_) {
        if (!newOwner.isEmpty()) {
            mainPresent_ = true;
        } else {
            mainPresent_ = false;
        }
    }

    updateAvailability();
}

void Fcitx4Watcher::updateAvailability() {
    setAvailability(mainPresent_ || connection_);
}

} // namespace fcitx