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