properly detect when profile list hasn't loaded yet
[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 == null) {
346             // profiles not yet loaded from DB
347             findViewById(R.id.loading_layout).setVisibility(View.VISIBLE);
348             findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
349             findViewById(R.id.pager_layout).setVisibility(View.GONE);
350             return;
351         }
352
353         if (newList.isEmpty()) {
354             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
355             findViewById(R.id.pager_layout).setVisibility(View.GONE);
356             findViewById(R.id.loading_layout).setVisibility(View.GONE);
357             return;
358         }
359
360         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
361         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
362         findViewById(R.id.loading_layout).setVisibility(View.GONE);
363
364         findViewById(R.id.nav_profile_list).setMinimumHeight(
365                 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
366
367         debug("profiles", "profile list changed");
368         mProfileListAdapter.notifyDataSetChanged();
369
370         createShortcuts(newList);
371     }
372     /**
373      * called when the current profile has changed
374      */
375     private void onProfileChanged(MobileLedgerProfile profile) {
376         boolean haveProfile = profile != null;
377         findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
378         findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
379
380         if (haveProfile) setTitle(profile.getName());
381         else setTitle(R.string.app_name);
382
383         this.profile = profile;
384
385         mProfileListAdapter.notifyDataSetChanged();
386
387         int newProfileTheme = haveProfile ? profile.getThemeId() : -1;
388         if (newProfileTheme != Colors.profileThemeId) {
389             debug("profiles",
390                     String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
391                             newProfileTheme));
392             MainActivity.this.profileThemeChanged();
393             Colors.profileThemeId = newProfileTheme;
394             // profileThemeChanged would restart the activity, so no need to reload the
395             // data sets below
396             return;
397         }
398         collapseProfileList();
399
400         drawer.closeDrawers();
401
402         Data.transactions.clear();
403         debug("transactions", "requesting list reload");
404         TransactionListViewModel.scheduleTransactionListReload();
405
406         Data.accounts.clear();
407         AccountSummaryViewModel.scheduleAccountListReload();
408
409         if (haveProfile) {
410             if (profile.isPostingPermitted()) {
411                 mToolbar.setSubtitle(null);
412                 fab.show();
413             }
414             else {
415                 mToolbar.setSubtitle(R.string.profile_subitlte_read_only);
416                 fab.hide();
417             }
418         }
419         else {
420             mToolbar.setSubtitle(null);
421             fab.hide();
422         }
423
424         updateLastUpdateTextFromDB();
425     }
426     private void updateLastUpdateDisplay(Date newValue) {
427         LinearLayout l = findViewById(R.id.transactions_last_update_layout);
428         TextView v = findViewById(R.id.transactions_last_update);
429         if (newValue == null) {
430             l.setVisibility(View.INVISIBLE);
431             debug("main", "no last update date :(");
432         }
433         else {
434             final String text = DateFormat.getDateTimeInstance().format(newValue);
435             v.setText(text);
436             l.setVisibility(View.VISIBLE);
437             debug("main", String.format("Date formatted: %s", text));
438         }
439
440         scheduleDataRetrievalIfStale(newValue);
441     }
442     private void profileThemeChanged() {
443         Bundle bundle = new Bundle();
444         onSaveInstanceState(bundle);
445
446         storeThemeIdInPrefs(profile.getThemeId());
447
448         // restart activity to reflect theme change
449         finish();
450
451         // un-hook all observed LiveData
452         Data.profile.removeObservers(this);
453         Data.profiles.removeObservers(this);
454         Data.lastUpdateDate.removeObservers(this);
455         Intent intent = new Intent(this, this.getClass());
456         intent.putExtra(BUNDLE_SAVED_STATE, bundle);
457         startActivity(intent);
458     }
459     private void storeThemeIdInPrefs(int themeId) {
460         // store the new theme id in the preferences
461         SharedPreferences prefs = getPreferences(MODE_PRIVATE);
462         SharedPreferences.Editor e = prefs.edit();
463         e.putInt(PREF_THEME_ID, themeId);
464         e.apply();
465     }
466     public void startEditProfileActivity(MobileLedgerProfile profile) {
467         Intent intent = new Intent(this, ProfileDetailActivity.class);
468         Bundle args = new Bundle();
469         if (profile != null) {
470             int index = Data.getProfileIndex(profile);
471             if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
472         }
473         intent.putExtras(args);
474         startActivity(intent, args);
475     }
476     private void setupProfile() {
477         MLDB.getOption(MLDB.OPT_PROFILE_UUID, null, new GetOptCallback() {
478             @Override
479             protected void onResult(String profileUUID) {
480                 MobileLedgerProfile startupProfile;
481
482                 startupProfile = Data.getProfile(profileUUID);
483                 Data.setCurrentProfile(startupProfile);
484             }
485         });
486     }
487     public void fabNewTransactionClicked(View view) {
488         Intent intent = new Intent(this, NewTransactionActivity.class);
489         startActivity(intent);
490         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
491     }
492     public void navSettingsClicked(View view) {
493         Intent intent = new Intent(this, SettingsActivity.class);
494         startActivity(intent);
495         drawer.closeDrawers();
496     }
497     public void markDrawerItemCurrent(int id) {
498         TextView item = drawer.findViewById(id);
499         item.setBackgroundColor(Colors.tableRowDarkBG);
500
501         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
502         for (int i = 0; i < actions.getChildCount(); i++) {
503             View view = actions.getChildAt(i);
504             if (view.getId() != id) {
505                 view.setBackgroundColor(Color.TRANSPARENT);
506             }
507         }
508     }
509     public void onAccountSummaryClicked(View view) {
510         drawer.closeDrawers();
511
512         showAccountSummaryFragment();
513     }
514     private void showAccountSummaryFragment() {
515         mViewPager.setCurrentItem(0, true);
516         Data.accountFilter.setValue(null);
517     }
518     public void onLatestTransactionsClicked(View view) {
519         drawer.closeDrawers();
520
521         showTransactionsFragment((String) null);
522     }
523     private void showTransactionsFragment(String accName) {
524         Data.accountFilter.setValue(accName);
525         mViewPager.setCurrentItem(1, true);
526     }
527     private void showTransactionsFragment(LedgerAccount account) {
528         showTransactionsFragment((account == null) ? null : account.getName());
529     }
530     public void showAccountTransactions(LedgerAccount account) {
531         mBackMeansToAccountList = true;
532         showTransactionsFragment(account);
533     }
534     @Override
535     public void onBackPressed() {
536         DrawerLayout drawer = findViewById(R.id.drawer_layout);
537         if (drawer.isDrawerOpen(GravityCompat.START)) {
538             drawer.closeDrawer(GravityCompat.START);
539         }
540         else {
541             if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
542                 Data.accountFilter.setValue(null);
543                 showAccountSummaryFragment();
544                 mBackMeansToAccountList = false;
545             }
546             else {
547                 debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
548                         fragmentManager.getBackStackEntryCount()));
549
550                 super.onBackPressed();
551             }
552         }
553     }
554     public void updateLastUpdateTextFromDB() {
555         long last_update = (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
556
557         debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", last_update));
558         if (last_update == 0) {
559             Data.lastUpdateDate.postValue(null);
560         }
561         else {
562             Data.lastUpdateDate.postValue(new Date(last_update));
563         }
564     }
565     public void onStopTransactionRefreshClick(View view) {
566         debug("interactive", "Cancelling transactions refresh");
567         Data.stopTransactionsRetrieval();
568         bTransactionListCancelDownload.setEnabled(false);
569     }
570     public void onRetrieveDone(String error) {
571         Data.transactionRetrievalDone();
572         progressLayout.setVisibility(View.GONE);
573
574         if (error == null) {
575             updateLastUpdateTextFromDB();
576
577             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
578             TransactionListViewModel.scheduleTransactionListReload();
579         }
580         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
581     }
582     public void onRetrieveStart() {
583         bTransactionListCancelDownload.setEnabled(true);
584         progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
585         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
586         progressBar.setIndeterminate(true);
587         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
588         else progressBar.setProgress(0);
589         progressLayout.setVisibility(View.VISIBLE);
590     }
591     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
592         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
593             (progress.getTotal() == 0))
594         {
595             progressBar.setIndeterminate(true);
596         }
597         else {
598             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
599                 progressBar.setMin(0);
600             }
601             progressBar.setMax(progress.getTotal());
602             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
603                 progressBar.setProgress(progress.getProgress(), true);
604             }
605             else progressBar.setProgress(progress.getProgress());
606             progressBar.setIndeterminate(false);
607         }
608     }
609     public void fabShouldShow() {
610         if ((profile != null) && profile.isPostingPermitted()) fab.show();
611     }
612     public void fabHide() {
613         fab.hide();
614     }
615     public void navProfilesHeadClicked(View view) {
616         if (profileListExpanded) {
617             collapseProfileList();
618         }
619         else {
620             expandProfileList();
621         }
622     }
623     private void expandProfileList() {
624         profileListExpanded = true;
625
626
627         profileListContainer.setVisibility(View.VISIBLE);
628         profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
629         profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
630         profileListHeadMore.setVisibility(View.VISIBLE);
631         profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
632         final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
633         findViewById(R.id.nav_profile_list).setMinimumHeight(
634                 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
635                        (profiles != null ? profiles.size() : 0)));
636     }
637     private void collapseProfileList() {
638         boolean wasExpanded = profileListExpanded;
639         profileListExpanded = false;
640
641         if (wasExpanded) {
642             final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
643             animation.setAnimationListener(new Animation.AnimationListener() {
644                 @Override
645                 public void onAnimationStart(Animation animation) {
646
647                 }
648                 @Override
649                 public void onAnimationEnd(Animation animation) {
650                     profileListContainer.setVisibility(View.GONE);
651                 }
652                 @Override
653                 public void onAnimationRepeat(Animation animation) {
654
655                 }
656             });
657             mProfileListAdapter.stopEditingProfiles();
658
659             profileListContainer.startAnimation(animation);
660             profileListHeadArrow.setRotation(0f);
661             profileListHeadArrow
662                     .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
663             final Animation moreAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
664             moreAnimation.setAnimationListener(new Animation.AnimationListener() {
665                 @Override
666                 public void onAnimationStart(Animation animation) {
667                 }
668                 @Override
669                 public void onAnimationEnd(Animation animation) {
670                     profileListHeadMore.setVisibility(View.GONE);
671                 }
672                 @Override
673                 public void onAnimationRepeat(Animation animation) {
674                 }
675             });
676             profileListHeadMore.startAnimation(moreAnimation);
677         }
678         else {
679             profileListContainer.setVisibility(View.GONE);
680             profileListHeadArrow.setRotation(0f);
681             profileListHeadMore.setVisibility(View.GONE);
682         }
683     }
684     public void onAccountSummaryRowViewClicked(View view) {
685         ViewGroup row;
686         if (view.getId() == R.id.account_expander) row = (ViewGroup) view.getParent().getParent();
687         else row = (ViewGroup) view.getParent();
688
689         LedgerAccount acc = (LedgerAccount) row.getTag();
690         switch (view.getId()) {
691             case R.id.account_row_acc_name:
692             case R.id.account_expander:
693             case R.id.account_expander_container:
694                 debug("accounts", "Account expander clicked");
695                 if (!acc.hasSubAccounts()) return;
696
697                 boolean wasExpanded = acc.isExpanded();
698
699                 View arrow = row.findViewById(R.id.account_expander_container);
700
701                 arrow.clearAnimation();
702                 ViewPropertyAnimator animator = arrow.animate();
703
704                 acc.toggleExpanded();
705                 DbOpQueue.add("update accounts set expanded=? where name=? and profile=?",
706                         new Object[]{acc.isExpanded(), acc.getName(), profile.getUuid()
707                         });
708
709                 if (wasExpanded) {
710                     debug("accounts", String.format("Collapsing account '%s'", acc.getName()));
711                     arrow.setRotation(0);
712                     animator.rotationBy(180);
713
714                     // removing all child accounts from the view
715                     int start = -1, count = 0;
716                     try (LockHolder ignored = Data.accounts.lockForWriting()) {
717                         for (int i = 0; i < Data.accounts.size(); i++) {
718                             if (acc.isParentOf(Data.accounts.get(i))) {
719 //                                debug("accounts", String.format("Found a child '%s' at position %d",
720 //                                        Data.accounts.get(i).getName(), i));
721                                 if (start == -1) {
722                                     start = i;
723                                 }
724                                 count++;
725                             }
726                             else {
727                                 if (start != -1) {
728 //                                    debug("accounts",
729 //                                            String.format("Found a non-child '%s' at position %d",
730 //                                                    Data.accounts.get(i).getName(), i));
731                                     break;
732                                 }
733                             }
734                         }
735
736                         if (start != -1) {
737                             for (int j = 0; j < count; j++) {
738 //                                debug("accounts", String.format("Removing item %d: %s", start + j,
739 //                                        Data.accounts.get(start).getName()));
740                                 Data.accounts.removeQuietly(start);
741                             }
742
743                             mAccountSummaryFragment.modelAdapter
744                                     .notifyItemRangeRemoved(start, count);
745                         }
746                     }
747                 }
748                 else {
749                     debug("accounts", String.format("Expanding account '%s'", acc.getName()));
750                     arrow.setRotation(180);
751                     animator.rotationBy(-180);
752                     List<LedgerAccount> children = profile.loadVisibleChildAccountsOf(acc);
753                     try (LockHolder ignored = Data.accounts.lockForWriting()) {
754                         int parentPos = Data.accounts.indexOf(acc);
755                         if (parentPos != -1) {
756                             // may have disappeared in a concurrent refresh operation
757                             Data.accounts.addAllQuietly(parentPos + 1, children);
758                             mAccountSummaryFragment.modelAdapter
759                                     .notifyItemRangeInserted(parentPos + 1, children.size());
760                         }
761                     }
762                 }
763                 break;
764             case R.id.account_row_acc_amounts:
765                 if (acc.getAmountCount() > AccountSummaryAdapter.AMOUNT_LIMIT) {
766                     acc.toggleAmountsExpanded();
767                     DbOpQueue
768                             .add("update accounts set amounts_expanded=? where name=? and profile=?",
769                                     new Object[]{acc.amountsExpanded(), acc.getName(),
770                                                  profile.getUuid()
771                                     });
772                     Data.accounts.triggerItemChangedNotification(acc);
773                 }
774                 break;
775         }
776     }
777
778     public class SectionsPagerAdapter extends FragmentPagerAdapter {
779
780         SectionsPagerAdapter(FragmentManager fm) {
781             super(fm);
782         }
783
784         @NotNull
785         @Override
786         public Fragment getItem(int position) {
787             debug("main", String.format(Locale.ENGLISH, "Switching to fragment %d", position));
788             switch (position) {
789                 case 0:
790 //                    debug("flow", "Creating account summary fragment");
791                     return mAccountSummaryFragment = new AccountSummaryFragment();
792                 case 1:
793                     return new TransactionListFragment();
794                 default:
795                     throw new IllegalStateException(
796                             String.format("Unexpected fragment index: " + "%d", position));
797             }
798         }
799
800         @Override
801         public int getCount() {
802             return 2;
803         }
804     }
805 }