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