diff options
Diffstat (limited to 'app/src/main/java/net/lacolaco/smileessence/activity/MainActivity.java')
-rw-r--r-- | app/src/main/java/net/lacolaco/smileessence/activity/MainActivity.java | 326 |
1 files changed, 108 insertions, 218 deletions
diff --git a/app/src/main/java/net/lacolaco/smileessence/activity/MainActivity.java b/app/src/main/java/net/lacolaco/smileessence/activity/MainActivity.java index 4e1b50e0..f6351f30 100644 --- a/app/src/main/java/net/lacolaco/smileessence/activity/MainActivity.java +++ b/app/src/main/java/net/lacolaco/smileessence/activity/MainActivity.java @@ -26,88 +26,49 @@ package net.lacolaco.smileessence.activity; import android.app.ActionBar; import android.app.Activity; -import android.content.Context; import android.content.Intent; -import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; -import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; -import android.support.annotation.NonNull; -import android.support.v4.app.ActivityCompat; -import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; import android.widget.ImageView; import de.keyboardsurfer.android.widget.crouton.Crouton; -import net.lacolaco.smileessence.Application; -import net.lacolaco.smileessence.BuildConfig; -import net.lacolaco.smileessence.IntentRouter; -import net.lacolaco.smileessence.R; +import net.lacolaco.smileessence.*; import net.lacolaco.smileessence.data.Account; import net.lacolaco.smileessence.data.ExtractionWord; -import net.lacolaco.smileessence.data.PostState; import net.lacolaco.smileessence.entity.RBinding; import net.lacolaco.smileessence.entity.User; import net.lacolaco.smileessence.logging.Logger; -import net.lacolaco.smileessence.notification.Notificator; -import net.lacolaco.smileessence.preference.InternalPreferenceHelper; -import net.lacolaco.smileessence.twitter.UserStreamListener; import net.lacolaco.smileessence.twitter.task.Users; -import net.lacolaco.smileessence.util.*; +import net.lacolaco.smileessence.util.BitmapOptimizer; +import net.lacolaco.smileessence.util.BitmapURLTask; +import net.lacolaco.smileessence.util.IntentUtils; +import net.lacolaco.smileessence.util.UIObserverBundle; import net.lacolaco.smileessence.view.adapter.PageListAdapter; import net.lacolaco.smileessence.view.dialog.ConfirmDialogFragment; import net.lacolaco.smileessence.view.page.*; -import twitter4j.TwitterStream; - -import java.lang.reflect.Field; -import java.util.Collections; -import java.util.Set; -import java.util.WeakHashMap; - -public class MainActivity extends Activity implements Application.OnCurrentAccountChangedListener, ViewPager.OnPageChangeListener { - // ------------------------------ FIELDS ------------------------------ +public class MainActivity extends Activity implements ViewPager.OnPageChangeListener { public static final int REQUEST_GET_PICTURE_FROM_GALLERY = 11; - private static final int REQUEST_MANAGE_ACCOUNT = 13; - private static final int REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION = 14; - private Account currentAccount; - private final Set<Application.OnCurrentAccountChangedListener> currentAccountChangedListeners = Collections.newSetFromMap(new WeakHashMap<>()); /* will be removed eventually */ + private final UIObserverBundle currentUserBundle = new UIObserverBundle(); + private World world; private ViewPager viewPager; private ImageView currentAccountIconImageView; private PageListAdapter pagerAdapter; - private TwitterStream stream; - private UserStreamListener userStreamListener; - private final UIObserverBundle currentUserBundle = new UIObserverBundle(); - - public Account getCurrentAccount() { - return currentAccount; - } - - public void setCurrentAccount(Account val) { - Logger.debug(String.format("setCurrentAccount: %s", val.getUser().getScreenName())); - currentAccount = val; - for (Application.OnCurrentAccountChangedListener listener : currentAccountChangedListeners) { - new UIHandler().post(() -> listener.onCurrentAccountChanged(val)); - } - } - - public void addOnCurrentAccountChangedListener(Application.OnCurrentAccountChangedListener listener) { - currentAccountChangedListeners.add(listener); - } - public boolean isStreaming() { - return userStreamListener != null && userStreamListener.isConnected(); + public World getWorld() { + return world; } - public void setSelectedPageIndex(int position) { + private void setSelectedPageIndex(int position) { setSelectedPageIndex(position, true); } - public void setSelectedPageIndex(int position, boolean smooth) { + private void setSelectedPageIndex(int position, boolean smooth) { viewPager.setCurrentItem(position, smooth); } @@ -125,15 +86,15 @@ public class MainActivity extends Activity implements Application.OnCurrentAccou assert c != null; c.moveToFirst(); String path = c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA)); - String rotatedPath = BitmapOptimizer.rotateImageByExif(this, path); - PostState.getState().beginTransaction() + String rotatedPath = path; // BitmapOptimizer.rotateImageByExif(this, path); + world.getPostState().beginTransaction() .setMediaFilePath(rotatedPath) .commitWithOpen(this); - Notificator.getInstance().publish(R.string.notice_select_image_succeeded); + world.notify(R.string.notice_select_image_succeeded); c.close(); } catch (Exception e) { e.printStackTrace(); - Notificator.getInstance().alert(R.string.notice_select_image_failed); + world.notifyError(R.string.notice_select_image_failed); } } @@ -171,29 +132,20 @@ public class MainActivity extends Activity implements Application.OnCurrentAccou @Override public void finish() { if (viewPager == null) { - forceFinish(); + super.finish(); return; } int homeIndex = pagerAdapter.getIndex(HomeFragment.class); if (viewPager.getCurrentItem() != homeIndex) { viewPager.setCurrentItem(homeIndex, true); } else { - ConfirmDialogFragment.show(this, getString(R.string.dialog_confirm_finish_app), this::forceFinish); + ConfirmDialogFragment.show(this, getString(R.string.dialog_confirm_finish_app), super::finish); } } - public void forceFinish() { - super.finish(); - } - @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { - case REQUEST_MANAGE_ACCOUNT: - if (resultCode == RESULT_CANCELED && getCurrentAccount() == null) { - forceFinish(); - } - break; case REQUEST_GET_PICTURE_FROM_GALLERY: getImageUri(requestCode, resultCode, data); break; @@ -203,61 +155,91 @@ public class MainActivity extends Activity implements Application.OnCurrentAccou @Override public void onCreate(Bundle savedInstanceState) { Logger.debug("onCreate"); - Application app = (Application) getApplication(); - app.resetState(); - setTheme(app.getThemeResId()); super.onCreate(savedInstanceState); + + Uri uri = getIntent().getData(); + if (uri == null) { + throw new IllegalStateException("[BUG] data not set"); + } + String userIdValue = uri.getQueryParameter("user_id"); + if (userIdValue == null) + throw new IllegalStateException("[BUG] user_id not set"); + long userId = Long.parseLong(userIdValue); + world = Application.getWorld(userId); + world.setMainActivity(this); + + // XXX + Account account = world.getAccount(); + + setTheme(account.themeIndex == 0 ? R.style.theme_dark : R.style.theme_light); setContentView(R.layout.layout_main); viewPager = (ViewPager) findViewById(R.id.viewPager); pagerAdapter = new PageListAdapter(this); viewPager.addOnPageChangeListener(this); + getActionBar().setDisplayHomeAsUpEnabled(true); currentAccountIconImageView = (ImageView) findViewById(android.R.id.home); currentAccountIconImageView.setScaleType(ImageView.ScaleType.FIT_XY); - Notificator.getInstance().setDefault(this); - Account.load(); + // TODO: tab order? + Bundle args = new Bundle(); + args.putLong(PageFragment.KEY_USER_ID, account.getUserId()); + pagerAdapter.addPage(PostFragment.class, getString(R.string.page_name_post), args, false); + pagerAdapter.addPage(HomeFragment.class, getString(R.string.page_name_home), args, false); + pagerAdapter.addPage(MentionsFragment.class, getString(R.string.page_name_mentions), args, false); + pagerAdapter.addPage(HistoryFragment.class, getString(R.string.page_name_history), args, false); + pagerAdapter.addPage(MessagesFragment.class, getString(R.string.page_name_messages), args, false); + pagerAdapter.addPage(SearchFragment.class, getString(R.string.page_name_search), args, false); + pagerAdapter.addPage(UserListFragment.class, getString(R.string.page_name_list), args, false); + pagerAdapter.notifyDataSetChanged(); + viewPager.setOffscreenPageLimit(pagerAdapter.getCount()); + viewPager.setAdapter(pagerAdapter); + setSelectedPageIndex(pagerAdapter.getIndex(HomeFragment.class), false); + ExtractionWord.load(); - initializePages(); - addOnCurrentAccountChangedListener(this); - int wextPermission = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE); - if (wextPermission == PackageManager.PERMISSION_GRANTED) { - startMainLogic(); - } else { - requestPermission(); - } - } + // update cache + world.refreshListSubscriptions(); + world.refreshUserMuteList(); + world.refreshSavedSearches(); + new Users.GetTask(account, account.getUserId()).execute(); - private void requestPermission() { - ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION); - } + User user = account.getUser(); - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { - switch (requestCode) { - case REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION: { - if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - // permission granted; start main logic - startMainLogic(); - } else { - // permission denied; どうする? - Notificator.getInstance().alert(R.string.notice_error_storage_permission); - forceFinish(); - } - break; + // Set application title + setTitle(); + + // update actionbar + Runnable update = () -> { + setTitle(); + updateActionBarTitle(); + String newUrl = user.getProfileImageUrlOriginal(); + if (newUrl != null) { + new BitmapURLTask(newUrl, currentAccountIconImageView).execute(); + } + }; + update.run(); //first run + + currentUserBundle.detachAll(); + currentUserBundle.attach(user, changes -> { + if (changes.contains(RBinding.BASIC)) update.run(); + }); + + // refresh all pages + for (int i = 0; i < pagerAdapter.getCount(); ++i) { + PageFragment pf = pagerAdapter.getCachedFragment(i); + if (pf != null && pf.isAdded()) { + Logger.debug(String.format("PageFragment %s is already attached; refreshing", pf.getClass().getName())); + pf.refresh(); } } + + // start user stream + world.setupStreaming(); } - private void startMainLogic() { - Account account = getLastUsedAccount(); - if (account != null) { - setCurrentAccount(account); - IntentRouter.onNewIntent(this, getIntent()); - } else { - startActivityForResult(new Intent(this, ManageAccountsActivity.class), REQUEST_MANAGE_ACCOUNT); - } + private void setTitle() { + setTitle(getString(R.string.app_name) + " - @" + world.getAccount().getUser().getScreenName()); } @Override @@ -265,19 +247,10 @@ public class MainActivity extends Activity implements Application.OnCurrentAccou super.onDestroy(); currentUserBundle.detachAll(); Crouton.cancelAllCroutons(); - if (stream != null) { - new Thread(stream::shutdown).start(); - } Logger.debug("onDestroy"); } @Override - protected void onNewIntent(Intent intent) { - IntentRouter.onNewIntent(this, intent); - super.onNewIntent(intent); - } - - @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; @@ -286,52 +259,46 @@ public class MainActivity extends Activity implements Application.OnCurrentAccou @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { - case R.id.actionbar_post: { - openPostPage(); + case android.R.id.home: { + Intent intent = new Intent(this, ManageAccountsActivity.class); + intent.putExtra(ManageAccountsActivity.INTENT_KEY_NOINIT, true); + startActivity(intent); return true; } - case R.id.actionbar_setting: { - startActivity(new Intent(this, SettingActivity.class)); + case R.id.actionbar_post: + openPostPage(); return true; - } - case R.id.actionbar_accounts: { - startActivity(new Intent(this, ManageAccountsActivity.class)); + case R.id.actionbar_setting: + startActivity(new Intent(this, SettingActivity.class)); return true; - } - case R.id.actionbar_edit_extraction: { + case R.id.actionbar_edit_extraction: startActivity(new Intent(this, EditExtractionActivity.class)); return true; - } - case R.id.actionbar_aclog: { - IntentUtils.openUri(this, getCurrentAccount().getUser().getAclogTimelineURL()); + case R.id.actionbar_aclog: + IntentUtils.openUri(this, world.getAccount().getUser().getAclogTimelineURL()); return true; - } - case R.id.actionbar_report: { - PostState.getState().beginTransaction() + case R.id.actionbar_report: + world.getPostState().beginTransaction() .appendText(getString(R.string.text_message_to_author, BuildConfig.VERSION_NAME)) .commitWithOpen(this); return true; - } - default: { - return false; - } + default: + return super.onOptionsItemSelected(item); } } @Override protected void onPause() { - super.onPause(); Logger.debug("onPause"); - getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - Notificator.getInstance().onBackground(); + super.onPause(); + world.setMainActivityActive(false); } @Override protected void onResume() { - super.onResume(); Logger.debug("onResume"); - getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - Notificator.getInstance().onForeground(); + super.onResume(); + world.setMainActivityActive(true); } // --------------------- Interface OnPageChangeListener --------------------- @@ -355,97 +322,20 @@ public class MainActivity extends Activity implements Application.OnCurrentAccou private void getImageUri(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) { Logger.error(requestCode); - Notificator.getInstance().alert(R.string.notice_select_image_failed); + world.notifyError(R.string.notice_select_image_failed); finish(); return; } openPostPageWithImage(data.getData()); } - private void startStream() { - if (stream != null) { - new Thread(stream::cleanUp).start(); - } - stream = getCurrentAccount().getTwitterStream(); - userStreamListener = new UserStreamListener(getCurrentAccount()); - stream.addListener(userStreamListener); - stream.addConnectionLifeCycleListener(userStreamListener); - stream.user(); - } - - @Override - public void onCurrentAccountChanged(Account account) { - // update cache - account.refreshListSubscriptions(); - account.refreshUserMuteList(); - account.refreshSavedSearches(); - new Users.GetTask(account, account.getUserId()).execute(); - - User user = account.getUser(); - - // update actionbar - Runnable update = () -> { - updateActionBarTitle(); - String newUrl = user.getProfileImageUrlOriginal(); - if (newUrl != null) { - new BitmapURLTask(newUrl, currentAccountIconImageView).execute(); - } - }; - update.run(); //first run - - currentUserBundle.detachAll(); - currentUserBundle.attach(user, changes -> { - if (changes.contains(RBinding.BASIC)) update.run(); - }); - - // refresh all pages - for (int i = 0; i < pagerAdapter.getCount(); ++i) { - PageFragment pf = pagerAdapter.getCachedFragment(i); - if (pf != null && pf.isAdded()) { - Logger.debug(String.format("PageFragment %s is already attached; refreshing", pf.getClass().getName())); - pf.refresh(); - } - } - - // start user stream - startStream(); - } - private void updateActionBarTitle() { ActionBar actionBar = getActionBar(); - Account currentAccount = getCurrentAccount(); - if (actionBar != null && currentAccount != null) { + Account currentAccount = world.getAccount(); + if (actionBar != null) { String screenName = currentAccount.getUser().getScreenName(); String pageTitle = pagerAdapter.getName(viewPager.getCurrentItem()); setTitle(String.format("%s / %s", screenName, pageTitle)); } } - - // TODO: tab order? - private void initializePages() { - pagerAdapter.addPage(PostFragment.class, getString(R.string.page_name_post), null, false); - pagerAdapter.addPage(HomeFragment.class, getString(R.string.page_name_home), null, false); - pagerAdapter.addPage(MentionsFragment.class, getString(R.string.page_name_mentions), null, false); - pagerAdapter.addPage(HistoryFragment.class, getString(R.string.page_name_history), null, false); - pagerAdapter.addPage(MessagesFragment.class, getString(R.string.page_name_messages), null, false); - pagerAdapter.addPage(SearchFragment.class, getString(R.string.page_name_search), null, false); - pagerAdapter.addPage(UserListFragment.class, getString(R.string.page_name_list), null, false); - pagerAdapter.notifyDataSetChanged(); - viewPager.setOffscreenPageLimit(pagerAdapter.getCount()); - viewPager.setAdapter(pagerAdapter); - setSelectedPageIndex(pagerAdapter.getIndex(HomeFragment.class), false); - PostState.newState().beginTransaction().commit(); - } - - private Account getLastUsedAccount() { - long lastId = InternalPreferenceHelper.getInstance().get(R.string.key_last_used_account_id, -1L); - Account account = null; - if (lastId != -1) { - account = Account.get(lastId); - } - if (account == null && Account.count() > 0) { - account = Account.all().get(0); - } - return account; - } } |