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.utils.Colors;
50 import net.ktnx.mobileledger.utils.MLDB;
52 import java.lang.ref.WeakReference;
53 import java.text.DateFormat;
54 import java.util.Date;
55 import java.util.Observable;
56 import java.util.Observer;
58 import androidx.appcompat.app.ActionBarDrawerToggle;
59 import androidx.appcompat.widget.Toolbar;
60 import androidx.core.view.GravityCompat;
61 import androidx.drawerlayout.widget.DrawerLayout;
62 import androidx.fragment.app.Fragment;
63 import androidx.fragment.app.FragmentManager;
64 import androidx.fragment.app.FragmentPagerAdapter;
65 import androidx.recyclerview.widget.LinearLayoutManager;
66 import androidx.recyclerview.widget.RecyclerView;
67 import androidx.viewpager.widget.ViewPager;
69 public class MainActivity extends ProfileThemedActivity {
70 private static final String STATE_CURRENT_PAGE = "current_page";
71 private static final String BUNDLE_SAVED_STATE = "bundle_savedState";
73 private LinearLayout profileListContainer;
74 private View profileListHeadArrow, profileListHeadMore, profileListHeadCancel;
75 private LinearLayout profileListHeadMoreAndCancel;
76 private FragmentManager fragmentManager;
77 private TextView tvLastUpdate;
78 private RetrieveTransactionsTask retrieveTransactionsTask;
79 private View bTransactionListCancelDownload;
80 private ProgressBar progressBar;
81 private LinearLayout progressLayout;
82 private SectionsPagerAdapter mSectionsPagerAdapter;
83 private ViewPager mViewPager;
84 private FloatingActionButton fab;
85 private boolean profileModificationEnabled = false;
86 private boolean profileListExpanded = false;
87 private ProfilesRecyclerViewAdapter mProfileListAdapter;
90 protected void onStart() {
93 Data.lastUpdateDate.set(null);
94 updateLastUpdateTextFromDB();
95 Date lastUpdate = Data.lastUpdateDate.get();
97 long now = new Date().getTime();
98 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
99 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
101 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
102 lastUpdate.getTime() / 1000f, now / 1000f));
104 scheduleTransactionListRetrieval();
108 protected void onSaveInstanceState(Bundle outState) {
109 super.onSaveInstanceState(outState);
110 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
113 protected void onCreate(Bundle savedInstanceState) {
114 super.onCreate(savedInstanceState);
116 setContentView(R.layout.activity_main);
118 fab = findViewById(R.id.btn_add_transaction);
119 profileListContainer = findViewById(R.id.nav_profile_list_container);
120 profileListHeadArrow = findViewById(R.id.nav_profiles_arrow);
121 profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
122 profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
123 profileListHeadMoreAndCancel = findViewById(R.id.nav_profile_list_head_buttons);
124 drawer = findViewById(R.id.drawer_layout);
125 tvLastUpdate = findViewById(R.id.transactions_last_update);
126 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
127 progressBar = findViewById(R.id.transaction_list_progress_bar);
128 progressLayout = findViewById(R.id.transaction_progress_layout);
129 fragmentManager = getSupportFragmentManager();
130 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
131 mViewPager = findViewById(R.id.root_frame);
133 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
134 if (extra != null && savedInstanceState == null) savedInstanceState = extra;
137 Toolbar toolbar = findViewById(R.id.toolbar);
138 setSupportActionBar(toolbar);
140 Data.profile.addObserver((o, arg) -> {
141 MobileLedgerProfile profile = Data.profile.get();
142 runOnUiThread(() -> {
143 if (profile == null) setTitle(R.string.app_name);
144 else setTitle(profile.getName());
145 updateLastUpdateTextFromDB();
146 if (profile.isPostingPermitted()) {
147 toolbar.setSubtitle(null);
151 toolbar.setSubtitle(R.string.profile_subitlte_read_only);
155 int newProfileTheme = profile.getThemeId();
156 if (newProfileTheme != Colors.profileThemeId) {
157 Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
159 profileThemeChanged();
160 Colors.profileThemeId = newProfileTheme;
165 ActionBarDrawerToggle toggle =
166 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
167 R.string.navigation_drawer_close);
168 drawer.addDrawerListener(toggle);
171 TextView ver = drawer.findViewById(R.id.drawer_version_text);
175 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
176 ver.setText(pi.versionName);
178 catch (Exception e) {
182 if (progressBar == null)
183 throw new RuntimeException("Can't get hold on the transaction value progress bar");
184 if (progressLayout == null) throw new RuntimeException(
185 "Can't get hold on the transaction value progress bar layout");
187 markDrawerItemCurrent(R.id.nav_account_summary);
189 mViewPager.setAdapter(mSectionsPagerAdapter);
190 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
192 public void onPageSelected(int position) {
195 markDrawerItemCurrent(R.id.nav_account_summary);
198 markDrawerItemCurrent(R.id.nav_latest_transactions);
201 Log.e("MainActivity", String.format("Unexpected page index %d", position));
204 super.onPageSelected(position);
208 if (savedInstanceState != null) {
209 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
210 if (currentPage != -1) {
211 mViewPager.setCurrentItem(currentPage, false);
215 Data.lastUpdateDate.addObserver((o, arg) -> {
216 Log.d("main", "lastUpdateDate changed");
217 runOnUiThread(() -> {
218 Date date = Data.lastUpdateDate.get();
220 tvLastUpdate.setText(R.string.transaction_last_update_never);
223 final String text = DateFormat.getDateTimeInstance().format(date);
224 tvLastUpdate.setText(text);
225 Log.d("despair", String.format("Date formatted: %s", text));
230 findViewById(R.id.btn_no_profiles_add)
231 .setOnClickListener(v -> startEditProfileActivity(null));
233 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
235 findViewById(R.id.nav_new_profile_button)
236 .setOnClickListener(v -> startEditProfileActivity(null));
238 RecyclerView root = findViewById(R.id.nav_profile_list);
240 throw new RuntimeException("Can't get hold on the transaction value view");
242 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
243 root.setAdapter(mProfileListAdapter);
245 mProfileListAdapter.addEditingProfilesObserver(new Observer() {
247 public void update(Observable o, Object arg) {
248 if (mProfileListAdapter.isEditingProfiles()) {
249 profileListHeadArrow.clearAnimation();
250 profileListHeadArrow.setVisibility(View.GONE);
251 profileListHeadMore.setVisibility(View.GONE);
252 profileListHeadCancel.setVisibility(View.VISIBLE);
255 profileListHeadArrow.setRotation(180f);
256 profileListHeadArrow.setVisibility(View.VISIBLE);
257 profileListHeadCancel.setVisibility(View.GONE);
258 profileListHeadMore.setVisibility(View.GONE);
260 .setVisibility(profileListExpanded ? View.VISIBLE : View.GONE);
265 LinearLayoutManager llm = new LinearLayoutManager(this);
267 llm.setOrientation(RecyclerView.VERTICAL);
268 root.setLayoutManager(llm);
270 profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
271 profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
272 profileListHeadMoreAndCancel
273 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
275 drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
277 public void onDrawerClosed(View drawerView) {
278 super.onDrawerClosed(drawerView);
279 collapseProfileList();
283 private void profileThemeChanged() {
284 setupProfileColors();
286 Bundle bundle = new Bundle();
287 onSaveInstanceState(bundle);
288 // restart activity to reflect theme change
290 Intent intent = new Intent(this, this.getClass());
291 intent.putExtra(BUNDLE_SAVED_STATE, bundle);
292 startActivity(intent);
295 protected void onResume() {
299 public void startEditProfileActivity(MobileLedgerProfile profile) {
300 Intent intent = new Intent(this, ProfileDetailActivity.class);
301 Bundle args = new Bundle();
302 if (profile != null) {
303 int index = Data.getProfileIndex(profile);
304 if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
306 intent.putExtras(args);
307 startActivity(intent, args);
309 private void setupProfile() {
310 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
311 MobileLedgerProfile profile;
313 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
315 if (Data.profiles.getList().isEmpty()) {
316 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
317 findViewById(R.id.pager_layout).setVisibility(View.GONE);
321 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
322 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
324 if (profile == null) profile = Data.profiles.get(0);
326 if (profile == null) throw new AssertionError("profile must have a value");
328 Data.setCurrentProfile(profile);
330 public void fabNewTransactionClicked(View view) {
331 Intent intent = new Intent(this, NewTransactionActivity.class);
332 startActivity(intent);
333 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
335 public void navSettingsClicked(View view) {
336 Intent intent = new Intent(this, SettingsActivity.class);
337 startActivity(intent);
338 drawer.closeDrawers();
340 public void markDrawerItemCurrent(int id) {
341 TextView item = drawer.findViewById(id);
342 item.setBackgroundColor(Colors.tableRowDarkBG);
344 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
345 for (int i = 0; i < actions.getChildCount(); i++) {
346 View view = actions.getChildAt(i);
347 if (view.getId() != id) {
348 view.setBackgroundColor(Color.TRANSPARENT);
352 public void onAccountSummaryClicked(View view) {
353 drawer.closeDrawers();
355 showAccountSummaryFragment();
357 private void showAccountSummaryFragment() {
358 mViewPager.setCurrentItem(0, true);
359 TransactionListFragment.accountFilter.set(null);
360 // FragmentTransaction ft = fragmentManager.beginTransaction();
361 // accountSummaryFragment = new AccountSummaryFragment();
362 // ft.replace(R.id.root_frame, accountSummaryFragment);
364 // currentFragment = accountSummaryFragment;
366 public void onLatestTransactionsClicked(View view) {
367 drawer.closeDrawers();
369 showTransactionsFragment(null);
371 private void resetFragmentBackStack() {
372 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
374 private void showTransactionsFragment(LedgerAccount account) {
375 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
376 mViewPager.setCurrentItem(1, true);
377 // FragmentTransaction ft = fragmentManager.beginTransaction();
378 // if (transactionListFragment == null) {
379 // Log.d("flow", "MainActivity creating TransactionListFragment");
380 // transactionListFragment = new TransactionListFragment();
382 // Bundle bundle = new Bundle();
383 // if (account != null) {
384 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
385 // account.getName());
387 // transactionListFragment.setArguments(bundle);
388 // ft.replace(R.id.root_frame, transactionListFragment);
389 // if (account != null)
390 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
393 // currentFragment = transactionListFragment;
395 public void showAccountTransactions(LedgerAccount account) {
396 showTransactionsFragment(account);
399 public void onBackPressed() {
400 DrawerLayout drawer = findViewById(R.id.drawer_layout);
401 if (drawer.isDrawerOpen(GravityCompat.START)) {
402 drawer.closeDrawer(GravityCompat.START);
406 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
408 super.onBackPressed();
411 public void updateLastUpdateTextFromDB() {
413 final MobileLedgerProfile profile = Data.profile.get();
415 (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
417 Log.d("transactions", String.format("Last update = %d", last_update));
418 if (last_update == 0) {
419 Data.lastUpdateDate.set(null);
422 Data.lastUpdateDate.set(new Date(last_update));
426 public void scheduleTransactionListRetrieval() {
427 if (Data.profile.get() == null) return;
429 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
431 retrieveTransactionsTask.execute();
433 public void onStopTransactionRefreshClick(View view) {
434 Log.d("interactive", "Cancelling transactions refresh");
435 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
436 bTransactionListCancelDownload.setEnabled(false);
438 public void onRetrieveDone(String error) {
439 progressLayout.setVisibility(View.GONE);
442 updateLastUpdateTextFromDB();
444 new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
446 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
448 public void onRetrieveStart() {
449 bTransactionListCancelDownload.setEnabled(true);
450 progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
451 progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
452 progressBar.setIndeterminate(true);
453 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
454 else progressBar.setProgress(0);
455 progressLayout.setVisibility(View.VISIBLE);
457 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
458 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
459 (progress.getTotal() == 0))
461 progressBar.setIndeterminate(true);
464 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
465 progressBar.setMin(0);
467 progressBar.setMax(progress.getTotal());
468 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
469 progressBar.setProgress(progress.getProgress(), true);
471 else progressBar.setProgress(progress.getProgress());
472 progressBar.setIndeterminate(false);
475 public void fabShouldShow() {
476 MobileLedgerProfile profile = Data.profile.get();
477 if ((profile != null) && profile.isPostingPermitted()) fab.show();
479 public void navProfilesHeadClicked(View view) {
480 if (profileListExpanded) {
481 collapseProfileList();
487 private void expandProfileList() {
488 profileListExpanded = true;
491 profileListContainer.setVisibility(View.VISIBLE);
492 profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
493 profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
494 profileListHeadMore.setVisibility(View.VISIBLE);
495 profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
497 private void collapseProfileList() {
498 profileListExpanded = false;
500 final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
501 animation.setAnimationListener(new Animation.AnimationListener() {
503 public void onAnimationStart(Animation animation) {
507 public void onAnimationEnd(Animation animation) {
508 profileListContainer.setVisibility(View.GONE);
511 public void onAnimationRepeat(Animation animation) {
515 mProfileListAdapter.stopEditingProfiles();
517 profileListContainer.startAnimation(animation);
518 profileListHeadArrow.setRotation(0f);
520 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
521 profileListHeadMore.setVisibility(View.GONE);
523 public void onProfileRowClicked(View v) {
524 Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
526 public void enableProfileModifications() {
527 profileModificationEnabled = true;
528 ViewGroup profileList = findViewById(R.id.nav_profile_list);
529 for (int i = 0; i < profileList.getChildCount(); i++) {
530 View aRow = profileList.getChildAt(i);
531 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
532 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
534 // FIXME enable rearranging
537 public void disableProfileModifications() {
538 profileModificationEnabled = false;
539 ViewGroup profileList = findViewById(R.id.nav_profile_list);
540 for (int i = 0; i < profileList.getChildCount(); i++) {
541 View aRow = profileList.getChildAt(i);
542 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
543 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.INVISIBLE);
545 // FIXME disable rearranging
549 public class SectionsPagerAdapter extends FragmentPagerAdapter {
551 public SectionsPagerAdapter(FragmentManager fm) {
556 public Fragment getItem(int position) {
557 Log.d("main", String.format("Switching to fragment %d", position));
560 return new AccountSummaryFragment();
562 return new TransactionListFragment();
564 throw new IllegalStateException(
565 String.format("Unexpected fragment index: " + "%d", position));
570 public int getCount() {