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