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