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.animation.Animation;
31 import android.view.animation.AnimationUtils;
32 import android.widget.LinearLayout;
33 import android.widget.ProgressBar;
34 import android.widget.TextView;
35 import android.widget.Toast;
37 import com.google.android.material.floatingactionbutton.FloatingActionButton;
39 import net.ktnx.mobileledger.R;
40 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
41 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
42 import net.ktnx.mobileledger.model.Data;
43 import net.ktnx.mobileledger.model.LedgerAccount;
44 import net.ktnx.mobileledger.model.MobileLedgerProfile;
45 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
46 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
47 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
48 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
49 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
50 import net.ktnx.mobileledger.utils.Colors;
51 import net.ktnx.mobileledger.utils.MLDB;
53 import java.lang.ref.WeakReference;
54 import java.text.DateFormat;
55 import java.util.Date;
56 import java.util.Observable;
57 import java.util.Observer;
59 import androidx.appcompat.app.ActionBarDrawerToggle;
60 import androidx.appcompat.widget.Toolbar;
61 import androidx.core.view.GravityCompat;
62 import androidx.drawerlayout.widget.DrawerLayout;
63 import androidx.fragment.app.Fragment;
64 import androidx.fragment.app.FragmentManager;
65 import androidx.fragment.app.FragmentPagerAdapter;
66 import androidx.recyclerview.widget.LinearLayoutManager;
67 import androidx.recyclerview.widget.RecyclerView;
68 import androidx.viewpager.widget.ViewPager;
70 public class MainActivity extends ProfileThemedActivity {
71 private static final String STATE_CURRENT_PAGE = "current_page";
72 private static final String BUNDLE_SAVED_STATE = "bundle_savedState";
74 private LinearLayout profileListContainer;
75 private View profileListHeadArrow, profileListHeadMore, profileListHeadCancel;
76 private LinearLayout profileListHeadMoreAndCancel;
77 private FragmentManager fragmentManager;
78 private TextView tvLastUpdate;
79 private RetrieveTransactionsTask retrieveTransactionsTask;
80 private View bTransactionListCancelDownload;
81 private ProgressBar progressBar;
82 private LinearLayout progressLayout;
83 private SectionsPagerAdapter mSectionsPagerAdapter;
84 private ViewPager mViewPager;
85 private FloatingActionButton fab;
86 private boolean profileModificationEnabled = false;
87 private boolean profileListExpanded = false;
88 private ProfilesRecyclerViewAdapter mProfileListAdapter;
91 protected void onStart() {
96 updateLastUpdateTextFromDB();
97 Date lastUpdate = Data.lastUpdateDate.get();
99 long now = new Date().getTime();
100 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
101 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
103 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
104 lastUpdate.getTime() / 1000f, now / 1000f));
106 scheduleTransactionListRetrieval();
110 protected void onSaveInstanceState(Bundle outState) {
111 super.onSaveInstanceState(outState);
112 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
115 protected void onCreate(Bundle savedInstanceState) {
116 super.onCreate(savedInstanceState);
118 setContentView(R.layout.activity_main);
120 fab = findViewById(R.id.btn_add_transaction);
121 profileListContainer = findViewById(R.id.nav_profile_list_container);
122 profileListHeadArrow = findViewById(R.id.nav_profiles_arrow);
123 profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
124 profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
125 profileListHeadMoreAndCancel = findViewById(R.id.nav_profile_list_head_buttons);
126 drawer = findViewById(R.id.drawer_layout);
127 tvLastUpdate = findViewById(R.id.transactions_last_update);
128 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
129 progressBar = findViewById(R.id.transaction_list_progress_bar);
130 progressLayout = findViewById(R.id.transaction_progress_layout);
131 fragmentManager = getSupportFragmentManager();
132 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
133 mViewPager = findViewById(R.id.root_frame);
135 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
136 if (extra != null && savedInstanceState == null) savedInstanceState = extra;
139 Toolbar toolbar = findViewById(R.id.toolbar);
140 setSupportActionBar(toolbar);
142 Data.profile.addObserver((o, arg) -> {
143 MobileLedgerProfile profile = Data.profile.get();
144 runOnUiThread(() -> {
145 if (profile == null) setTitle(R.string.app_name);
146 else setTitle(profile.getName());
147 updateLastUpdateTextFromDB();
148 if (profile.isPostingPermitted()) {
149 toolbar.setSubtitle(null);
153 toolbar.setSubtitle(R.string.profile_subitlte_read_only);
157 int newProfileTheme = profile.getThemeId();
158 if (newProfileTheme != Colors.profileThemeId) {
159 Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
161 profileThemeChanged();
162 Colors.profileThemeId = newProfileTheme;
167 ActionBarDrawerToggle toggle =
168 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
169 R.string.navigation_drawer_close);
170 drawer.addDrawerListener(toggle);
173 TextView ver = drawer.findViewById(R.id.drawer_version_text);
177 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
178 ver.setText(pi.versionName);
180 catch (Exception e) {
184 if (progressBar == null)
185 throw new RuntimeException("Can't get hold on the transaction value progress bar");
186 if (progressLayout == null) throw new RuntimeException(
187 "Can't get hold on the transaction value progress bar layout");
189 markDrawerItemCurrent(R.id.nav_account_summary);
191 mViewPager.setAdapter(mSectionsPagerAdapter);
192 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
194 public void onPageSelected(int position) {
197 markDrawerItemCurrent(R.id.nav_account_summary);
200 markDrawerItemCurrent(R.id.nav_latest_transactions);
203 Log.e("MainActivity", String.format("Unexpected page index %d", position));
206 super.onPageSelected(position);
210 if (savedInstanceState != null) {
211 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
212 if (currentPage != -1) {
213 mViewPager.setCurrentItem(currentPage, false);
217 Data.lastUpdateDate.addObserver((o, arg) -> {
218 Log.d("main", "lastUpdateDate changed");
219 runOnUiThread(this::updateLastUpdateDisplay);
222 updateLastUpdateDisplay();
224 findViewById(R.id.btn_no_profiles_add)
225 .setOnClickListener(v -> startEditProfileActivity(null));
227 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
229 findViewById(R.id.nav_new_profile_button)
230 .setOnClickListener(v -> startEditProfileActivity(null));
232 RecyclerView root = findViewById(R.id.nav_profile_list);
234 throw new RuntimeException("Can't get hold on the transaction value view");
236 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
237 root.setAdapter(mProfileListAdapter);
239 mProfileListAdapter.addEditingProfilesObserver(new Observer() {
241 public void update(Observable o, Object arg) {
242 if (mProfileListAdapter.isEditingProfiles()) {
243 profileListHeadArrow.clearAnimation();
244 profileListHeadArrow.setVisibility(View.GONE);
245 profileListHeadMore.setVisibility(View.GONE);
246 profileListHeadCancel.setVisibility(View.VISIBLE);
249 profileListHeadArrow.setRotation(180f);
250 profileListHeadArrow.setVisibility(View.VISIBLE);
251 profileListHeadCancel.setVisibility(View.GONE);
252 profileListHeadMore.setVisibility(View.GONE);
254 .setVisibility(profileListExpanded ? View.VISIBLE : View.GONE);
259 LinearLayoutManager llm = new LinearLayoutManager(this);
261 llm.setOrientation(RecyclerView.VERTICAL);
262 root.setLayoutManager(llm);
264 profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
265 profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
266 profileListHeadMoreAndCancel
267 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
269 drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
271 public void onDrawerClosed(View drawerView) {
272 super.onDrawerClosed(drawerView);
273 collapseProfileList();
277 private void updateLastUpdateDisplay() {
278 TextView v = findViewById(R.id.transactions_last_update);
279 Date date = Data.lastUpdateDate.get();
281 v.setText(R.string.transaction_last_update_never);
282 Log.d("main", "no last update date :(");
285 final String text = DateFormat.getDateTimeInstance().format(date);
287 Log.d("main", String.format("Date formatted: %s", text));
290 private void profileThemeChanged() {
291 setupProfileColors();
293 Bundle bundle = new Bundle();
294 onSaveInstanceState(bundle);
295 // restart activity to reflect theme change
297 Intent intent = new Intent(this, this.getClass());
298 intent.putExtra(BUNDLE_SAVED_STATE, bundle);
299 startActivity(intent);
301 public void startEditProfileActivity(MobileLedgerProfile profile) {
302 Intent intent = new Intent(this, ProfileDetailActivity.class);
303 Bundle args = new Bundle();
304 if (profile != null) {
305 int index = Data.getProfileIndex(profile);
306 if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
308 intent.putExtras(args);
309 startActivity(intent, args);
311 private void setupProfile() {
312 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
313 MobileLedgerProfile profile;
315 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
317 if (Data.profiles.getList().isEmpty()) {
318 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
319 findViewById(R.id.pager_layout).setVisibility(View.GONE);
323 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
324 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
326 if (profile == null) profile = Data.profiles.get(0);
328 if (profile == null) throw new AssertionError("profile must have a value");
330 Data.setCurrentProfile(profile);
332 public void fabNewTransactionClicked(View view) {
333 Intent intent = new Intent(this, NewTransactionActivity.class);
334 startActivity(intent);
335 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
337 public void navSettingsClicked(View view) {
338 Intent intent = new Intent(this, SettingsActivity.class);
339 startActivity(intent);
340 drawer.closeDrawers();
342 public void markDrawerItemCurrent(int id) {
343 TextView item = drawer.findViewById(id);
344 item.setBackgroundColor(Colors.tableRowDarkBG);
346 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
347 for (int i = 0; i < actions.getChildCount(); i++) {
348 View view = actions.getChildAt(i);
349 if (view.getId() != id) {
350 view.setBackgroundColor(Color.TRANSPARENT);
354 public void onAccountSummaryClicked(View view) {
355 drawer.closeDrawers();
357 showAccountSummaryFragment();
359 private void showAccountSummaryFragment() {
360 mViewPager.setCurrentItem(0, true);
361 TransactionListFragment.accountFilter.set(null);
362 // FragmentTransaction ft = fragmentManager.beginTransaction();
363 // accountSummaryFragment = new AccountSummaryFragment();
364 // ft.replace(R.id.root_frame, accountSummaryFragment);
366 // currentFragment = accountSummaryFragment;
368 public void onLatestTransactionsClicked(View view) {
369 drawer.closeDrawers();
371 showTransactionsFragment(null);
373 private void resetFragmentBackStack() {
374 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
376 private void showTransactionsFragment(LedgerAccount account) {
377 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
378 mViewPager.setCurrentItem(1, true);
379 // FragmentTransaction ft = fragmentManager.beginTransaction();
380 // if (transactionListFragment == null) {
381 // Log.d("flow", "MainActivity creating TransactionListFragment");
382 // transactionListFragment = new TransactionListFragment();
384 // Bundle bundle = new Bundle();
385 // if (account != null) {
386 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
387 // account.getName());
389 // transactionListFragment.setArguments(bundle);
390 // ft.replace(R.id.root_frame, transactionListFragment);
391 // if (account != null)
392 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
395 // currentFragment = transactionListFragment;
397 public void showAccountTransactions(LedgerAccount account) {
398 showTransactionsFragment(account);
401 public void onBackPressed() {
402 DrawerLayout drawer = findViewById(R.id.drawer_layout);
403 if (drawer.isDrawerOpen(GravityCompat.START)) {
404 drawer.closeDrawer(GravityCompat.START);
408 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
410 super.onBackPressed();
413 public void updateLastUpdateTextFromDB() {
415 final MobileLedgerProfile profile = Data.profile.get();
417 (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
419 Log.d("transactions", String.format("Last update = %d", last_update));
420 if (last_update == 0) {
421 Data.lastUpdateDate.set(null);
424 Data.lastUpdateDate.set(new Date(last_update));
428 public void scheduleTransactionListRetrieval() {
429 if (Data.profile.get() == null) return;
431 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
433 retrieveTransactionsTask.execute();
435 public void onStopTransactionRefreshClick(View view) {
436 Log.d("interactive", "Cancelling transactions refresh");
437 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
438 bTransactionListCancelDownload.setEnabled(false);
440 public void onRetrieveDone(String error) {
441 progressLayout.setVisibility(View.GONE);
444 updateLastUpdateTextFromDB();
446 new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
447 TransactionListViewModel.scheduleTransactionListReload();
449 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
451 public void onRetrieveStart() {
452 bTransactionListCancelDownload.setEnabled(true);
453 progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
454 progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
455 progressBar.setIndeterminate(true);
456 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
457 else progressBar.setProgress(0);
458 progressLayout.setVisibility(View.VISIBLE);
460 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
461 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
462 (progress.getTotal() == 0))
464 progressBar.setIndeterminate(true);
467 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
468 progressBar.setMin(0);
470 progressBar.setMax(progress.getTotal());
471 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
472 progressBar.setProgress(progress.getProgress(), true);
474 else progressBar.setProgress(progress.getProgress());
475 progressBar.setIndeterminate(false);
478 public void fabShouldShow() {
479 MobileLedgerProfile profile = Data.profile.get();
480 if ((profile != null) && profile.isPostingPermitted()) fab.show();
482 public void navProfilesHeadClicked(View view) {
483 if (profileListExpanded) {
484 collapseProfileList();
490 private void expandProfileList() {
491 profileListExpanded = true;
494 profileListContainer.setVisibility(View.VISIBLE);
495 profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
496 profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
497 profileListHeadMore.setVisibility(View.VISIBLE);
498 profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
499 findViewById(R.id.nav_profile_list).setMinimumHeight(
500 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
501 Data.profiles.size()));
503 private void collapseProfileList() {
504 profileListExpanded = false;
506 final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
507 animation.setAnimationListener(new Animation.AnimationListener() {
509 public void onAnimationStart(Animation animation) {
513 public void onAnimationEnd(Animation animation) {
514 profileListContainer.setVisibility(View.GONE);
517 public void onAnimationRepeat(Animation animation) {
521 mProfileListAdapter.stopEditingProfiles();
523 profileListContainer.startAnimation(animation);
524 profileListHeadArrow.setRotation(0f);
526 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
527 profileListHeadMore.setVisibility(View.GONE);
529 public void onProfileRowClicked(View v) {
530 Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
532 public void enableProfileModifications() {
533 profileModificationEnabled = true;
534 ViewGroup profileList = findViewById(R.id.nav_profile_list);
535 for (int i = 0; i < profileList.getChildCount(); i++) {
536 View aRow = profileList.getChildAt(i);
537 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
538 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
540 // FIXME enable rearranging
543 public void disableProfileModifications() {
544 profileModificationEnabled = false;
545 ViewGroup profileList = findViewById(R.id.nav_profile_list);
546 for (int i = 0; i < profileList.getChildCount(); i++) {
547 View aRow = profileList.getChildAt(i);
548 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
549 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.INVISIBLE);
551 // FIXME disable rearranging
555 public class SectionsPagerAdapter extends FragmentPagerAdapter {
557 public SectionsPagerAdapter(FragmentManager fm) {
562 public Fragment getItem(int position) {
563 Log.d("main", String.format("Switching to fragment %d", position));
566 return new AccountSummaryFragment();
568 return new TransactionListFragment();
570 throw new IllegalStateException(
571 String.format("Unexpected fragment index: " + "%d", position));
576 public int getCount() {