/*
 * @Author: yushuoqi yushuoqi@kylinos.cn
 * @Date: 2024-04-11 20:24:44
 * @LastEditors: caoxiansheng caoxiansheng@kylinos.cn
 * @LastEditTime: 2025-05-01 10:25:13
 * @FilePath: /kaiming/app/dbus/KMSystemServerAdaptor.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * 
 * Copyright (c) KylinSoft  Co., Ltd. 2024. All rights reserved.
 *
 * kaiming is licensed under the GPL v2.0+.
 * 
 * See the LICENSE file for more details.
 */

#include "KMSystemServerAdaptor.h"
#include <gio/gio.h>
#include <unistd.h>
#include <iostream>
#include <malloc.h>

#include "common/KMLogger.h"
#include "common/KMError.h"
#include "common/KMFileUtils.h"
#include "common/KMFolder.h"
#include "common/KMOverlay.h"
#include "common/KMBrowserUtils.h"

#define KAIMING_DBUS_SERVICE "org.kylin.kaiming"
#define KAIMING_DBUS_PATH "/org/kylin/kaiming"
#define KAIMING_DBUS_INTERFACE "org.kylin.kaiming.interface"


KMSystemServerAdaptor::KMSystemServerAdaptor()
{
}

KMPackageManager *KMSystemServerAdaptor::getPackageManager()
{
    if (!m_pkgManager)
    {
        m_pkgManager = std::make_unique<KMPackageManager>();
    }
    return m_pkgManager.get();
}

KMInfoCommand *KMSystemServerAdaptor::getKMInfoCommand()
{
    if (!m_kmLocalInfo)
    {
        m_kmLocalInfo = std::make_unique<KMInfoCommand>();
    }
    return m_kmLocalInfo.get();
}

KMList *KMSystemServerAdaptor::getKMList()
{
    if (!m_kmList)
    {
        m_kmList = std::make_unique<KMList>();
    }
    return m_kmList.get();
}

bool KMSystemServerAdaptor::validateInputName(const gchar *name)
{
    return name && *name;
}

bool KMSystemServerAdaptor::checkOperationRunning(std::atomic<bool> &flag)
{
    bool expected = false;
    return !flag.compare_exchange_strong(expected, true);
}

gboolean KMSystemServerAdaptor::install(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name, const gchar *branch)
{
    kmlogger.info("begin call install api, m_installRunningFlag = %d", m_installRunningFlag.load());

    if (!validateInputName(name))
    {
        g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Package name must be specified");
        return TRUE;
    }

    if (checkOperationRunning(m_installRunningFlag))
    {
        kaiming_interface_complete_install(object, invocation, false);
        return TRUE;
    }

    m_installRunningFlag.store(TRUE);

    // 创建回调函数，负责发送信号
    auto callback = [this, object](const std::string &progressJson)
    {
        kmlogger.info("receive jsonData: %s", progressJson.c_str());
        g_signal_emit_by_name(object, "progresschangesignal", progressJson.c_str());
    };

    std::vector<std::string> refs;
    // 调用真实安装函数，并传递回调函数,不阻塞主线程，在子线程中异步处理
    int ret = getPackageManager()->installSoftwareCenter(name, branch, callback, refs);

    // 发送 finishsignal 信号    g_signal_emit_by_name:通过名称触发一个信号
    g_signal_emit_by_name(object, "finishsignal", name, KM_INSTALL_OPERATION, ret, KMErrorMsg::getErrorMessage(ret).c_str());
    m_installRunningFlag.store(FALSE);
    kmlogger.info("end emit install signal, m_installRunningFlag = %d", this->m_installRunningFlag.load());

    // 返回布尔值表示成功或失败
    kaiming_interface_complete_install(object, invocation, ret == KM_ERROR_NO);
    return TRUE;
}

