5a8e198f778400ef00ef9aac6cbe1fd8336056dd
[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
253                 .observe(this, newValue -> {
254                     if (newValue) {
255                         profileListHeadMore.setVisibility(View.GONE);
256                         profileListHeadCancel.setVisibility(View.VISIBLE);
257                         profileListHeadAddProfile.setVisibility(View.VISIBLE);
258                         if (drawer.isDrawerOpen(GravityCompat.START)) {
259                             profileListHeadMore.startAnimation(AnimationUtils
260                                     .loadAnimation(MainActivity.this, R.anim.fade_out));
261                             profileListHeadCancel.startAnimation(AnimationUtils
262                                     .loadAnimation(MainActivity.this, R.anim.fade_in));
263                             profileListHeadAddProfile.startAnimation(AnimationUtils
264                                     .loadAnimation(MainActivity.this, R.anim.fade_in));
265                         }
266                     }
267                     else {
268                         profileListHeadCancel.setVisibility(View.GONE);
269                         profileListHeadMore.setVisibility(View.VISIBLE);
270                         profileListHeadAddProfile.setVisibility(View.GONE);
271                         if (drawer.isDrawerOpen(GravityCompat.START)) {
272                             profileListHeadCancel.startAnimation(AnimationUtils
273                                     .loadAnimation(MainActivity.this, R.anim.fade_out));
274                             profileListHeadMore.startAnimation(AnimationUtils
275                                     .loadAnimation(MainActivity.this, R.anim.fade_in));
276                             profileListHeadAddProfile.startAnimation(AnimationUtils
277                                     .loadAnimation(MainActivity.this, R.anim.fade_out));
278                         }
279                     }
280
281                     mProfileListAdapter.notifyDataSetChanged();
282                 });
283
284         LinearLayoutManager llm = new LinearLayoutManager(this);
285
286         llm.setOrientation(RecyclerView.VERTICAL);
287         root.setLayoutManager(llm);
288
289         profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
290         profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
291         profileListHeadMoreAndCancel
292                 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
293         if (drawerListener == null) {
294             drawerListener = new DrawerLayout.SimpleDrawerListener() {
295                 @Override
296                 public void onDrawerClosed(View drawerView) {
297                     super.onDrawerClosed(drawerView);
298                     mProfileListAdapter.setAnimationsEnabled(false);
299                     mProfileListAdapter.editingProfiles.setValue(false);
300                 }
301                 @Override
302                 public void onDrawerOpened(View drawerView) {
303                     super.onDrawerOpened(drawerView);
304                     mProfileListAdapter.setAnimationsEnabled(true);
305                 }
306             };
307             drawer.addDrawerListener(drawerListener);
308         }
309         setupProfile();
310     }
311     private void scheduleDataRetrievalIfStale(Date lastUpdate) {
312         long now = new Date().getTime();
313         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
314             if (lastUpdate == null) debug("db::", "WEB data never fetched. scheduling a fetch");
315             else debug("db", String.format(Locale.ENGLISH,
316                     "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
317                     lastUpdate.getTime() / 1000f, now / 1000f));
318
319             Data.scheduleTransactionListRetrieval(this);
320         }
321     }
322     private void createShortcuts(List<MobileLedgerProfile> list) {
323         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return;
324
325         List<ShortcutInfo> shortcuts = new ArrayList<>();
326         int i = 0;
327         for (MobileLedgerProfile p : list) {
328             if (!p.isPostingPermitted()) continue;
329
330             ShortcutInfo si = new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid())
331                     .setShortLabel(p.getName())
332                     .setIcon(Icon.createWithResource(this, R.drawable.svg_thick_plus_white))
333                     .setIntent(
334                             new Intent(Intent.ACTION_VIEW, null, this, NewTransactionActivity.class)
335                                     .putExtra("profile_uuid", p.getUuid())).setRank(i).build();
336             shortcuts.add(si);
337             i++;
338         }
339         ShortcutManager sm = getSystemService(ShortcutManager.class);
340         sm.setDynamicShortcuts(shortcuts);
341     }
342     private void onProfileListChanged(List<MobileLedgerProfile> newList) {
343         if (newList == null) {
344             // profiles not yet loaded from DB
345             findViewById(R.id.loading_layout).setVisibility(View.VISIBLE);
346             findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
347             findViewById(R.id.pager_layout).setVisibility(View.GONE);
348             return;
349         }
350
351         if (newList.isEmpty()) {
352             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
353             findViewById(R.id.pager_layout).setVisibility(View.GONE);
354             findViewById(R.id.loading_layout).setVisibility(View.GONE);
355             return;
356         }
357
358         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
359         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
360         findViewById(R.id.loading_layout).setVisibility(View.GONE);
361
362         findViewById(R.id.nav_profile_list).setMinimumHeight(
363                 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
364
365         debug("profiles", "profile list changed");
366         mProfileListAdapter.notifyDataSetChanged();
367
368         createShortcuts(newList);
369     }
370     /**
371      * called when the current profile has changed
372      */
373     private void onProfileChanged(MobileLedgerProfile profile) {
374         boolean haveProfile = profile != null;
375         findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
376         findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
377
378         if (haveProfile) setTitle(profile.getName());
379         else setTitle(R.string.app_name);
380
381         this.profile = profile;
382
383         mProfileListAdapter.notifyDataSetChanged();
384
385         int newProfileTheme = haveProfile ? profile.getThemeId() : -1;
386         if (newProfileTheme != Colors.profileThemeId) {
387             debug("profiles",
388                     String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
389                             newProfileTheme));
390             MainActivity.this.profileThemeChanged();
391             Colors.profileThemeId = newProfileTheme;
392             // profileThemeChanged would restart the activity, so no need to reload the
393             // data sets below
394             return;
395         }
396
397         drawer.closeDrawers();
398
399         Data.transactions.clear();
400         debug("transactions", "requesting list reload");
401         TransactionListViewModel.scheduleTransactionListReload();
402
403         Data.accounts.clear();
404         AccountSummaryViewModel.scheduleAccountListReload();
405
406         if (haveProfile) {
407             if (profile.isPostingPermitted()) {
408                 mToolbar.setSubtitle(null);
409                 fab.show();
410             }
411             else {
412                 mToolbar.setSubtitle(R.string.profile_subitlte_read_only);
413                 fab.hide();
414             }
415         }
416         else {
417             mToolbar.setSubtitle(null);
418             fab.hide();
419         }
420
421         updateLastUpdateTextFromDB();
422     }
423     private void updateLastUpdateDisplay(Date newValue) {
424         LinearLayout l = findViewById(R.id.transactions_last_update_layout);
425         TextView v = findViewById(R.id.transactions_last_update);
426         if (newValue == null) {
427             l.setVisibility(View.INVISIBLE);
428             debug("main", "no last update date :(");
429         }
430         else {
431             final String text = DateFormat.getDateTimeInstance().format(newValue);
432             v.setText(text);
433             l.setVisibility(View.VISIBLE);
434             debug("main", String.format("Date formatted: %s", text));
435         }
436
437         scheduleDataRetrievalIfStale(newValue);
438     }
439     private void profileThemeChanged() {
440         Bundle bundle = new Bundle();
441         onSaveInstanceState(bundle);
442
443         storeThemeIdInPrefs(profile.getThemeId());
444
445         // restart activity to reflect theme change
446         finish();
447
448         // un-hook all observed LiveData
449         Data.profile.removeObservers(this);
450         Data.profiles.removeObservers(this);
451         Data.lastUpdateDate.removeObservers(this);
452         Intent intent = new Intent(this, this.getClass());
453         intent.putExtra(BUNDLE_SAVED_STATE, bundle);
454         startActivity(intent);
455     }
456     private void storeThemeIdInPrefs(int themeId) {
457         // store the new theme id in the preferences
458         SharedPreferences prefs = getPreferences(MODE_PRIVATE);
459         SharedPreferences.Editor e = prefs.edit();
460         e.putInt(PREF_THEME_ID, themeId);
461         e.apply();
462     }
463     public void startEditProfileActivity(MobileLedgerProfile profile) {
464         Intent intent = new Intent(this, ProfileDetailActivity.class);
465         Bundle args = new Bundle();
466         if (profile != null) {
467             int index = Data.getProfileIndex(profile);
468             if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
469         }
470         intent.putExtras(args);
471         startActivity(intent, args);
472     }
473     private void setupProfile() {
474         MLDB.getOption(MLDB.OPT_PROFILE_UUID, null, new GetOptCallback() {
475             @Override
476             protected void onResult(String profileUUID) {
477                 MobileLedgerProfile startupProfile;
478
479                 startupProfile = Data.getProfile(profileUUID);
480                 Data.setCurrentProfile(startupProfile);
481             }
482         });
483     }
484     public void fabNewTransactionClicked(View view) {
485         Intent intent = new Intent(this, NewTransactionActivity.class);
486         startActivity(intent);
487         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
488     }
489     public void navSettingsClicked(View view) {
490         Intent intent = new Intent(this, SettingsActivity.class);
491         startActivity(intent);
492         drawer.closeDrawers();
493     }
494     public void markDrawerItemCurrent(int id) {
495         TextView item = drawer.findViewById(id);
496         item.setBackgroundColor(Colors.tableRowDarkBG);
497
498         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
499         for (int i = 0; i < actions.getChildCount(); i++) {
500             View view = actions.getChildAt(i);
501             if (view.getId() != id) {
502                 view.setBackgroundColor(Color.TRANSPARENT);
503             }
504         }
505     }
506     public void onAccountSummaryClicked(View view) {
507         drawer.closeDrawers();
508
509         showAccountSummaryFragment();
510     }
511     private void showAccountSummaryFragment() {
512         mViewPager.setCurrentItem(0, true);
513         Data.accountFilter.setValue(null);
514     }
515     public void onLatestTransactionsClicked(View view) {
516         drawer.closeDrawers();
517
518         showTransactionsFragment((String) null);
519     }
520     private void showTransactionsFragment(String accName) {
521         Data.accountFilter.setValue(accName);
522         mViewPager.setCurrentItem(1, true);
523     }
524     private void showTransactionsFragment(LedgerAccount account) {
525         showTransactionsFragment((account == null) ? null : account.getName());
526     }
527     public void showAccountTransactions(LedgerAccount account) {
528         mBackMeansToAccountList = true;
529         showTransactionsFragment(account);
530     }
531     @Override
532     public void onBackPressed() {
533         DrawerLayout drawer = findViewById(R.id.drawer_layout);
534         if (drawer.isDrawerOpen(GravityCompat.START)) {
535             drawer.closeDrawer(GravityCompat.START);
536         }
537         else {
538             if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
539                 Data.accountFilter.setValue(null);
540                 showAccountSummaryFragment();
541                 mBackMeansToAccountList = false;
542             }
543             else {
544                 debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
545                         fragmentManager.getBackStackEntryCount()));
546
547                 super.onBackPressed();
548             }
549         }
550     }
551     public void updateLastUpdateTextFromDB() {
552         if (profile == null) return;
553
554         long last_update = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
555
556         debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", last_update));
557         if (last_update == 0) {
558             Data.lastUpdateDate.postValue(null);
559         }
560         else {
561             Data.lastUpdateDate.postValue(new Date(last_update));
562         }
563     }
564     public void onStopTransactionRefreshClick(View view) {
565         debug("interactive", "Cancelling transactions refresh");
566         Data.stopTransactionsRetrieval();
567         bTransactionListCancelDownload.setEnabled(false);
568     }
569     public void onRetrieveDone(String error) {
570         Data.transactionRetrievalDone();
571         progressLayout.setVisibility(View.GONE);
572
573         if (error == null) {
574             updateLastUpdateTextFromDB();
575
576             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
577             TransactionListViewModel.scheduleTransactionListReload();
578         }
579         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
580     }
581     public void onRetrieveStart() {
582         bTransactionListCancelDownload.setEnabled(true);
583         progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
584         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
585         progressBar.setIndeterminate(true);
586         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
587         else progressBar.setProgress(0);
588         progressLayout.setVisibility(View.VISIBLE);
589     }
590     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
591         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
592             (progress.getTotal() == 0))
593         {
594             progressBar.setIndeterminate(true);
595         }
596         else {
597             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
598                 progressBar.setMin(0);
599             }
600             progressBar.setMax(progress.getTotal());
601             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
602                 progressBar.setProgress(progress.getProgress(), true);
603             }
604             else progressBar.setProgress(progress.getProgress());
605             progressBar.setIndeterminate(false);
606         }
607     }
608     public void fabShouldShow() {
609         if ((profile != null) && profile.isPostingPermitted()) fab.show();
610     }
611     public void fabHide() {
612         fab.hide();
613     }
614     public void onAccountSummaryRowViewClicked(View view) {
615         ViewGroup row;
616         if (view.getId() == R.id.account_expander) row = (ViewGroup) view.getParent().getParent();
617         else row = (ViewGroup) view.getParent();
618
619         LedgerAccount acc = (LedgerAccount) row.getTag();
620         switch (view.getId()) {
621             case R.id.account_row_acc_name:
622             case R.id.account_expander:
623             case R.id.account_expander_container:
624                 debug("accounts", "Account expander clicked");
625                 if (!acc.hasSubAccounts()) return;
626
627                 boolean wasExpanded = acc.isExpanded();
628
629                 View arrow = row.findViewById(R.id.account_expander_container);
630
631                 arrow.clearAnimation();
632                 ViewPropertyAnimator animator = arrow.animate();
633
634                 acc.toggleExpanded();
635                 DbOpQueue.add("update accounts set expanded=? where name=? and profile=?",
636                         new Object[]{acc.isExpanded(), acc.getName(), profile.getUuid()
637                         });
638
639                 if (wasExpanded) {
640                     debug("accounts", String.format("Collapsing account '%s'", acc.getName()));
641                     arrow.setRotation(0);
642                     animator.rotationBy(180);
643
644                     // removing all child accounts from the view
645                     int start = -1, count = 0;
646                     try (LockHolder ignored = Data.accounts.lockForWriting()) {
647                         for (int i = 0; i < Data.accounts.size(); i++) {
648                             if (acc.isParentOf(Data.accounts.get(i))) {
649 //                                debug("accounts", String.format("Found a child '%s' at position %d",
650 //                                        Data.accounts.get(i).getName(), i));
651                                 if (start == -1) {
652                                     start = i;
653                                 }
654                                 count++;
655                             }
656                             else {
657                                 if (start != -1) {
658 //                                    debug("accounts",
659 //                                            String.format("Found a non-child '%s' at position %d",
660 //                                                    Data.accounts.get(i).getName(), i));
661                                     break;
662                                 }
663                             }
664                         }
665
666                         if (start != -1) {
667                             for (int j = 0; j < count; j++) {
668 //                                debug("accounts", String.format("Removing item %d: %s", start + j,
669 //                                        Data.accounts.get(start).getName()));
670                                 Data.accounts.removeQuietly(start);
671                             }
672
673                             mAccountSummaryFragment.modelAdapter
674                                     .notifyItemRangeRemoved(start, count);
675                         }
676                     }
677                 }
678                 else {
679                     debug("accounts", String.format("Expanding account '%s'", acc.getName()));
680                     arrow.setRotation(180);
681                     animator.rotationBy(-180);
682                     List<LedgerAccount> children = profile.loadVisibleChildAccountsOf(acc);
683                     try (LockHolder ignored = Data.accounts.lockForWriting()) {
684                         int parentPos = Data.accounts.indexOf(acc);
685                         if (parentPos != -1) {
686                             // may have disappeared in a concurrent refresh operation
687                             Data.accounts.addAllQuietly(parentPos + 1, children);
688                             mAccountSummaryFragment.modelAdapter
689                                     .notifyItemRangeInserted(parentPos + 1, children.size());
690                         }
691                     }
692                 }
693                 break;
694             case R.id.account_row_acc_amounts:
695                 if (acc.getAmountCount() > AccountSummaryAdapter.AMOUNT_LIMIT) {
696                     acc.toggleAmountsExpanded();
697                     DbOpQueue
698                             .add("update accounts set amounts_expanded=? where name=? and profile=?",
699                                     new Object[]{acc.amountsExpanded(), acc.getName(),
700                                                  profile.getUuid()
701                                     });
702                     Data.accounts.triggerItemChangedNotification(acc);
703                 }
704                 break;
705         }
706     }
707
708     public class SectionsPagerAdapter extends FragmentPagerAdapter {
709
710         SectionsPagerAdapter(FragmentManager fm) {
711             super(fm);
712         }
713
714         @NotNull
715         @Override
716         public Fragment getItem(int position) {
717             debug("main", String.format(Locale.ENGLISH, "Switching to fragment %d", position));
718             switch (position) {
719                 case 0:
720 //                    debug("flow", "Creating account summary fragment");
721                     return mAccountSummaryFragment = new AccountSummaryFragment();
722                 case 1:
723                     return new TransactionListFragment();
724                 default:
725                     throw new IllegalStateException(
726                             String.format("Unexpected fragment index: " + "%d", position));
727             }
728         }
729
730         @Override
731         public int getCount() {
732             return 2;
733         }
734     }
735 }