File: main.cpp

package info (click to toggle)
ukui-session-manager 4.0.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,176 kB
  • sloc: cpp: 9,043; xml: 102; python: 24; sh: 15; makefile: 15
file content (465 lines) | stat: -rw-r--r-- 14,767 bytes parent folder | download
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/* BEGIN_COMMON_COPYRIGHT_HEADER
 *
 * Copyright: 2023, KylinSoft Co., Ltd.
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */
#include "sessionapplication.h"
#include "ukuisessiondebug.h"

#include <signal.h>
#include <QDBusMetaType>
#include <QStandardPaths>
#include <QDBusInterface>
#include <QFile>
#include <QDir>
#include <QTextStream>
#include <QDateTime>
#include <QDebug>
#include <QTimer>
#include <QMediaPlayer>
#include <QSoundEffect>
#include <QFileInfo>
#include <QScreen>
#include <QProcess>
#include <QGSettings/QGSettings>
#include <QCommandLineParser>
#include <QTranslator>
#include <ukui-log4qt.h>

#ifdef KDKINFO_FOUND
#include <kysdk/kysdk-system/libkysysinfo.h>
#endif

extern "C" {
#include <X11/Xatom.h>
#include <X11/Xlib.h>
}

#define XSETTINGS_SCHEMA    "org.ukui.SettingsDaemon.plugins.xsettings"
#define MOUSE_SCHEMA        "org.ukui.peripherals-mouse"
#define SCALING_KEY         "scaling-factor"
#define CURSOR_SIZE         "cursor-size"
#define CURSOR_THEME        "cursor-theme"

void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QString logPath = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)
        + "/ukui-session/ukui-session-xsmp.log";
    //判断log文件是否存在
    if (!QFile::exists(logPath)) {
        QString logDir = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + "/ukui-session";
        //不存在时,创建ukui-session文件夹
        QDir dir(logDir);
        if (!dir.exists(logDir)) {
            if (!dir.mkdir(logDir)) {
                return;
            }
        }
        //创建log文件
        QFile file(logPath);
        if (!file.open(QIODevice::WriteOnly)) {
            return;
        }
        file.close();
    }
    if (!QFile::exists(logPath)) {
        return;
    }

    QByteArray localMsg = msg.toLocal8Bit();
    QDateTime  dateTime = QDateTime::currentDateTime();
    QByteArray time = QString("[%1] ").arg(dateTime.toString("MM-dd hh:mm:ss.zzz")).toLocal8Bit();
    QString    logMsg;
    switch (type) {
    case QtDebugMsg:
        logMsg = QString("%1 Debug: %2 (%3:%4, %5)\n")
                     .arg(time.constData())
                     .arg(localMsg.constData())
                     .arg(context.file)
                     .arg(context.line)
                     .arg(context.function);
        break;
    case QtInfoMsg:
        logMsg = QString("%1 Info: %2 (%3:%4, %5)\n")
                     .arg(time.constData())
                     .arg(localMsg.constData())
                     .arg(context.file)
                     .arg(context.line)
                     .arg(context.function);
        break;
    case QtWarningMsg:
        logMsg = QString("%1 Warning: %2 (%3:%4, %5)\n")
                     .arg(time.constData())
                     .arg(localMsg.constData())
                     .arg(context.file)
                     .arg(context.line)
                     .arg(context.function);
        break;
    case QtCriticalMsg:
        logMsg = QString("%1 Critical: %2 (%3:%4, %5)\n")
                     .arg(time.constData())
                     .arg(localMsg.constData())
                     .arg(context.file)
                     .arg(context.line)
                     .arg(context.function);
        break;
    case QtFatalMsg:
        logMsg = QString("%1 Fatal: %2 (%3:%4, %5)\n")
                     .arg(time.constData())
                     .arg(localMsg.constData())
                     .arg(context.file)
                     .arg(context.line)
                     .arg(context.function);
        break;
    }

    //clear file content when it is too large
    QFile file(logPath);
    qint64 fileSize = file.size();
    if (fileSize >= 1024 * 1024 * 10) {
        file.open(QFile::WriteOnly | QFile::Truncate);
        file.flush();
        file.close();
    }

    QFile logFile(logPath);
    logFile.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream ts(&logFile);
    ts << logMsg << endl;
    logFile.flush();
    logFile.close();
}

/* 设置DPI环境变量 */
void setXresources(double scale)
{
    Display    *dpy;
    QGSettings *mouse_settings = new QGSettings(MOUSE_SCHEMA);
    QString str = QString("Xft.dpi:\t%1\nXcursor.size:\t%2\nXcursor.theme:\t%3\n")
                         .arg(scale * 96)
                         .arg(mouse_settings->get(CURSOR_SIZE).toInt() * scale)
                         .arg(mouse_settings->get(CURSOR_THEME).toString());

    dpy = XOpenDisplay(NULL);
    XChangeProperty(dpy, RootWindow(dpy, 0), XA_RESOURCE_MANAGER, XA_STRING, 8,
                    PropModeReplace, (unsigned char *) str.toLatin1().data(), str.length());
    XCloseDisplay(dpy);

    qDebug() << "setXresources:" << str;

    delete mouse_settings;
}

