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