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