/* 过滤低分辨率高缩放比情况 */
void screenScaleJudgement(QGSettings *settings)
{
    qreal        scaling = qApp->devicePixelRatio();
    double       scale;
    scale = settings->get(SCALING_KEY).toDouble();
    if (scale > 1.25) {
        bool state  = false;
        bool mScale = false;

        for (QScreen *screen : QGuiApplication::screens()) {
            int width  = screen->geometry().width() * scaling;
            int height = screen->geometry().height() * scaling;

            if (width < 1920 && height < 1080) {
                state = true;
            }
            else if (width == 1920 && height == 1080 && scale > 1.5) {
                state = true;
            }
            /*
            else if (width > 2560 && height > 1440) {
                mScale = true;
            }
            */
        }

//        if (state && !mScale) {
        if (state) {
            settings->set(SCALING_KEY, 1.0);
            scale = 1.0;
        }
    }
    setXresources(scale);
}

/* 判断文件是否存在 */
bool isFileExist(QString XresourcesFile)
{
    QFileInfo fileInfo(XresourcesFile);
    if (fileInfo.isFile()) {
        qDebug() << "File exists";
        return true;
    }

    qDebug() << "File does not exis";

    return false;
}

/* 编写判断标志文件,更改 鼠标/DPI 配置大小*/
void writeXresourcesFile(QString XresourcesFile, QGSettings *settings, double scaling)
{
    QFile file(XresourcesFile);
    QString content = QString("Xft.dpi:%1\nXcursor.size:%2").arg(96.0 * scaling).arg(24.0 * scaling);
    QByteArray str = content.toLatin1().data();

    file.open(QIODevice::ReadWrite | QIODevice::Text);
    file.write(str);
    file.close();

    QGSettings *Font = new QGSettings("org.ukui.font-rendering");

    Font->set("dpi", 96.0);
    settings->set(SCALING_KEY, scaling);

    qDebug() << " writeXresourcesFile: content = " << content
             << " scalings = " << settings->get(SCALING_KEY).toDouble();
    delete Font;
}

/* 判断是否为首次登陆 */
bool isTheFirstLogin(QGSettings *settings)
{
    QString homePath       = getenv("HOME");
    QString XresourcesFile = homePath+"/.config/xresources";
    QString Xresources     = homePath+"/.Xresources";
    qreal   scaling        = qApp->devicePixelRatio();
    bool    zoom1 = false, zoom2 = false, zoom3 = false;
    double  mScaling;
    bool xres, Xres;

    Xres = isFileExist(Xresources);
    xres = isFileExist(XresourcesFile); //判断标志文件是否存在

    if (xres && !Xres) {
        return false;
    } else if (xres && Xres) {
        QFile::remove(Xresources);
        return false;
    } else if (Xres && !xres) {
        QFile::rename(Xresources, XresourcesFile);
        return false;
    }

    for (QScreen *screen : QGuiApplication::screens()) {
        int width  = screen->geometry().width() * scaling;
        int height = screen->geometry().height() * scaling;

        if (width <= 1920 && height <= 1080) {
            zoom1 = true;
        } else if (width > 1920 && height > 1080 && width <= 2560 && height <=1500) {
            zoom2 = true;
        } else if (width > 2560 && height > 1440) {
            zoom3 = true;
        }
    }

    if (zoom1) {
        mScaling = 1.0;
    } else if (!zoom1 && zoom2) {
        mScaling = 1.5; //考虑新版缩放,设置默认150%暂时停止设置;
    } else if (!zoom1 && !zoom2 && zoom3) {
        mScaling = 2.0;
    }

    writeXresourcesFile(XresourcesFile, settings, mScaling);

    setXresources(mScaling);

    return true;
}

/* 配置新装系统、新建用户第一次登陆时,4K缩放功能*/
void setHightResolutionScreenZoom(bool platForm)
{
    QGSettings *settings;
    double      scale;
    int         ScreenNum = QApplication::screens().length();
    if (!QGSettings::isSchemaInstalled(XSETTINGS_SCHEMA) || !QGSettings::isSchemaInstalled("org.ukui.font-rendering") ||
            !QGSettings::isSchemaInstalled(MOUSE_SCHEMA)) {
        qDebug() << "Error: ukui-settings-daemon's Schema  is not installed, will not setting dpi!";
        delete settings;
        return;
    }
    settings = new QGSettings(XSETTINGS_SCHEMA);

    scale = settings->get(SCALING_KEY).toDouble();

    if (platForm) {
        setXresources(scale);
        goto end;
    }

    if (isTheFirstLogin(settings)) {
        qDebug() << "Set the default zoom value when logging in for the first time.";
        goto end;
    }
    /* 过滤单双屏下小分辨率大缩放值 */


    if (ScreenNum > 1) {
        setXresources(scale);
        goto end;
    }

    screenScaleJudgement(settings);

end:
    delete settings;
}

