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