1 | // Aseprite |
---|---|
2 | // Copyright (C) 2018 David Capello |
3 | // |
4 | // This program is distributed under the terms of |
5 | // the End-User License Agreement for Aseprite. |
6 | |
7 | #ifndef APP_UI_PREF_WIDGET_H_INCLUDED |
8 | #define APP_UI_PREF_WIDGET_H_INCLUDED |
9 | #pragma once |
10 | |
11 | #include "app/pref/preferences.h" |
12 | #include "base/split_string.h" |
13 | #include "base/exception.h" |
14 | #include "ui/message.h" |
15 | #include "ui/register_message.h" |
16 | |
17 | namespace app { |
18 | |
19 | extern ui::RegisterMessage kSavePreferencesMessage; |
20 | |
21 | template<class Base> |
22 | class BoolPrefWidget : public Base { |
23 | public: |
24 | template<typename...Args> |
25 | BoolPrefWidget(Args&&...args) |
26 | : Base(args...) |
27 | , m_option(nullptr) { |
28 | } |
29 | |
30 | void setPref(const char* prefString) { |
31 | ASSERT(prefString); |
32 | |
33 | std::vector<std::string> parts; |
34 | base::split_string(prefString, parts, "."); |
35 | if (parts.size() == 2) { |
36 | auto& pref = Preferences::instance(); |
37 | auto section = pref.section(parts[0].c_str()); |
38 | if (!section) |
39 | throw base::Exception("Preference section not found: %s", prefString); |
40 | |
41 | m_option = |
42 | dynamic_cast<Option<bool>*>( |
43 | section->option(parts[1].c_str())); |
44 | |
45 | if (!m_option) |
46 | throw base::Exception("Preference option not found: %s", prefString); |
47 | |
48 | // Load option value |
49 | this->setSelected((*m_option)()); |
50 | } |
51 | } |
52 | |
53 | void resetWithDefaultValue() { |
54 | // Reset to default value in preferences |
55 | if (m_option) |
56 | this->setSelected(m_option->defaultValue()); |
57 | } |
58 | |
59 | protected: |
60 | bool onProcessMessage(ui::Message* msg) override { |
61 | if (msg->type() == kSavePreferencesMessage) { |
62 | ASSERT(m_option); |
63 | |
64 | // Update Option value. |
65 | (*m_option)(this->isSelected()); |
66 | } |
67 | return Base::onProcessMessage(msg); |
68 | } |
69 | |
70 | private: |
71 | Option<bool>* m_option; |
72 | }; |
73 | |
74 | } // namespace app |
75 | |
76 | #endif |
77 |