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