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