1package eu.siacs.conversations;
2
3import android.app.Application;
4import android.content.Context;
5import android.content.SharedPreferences;
6import android.preference.PreferenceManager;
7
8import androidx.appcompat.app.AppCompatDelegate;
9
10import com.google.android.material.color.DynamicColors;
11import com.google.android.material.color.DynamicColorsOptions;
12
13public class Conversations extends Application {
14
15 @Override
16 public void onCreate() {
17 super.onCreate();
18 applyThemeSettings();
19 }
20
21 public void applyThemeSettings() {
22 final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
23 if (sharedPreferences == null) {
24 return;
25 }
26 applyThemeSettings(sharedPreferences);
27 }
28
29 private void applyThemeSettings(final SharedPreferences sharedPreferences) {
30 AppCompatDelegate.setDefaultNightMode(getDesiredNightMode(this, sharedPreferences));
31 var dynamicColorsOptions =
32 new DynamicColorsOptions.Builder()
33 .setPrecondition((activity, t) -> isDynamicColorsDesired(activity))
34 .build();
35 DynamicColors.applyToActivitiesIfAvailable(this, dynamicColorsOptions);
36 }
37
38 public static int getDesiredNightMode(final Context context) {
39 final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
40 if (sharedPreferences == null) {
41 return AppCompatDelegate.getDefaultNightMode();
42 }
43 return getDesiredNightMode(context, sharedPreferences);
44 }
45
46 public static boolean isDynamicColorsDesired(final Context context) {
47 final var preferences = PreferenceManager.getDefaultSharedPreferences(context);
48 return preferences.getBoolean("dynamic_colors", false);
49 }
50
51 private static int getDesiredNightMode(
52 final Context context, final SharedPreferences sharedPreferences) {
53 final String theme =
54 sharedPreferences.getString("theme", context.getString(R.string.theme));
55 return getDesiredNightMode(theme);
56 }
57
58 public static int getDesiredNightMode(final String theme) {
59 if ("automatic".equals(theme)) {
60 return AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
61 } else if ("light".equals(theme)) {
62 return AppCompatDelegate.MODE_NIGHT_NO;
63 } else {
64 return AppCompatDelegate.MODE_NIGHT_YES;
65 }
66 }
67}