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