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