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