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