]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
remove 'Loading' layout from the main activity
[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) || newList.isEmpty()) {
376             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
377             findViewById(R.id.main_app_layout).setVisibility(View.GONE);
378             return;
379         }
380
381         findViewById(R.id.main_app_layout).setVisibility(View.VISIBLE);
382         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
383
384         findViewById(R.id.nav_profile_list).setMinimumHeight(
385                 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
386
387         debug("profiles", "profile list changed");
388         mProfileListAdapter.notifyDataSetChanged();
389
390         createShortcuts(newList);
391     }
392     /**
393      * called when the current profile has changed
394      */
395     private void onProfileChanged(MobileLedgerProfile profile) {
396         boolean haveProfile = profile != null;
397
398         if (haveProfile)
399             setTitle(profile.getName());
400         else
401             setTitle(R.string.app_name);
402
403         this.profile = profile;
404
405         int newProfileTheme = haveProfile ? profile.getThemeHue() : -1;
406         if (newProfileTheme != Colors.profileThemeId) {
407             debug("profiles",
408                     String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
409                             newProfileTheme));
410             Colors.profileThemeId = newProfileTheme;
411             profileThemeChanged();
412             // profileThemeChanged would restart the activity, so no need to reload the
413             // data sets below
414             return;
415         }
416
417         findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
418         findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
419
420         mProfileListAdapter.notifyDataSetChanged();
421
422         Data.transactions.clear();
423         debug("transactions", "requesting list reload");
424         TransactionListViewModel.scheduleTransactionListReload();
425
426         Data.accounts.clear();
427         AccountSummaryViewModel.scheduleAccountListReload();
428
429         if (haveProfile) {
430             if (profile.isPostingPermitted()) {
431                 mToolbar.setSubtitle(null);
432                 fab.show();
433             }
434             else {
435                 mToolbar.setSubtitle(R.string.profile_subtitle_read_only);
436                 fab.hide();
437             }
438         }
439         else {
440             mToolbar.setSubtitle(null);
441             fab.hide();
442         }
443
444         updateLastUpdateTextFromDB();
445     }
446     private void updateLastUpdateDisplay(Date newValue) {
447         LinearLayout l = findViewById(R.id.transactions_last_update_layout);
448         TextView v = findViewById(R.id.transactions_last_update);
449         if (newValue == null) {
450             l.setVisibility(View.INVISIBLE);
451             debug("main", "no last update date :(");
452         }
453         else {
454             final String text = DateFormat.getDateTimeInstance()
455                                           .format(newValue);
456             v.setText(text);
457             l.setVisibility(View.VISIBLE);
458             debug("main", String.format("Date formatted: %s", text));
459         }
460
461         scheduleDataRetrievalIfStale(newValue);
462     }
463     private void profileThemeChanged() {
464         storeThemeIdInPrefs(profile.getThemeHue());
465
466         // un-hook all observed LiveData
467         Data.profile.removeObservers(this);
468         Data.profiles.removeObservers(this);
469         Data.lastUpdateDate.removeObservers(this);
470
471         recreate();
472     }
473     private void storeThemeIdInPrefs(int themeId) {
474         // store the new theme id in the preferences
475         SharedPreferences prefs = getPreferences(MODE_PRIVATE);
476         SharedPreferences.Editor e = prefs.edit();
477         e.putInt(PREF_THEME_ID, themeId);
478         e.apply();
479     }
480     public void startEditProfileActivity(MobileLedgerProfile profile) {
481         Intent intent = new Intent(this, ProfileDetailActivity.class);
482         Bundle args = new Bundle();
483         if (profile != null) {
484             int index = Data.getProfileIndex(profile);
485             if (index != -1)
486                 intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
487         }
488         intent.putExtras(args);
489         startActivity(intent, args);
490     }
491     private void setupProfile() {
492         MLDB.getOption(MLDB.OPT_PROFILE_UUID, null, new GetOptCallback() {
493             @Override
494             protected void onResult(String profileUUID) {
495                 MobileLedgerProfile startupProfile;
496
497                 startupProfile = Data.getProfile(profileUUID);
498                 Data.setCurrentProfile(startupProfile);
499             }
500         });
501     }
502     public void fabNewTransactionClicked(View view) {
503         Intent intent = new Intent(this, NewTransactionActivity.class);
504         startActivity(intent);
505         overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
506     }
507     public void markDrawerItemCurrent(int id) {
508         TextView item = drawer.findViewById(id);
509         item.setBackgroundColor(Colors.tableRowDarkBG);
510
511         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
512         for (int i = 0; i < actions.getChildCount(); i++) {
513             View view = actions.getChildAt(i);
514             if (view.getId() != id) {
515                 view.setBackgroundColor(Color.TRANSPARENT);
516             }
517         }
518     }
519     public void onAccountSummaryClicked(View view) {
520         drawer.closeDrawers();
521
522         showAccountSummaryFragment();
523     }
524     private void showAccountSummaryFragment() {
525         mViewPager.setCurrentItem(0, true);
526         Data.accountFilter.setValue(null);
527     }
528     public void onLatestTransactionsClicked(View view) {
529         drawer.closeDrawers();
530
531         showTransactionsFragment((String) null);
532     }
533     private void showTransactionsFragment(String accName) {
534         Data.accountFilter.setValue(accName);
535         mViewPager.setCurrentItem(1, true);
536     }
537     private void showTransactionsFragment(LedgerAccount account) {
538         showTransactionsFragment((account == null) ? null : account.getName());
539     }
540     public void showAccountTransactions(LedgerAccount account) {
541         mBackMeansToAccountList = true;
542         showTransactionsFragment(account);
543     }
544     @Override
545     public void onBackPressed() {
546         DrawerLayout drawer = findViewById(R.id.drawer_layout);
547         if (drawer.isDrawerOpen(GravityCompat.START)) {
548             drawer.closeDrawer(GravityCompat.START);
549         }
550         else {
551             if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
552                 Data.accountFilter.setValue(null);
553                 showAccountSummaryFragment();
554                 mBackMeansToAccountList = false;
555             }
556             else {
557                 debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
558                         getSupportFragmentManager().getBackStackEntryCount()));
559
560                 super.onBackPressed();
561             }
562         }
563     }
564     public void updateLastUpdateTextFromDB() {
565         if (profile == null)
566             return;
567
568         long last_update = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
569
570         debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", last_update));
571         if (last_update == 0) {
572             Data.lastUpdateDate.postValue(null);
573         }
574         else {
575             Data.lastUpdateDate.postValue(new Date(last_update));
576         }
577     }
578     public void onStopTransactionRefreshClick(View view) {
579         debug("interactive", "Cancelling transactions refresh");
580         Data.stopTransactionsRetrieval();
581         bTransactionListCancelDownload.setEnabled(false);
582     }
583     public void onRetrieveDone(String error) {
584         Data.transactionRetrievalDone();
585         findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
586
587         if (error == null) {
588             updateLastUpdateTextFromDB();
589
590             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
591             TransactionListViewModel.scheduleTransactionListReload();
592         }
593         else
594             Snackbar.make(mViewPager, error, Snackbar.LENGTH_LONG)
595                     .show();
596     }
597     public void onRetrieveStart() {
598         ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
599         bTransactionListCancelDownload.setEnabled(true);
600         ColorStateList csl = Colors.getColorStateList();
601         progressBar.setIndeterminateTintList(csl);
602         progressBar.setProgressTintList(csl);
603         progressBar.setIndeterminate(true);
604         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
605             progressBar.setProgress(0, false);
606         else
607             progressBar.setProgress(0);
608         findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
609     }
610     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
611         ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
612         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
613             (progress.getTotal() == 0))
614         {
615             progressBar.setIndeterminate(true);
616         }
617         else {
618             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
619                 progressBar.setMin(0);
620             }
621             progressBar.setMax(progress.getTotal());
622             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
623                 progressBar.setProgress(progress.getProgress(), true);
624             }
625             else
626                 progressBar.setProgress(progress.getProgress());
627             progressBar.setIndeterminate(false);
628         }
629     }
630     public void fabShouldShow() {
631         if ((profile != null) && profile.isPostingPermitted() && !drawer.isOpen())
632             fab.show();
633         else
634             fabHide();
635     }
636     public void fabHide() {
637         fab.hide();
638     }
639     public void onAccountSummaryRowViewClicked(View view) {
640         ViewGroup row;
641         switch (view.getId()) {
642             case R.id.account_expander:
643                 row = (ViewGroup) view.getParent()
644                                       .getParent()
645                                       .getParent();
646                 break;
647             case R.id.account_expander_container:
648             case R.id.account_row_acc_name:
649                 row = (ViewGroup) view.getParent()
650                                       .getParent();
651                 break;
652             default:
653                 row = (ViewGroup) view.getParent();
654                 break;
655         }
656
657         LedgerAccount acc = (LedgerAccount) row.getTag();
658         switch (view.getId()) {
659             case R.id.account_row_acc_name:
660             case R.id.account_expander:
661             case R.id.account_expander_container:
662                 debug("accounts", "Account expander clicked");
663                 if (!acc.hasSubAccounts())
664                     return;
665
666                 boolean wasExpanded = acc.isExpanded();
667
668                 View arrow = row.findViewById(R.id.account_expander_container);
669
670                 arrow.clearAnimation();
671                 ViewPropertyAnimator animator = arrow.animate();
672
673                 acc.toggleExpanded();
674                 DbOpQueue.add("update accounts set expanded=? where name=? and profile=?",
675                         new Object[]{acc.isExpanded(), acc.getName(), profile.getUuid()
676                         });
677
678                 if (wasExpanded) {
679                     debug("accounts", String.format("Collapsing account '%s'", acc.getName()));
680                     arrow.setRotation(0);
681                     animator.rotationBy(180);
682
683                     // removing all child accounts from the view
684                     int start = -1, count = 0;
685                     try (LockHolder ignored = Data.accounts.lockForWriting()) {
686                         for (int i = 0; i < Data.accounts.size(); i++) {
687                             if (acc.isParentOf(Data.accounts.get(i))) {
688 //                                debug("accounts", String.format("Found a child '%s' at position
689 //                                %d",
690 //                                        Data.accounts.get(i).getName(), i));
691                                 if (start == -1) {
692                                     start = i;
693                                 }
694                                 count++;
695                             }
696                             else {
697                                 if (start != -1) {
698 //                                    debug("accounts",
699 //                                            String.format("Found a non-child '%s' at position %d",
700 //                                                    Data.accounts.get(i).getName(), i));
701                                     break;
702                                 }
703                             }
704                         }
705
706                         if (start != -1) {
707                             for (int j = 0; j < count; j++) {
708 //                                debug("accounts", String.format("Removing item %d: %s", start + j,
709 //                                        Data.accounts.get(start).getName()));
710                                 Data.accounts.removeQuietly(start);
711                             }
712
713                             mAccountSummaryFragment.modelAdapter.notifyItemRangeRemoved(start,
714                                     count);
715                         }
716                     }
717                 }
718                 else {
719                     debug("accounts", String.format("Expanding account '%s'", acc.getName()));
720                     arrow.setRotation(180);
721                     animator.rotationBy(-180);
722                     List<LedgerAccount> children = profile.loadVisibleChildAccountsOf(acc);
723                     try (LockHolder ignored = Data.accounts.lockForWriting()) {
724                         int parentPos = Data.accounts.indexOf(acc);
725                         if (parentPos != -1) {
726                             // may have disappeared in a concurrent refresh operation
727                             Data.accounts.addAllQuietly(parentPos + 1, children);
728                             mAccountSummaryFragment.modelAdapter.notifyItemRangeInserted(
729                                     parentPos + 1, children.size());
730                         }
731                     }
732                 }
733                 break;
734             case R.id.account_row_acc_amounts:
735                 if (acc.getAmountCount() > AccountSummaryAdapter.AMOUNT_LIMIT) {
736                     acc.toggleAmountsExpanded();
737                     DbOpQueue.add(
738                             "update accounts set amounts_expanded=? where name=? and profile=?",
739                             new Object[]{acc.amountsExpanded(), acc.getName(), profile.getUuid()
740                             });
741                     Data.accounts.triggerItemChangedNotification(acc);
742                 }
743                 break;
744         }
745     }
746
747     public class SectionsPagerAdapter extends FragmentPagerAdapter {
748
749         SectionsPagerAdapter(FragmentManager fm) {
750             super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
751         }
752
753         @NotNull
754         @Override
755         public Fragment getItem(int position) {
756             debug("main", String.format(Locale.ENGLISH, "Switching to fragment %d", position));
757             switch (position) {
758                 case 0:
759 //                    debug("flow", "Creating account summary fragment");
760                     return mAccountSummaryFragment = new AccountSummaryFragment();
761                 case 1:
762                     return new TransactionListFragment();
763                 default:
764                     throw new IllegalStateException(
765                             String.format("Unexpected fragment index: " + "%d", position));
766             }
767         }
768
769         @Override
770         public int getCount() {
771             return 2;
772         }
773     }
774 }