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