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