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