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.
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.
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/>.
18 package net.ktnx.mobileledger.ui.activity;
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;
38 import com.google.android.material.floatingactionbutton.FloatingActionButton;
40 import net.ktnx.mobileledger.R;
41 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
42 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
43 import net.ktnx.mobileledger.model.Data;
44 import net.ktnx.mobileledger.model.LedgerAccount;
45 import net.ktnx.mobileledger.model.MobileLedgerProfile;
46 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
47 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
48 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
49 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
50 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
51 import net.ktnx.mobileledger.utils.Colors;
52 import net.ktnx.mobileledger.utils.MLDB;
54 import java.lang.ref.WeakReference;
55 import java.text.DateFormat;
56 import java.util.ArrayList;
57 import java.util.Date;
58 import java.util.List;
59 import java.util.Observable;
60 import java.util.Observer;
62 import androidx.appcompat.app.ActionBarDrawerToggle;
63 import androidx.appcompat.widget.Toolbar;
64 import androidx.core.view.GravityCompat;
65 import androidx.drawerlayout.widget.DrawerLayout;
66 import androidx.fragment.app.Fragment;
67 import androidx.fragment.app.FragmentManager;
68 import androidx.fragment.app.FragmentPagerAdapter;
69 import androidx.recyclerview.widget.LinearLayoutManager;
70 import androidx.recyclerview.widget.RecyclerView;
71 import androidx.viewpager.widget.ViewPager;
73 public class MainActivity extends ProfileThemedActivity {
74 private static final String STATE_CURRENT_PAGE = "current_page";
75 private static final String BUNDLE_SAVED_STATE = "bundle_savedState";
76 public AccountSummaryFragment mAccountSummaryFragment;
78 private LinearLayout profileListContainer;
79 private View profileListHeadArrow, profileListHeadMore, profileListHeadCancel;
80 private LinearLayout profileListHeadMoreAndCancel;
81 private FragmentManager fragmentManager;
82 private TextView tvLastUpdate;
83 private RetrieveTransactionsTask retrieveTransactionsTask;
84 private View bTransactionListCancelDownload;
85 private ProgressBar progressBar;
86 private LinearLayout progressLayout;
87 private SectionsPagerAdapter mSectionsPagerAdapter;
88 private ViewPager mViewPager;
89 private FloatingActionButton fab;
90 private boolean profileModificationEnabled = false;
91 private boolean profileListExpanded = false;
92 private ProfilesRecyclerViewAdapter mProfileListAdapter;
94 protected void onStart() {
99 updateLastUpdateTextFromDB();
100 Date lastUpdate = Data.lastUpdateDate.get();
102 long now = new Date().getTime();
103 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
104 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
106 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
107 lastUpdate.getTime() / 1000f, now / 1000f));
109 scheduleTransactionListRetrieval();
113 protected void onSaveInstanceState(Bundle outState) {
114 super.onSaveInstanceState(outState);
115 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
118 protected void onCreate(Bundle savedInstanceState) {
119 super.onCreate(savedInstanceState);
121 setContentView(R.layout.activity_main);
123 fab = findViewById(R.id.btn_add_transaction);
124 profileListContainer = findViewById(R.id.nav_profile_list_container);
125 profileListHeadArrow = findViewById(R.id.nav_profiles_arrow);
126 profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
127 profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
128 profileListHeadMoreAndCancel = findViewById(R.id.nav_profile_list_head_buttons);
129 drawer = findViewById(R.id.drawer_layout);
130 tvLastUpdate = findViewById(R.id.transactions_last_update);
131 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
132 progressBar = findViewById(R.id.transaction_list_progress_bar);
133 progressLayout = findViewById(R.id.transaction_progress_layout);
134 fragmentManager = getSupportFragmentManager();
135 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
136 mViewPager = findViewById(R.id.root_frame);
138 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
139 if (extra != null && savedInstanceState == null) savedInstanceState = extra;
142 Toolbar toolbar = findViewById(R.id.toolbar);
143 setSupportActionBar(toolbar);
145 Data.profile.addObserver((o, arg) -> {
146 MobileLedgerProfile profile = Data.profile.get();
147 runOnUiThread(() -> {
148 if (profile == null) setTitle(R.string.app_name);
149 else setTitle(profile.getName());
150 updateLastUpdateTextFromDB();
151 if (profile.isPostingPermitted()) {
152 toolbar.setSubtitle(null);
156 toolbar.setSubtitle(R.string.profile_subitlte_read_only);
160 int newProfileTheme = profile.getThemeId();
161 if (newProfileTheme != Colors.profileThemeId) {
162 Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
164 profileThemeChanged();
165 Colors.profileThemeId = newProfileTheme;
169 Data.profiles.addObserver((o, arg) -> {
170 findViewById(R.id.nav_profile_list).setMinimumHeight(
171 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
172 Data.profiles.size()));
173 mProfileListAdapter.notifyDataSetChanged();
176 ActionBarDrawerToggle toggle =
177 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
178 R.string.navigation_drawer_close);
179 drawer.addDrawerListener(toggle);
182 TextView ver = drawer.findViewById(R.id.drawer_version_text);
186 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
187 ver.setText(pi.versionName);
189 catch (Exception e) {
193 if (progressBar == null)
194 throw new RuntimeException("Can't get hold on the transaction value progress bar");
195 if (progressLayout == null) throw new RuntimeException(
196 "Can't get hold on the transaction value progress bar layout");
198 markDrawerItemCurrent(R.id.nav_account_summary);
200 mViewPager.setAdapter(mSectionsPagerAdapter);
201 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
203 public void onPageSelected(int position) {
206 markDrawerItemCurrent(R.id.nav_account_summary);
209 markDrawerItemCurrent(R.id.nav_latest_transactions);
212 Log.e("MainActivity", String.format("Unexpected page index %d", position));
215 super.onPageSelected(position);
219 if (savedInstanceState != null) {
220 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
221 if (currentPage != -1) {
222 mViewPager.setCurrentItem(currentPage, false);
226 Data.lastUpdateDate.addObserver((o, arg) -> {
227 Log.d("main", "lastUpdateDate changed");
228 runOnUiThread(this::updateLastUpdateDisplay);
231 updateLastUpdateDisplay();
233 findViewById(R.id.btn_no_profiles_add)
234 .setOnClickListener(v -> startEditProfileActivity(null));
236 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
238 findViewById(R.id.nav_new_profile_button)
239 .setOnClickListener(v -> startEditProfileActivity(null));
241 RecyclerView root = findViewById(R.id.nav_profile_list);
243 throw new RuntimeException("Can't get hold on the transaction value view");
245 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
246 root.setAdapter(mProfileListAdapter);
248 mProfileListAdapter.addEditingProfilesObserver(new Observer() {
250 public void update(Observable o, Object arg) {
251 if (mProfileListAdapter.isEditingProfiles()) {
252 profileListHeadArrow.clearAnimation();
253 profileListHeadArrow.setVisibility(View.GONE);
254 profileListHeadMore.setVisibility(View.GONE);
255 profileListHeadCancel.setVisibility(View.VISIBLE);
258 profileListHeadArrow.setRotation(180f);
259 profileListHeadArrow.setVisibility(View.VISIBLE);
260 profileListHeadCancel.setVisibility(View.GONE);
261 profileListHeadMore.setVisibility(View.GONE);
263 .setVisibility(profileListExpanded ? View.VISIBLE : View.GONE);
268 LinearLayoutManager llm = new LinearLayoutManager(this);
270 llm.setOrientation(RecyclerView.VERTICAL);
271 root.setLayoutManager(llm);
273 profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
274 profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
275 profileListHeadMoreAndCancel
276 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
278 drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
280 public void onDrawerClosed(View drawerView) {
281 super.onDrawerClosed(drawerView);
282 collapseProfileList();
286 private void updateLastUpdateDisplay() {
287 TextView v = findViewById(R.id.transactions_last_update);
288 Date date = Data.lastUpdateDate.get();
290 v.setText(R.string.transaction_last_update_never);
291 Log.d("main", "no last update date :(");
294 final String text = DateFormat.getDateTimeInstance().format(date);
296 Log.d("main", String.format("Date formatted: %s", text));
299 private void profileThemeChanged() {
300 setupProfileColors();
302 Bundle bundle = new Bundle();
303 onSaveInstanceState(bundle);
304 // restart activity to reflect theme change
306 Intent intent = new Intent(this, this.getClass());
307 intent.putExtra(BUNDLE_SAVED_STATE, bundle);
308 startActivity(intent);
310 public void startEditProfileActivity(MobileLedgerProfile profile) {
311 Intent intent = new Intent(this, ProfileDetailActivity.class);
312 Bundle args = new Bundle();
313 if (profile != null) {
314 int index = Data.getProfileIndex(profile);
315 if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
317 intent.putExtras(args);
318 startActivity(intent, args);
320 private void setupProfile() {
321 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
322 MobileLedgerProfile profile;
324 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
326 if (Data.profiles.getList().isEmpty()) {
327 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
328 findViewById(R.id.pager_layout).setVisibility(View.GONE);
332 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
333 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
335 if (profile == null) profile = Data.profiles.get(0);
337 if (profile == null) throw new AssertionError("profile must have a value");
339 Data.setCurrentProfile(profile);
341 public void fabNewTransactionClicked(View view) {
342 Intent intent = new Intent(this, NewTransactionActivity.class);
343 startActivity(intent);
344 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
346 public void navSettingsClicked(View view) {
347 Intent intent = new Intent(this, SettingsActivity.class);
348 startActivity(intent);
349 drawer.closeDrawers();
351 public void markDrawerItemCurrent(int id) {
352 TextView item = drawer.findViewById(id);
353 item.setBackgroundColor(Colors.tableRowDarkBG);
355 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
356 for (int i = 0; i < actions.getChildCount(); i++) {
357 View view = actions.getChildAt(i);
358 if (view.getId() != id) {
359 view.setBackgroundColor(Color.TRANSPARENT);
363 public void onAccountSummaryClicked(View view) {
364 drawer.closeDrawers();
366 showAccountSummaryFragment();
368 private void showAccountSummaryFragment() {
369 mViewPager.setCurrentItem(0, true);
370 TransactionListFragment.accountFilter.set(null);
371 // FragmentTransaction ft = fragmentManager.beginTransaction();
372 // accountSummaryFragment = new AccountSummaryFragment();
373 // ft.replace(R.id.root_frame, accountSummaryFragment);
375 // currentFragment = accountSummaryFragment;
377 public void onLatestTransactionsClicked(View view) {
378 drawer.closeDrawers();
380 showTransactionsFragment(null);
382 private void resetFragmentBackStack() {
383 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
385 private void showTransactionsFragment(LedgerAccount account) {
386 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
387 mViewPager.setCurrentItem(1, true);
388 // FragmentTransaction ft = fragmentManager.beginTransaction();
389 // if (transactionListFragment == null) {
390 // Log.d("flow", "MainActivity creating TransactionListFragment");
391 // transactionListFragment = new TransactionListFragment();
393 // Bundle bundle = new Bundle();
394 // if (account != null) {
395 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
396 // account.getName());
398 // transactionListFragment.setArguments(bundle);
399 // ft.replace(R.id.root_frame, transactionListFragment);
400 // if (account != null)
401 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
404 // currentFragment = transactionListFragment;
406 public void showAccountTransactions(LedgerAccount account) {
407 showTransactionsFragment(account);
410 public void onBackPressed() {
411 DrawerLayout drawer = findViewById(R.id.drawer_layout);
412 if (drawer.isDrawerOpen(GravityCompat.START)) {
413 drawer.closeDrawer(GravityCompat.START);
417 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
419 super.onBackPressed();
422 public void updateLastUpdateTextFromDB() {
424 final MobileLedgerProfile profile = Data.profile.get();
426 (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
428 Log.d("transactions", String.format("Last update = %d", last_update));
429 if (last_update == 0) {
430 Data.lastUpdateDate.set(null);
433 Data.lastUpdateDate.set(new Date(last_update));
437 public void scheduleTransactionListRetrieval() {
438 if (Data.profile.get() == null) return;
440 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
442 retrieveTransactionsTask.execute();
444 public void onStopTransactionRefreshClick(View view) {
445 Log.d("interactive", "Cancelling transactions refresh");
446 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
447 bTransactionListCancelDownload.setEnabled(false);
449 public void onRetrieveDone(String error) {
450 progressLayout.setVisibility(View.GONE);
453 updateLastUpdateTextFromDB();
455 new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
456 TransactionListViewModel.scheduleTransactionListReload();
458 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
460 public void onRetrieveStart() {
461 bTransactionListCancelDownload.setEnabled(true);
462 progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
463 progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
464 progressBar.setIndeterminate(true);
465 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
466 else progressBar.setProgress(0);
467 progressLayout.setVisibility(View.VISIBLE);
469 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
470 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
471 (progress.getTotal() == 0))
473 progressBar.setIndeterminate(true);
476 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
477 progressBar.setMin(0);
479 progressBar.setMax(progress.getTotal());
480 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
481 progressBar.setProgress(progress.getProgress(), true);
483 else progressBar.setProgress(progress.getProgress());
484 progressBar.setIndeterminate(false);
487 public void fabShouldShow() {
488 MobileLedgerProfile profile = Data.profile.get();
489 if ((profile != null) && profile.isPostingPermitted()) fab.show();
491 public void navProfilesHeadClicked(View view) {
492 if (profileListExpanded) {
493 collapseProfileList();
499 private void expandProfileList() {
500 profileListExpanded = true;
503 profileListContainer.setVisibility(View.VISIBLE);
504 profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
505 profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
506 profileListHeadMore.setVisibility(View.VISIBLE);
507 profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
508 findViewById(R.id.nav_profile_list).setMinimumHeight(
509 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
510 Data.profiles.size()));
512 private void collapseProfileList() {
513 profileListExpanded = false;
515 final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
516 animation.setAnimationListener(new Animation.AnimationListener() {
518 public void onAnimationStart(Animation animation) {
522 public void onAnimationEnd(Animation animation) {
523 profileListContainer.setVisibility(View.GONE);
526 public void onAnimationRepeat(Animation animation) {
530 mProfileListAdapter.stopEditingProfiles();
532 profileListContainer.startAnimation(animation);
533 profileListHeadArrow.setRotation(0f);
535 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
536 profileListHeadMore.setVisibility(View.GONE);
538 public void onProfileRowClicked(View v) {
539 Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
541 public void enableProfileModifications() {
542 profileModificationEnabled = true;
543 ViewGroup profileList = findViewById(R.id.nav_profile_list);
544 for (int i = 0; i < profileList.getChildCount(); i++) {
545 View aRow = profileList.getChildAt(i);
546 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
547 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
549 // FIXME enable rearranging
552 public void disableProfileModifications() {
553 profileModificationEnabled = false;
554 ViewGroup profileList = findViewById(R.id.nav_profile_list);
555 for (int i = 0; i < profileList.getChildCount(); i++) {
556 View aRow = profileList.getChildAt(i);
557 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
558 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.INVISIBLE);
560 // FIXME disable rearranging
563 public void onAccountSummaryRowViewClicked(View view) {
564 ViewGroup row = (ViewGroup) view.getParent();
565 LedgerAccount acc = (LedgerAccount) row.getTag();
566 switch (view.getId()) {
567 case R.id.account_row_acc_name:
568 case R.id.account_expander_container:
569 Log.d("accounts", "Account expander clicked");
570 if (!acc.hasSubAccounts()) return;
572 boolean wasExpanded = acc.isExpanded();
574 View arrow = row.findViewById(R.id.account_expander_container);
576 arrow.clearAnimation();
577 ViewPropertyAnimator animator = arrow.animate();
579 acc.toggleExpanded();
580 Data.profile.get().storeAccount(MLDB.getDatabase(), acc);
583 Log.d("accounts", String.format("Collapsing account '%s'", acc.getName()));
584 arrow.setRotation(0);
585 animator.rotationBy(180);
587 // removing all child accounts from the view
588 int start = -1, count = 0;
590 final ArrayList<LedgerAccount> accountList = Data.accounts.get();
591 for (LedgerAccount a : accountList) {
592 if (acc.isParentOf(a)) {
607 for (int j = 0; j < count; j++) {
608 Log.d("accounts", String.format("Removing item %d: %s", start + j,
609 accountList.get(start).getName()));
610 accountList.remove(start);
613 mAccountSummaryFragment.modelAdapter.notifyItemRangeRemoved(start, count);
617 Log.d("accounts", String.format("Expanding account '%s'", acc.getName()));
618 arrow.setRotation(180);
619 animator.rotationBy(-180);
620 ArrayList<LedgerAccount> accounts = Data.accounts.get();
621 List<LedgerAccount> children =
622 Data.profile.get().loadVisibleChildAccountsOf(acc);
623 int parentPos = accounts.indexOf(acc);
624 if (parentPos == -1) throw new RuntimeException(
625 "Can't find index of clicked account " + acc.getName());
626 accounts.addAll(parentPos + 1, children);
627 mAccountSummaryFragment.modelAdapter
628 .notifyItemRangeInserted(parentPos + 1, children.size());
631 case R.id.account_row_acc_amounts:
632 showAccountTransactions(acc);
637 public class SectionsPagerAdapter extends FragmentPagerAdapter {
639 public SectionsPagerAdapter(FragmentManager fm) {
644 public Fragment getItem(int position) {
645 Log.d("main", String.format("Switching to fragment %d", position));
648 // Log.d("flow", "Creating account summary fragment");
649 return mAccountSummaryFragment = new AccountSummaryFragment();
651 return new TransactionListFragment();
653 throw new IllegalStateException(
654 String.format("Unexpected fragment index: " + "%d", position));
659 public int getCount() {