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