]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
a2cf30ea42264a33c1c71f8da96c37e62f1283a0
[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         setupProfile();
313         onProfileChanged(null);
314
315         updateLastUpdateTextFromDB();
316     }
317     private void scheduleDataRetrievalIfStale(Date lastUpdate) {
318         long now = new Date().getTime();
319         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
320             if (lastUpdate == null) debug("db::", "WEB data never fetched. scheduling a fetch");
321             else debug("db",
322                     String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
323                             lastUpdate.getTime() / 1000f, now / 1000f));
324
325             scheduleTransactionListRetrieval();
326         }
327     }
328     private void createShortcuts() {
329         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return;
330
331         List<ShortcutInfo> shortcuts = new ArrayList<>();
332         try (LockHolder lh = Data.profiles.lockForReading()) {
333             for (int i = 0; i < Data.profiles.size(); i++) {
334                 MobileLedgerProfile p = Data.profiles.get(i);
335                 if (!p.isPostingPermitted()) continue;
336
337                 ShortcutInfo si = new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid())
338                         .setShortLabel(p.getName())
339                         .setIcon(Icon.createWithResource(this, R.drawable.svg_thick_plus_white))
340                         .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
341                                 NewTransactionActivity.class).putExtra("profile_uuid", p.getUuid()))
342                         .setRank(i).build();
343                 shortcuts.add(si);
344             }
345         }
346         ShortcutManager sm = getSystemService(ShortcutManager.class);
347         sm.setDynamicShortcuts(shortcuts);
348     }
349     private void onProfileListChanged(Object arg) {
350         findViewById(R.id.nav_profile_list).setMinimumHeight(
351                 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
352                        Data.profiles.size()));
353
354         debug("profiles", "profile list changed");
355         if (arg == null) mProfileListAdapter.notifyDataSetChanged();
356         else mProfileListAdapter.notifyItemChanged((int) arg);
357
358         createShortcuts();
359     }
360     private void onProfileChanged(Object arg) {
361         MobileLedgerProfile profile = Data.profile.get();
362         MainActivity.this.runOnUiThread(() -> {
363
364             boolean haveProfile = profile != null;
365             findViewById(R.id.no_profiles_layout)
366                     .setVisibility(haveProfile ? View.GONE : View.VISIBLE);
367             findViewById(R.id.pager_layout)
368                     .setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
369
370             Data.transactions.clear();
371             debug("transactions", "requesting list reload");
372             TransactionListViewModel.scheduleTransactionListReload();
373
374             Data.accounts.clear();
375             AccountSummaryViewModel.scheduleAccountListReload();
376
377             if (profile == null) MainActivity.this.setTitle(R.string.app_name);
378             else MainActivity.this.setTitle(profile.getName());
379             MainActivity.this.updateLastUpdateTextFromDB();
380             int old_index = -1;
381             int new_index = -1;
382             if (arg != null) {
383                 MobileLedgerProfile old = (MobileLedgerProfile) arg;
384                 old_index = Data.getProfileIndex(old);
385                 new_index = Data.getProfileIndex(profile);
386             }
387
388             if ((old_index != -1) && (new_index != -1)) {
389                 mProfileListAdapter.notifyItemChanged(old_index);
390                 mProfileListAdapter.notifyItemChanged(new_index);
391             }
392             else mProfileListAdapter.notifyDataSetChanged();
393
394             MainActivity.this.collapseProfileList();
395
396             int newProfileTheme = (profile == null) ? -1 : profile.getThemeId();
397             if (newProfileTheme != Colors.profileThemeId) {
398                 debug("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
399                         newProfileTheme));
400                 MainActivity.this.profileThemeChanged();
401                 Colors.profileThemeId = newProfileTheme;
402                 // profileThemeChanged would restart the activity, so no need to reload the
403                 // data sets below
404                 return;
405             }
406             drawer.closeDrawers();
407
408             if (profile == null) {
409                 mToolbar.setSubtitle(null);
410                 fab.hide();
411             }
412             else {
413                 if (profile.isPostingPermitted()) {
414                     mToolbar.setSubtitle(null);
415                     fab.show();
416                 }
417                 else {
418                     mToolbar.setSubtitle(R.string.profile_subitlte_read_only);
419                     fab.hide();
420                 }
421             }
422
423             updateLastUpdateTextFromDB();
424         });
425     }
426     private void updateLastUpdateDisplay(Date newValue) {
427         LinearLayout l = findViewById(R.id.transactions_last_update_layout);
428         TextView v = findViewById(R.id.transactions_last_update);
429         if (newValue == null) {
430             l.setVisibility(View.INVISIBLE);
431             debug("main", "no last update date :(");
432         }
433         else {
434             final String text = DateFormat.getDateTimeInstance().format(newValue);
435             v.setText(text);
436             l.setVisibility(View.VISIBLE);
437             debug("main", String.format("Date formatted: %s", text));
438         }
439
440         scheduleDataRetrievalIfStale(newValue);
441     }
442     @Override
443     public void finish() {
444         if (profilesObserver != null) {
445             Data.profiles.deleteObserver(profilesObserver);
446             profilesObserver = null;
447         }
448
449         if (profileObserver != null) {
450             Data.profile.deleteObserver(profileObserver);
451             profileObserver = null;
452         }
453
454         super.finish();
455     }
456     private void profileThemeChanged() {
457         setupProfileColors();
458
459         Bundle bundle = new Bundle();
460         onSaveInstanceState(bundle);
461         // restart activity to reflect theme change
462         finish();
463         Intent intent = new Intent(this, this.getClass());
464         intent.putExtra(BUNDLE_SAVED_STATE, bundle);
465         startActivity(intent);
466     }
467     public void startEditProfileActivity(MobileLedgerProfile profile) {
468         Intent intent = new Intent(this, ProfileDetailActivity.class);
469         Bundle args = new Bundle();
470         if (profile != null) {
471             int index = Data.getProfileIndex(profile);
472             if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
473         }
474         intent.putExtras(args);
475         startActivity(intent, args);
476     }
477     private void setupProfile() {
478         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
479         MobileLedgerProfile profile;
480
481         profile = Data.getProfile(profileUUID);
482
483         if (Data.profiles.isEmpty()) {
484             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
485             findViewById(R.id.pager_layout).setVisibility(View.GONE);
486             return;
487         }
488
489         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
490         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
491
492         if (profile == null) profile = Data.profiles.get(0);
493
494         if (profile == null) throw new AssertionError("profile must have a value");
495
496         Data.setCurrentProfile(profile);
497     }
498     public void fabNewTransactionClicked(View view) {
499         Intent intent = new Intent(this, NewTransactionActivity.class);
500         startActivity(intent);
501         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
502     }
503     public void navSettingsClicked(View view) {
504         Intent intent = new Intent(this, SettingsActivity.class);
505         startActivity(intent);
506         drawer.closeDrawers();
507     }
508     public void markDrawerItemCurrent(int id) {
509         TextView item = drawer.findViewById(id);
510         item.setBackgroundColor(Colors.tableRowDarkBG);
511
512         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
513         for (int i = 0; i < actions.getChildCount(); i++) {
514             View view = actions.getChildAt(i);
515             if (view.getId() != id) {
516                 view.setBackgroundColor(Color.TRANSPARENT);
517             }
518         }
519     }
520     public void onAccountSummaryClicked(View view) {
521         drawer.closeDrawers();
522
523         showAccountSummaryFragment();
524     }
525     private void showAccountSummaryFragment() {
526         mViewPager.setCurrentItem(0, true);
527         Data.accountFilter.setValue(null);
528 //        FragmentTransaction ft = fragmentManager.beginTransaction();
529 //        accountSummaryFragment = new AccountSummaryFragment();
530 //        ft.replace(R.id.root_frame, accountSummaryFragment);
531 //        ft.commit();
532 //        currentFragment = accountSummaryFragment;
533     }
534     public void onLatestTransactionsClicked(View view) {
535         drawer.closeDrawers();
536
537         showTransactionsFragment((String) null);
538     }
539     private void resetFragmentBackStack() {
540 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
541     }
542     private void showTransactionsFragment(String accName) {
543         Data.accountFilter.setValue(accName);
544         mViewPager.setCurrentItem(1, true);
545     }
546     private void showTransactionsFragment(LedgerAccount account) {
547         showTransactionsFragment((account == null) ? (String) null : account.getName());
548 //        FragmentTransaction ft = fragmentManager.beginTransaction();
549 //        if (transactionListFragment == null) {
550 //            debug("flow", "MainActivity creating TransactionListFragment");
551 //            transactionListFragment = new TransactionListFragment();
552 //        }
553 //        Bundle bundle = new Bundle();
554 //        if (account != null) {
555 //            bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
556 //                    account.getName());
557 //        }
558 //        transactionListFragment.setArguments(bundle);
559 //        ft.replace(R.id.root_frame, transactionListFragment);
560 //        if (account != null)
561 //            ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
562 //        ft.commit();
563 //
564 //        currentFragment = transactionListFragment;
565     }
566     public void showAccountTransactions(LedgerAccount account) {
567         mBackMeansToAccountList = true;
568         showTransactionsFragment(account);
569     }
570     @Override
571     public void onBackPressed() {
572         DrawerLayout drawer = findViewById(R.id.drawer_layout);
573         if (drawer.isDrawerOpen(GravityCompat.START)) {
574             drawer.closeDrawer(GravityCompat.START);
575         }
576         else {
577             if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
578                 Data.accountFilter.setValue(null);
579                 showAccountSummaryFragment();
580                 mBackMeansToAccountList = false;
581             }
582             else {
583                 debug("fragments", String.format("manager stack: %d",
584                         fragmentManager.getBackStackEntryCount()));
585
586                 super.onBackPressed();
587             }
588         }
589     }
590     public void updateLastUpdateTextFromDB() {
591         final MobileLedgerProfile profile = Data.profile.get();
592         long last_update = (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
593
594         debug("transactions", String.format("Last update = %d", last_update));
595         if (last_update == 0) {
596             Data.lastUpdateDate.postValue(null);
597         }
598         else {
599             Data.lastUpdateDate.postValue(new Date(last_update));
600         }
601     }
602     public void scheduleTransactionListRetrieval() {
603         if (Data.profile.get() == null) return;
604
605         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
606
607         retrieveTransactionsTask.execute();
608     }
609     public void onStopTransactionRefreshClick(View view) {
610         debug("interactive", "Cancelling transactions refresh");
611         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
612         bTransactionListCancelDownload.setEnabled(false);
613     }
614     public void onRetrieveDone(String error) {
615         progressLayout.setVisibility(View.GONE);
616
617         if (error == null) {
618             updateLastUpdateTextFromDB();
619
620             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
621             TransactionListViewModel.scheduleTransactionListReload();
622         }
623         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
624     }
625     public void onRetrieveStart() {
626         bTransactionListCancelDownload.setEnabled(true);
627         progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
628         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
629         progressBar.setIndeterminate(true);
630         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
631         else progressBar.setProgress(0);
632         progressLayout.setVisibility(View.VISIBLE);
633     }
634     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
635         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
636             (progress.getTotal() == 0))
637         {
638             progressBar.setIndeterminate(true);
639         }
640         else {
641             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
642                 progressBar.setMin(0);
643             }
644             progressBar.setMax(progress.getTotal());
645             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
646                 progressBar.setProgress(progress.getProgress(), true);
647             }
648             else progressBar.setProgress(progress.getProgress());
649             progressBar.setIndeterminate(false);
650         }
651     }
652     public void fabShouldShow() {
653         MobileLedgerProfile profile = Data.profile.get();
654         if ((profile != null) && profile.isPostingPermitted()) fab.show();
655     }
656     public void navProfilesHeadClicked(View view) {
657         if (profileListExpanded) {
658             collapseProfileList();
659         }
660         else {
661             expandProfileList();
662         }
663     }
664     private void expandProfileList() {
665         profileListExpanded = true;
666
667
668         profileListContainer.setVisibility(View.VISIBLE);
669         profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
670         profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
671         profileListHeadMore.setVisibility(View.VISIBLE);
672         profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
673         findViewById(R.id.nav_profile_list).setMinimumHeight(
674                 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
675                        Data.profiles.size()));
676     }
677     private void collapseProfileList() {
678         profileListExpanded = false;
679
680         final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
681         animation.setAnimationListener(new Animation.AnimationListener() {
682             @Override
683             public void onAnimationStart(Animation animation) {
684
685             }
686             @Override
687             public void onAnimationEnd(Animation animation) {
688                 profileListContainer.setVisibility(View.GONE);
689             }
690             @Override
691             public void onAnimationRepeat(Animation animation) {
692
693             }
694         });
695         mProfileListAdapter.stopEditingProfiles();
696
697         profileListContainer.startAnimation(animation);
698         profileListHeadArrow.setRotation(0f);
699         profileListHeadArrow
700                 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
701         profileListHeadMore.setVisibility(View.GONE);
702     }
703     public void onAccountSummaryRowViewClicked(View view) {
704         ViewGroup row;
705         if (view.getId() == R.id.account_expander) row = (ViewGroup) view.getParent().getParent();
706         else row = (ViewGroup) view.getParent();
707
708         LedgerAccount acc = (LedgerAccount) row.getTag();
709         switch (view.getId()) {
710             case R.id.account_row_acc_name:
711             case R.id.account_expander:
712             case R.id.account_expander_container:
713                 debug("accounts", "Account expander clicked");
714                 if (!acc.hasSubAccounts()) return;
715
716                 boolean wasExpanded = acc.isExpanded();
717
718                 View arrow = row.findViewById(R.id.account_expander_container);
719
720                 arrow.clearAnimation();
721                 ViewPropertyAnimator animator = arrow.animate();
722
723                 acc.toggleExpanded();
724                 DbOpQueue.add("update accounts set expanded=? where name=? and profile=?",
725                         new Object[]{acc.isExpanded(), acc.getName(), Data.profile.get().getUuid()
726                         });
727
728                 if (wasExpanded) {
729                     debug("accounts", String.format("Collapsing account '%s'", acc.getName()));
730                     arrow.setRotation(0);
731                     animator.rotationBy(180);
732
733                     // removing all child accounts from the view
734                     int start = -1, count = 0;
735                     try (LockHolder lh = Data.accounts.lockForWriting()) {
736                         for (int i = 0; i < Data.accounts.size(); i++) {
737                             if (acc.isParentOf(Data.accounts.get(i))) {
738 //                                debug("accounts", String.format("Found a child '%s' at position %d",
739 //                                        Data.accounts.get(i).getName(), i));
740                                 if (start == -1) {
741                                     start = i;
742                                 }
743                                 count++;
744                             }
745                             else {
746                                 if (start != -1) {
747 //                                    debug("accounts",
748 //                                            String.format("Found a non-child '%s' at position %d",
749 //                                                    Data.accounts.get(i).getName(), i));
750                                     break;
751                                 }
752                             }
753                         }
754
755                         if (start != -1) {
756                             for (int j = 0; j < count; j++) {
757 //                                debug("accounts", String.format("Removing item %d: %s", start + j,
758 //                                        Data.accounts.get(start).getName()));
759                                 Data.accounts.removeQuietly(start);
760                             }
761
762                             mAccountSummaryFragment.modelAdapter
763                                     .notifyItemRangeRemoved(start, count);
764                         }
765                     }
766                 }
767                 else {
768                     debug("accounts", String.format("Expanding account '%s'", acc.getName()));
769                     arrow.setRotation(180);
770                     animator.rotationBy(-180);
771                     List<LedgerAccount> children =
772                             Data.profile.get().loadVisibleChildAccountsOf(acc);
773                     try (LockHolder lh = Data.accounts.lockForWriting()) {
774                         int parentPos = Data.accounts.indexOf(acc);
775                         if (parentPos != -1) {
776                             // may have disappeared in a concurrent refresh operation
777                             Data.accounts.addAllQuietly(parentPos + 1, children);
778                             mAccountSummaryFragment.modelAdapter
779                                     .notifyItemRangeInserted(parentPos + 1, children.size());
780                         }
781                     }
782                 }
783                 break;
784             case R.id.account_row_acc_amounts:
785                 if (acc.getAmountCount() > AccountSummaryAdapter.AMOUNT_LIMIT) {
786                     acc.toggleAmountsExpanded();
787                     DbOpQueue
788                             .add("update accounts set amounts_expanded=? where name=? and profile=?",
789                                     new Object[]{acc.amountsExpanded(), acc.getName(),
790                                                  Data.profile.get().getUuid()
791                                     });
792                     Data.accounts.triggerItemChangedNotification(acc);
793                 }
794                 break;
795         }
796     }
797
798     public class SectionsPagerAdapter extends FragmentPagerAdapter {
799
800         public SectionsPagerAdapter(FragmentManager fm) {
801             super(fm);
802         }
803
804         @NotNull
805         @Override
806         public Fragment getItem(int position) {
807             debug("main", String.format("Switching to fragment %d", position));
808             switch (position) {
809                 case 0:
810 //                    debug("flow", "Creating account summary fragment");
811                     return mAccountSummaryFragment = new AccountSummaryFragment();
812                 case 1:
813                     return new TransactionListFragment();
814                 default:
815                     throw new IllegalStateException(
816                             String.format("Unexpected fragment index: " + "%d", position));
817             }
818         }
819
820         @Override
821         public int getCount() {
822             return 2;
823         }
824     }
825 }