bool requireDbusSession()
{
    QString env_dbus = qgetenv("DBUS_SESSION_BUS_ADDRESS");
    if (!env_dbus.isEmpty()) return true;
    qDebug() << "Fatal DBus Error";
    QProcess *a  = new QProcess;
    a->setProcessChannelMode(QProcess::ForwardedChannels);
    a->start("dbus-launch", QStringList() << "--exit-with-session" << "ukui-session");
    a->waitForFinished(-1);
    if (a->exitCode()) {
        qWarning() <<  "exited with code" << a->exitCode();
    }
    delete a;
    return true;
}

void signalHandler(int sig)
{
    QDBusInterface face("org.freedesktop.login1",
                        "/org/freedesktop/login1/user/self",
                        "org.freedesktop.login1.User",
                        QDBusConnection::systemBus());

    face.call("Kill", 9);
}

void openDubug()
{
//#ifdef QT_NO_DEBUG
//    UKUI_SESSION().setFilterRules(QLatin1Literal("org.ukui.ukuisession=false"));
//#else
//    UKUI_SESSION().setFilterRules(QLatin1Literal("org.ukui.ukuisession=true"));
//#endif
    UKUI_SESSION().setFilterRules(QLatin1Literal("org.ukui.ukuisession=true"));
    qInstallMessageHandler(myMessageOutput);
    qCDebug(UKUI_SESSION) << "===================================================    UKUI session manager start.    ===================================================";
}


void launchUKUISMServer() {
    QGSettings *sSettings;
    QString wm = "ukui-kwin";
    if (!QGSettings::isSchemaInstalled("org.ukui.session.required-components") ) {
        qDebug() << "Error: ukui-session-manager's Schema  is not installed!";
    } else {
        sSettings = new QGSettings("org.ukui.session.required-components");
        wm = sSettings->get("windowmanager").toString();
    }
    delete sSettings;

    qDebug() << "start ukuismserver with windowmanager=" << wm ;
    QProcess *p = new QProcess;
    QString fullPath = "/usr/bin/" + wm;
    QFile file(fullPath);
    if(file.exists()) {
        QStringList arg;
        arg << "-w";
        arg << wm;
        p->start("ukuismserver",arg);
    } else {
        qDebug() << "Can not find file " << fullPath << ", start ukwm instead" ;
        QStringList arg;
        arg << "-w";
        arg << "ukwm";
        p->start("ukuismserver",arg);
    }
    p->closeReadChannel(QProcess::StandardOutput);
    p->closeReadChannel(QProcess::StandardError);
}

int main(int argc, char **argv)
{
    //initUkuiLog4qt("ukui-session");
    //加上这个处理会在终端一直输出信息,原因不明
    //    signal(SIGTERM, signalHandler);

    openDubug();

    requireDbusSession();

    //qputenv("QT_QPA_PLATFORM", "xcb");

    SessionApplication app(argc, argv);

    //后续需要细化区分,部分wayland环境也需要缩放设置
    QString xdg_session_type = qgetenv("XDG_SESSION_TYPE");
    if (xdg_session_type != "wayland") {
#ifdef KDKINFO_FOUND
        QString platForm = kdk_system_get_hostCloudPlatform();
#else
        QString platForm = "none";
#endif
        if (platForm == "none") {
            qDebug() << "platForm=" << platForm << ", 系统环境为实体机";
            setHightResolutionScreenZoom(false);
        } else {
            qDebug() << "platForm=" << platForm << ", 系统环境为云环境";
            setHightResolutionScreenZoom(true);
        }
    }

    app.setQuitOnLastWindowClosed(false);

    //启动ukuismserver
    launchUKUISMServer();

    // Load ts files
    const QString locale = QLocale::system().name();
    QTranslator   translator;
    qDebug() << "local: " << locale;
    qDebug() << "path: " << QStringLiteral(UKUI_TRANSLATIONS_DIR) + QStringLiteral("/ukui-session-manager");
    if (translator.load(locale, QStringLiteral(UKUI_TRANSLATIONS_DIR) + QStringLiteral("/ukui-session-manager"))) {
        app.installTranslator(&translator);
    } else {
        qDebug() << "Load translations file failed!";
    }

    QCommandLineParser parser;
    parser.setApplicationDescription(QApplication::tr("UKUI Session Manager"));

    const QString VERINFO = QStringLiteral("2.0.11-7");
    app.setApplicationVersion(VERINFO);

    parser.addHelpOption();
    parser.addVersionOption();
    parser.process(app);
    
    QString serviceId = "org.ukui.ukuismserver";
    auto watcher = new QDBusServiceWatcher(serviceId, QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForRegistration);
    QObject::connect(watcher, &QDBusServiceWatcher::serviceRegistered, [&app]() {
        qDebug() << "ukuismserver service registered, begin startup.";
        app.startup();
    });//服务注册成功会发出信号

    return app.exec();
}