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