]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
d20e63f05ea8a886264598fe52e7e103158447ec
[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 SectionsPagerAdapter mSectionsPagerAdapter;
94     private ViewPager mViewPager;
95     private FloatingActionButton fab;
96     private ProfilesRecyclerViewAdapter mProfileListAdapter;
97     private int mCurrentPage;
98     private String mAccountFilter;
99     private boolean mBackMeansToAccountList = false;
100     private Toolbar mToolbar;
101     private DrawerLayout.SimpleDrawerListener drawerListener;
102     private ActionBarDrawerToggle barDrawerToggle;
103     private ViewPager.SimpleOnPageChangeListener pageChangeListener;
104     private MobileLedgerProfile profile;
105     @Override
106     protected void onStart() {
107         super.onStart();
108
109         debug("flow", String.format(Locale.ENGLISH,
110                 "MainActivity.onStart(), currentPage is %d, accountFilter is %s", mCurrentPage,
111                 (mAccountFilter == null) ? "<NULL>" : mAccountFilter));
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 onResume() {
147         super.onResume();
148         fabShouldShow();
149     }
150     @Override
151     protected void onCreate(Bundle savedInstanceState) {
152         super.onCreate(savedInstanceState);
153         debug("flow", "MainActivity.onCreate()");
154         setContentView(R.layout.activity_main);
155
156         fab = findViewById(R.id.btn_add_transaction);
157         profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
158         profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
159         LinearLayout profileListHeadMoreAndCancel =
160                 findViewById(R.id.nav_profile_list_head_buttons);
161         profileListHeadAddProfile = findViewById(R.id.nav_new_profile_button);
162         drawer = findViewById(R.id.drawer_layout);
163         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
164         fragmentManager = getSupportFragmentManager();
165         mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
166         mViewPager = findViewById(R.id.root_frame);
167
168         Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
169         if (extra != null && savedInstanceState == null) savedInstanceState = extra;
170
171
172         mToolbar = findViewById(R.id.toolbar);
173         setSupportActionBar(mToolbar);
174
175         Data.profile.observe(this, this::onProfileChanged);
176
177         Data.profiles.observe(this, this::onProfileListChanged);
178
179         if (barDrawerToggle == null) {
180             barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
181                     R.string.navigation_drawer_open, R.string.navigation_drawer_close);
182             drawer.addDrawerListener(barDrawerToggle);
183         }
184         barDrawerToggle.syncState();
185
186         TextView ver = drawer.findViewById(R.id.drawer_version_text);
187
188         try {
189             PackageInfo pi =
190                     getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
191             ver.setText(pi.versionName);
192         }
193         catch (Exception e) {
194             e.printStackTrace();
195         }
196
197         markDrawerItemCurrent(R.id.nav_account_summary);
198
199         mViewPager.setAdapter(mSectionsPagerAdapter);
200
201         if (pageChangeListener == null) {
202             pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
203                 @Override
204                 public void onPageSelected(int position) {
205                     mCurrentPage = position;
206                     switch (position) {
207                         case 0:
208                             markDrawerItemCurrent(R.id.nav_account_summary);
209                             break;
210                         case 1:
211                             markDrawerItemCurrent(R.id.nav_latest_transactions);
212                             break;
213                         default:
214                             Log.e("MainActivity",
215                                     String.format("Unexpected page index %d", position));
216                     }
217
218                     super.onPageSelected(position);
219                 }
220             };
221             mViewPager.addOnPageChangeListener(pageChangeListener);
222         }
223
224         mCurrentPage = 0;
225         if (savedInstanceState != null) {
226             int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
227             if (currentPage != -1) {
228                 mCurrentPage = currentPage;
229             }
230             mAccountFilter = savedInstanceState.getString(STATE_ACC_FILTER, null);
231         }
232         else mAccountFilter = null;
233
234         Data.lastUpdateDate.observe(this, this::updateLastUpdateDisplay);
235
236         findViewById(R.id.btn_no_profiles_add)
237                 .setOnClickListener(v -> startEditProfileActivity(null));
238
239         findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
240
241         findViewById(R.id.nav_new_profile_button)
242                 .setOnClickListener(v -> startEditProfileActivity(null));
243
244         RecyclerView root = findViewById(R.id.nav_profile_list);
245         if (root == null)
246             throw new RuntimeException("Can't get hold on the transaction value view");
247
248         if (mProfileListAdapter == null) mProfileListAdapter = new ProfilesRecyclerViewAdapter();
249         root.setAdapter(mProfileListAdapter);
250
251         mProfileListAdapter.editingProfiles.observe(this, newValue -> {
252             if (newValue) {
253                 profileListHeadMore.setVisibility(View.GONE);
254                 profileListHeadCancel.setVisibility(View.VISIBLE);
255                 profileListHeadAddProfile.setVisibility(View.VISIBLE);
256                 if (drawer.isDrawerOpen(GravityCompat.START)) {
257                     profileListHeadMore.startAnimation(
258                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
259                     profileListHeadCancel.startAnimation(
260                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
261                     profileListHeadAddProfile.startAnimation(
262                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
263                 }
264             }
265             else {
266                 profileListHeadCancel.setVisibility(View.GONE);
267                 profileListHeadMore.setVisibility(View.VISIBLE);
268                 profileListHeadAddProfile.setVisibility(View.GONE);
269                 if (drawer.isDrawerOpen(GravityCompat.START)) {
270                     profileListHeadCancel.startAnimation(
271                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
272                     profileListHeadMore.startAnimation(
273                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
274                     profileListHeadAddProfile.startAnimation(
275                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
276                 }
277             }
278
279             mProfileListAdapter.notifyDataSetChanged();
280         });
281
282         LinearLayoutManager llm = new LinearLayoutManager(this);
283
284         llm.setOrientation(RecyclerView.VERTICAL);
285         root.setLayoutManager(llm);
286
287         profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
288         profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
289         profileListHeadMoreAndCancel
290                 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
291         if (drawerListener == null) {
292             drawerListener = new DrawerLayout.SimpleDrawerListener() {
293                 @Override
294                 public void onDrawerClosed(View drawerView) {
295                     super.onDrawerClosed(drawerView);
296                     mProfileListAdapter.setAnimationsEnabled(false);
297                     mProfileListAdapter.editingProfiles.setValue(false);
298                 }
299                 @Override
300                 public void onDrawerOpened(View drawerView) {
301                     super.onDrawerOpened(drawerView);
302                     mProfileListAdapter.setAnimationsEnabled(true);
303                 }
304             };
305             drawer.addDrawerListener(drawerListener);
306         }
307         setupProfile();
308     }
309     private void scheduleDataRetrievalIfStale(Date lastUpdate) {
310         long now = new Date().getTime();
311         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
312             if (lastUpdate == null) debug("db::", "WEB data never fetched. scheduling a fetch");
313             else debug("db", String.format(Locale.ENGLISH,
314                     "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
315                     lastUpdate.getTime() / 1000f, now / 1000f));
316
317             Data.scheduleTransactionListRetrieval(this);
318         }
319     }
320     private void createShortcuts(List<MobileLedgerProfile> list) {
321         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return;
322
323         List<ShortcutInfo> shortcuts = new ArrayList<>();
324         int i = 0;
325         for (MobileLedgerProfile p : list) {
326             if (!p.isPostingPermitted()) continue;
327
328             ShortcutInfo si = new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid())
329                     .setShortLabel(p.getName())
330                     .setIcon(Icon.createWithResource(this, R.drawable.svg_thick_plus_white))
331                     .setIntent(
332                             new Intent(Intent.ACTION_VIEW, null, this, NewTransactionActivity.class)
333                                     .putExtra("profile_uuid", p.getUuid())).setRank(i).build();
334             shortcuts.add(si);
335             i++;
336         }
337         ShortcutManager sm = getSystemService(ShortcutManager.class);
338         sm.setDynamicShortcuts(shortcuts);
339     }
340     private void onProfileListChanged(List<MobileLedgerProfile> newList) {
341         if (newList == null) {
342             // profiles not yet loaded from DB
343             findViewById(R.id.loading_layout).setVisibility(View.VISIBLE);
344             findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
345             findViewById(R.id.pager_layout).setVisibility(View.GONE);
346             return;
347         }
348
349         if (newList.isEmpty()) {
350             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
351             findViewById(R.id.pager_layout).setVisibility(View.GONE);
352             findViewById(R.id.loading_layout).setVisibility(View.GONE);
353             return;
354         }
355
356         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
357         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
358         findViewById(R.id.loading_layout).setVisibility(View.GONE);
359
360         findViewById(R.id.nav_profile_list).setMinimumHeight(
361                 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
362
363         debug("profiles", "profile list changed");
364         mProfileListAdapter.notifyDataSetChanged();
365
366         createShortcuts(newList);
367     }
368     /**
369      * called when the current profile has changed
370      */
371     private void onProfileChanged(MobileLedgerProfile profile) {
372         boolean haveProfile = profile != null;
373         findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
374         findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
375
376         if (haveProfile) setTitle(profile.getName());
377         else setTitle(R.string.app_name);
378
379         this.profile = profile;
380
381         mProfileListAdapter.notifyDataSetChanged();
382
383         int newProfileTheme = haveProfile ? profile.getThemeId() : -1;
384         if (newProfileTheme != Colors.profileThemeId) {
385             debug("profiles",
386                     String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
387                             newProfileTheme));
388             MainActivity.this.profileThemeChanged();
389             Colors.profileThemeId = newProfileTheme;
390             // profileThemeChanged would restart the activity, so no need to reload the
391             // data sets below
392             return;
393         }
394
395         drawer.closeDrawers();
396
397         Data.transactions.clear();
398         debug("transactions", "requesting list reload");
399         TransactionListViewModel.scheduleTransactionListReload();
400
401         Data.accounts.clear();
402         AccountSummaryViewModel.scheduleAccountListReload();
403
404         if (haveProfile) {
405             if (profile.isPostingPermitted()) {
406                 mToolbar.setSubtitle(null);
407                 fab.show();
408             }
409             else {
410                 mToolbar.setSubtitle(R.string.profile_subitlte_read_only);
411                 fab.hide();
412             }
413         }
414         else {
415             mToolbar.setSubtitle(null);
416             fab.hide();
417         }
418
419         updateLastUpdateTextFromDB();
420     }
421     private void updateLastUpdateDisplay(Date newValue) {
422         LinearLayout l = findViewById(R.id.transactions_last_update_layout);
423         TextView v = findViewById(R.id.transactions_last_update);
424         if (newValue == null) {
425             l.setVisibility(View.INVISIBLE);
426             debug("main", "no last update date :(");
427         }
428         else {
429             final String text = DateFormat.getDateTimeInstance().format(newValue);
430             v.setText(text);
431             l.setVisibility(View.VISIBLE);
432             debug("main", String.format("Date formatted: %s", text));
433         }
434
435         scheduleDataRetrievalIfStale(newValue);
436     }
437     private void profileThemeChanged() {
438         Bundle bundle = new Bundle();
439         onSaveInstanceState(bundle);
440
441         storeThemeIdInPrefs(profile.getThemeId());
442
443         // restart activity to reflect theme change
444         finish();
445
446         // un-hook all observed LiveData
447         Data.profile.removeObservers(this);
448         Data.profiles.removeObservers(this);
449         Data.lastUpdateDate.removeObservers(this);
450         Intent intent = new Intent(this, this.getClass());
451         intent.putExtra(BUNDLE_SAVED_STATE, bundle);
452         startActivity(intent);
453     }
454     private void storeThemeIdInPrefs(int themeId) {
455         // store the new theme id in the preferences
456         SharedPreferences prefs = getPreferences(MODE_PRIVATE);
457         SharedPreferences.Editor e = prefs.edit();
458         e.putInt(PREF_THEME_ID, themeId);
459         e.apply();
460     }
461     public void startEditProfileActivity(MobileLedgerProfile profile) {
462         Intent intent = new Intent(this, ProfileDetailActivity.class);
463         Bundle args = new Bundle();
464         if (profile != null) {
465             int index = Data.getProfileIndex(profile);
466             if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
467         }
468         intent.putExtras(args);
469         startActivity(intent, args);
470     }
471     private void setupProfile() {
472         MLDB.getOption(MLDB.OPT_PROFILE_UUID, null, new GetOptCallback() {
473             @Override
474             protected void onResult(String profileUUID) {
475                 MobileLedgerProfile startupProfile;
476
477                 startupProfile = Data.getProfile(profileUUID);
478                 Data.setCurrentProfile(startupProfile);
479             }
480         });
481     }
482     public void fabNewTransactionClicked(View view) {
483         Intent intent = new Intent(this, NewTransactionActivity.class);
484         startActivity(intent);
485         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
486     }
487     public void navSettingsClicked(View view) {
488         Intent intent = new Intent(this, SettingsActivity.class);
489         startActivity(intent);
490         drawer.closeDrawers();
491     }
492     public void markDrawerItemCurrent(int id) {
493         TextView item = drawer.findViewById(id);
494         item.setBackgroundColor(Colors.tableRowDarkBG);
495
496         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
497         for (int i = 0; i < actions.getChildCount(); i++) {
498             View view = actions.getChildAt(i);
499             if (view.getId() != id) {
500                 view.setBackgroundColor(Color.TRANSPARENT);
501             }
502         }
503     }
504     public void onAccountSummaryClicked(View view) {
505         drawer.closeDrawers();
506
507         showAccountSummaryFragment();
508     }
509     private void showAccountSummaryFragment() {
510         mViewPager.setCurrentItem(0, true);
511         Data.accountFilter.setValue(null);
512     }
513     public void onLatestTransactionsClicked(View view) {
514         drawer.closeDrawers();
515
516         showTransactionsFragment((String) null);
517     }
518     private void showTransactionsFragment(String accName) {
519         Data.accountFilter.setValue(accName);
520         mViewPager.setCurrentItem(1, true);
521     }
522     private void showTransactionsFragment(LedgerAccount account) {
523         showTransactionsFragment((account == null) ? null : account.getName());
524     }
525     public void showAccountTransactions(LedgerAccount account) {
526         mBackMeansToAccountList = true;
527         showTransactionsFragment(account);
528     }
529     @Override
530     public void onBackPressed() {
531         DrawerLayout drawer = findViewById(R.id.drawer_layout);
532         if (drawer.isDrawerOpen(GravityCompat.START)) {
533             drawer.closeDrawer(GravityCompat.START);
534         }
535         else {
536             if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
537                 Data.accountFilter.setValue(null);
538                 showAccountSummaryFragment();
539                 mBackMeansToAccountList = false;
540             }
541             else {
542                 debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
543                         fragmentManager.getBackStackEntryCount()));
544
545                 super.onBackPressed();
546             }
547         }
548     }
549     public void updateLastUpdateTextFromDB() {
550         if (profile == null) return;
551
552         long last_update = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
553
554         debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", last_update));
555         if (last_update == 0) {
556             Data.lastUpdateDate.postValue(null);
557         }
558         else {
559             Data.lastUpdateDate.postValue(new Date(last_update));
560         }
561     }
562     public void onStopTransactionRefreshClick(View view) {
563         debug("interactive", "Cancelling transactions refresh");
564         Data.stopTransactionsRetrieval();
565         bTransactionListCancelDownload.setEnabled(false);
566     }
567     public void onRetrieveDone(String error) {
568         Data.transactionRetrievalDone();
569         findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
570
571         if (error == null) {
572             updateLastUpdateTextFromDB();
573
574             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
575             TransactionListViewModel.scheduleTransactionListReload();
576         }
577         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
578     }
579     public void onRetrieveStart() {
580         ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
581         bTransactionListCancelDownload.setEnabled(true);
582         progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
583         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
584         progressBar.setIndeterminate(true);
585         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
586         else progressBar.setProgress(0);
587         findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
588     }
589     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
590         ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
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 }