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.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.AccountSummaryFragment;
48 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
49 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
50 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
51 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
52 import net.ktnx.mobileledger.utils.Colors;
53 import net.ktnx.mobileledger.utils.MLDB;
55 import java.lang.ref.WeakReference;
56 import java.text.DateFormat;
57 import java.util.ArrayList;
58 import java.util.Date;
59 import java.util.List;
60 import java.util.Observable;
61 import java.util.Observer;
63 import androidx.appcompat.app.ActionBarDrawerToggle;
64 import androidx.appcompat.widget.Toolbar;
65 import androidx.core.view.GravityCompat;
66 import androidx.drawerlayout.widget.DrawerLayout;
67 import androidx.fragment.app.Fragment;
68 import androidx.fragment.app.FragmentManager;
69 import androidx.fragment.app.FragmentPagerAdapter;
70 import androidx.recyclerview.widget.LinearLayoutManager;
71 import androidx.recyclerview.widget.RecyclerView;
72 import androidx.viewpager.widget.ViewPager;
74 public class MainActivity extends ProfileThemedActivity {
75 private static final String STATE_CURRENT_PAGE = "current_page";
76 private static final String BUNDLE_SAVED_STATE = "bundle_savedState";
77 public AccountSummaryFragment mAccountSummaryFragment;
79 private LinearLayout profileListContainer;
80 private View profileListHeadArrow, profileListHeadMore, profileListHeadCancel;
81 private LinearLayout profileListHeadMoreAndCancel;
82 private FragmentManager fragmentManager;
83 private TextView tvLastUpdate;
84 private RetrieveTransactionsTask retrieveTransactionsTask;
85 private View bTransactionListCancelDownload;
86 private ProgressBar progressBar;
87 private LinearLayout progressLayout;
88 private SectionsPagerAdapter mSectionsPagerAdapter;
89 private ViewPager mViewPager;
90 private FloatingActionButton fab;
91 private boolean profileModificationEnabled = false;
92 private boolean profileListExpanded = false;
93 private ProfilesRecyclerViewAdapter mProfileListAdapter;
95 protected void onStart() {
100 updateLastUpdateTextFromDB();
101 Date lastUpdate = Data.lastUpdateDate.get();
103 long now = new Date().getTime();
104 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
105 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
107 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
108 lastUpdate.getTime() / 1000f, now / 1000f));
110 scheduleTransactionListRetrieval();
114 protected void onSaveInstanceState(Bundle outState) {
115 super.onSaveInstanceState(outState);
116 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
119 protected void onCreate(Bundle savedInstanceState) {
120 super.onCreate(savedInstanceState);
122 setContentView(R.layout.activity_main);
124 fab = findViewById(R.id.btn_add_transaction);
125 profileListContainer = findViewById(R.id.nav_profile_list_container);
126 profileListHeadArrow = findViewById(R.id.nav_profiles_arrow);
127 profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
128 profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
129 profileListHeadMoreAndCancel = findViewById(R.id.nav_profile_list_head_buttons);
130 drawer = findViewById(R.id.drawer_layout);
131 tvLastUpdate = findViewById(R.id.transactions_last_update);
132 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
133 progressBar = findViewById(R.id.transaction_list_progress_bar);
134 progressLayout = findViewById(R.id.transaction_progress_layout);
135 fragmentManager = getSupportFragmentManager();
136 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
137 mViewPager = findViewById(R.id.root_frame);
139 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
140 if (extra != null && savedInstanceState == null) savedInstanceState = extra;
143 Toolbar toolbar = findViewById(R.id.toolbar);
144 setSupportActionBar(toolbar);
146 Data.profile.addObserver((o, arg) -> {
147 MobileLedgerProfile profile = Data.profile.get();
148 runOnUiThread(() -> {
149 if (profile == null) setTitle(R.string.app_name);
150 else setTitle(profile.getName());
151 updateLastUpdateTextFromDB();
152 if (profile.isPostingPermitted()) {
153 toolbar.setSubtitle(null);
157 toolbar.setSubtitle(R.string.profile_subitlte_read_only);
161 int newProfileTheme = profile.getThemeId();
162 if (newProfileTheme != Colors.profileThemeId) {
163 Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
165 profileThemeChanged();
166 Colors.profileThemeId = newProfileTheme;
170 Data.profiles.addObserver((o, arg) -> {
171 findViewById(R.id.nav_profile_list).setMinimumHeight(
172 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
173 Data.profiles.size()));
174 mProfileListAdapter.notifyDataSetChanged();
177 ActionBarDrawerToggle toggle =
178 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
179 R.string.navigation_drawer_close);
180 drawer.addDrawerListener(toggle);
183 TextView ver = drawer.findViewById(R.id.drawer_version_text);
187 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
188 ver.setText(pi.versionName);
190 catch (Exception e) {
194 if (progressBar == null)
195 throw new RuntimeException("Can't get hold on the transaction value progress bar");
196 if (progressLayout == null) throw new RuntimeException(
197 "Can't get hold on the transaction value progress bar layout");
199 markDrawerItemCurrent(R.id.nav_account_summary);
201 mViewPager.setAdapter(mSectionsPagerAdapter);
202 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
204 public void onPageSelected(int position) {
207 markDrawerItemCurrent(R.id.nav_account_summary);
210 markDrawerItemCurrent(R.id.nav_latest_transactions);
213 Log.e("MainActivity", String.format("Unexpected page index %d", position));
216 super.onPageSelected(position);
220 if (savedInstanceState != null) {
221 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
222 if (currentPage != -1) {
223 mViewPager.setCurrentItem(currentPage, false);
227 Data.lastUpdateDate.addObserver((o, arg) -> {
228 Log.d("main", "lastUpdateDate changed");
229 runOnUiThread(this::updateLastUpdateDisplay);
232 updateLastUpdateDisplay();
234 findViewById(R.id.btn_no_profiles_add)
235 .setOnClickListener(v -> startEditProfileActivity(null));
237 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
239 findViewById(R.id.nav_new_profile_button)
240 .setOnClickListener(v -> startEditProfileActivity(null));
242 RecyclerView root = findViewById(R.id.nav_profile_list);
244 throw new RuntimeException("Can't get hold on the transaction value view");
246 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
247 root.setAdapter(mProfileListAdapter);
249 mProfileListAdapter.addEditingProfilesObserver(new Observer() {
251 public void update(Observable o, Object arg) {
252 if (mProfileListAdapter.isEditingProfiles()) {
253 profileListHeadArrow.clearAnimation();
254 profileListHeadArrow.setVisibility(View.GONE);
255 profileListHeadMore.setVisibility(View.GONE);
256 profileListHeadCancel.setVisibility(View.VISIBLE);
259 profileListHeadArrow.setRotation(180f);
260 profileListHeadArrow.setVisibility(View.VISIBLE);
261 profileListHeadCancel.setVisibility(View.GONE);
262 profileListHeadMore.setVisibility(View.GONE);
264 .setVisibility(profileListExpanded ? View.VISIBLE : View.GONE);
269 LinearLayoutManager llm = new LinearLayoutManager(this);
271 llm.setOrientation(RecyclerView.VERTICAL);
272 root.setLayoutManager(llm);
274 profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
275 profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
276 profileListHeadMoreAndCancel
277 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
279 drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
281 public void onDrawerClosed(View drawerView) {
282 super.onDrawerClosed(drawerView);
283 collapseProfileList();
287 private void updateLastUpdateDisplay() {
288 TextView v = findViewById(R.id.transactions_last_update);
289 Date date = Data.lastUpdateDate.get();
291 v.setText(R.string.transaction_last_update_never);
292 Log.d("main", "no last update date :(");
295 final String text = DateFormat.getDateTimeInstance().format(date);
297 Log.d("main", String.format("Date formatted: %s", text));
300 private void profileThemeChanged() {
301 setupProfileColors();
303 Bundle bundle = new Bundle();
304 onSaveInstanceState(bundle);
305 // restart activity to reflect theme change
307 Intent intent = new Intent(this, this.getClass());
308 intent.putExtra(BUNDLE_SAVED_STATE, bundle);
309 startActivity(intent);
311 public void startEditProfileActivity(MobileLedgerProfile profile) {
312 Intent intent = new Intent(this, ProfileDetailActivity.class);
313 Bundle args = new Bundle();
314 if (profile != null) {
315 int index = Data.getProfileIndex(profile);
316 if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
318 intent.putExtras(args);
319 startActivity(intent, args);
321 private void setupProfile() {
322 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
323 MobileLedgerProfile profile;
325 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
327 if (Data.profiles.getList().isEmpty()) {
328 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
329 findViewById(R.id.pager_layout).setVisibility(View.GONE);
333 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
334 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
336 if (profile == null) profile = Data.profiles.get(0);
338 if (profile == null) throw new AssertionError("profile must have a value");
340 Data.setCurrentProfile(profile);
342 public void fabNewTransactionClicked(View view) {
343 Intent intent = new Intent(this, NewTransactionActivity.class);
344 startActivity(intent);
345 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
347 public void navSettingsClicked(View view) {
348 Intent intent = new Intent(this, SettingsActivity.class);
349 startActivity(intent);
350 drawer.closeDrawers();
352 public void markDrawerItemCurrent(int id) {
353 TextView item = drawer.findViewById(id);
354 item.setBackgroundColor(Colors.tableRowDarkBG);
356 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
357 for (int i = 0; i < actions.getChildCount(); i++) {
358 View view = actions.getChildAt(i);
359 if (view.getId() != id) {
360 view.setBackgroundColor(Color.TRANSPARENT);
364 public void onAccountSummaryClicked(View view) {
365 drawer.closeDrawers();
367 showAccountSummaryFragment();
369 private void showAccountSummaryFragment() {
370 mViewPager.setCurrentItem(0, true);
371 TransactionListFragment.accountFilter.set(null);
372 // FragmentTransaction ft = fragmentManager.beginTransaction();
373 // accountSummaryFragment = new AccountSummaryFragment();
374 // ft.replace(R.id.root_frame, accountSummaryFragment);
376 // currentFragment = accountSummaryFragment;
378 public void onLatestTransactionsClicked(View view) {
379 drawer.closeDrawers();
381 showTransactionsFragment(null);
383 private void resetFragmentBackStack() {
384 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
386 private void showTransactionsFragment(LedgerAccount account) {
387 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
388 mViewPager.setCurrentItem(1, true);
389 // FragmentTransaction ft = fragmentManager.beginTransaction();
390 // if (transactionListFragment == null) {
391 // Log.d("flow", "MainActivity creating TransactionListFragment");
392 // transactionListFragment = new TransactionListFragment();
394 // Bundle bundle = new Bundle();
395 // if (account != null) {
396 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
397 // account.getName());
399 // transactionListFragment.setArguments(bundle);
400 // ft.replace(R.id.root_frame, transactionListFragment);
401 // if (account != null)
402 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
405 // currentFragment = transactionListFragment;
407 public void showAccountTransactions(LedgerAccount account) {
408 showTransactionsFragment(account);
411 public void onBackPressed() {
412 DrawerLayout drawer = findViewById(R.id.drawer_layout);
413 if (drawer.isDrawerOpen(GravityCompat.START)) {
414 drawer.closeDrawer(GravityCompat.START);
418 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
420 super.onBackPressed();
423 public void updateLastUpdateTextFromDB() {
425 final MobileLedgerProfile profile = Data.profile.get();
427 (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
429 Log.d("transactions", String.format("Last update = %d", last_update));
430 if (last_update == 0) {
431 Data.lastUpdateDate.set(null);
434 Data.lastUpdateDate.set(new Date(last_update));
438 public void scheduleTransactionListRetrieval() {
439 if (Data.profile.get() == null) return;
441 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
443 retrieveTransactionsTask.execute();
445 public void onStopTransactionRefreshClick(View view) {
446 Log.d("interactive", "Cancelling transactions refresh");
447 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
448 bTransactionListCancelDownload.setEnabled(false);
450 public void onRetrieveDone(String error) {
451 progressLayout.setVisibility(View.GONE);
454 updateLastUpdateTextFromDB();
456 new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
457 TransactionListViewModel.scheduleTransactionListReload();
459 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
461 public void onRetrieveStart() {
462 bTransactionListCancelDownload.setEnabled(true);
463 progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
464 progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
465 progressBar.setIndeterminate(true);
466 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
467 else progressBar.setProgress(0);
468 progressLayout.setVisibility(View.VISIBLE);
470 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
471 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
472 (progress.getTotal() == 0))
474 progressBar.setIndeterminate(true);
477 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
478 progressBar.setMin(0);
480 progressBar.setMax(progress.getTotal());
481 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
482 progressBar.setProgress(progress.getProgress(), true);
484 else progressBar.setProgress(progress.getProgress());
485 progressBar.setIndeterminate(false);
488 public void fabShouldShow() {
489 MobileLedgerProfile profile = Data.profile.get();
490 if ((profile != null) && profile.isPostingPermitted()) fab.show();
492 public void navProfilesHeadClicked(View view) {
493 if (profileListExpanded) {
494 collapseProfileList();
500 private void expandProfileList() {
501 profileListExpanded = true;
504 profileListContainer.setVisibility(View.VISIBLE);
505 profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
506 profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
507 profileListHeadMore.setVisibility(View.VISIBLE);
508 profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
509 findViewById(R.id.nav_profile_list).setMinimumHeight(
510 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
511 Data.profiles.size()));
513 private void collapseProfileList() {
514 profileListExpanded = false;
516 final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
517 animation.setAnimationListener(new Animation.AnimationListener() {
519 public void onAnimationStart(Animation animation) {
523 public void onAnimationEnd(Animation animation) {
524 profileListContainer.setVisibility(View.GONE);
527 public void onAnimationRepeat(Animation animation) {
531 mProfileListAdapter.stopEditingProfiles();
533 profileListContainer.startAnimation(animation);
534 profileListHeadArrow.setRotation(0f);
536 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
537 profileListHeadMore.setVisibility(View.GONE);
539 public void onProfileRowClicked(View v) {
540 Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
542 public void enableProfileModifications() {
543 profileModificationEnabled = true;
544 ViewGroup profileList = findViewById(R.id.nav_profile_list);
545 for (int i = 0; i < profileList.getChildCount(); i++) {
546 View aRow = profileList.getChildAt(i);
547 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
548 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
550 // FIXME enable rearranging
553 public void disableProfileModifications() {
554 profileModificationEnabled = false;
555 ViewGroup profileList = findViewById(R.id.nav_profile_list);
556 for (int i = 0; i < profileList.getChildCount(); i++) {
557 View aRow = profileList.getChildAt(i);
558 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
559 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.INVISIBLE);
561 // FIXME disable rearranging
564 public void onAccountSummaryRowViewClicked(View view) {
565 ViewGroup row = (ViewGroup) view.getParent();
566 LedgerAccount acc = (LedgerAccount) row.getTag();
567 switch (view.getId()) {
568 case R.id.account_row_acc_name:
569 case R.id.account_expander_container:
570 Log.d("accounts", "Account expander clicked");
571 if (!acc.hasSubAccounts()) return;
573 boolean wasExpanded = acc.isExpanded();
575 View arrow = row.findViewById(R.id.account_expander_container);
577 arrow.clearAnimation();
578 ViewPropertyAnimator animator = arrow.animate();
580 acc.toggleExpanded();
581 Data.profile.get().storeAccount(MLDB.getDatabase(), acc);
584 Log.d("accounts", String.format("Collapsing account '%s'", acc.getName()));
585 arrow.setRotation(0);
586 animator.rotationBy(180);
588 // removing all child accounts from the view
589 int start = -1, count = 0;
591 final ArrayList<LedgerAccount> accountList = Data.accounts.get();
592 for (LedgerAccount a : accountList) {
593 if (acc.isParentOf(a)) {
608 for (int j = 0; j < count; j++) {
609 Log.d("accounts", String.format("Removing item %d: %s", start + j,
610 accountList.get(start).getName()));
611 accountList.remove(start);
614 mAccountSummaryFragment.modelAdapter.notifyItemRangeRemoved(start, count);
618 Log.d("accounts", String.format("Expanding account '%s'", acc.getName()));
619 arrow.setRotation(180);
620 animator.rotationBy(-180);
621 ArrayList<LedgerAccount> accounts = Data.accounts.get();
622 List<LedgerAccount> children =
623 Data.profile.get().loadVisibleChildAccountsOf(acc);
624 int parentPos = accounts.indexOf(acc);
625 if (parentPos == -1) throw new RuntimeException(
626 "Can't find index of clicked account " + acc.getName());
627 accounts.addAll(parentPos + 1, children);
628 mAccountSummaryFragment.modelAdapter
629 .notifyItemRangeInserted(parentPos + 1, children.size());
632 case R.id.account_row_acc_amounts:
633 showAccountTransactions(acc);
638 public class SectionsPagerAdapter extends FragmentPagerAdapter {
640 public SectionsPagerAdapter(FragmentManager fm) {
645 public Fragment getItem(int position) {
646 Log.d("main", String.format("Switching to fragment %d", position));
649 // Log.d("flow", "Creating account summary fragment");
650 return mAccountSummaryFragment = new AccountSummaryFragment();
652 return new TransactionListFragment();
654 throw new IllegalStateException(
655 String.format("Unexpected fragment index: " + "%d", position));
660 public int getCount() {