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