gboolean KMSystemServerAdaptor::installOfflinePackage(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name, const gchar *branch)
{
    kmlogger.info("begin call install api, m_installRunningFlag = %d", m_installRunningFlag.load());

    if (!validateInputName(name))
    {
        g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Package name must be specified");
        return TRUE;
    }

    if (checkOperationRunning(m_installRunningFlag))
    {
        kaiming_interface_complete_install(object, invocation, false);
        return TRUE;
    }

    m_installRunningFlag.store(TRUE);

    auto callback = [this, object](const std::string &progressJson)
    {
        kmlogger.info("receive jsonData: %s", progressJson.c_str());
        g_signal_emit_by_name(object, "progresschangesignal", progressJson.c_str());
    };

    std::vector<std::string> refs;
    int ret = getPackageManager()->installSoftwareCenter(name, branch, callback, refs);
    std::string errorInfo = KMErrorMsg::getErrorMessage(ret);

    if (ret == KM_ERROR_NOT_INSTALLED)
    {
        std::stringstream ss;
        for (size_t i = 0; i < refs.size(); ++i)
        {
            if (i != 0)
                ss << ",";
            ss << refs[i];
        }
        errorInfo += ":" + ss.str();
    }

    g_signal_emit_by_name(object, "finishsignal", name, KM_INSTALL_OPERATION, ret, errorInfo.c_str());
    m_installRunningFlag.store(FALSE);
    kmlogger.info("end emit install signal, errorInfo = %s, m_installRunningFlag = %d", errorInfo.c_str(), m_installRunningFlag.load());

    kaiming_interface_complete_install_offline_package(object, invocation, ret == KM_ERROR_NO);
    return TRUE;
}

gboolean KMSystemServerAdaptor::update(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name, const gchar *branch)
{
    kmlogger.info("begin call update api, m_updateRunningFlag = %d", m_updateRunningFlag.load());

    if (checkOperationRunning(m_updateRunningFlag))
    {
        kaiming_interface_complete_install(object, invocation, false);
        return TRUE;
    }

    m_updateRunningFlag.store(TRUE);

    std::function<void(const std::string &)> updatecallback = [this, object](const std::string &progressJson)
    {
        kmlogger.info("receive jsonData: %s", progressJson.c_str());
        g_signal_emit_by_name(object, "progresschangesignal", progressJson.c_str());
    };

    int ret = getPackageManager()->updateSoftwareCenter(name, branch, updatecallback);

    g_signal_emit_by_name(object, "finishsignal", name, KM_UPDATE_OPERATION, ret, KMErrorMsg::getErrorMessage(ret).c_str());
    m_updateRunningFlag.store(FALSE);
    kmlogger.info("end emit update signal, m_updateRunningFlag = %d", m_updateRunningFlag.load());

    kaiming_interface_complete_update(object, invocation, ret == KM_ERROR_NO);
    return TRUE;
}

gboolean KMSystemServerAdaptor::uninstall(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name, const gchar *branch)
{
    kmlogger.info("begin call uninstall api, m_uninstallRunningFlag = %d", m_uninstallRunningFlag.load());

    if (checkOperationRunning(m_uninstallRunningFlag))
    {
        kaiming_interface_complete_install(object, invocation, false);
        return TRUE;
    }

    m_uninstallRunningFlag.store(TRUE);
    int ret = getPackageManager()->uninstallSoftwareCenter(name);

    g_signal_emit_by_name(object, "finishsignal", name, KM_UNINSTALL_OPERATION, ret, KMErrorMsg::getErrorMessage(ret).c_str());
    m_uninstallRunningFlag.store(FALSE);
    kmlogger.info("end emit uninstall signal, m_uninstallRunningFlag = %d", m_uninstallRunningFlag.load());

    kaiming_interface_complete_uninstall(object, invocation, ret == KM_ERROR_NO);
    return TRUE;
}

gboolean KMSystemServerAdaptor::getLocalInfomation(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name)
{
    kmlogger.info("begin call getLocalInfo api");

    int errorCode;
    string localInfoJson = getKMInfoCommand()->getLocalInfo(name, errorCode);

    kmlogger.info("before emit getLocalInfo signal");
    g_signal_emit_by_name(object, "getlocalinfosignal", name, localInfoJson.c_str(), errorCode, KMErrorMsg::getErrorMessage(errorCode).c_str());
    kmlogger.info("end emit getLocalInfo signal");

    // 创建一个 GVariant 来封装字符串
    GVariant *result = g_variant_new("(s)", localInfoJson.c_str());

    g_dbus_method_invocation_return_value(invocation, result);
    return TRUE;
}

