Skip to content

Commit 803d647

Browse files
committed
add change listeners to utils.Preferences
set()/unset() notify registered listeners when a value actually changes; loading stays silent. per the #1104 todo list.
1 parent cedd0dc commit 803d647

1 file changed

Lines changed: 49 additions & 2 deletions

File tree

‎app/utils/src/main/java/processing/utils/Preferences.java‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,10 @@
3333
import java.nio.charset.StandardCharsets;
3434
import java.util.Arrays;
3535
import java.util.HashMap;
36+
import java.util.List;
3637
import java.util.Map;
38+
import java.util.Objects;
39+
import java.util.concurrent.CopyOnWriteArrayList;
3740

3841

3942
/**
@@ -76,6 +79,45 @@ public class Preferences {
7679
static File preferencesFile;
7780
static private boolean initialized = false;
7881

82+
static private final List<ChangeListener> listeners =
83+
new CopyOnWriteArrayList<>();
84+
85+
86+
/**
87+
* Callback for preference changes made through set() or unset().
88+
* Loading (init or otherwise) does not fire events: listeners are for
89+
* reacting to changes, not for observing startup.
90+
*/
91+
public interface ChangeListener {
92+
/**
93+
* @param key the preference that changed
94+
* @param value the new value, or null if the key was removed
95+
*/
96+
void preferenceChanged(String key, String value);
97+
}
98+
99+
100+
static public void addChangeListener(ChangeListener listener) {
101+
listeners.add(listener);
102+
}
103+
104+
105+
static public void removeChangeListener(ChangeListener listener) {
106+
listeners.remove(listener);
107+
}
108+
109+
110+
static private void fireChange(String key, String value) {
111+
for (ChangeListener listener : listeners) {
112+
try {
113+
listener.preferenceChanged(key, value);
114+
} catch (Exception e) {
115+
// one broken listener shouldn't prevent the change (or the others)
116+
e.printStackTrace();
117+
}
118+
}
119+
}
120+
79121

80122
/**
81123
* Load the bundled defaults followed by the user's preferences.txt from
@@ -323,12 +365,17 @@ static public String getDefault(String attribute) {
323365

324366

325367
static public void set(String attribute, String value) {
326-
table.put(attribute, value);
368+
String previous = table.put(attribute, value);
369+
if (!Objects.equals(previous, value)) {
370+
fireChange(attribute, value);
371+
}
327372
}
328373

329374

330375
static public void unset(String attribute) {
331-
table.remove(attribute);
376+
if (table.remove(attribute) != null) {
377+
fireChange(attribute, null);
378+
}
332379
}
333380

334381

0 commit comments

Comments
 (0)