code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <cstddef>
#include <mutex>
#include <string>
#include <boost/container/flat_map.hpp>
#include "common/common_types.h"
#include "core/hle/service/hle_ipc.h"

////////////////////////////////////////////////////////////////////////////////////////////////////
// Namespace Service

namespace Core {
class System;
}

namespace Kernel {
class KServerSession;
class ServiceThread;
} // namespace Kernel

namespace Service {

namespace FileSystem {
class FileSystemController;
}

namespace SM {
class ServiceManager;
}

/// Default number of maximum connections to a server session.
static constexpr u32 ServerSessionCountMax = 0x40;
static_assert(ServerSessionCountMax == 0x40,
              "ServerSessionCountMax isn't 0x40 somehow, this assert is a reminder that this will "
              "break lots of things");

/**
 * This is an non-templated base of ServiceFramework to reduce code bloat and compilation times, it
 * is not meant to be used directly.
 *
 * @see ServiceFramework
 */
class ServiceFrameworkBase : public SessionRequestHandler {
public:
    /// Returns the string identifier used to connect to the service.
    std::string GetServiceName() const {
        return service_name;
    }

    /**
     * Returns the maximum number of sessions that can be connected to this service at the same
     * time.
     */
    u32 GetMaxSessions() const {
        return max_sessions;
    }

    /// Invokes a service request routine using the HIPC protocol.
    void InvokeRequest(HLERequestContext& ctx);

    /// Invokes a service request routine using the HIPC protocol.
    void InvokeRequestTipc(HLERequestContext& ctx);

    /// Handles a synchronization request for the service.
    Result HandleSyncRequest(Kernel::KServerSession& session, HLERequestContext& context) override;

protected:
    /// Member-function pointer type of SyncRequest handlers.
    template <typename Self>
    using HandlerFnP = void (Self::*)(HLERequestContext&);

    /// Used to gain exclusive access to the service members, e.g. from CoreTiming thread.
    [[nodiscard]] virtual std::unique_lock<std::mutex> LockService() {
        return std::unique_lock{lock_service};
    }

    /// System context that the service operates under.
    Core::System& system;

    /// Identifier string used to connect to the service.
    std::string service_name;

private:
    template <typename T>
    friend class ServiceFramework;

    struct FunctionInfoBase {
        u32 expected_header;
        HandlerFnP<ServiceFrameworkBase> handler_callback;
        const char* name;
    };

    using InvokerFn = void(ServiceFrameworkBase* object, HandlerFnP<ServiceFrameworkBase> member,
                           HLERequestContext& ctx);

    explicit ServiceFrameworkBase(Core::System& system_, const char* service_name_,
                                  u32 max_sessions_, InvokerFn* handler_invoker_);
    ~ServiceFrameworkBase() override;

    void RegisterHandlersBase(const FunctionInfoBase* functions, std::size_t n);
    void RegisterHandlersBaseTipc(const FunctionInfoBase* functions, std::size_t n);
    void ReportUnimplementedFunction(HLERequestContext& ctx, const FunctionInfoBase* info);

    /// Maximum number of concurrent sessions that this service can handle.
    u32 max_sessions;

    /// Flag to store if a port was already create/installed to detect multiple install attempts,
    /// which is not supported.
    bool service_registered = false;

    /// Function used to safely up-cast pointers to the derived class before invoking a handler.
    InvokerFn* handler_invoker;
    boost::container::flat_map<u32, FunctionInfoBase> handlers;
    boost::container::flat_map<u32, FunctionInfoBase> handlers_tipc;

    /// Used to gain exclusive access to the service members, e.g. from CoreTiming thread.
    std::mutex lock_service;
};

/**
 * Framework for implementing HLE services. Dispatches on the header id of incoming SyncRequests
 * based on a table mapping header ids to handler functions. Service implementations should inherit
 * from ServiceFramework using the CRTP (`class Foo : public ServiceFramework<Foo> { ... };`) and
 * populate it with handlers by calling #RegisterHandlers.
 *
 * In order to avoid duplicating code in the binary and exposing too many implementation details in
 * the header, this class is split into a non-templated base (ServiceFrameworkBase) and a template
 * deriving from it (ServiceFramework). The functions in this class will mostly only erase the type
 * of the passed in function pointers and then delegate the actual work to the implementation in the
 * base class.
 */
template <typename Self>
class ServiceFramework : public ServiceFrameworkBase {
protected:
    /// Contains information about a request type which is handled by the service.
    template <typename T>
    struct FunctionInfoTyped : FunctionInfoBase {
        // TODO(yuriks): This function could be constexpr, but clang is the only compiler that
        // doesn't emit an ICE or a wrong diagnostic because of the static_cast.

        /**
         * Constructs a FunctionInfo for a function.
         *
         * @param expected_header_ request header in the command buffer which will trigger dispatch
         *     to this handler
         * @param handler_callback_ member function in this service which will be called to handle
         *     the request
         * @param name_ human-friendly name for the request. Used mostly for logging purposes.
         */
        FunctionInfoTyped(u32 expected_header_, HandlerFnP<T> handler_callback_, const char* name_)
            : FunctionInfoBase{
                  expected_header_,
                  // Type-erase member function pointer by casting it down to the base class.
                  static_cast<HandlerFnP<ServiceFrameworkBase>>(handler_callback_), name_} {}
    };
    using FunctionInfo = FunctionInfoTyped<Self>;

    /**
     * Initializes the handler with no functions installed.
     *
     * @param system_ The system context to construct this service under.
     * @param service_name_ Name of the service.
     * @param max_sessions_ Maximum number of sessions that can be connected to this service at the
     * same time.
     */
    explicit ServiceFramework(Core::System& system_, const char* service_name_,
                              u32 max_sessions_ = ServerSessionCountMax)
        : ServiceFrameworkBase(system_, service_name_, max_sessions_, Invoker) {}

    /// Registers handlers in the service.
    template <typename T = Self, std::size_t N>
    void RegisterHandlers(const FunctionInfoTyped<T> (&functions)[N]) {
        RegisterHandlers(functions, N);
    }

    /**
     * Registers handlers in the service. Usually prefer using the other RegisterHandlers
     * overload in order to avoid needing to specify the array size.
     */
    template <typename T = Self>
    void RegisterHandlers(const FunctionInfoTyped<T>* functions, std::size_t n) {
        RegisterHandlersBase(functions, n);
    }

    /// Registers handlers in the service.
    template <typename T = Self, std::size_t N>
    void RegisterHandlersTipc(const FunctionInfoTyped<T> (&functions)[N]) {
        RegisterHandlersTipc(functions, N);
    }

    /**
     * Registers handlers in the service. Usually prefer using the other RegisterHandlers
     * overload in order to avoid needing to specify the array size.
     */
    template <typename T = Self>
    void RegisterHandlersTipc(const FunctionInfoTyped<T>* functions, std::size_t n) {
        RegisterHandlersBaseTipc(functions, n);
    }

protected:
    template <bool Domain, auto F>
    void CmifReplyWrap(HLERequestContext& ctx);

    /**
     * Wraps the template pointer-to-member function for use in a domain session.
     */
    template <auto F>
    static constexpr HandlerFnP<Self> D = &Self::template CmifReplyWrap<true, F>;

    /**
     * Wraps the template pointer-to-member function for use in a non-domain session.
     */
    template <auto F>
    static constexpr HandlerFnP<Self> C = &Self::template CmifReplyWrap<false, F>;

private:
    /**
     * This function is used to allow invocation of pointers to handlers stored in the base class
     * without needing to expose the type of this derived class. Pointers-to-member may require a
     * fixup when being up or downcast, and thus code that does that needs to know the concrete type
     * of the derived class in order to invoke one of it's functions through a pointer.
     */
    static void Invoker(ServiceFrameworkBase* object, HandlerFnP<ServiceFrameworkBase> member,
                        HLERequestContext& ctx) {
        // Cast back up to our original types and call the member function
        (static_cast<Self*>(object)->*static_cast<HandlerFnP<Self>>(member))(ctx);
    }
};

} // namespace Service


code:
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "core/hle/service/services.h"