gboolean KMSystemServerAdaptor::getAllLocalInfo(KaimingInterface *object, GDBusMethodInvocation *invocation)
{
    kmlogger.info("begin call getAllLocalInfo api");

    std::vector<std::string> localInfoList = getKMList()->getAllLocalInfo();

    // for (const auto &item : localInfoList) {
    //     kmlogger.info("%s", item.c_str());
    // }

    kmlogger.info("before emit getAllLocalInfo signal");
    int errorCode = 0;
    // 转换 std::vector<std::string> 为 GStrv（信号与返回值都用这批数据）
    gchar **strv = g_new0(gchar *, localInfoList.size() + 1);
    for (size_t i = 0; i < localInfoList.size(); ++i)
    {
        strv[i] = g_strdup(localInfoList[i].c_str());
    }
    // 发送 getalllocalinfosignal 信号
    g_signal_emit_by_name(object, "getalllocalinfosignal", "", strv, errorCode, KMErrorMsg::getErrorMessage(errorCode).c_str());
    kmlogger.info("end emit getalllocalinfosignal signal");

    // 使用 g_variant_new_strv 生成数组，并尽早释放 GStrv
    GVariant *array_variant = g_variant_new_strv((const gchar * const *)strv, (gssize)localInfoList.size());
    g_strfreev(strv);

    // 用完源数据后，主动释放局部容器内存
    std::vector<std::string>().swap(localInfoList);
    malloc_trim(0);

    // 打包为元组返回（零拷贝封装已有变体）
    GVariant *result = g_variant_new("(@as)", array_variant);

    // 返回给调用方
    g_dbus_method_invocation_return_value(invocation, result);
    return TRUE;
}

/*
     * 软件商店通过直接返回字符串中branch是否为空判断查询结果是否正确，而不是通过发出的信号
     *
     * branch为空： 返回信息失败
     * branch不为空： 返回信息正确后，另外商店也能获取到发布平台发布的应用信息，商店就可以正确显示该应用
     */
gboolean KMSystemServerAdaptor::getRemoteInfomation(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name)
{
    kmlogger.info("begin call getRemoteInfo api, ID: %s", name);

    string remoteInfoJson;
    std::vector<std::string> allRemoteInfo;
    std::string remoteKind = "";
    int errorCode = getPackageManager()->getRemoteInfo(name, remoteInfoJson, allRemoteInfo, remoteKind);

    kmlogger.info("before emit getRemoteInfo signal");
    // 发送 getremoteinfosignal 信号
    g_signal_emit_by_name(object, "getremoteinfosignal", name, remoteInfoJson.c_str(), errorCode, KMErrorMsg::getErrorMessage(errorCode).c_str());
    kmlogger.info("end emit getRemoteInfo signal");

    // 创建一个 GVariant 来封装字符串
    GVariant *result = g_variant_new("(s)", remoteInfoJson.c_str());

    // 返回结果给调用方
    g_dbus_method_invocation_return_value(invocation, result);
    return TRUE;
}

gboolean KMSystemServerAdaptor::getRemotePackageStatus(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name, const gchar *version, const gchar *branch)
{
    kmlogger.info("begin call getRemotePackageStatus api, ID: %s, version is %s, branch is %s", name, version, branch);

    std::vector<std::string> completeRef;
    if (std::string(branch).empty())
    {
        branch = "stable";
    }
    int errorCode;
    std::string remoteStatusInfo;
    errorCode = getPackageManager()->getRemoteStatusInfo(name, version, branch, remoteStatusInfo, errorCode);

    kmlogger.info("before emit getRemotePackageStatus signal");
    // 发送 getremotepackagestatussignal 信号
    g_signal_emit_by_name(object, "getremotepackagestatussignal", name, remoteStatusInfo.c_str(), errorCode, KMErrorMsg::getErrorMessage(errorCode).c_str());
    kmlogger.info("end emit getRemotePackageStatus signal");

    // 创建一个 GVariant 来封装字符串
    GVariant *result = g_variant_new("(s)", remoteStatusInfo.c_str());

    // 返回结果给调用方
    g_dbus_method_invocation_return_value(invocation, result);
    return TRUE;
}

