blob: de11e84a4ed3bc1595b8497d4fc577e8ea61df4d [file] [log] [blame]
Matt Spinler1a309f72023-04-04 13:12:19 -05001#pragma once
2
3#include "config.h"
4
5#include "power_button_profile.hpp"
6
7#include <memory>
8#include <unordered_map>
9
10namespace phosphor::button
11{
12
13using powerButtonProfileCreator =
14 std::function<std::unique_ptr<PowerButtonProfile>(sdbusplus::bus_t& bus)>;
15
16/**
17 * @class PowerButtonProfileFactory
18 *
19 * Creates the custom power button profile class if one is set with
20 * the 'power-button-profile' meson option.
21 *
22 * The createProfile() method will return a nullptr if no custom
23 * profile is enabled.
24 */
25class PowerButtonProfileFactory
26{
27 public:
28 static PowerButtonProfileFactory& instance()
29 {
30 static PowerButtonProfileFactory factory;
31 return factory;
32 }
33
34 template <typename T>
35 void addToRegistry()
36 {
37 profileRegistry[std::string(T::getName())] = [](sdbusplus::bus_t& bus) {
38 return std::make_unique<T>(bus);
39 };
40 }
41
42 std::unique_ptr<PowerButtonProfile> createProfile(sdbusplus::bus_t& bus)
43 {
44 // Find the creator method named after the
45 // 'power-button-profile' option value.
46 auto objectIter = profileRegistry.find(POWER_BUTTON_PROFILE);
47 if (objectIter != profileRegistry.end())
48 {
49 return objectIter->second(bus);
50 }
51 else
52 {
53 return nullptr;
54 }
55 }
56
57 private:
58 PowerButtonProfileFactory() = default;
59
60 std::unordered_map<std::string, powerButtonProfileCreator> profileRegistry;
61};
62
63/**
64 * @brief Registers a power button profile with the factory.
65 *
66 * Declare a static instance of this at the top of the profile
67 * .cpp file like:
68 * static PowerButtonProfileRegister<MyClass> register;
69 */
70template <class T>
71class PowerButtonProfileRegister
72{
73 public:
74 PowerButtonProfileRegister()
75 {
76 PowerButtonProfileFactory::instance().addToRegistry<T>();
77 }
78};
79} // namespace phosphor::button