#include "core/hle/service/acc/acc.h"
#include "core/hle/service/am/am.h"
#include "core/hle/service/aoc/addon_content_manager.h"
#include "core/hle/service/apm/apm.h"
#include "core/hle/service/audio/audio.h"
#include "core/hle/service/bcat/bcat.h"
#include "core/hle/service/bpc/bpc.h"
#include "core/hle/service/btdrv/btdrv.h"
#include "core/hle/service/btm/btm.h"
#include "core/hle/service/caps/caps.h"
#include "core/hle/service/erpt/erpt.h"
#include "core/hle/service/es/es.h"
#include "core/hle/service/eupld/eupld.h"
#include "core/hle/service/fatal/fatal.h"
#include "core/hle/service/fgm/fgm.h"
#include "core/hle/service/filesystem/filesystem.h"
#include "core/hle/service/friend/friend.h"
#include "core/hle/service/glue/glue.h"
#include "core/hle/service/grc/grc.h"
#include "core/hle/service/hid/hid.h"
#include "core/hle/service/ipc_helpers.h"
#include "core/hle/service/jit/jit.h"
#include "core/hle/service/lbl/lbl.h"
#include "core/hle/service/ldn/ldn.h"
#include "core/hle/service/ldr/ldr.h"
#include "core/hle/service/lm/lm.h"
#include "core/hle/service/mig/mig.h"
#include "core/hle/service/mii/mii.h"
#include "core/hle/service/mm/mm_u.h"
#include "core/hle/service/mnpp/mnpp_app.h"
#include "core/hle/service/ncm/ncm.h"
#include "core/hle/service/nfc/nfc.h"
#include "core/hle/service/nfp/nfp.h"
#include "core/hle/service/ngc/ngc.h"
#include "core/hle/service/nifm/nifm.h"
#include "core/hle/service/nim/nim.h"
#include "core/hle/service/npns/npns.h"
#include "core/hle/service/ns/ns.h"
#include "core/hle/service/nvdrv/nvdrv.h"
#include "core/hle/service/nvnflinger/nvnflinger.h"
#include "core/hle/service/olsc/olsc.h"
#include "core/hle/service/omm/omm.h"
#include "core/hle/service/pcie/pcie.h"
#include "core/hle/service/pctl/pctl.h"
#include "core/hle/service/pcv/pcv.h"
#include "core/hle/service/pm/pm.h"
#include "core/hle/service/prepo/prepo.h"
#include "core/hle/service/psc/psc.h"
#include "core/hle/service/ptm/ptm.h"
#include "core/hle/service/ro/ro.h"
#include "core/hle/service/service.h"
#include "core/hle/service/set/settings.h"
#include "core/hle/service/sm/sm.h"
#include "core/hle/service/sockets/sockets.h"
#include "core/hle/service/spl/spl_module.h"
#include "core/hle/service/ssl/ssl.h"
#include "core/hle/service/usb/usb.h"
#include "core/hle/service/vi/vi.h"