gboolean KMSystemServerAdaptor::getAllRemoteInfo(KaimingInterface *object, GDBusMethodInvocation *invocation)
{
    kmlogger.info("begin call getAllRemoteInfo api");

    string remoteInfoJson;
    std::vector<std::string> allRemoteInfo;
    int errorCode;
    std::string remoteKind = "";
    try
    {   
        errorCode = getPackageManager()->getRemoteInfo("", remoteInfoJson, allRemoteInfo, remoteKind);
    }
    catch (const std::exception &e)
    {
        kmlogger.info("getAllRemoteInfo error: %s", e.what());
    }

    kmlogger.info("before emit getAllRemoteInfo signal");

    // 转换 std::vector<std::string> 为 GStrv（信号与返回值都用这批数据）
    gchar **strv = g_new0(gchar *, allRemoteInfo.size() + 1);
    for (size_t i = 0; i < allRemoteInfo.size(); ++i)
    {
        strv[i] = g_strdup(allRemoteInfo[i].c_str());
    }
    // 发送 getallremoteinfosignal 信号
    g_signal_emit_by_name(object, "getallremoteinfosignal", "", strv, errorCode, KMErrorMsg::getErrorMessage(errorCode).c_str());
    kmlogger.info("end emit getallremoteinfosignal signal");

    // 使用 g_variant_new_strv 生成数组，并尽早释放 GStrv
    GVariant *array_variant = g_variant_new_strv((const gchar * const *)strv, (gssize)allRemoteInfo.size());
    g_strfreev(strv);

    // 用完源数据后，主动释放局部容器内存
    std::vector<std::string>().swap(allRemoteInfo);
    malloc_trim(0);

    // 封装返回值并返回给调用方
    GVariant *result = g_variant_new("(@as)", array_variant);
    g_dbus_method_invocation_return_value(invocation, result);

    return TRUE;
}

gboolean KMSystemServerAdaptor::getAPPsRemoteInfo(KaimingInterface *object, GDBusMethodInvocation *invocation)
{
    kmlogger.info("begin call getAPPsRemoteInfo api");

    string remoteInfoJson;
    std::vector<std::string> allRemoteInfo;
    std::string remoteKind = "app";
    int errorCode;
    try
    {   
        errorCode = getPackageManager()->getRemoteInfo("", remoteInfoJson, allRemoteInfo, remoteKind);
    }
    catch (const std::exception &e)
    {
        kmlogger.info("getAPPsRemoteInfo error: %s", e.what());
    }

    kmlogger.info("before emit getAPPsRemoteInfo signal");

    // 转换 std::vector<std::string> 为 GStrv（信号与返回值都用这批数据）
    gchar **strv = g_new0(gchar *, allRemoteInfo.size() + 1);
    for (size_t i = 0; i < allRemoteInfo.size(); ++i)
    {
        strv[i] = g_strdup(allRemoteInfo[i].c_str());
    }
    // 发送 getappsremoteinfosignal 信号
    g_signal_emit_by_name(object, "getappsremoteinfosignal", "", strv, errorCode, KMErrorMsg::getErrorMessage(errorCode).c_str());
    kmlogger.info("end emit getappsremoteinfosignal signal");

    // 使用 g_variant_new_strv 生成数组，并尽早释放 GStrv
    GVariant *array_variant = g_variant_new_strv((const gchar * const *)strv, (gssize)allRemoteInfo.size());
    g_strfreev(strv);

    // 用完源数据后，主动释放局部容器内存
    std::vector<std::string>().swap(allRemoteInfo);
    malloc_trim(0);

    // 封装返回值并返回给调用方
    GVariant *result = g_variant_new("(@as)", array_variant);
    g_dbus_method_invocation_return_value(invocation, result);

    return TRUE;
}

gboolean KMSystemServerAdaptor::isInstalled(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name)
{
    kmlogger.info("begin call isInstalled api, name = %s", name);

    if (!validateInputName(name))
    {
        kmlogger.error("Package name must be specified");
        g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Package name must be specified");
        return TRUE;
    }

    int ret = getPackageManager()->isInstalled(name);
    g_signal_emit_by_name(object, "isinstalledsignal", name, ret, 0, KMErrorMsg::getErrorMessage(ret).c_str());
    kmlogger.info("end emit isInstalled signal");

    kaiming_interface_complete_is_installed(object, invocation, ret == KM_ERROR_NO);
    return TRUE;
}

