Debian Codegraph @

qt5/platforminputcontext/fcitx4watcher.cpp

raw
1 /*
2 * SPDX-FileCopyrightText: 2011~2023 CSSlayer <[email protected]>
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 *
6 */
7
8 #include "fcitx4watcher.h"
9 #include <QDBusConnection>
10 #include <QDBusConnectionInterface>
11 #include <QDBusServiceWatcher>
12 #include <QDebug>
13 #include <QDir>
14 #include <QFileSystemWatcher>
15 #include <errno.h>
16 #include <signal.h>
17 #include <unistd.h>
18
19 // utils function in fcitx-utils and fcitx-config
20 bool _pid_exists(pid_t pid) {
21 if (pid <= 0)
22 return 0;
23 return !(kill(pid, 0) && (errno == ESRCH));
24 }
25
26 int displayNumber() {
27 QByteArray display(qgetenv("DISPLAY"));
28 QByteArray displayNumber("0");
29 int pos = display.indexOf(':');
30
31 if (pos >= 0) {
32 ++pos;
33 int pos2 = display.indexOf('.', pos);
34 if (pos2 > 0) {
35 displayNumber = display.mid(pos, pos2 - pos);
36 } else {
37 displayNumber = display.mid(pos);
38 }
39 }
40
41 bool ok;
42 int d = displayNumber.toInt(&ok);
43 if (ok) {
44 return d;
45 }
46 return 0;
47 }
48
49 QString socketFile() {
50 QString filename =
51 QStringLiteral("%1-%2")
52 .arg(QString::fromLatin1(QDBusConnection::localMachineId()))
53 .arg(displayNumber());
54
55 QString home = QString::fromLocal8Bit(qgetenv("XDG_CONFIG_HOME"));
56 if (home.isEmpty()) {
57 home = QDir::homePath().append(QLatin1String("/.config"));
58 }
59 return QStringLiteral("%1/fcitx/dbus/%2").arg(home).arg(filename);
60 }
61
62 namespace fcitx {
63
64 QString newUniqueConnectionName() {
65 static int idx = 0;
66 const auto newIdx = idx++;
67 return QStringLiteral("_fcitx4_%1").arg(newIdx);
68 }
69
70 Fcitx4Watcher::Fcitx4Watcher(QDBusConnection sessionBus, QObject *parent)
71 : QObject(parent), connection_(nullptr), sessionBus_(sessionBus),
72 socketFile_(socketFile()),
73 serviceName_(QStringLiteral("org.fcitx.Fcitx-%1").arg(displayNumber())),
74 availability_(false), uniqueConnectionName_(newUniqueConnectionName()) {}
75
76 Fcitx4Watcher::~Fcitx4Watcher() {
77 cleanUpConnection();
78 unwatchSocketFile();
79 }
80
81 bool Fcitx4Watcher::availability() const { return availability_; }
82
83 QDBusConnection Fcitx4Watcher::connection() const {
84 if (connection_) {
85 return *connection_;
86 }
87 return sessionBus_;
88 }
89
90 QString Fcitx4Watcher::service() const {
91 if (connection_) {
92 return serviceName_;
93 }
94 if (mainPresent_) {
95 return serviceName_;
96 }
97 return QString();
98 }
99
100 void Fcitx4Watcher::setAvailability(bool availability) {
101 if (availability_ != availability) {
102 availability_ = availability;
103 Q_EMIT availabilityChanged(availability_);
104 }
105 }
106
107 void Fcitx4Watcher::watch() {
108 if (watched_) {
109 return;
110 }
111
112 serviceWatcher_ = new QDBusServiceWatcher(this);
113 connect(serviceWatcher_, &QDBusServiceWatcher::serviceOwnerChanged, this,
114 &Fcitx4Watcher::imChanged);
115 serviceWatcher_->setConnection(sessionBus_);
116 serviceWatcher_->addWatchedService(serviceName_);
117
118 if (sessionBus_.interface()->isServiceRegistered(serviceName_)) {
119 mainPresent_ = true;
120 }
121
122 watchSocketFile();
123 createConnection();
124 updateAvailability();
125 watched_ = true;
126 }
127
128 void Fcitx4Watcher::unwatch() {
129 if (!watched_) {
130 return;
131 }
132
133 delete serviceWatcher_;
134 serviceWatcher_ = nullptr;
135 unwatchSocketFile();
136 cleanUpConnection();
137 mainPresent_ = false;
138 watched_ = false;
139 updateAvailability();
140 }
141
142 QString Fcitx4Watcher::address() {
143 QString addr;
144 QByteArray addrVar = qgetenv("FCITX_DBUS_ADDRESS");
145 if (!addrVar.isNull())
146 return QString::fromLocal8Bit(addrVar);
147
148 QFile file(socketFile_);
149 if (!file.open(QIODevice::ReadOnly))
150 return QString();
151
152 const int BUFSIZE = 1024;
153
154 char buffer[BUFSIZE];
155 size_t sz = file.read(buffer, BUFSIZE);
156 file.close();
157 if (sz == 0)
158 return QString();
159 char *p = buffer;
160 while (*p)
161 p++;
162 size_t addrlen = p - buffer;
163 if (sz != addrlen + 2 * sizeof(pid_t) + 1)
164 return QString();
165
166 /* skip '\0' */
167 p++;
168 pid_t *ppid = (pid_t *)p;
169 pid_t daemonpid = ppid[0];
170 pid_t fcitxpid = ppid[1];
171
172 if (!_pid_exists(daemonpid) || !_pid_exists(fcitxpid))
173 return QString();
174
175 addr = QLatin1String(buffer);
176
177 return addr;
178 }
179
180 void Fcitx4Watcher::cleanUpConnection() {
181 QDBusConnection::disconnectFromBus(uniqueConnectionName_);
182 delete connection_;
183 connection_ = nullptr;
184 }
185
186 void Fcitx4Watcher::socketFileChanged() {
187 cleanUpConnection();
188 createConnection();
189 }
190
191 void Fcitx4Watcher::createConnection() {
192 QString addr = address();
193 if (!addr.isNull()) {
194 QDBusConnection connection(
195 QDBusConnection::connectToBus(addr, uniqueConnectionName_));
196 if (connection.isConnected()) {
197 connection_ = new QDBusConnection(connection);
198 } else {
199 QDBusConnection::disconnectFromBus(uniqueConnectionName_);
200 }
201 }
202
203 if (connection_) {
204 connection_->connect("org.freedesktop.DBus.Local",
205 "/org/freedesktop/DBus/Local",
206 "org.freedesktop.DBus.Local", "Disconnected", this,
207 SLOT(dbusDisconnected()));
208 unwatchSocketFile();
209 }
210 updateAvailability();
211 }
212
213 void Fcitx4Watcher::dbusDisconnected() {
214 cleanUpConnection();
215 watchSocketFile();
216 // Try recreation immediately to avoid race.
217 createConnection();
218 }
219
220 void Fcitx4Watcher::watchSocketFile() {
221 if (socketFile_.isEmpty()) {
222 return;
223 }
224 QFileInfo info(socketFile_);
225 QDir dir(info.path());
226 if (!dir.exists()) {
227 QDir rt(QDir::root());
228 rt.mkpath(info.path());
229 }
230 fsWatcher_ = new QFileSystemWatcher(this);
231 fsWatcher_->addPath(info.path());
232 if (info.exists()) {
233 fsWatcher_->addPath(info.filePath());
234 }
235
236 connect(fsWatcher_, &QFileSystemWatcher::fileChanged, this,
237 &Fcitx4Watcher::socketFileChanged);
238 connect(fsWatcher_, &QFileSystemWatcher::directoryChanged, this,
239 &Fcitx4Watcher::socketFileChanged);
240 }
241
242 void Fcitx4Watcher::unwatchSocketFile() {
243 if (fsWatcher_) {
244 fsWatcher_->disconnect(this);
245 fsWatcher_->deleteLater();
246 fsWatcher_ = nullptr;
247 }
248 }
249
250 void Fcitx4Watcher::imChanged(const QString &service, const QString &,
251 const QString &newOwner) {
252 if (service == serviceName_) {
253 if (!newOwner.isEmpty()) {
254 mainPresent_ = true;
255 } else {
256 mainPresent_ = false;
257 }
258 }
259
260 updateAvailability();
261 }
262
263 void Fcitx4Watcher::updateAvailability() {
264 setAvailability(mainPresent_ || connection_);
265 }
266
267 } // namespace fcitx