xref: /haiku/src/kits/debugger/settings/generic/Settings.cpp (revision 02354704729d38c3b078c696adc1bbbd33cbcf72)
1 /*
2  * Copyright 2013, Rene Gollent, rene@gollent.com.
3  * Copyright 2009, Ingo Weinhold, ingo_weinhold@gmx.de.
4  * Distributed under the terms of the MIT License.
5  */
6 
7 
8 #include "Settings.h"
9 
10 #include <AutoLocker.h>
11 
12 #include "SettingsDescription.h"
13 
14 
15 // #pragma mark - Settings
16 
17 
18 Settings::Settings(SettingsDescription* description)
19 	:
20 	fLock("settings"),
21 	fDescription(description)
22 {
23 	fDescription->AcquireReference();
24 }
25 
26 
27 Settings::~Settings()
28 {
29 	fDescription->ReleaseReference();
30 }
31 
32 
33 status_t
34 Settings::Init()
35 {
36 	return fLock.InitCheck();
37 }
38 
39 
40 BVariant
41 Settings::Value(Setting* setting) const
42 {
43 	AutoLocker<BLocker> locker(fLock);
44 
45 	BVariant value;
46 	return value.SetFromMessage(fValues, setting->ID()) == B_OK
47 		? value : setting->DefaultValue();
48 }
49 
50 
51 BVariant
52 Settings::Value(const char* settingID) const
53 {
54 	AutoLocker<BLocker> locker(fLock);
55 
56 	BVariant value;
57 	if (value.SetFromMessage(fValues, settingID) == B_OK)
58 		return value;
59 
60 	Setting* setting = fDescription->SettingByID(settingID);
61 	return setting != NULL ? setting->DefaultValue() : value;
62 }
63 
64 
65 bool
66 Settings::SetValue(Setting* setting, const BVariant& value)
67 {
68 	AutoLocker<BLocker> locker(fLock);
69 
70 	// remove the message field and re-add it with the new value
71 	const char* fieldName = setting->ID();
72 	fValues.RemoveName(fieldName);
73 
74 	bool success = value.AddToMessage(fValues, fieldName) == B_OK;
75 
76 	// notify the listeners
77 	int32 count = fListeners.CountItems();
78 	for (int32 i = count - 1; i >= 0; i--)
79 		fListeners.ItemAt(i)->SettingValueChanged(setting);
80 
81 	return success;
82 }
83 
84 
85 bool
86 Settings::RestoreValues(const BMessage& message)
87 {
88 	AutoLocker<BLocker> locker(fLock);
89 
90 	for (int32 i = 0; i < fDescription->CountSettings(); i++) {
91 		Setting* setting = fDescription->SettingAt(i);
92 		BVariant value;
93 		if (value.SetFromMessage(message, setting->ID()) == B_OK) {
94 			if (!SetValue(setting, value))
95 				return false;
96 		}
97 	}
98 
99 	return true;
100 }
101 
102 
103 SettingsOption*
104 Settings::OptionValue(OptionsSetting* setting) const
105 {
106 	BVariant value = Value(setting);
107 	return value.Type() == B_STRING_TYPE
108 		? setting->OptionByID(value.ToString())
109 		: setting->DefaultOption();
110 }
111 
112 
113 bool
114 Settings::AddListener(Listener* listener)
115 {
116 	AutoLocker<BLocker> locker(fLock);
117 	return fListeners.AddItem(listener);
118 }
119 
120 
121 void
122 Settings::RemoveListener(Listener* listener)
123 {
124 	AutoLocker<BLocker> locker(fLock);
125 	fListeners.RemoveItem(listener);
126 }
127 
128 
129 // #pragma mark - Listener
130 
131 
132 Settings::Listener::~Listener()
133 {
134 }
135