gboolean KMSystemServerAdaptor::isUpgradable(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name)
{
    kmlogger.info("begin call isUpgradable api, name = %s", name);

    if (!validateInputName(name))
    {
        kmlogger.error("Package name must be specified");
        g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Package name must be specified");
        return TRUE;
    }

    int ret = getPackageManager()->isUpgradabled(name);
    g_signal_emit_by_name(object, "isupgradablesignal", name, ret, 0, KMErrorMsg::getErrorMessage(ret).c_str());
    kmlogger.info("end emit isUpgradable signal");

    kaiming_interface_complete_is_upgradable(object, invocation, ret == KM_ERROR_NO);
    return TRUE;
}

gboolean KMSystemServerAdaptor::getRemoteSummary(KaimingInterface *object, GDBusMethodInvocation *invocation)
{
    kmlogger.info("begin call getRemoteSummary api");

    KMFolder folder;
    folder.ensureRepoForSudo(FALSE);

    // 下载和解析清单依赖文件 summary.json
    string ostreeRepoUrl = getPackageManager()->getRemoteUrl(REPO_NAME);
    std::string summaryUrl = ostreeRepoUrl.append("/").append("summary.json");

    fs::path basePath = folder.getPath();
    fs::path summaryJsonPath = basePath / "summary.json";
    bool isSummaryJsonExpired = KMFileUtils::isFileExpired(summaryJsonPath, 3600);
    int errorCode = getPackageManager()->getRemoteSummary(summaryUrl, isSummaryJsonExpired);

    // 发送 getremotesummarysignal 信号
    g_signal_emit_by_name(object, "getremotesummarysignal", summaryUrl, errorCode, KMErrorMsg::getErrorMessage(errorCode).c_str());
    kmlogger.info("end emit getRemoteSummary signal");

    // 返回生成的信息字符串
    kaiming_interface_complete_is_upgradable(object, invocation, errorCode == KM_ERROR_NO);
    return TRUE;
}

// 静态适配器方法，用于连接 GDBus 信号   KaimingInterface需与xml自动生成的.c中的一致
gboolean KMSystemServerAdaptor::handleInstall(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                              const gchar *name, const gchar *branch, gpointer user_data)
{
    // 将 user_data 转换为 KMSystemServerAdaptor 实例
    KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
    return instance->install(object, invocation, name, branch);
}

gboolean KMSystemServerAdaptor::handleInstallOfflinePackage(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                                            const gchar *name, const gchar *branch, gpointer user_data)
{
    KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
    return instance->installOfflinePackage(object, invocation, name, branch);
}

gboolean KMSystemServerAdaptor::handleUpdate(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                             const gchar *name, const gchar *branch, gpointer user_data)
{
    KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
    return instance->update(object, invocation, name, branch);
}

gboolean KMSystemServerAdaptor::handleUninstall(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                                const gchar *name, const gchar *branch, gpointer user_data)
{
    KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
    return instance->uninstall(object, invocation, name, branch);
}

gboolean KMSystemServerAdaptor::handleGetLocalInfo(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                                   const gchar *name, gpointer user_data)
{
    KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
    return instance->getLocalInfomation(object, invocation, name);
}

gboolean KMSystemServerAdaptor::handleGetAllLocalInfo(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                                      gpointer user_data)
{
    KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
    return instance->getAllLocalInfo(object, invocation);
}

gboolean KMSystemServerAdaptor::handleGetAllRemoteInfo(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                                       gpointer user_data)
{
    KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
    return instance->getAllRemoteInfo(object, invocation);
}

gboolean KMSystemServerAdaptor::handleGetAPPsRemoteInfo(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                                        gpointer user_data)
{
    KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
    return instance->getAPPsRemoteInfo(object, invocation);
}

gboolean KMSystemServerAdaptor::handleGetRemoteInfo(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                                    const gchar *name, gpointer user_data)
{
    KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
    return instance->getRemoteInfomation(object, invocation, name);
}

gboolean KMSystemServerAdaptor::handleGetRemotePackageStatus(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                                    const gchar *name, const gchar *version, const gchar *branch, gpointer user_data)
{
    KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
    return instance->getRemotePackageStatus(object, invocation, name, version, branch);
}

gboolean KMSystemServerAdaptor::handleIsInstalled(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                                  const gchar *name, gpointer user_data)
{
    KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
    return instance->isInstalled(object, invocation, name);
}

