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