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