]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
notify profile list adapter when the currently selected profile changes
[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", fragmentManager.getBackStackEntryCount()));
458
459                 super.onBackPressed();
460             }
461         }
462     }
463     public void updateLastUpdateTextFromDB() {
464         {
465             final MobileLedgerProfile profile = Data.profile.get();
466             long last_update =
467                     (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
468
469             Log.d("transactions", String.format("Last update = %d", last_update));
470             if (last_update == 0) {
471                 Data.lastUpdateDate.set(null);
472             }
473             else {
474                 Data.lastUpdateDate.set(new Date(last_update));
475             }
476         }
477     }
478     public void scheduleTransactionListRetrieval() {
479         if (Data.profile.get() == null) return;
480
481         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
482
483         retrieveTransactionsTask.execute();
484     }
485     public void onStopTransactionRefreshClick(View view) {
486         Log.d("interactive", "Cancelling transactions refresh");
487         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
488         bTransactionListCancelDownload.setEnabled(false);
489     }
490     public void onRetrieveDone(String error) {
491         progressLayout.setVisibility(View.GONE);
492
493         if (error == null) {
494             updateLastUpdateTextFromDB();
495
496             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
497             TransactionListViewModel.scheduleTransactionListReload();
498         }
499         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
500     }
501     public void onRetrieveStart() {
502         bTransactionListCancelDownload.setEnabled(true);
503         progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
504         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
505         progressBar.setIndeterminate(true);
506         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
507         else progressBar.setProgress(0);
508         progressLayout.setVisibility(View.VISIBLE);
509     }
510     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
511         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
512             (progress.getTotal() == 0))
513         {
514             progressBar.setIndeterminate(true);
515         }
516         else {
517             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
518                 progressBar.setMin(0);
519             }
520             progressBar.setMax(progress.getTotal());
521             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
522                 progressBar.setProgress(progress.getProgress(), true);
523             }
524             else progressBar.setProgress(progress.getProgress());
525             progressBar.setIndeterminate(false);
526         }
527     }
528     public void fabShouldShow() {
529         MobileLedgerProfile profile = Data.profile.get();
530         if ((profile != null) && profile.isPostingPermitted()) fab.show();
531     }
532     public void navProfilesHeadClicked(View view) {
533         if (profileListExpanded) {
534             collapseProfileList();
535         }
536         else {
537             expandProfileList();
538         }
539     }
540     private void expandProfileList() {
541         profileListExpanded = true;
542
543
544         profileListContainer.setVisibility(View.VISIBLE);
545         profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
546         profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
547         profileListHeadMore.setVisibility(View.VISIBLE);
548         profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
549         findViewById(R.id.nav_profile_list).setMinimumHeight(
550                 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
551                        Data.profiles.size()));
552     }
553     private void collapseProfileList() {
554         profileListExpanded = false;
555
556         final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
557         animation.setAnimationListener(new Animation.AnimationListener() {
558             @Override
559             public void onAnimationStart(Animation animation) {
560
561             }
562             @Override
563             public void onAnimationEnd(Animation animation) {
564                 profileListContainer.setVisibility(View.GONE);
565             }
566             @Override
567             public void onAnimationRepeat(Animation animation) {
568
569             }
570         });
571         mProfileListAdapter.stopEditingProfiles();
572
573         profileListContainer.startAnimation(animation);
574         profileListHeadArrow.setRotation(0f);
575         profileListHeadArrow
576                 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
577         profileListHeadMore.setVisibility(View.GONE);
578     }
579     public void onProfileRowClicked(View v) {
580         Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
581     }
582     public void enableProfileModifications() {
583         profileModificationEnabled = true;
584         ViewGroup profileList = findViewById(R.id.nav_profile_list);
585         for (int i = 0; i < profileList.getChildCount(); i++) {
586             View aRow = profileList.getChildAt(i);
587             aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
588             aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
589         }
590         // FIXME enable rearranging
591
592     }
593     public void disableProfileModifications() {
594         profileModificationEnabled = false;
595         ViewGroup profileList = findViewById(R.id.nav_profile_list);
596         for (int i = 0; i < profileList.getChildCount(); i++) {
597             View aRow = profileList.getChildAt(i);
598             aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
599             aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.INVISIBLE);
600         }
601         // FIXME disable rearranging
602
603     }
604     public void onAccountSummaryRowViewClicked(View view) {
605         ViewGroup row = (ViewGroup) view.getParent();
606         LedgerAccount acc = (LedgerAccount) row.getTag();
607         switch (view.getId()) {
608             case R.id.account_row_acc_name:
609             case R.id.account_expander_container:
610                 Log.d("accounts", "Account expander clicked");
611                 if (!acc.hasSubAccounts()) return;
612
613                 boolean wasExpanded = acc.isExpanded();
614
615                 View arrow = row.findViewById(R.id.account_expander_container);
616
617                 arrow.clearAnimation();
618                 ViewPropertyAnimator animator = arrow.animate();
619
620                 acc.toggleExpanded();
621                 DbOpQueue.add("update accounts set expanded=? where name=? and profile=?",
622                         new Object[]{acc.isExpanded(), acc.getName(), Data.profile.get().getUuid()
623                         });
624
625                 if (wasExpanded) {
626                     Log.d("accounts", String.format("Collapsing account '%s'", acc.getName()));
627                     arrow.setRotation(0);
628                     animator.rotationBy(180);
629
630                     // removing all child accounts from the view
631                     int start = -1, count = 0;
632                     try (LockHolder lh = Data.accounts.lockForWriting()) {
633                         for (int i = 0; i < Data.accounts.size(); i++) {
634                             if (acc.isParentOf(Data.accounts.get(i))) {
635 //                                Log.d("accounts", String.format("Found a child '%s' at position %d",
636 //                                        Data.accounts.get(i).getName(), i));
637                                 if (start == -1) {
638                                     start = i;
639                                 }
640                                 count++;
641                             }
642                             else {
643                                 if (start != -1) {
644 //                                    Log.d("accounts",
645 //                                            String.format("Found a non-child '%s' at position %d",
646 //                                                    Data.accounts.get(i).getName(), i));
647                                     break;
648                                 }
649                             }
650                         }
651
652                         if (start != -1) {
653                             for (int j = 0; j < count; j++) {
654 //                                Log.d("accounts", String.format("Removing item %d: %s", start + j,
655 //                                        Data.accounts.get(start).getName()));
656                                 Data.accounts.removeQuietly(start);
657                             }
658
659                             mAccountSummaryFragment.modelAdapter
660                                     .notifyItemRangeRemoved(start, count);
661                         }
662                     }
663                 }
664                 else {
665                     Log.d("accounts", String.format("Expanding account '%s'", acc.getName()));
666                     arrow.setRotation(180);
667                     animator.rotationBy(-180);
668                     List<LedgerAccount> children =
669                             Data.profile.get().loadVisibleChildAccountsOf(acc);
670                     try (LockHolder lh = Data.accounts.lockForWriting()) {
671                         int parentPos = Data.accounts.indexOf(acc);
672                         if (parentPos != -1) {
673                             // may have disappeared in a concurrent refresh operation
674                             Data.accounts.addAllQuietly(parentPos + 1, children);
675                             mAccountSummaryFragment.modelAdapter
676                                     .notifyItemRangeInserted(parentPos + 1, children.size());
677                         }
678                     }
679                 }
680                 break;
681             case R.id.account_row_acc_amounts:
682                 if (acc.getAmountCount() > AccountSummaryAdapter.AMOUNT_LIMIT) {
683                     acc.toggleAmountsExpanded();
684                     DbOpQueue
685                             .add("update accounts set amounts_expanded=? where name=? and profile=?",
686                                     new Object[]{acc.amountsExpanded(), acc.getName(),
687                                                  Data.profile.get().getUuid()
688                                     });
689                     Data.accounts.triggerItemChangedNotification(acc);
690                 }
691                 break;
692         }
693     }
694
695     public class SectionsPagerAdapter extends FragmentPagerAdapter {
696
697         public SectionsPagerAdapter(FragmentManager fm) {
698             super(fm);
699         }
700
701         @Override
702         public Fragment getItem(int position) {
703             Log.d("main", String.format("Switching to fragment %d", position));
704             switch (position) {
705                 case 0:
706 //                    Log.d("flow", "Creating account summary fragment");
707                     return mAccountSummaryFragment = new AccountSummaryFragment();
708                 case 1:
709                     return new TransactionListFragment();
710                 default:
711                     throw new IllegalStateException(
712                             String.format("Unexpected fragment index: " + "%d", position));
713             }
714         }
715
716         @Override
717         public int getCount() {
718             return 2;
719         }
720     }
721 }