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