]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
store the theme Id in the preferences so that no DB is needed to access it
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / MainActivity.java
1 /*
2  * Copyright © 2019 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.ui.activity;
19
20 import android.content.Intent;
21 import android.content.SharedPreferences;
22 import android.content.pm.PackageInfo;
23 import android.content.pm.ShortcutInfo;
24 import android.content.pm.ShortcutManager;
25 import android.content.res.ColorStateList;
26 import android.graphics.Color;
27 import android.graphics.drawable.Icon;
28 import android.os.AsyncTask;
29 import android.os.Build;
30 import android.os.Bundle;
31 import android.util.Log;
32 import android.view.View;
33 import android.view.ViewGroup;
34 import android.view.ViewPropertyAnimator;
35 import android.view.animation.Animation;
36 import android.view.animation.AnimationUtils;
37 import android.widget.LinearLayout;
38 import android.widget.ProgressBar;
39 import android.widget.TextView;
40 import android.widget.Toast;
41
42 import com.google.android.material.floatingactionbutton.FloatingActionButton;
43
44 import net.ktnx.mobileledger.R;
45 import net.ktnx.mobileledger.async.DbOpQueue;
46 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
47 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
48 import net.ktnx.mobileledger.model.Data;
49 import net.ktnx.mobileledger.model.LedgerAccount;
50 import net.ktnx.mobileledger.model.MobileLedgerProfile;
51 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryAdapter;
52 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
53 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryViewModel;
54 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
55 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
56 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
57 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
58 import net.ktnx.mobileledger.utils.Colors;
59 import net.ktnx.mobileledger.utils.GetOptCallback;
60 import net.ktnx.mobileledger.utils.LockHolder;
61 import net.ktnx.mobileledger.utils.MLDB;
62
63 import org.jetbrains.annotations.NotNull;
64
65 import java.text.DateFormat;
66 import java.util.ArrayList;
67 import java.util.Date;
68 import java.util.List;
69 import java.util.Locale;
70 import java.util.Observer;
71
72 import androidx.appcompat.app.ActionBarDrawerToggle;
73 import androidx.appcompat.widget.Toolbar;
74 import androidx.core.view.GravityCompat;
75 import androidx.drawerlayout.widget.DrawerLayout;
76 import androidx.fragment.app.Fragment;
77 import androidx.fragment.app.FragmentManager;
78 import androidx.fragment.app.FragmentPagerAdapter;
79 import androidx.recyclerview.widget.LinearLayoutManager;
80 import androidx.recyclerview.widget.RecyclerView;
81 import androidx.viewpager.widget.ViewPager;
82
83 import static net.ktnx.mobileledger.utils.Logger.debug;
84
85 public class MainActivity extends ProfileThemedActivity {
86     public static final String STATE_CURRENT_PAGE = "current_page";
87     public static final String BUNDLE_SAVED_STATE = "bundle_savedState";
88     public static final String STATE_ACC_FILTER = "account_filter";
89     private static final String PREF_THEME_ID = "themeId";
90     public AccountSummaryFragment mAccountSummaryFragment;
91     DrawerLayout drawer;
92     private LinearLayout profileListContainer;
93     private View profileListHeadArrow, profileListHeadMore, profileListHeadCancel;
94     private FragmentManager fragmentManager;
95     private View bTransactionListCancelDownload;
96     private ProgressBar progressBar;
97     private LinearLayout progressLayout;
98     private SectionsPagerAdapter mSectionsPagerAdapter;
99     private ViewPager mViewPager;
100     private FloatingActionButton fab;
101     private boolean profileListExpanded = false;
102     private ProfilesRecyclerViewAdapter mProfileListAdapter;
103     private int mCurrentPage;
104     private String mAccountFilter;
105     private boolean mBackMeansToAccountList = false;
106     private Toolbar mToolbar;
107     private DrawerLayout.SimpleDrawerListener drawerListener;
108     private ActionBarDrawerToggle barDrawerToggle;
109     private ViewPager.SimpleOnPageChangeListener pageChangeListener;
110     private Observer editingProfilesObserver;
111     private MobileLedgerProfile profile;
112     @Override
113     protected void onStart() {
114         super.onStart();
115
116         debug("flow", "MainActivity.onStart()");
117         mViewPager.setCurrentItem(mCurrentPage, false);
118         if (mAccountFilter != null) showTransactionsFragment(mAccountFilter);
119         else Data.accountFilter.setValue(null);
120
121     }
122     @Override
123     protected void onSaveInstanceState(@NotNull Bundle outState) {
124         super.onSaveInstanceState(outState);
125         outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
126         if (mAccountFilter != null) outState.putString(STATE_ACC_FILTER, mAccountFilter);
127     }
128     @Override
129     protected void onDestroy() {
130         mSectionsPagerAdapter = null;
131         RecyclerView root = findViewById(R.id.nav_profile_list);
132         if (root != null) root.setAdapter(null);
133         if (drawer != null) drawer.removeDrawerListener(drawerListener);
134         drawerListener = null;
135         if (drawer != null) drawer.removeDrawerListener(barDrawerToggle);
136         barDrawerToggle = null;
137         if (mViewPager != null) mViewPager.removeOnPageChangeListener(pageChangeListener);
138         pageChangeListener = null;
139         if (mProfileListAdapter != null)
140             mProfileListAdapter.deleteEditingProfilesObserver(editingProfilesObserver);
141         editingProfilesObserver = null;
142         super.onDestroy();
143     }
144     @Override
145     protected void setupProfileColors() {
146         SharedPreferences prefs = getPreferences(MODE_PRIVATE);
147         int profileColor = prefs.getInt(PREF_THEME_ID, -2);
148         if (profileColor == -2) profileColor = Data.retrieveCurrentThemeIdFromDb();
149         Colors.setupTheme(this, profileColor);
150         Colors.profileThemeId = profileColor;
151         storeThemeIdInPrefs(profileColor);
152     }
153     @Override
154     protected void onCreate(Bundle savedInstanceState) {
155         super.onCreate(savedInstanceState);
156         debug("flow", "MainActivity.onCreate()");
157         setContentView(R.layout.activity_main);
158
159         fab = findViewById(R.id.btn_add_transaction);
160         profileListContainer = findViewById(R.id.nav_profile_list_container);
161         profileListHeadArrow = findViewById(R.id.nav_profiles_arrow);
162         profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
163         profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
164         LinearLayout profileListHeadMoreAndCancel =
165                 findViewById(R.id.nav_profile_list_head_buttons);
166         drawer = findViewById(R.id.drawer_layout);
167         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
168         progressBar = findViewById(R.id.transaction_list_progress_bar);
169         progressLayout = findViewById(R.id.transaction_progress_layout);
170         fragmentManager = getSupportFragmentManager();
171         mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
172         mViewPager = findViewById(R.id.root_frame);
173
174         Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
175         if (extra != null && savedInstanceState == null) savedInstanceState = extra;
176
177
178         mToolbar = findViewById(R.id.toolbar);
179         setSupportActionBar(mToolbar);
180
181         Data.profile.observe(this, this::onProfileChanged);
182
183         Data.profiles.observe(this, this::onProfileListChanged);
184
185         if (barDrawerToggle == null) {
186             barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
187                     R.string.navigation_drawer_open, R.string.navigation_drawer_close);
188             drawer.addDrawerListener(barDrawerToggle);
189         }
190         barDrawerToggle.syncState();
191
192         TextView ver = drawer.findViewById(R.id.drawer_version_text);
193
194         try {
195             PackageInfo pi =
196                     getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
197             ver.setText(pi.versionName);
198         }
199         catch (Exception e) {
200             e.printStackTrace();
201         }
202
203         if (progressBar == null)
204             throw new RuntimeException("Can't get hold on the transaction value progress bar");
205         if (progressLayout == null) throw new RuntimeException(
206                 "Can't get hold on the transaction value progress bar layout");
207
208         markDrawerItemCurrent(R.id.nav_account_summary);
209
210         mViewPager.setAdapter(mSectionsPagerAdapter);
211
212         if (pageChangeListener == null) {
213             pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
214                 @Override
215                 public void onPageSelected(int position) {
216                     switch (position) {
217                         case 0:
218                             markDrawerItemCurrent(R.id.nav_account_summary);
219                             break;
220                         case 1:
221                             markDrawerItemCurrent(R.id.nav_latest_transactions);
222                             break;
223                         default:
224                             Log.e("MainActivity",
225                                     String.format("Unexpected page index %d", position));
226                     }
227
228                     super.onPageSelected(position);
229                 }
230             };
231             mViewPager.addOnPageChangeListener(pageChangeListener);
232         }
233
234         mCurrentPage = 0;
235         if (savedInstanceState != null) {
236             int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
237             if (currentPage != -1) {
238                 mCurrentPage = currentPage;
239             }
240             mAccountFilter = savedInstanceState.getString(STATE_ACC_FILTER, null);
241         }
242         else mAccountFilter = null;
243
244         Data.lastUpdateDate.observe(this, this::updateLastUpdateDisplay);
245
246         findViewById(R.id.btn_no_profiles_add)
247                 .setOnClickListener(v -> startEditProfileActivity(null));
248
249         findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
250
251         findViewById(R.id.nav_new_profile_button)
252                 .setOnClickListener(v -> startEditProfileActivity(null));
253
254         RecyclerView root = findViewById(R.id.nav_profile_list);
255         if (root == null)
256             throw new RuntimeException("Can't get hold on the transaction value view");
257
258         if (mProfileListAdapter == null) mProfileListAdapter = new ProfilesRecyclerViewAdapter();
259         root.setAdapter(mProfileListAdapter);
260
261         if (editingProfilesObserver == null) {
262             editingProfilesObserver = (o, arg) -> {
263                 if (mProfileListAdapter.isEditingProfiles()) {
264                     profileListHeadMore.setVisibility(View.GONE);
265                     profileListHeadMore
266                             .startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_out));
267                     profileListHeadCancel.setVisibility(View.VISIBLE);
268                     profileListHeadCancel
269                             .startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
270                 }
271                 else {
272                     profileListHeadCancel.setVisibility(View.GONE);
273                     profileListHeadCancel
274                             .startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_out));
275                     profileListHeadMore.setVisibility(View.GONE);
276                     if (profileListExpanded) {
277                         profileListHeadMore.setVisibility(View.VISIBLE);
278                         profileListHeadMore
279                                 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
280                     }
281                     else profileListHeadMore.setVisibility(View.GONE);
282                 }
283             };
284             mProfileListAdapter.addEditingProfilesObserver(editingProfilesObserver);
285         }
286
287         LinearLayoutManager llm = new LinearLayoutManager(this);
288
289         llm.setOrientation(RecyclerView.VERTICAL);
290         root.setLayoutManager(llm);
291
292         profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
293         profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
294         profileListHeadMoreAndCancel
295                 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
296
297         if (drawerListener == null) {
298             drawerListener = new DrawerLayout.SimpleDrawerListener() {
299                 @Override
300                 public void onDrawerClosed(View drawerView) {
301                     super.onDrawerClosed(drawerView);
302                     collapseProfileList();
303                 }
304             };
305             drawer.addDrawerListener(drawerListener);
306         }
307
308         findViewById(R.id.nav_profile_list_head_layout)
309                 .setOnClickListener(this::navProfilesHeadClicked);
310         findViewById(R.id.nav_profiles_label).setOnClickListener(this::navProfilesHeadClicked);
311         setupProfile();
312     }
313     private void scheduleDataRetrievalIfStale(Date lastUpdate) {
314         long now = new Date().getTime();
315         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
316             if (lastUpdate == null) debug("db::", "WEB data never fetched. scheduling a fetch");
317             else debug("db", String.format(Locale.ENGLISH,
318                     "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
319                     lastUpdate.getTime() / 1000f, now / 1000f));
320
321             Data.scheduleTransactionListRetrieval(this);
322         }
323     }
324     private void createShortcuts(List<MobileLedgerProfile> list) {
325         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return;
326
327         List<ShortcutInfo> shortcuts = new ArrayList<>();
328         int i = 0;
329         for (MobileLedgerProfile p : list) {
330             if (!p.isPostingPermitted()) continue;
331
332             ShortcutInfo si = new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid())
333                     .setShortLabel(p.getName())
334                     .setIcon(Icon.createWithResource(this, R.drawable.svg_thick_plus_white))
335                     .setIntent(
336                             new Intent(Intent.ACTION_VIEW, null, this, NewTransactionActivity.class)
337                                     .putExtra("profile_uuid", p.getUuid())).setRank(i).build();
338             shortcuts.add(si);
339             i++;
340         }
341         ShortcutManager sm = getSystemService(ShortcutManager.class);
342         sm.setDynamicShortcuts(shortcuts);
343     }
344     private void onProfileListChanged(List<MobileLedgerProfile> newList) {
345         if (newList.isEmpty()) {
346             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
347             findViewById(R.id.pager_layout).setVisibility(View.GONE);
348             findViewById(R.id.loading_layout).setVisibility(View.GONE);
349             return;
350         }
351
352         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
353         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
354         findViewById(R.id.loading_layout).setVisibility(View.GONE);
355
356         findViewById(R.id.nav_profile_list).setMinimumHeight(
357                 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
358
359         debug("profiles", "profile list changed");
360         mProfileListAdapter.notifyDataSetChanged();
361
362         createShortcuts(newList);
363     }
364     /** called when the current profile has changed */
365     private void onProfileChanged(MobileLedgerProfile profile) {
366         boolean haveProfile = profile != null;
367         findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
368         findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
369
370         if (haveProfile) setTitle(profile.getName());
371         else setTitle(R.string.app_name);
372
373         this.profile = profile;
374
375         mProfileListAdapter.notifyDataSetChanged();
376
377         int newProfileTheme = haveProfile ? profile.getThemeId() : -1;
378         if (newProfileTheme != Colors.profileThemeId) {
379             debug("profiles",
380                     String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
381                             newProfileTheme));
382             MainActivity.this.profileThemeChanged();
383             Colors.profileThemeId = newProfileTheme;
384             // profileThemeChanged would restart the activity, so no need to reload the
385             // data sets below
386             return;
387         }
388         collapseProfileList();
389
390         drawer.closeDrawers();
391
392         Data.transactions.clear();
393         debug("transactions", "requesting list reload");
394         TransactionListViewModel.scheduleTransactionListReload();
395
396         Data.accounts.clear();
397         AccountSummaryViewModel.scheduleAccountListReload();
398
399         if (haveProfile) {
400             if (profile.isPostingPermitted()) {
401                 mToolbar.setSubtitle(null);
402                 fab.show();
403             }
404             else {
405                 mToolbar.setSubtitle(R.string.profile_subitlte_read_only);
406                 fab.hide();
407             }
408         }
409         else {
410             mToolbar.setSubtitle(null);
411             fab.hide();
412         }
413
414         updateLastUpdateTextFromDB();
415     }
416     private void updateLastUpdateDisplay(Date newValue) {
417         LinearLayout l = findViewById(R.id.transactions_last_update_layout);
418         TextView v = findViewById(R.id.transactions_last_update);
419         if (newValue == null) {
420             l.setVisibility(View.INVISIBLE);
421             debug("main", "no last update date :(");
422         }
423         else {
424             final String text = DateFormat.getDateTimeInstance().format(newValue);
425             v.setText(text);
426             l.setVisibility(View.VISIBLE);
427             debug("main", String.format("Date formatted: %s", text));
428         }
429
430         scheduleDataRetrievalIfStale(newValue);
431     }
432     private void profileThemeChanged() {
433         Bundle bundle = new Bundle();
434         onSaveInstanceState(bundle);
435
436         storeThemeIdInPrefs(profile.getThemeId());
437
438         // restart activity to reflect theme change
439         finish();
440
441         // un-hook all observed LiveData
442         Data.profile.removeObservers(this);
443         Data.profiles.removeObservers(this);
444         Data.lastUpdateDate.removeObservers(this);
445         Intent intent = new Intent(this, this.getClass());
446         intent.putExtra(BUNDLE_SAVED_STATE, bundle);
447         startActivity(intent);
448     }
449     private void storeThemeIdInPrefs(int themeId) {
450         // store the new theme id in the preferences
451         SharedPreferences prefs = getPreferences(MODE_PRIVATE);
452         SharedPreferences.Editor e = prefs.edit();
453         e.putInt(PREF_THEME_ID, themeId);
454         e.apply();
455     }
456     public void startEditProfileActivity(MobileLedgerProfile profile) {
457         Intent intent = new Intent(this, ProfileDetailActivity.class);
458         Bundle args = new Bundle();
459         if (profile != null) {
460             int index = Data.getProfileIndex(profile);
461             if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
462         }
463         intent.putExtras(args);
464         startActivity(intent, args);
465     }
466     private void setupProfile() {
467         MLDB.getOption(MLDB.OPT_PROFILE_UUID, null, new GetOptCallback(){
468             @Override
469             protected void onResult(String profileUUID) {
470                 MobileLedgerProfile startupProfile;
471
472                 startupProfile = Data.getProfile(profileUUID);
473                 Data.setCurrentProfile(startupProfile);
474             }
475         });
476     }
477     public void fabNewTransactionClicked(View view) {
478         Intent intent = new Intent(this, NewTransactionActivity.class);
479         startActivity(intent);
480         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
481     }
482     public void navSettingsClicked(View view) {
483         Intent intent = new Intent(this, SettingsActivity.class);
484         startActivity(intent);
485         drawer.closeDrawers();
486     }
487     public void markDrawerItemCurrent(int id) {
488         TextView item = drawer.findViewById(id);
489         item.setBackgroundColor(Colors.tableRowDarkBG);
490
491         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
492         for (int i = 0; i < actions.getChildCount(); i++) {
493             View view = actions.getChildAt(i);
494             if (view.getId() != id) {
495                 view.setBackgroundColor(Color.TRANSPARENT);
496             }
497         }
498     }
499     public void onAccountSummaryClicked(View view) {
500         drawer.closeDrawers();
501
502         showAccountSummaryFragment();
503     }
504     private void showAccountSummaryFragment() {
505         mViewPager.setCurrentItem(0, true);
506         Data.accountFilter.setValue(null);
507     }
508     public void onLatestTransactionsClicked(View view) {
509         drawer.closeDrawers();
510
511         showTransactionsFragment((String) null);
512     }
513     private void showTransactionsFragment(String accName) {
514         Data.accountFilter.setValue(accName);
515         mViewPager.setCurrentItem(1, true);
516     }
517     private void showTransactionsFragment(LedgerAccount account) {
518         showTransactionsFragment((account == null) ? null : account.getName());
519     }
520     public void showAccountTransactions(LedgerAccount account) {
521         mBackMeansToAccountList = true;
522         showTransactionsFragment(account);
523     }
524     @Override
525     public void onBackPressed() {
526         DrawerLayout drawer = findViewById(R.id.drawer_layout);
527         if (drawer.isDrawerOpen(GravityCompat.START)) {
528             drawer.closeDrawer(GravityCompat.START);
529         }
530         else {
531             if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
532                 Data.accountFilter.setValue(null);
533                 showAccountSummaryFragment();
534                 mBackMeansToAccountList = false;
535             }
536             else {
537                 debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
538                         fragmentManager.getBackStackEntryCount()));
539
540                 super.onBackPressed();
541             }
542         }
543     }
544     public void updateLastUpdateTextFromDB() {
545         long last_update = (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
546
547         debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", last_update));
548         if (last_update == 0) {
549             Data.lastUpdateDate.postValue(null);
550         }
551         else {
552             Data.lastUpdateDate.postValue(new Date(last_update));
553         }
554     }
555     public void onStopTransactionRefreshClick(View view) {
556         debug("interactive", "Cancelling transactions refresh");
557         Data.stopTransactionsRetrieval();
558         bTransactionListCancelDownload.setEnabled(false);
559     }
560     public void onRetrieveDone(String error) {
561         Data.transactionRetrievalDone();
562         progressLayout.setVisibility(View.GONE);
563
564         if (error == null) {
565             updateLastUpdateTextFromDB();
566
567             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
568             TransactionListViewModel.scheduleTransactionListReload();
569         }
570         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
571     }
572     public void onRetrieveStart() {
573         bTransactionListCancelDownload.setEnabled(true);
574         progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
575         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
576         progressBar.setIndeterminate(true);
577         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
578         else progressBar.setProgress(0);
579         progressLayout.setVisibility(View.VISIBLE);
580     }
581     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
582         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
583             (progress.getTotal() == 0))
584         {
585             progressBar.setIndeterminate(true);
586         }
587         else {
588             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
589                 progressBar.setMin(0);
590             }
591             progressBar.setMax(progress.getTotal());
592             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
593                 progressBar.setProgress(progress.getProgress(), true);
594             }
595             else progressBar.setProgress(progress.getProgress());
596             progressBar.setIndeterminate(false);
597         }
598     }
599     public void fabShouldShow() {
600         if ((profile != null) && profile.isPostingPermitted()) fab.show();
601     }
602     public void fabHide() {
603         fab.hide();
604     }
605     public void navProfilesHeadClicked(View view) {
606         if (profileListExpanded) {
607             collapseProfileList();
608         }
609         else {
610             expandProfileList();
611         }
612     }
613     private void expandProfileList() {
614         profileListExpanded = true;
615
616
617         profileListContainer.setVisibility(View.VISIBLE);
618         profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
619         profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
620         profileListHeadMore.setVisibility(View.VISIBLE);
621         profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
622         final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
623         findViewById(R.id.nav_profile_list).setMinimumHeight(
624                 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
625                        (profiles != null ? profiles.size() : 0)));
626     }
627     private void collapseProfileList() {
628         boolean wasExpanded = profileListExpanded;
629         profileListExpanded = false;
630
631         if (wasExpanded) {
632             final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
633             animation.setAnimationListener(new Animation.AnimationListener() {
634                 @Override
635                 public void onAnimationStart(Animation animation) {
636
637                 }
638                 @Override
639                 public void onAnimationEnd(Animation animation) {
640                     profileListContainer.setVisibility(View.GONE);
641                 }
642                 @Override
643                 public void onAnimationRepeat(Animation animation) {
644
645                 }
646             });
647             mProfileListAdapter.stopEditingProfiles();
648
649             profileListContainer.startAnimation(animation);
650             profileListHeadArrow.setRotation(0f);
651             profileListHeadArrow
652                     .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
653             final Animation moreAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
654             moreAnimation.setAnimationListener(new Animation.AnimationListener() {
655                 @Override
656                 public void onAnimationStart(Animation animation) {
657                 }
658                 @Override
659                 public void onAnimationEnd(Animation animation) {
660                     profileListHeadMore.setVisibility(View.GONE);
661                 }
662                 @Override
663                 public void onAnimationRepeat(Animation animation) {
664                 }
665             });
666             profileListHeadMore.startAnimation(moreAnimation);
667         }
668         else {
669             profileListContainer.setVisibility(View.GONE);
670             profileListHeadArrow.setRotation(0f);
671             profileListHeadMore.setVisibility(View.GONE);
672         }
673     }
674     public void onAccountSummaryRowViewClicked(View view) {
675         ViewGroup row;
676         if (view.getId() == R.id.account_expander) row = (ViewGroup) view.getParent().getParent();
677         else row = (ViewGroup) view.getParent();
678
679         LedgerAccount acc = (LedgerAccount) row.getTag();
680         switch (view.getId()) {
681             case R.id.account_row_acc_name:
682             case R.id.account_expander:
683             case R.id.account_expander_container:
684                 debug("accounts", "Account expander clicked");
685                 if (!acc.hasSubAccounts()) return;
686
687                 boolean wasExpanded = acc.isExpanded();
688
689                 View arrow = row.findViewById(R.id.account_expander_container);
690
691                 arrow.clearAnimation();
692                 ViewPropertyAnimator animator = arrow.animate();
693
694                 acc.toggleExpanded();
695                 DbOpQueue.add("update accounts set expanded=? where name=? and profile=?",
696                         new Object[]{acc.isExpanded(), acc.getName(), profile.getUuid()
697                         });
698
699                 if (wasExpanded) {
700                     debug("accounts", String.format("Collapsing account '%s'", acc.getName()));
701                     arrow.setRotation(0);
702                     animator.rotationBy(180);
703
704                     // removing all child accounts from the view
705                     int start = -1, count = 0;
706                     try (LockHolder ignored = Data.accounts.lockForWriting()) {
707                         for (int i = 0; i < Data.accounts.size(); i++) {
708                             if (acc.isParentOf(Data.accounts.get(i))) {
709 //                                debug("accounts", String.format("Found a child '%s' at position %d",
710 //                                        Data.accounts.get(i).getName(), i));
711                                 if (start == -1) {
712                                     start = i;
713                                 }
714                                 count++;
715                             }
716                             else {
717                                 if (start != -1) {
718 //                                    debug("accounts",
719 //                                            String.format("Found a non-child '%s' at position %d",
720 //                                                    Data.accounts.get(i).getName(), i));
721                                     break;
722                                 }
723                             }
724                         }
725
726                         if (start != -1) {
727                             for (int j = 0; j < count; j++) {
728 //                                debug("accounts", String.format("Removing item %d: %s", start + j,
729 //                                        Data.accounts.get(start).getName()));
730                                 Data.accounts.removeQuietly(start);
731                             }
732
733                             mAccountSummaryFragment.modelAdapter
734                                     .notifyItemRangeRemoved(start, count);
735                         }
736                     }
737                 }
738                 else {
739                     debug("accounts", String.format("Expanding account '%s'", acc.getName()));
740                     arrow.setRotation(180);
741                     animator.rotationBy(-180);
742                     List<LedgerAccount> children = profile.loadVisibleChildAccountsOf(acc);
743                     try (LockHolder ignored = Data.accounts.lockForWriting()) {
744                         int parentPos = Data.accounts.indexOf(acc);
745                         if (parentPos != -1) {
746                             // may have disappeared in a concurrent refresh operation
747                             Data.accounts.addAllQuietly(parentPos + 1, children);
748                             mAccountSummaryFragment.modelAdapter
749                                     .notifyItemRangeInserted(parentPos + 1, children.size());
750                         }
751                     }
752                 }
753                 break;
754             case R.id.account_row_acc_amounts:
755                 if (acc.getAmountCount() > AccountSummaryAdapter.AMOUNT_LIMIT) {
756                     acc.toggleAmountsExpanded();
757                     DbOpQueue
758                             .add("update accounts set amounts_expanded=? where name=? and profile=?",
759                                     new Object[]{acc.amountsExpanded(), acc.getName(),
760                                                  profile.getUuid()
761                                     });
762                     Data.accounts.triggerItemChangedNotification(acc);
763                 }
764                 break;
765         }
766     }
767
768     public class SectionsPagerAdapter extends FragmentPagerAdapter {
769
770         SectionsPagerAdapter(FragmentManager fm) {
771             super(fm);
772         }
773
774         @NotNull
775         @Override
776         public Fragment getItem(int position) {
777             debug("main", String.format(Locale.ENGLISH, "Switching to fragment %d", position));
778             switch (position) {
779                 case 0:
780 //                    debug("flow", "Creating account summary fragment");
781                     return mAccountSummaryFragment = new AccountSummaryFragment();
782                 case 1:
783                     return new TransactionListFragment();
784                 default:
785                     throw new IllegalStateException(
786                             String.format("Unexpected fragment index: " + "%d", position));
787             }
788         }
789
790         @Override
791         public int getCount() {
792             return 2;
793         }
794     }
795 }