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