namespace Service {

Services::Services(std::shared_ptr<SM::ServiceManager>& sm, Core::System& system,
                   std::stop_token token) {
    auto& kernel = system.Kernel();

    system.GetFileSystemController().CreateFactories(*system.GetFilesystem(), false);

    // clang-format off
    kernel.RunOnHostCoreProcess("audio",      [&] { Audio::LoopProcess(system); }).detach();
    kernel.RunOnHostCoreProcess("FS",         [&] { FileSystem::LoopProcess(system); }).detach();
    kernel.RunOnHostCoreProcess("jit",        [&] { JIT::LoopProcess(system); }).detach();
    kernel.RunOnHostCoreProcess("ldn",        [&] { LDN::LoopProcess(system); }).detach();
    kernel.RunOnHostCoreProcess("Loader",     [&] { LDR::LoopProcess(system); }).detach();
    kernel.RunOnHostCoreProcess("nvservices", [&] { Nvidia::LoopProcess(system); }).detach();
    kernel.RunOnHostCoreProcess("bsdsocket",  [&] { Sockets::LoopProcess(system); }).detach();
    kernel.RunOnHostCoreProcess("vi",         [&, token] { VI::LoopProcess(system, token); }).detach();

    kernel.RunOnGuestCoreProcess("sm",         [&] { SM::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("account",    [&] { Account::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("am",         [&] { AM::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("aoc",        [&] { AOC::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("apm",        [&] { APM::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("bcat",       [&] { BCAT::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("bpc",        [&] { BPC::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("btdrv",      [&] { BtDrv::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("btm",        [&] { BTM::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("capsrv",     [&] { Capture::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("erpt",       [&] { ERPT::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("es",         [&] { ES::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("eupld",      [&] { EUPLD::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("fatal",      [&] { Fatal::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("fgm",        [&] { FGM::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("friends",    [&] { Friend::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("settings",   [&] { Set::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("psc",        [&] { PSC::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("glue",       [&] { Glue::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("grc",        [&] { GRC::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("hid",        [&] { HID::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("lbl",        [&] { LBL::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("LogManager.Prod", [&] { LM::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("mig",        [&] { Migration::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("mii",        [&] { Mii::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("mm",         [&] { MM::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("mnpp",       [&] { MNPP::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("nvnflinger", [&] { Nvnflinger::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("NCM",        [&] { NCM::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("nfc",        [&] { NFC::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("nfp",        [&] { NFP::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("ngc",        [&] { NGC::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("nifm",       [&] { NIFM::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("nim",        [&] { NIM::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("npns",       [&] { NPNS::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("ns",         [&] { NS::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("olsc",       [&] { OLSC::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("omm",        [&] { OMM::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("pcie",       [&] { PCIe::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("pctl",       [&] { PCTL::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("pcv",        [&] { PCV::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("prepo",      [&] { PlayReport::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("ProcessManager", [&] { PM::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("ptm",        [&] { PTM::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("ro",         [&] { RO::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("spl",        [&] { SPL::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("ssl",        [&] { SSL::LoopProcess(system); });
    kernel.RunOnGuestCoreProcess("usb",        [&] { USB::LoopProcess(system); });
    // clang-format on
}

Services::~Services() = default;

} // namespace Service

repo_name: litucks/torzu

license: mit


code:
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include "common/polyfill_thread.h"
#include "core/hle/service/sm/sm.h"

namespace Service {

/**
 * The purpose of this class is to own any objects that need to be shared across the other service
 * implementations. Will be torn down when the global system instance is shutdown.
 */
class Services final {
public:
    explicit Services(std::shared_ptr<SM::ServiceManager>& sm, Core::System& system,
                      std::stop_token token);
    ~Services();
};

} // namespace Service


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "core/hle/service/set/factory_settings_server.h"

namespace Service::Set {

IFactorySettingsServer::IFactorySettingsServer(Core::System& system_)
    : ServiceFramework{system_, "set:cal"} {
    // clang-format off
    static const FunctionInfo functions[] = {
        {0, nullptr, "GetBluetoothBdAddress"},
        {1, nullptr, "GetConfigurationId1"},
        {2, nullptr, "GetAccelerometerOffset"},
        {3, nullptr, "GetAccelerometerScale"},
        {4, nullptr, "GetGyroscopeOffset"},
        {5, nullptr, "GetGyroscopeScale"},
        {6, nullptr, "GetWirelessLanMacAddress"},
        {7, nullptr, "GetWirelessLanCountryCodeCount"},
        {8, nullptr, "GetWirelessLanCountryCodes"},
        {9, nullptr, "GetSerialNumber"},
        {10, nullptr, "SetInitialSystemAppletProgramId"},
        {11, nullptr, "SetOverlayDispProgramId"},
        {12, nullptr, "GetBatteryLot"},
        {14, nullptr, "GetEciDeviceCertificate"},
        {15, nullptr, "GetEticketDeviceCertificate"},
        {16, nullptr, "GetSslKey"},
        {17, nullptr, "GetSslCertificate"},
        {18, nullptr, "GetGameCardKey"},
        {19, nullptr, "GetGameCardCertificate"},
        {20, nullptr, "GetEciDeviceKey"},
        {21, nullptr, "GetEticketDeviceKey"},
        {22, nullptr, "GetSpeakerParameter"},
        {23, nullptr, "GetLcdVendorId"},
        {24, nullptr, "GetEciDeviceCertificate2"},
        {25, nullptr, "GetEciDeviceKey2"},
        {26, nullptr, "GetAmiiboKey"},
        {27, nullptr, "GetAmiiboEcqvCertificate"},
        {28, nullptr, "GetAmiiboEcdsaCertificate"},
        {29, nullptr, "GetAmiiboEcqvBlsKey"},
        {30, nullptr, "GetAmiiboEcqvBlsCertificate"},
        {31, nullptr, "GetAmiiboEcqvBlsRootCertificate"},
        {32, nullptr, "GetUsbTypeCPowerSourceCircuitVersion"},
        {33, nullptr, "GetAnalogStickModuleTypeL"},
        {34, nullptr, "GetAnalogStickModelParameterL"},
        {35, nullptr, "GetAnalogStickFactoryCalibrationL"},
        {36, nullptr, "GetAnalogStickModuleTypeR"},
        {37, nullptr, "GetAnalogStickModelParameterR"},
        {38, nullptr, "GetAnalogStickFactoryCalibrationR"},
        {39, nullptr, "GetConsoleSixAxisSensorModuleType"},
        {40, nullptr, "GetConsoleSixAxisSensorHorizontalOffset"},
        {41, nullptr, "GetBatteryVersion"},
        {42, nullptr, "GetDeviceId"},
        {43, nullptr, "GetConsoleSixAxisSensorMountType"},
    };
    // clang-format on

    RegisterHandlers(functions);
}

IFactorySettingsServer::~IFactorySettingsServer() = default;

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include "core/hle/service/service.h"

namespace Core {
class System;
}

namespace Service::Set {

class IFactorySettingsServer final : public ServiceFramework<IFactorySettingsServer> {
public:
    explicit IFactorySettingsServer(Core::System& system_);
    ~IFactorySettingsServer() override;
};

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "core/hle/service/set/firmware_debug_settings_server.h"

namespace Service::Set {

IFirmwareDebugSettingsServer::IFirmwareDebugSettingsServer(Core::System& system_)
    : ServiceFramework{system_, "set:fd"} {
    // clang-format off
    static const FunctionInfo functions[] = {
        {2, nullptr, "SetSettingsItemValue"},
        {3, nullptr, "ResetSettingsItemValue"},
        {4, nullptr, "CreateSettingsItemKeyIterator"},
        {10, nullptr, "ReadSettings"},
        {11, nullptr, "ResetSettings"},
        {20, nullptr, "SetWebInspectorFlag"},
        {21, nullptr, "SetAllowedSslHosts"},
        {22, nullptr, "SetHostFsMountPoint"},
        {23, nullptr, "SetMemoryUsageRateFlag"},
    };
    // clang-format on

    RegisterHandlers(functions);
}

IFirmwareDebugSettingsServer::~IFirmwareDebugSettingsServer() = default;

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include "core/hle/service/service.h"

namespace Core {
class System;
}

namespace Service::Set {

class IFirmwareDebugSettingsServer final : public ServiceFramework<IFirmwareDebugSettingsServer> {
public:
    explicit IFirmwareDebugSettingsServer(Core::System& system_);
    ~IFirmwareDebugSettingsServer() override;
};

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "core/hle/service/set/setting_formats/appln_settings.h"

namespace Service::Set {

ApplnSettings DefaultApplnSettings() {
    ApplnSettings settings{};

    settings.mii_author_id = Common::UUID::MakeDefault();

    return settings;
}

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <array>
#include <cstddef>

#include "common/common_types.h"
#include "common/uuid.h"
#include "core/hle/service/set/settings_types.h"

namespace Service::Set {
struct ApplnSettings {
    INSERT_PADDING_BYTES(0x10); // Reserved

    // nn::util::Uuid MiiAuthorId, copied from system settings 0x94B0
    Common::UUID mii_author_id;
    INSERT_PADDING_BYTES(0x30); // Reserved

    // nn::settings::system::ServiceDiscoveryControlSettings
    u32 service_discovery_control_settings;
    INSERT_PADDING_BYTES(0x20); // Reserved

    bool in_repair_process_enable_flag;
    INSERT_PADDING_BYTES(0x3);
};
static_assert(offsetof(ApplnSettings, mii_author_id) == 0x10);
static_assert(offsetof(ApplnSettings, service_discovery_control_settings) == 0x50);
static_assert(offsetof(ApplnSettings, in_repair_process_enable_flag) == 0x74);
static_assert(sizeof(ApplnSettings) == 0x78, "ApplnSettings has the wrong size!");

ApplnSettings DefaultApplnSettings();

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "core/hle/service/set/setting_formats/device_settings.h"

namespace Service::Set {

DeviceSettings DefaultDeviceSettings() {
    return {};
}

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <array>
#include <cstddef>

#include "common/common_types.h"
#include "common/vector_math.h"
#include "core/hle/service/set/settings_types.h"

namespace Service::Set {
struct DeviceSettings {
    INSERT_PADDING_BYTES(0x10); // Reserved

    // nn::settings::BatteryLot
    std::array<u8, 0x18> ptm_battery_lot;
    // nn::settings::system::PtmFuelGaugeParameter
    std::array<u8, 0x18> ptm_fuel_gauge_parameter;
    u8 ptm_battery_version;
    // nn::settings::system::PtmCycleCountReliability
    u32 ptm_cycle_count_reliability;
    INSERT_PADDING_BYTES(0x48); // Reserved

    // nn::settings::system::AnalogStickUserCalibration L
    std::array<u8, 0x10> analog_user_stick_calibration_l;
    // nn::settings::system::AnalogStickUserCalibration R
    std::array<u8, 0x10> analog_user_stick_calibration_r;
    INSERT_PADDING_BYTES(0x20); // Reserved

    // nn::settings::system::ConsoleSixAxisSensorAccelerationBias
    Common::Vec3<f32> console_six_axis_sensor_acceleration_bias;
    // nn::settings::system::ConsoleSixAxisSensorAngularVelocityBias
    Common::Vec3<f32> console_six_axis_sensor_angular_velocity_bias;
    // nn::settings::system::ConsoleSixAxisSensorAccelerationGain
    std::array<u8, 0x24> console_six_axis_sensor_acceleration_gain;
    // nn::settings::system::ConsoleSixAxisSensorAngularVelocityGain
    std::array<u8, 0x24> console_six_axis_sensor_angular_velocity_gain;
    // nn::settings::system::ConsoleSixAxisSensorAngularVelocityTimeBias
    Common::Vec3<f32> console_six_axis_sensor_angular_velocity_time_bias;
    // nn::settings::system::ConsoleSixAxisSensorAngularAcceleration
    std::array<u8, 0x24> console_six_axis_sensor_angular_acceleration;
};
static_assert(offsetof(DeviceSettings, ptm_battery_lot) == 0x10);
static_assert(offsetof(DeviceSettings, ptm_cycle_count_reliability) == 0x44);
static_assert(offsetof(DeviceSettings, analog_user_stick_calibration_l) == 0x90);
static_assert(offsetof(DeviceSettings, console_six_axis_sensor_acceleration_bias) == 0xD0);
static_assert(offsetof(DeviceSettings, console_six_axis_sensor_angular_acceleration) == 0x13C);
static_assert(sizeof(DeviceSettings) == 0x160, "DeviceSettings has the wrong size!");

DeviceSettings DefaultDeviceSettings();

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "core/hle/service/set/setting_formats/private_settings.h"

namespace Service::Set {

PrivateSettings DefaultPrivateSettings() {
    return {};
}

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <array>

#include "common/common_types.h"
#include "common/uuid.h"
#include "core/hle/service/set/settings_types.h"

namespace Service::Set {

struct PrivateSettings {
    INSERT_PADDING_BYTES(0x10); // Reserved

    InitialLaunchSettings initial_launch_settings;
    INSERT_PADDING_BYTES(0x20); // Reserved

    Common::UUID external_clock_source_id;
    s64 shutdown_rtc_value;
    s64 external_steady_clock_internal_offset;
    INSERT_PADDING_BYTES(0x60); // Reserved

    // nn::settings::system::PlatformRegion
    s32 platform_region;
    INSERT_PADDING_BYTES(0x4); // Reserved
};
static_assert(offsetof(PrivateSettings, initial_launch_settings) == 0x10);
static_assert(offsetof(PrivateSettings, external_clock_source_id) == 0x50);
static_assert(offsetof(PrivateSettings, shutdown_rtc_value) == 0x60);
static_assert(offsetof(PrivateSettings, external_steady_clock_internal_offset) == 0x68);
static_assert(offsetof(PrivateSettings, platform_region) == 0xD0);
static_assert(sizeof(PrivateSettings) == 0xD8, "PrivateSettings has the wrong size!");

PrivateSettings DefaultPrivateSettings();

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "common/settings.h"
#include "core/hle/service/set/setting_formats/system_settings.h"

namespace Service::Set {

SystemSettings DefaultSystemSettings() {
    SystemSettings settings{};

    settings.version = 0x140000;
    settings.flags = 7;

    settings.mii_author_id = Common::UUID::MakeDefault();

    settings.color_set_id = ColorSet::BasicWhite;

    settings.notification_settings = {
        .flags{0x300},
        .volume = NotificationVolume::High,
        .start_time = {.hour = 9, .minute = 0},
        .stop_time = {.hour = 21, .minute = 0},
    };

    settings.tv_settings = {
        .flags = {0xC},
        .tv_resolution = TvResolution::Auto,
        .hdmi_content_type = HdmiContentType::Game,
        .rgb_range = RgbRange::Auto,
        .cmu_mode = CmuMode::None,
        .tv_underscan = {},
        .tv_gama = 1.0f,
        .contrast_ratio = 0.5f,
    };

    settings.initial_launch_settings_packed = {
        .flags = {0x10001},
        .timestamp = {},
    };

    settings.sleep_settings = {
        .flags = {0x3},
        .handheld_sleep_plan = HandheldSleepPlan::Sleep10Min,
        .console_sleep_plan = ConsoleSleepPlan::Sleep1Hour,
    };

    settings.device_time_zone_location_name = Service::PSC::Time::LocationName{"UTC"};
    settings.user_system_clock_automatic_correction_enabled = true;

    settings.primary_album_storage = PrimaryAlbumStorage::SdCard;
    settings.battery_percentage_flag = true;
    settings.chinese_traditional_input_method = ChineseTraditionalInputMethod::Unknown0;
    settings.vibration_master_volume = 1.0f;
    settings.touch_screen_mode = TouchScreenMode::Standard;
    settings.nfc_enable_flag = true;
    settings.bluetooth_enable_flag = true;
    settings.wireless_lan_enable_flag = true;

    const auto language_code =
        available_language_codes[static_cast<s32>(::Settings::values.language_index.GetValue())];
    const auto key_code =
        std::find_if(language_to_layout.cbegin(), language_to_layout.cend(),
                     [=](const auto& element) { return element.first == language_code; });

    settings.keyboard_layout = KeyboardLayout::EnglishUs;
    if (key_code != language_to_layout.end()) {
        settings.keyboard_layout = key_code->second;
    }

    return settings;
}

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <array>

#include "common/bit_field.h"
#include "common/common_funcs.h"
#include "common/common_types.h"
#include "common/uuid.h"
#include "common/vector_math.h"
#include "core/hle/service/set/setting_formats/private_settings.h"
#include "core/hle/service/set/settings_types.h"
#include "hid_core/resources/touch_screen/touch_types.h"

namespace Service::Set {

struct SystemSettings {
    // 0/unwritten (1.0.0), 0x20000 (2.0.0), 0x30000 (3.0.0-3.0.1), 0x40001 (4.0.0-4.1.0), 0x50000
    // (5.0.0-5.1.0), 0x60000 (6.0.0-6.2.0), 0x70000 (7.0.0), 0x80000 (8.0.0-8.1.1), 0x90000
    // (9.0.0-10.0.4), 0x100100 (10.1.0+), 0x120000 (12.0.0-12.1.0), 0x130000 (13.0.0-13.2.1),
    // 0x140000 (14.0.0+)
    u32 version;
    // 0/unwritten (1.0.0), 1 (6.0.0-8.1.0), 2 (8.1.1), 7 (9.0.0+).
    // if (flags & 2), defaults are written for AnalogStickUserCalibration
    u32 flags;
    INSERT_PADDING_BYTES(0x8); // Reserved

    LanguageCode language_code;
    INSERT_PADDING_BYTES(0x38); // Reserved

    // nn::settings::system::NetworkSettings
    u32 network_setting_count;
    bool wireless_lan_enable_flag;
    INSERT_PADDING_BYTES(0x3);
    INSERT_PADDING_BYTES(0x8); // Reserved

    // nn::settings::system::NetworkSettings
    std::array<std::array<u8, 0x400>, 32> network_settings_1B0;

    // nn::settings::system::BluetoothDevicesSettings
    std::array<u8, 0x4> bluetooth_device_settings_count;
    bool bluetooth_enable_flag;
    INSERT_PADDING_BYTES(0x3);
    bool bluetooth_afh_enable_flag;
    INSERT_PADDING_BYTES(0x3);
    bool bluetooth_boost_enable_flag;
    INSERT_PADDING_BYTES(0x3);
    std::array<std::array<u8, 0x200>, 10> bluetooth_device_settings_first_10;

    s32 ldn_channel;
    INSERT_PADDING_BYTES(0x3C); // Reserved

    // nn::util::Uuid MiiAuthorId
    Common::UUID mii_author_id;

    INSERT_PADDING_BYTES(0x30); // Reserved

    // nn::settings::system::NxControllerSettings
    u32 nx_controller_settings_count;

    INSERT_PADDING_BYTES(0xC); // Reserved

    // nn::settings::system::NxControllerSettings,
    // nn::settings::system::NxControllerLegacySettings on 13.0.0+
    std::array<std::array<u8, 0x40>, 10> nx_controller_legacy_settings;
    INSERT_PADDING_BYTES(0x170); // Reserved

    bool external_rtc_reset_flag;
    INSERT_PADDING_BYTES(0x3);
    INSERT_PADDING_BYTES(0x3C); // Reserved

    s32 push_notification_activity_mode_on_sleep;
    INSERT_PADDING_BYTES(0x3C); // Reserved

    ErrorReportSharePermission error_report_share_permission;
    INSERT_PADDING_BYTES(0x3C); // Reserved

    KeyboardLayout keyboard_layout;
    INSERT_PADDING_BYTES(0x3C); // Reserved

    bool web_inspector_flag;
    INSERT_PADDING_BYTES(0x3);

    // nn::settings::system::AllowedSslHost
    u32 allowed_ssl_host_count;

    bool memory_usage_rate_flag;
    INSERT_PADDING_BYTES(0x3);
    INSERT_PADDING_BYTES(0x34); // Reserved

    // nn::settings::system::HostFsMountPoint
    std::array<u8, 0x100> host_fs_mount_point;

    // nn::settings::system::AllowedSslHost
    std::array<std::array<u8, 0x100>, 8> allowed_ssl_hosts;
    INSERT_PADDING_BYTES(0x6C0); // Reserved

    // nn::settings::system::BlePairingSettings
    u32 ble_pairing_settings_count;
    INSERT_PADDING_BYTES(0xC); // Reserved
    std::array<std::array<u8, 0x80>, 10> ble_pairing_settings;

    // nn::settings::system::AccountOnlineStorageSettings
    u32 account_online_storage_settings_count;
    INSERT_PADDING_BYTES(0xC); // Reserved
    std::array<std::array<u8, 0x40>, 8> account_online_storage_settings;

    bool pctl_ready_flag;
    INSERT_PADDING_BYTES(0x3);
    INSERT_PADDING_BYTES(0x3C); // Reserved

    // nn::settings::system::ThemeId
    std::array<u8, 0x80> theme_id_type0;
    std::array<u8, 0x80> theme_id_type1;
    INSERT_PADDING_BYTES(0x100); // Reserved

    ChineseTraditionalInputMethod chinese_traditional_input_method;
    INSERT_PADDING_BYTES(0x3C); // Reserved

    bool zoom_flag;
    INSERT_PADDING_BYTES(0x3);
    INSERT_PADDING_BYTES(0x3C); // Reserved

    // nn::settings::system::ButtonConfigRegisteredSettings
    u32 button_config_registered_settings_count;
    INSERT_PADDING_BYTES(0xC); // Reserved

    // nn::settings::system::ButtonConfigSettings
    u32 button_config_settings_count;
    INSERT_PADDING_BYTES(0x4); // Reserved
    std::array<std::array<u8, 0x5A8>, 5> button_config_settings;
    INSERT_PADDING_BYTES(0x13B0); // Reserved
    u32 button_config_settings_embedded_count;
    INSERT_PADDING_BYTES(0x4); // Reserved
    std::array<std::array<u8, 0x5A8>, 5> button_config_settings_embedded;
    INSERT_PADDING_BYTES(0x13B0); // Reserved
    u32 button_config_settings_left_count;
    INSERT_PADDING_BYTES(0x4); // Reserved
    std::array<std::array<u8, 0x5A8>, 5> button_config_settings_left;
    INSERT_PADDING_BYTES(0x13B0); // Reserved
    u32 button_config_settings_right_count;
    INSERT_PADDING_BYTES(0x4); // Reserved
    std::array<std::array<u8, 0x5A8>, 5> button_config_settings_right;
    INSERT_PADDING_BYTES(0x73B0); // Reserved
    // nn::settings::system::ButtonConfigRegisteredSettings
    std::array<u8, 0x5C8> button_config_registered_settings_embedded;
    std::array<std::array<u8, 0x5C8>, 10> button_config_registered_settings;
    INSERT_PADDING_BYTES(0x7FF8); // Reserved

    // nn::settings::system::ConsoleSixAxisSensorAccelerationBias
    Common::Vec3<f32> console_six_axis_sensor_acceleration_bias;
    // nn::settings::system::ConsoleSixAxisSensorAngularVelocityBias
    Common::Vec3<f32> console_six_axis_sensor_angular_velocity_bias;
    // nn::settings::system::ConsoleSixAxisSensorAccelerationGain
    std::array<u8, 0x24> console_six_axis_sensor_acceleration_gain;
    // nn::settings::system::ConsoleSixAxisSensorAngularVelocityGain
    std::array<u8, 0x24> console_six_axis_sensor_angular_velocity_gain;
    // nn::settings::system::ConsoleSixAxisSensorAngularVelocityTimeBias
    Common::Vec3<f32> console_six_axis_sensor_angular_velocity_time_bias;
    // nn::settings::system::ConsoleSixAxisSensorAngularAcceleration
    std::array<u8, 0x24> console_six_axis_sensor_angular_velocity_acceleration;
    INSERT_PADDING_BYTES(0x70); // Reserved

    bool lock_screen_flag;
    INSERT_PADDING_BYTES(0x3);
    INSERT_PADDING_BYTES(0x4); // Reserved

    ColorSet color_set_id;

    QuestFlag quest_flag;

    SystemRegionCode region_code;

    // Different to nn::settings::system::InitialLaunchSettings?
    InitialLaunchSettingsPacked initial_launch_settings_packed;

    bool battery_percentage_flag;
    INSERT_PADDING_BYTES(0x3);

    // BitFlagSet<32, nn::settings::system::AppletLaunchFlag>
    u32 applet_launch_flag;

    // nn::settings::system::ThemeSettings
    std::array<u8, 0x8> theme_settings;
    // nn::fssystem::ArchiveMacKey
    std::array<u8, 0x10> theme_key;

    bool field_testing_flag;
    INSERT_PADDING_BYTES(0x3);

    s32 panel_crc_mode;
    INSERT_PADDING_BYTES(0x28); // Reserved

    // nn::settings::system::BacklightSettings
    std::array<u8, 0x2C> backlight_settings_mixed_up;
    INSERT_PADDING_BYTES(0x64); // Reserved

    // nn::time::SystemClockContext
    Service::PSC::Time::SystemClockContext user_system_clock_context;
    Service::PSC::Time::SystemClockContext network_system_clock_context;
    bool user_system_clock_automatic_correction_enabled;
    INSERT_PADDING_BYTES(0x3);
    INSERT_PADDING_BYTES(0x4); // Reserved
    // nn::time::SteadyClockTimePoint
    Service::PSC::Time::SteadyClockTimePoint
        user_system_clock_automatic_correction_updated_time_point;
    INSERT_PADDING_BYTES(0x10); // Reserved

    AccountSettings account_settings;
    INSERT_PADDING_BYTES(0xFC); // Reserved

    // nn::settings::system::AudioVolume
    std::array<u8, 0x8> audio_volume_type0;
    std::array<u8, 0x8> audio_volume_type1;
    AudioOutputMode audio_output_mode_hdmi;
    AudioOutputMode audio_output_mode_speaker;
    AudioOutputMode audio_output_mode_headphone;
    bool force_mute_on_headphone_removed;
    INSERT_PADDING_BYTES(0x3);
    s32 headphone_volume_warning_count;
    bool heaphone_volume_update_flag;
    INSERT_PADDING_BYTES(0x3);
    // nn::settings::system::AudioVolume
    std::array<u8, 0x8> audio_volume_type2;
    AudioOutputMode audio_output_mode_type3;
    AudioOutputMode audio_output_mode_type4;
    bool hearing_protection_safeguard_flag;
    INSERT_PADDING_BYTES(0x3);
    INSERT_PADDING_BYTES(0x4); // Reserved
    s64 hearing_protection_safeguard_remaining_time;
    INSERT_PADDING_BYTES(0x38); // Reserved

    bool console_information_upload_flag;
    INSERT_PADDING_BYTES(0x3);
    INSERT_PADDING_BYTES(0x3C); // Reserved

    bool automatic_application_download_flag;
    INSERT_PADDING_BYTES(0x3);
    INSERT_PADDING_BYTES(0x4); // Reserved

    NotificationSettings notification_settings;
    INSERT_PADDING_BYTES(0x60); // Reserved

    // nn::settings::system::AccountNotificationSettings
    s32 account_notification_settings_count;
    INSERT_PADDING_BYTES(0xC); // Reserved
    std::array<AccountNotificationSettings, 8> account_notification_settings;
    INSERT_PADDING_BYTES(0x140); // Reserved

    f32 vibration_master_volume;

    bool usb_full_key_enable_flag;
    INSERT_PADDING_BYTES(0x3);

    // nn::settings::system::AnalogStickUserCalibration
    std::array<u8, 0x10> analog_stick_user_calibration_left;
    std::array<u8, 0x10> analog_stick_user_calibration_right;

    TouchScreenMode touch_screen_mode;
    INSERT_PADDING_BYTES(0x14); // Reserved

    TvSettings tv_settings;

    // nn::settings::system::Edid
    std::array<u8, 0x100> edid;
    INSERT_PADDING_BYTES(0x2E0); // Reserved

    // nn::settings::system::DataDeletionSettings
    std::array<u8, 0x8> data_deletion_settings;
    INSERT_PADDING_BYTES(0x38); // Reserved

    // nn::ncm::ProgramId
    std::array<u8, 0x8> initial_system_applet_program_id;
    std::array<u8, 0x8> overlay_disp_program_id;
    INSERT_PADDING_BYTES(0x4); // Reserved

    bool requires_run_repair_time_reviser;
    INSERT_PADDING_BYTES(0x6B); // Reserved

    // nn::time::LocationName
    Service::PSC::Time::LocationName device_time_zone_location_name;
    INSERT_PADDING_BYTES(0x4); // Reserved
    // nn::time::SteadyClockTimePoint
    Service::PSC::Time::SteadyClockTimePoint device_time_zone_location_updated_time;

    INSERT_PADDING_BYTES(0xC0); // Reserved

    // nn::settings::system::PrimaryAlbumStorage
    PrimaryAlbumStorage primary_album_storage;
    INSERT_PADDING_BYTES(0x3C); // Reserved

    bool usb_30_enable_flag;
    INSERT_PADDING_BYTES(0x3);
    bool usb_30_host_enable_flag;
    INSERT_PADDING_BYTES(0x3);
    bool usb_30_device_enable_flag;
    INSERT_PADDING_BYTES(0x3);
    INSERT_PADDING_BYTES(0x34); // Reserved

    bool nfc_enable_flag;
    INSERT_PADDING_BYTES(0x3);
    INSERT_PADDING_BYTES(0x3C); // Reserved

    // nn::settings::system::SleepSettings
    SleepSettings sleep_settings;
    INSERT_PADDING_BYTES(0x34); // Reserved

    // nn::settings::system::EulaVersion
    s32 eula_version_count;
    INSERT_PADDING_BYTES(0xC); // Reserved
    std::array<EulaVersion, 32> eula_versions;
    INSERT_PADDING_BYTES(0x200); // Reserved

    // nn::settings::system::DeviceNickName
    std::array<u8, 0x80> device_nick_name;
    INSERT_PADDING_BYTES(0x80); // Reserved

    bool auto_update_enable_flag;
    INSERT_PADDING_BYTES(0x3);
    INSERT_PADDING_BYTES(0x4C); // Reserved

    // nn::settings::system::BluetoothDevicesSettings
    std::array<std::array<u8, 0x200>, 14> bluetooth_device_settings_last_14;
    INSERT_PADDING_BYTES(0x2000); // Reserved

    // nn::settings::system::NxControllerSettings
    std::array<std::array<u8, 0x800>, 10> nx_controller_settings_data_from_offset_30;
};

static_assert(offsetof(SystemSettings, language_code) == 0x10);
static_assert(offsetof(SystemSettings, network_setting_count) == 0x50);
static_assert(offsetof(SystemSettings, network_settings_1B0) == 0x60);
static_assert(offsetof(SystemSettings, bluetooth_device_settings_count) == 0x8060);
static_assert(offsetof(SystemSettings, bluetooth_enable_flag) == 0x8064);
static_assert(offsetof(SystemSettings, bluetooth_device_settings_first_10) == 0x8070);
static_assert(offsetof(SystemSettings, ldn_channel) == 0x9470);
static_assert(offsetof(SystemSettings, mii_author_id) == 0x94B0);
static_assert(offsetof(SystemSettings, nx_controller_settings_count) == 0x94F0);
static_assert(offsetof(SystemSettings, nx_controller_legacy_settings) == 0x9500);
static_assert(offsetof(SystemSettings, external_rtc_reset_flag) == 0x98F0);
static_assert(offsetof(SystemSettings, push_notification_activity_mode_on_sleep) == 0x9930);
static_assert(offsetof(SystemSettings, allowed_ssl_host_count) == 0x99F4);
static_assert(offsetof(SystemSettings, host_fs_mount_point) == 0x9A30);
static_assert(offsetof(SystemSettings, allowed_ssl_hosts) == 0x9B30);
static_assert(offsetof(SystemSettings, ble_pairing_settings_count) == 0xA9F0);
static_assert(offsetof(SystemSettings, ble_pairing_settings) == 0xAA00);
static_assert(offsetof(SystemSettings, account_online_storage_settings_count) == 0xAF00);
static_assert(offsetof(SystemSettings, account_online_storage_settings) == 0xAF10);
static_assert(offsetof(SystemSettings, pctl_ready_flag) == 0xB110);
static_assert(offsetof(SystemSettings, theme_id_type0) == 0xB150);
static_assert(offsetof(SystemSettings, chinese_traditional_input_method) == 0xB350);
static_assert(offsetof(SystemSettings, button_config_registered_settings_count) == 0xB3D0);
static_assert(offsetof(SystemSettings, button_config_settings_count) == 0xB3E0);
static_assert(offsetof(SystemSettings, button_config_settings) == 0xB3E8);
static_assert(offsetof(SystemSettings, button_config_registered_settings_embedded) == 0x1D3E0);
static_assert(offsetof(SystemSettings, console_six_axis_sensor_acceleration_bias) == 0x29370);
static_assert(offsetof(SystemSettings, lock_screen_flag) == 0x29470);
static_assert(offsetof(SystemSettings, battery_percentage_flag) == 0x294A0);
static_assert(offsetof(SystemSettings, field_testing_flag) == 0x294C0);
static_assert(offsetof(SystemSettings, backlight_settings_mixed_up) == 0x294F0);
static_assert(offsetof(SystemSettings, user_system_clock_context) == 0x29580);
static_assert(offsetof(SystemSettings, network_system_clock_context) == 0x295A0);
static_assert(offsetof(SystemSettings, user_system_clock_automatic_correction_enabled) == 0x295C0);
static_assert(offsetof(SystemSettings, user_system_clock_automatic_correction_updated_time_point) ==
              0x295C8);
static_assert(offsetof(SystemSettings, account_settings) == 0x295F0);
static_assert(offsetof(SystemSettings, audio_volume_type0) == 0x296F0);
static_assert(offsetof(SystemSettings, hearing_protection_safeguard_remaining_time) == 0x29730);
static_assert(offsetof(SystemSettings, automatic_application_download_flag) == 0x297B0);
static_assert(offsetof(SystemSettings, notification_settings) == 0x297B8);
static_assert(offsetof(SystemSettings, account_notification_settings) == 0x29840);
static_assert(offsetof(SystemSettings, vibration_master_volume) == 0x29A40);
static_assert(offsetof(SystemSettings, analog_stick_user_calibration_left) == 0x29A48);
static_assert(offsetof(SystemSettings, touch_screen_mode) == 0x29A68);
static_assert(offsetof(SystemSettings, edid) == 0x29AA0);
static_assert(offsetof(SystemSettings, data_deletion_settings) == 0x29E80);
static_assert(offsetof(SystemSettings, requires_run_repair_time_reviser) == 0x29ED4);
static_assert(offsetof(SystemSettings, device_time_zone_location_name) == 0x29F40);
static_assert(offsetof(SystemSettings, nfc_enable_flag) == 0x2A0C0);
static_assert(offsetof(SystemSettings, eula_version_count) == 0x2A140);
static_assert(offsetof(SystemSettings, device_nick_name) == 0x2A950);
static_assert(offsetof(SystemSettings, bluetooth_device_settings_last_14) == 0x2AAA0);
static_assert(offsetof(SystemSettings, nx_controller_settings_data_from_offset_30) == 0x2E6A0);

static_assert(sizeof(SystemSettings) == 0x336A0, "SystemSettings has the wrong size!");

SystemSettings DefaultSystemSettings();

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "core/hle/service/server_manager.h"
#include "core/hle/service/set/factory_settings_server.h"
#include "core/hle/service/set/firmware_debug_settings_server.h"
#include "core/hle/service/set/settings.h"
#include "core/hle/service/set/settings_server.h"
#include "core/hle/service/set/system_settings_server.h"

namespace Service::Set {

void LoopProcess(Core::System& system) {
    auto server_manager = std::make_unique<ServerManager>(system);

    server_manager->RegisterNamedService("set", std::make_shared<ISettingsServer>(system));
    server_manager->RegisterNamedService("set:cal",
                                         std::make_shared<IFactorySettingsServer>(system));
    server_manager->RegisterNamedService("set:fd",
                                         std::make_shared<IFirmwareDebugSettingsServer>(system));
    server_manager->RegisterNamedService("set:sys",
                                         std::make_shared<ISystemSettingsServer>(system));
    ServerManager::RunServer(std::move(server_manager));
}

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

namespace Core {
class System;
}

namespace Service::Set {

void LoopProcess(Core::System& system);

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <algorithm>
#include <array>
#include <chrono>
#include "common/logging/log.h"
#include "common/settings.h"
#include "core/hle/service/cmif_serialization.h"
#include "core/hle/service/ipc_helpers.h"
#include "core/hle/service/set/key_code_map.h"
#include "core/hle/service/set/settings_server.h"

namespace Service::Set {
namespace {
constexpr std::size_t PRE_4_0_0_MAX_ENTRIES = 0xF;
constexpr std::size_t POST_4_0_0_MAX_ENTRIES = 0x40;

constexpr Result ResultInvalidLanguage{ErrorModule::Settings, 625};
constexpr Result ResultNullPointer{ErrorModule::Settings, 1261};

Result GetKeyCodeMapImpl(KeyCodeMap& out_key_code_map, KeyboardLayout keyboard_layout,
                         LanguageCode language_code) {
    switch (keyboard_layout) {
    case KeyboardLayout::Japanese:
        out_key_code_map = KeyCodeMapJapanese;
        R_SUCCEED();
    case KeyboardLayout::EnglishUs:
        out_key_code_map = KeyCodeMapEnglishUsInternational;
        if (language_code == LanguageCode::KO) {
            out_key_code_map = KeyCodeMapKorean;
        }
        if (language_code == LanguageCode::ZH_HANS) {
            out_key_code_map = KeyCodeMapChineseSimplified;
        }
        if (language_code == LanguageCode::ZH_HANT) {
            out_key_code_map = KeyCodeMapChineseTraditional;
        }
        R_SUCCEED();
    case KeyboardLayout::EnglishUk:
        out_key_code_map = KeyCodeMapEnglishUk;
        R_SUCCEED();
    case KeyboardLayout::French:
        out_key_code_map = KeyCodeMapFrench;
        R_SUCCEED();
    case KeyboardLayout::FrenchCa:
        out_key_code_map = KeyCodeMapFrenchCa;
        R_SUCCEED();
    case KeyboardLayout::Spanish:
        out_key_code_map = KeyCodeMapSpanish;
        R_SUCCEED();
    case KeyboardLayout::SpanishLatin:
        out_key_code_map = KeyCodeMapSpanishLatin;
        R_SUCCEED();
    case KeyboardLayout::German:
        out_key_code_map = KeyCodeMapGerman;
        R_SUCCEED();
    case KeyboardLayout::Italian:
        out_key_code_map = KeyCodeMapItalian;
        R_SUCCEED();
    case KeyboardLayout::Portuguese:
        out_key_code_map = KeyCodeMapPortuguese;
        R_SUCCEED();
    case KeyboardLayout::Russian:
        out_key_code_map = KeyCodeMapRussian;
        R_SUCCEED();
    case KeyboardLayout::Korean:
        out_key_code_map = KeyCodeMapKorean;
        R_SUCCEED();
    case KeyboardLayout::ChineseSimplified:
        out_key_code_map = KeyCodeMapChineseSimplified;
        R_SUCCEED();
    case KeyboardLayout::ChineseTraditional:
        out_key_code_map = KeyCodeMapChineseTraditional;
        R_SUCCEED();
    default:
    case KeyboardLayout::EnglishUsInternational:
        out_key_code_map = KeyCodeMapEnglishUsInternational;
        R_SUCCEED();
    }
}

} // Anonymous namespace

LanguageCode GetLanguageCodeFromIndex(std::size_t index) {
    return available_language_codes.at(index);
}

ISettingsServer::ISettingsServer(Core::System& system_) : ServiceFramework{system_, "set"} {
    // clang-format off
    static const FunctionInfo functions[] = {
        {0, C<&ISettingsServer::GetLanguageCode>, "GetLanguageCode"},
        {1, C<&ISettingsServer::GetAvailableLanguageCodes>, "GetAvailableLanguageCodes"},
        {2, C<&ISettingsServer::MakeLanguageCode>, "MakeLanguageCode"},
        {3, C<&ISettingsServer::GetAvailableLanguageCodeCount>, "GetAvailableLanguageCodeCount"},
        {4, C<&ISettingsServer::GetRegionCode>, "GetRegionCode"},
        {5, C<&ISettingsServer::GetAvailableLanguageCodes2>, "GetAvailableLanguageCodes2"},
        {6, C<&ISettingsServer::GetAvailableLanguageCodeCount2>, "GetAvailableLanguageCodeCount2"},
        {7, C<&ISettingsServer::GetKeyCodeMap>, "GetKeyCodeMap"},
        {8, C<&ISettingsServer::GetQuestFlag>, "GetQuestFlag"},
        {9, C<&ISettingsServer::GetKeyCodeMap2>, "GetKeyCodeMap2"},
        {10, nullptr, "GetFirmwareVersionForDebug"},
        {11, C<&ISettingsServer::GetDeviceNickName>, "GetDeviceNickName"},
    };
    // clang-format on

    RegisterHandlers(functions);
}

ISettingsServer::~ISettingsServer() = default;

Result ISettingsServer::GetLanguageCode(Out<LanguageCode> out_language_code) {
    LOG_DEBUG(Service_SET, "called {}", Settings::values.language_index.GetValue());

    *out_language_code = available_language_codes[static_cast<std::size_t>(
        Settings::values.language_index.GetValue())];
    R_SUCCEED();
}

Result ISettingsServer::GetAvailableLanguageCodes(
    Out<s32> out_count, OutArray<LanguageCode, BufferAttr_HipcPointer> out_language_codes) {
    LOG_DEBUG(Service_SET, "called");

    const std::size_t max_amount = std::min(PRE_4_0_0_MAX_ENTRIES, out_language_codes.size());
    *out_count = static_cast<s32>(std::min(available_language_codes.size(), max_amount));

    memcpy(out_language_codes.data(), available_language_codes.data(),
           static_cast<std::size_t>(*out_count) * sizeof(LanguageCode));

    R_SUCCEED();
}

Result ISettingsServer::MakeLanguageCode(Out<LanguageCode> out_language_code, Language language) {
    LOG_DEBUG(Service_SET, "called, language={}", language);

    const auto index = static_cast<std::size_t>(language);
    R_UNLESS(index < available_language_codes.size(), Set::ResultInvalidLanguage);

    *out_language_code = available_language_codes[index];
    R_SUCCEED();
}

Result ISettingsServer::GetAvailableLanguageCodeCount(Out<s32> out_count) {
    LOG_DEBUG(Service_SET, "called");

    *out_count = PRE_4_0_0_MAX_ENTRIES;
    R_SUCCEED();
}

Result ISettingsServer::GetRegionCode(Out<SystemRegionCode> out_region_code) {
    LOG_DEBUG(Service_SET, "called");

    *out_region_code = static_cast<SystemRegionCode>(Settings::values.region_index.GetValue());
    R_SUCCEED();
}

Result ISettingsServer::GetAvailableLanguageCodes2(
    Out<s32> out_count, OutArray<LanguageCode, BufferAttr_HipcMapAlias> language_codes) {
    LOG_DEBUG(Service_SET, "called");

    const std::size_t max_amount = std::min(POST_4_0_0_MAX_ENTRIES, language_codes.size());
    *out_count = static_cast<s32>(std::min(available_language_codes.size(), max_amount));

    memcpy(language_codes.data(), available_language_codes.data(),
           static_cast<std::size_t>(*out_count) * sizeof(LanguageCode));

    R_SUCCEED();
}

Result ISettingsServer::GetAvailableLanguageCodeCount2(Out<s32> out_count) {
    LOG_DEBUG(Service_SET, "called");

    *out_count = POST_4_0_0_MAX_ENTRIES;
    R_SUCCEED();
}

Result ISettingsServer::GetKeyCodeMap(
    OutLargeData<KeyCodeMap, BufferAttr_HipcMapAlias> out_key_code_map) {
    LOG_DEBUG(Service_SET, "called");

    R_UNLESS(out_key_code_map != nullptr, ResultNullPointer);

    const auto language_code =
        available_language_codes[static_cast<s32>(Settings::values.language_index.GetValue())];
    const auto key_code =
        std::find_if(language_to_layout.cbegin(), language_to_layout.cend(),
                     [=](const auto& element) { return element.first == language_code; });

    if (key_code == language_to_layout.cend()) {
        LOG_ERROR(Service_SET,
                  "Could not find keyboard layout for language index {}, defaulting to English us",
                  Settings::values.language_index.GetValue());
        *out_key_code_map = KeyCodeMapEnglishUsInternational;
        R_SUCCEED();
    }

    R_RETURN(GetKeyCodeMapImpl(*out_key_code_map, key_code->second, key_code->first));
}

Result ISettingsServer::GetQuestFlag(Out<bool> out_quest_flag) {
    LOG_DEBUG(Service_SET, "called");

    *out_quest_flag = Settings::values.quest_flag.GetValue();
    R_SUCCEED();
}

Result ISettingsServer::GetKeyCodeMap2(
    OutLargeData<KeyCodeMap, BufferAttr_HipcMapAlias> out_key_code_map) {
    LOG_DEBUG(Service_SET, "called");

    R_UNLESS(out_key_code_map != nullptr, ResultNullPointer);

    const auto language_code =
        available_language_codes[static_cast<s32>(Settings::values.language_index.GetValue())];
    const auto key_code =
        std::find_if(language_to_layout.cbegin(), language_to_layout.cend(),
                     [=](const auto& element) { return element.first == language_code; });

    if (key_code == language_to_layout.cend()) {
        LOG_ERROR(Service_SET,
                  "Could not find keyboard layout for language index {}, defaulting to English us",
                  Settings::values.language_index.GetValue());
        *out_key_code_map = KeyCodeMapEnglishUsInternational;
        R_SUCCEED();
    }

    R_RETURN(GetKeyCodeMapImpl(*out_key_code_map, key_code->second, key_code->first));
}

Result ISettingsServer::GetDeviceNickName(
    OutLargeData<std::array<u8, 0x80>, BufferAttr_HipcMapAlias> out_device_name) {
    LOG_DEBUG(Service_SET, "called");

    const std::size_t string_size =
        std::min(Settings::values.device_name.GetValue().size(), out_device_name->size());

    *out_device_name = {};
    memcpy(out_device_name->data(), Settings::values.device_name.GetValue().data(), string_size);
    R_SUCCEED();
}

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include "core/hle/service/cmif_types.h"
#include "core/hle/service/service.h"
#include "core/hle/service/set/settings_types.h"

namespace Core {
class System;
}

namespace Service::Set {
using KeyCodeMap = std::array<u8, 0x1000>;

LanguageCode GetLanguageCodeFromIndex(std::size_t idx);

class ISettingsServer final : public ServiceFramework<ISettingsServer> {
public:
    explicit ISettingsServer(Core::System& system_);
    ~ISettingsServer() override;

private:
    Result GetLanguageCode(Out<LanguageCode> out_language_code);

    Result GetAvailableLanguageCodes(Out<s32> out_count,
                                     OutArray<LanguageCode, BufferAttr_HipcPointer> language_codes);

    Result MakeLanguageCode(Out<LanguageCode> out_language_code, Language language);

    Result GetAvailableLanguageCodeCount(Out<s32> out_count);

    Result GetRegionCode(Out<SystemRegionCode> out_region_code);

    Result GetAvailableLanguageCodes2(
        Out<s32> out_count, OutArray<LanguageCode, BufferAttr_HipcMapAlias> language_codes);

    Result GetAvailableLanguageCodeCount2(Out<s32> out_count);

    Result GetKeyCodeMap(OutLargeData<KeyCodeMap, BufferAttr_HipcMapAlias> out_key_code_map);

    Result GetQuestFlag(Out<bool> out_quest_flag);

    Result GetKeyCodeMap2(OutLargeData<KeyCodeMap, BufferAttr_HipcMapAlias> out_key_code_map);

    Result GetDeviceNickName(
        OutLargeData<std::array<u8, 0x80>, BufferAttr_HipcMapAlias> out_device_name);
};

} // namespace Service::Set


code:
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later

#pragma once

#include <array>

#include "common/bit_field.h"
#include "common/common_funcs.h"
#include "common/common_types.h"
#include "common/uuid.h"
#include "core/hle/service/psc/time/common.h"

namespace Service::Set {
using SettingItemName = std::array<u8, 0x48>;

/// This is nn::settings::system::AudioOutputMode
enum class AudioOutputMode : u32 {
    ch_1,
    ch_2,
    ch_5_1,
    ch_7_1,
};

/// This is nn::settings::system::AudioOutputModeTarget
enum class AudioOutputModeTarget : u32 {
    None,
    Hdmi,
    Speaker,
    Headphone,
    Type3,
    Type4,
};

/// This is nn::settings::system::AudioVolumeTarget
enum class AudioVolumeTarget : u32 {
    Speaker,
    Headphone,
};

/// This is nn::settings::system::ClockSourceId
enum class ClockSourceId : u32 {
    NetworkSystemClock,
    SteadyClock,
};

/// This is nn::settings::system::CmuMode
enum class CmuMode : u32 {
    None,
    ColorInvert,
    HighContrast,
    GrayScale,
};

/// This is nn::settings::system::ChineseTraditionalInputMethod
enum class ChineseTraditionalInputMethod : u32 {
    Unknown0 = 0,
    Unknown1 = 1,
    Unknown2 = 2,
};

/// Indicates the current theme set by the system settings
enum class ColorSet : u32 {
    BasicWhite = 0,
    BasicBlack = 1,
};

/// This is nn::settings::system::ConsoleSleepPlan
enum class ConsoleSleepPlan : u32 {
    Sleep1Hour,
    Sleep2Hour,
    Sleep3Hour,
    Sleep6Hour,
    Sleep12Hour,
    Never,
};

/// This is nn::settings::system::ErrorReportSharePermission
enum class ErrorReportSharePermission : u32 {
    NotConfirmed,
    Granted,
    Denied,
};

/// This is nn::settings::system::EulaVersionClockType
enum class EulaVersionClockType : u32 {
    NetworkSystemClock,
    SteadyClock,
};

/// This is nn::settings::factory::RegionCode
enum class FactoryRegionCode : u32 {
    Japan,
    Usa,
    Europe,
    Australia,
    China,
    Korea,
    Taiwan,
};

/// This is nn::settings::system::FriendPresenceOverlayPermission
enum class FriendPresenceOverlayPermission : u8 {
    NotConfirmed,
    NoDisplay,
    FavoriteFriends,
    Friends,
};

enum class GetFirmwareVersionType {
    Version1,
    Version2,
};

/// This is nn::settings::system::HandheldSleepPlan
enum class HandheldSleepPlan : u32 {
    Sleep1Min,
    Sleep3Min,
    Sleep5Min,
    Sleep10Min,
    Sleep30Min,
    Never,
};

/// This is nn::settings::system::HdmiContentType
enum class HdmiContentType : u32 {
    None,
    Graphics,
    Cinema,
    Photo,
    Game,
};

enum class KeyboardLayout : u32 {
    Japanese = 0,
    EnglishUs = 1,
    EnglishUsInternational = 2,
    EnglishUk = 3,
    French = 4,
    FrenchCa = 5,
    Spanish = 6,
    SpanishLatin = 7,
    German = 8,
    Italian = 9,
    Portuguese = 10,
    Russian = 11,
    Korean = 12,
    ChineseSimplified = 13,
    ChineseTraditional = 14,
};

// This is nn::settings::Language
enum class Language : u32 {
    Japanese,
    AmericanEnglish,
    French,
    German,
    Italian,
    Spanish,
    Chinese,
    Korean,
    Dutch,
    Portiguesue,
    Russian,
    Taiwanese,
    BritishEnglish,
    CanadianFrench,
    LatinAmericanSpanish,
    SimplifiedCHhinese,
    TraditionalChinese,
    BrazilianPortuguese,
};

/// This is "nn::settings::LanguageCode", which is a NUL-terminated string stored in a u64.
enum class LanguageCode : u64 {
    JA = 0x000000000000616A,
    EN_US = 0x00000053552D6E65,
    FR = 0x0000000000007266,
    DE = 0x0000000000006564,
    IT = 0x0000000000007469,
    ES = 0x0000000000007365,
    ZH_CN = 0x0000004E432D687A,
    KO = 0x0000000000006F6B,
    NL = 0x0000000000006C6E,
    PT = 0x0000000000007470,
    RU = 0x0000000000007572,
    ZH_TW = 0x00000057542D687A,
    EN_GB = 0x00000042472D6E65,
    FR_CA = 0x00000041432D7266,
    ES_419 = 0x00003931342D7365,
    ZH_HANS = 0x00736E61482D687A,
    ZH_HANT = 0x00746E61482D687A,
    PT_BR = 0x00000052422D7470,
};

/// This is nn::settings::system::NotificationVolume
enum class NotificationVolume : u32 {
    Mute,
    Low,
    High,
};

/// This is nn::settings::system::PrimaryAlbumStorage
enum class PrimaryAlbumStorage : u32 {
    Nand,
    SdCard,
};

/// Indicates the current console is a retail or kiosk unit
enum class QuestFlag : u8 {
    Retail = 0,
    Kiosk = 1,
};

/// This is nn::settings::system::RgbRange
enum class RgbRange : u32 {
    Auto,
    Full,
    Limited,
};

/// This is nn::settings::system::RegionCode
enum class SystemRegionCode : u32 {
    Japan,
    Usa,
    Europe,
    Australia,
    HongKongTaiwanKorea,
    China,
};

/// This is nn::settings::system::TouchScreenMode
enum class TouchScreenMode : u32 {
    Stylus,
    Standard,
};

/// This is nn::settings::system::TvResolution
enum class TvResolution : u32 {
    Auto,
    Resolution1080p,
    Resolution720p,
    Resolution480p,
};

enum class PlatformRegion : s32 {
    Global = 1,
    Terra = 2,
};

constexpr std::array<LanguageCode, 18> available_language_codes = {{
    LanguageCode::JA,
    LanguageCode::EN_US,
    LanguageCode::FR,
    LanguageCode::DE,
    LanguageCode::IT,
    LanguageCode::ES,
    LanguageCode::ZH_CN,
    LanguageCode::KO,
    LanguageCode::NL,
    LanguageCode::PT,
    LanguageCode::RU,
    LanguageCode::ZH_TW,
    LanguageCode::EN_GB,
    LanguageCode::FR_CA,
    LanguageCode::ES_419,
    LanguageCode::ZH_HANS,
    LanguageCode::ZH_HANT,
    LanguageCode::PT_BR,
}};

static constexpr std::array<std::pair<LanguageCode, KeyboardLayout>, 18> language_to_layout{{
    {LanguageCode::JA, KeyboardLayout::Japanese},
    {LanguageCode::EN_US, KeyboardLayout::EnglishUs},
    {LanguageCode::FR, KeyboardLayout::French},
    {LanguageCode::DE, KeyboardLayout::German},
    {LanguageCode::IT, KeyboardLayout::Italian},
    {LanguageCode::ES, KeyboardLayout::Spanish},
    {LanguageCode::ZH_CN, KeyboardLayout::ChineseSimplified},
    {LanguageCode::KO, KeyboardLayout::Korean},
    {LanguageCode::NL, KeyboardLayout::EnglishUsInternational},
    {LanguageCode::PT, KeyboardLayout::Portuguese},
    {LanguageCode::RU, KeyboardLayout::Russian},
    {LanguageCode::ZH_TW, KeyboardLayout::ChineseTraditional},
    {LanguageCode::EN_GB, KeyboardLayout::EnglishUk},
    {LanguageCode::FR_CA, KeyboardLayout::FrenchCa},
    {LanguageCode::ES_419, KeyboardLayout::SpanishLatin},
    {LanguageCode::ZH_HANS, KeyboardLayout::ChineseSimplified},
    {LanguageCode::ZH_HANT, KeyboardLayout::ChineseTraditional},
    {LanguageCode::PT_BR, KeyboardLayout::Portuguese},
}};

/// This is nn::settings::system::AccountNotificationFlag
struct AccountNotificationFlag {
    union {
        u32 raw{};

        BitField<0, 1, u32> FriendOnlineFlag;
        BitField<1, 1, u32> FriendRequestFlag;
        BitField<8, 1, u32> CoralInvitationFlag;
    };
};
static_assert(sizeof(AccountNotificationFlag) == 4, "AccountNotificationFlag is an invalid size");

/// This is nn::settings::system::AccountSettings
struct AccountSettings {
    u32 flags;
};
static_assert(sizeof(AccountSettings) == 4, "AccountSettings is an invalid size");

/// This is nn::settings::system::DataDeletionFlag
struct DataDeletionFlag {
    union {
        u32 raw{};

        BitField<0, 1, u32> AutomaticDeletionFlag;
    };
};
static_assert(sizeof(DataDeletionFlag) == 4, "DataDeletionFlag is an invalid size");

/// This is nn::settings::system::InitialLaunchFlag
struct InitialLaunchFlag {
    union {
        u32 raw{};

        BitField<0, 1, u32> InitialLaunchCompletionFlag;
        BitField<8, 1, u32> InitialLaunchUserAdditionFlag;
        BitField<16, 1, u32> InitialLaunchTimestampFlag;
    };
};
static_assert(sizeof(InitialLaunchFlag) == 4, "InitialLaunchFlag is an invalid size");

/// This is nn::settings::system::SleepFlag
struct SleepFlag {
    union {
        u32 raw{};

        BitField<0, 1, u32> SleepsWhilePlayingMedia;
        BitField<1, 1, u32> WakesAtPowerStateChange;
    };
};
static_assert(sizeof(SleepFlag) == 4, "TvFlag is an invalid size");

/// This is nn::settings::system::NotificationFlag
struct NotificationFlag {
    union {
        u32 raw{};

        BitField<0, 1, u32> RingtoneFlag;
        BitField<1, 1, u32> DownloadCompletionFlag;
        BitField<8, 1, u32> EnablesNews;
        BitField<9, 1, u32> IncomingLampFlag;
    };
};
static_assert(sizeof(NotificationFlag) == 4, "NotificationFlag is an invalid size");

struct PlatformConfig {
    union {
        u32 raw{};
        BitField<0, 1, u32> has_rail_interface;
        BitField<1, 1, u32> has_sio_mcu;
    };
};
static_assert(sizeof(PlatformConfig) == 0x4, "PlatformConfig is an invalid size");

/// This is nn::settings::system::TvFlag
struct TvFlag {
    union {
        u32 raw{};

        BitField<0, 1, u32> Allows4k;
        BitField<1, 1, u32> Allows3d;
        BitField<2, 1, u32> AllowsCec;
        BitField<3, 1, u32> PreventsScreenBurnIn;
    };
};
static_assert(sizeof(TvFlag) == 4, "TvFlag is an invalid size");

/// This is nn::settings::system::UserSelectorFlag
struct UserSelectorFlag {
    union {
        u32 raw{};

        BitField<0, 1, u32> SkipIfSingleUser;
        BitField<31, 1, u32> Unknown;
    };
};
static_assert(sizeof(UserSelectorFlag) == 4, "UserSelectorFlag is an invalid size");

/// This is nn::settings::system::AccountNotificationSettings
struct AccountNotificationSettings {
    Common::UUID uid;
    AccountNotificationFlag flags;
    FriendPresenceOverlayPermission friend_presence_permission;
    FriendPresenceOverlayPermission friend_invitation_permission;
    INSERT_PADDING_BYTES(0x2);
};
static_assert(sizeof(AccountNotificationSettings) == 0x18,
              "AccountNotificationSettings is an invalid size");

/// This is nn::settings::factory::BatteryLot
struct BatteryLot {
    std::array<char, 0x18> lot_number;
};
static_assert(sizeof(BatteryLot) == 0x18, "BatteryLot is an invalid size");

/// This is nn::settings::system::EulaVersion
struct EulaVersion {
    u32 version;
    SystemRegionCode region_code;
    EulaVersionClockType clock_type;
    INSERT_PADDING_BYTES(0x4);
    Service::PSC::Time::SystemClockContext system_clock_context;
};
static_assert(sizeof(EulaVersion) == 0x30, "EulaVersion is incorrect size");

struct FirmwareVersionFormat {
    u8 major;
    u8 minor;
    u8 micro;
    INSERT_PADDING_BYTES_NOINIT(1);
    u8 revision_major;
    u8 revision_minor;
    INSERT_PADDING_BYTES_NOINIT(2);
    std::array<char, 0x20> platform;
    std::array<u8, 0x40> version_hash;
    std::array<char, 0x18> display_version;
    std::array<char, 0x80> display_title;
};
static_assert(sizeof(FirmwareVersionFormat) == 0x100, "FirmwareVersionFormat is an invalid size");
static_assert(std::is_trivial_v<FirmwareVersionFormat>,
              "FirmwareVersionFormat type must be trivially copyable.");

/// This is nn::settings::system::HomeMenuScheme
struct HomeMenuScheme {
    u32 main;
    u32 back;
    u32 sub;
    u32 bezel;
    u32 extra;
};
static_assert(sizeof(HomeMenuScheme) == 0x14, "HomeMenuScheme is incorrect size");

/// This is nn::settings::system::InitialLaunchSettings
struct InitialLaunchSettings {
    InitialLaunchFlag flags;
    INSERT_PADDING_BYTES(0x4);
    Service::PSC::Time::SteadyClockTimePoint timestamp;
};
static_assert(sizeof(InitialLaunchSettings) == 0x20, "InitialLaunchSettings is incorrect size");

#pragma pack(push, 4)
struct InitialLaunchSettingsPacked {
    InitialLaunchFlag flags;
    Service::PSC::Time::SteadyClockTimePoint timestamp;
};
#pragma pack(pop)
static_assert(sizeof(InitialLaunchSettingsPacked) == 0x1C,
              "InitialLaunchSettingsPacked is incorrect size");

/// This is nn::settings::system::NotificationTime
struct NotificationTime {
    u32 hour;
    u32 minute;
};
static_assert(sizeof(NotificationTime) == 0x8, "NotificationTime is an invalid size");

/// This is nn::settings::system::NotificationSettings
struct NotificationSettings {
    NotificationFlag flags;
    NotificationVolume volume;
    NotificationTime start_time;
    NotificationTime stop_time;
};
static_assert(sizeof(NotificationSettings) == 0x18, "NotificationSettings is an invalid size");

/// This is nn::settings::factory::SerialNumber
struct SerialNumber {
    std::array<char, 0x18> serial_number;
};
static_assert(sizeof(SerialNumber) == 0x18, "SerialNumber is an invalid size");

/// This is nn::settings::system::SleepSettings
struct SleepSettings {
    SleepFlag flags;
    HandheldSleepPlan handheld_sleep_plan;
    ConsoleSleepPlan console_sleep_plan;
};
static_assert(sizeof(SleepSettings) == 0xc, "SleepSettings is incorrect size");

/// This is nn::settings::system::TvSettings
struct TvSettings {
    TvFlag flags;
    TvResolution tv_resolution;
    HdmiContentType hdmi_content_type;
    RgbRange rgb_range;
    CmuMode cmu_mode;
    u32 tv_underscan;
    f32 tv_gama;
    f32 contrast_ratio;
};
static_assert(sizeof(TvSettings) == 0x20, "TvSettings is an invalid size");

} // namespace Service::Set