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