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