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.Build;
25 import android.os.Bundle;
26 import android.util.Log;
27 import android.view.View;
28 import android.view.ViewGroup;
29 import android.view.animation.Animation;
30 import android.view.animation.AnimationUtils;
31 import android.widget.LinearLayout;
32 import android.widget.ProgressBar;
33 import android.widget.TextView;
34 import android.widget.Toast;
36 import com.google.android.material.floatingactionbutton.FloatingActionButton;
38 import net.ktnx.mobileledger.R;
39 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
40 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
41 import net.ktnx.mobileledger.model.Data;
42 import net.ktnx.mobileledger.model.LedgerAccount;
43 import net.ktnx.mobileledger.model.MobileLedgerProfile;
44 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
45 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
46 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
47 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
48 import net.ktnx.mobileledger.utils.Colors;
49 import net.ktnx.mobileledger.utils.MLDB;
51 import java.lang.ref.WeakReference;
52 import java.text.DateFormat;
53 import java.util.Date;
55 import androidx.appcompat.app.ActionBarDrawerToggle;
56 import androidx.appcompat.widget.Toolbar;
57 import androidx.core.view.GravityCompat;
58 import androidx.drawerlayout.widget.DrawerLayout;
59 import androidx.fragment.app.Fragment;
60 import androidx.fragment.app.FragmentManager;
61 import androidx.fragment.app.FragmentPagerAdapter;
62 import androidx.recyclerview.widget.LinearLayoutManager;
63 import androidx.recyclerview.widget.RecyclerView;
64 import androidx.viewpager.widget.ViewPager;
66 public class MainActivity extends CrashReportingActivity {
67 private static final String STATE_CURRENT_PAGE = "current_page";
68 private static final String BUNDLE_SAVED_STATE = "bundle_savedState";
70 private LinearLayout profileListContainer;
71 private View profileListHeadArrow;
72 private FragmentManager fragmentManager;
73 private TextView tvLastUpdate;
74 private RetrieveTransactionsTask retrieveTransactionsTask;
75 private View bTransactionListCancelDownload;
76 private ProgressBar progressBar;
77 private LinearLayout progressLayout;
78 private SectionsPagerAdapter mSectionsPagerAdapter;
79 private ViewPager mViewPager;
80 private FloatingActionButton fab;
81 private boolean profileModificationEnabled = false;
82 private boolean profileListExpanded = false;
83 private ProfilesRecyclerViewAdapter mProfileListAdapter;
86 protected void onStart() {
89 Data.lastUpdateDate.set(null);
90 updateLastUpdateTextFromDB();
91 Date lastUpdate = Data.lastUpdateDate.get();
93 long now = new Date().getTime();
94 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
95 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
97 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
98 lastUpdate.getTime() / 1000f, now / 1000f));
100 scheduleTransactionListRetrieval();
104 protected void onSaveInstanceState(Bundle outState) {
105 super.onSaveInstanceState(outState);
106 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
109 protected void onCreate(Bundle savedInstanceState) {
110 super.onCreate(savedInstanceState);
112 setContentView(R.layout.activity_main);
114 fab = findViewById(R.id.btn_add_transaction);
115 profileListContainer = findViewById(R.id.nav_profile_list_container);
116 profileListHeadArrow = findViewById(R.id.nav_profiles_arrow);
117 drawer = findViewById(R.id.drawer_layout);
118 tvLastUpdate = findViewById(R.id.transactions_last_update);
119 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
120 progressBar = findViewById(R.id.transaction_list_progress_bar);
121 progressLayout = findViewById(R.id.transaction_progress_layout);
122 fragmentManager = getSupportFragmentManager();
123 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
124 mViewPager = findViewById(R.id.root_frame);
126 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
127 if (extra != null && savedInstanceState == null) savedInstanceState = extra;
130 Toolbar toolbar = findViewById(R.id.toolbar);
131 setSupportActionBar(toolbar);
133 Data.profile.addObserver((o, arg) -> {
134 MobileLedgerProfile profile = Data.profile.get();
135 runOnUiThread(() -> {
136 if (profile == null) setTitle(R.string.app_name);
137 else setTitle(profile.getName());
138 updateLastUpdateTextFromDB();
139 if (profile.isPostingPermitted()) {
140 toolbar.setSubtitle(null);
144 toolbar.setSubtitle(R.string.profile_subitlte_read_only);
148 int newProfileTheme = profile.getThemeId();
149 if (newProfileTheme != Colors.profileThemeId) {
150 Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
152 profileThemeChanged();
153 Colors.profileThemeId = newProfileTheme;
158 ActionBarDrawerToggle toggle =
159 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
160 R.string.navigation_drawer_close);
161 drawer.addDrawerListener(toggle);
164 TextView ver = drawer.findViewById(R.id.drawer_version_text);
168 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
169 ver.setText(pi.versionName);
171 catch (Exception e) {
175 if (progressBar == null)
176 throw new RuntimeException("Can't get hold on the transaction value progress bar");
177 if (progressLayout == null) throw new RuntimeException(
178 "Can't get hold on the transaction value progress bar layout");
180 markDrawerItemCurrent(R.id.nav_account_summary);
182 mViewPager.setAdapter(mSectionsPagerAdapter);
183 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
185 public void onPageSelected(int position) {
188 markDrawerItemCurrent(R.id.nav_account_summary);
191 markDrawerItemCurrent(R.id.nav_latest_transactions);
194 Log.e("MainActivity", String.format("Unexpected page index %d", position));
197 super.onPageSelected(position);
201 if (savedInstanceState != null) {
202 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
203 if (currentPage != -1) {
204 mViewPager.setCurrentItem(currentPage, false);
208 Data.lastUpdateDate.addObserver((o, arg) -> {
209 Log.d("main", "lastUpdateDate changed");
210 runOnUiThread(() -> {
211 Date date = Data.lastUpdateDate.get();
213 tvLastUpdate.setText(R.string.transaction_last_update_never);
216 final String text = DateFormat.getDateTimeInstance().format(date);
217 tvLastUpdate.setText(text);
218 Log.d("despair", String.format("Date formatted: %s", text));
223 findViewById(R.id.btn_no_profiles_add)
224 .setOnClickListener(v -> startEditProfileActivity(null));
226 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
228 findViewById(R.id.nav_new_profile_button)
229 .setOnClickListener(v -> startEditProfileActivity(null));
231 RecyclerView root = findViewById(R.id.nav_profile_list);
233 throw new RuntimeException("Can't get hold on the transaction value view");
235 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
236 root.setAdapter(mProfileListAdapter);
238 LinearLayoutManager llm = new LinearLayoutManager(this);
240 llm.setOrientation(RecyclerView.VERTICAL);
241 root.setLayoutManager(llm);
243 private void profileThemeChanged() {
244 setupProfileColors();
246 Bundle bundle = new Bundle();
247 onSaveInstanceState(bundle);
248 // restart activity to reflect theme change
250 Intent intent = new Intent(this, this.getClass());
251 intent.putExtra(BUNDLE_SAVED_STATE, bundle);
252 startActivity(intent);
255 protected void onResume() {
259 public void startEditProfileActivity(MobileLedgerProfile profile) {
260 Intent intent = new Intent(this, ProfileDetailActivity.class);
261 Bundle args = new Bundle();
262 if (profile != null) {
263 int index = Data.getProfileIndex(profile);
264 if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
266 intent.putExtras(args);
267 startActivity(intent, args);
269 private void setupProfile() {
270 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
271 MobileLedgerProfile profile;
273 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
275 if (Data.profiles.getList().isEmpty()) {
276 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
277 findViewById(R.id.pager_layout).setVisibility(View.GONE);
281 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
282 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
284 if (profile == null) profile = Data.profiles.get(0);
286 if (profile == null) throw new AssertionError("profile must have a value");
288 Data.setCurrentProfile(profile);
290 public void fabNewTransactionClicked(View view) {
291 Intent intent = new Intent(this, NewTransactionActivity.class);
292 startActivity(intent);
293 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
295 public void navSettingsClicked(View view) {
296 Intent intent = new Intent(this, SettingsActivity.class);
297 startActivity(intent);
298 drawer.closeDrawers();
300 public void markDrawerItemCurrent(int id) {
301 TextView item = drawer.findViewById(id);
302 item.setBackgroundColor(Colors.tableRowDarkBG);
304 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
305 for (int i = 0; i < actions.getChildCount(); i++) {
306 View view = actions.getChildAt(i);
307 if (view.getId() != id) {
308 view.setBackgroundColor(Color.TRANSPARENT);
312 public void onAccountSummaryClicked(View view) {
313 drawer.closeDrawers();
315 showAccountSummaryFragment();
317 private void showAccountSummaryFragment() {
318 mViewPager.setCurrentItem(0, true);
319 TransactionListFragment.accountFilter.set(null);
320 // FragmentTransaction ft = fragmentManager.beginTransaction();
321 // accountSummaryFragment = new AccountSummaryFragment();
322 // ft.replace(R.id.root_frame, accountSummaryFragment);
324 // currentFragment = accountSummaryFragment;
326 public void onLatestTransactionsClicked(View view) {
327 drawer.closeDrawers();
329 showTransactionsFragment(null);
331 private void resetFragmentBackStack() {
332 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
334 private void showTransactionsFragment(LedgerAccount account) {
335 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
336 mViewPager.setCurrentItem(1, true);
337 // FragmentTransaction ft = fragmentManager.beginTransaction();
338 // if (transactionListFragment == null) {
339 // Log.d("flow", "MainActivity creating TransactionListFragment");
340 // transactionListFragment = new TransactionListFragment();
342 // Bundle bundle = new Bundle();
343 // if (account != null) {
344 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
345 // account.getName());
347 // transactionListFragment.setArguments(bundle);
348 // ft.replace(R.id.root_frame, transactionListFragment);
349 // if (account != null)
350 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
353 // currentFragment = transactionListFragment;
355 public void showAccountTransactions(LedgerAccount account) {
356 showTransactionsFragment(account);
359 public void onBackPressed() {
360 DrawerLayout drawer = findViewById(R.id.drawer_layout);
361 if (drawer.isDrawerOpen(GravityCompat.START)) {
362 drawer.closeDrawer(GravityCompat.START);
366 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
368 super.onBackPressed();
371 public void updateLastUpdateTextFromDB() {
373 final MobileLedgerProfile profile = Data.profile.get();
375 (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
377 Log.d("transactions", String.format("Last update = %d", last_update));
378 if (last_update == 0) {
379 Data.lastUpdateDate.set(null);
382 Data.lastUpdateDate.set(new Date(last_update));
386 public void scheduleTransactionListRetrieval() {
387 if (Data.profile.get() == null) return;
389 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
391 retrieveTransactionsTask.execute();
393 public void onStopTransactionRefreshClick(View view) {
394 Log.d("interactive", "Cancelling transactions refresh");
395 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
396 bTransactionListCancelDownload.setEnabled(false);
398 public void onRetrieveDone(String error) {
399 progressLayout.setVisibility(View.GONE);
402 updateLastUpdateTextFromDB();
404 new RefreshDescriptionsTask().execute();
406 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
408 public void onRetrieveStart() {
409 bTransactionListCancelDownload.setEnabled(true);
410 progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
411 progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
412 progressBar.setIndeterminate(true);
413 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
414 else progressBar.setProgress(0);
415 progressLayout.setVisibility(View.VISIBLE);
417 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
418 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
419 (progress.getTotal() == 0))
421 progressBar.setIndeterminate(true);
424 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
425 progressBar.setMin(0);
427 progressBar.setMax(progress.getTotal());
428 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
429 progressBar.setProgress(progress.getProgress(), true);
431 else progressBar.setProgress(progress.getProgress());
432 progressBar.setIndeterminate(false);
435 public void fabShouldShow() {
436 MobileLedgerProfile profile = Data.profile.get();
437 if ((profile != null) && profile.isPostingPermitted()) fab.show();
439 public void navProfilesHeadClicked(View view) {
440 if (profileListExpanded) {
441 collapseProfileList();
447 private void expandProfileList() {
448 profileListExpanded = true;
451 profileListContainer.setVisibility(View.VISIBLE);
452 profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
453 profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
455 private void collapseProfileList() {
456 profileListExpanded = false;
458 final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
459 animation.setAnimationListener(new Animation.AnimationListener() {
461 public void onAnimationStart(Animation animation) {
465 public void onAnimationEnd(Animation animation) {
466 profileListContainer.setVisibility(View.GONE);
469 public void onAnimationRepeat(Animation animation) {
473 profileListContainer.startAnimation(animation);
475 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
477 mProfileListAdapter.stopEditingProfiles();
479 public void onProfileRowClicked(View v) {
480 Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
482 public void enableProfileModifications() {
483 profileModificationEnabled = true;
484 ViewGroup profileList = findViewById(R.id.nav_profile_list);
485 for (int i = 0; i < profileList.getChildCount(); i++) {
486 View aRow = profileList.getChildAt(i);
487 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
488 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
490 // FIXME enable rearranging
493 public void disableProfileModifications() {
494 profileModificationEnabled = false;
495 ViewGroup profileList = findViewById(R.id.nav_profile_list);
496 for (int i = 0; i < profileList.getChildCount(); i++) {
497 View aRow = profileList.getChildAt(i);
498 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
499 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.GONE);
501 // FIXME disable rearranging
505 public class SectionsPagerAdapter extends FragmentPagerAdapter {
507 public SectionsPagerAdapter(FragmentManager fm) {
512 public Fragment getItem(int position) {
513 Log.d("main", String.format("Switching to fragment %d", position));
516 return new AccountSummaryFragment();
518 return new TransactionListFragment();
520 throw new IllegalStateException(
521 String.format("Unexpected fragment index: " + "%d", position));
526 public int getCount() {