]> git.ktnx.net Git - mobile-ledger-staging.git/blob - app/src/main/java/net/ktnx/mobileledger/model/Data.java
fixed a hard to reproduce crash upon returning to the app
[mobile-ledger-staging.git] / app / src / main / java / net / ktnx / mobileledger / model / Data.java
1 /*
2  * Copyright © 2020 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * MoLe is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.model;
19
20 import android.database.Cursor;
21 import android.database.sqlite.SQLiteDatabase;
22
23 import androidx.annotation.NonNull;
24 import androidx.annotation.Nullable;
25 import androidx.lifecycle.LifecycleOwner;
26 import androidx.lifecycle.MutableLiveData;
27 import androidx.lifecycle.Observer;
28
29 import net.ktnx.mobileledger.App;
30 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
31 import net.ktnx.mobileledger.utils.LockHolder;
32 import net.ktnx.mobileledger.utils.Locker;
33 import net.ktnx.mobileledger.utils.Logger;
34 import net.ktnx.mobileledger.utils.MLDB;
35 import net.ktnx.mobileledger.utils.ObservableValue;
36
37 import java.text.NumberFormat;
38 import java.util.ArrayList;
39 import java.util.Date;
40 import java.util.List;
41 import java.util.Locale;
42 import java.util.Objects;
43 import java.util.concurrent.atomic.AtomicInteger;
44
45 import static net.ktnx.mobileledger.utils.Logger.debug;
46
47 public final class Data {
48     public static final MutableLiveData<Boolean> backgroundTasksRunning =
49             new MutableLiveData<>(false);
50     public static final MutableLiveData<RetrieveTransactionsTask.Progress> backgroundTaskProgress =
51             new MutableLiveData<>();
52     public static final MutableLiveData<ArrayList<MobileLedgerProfile>> profiles =
53             new MutableLiveData<>(null);
54     public static final MutableLiveData<Currency.Position> currencySymbolPosition =
55             new MutableLiveData<>();
56     public static final MutableLiveData<Boolean> currencyGap = new MutableLiveData<>(true);
57     public static final MutableLiveData<Locale> locale = new MutableLiveData<>();
58     public static final MutableLiveData<Boolean> drawerOpen = new MutableLiveData<>(false);
59     public static final MutableLiveData<Date> lastUpdateDate = new MutableLiveData<>(null);
60     public static final MutableLiveData<Integer> lastUpdateTransactionCount =
61             new MutableLiveData<>(0);
62     public static final MutableLiveData<Integer> lastUpdateAccountCount = new MutableLiveData<>(0);
63     public static final ObservableValue<String> lastTransactionsUpdateText =
64             new ObservableValue<>();
65     public static final ObservableValue<String> lastAccountsUpdateText = new ObservableValue<>();
66     private static final MutableLiveData<MobileLedgerProfile> profile =
67             new InertMutableLiveData<>();
68     private static final AtomicInteger backgroundTaskCount = new AtomicInteger(0);
69     private static final Locker profilesLocker = new Locker();
70
71     static {
72         locale.setValue(Locale.getDefault());
73     }
74
75     @NonNull
76     public static MobileLedgerProfile getProfile() {
77         return Objects.requireNonNull(profile.getValue());
78     }
79     public static void backgroundTaskStarted() {
80         int cnt = backgroundTaskCount.incrementAndGet();
81         debug("data",
82                 String.format(Locale.ENGLISH, "background task count is %d after incrementing",
83                         cnt));
84         backgroundTasksRunning.postValue(cnt > 0);
85     }
86     public static void backgroundTaskFinished() {
87         int cnt = backgroundTaskCount.decrementAndGet();
88         debug("data",
89                 String.format(Locale.ENGLISH, "background task count is %d after decrementing",
90                         cnt));
91         backgroundTasksRunning.postValue(cnt > 0);
92     }
93     public static void setCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
94         MLDB.setOption(MLDB.OPT_PROFILE_UUID, newProfile.getUuid());
95         profile.setValue(newProfile);
96     }
97     public static void postCurrentProfile(@NonNull MobileLedgerProfile newProfile) {
98         MLDB.setOption(MLDB.OPT_PROFILE_UUID, newProfile.getUuid());
99         profile.postValue(newProfile);
100     }
101     public static int getProfileIndex(MobileLedgerProfile profile) {
102         try (LockHolder ignored = profilesLocker.lockForReading()) {
103             List<MobileLedgerProfile> prList = profiles.getValue();
104             if (prList == null)
105                 throw new AssertionError();
106             for (int i = 0; i < prList.size(); i++) {
107                 MobileLedgerProfile p = prList.get(i);
108                 if (p.equals(profile))
109                     return i;
110             }
111
112             return -1;
113         }
114     }
115     @SuppressWarnings("WeakerAccess")
116     public static int getProfileIndex(String profileUUID) {
117         try (LockHolder ignored = profilesLocker.lockForReading()) {
118             List<MobileLedgerProfile> prList = profiles.getValue();
119             if (prList == null)
120                 throw new AssertionError();
121             for (int i = 0; i < prList.size(); i++) {
122                 MobileLedgerProfile p = prList.get(i);
123                 if (p.getUuid()
124                      .equals(profileUUID))
125                     return i;
126             }
127
128             return -1;
129         }
130     }
131     public static int retrieveCurrentThemeIdFromDb() {
132         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
133         if (profileUUID == null)
134             return -1;
135
136         SQLiteDatabase db = App.getDatabase();
137         try (Cursor c = db.rawQuery("SELECT theme from profiles where uuid=?",
138                 new String[]{profileUUID}))
139         {
140             if (c.moveToNext())
141                 return c.getInt(0);
142         }
143
144         return -1;
145     }
146     @Nullable
147     public static MobileLedgerProfile getProfile(String profileUUID) {
148         MobileLedgerProfile profile;
149         try (LockHolder readLock = profilesLocker.lockForReading()) {
150             List<MobileLedgerProfile> prList = profiles.getValue();
151             if ((prList == null) || prList.isEmpty()) {
152                 readLock.close();
153                 try (LockHolder ignored = profilesLocker.lockForWriting()) {
154                     profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
155                 }
156             }
157             else {
158                 int i = getProfileIndex(profileUUID);
159                 if (i == -1)
160                     i = 0;
161                 profile = prList.get(i);
162             }
163         }
164         return profile;
165     }
166     public static void refreshCurrencyData(Locale locale) {
167         NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
168         java.util.Currency currency = formatter.getCurrency();
169         String symbol = currency != null ? currency.getSymbol() : "";
170         Logger.debug("locale", String.format(
171                 "Discovering currency symbol position for locale %s (currency is %s; symbol is %s)",
172                 locale.toString(), currency != null ? currency.toString() : "<none>", symbol));
173         String formatted = formatter.format(1234.56f);
174         Logger.debug("locale", String.format("1234.56 formats as '%s'", formatted));
175
176         if (formatted.startsWith(symbol)) {
177             currencySymbolPosition.setValue(Currency.Position.before);
178
179             // is the currency symbol directly followed by the first formatted digit?
180             final char canary = formatted.charAt(symbol.length());
181             currencyGap.setValue(canary != '1');
182         }
183         else if (formatted.endsWith(symbol)) {
184             currencySymbolPosition.setValue(Currency.Position.after);
185
186             // is the currency symbol directly preceded bu the last formatted digit?
187             final char canary = formatted.charAt(formatted.length() - symbol.length() - 1);
188             currencyGap.setValue(canary != '6');
189         }
190         else
191             currencySymbolPosition.setValue(Currency.Position.none);
192     }
193
194     public static void observeProfile(LifecycleOwner lifecycleOwner,
195                                       Observer<MobileLedgerProfile> observer) {
196         profile.observe(lifecycleOwner, observer);
197     }
198     public synchronized static MobileLedgerProfile initProfile() {
199         MobileLedgerProfile currentProfile = profile.getValue();
200         if (currentProfile != null)
201             return currentProfile;
202
203         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
204         MobileLedgerProfile startupProfile = getProfile(profileUUID);
205         if (startupProfile != null)
206             setCurrentProfile(startupProfile);
207         Logger.debug("profile", "initProfile() returning " + startupProfile);
208         return startupProfile;
209     }
210
211     public static void removeProfileObservers(LifecycleOwner owner) {
212         profile.removeObservers(owner);
213     }
214 }