gboolean KMSystemServerAdaptor::handleIsUpgradable(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                                   const gchar *name, gpointer user_data)
{
    KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
    return instance->isUpgradable(object, invocation, name);
}

gboolean KMSystemServerAdaptor::handleGetRemoteSummary(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                                       gpointer user_data)
{
    KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
    return instance->getRemoteSummary(object, invocation);
}

// 当总线获取成功时的回调
static void on_bus_acquired(GDBusConnection *connection, const gchar *name, gpointer user_data)
{
    GError *error = NULL;
    // 获取 KMSystemServerAdaptor 实例
    KMSystemServerAdaptor *handler = static_cast<KMSystemServerAdaptor *>(user_data);
    // 创建一个新的 Service 对象  需与xml自动生成的.c中的一致
    KaimingInterface *service = kaiming_interface_skeleton_new();
    // 将 Service 对象的方法调用与 KMSystemServerAdaptor 的方法连接起来   "handle-install-offline-package"需与xml自动生成的.c中的一致
    g_signal_connect(service, "handle-install", G_CALLBACK(KMSystemServerAdaptor::handleInstall), handler);
    g_signal_connect(service, "handle-install-offline-package", G_CALLBACK(KMSystemServerAdaptor::handleInstallOfflinePackage), handler);
    g_signal_connect(service, "handle-update", G_CALLBACK(KMSystemServerAdaptor::handleUpdate), handler);
    g_signal_connect(service, "handle-uninstall", G_CALLBACK(KMSystemServerAdaptor::handleUninstall), handler);
    g_signal_connect(service, "handle-get-local-info", G_CALLBACK(KMSystemServerAdaptor::handleGetLocalInfo), handler);
    g_signal_connect(service, "handle_get_all_local_info", G_CALLBACK(KMSystemServerAdaptor::handleGetAllLocalInfo), handler);
    g_signal_connect(service, "handle_get_all_remote_info", G_CALLBACK(KMSystemServerAdaptor::handleGetAllRemoteInfo), handler);
    g_signal_connect(service, "handle_get_apps_remote_info", G_CALLBACK(KMSystemServerAdaptor::handleGetAPPsRemoteInfo), handler);
    g_signal_connect(service, "handle-get-remote-info", G_CALLBACK(KMSystemServerAdaptor::handleGetRemoteInfo), handler);
    g_signal_connect(service, "handle-get-remote-package-status", G_CALLBACK(KMSystemServerAdaptor::handleGetRemotePackageStatus), handler);
    g_signal_connect(service, "handle-is-installed", G_CALLBACK(KMSystemServerAdaptor::handleIsInstalled), handler);
    g_signal_connect(service, "handle-is-upgradable", G_CALLBACK(KMSystemServerAdaptor::handleIsUpgradable), handler);
    g_signal_connect(service, "handle-get-remote-summary", G_CALLBACK(KMSystemServerAdaptor::handleGetRemoteSummary), handler);

    // 将 Service 对象导出到 D-Bus 连接上
    g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(service), connection, KAIMING_DBUS_PATH, &error);
    if (error)
    {
        std::cerr << "Failed to export interface: " << error->message << std::endl;
        g_clear_error(&error);
        g_object_unref(service);
    }
}

int main(int argc, char *argv[])
{
    // 检查 overlay 配置文件
    KMOverlay::checkOverlayConfig();

    // 获取系统上已注册的浏览器二进制文件
    KMBrowserUtils::getAllBrowserExecutables();

    // 创建主循环对象
    GMainLoop *loop;
    guint owner_id;

    // 创建 KMSystemServerAdaptor 实例
    KMSystemServerAdaptor handler;

    // 将 handler 作为 user_data 传递
    owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM, KAIMING_DBUS_SERVICE, G_BUS_NAME_OWNER_FLAGS_NONE,
                              on_bus_acquired, NULL, NULL, &handler, NULL);

    // 创建主循环
    loop = g_main_loop_new(NULL, FALSE);

    kmlogger.info("org.kylin.kaiming service started successfully, waiting for D-Bus requests...");

    // 进入循环
    g_main_loop_run(loop);

    // 取消 D-Bus 名称的所有权 释放资源
    g_bus_unown_name(owner_id);
    // 释放 GMainLoop 对象
    g_main_loop_unref(loop);

    return 0;
}
