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