com.pixby.texo.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.pixby.texo.MainActivity.java

Source

package com.pixby.texo;

/*
 * Copyright (c) 2016 David Allen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.pixby.texo.EditTools.EditToolsPresenter;
import com.pixby.texo.EditTools.EditorState;
import com.pixby.texo.data.LoaderConstants;
import com.pixby.texo.data.StyleDatabaseHelper;
import com.pixby.texo.images.ImageFile;
import com.pixby.texo.images.ImageUtil;
import com.pixby.texo.images.SaveImageService;
import com.pixby.texo.util.Tracker;
import com.pixby.texo.watermark.Watermark;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private static final String STATE_IMAGE_URI = "image-uri";
    private static final String STATE_WATERMARK = "watermark-json";
    private static final String STATE_SHARE_PATH = "share-path";
    private static final String STATE_IMAGE_CHANGED = "image-changed";
    private static final String STATE_WATERMARK_CHANGED = "watermark-changed";
    private static final String STATE_EDITOR = "editor-state";

    private ImageFile mSourceImage;
    public Watermark mWatermark;
    private String mShareImagePath;

    public StageView mStageView;
    public EditToolsPresenter mEditPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        trackStart();

        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.app_toolbar);
        setSupportActionBar(toolbar);
        mStageView = (StageView) findViewById(R.id.stage_view);
        mEditPresenter = new EditToolsPresenter(this, mStageView);

        if (savedInstanceState == null) {
            importStyleData();
            mWatermark = Watermark.createDefaultWatermark(getApplication().getAssets(),
                    getResources().getString(R.string.action_doubletap));
            handleImageOpenIntent(getIntent());
        } else {
            String imageUriString = savedInstanceState.getString(STATE_IMAGE_URI);
            loadImage(Uri.parse(imageUriString), mStageView);

            mWatermark = Watermark.fromJson(savedInstanceState.getString(STATE_WATERMARK),
                    getApplication().getAssets());
            mShareImagePath = savedInstanceState.getString(STATE_SHARE_PATH);

            mEditPresenter.setEditorState((EditorState) savedInstanceState.getSerializable(STATE_EDITOR));
            mEditPresenter.setWatermarkModified(savedInstanceState.getBoolean(STATE_WATERMARK_CHANGED));
            mEditPresenter.setImageChanged(savedInstanceState.getBoolean(STATE_IMAGE_CHANGED));
            mEditPresenter.showTool();
        }

        mStageView.setWatermark(mWatermark);
    }

    private void trackStart() {
        Bundle payload = new Bundle();
        payload.putString(FirebaseAnalytics.Param.ORIGIN, Tracker.Param.EDIT_ACTIVITY);
        Tracker.trackEvent(this, FirebaseAnalytics.Event.APP_OPEN, payload);
    }

    // Receive broadcasts from Save Image service
    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                String path = bundle.getString(SaveImageService.OUTPUT_PATH);
                int resultCode = bundle.getInt(SaveImageService.RESULT);
                int outputDestination = bundle.getInt(SaveImageService.OUTPUT_DESTINATION);
                if (resultCode == RESULT_OK) {
                    onFileSaved(path, outputDestination);
                } else {
                    String resultMessage = bundle.getString(SaveImageService.RESULT_MESSAGE);
                    onFileSaveError(resultMessage);
                }
            }
        }
    };

    private void handleImageOpenIntent(Intent intent) {
        if (intent != null) {
            Tracker.trackSimpleEvent(this, Tracker.Event.LOAD_IMAGE);
            Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
            loadImage(imageUri, mStageView);
            mEditPresenter.setImageChanged(true);
        }
    }

    private void importStyleData() {

        // data already loaded
        if (StyleDatabaseHelper.isDataAvailable(getContentResolver())) {
            return;
        }
        getSupportLoaderManager().initLoader(LoaderConstants.STYLE_IMPORT_LOADER, null,
                new LoaderManager.LoaderCallbacks() {
                    @Override
                    public Loader onCreateLoader(int id, Bundle args) {
                        return new com.pixby.texo.data.LoadStyleDataTask(MainActivity.this,
                                MainActivity.this.getContentResolver(), getAssets());
                    }

                    @Override
                    public void onLoadFinished(Loader loader, Object data) {
                    }

                    @Override
                    public void onLoaderReset(Loader loader) {
                    }
                });
    }

    private void shareImage() {

        Tracker.trackSimpleEvent(this, Tracker.Event.SHARE);

        // image or watermark have changed - save new image
        if (mEditPresenter.getImageChanged() || mEditPresenter.getWatermarkModified()) {
            ImageUtil.deleteCachedImage(mShareImagePath);
            mEditPresenter.setImageChanged(false);
            mEditPresenter.setWatermarkModified(false);
            startSaveService(ImageUtil.TEMP_FOLDER, ImageUtil.SIZE_SHARE, SaveImageService.INTENT_SHARE);
        } else {
            // reuse last shared image
            if (mShareImagePath != null) {
                Uri uri = Uri.fromFile(new File(mShareImagePath));
                runShareIntent(uri);
            }
        }
    }

    // write new image every time
    private void exportImage() {
        Tracker.trackSimpleEvent(this, Tracker.Event.EXPORT);
        if (ImageUtil.verifyStoragePermissions(this)) {
            startSaveService(ImageUtil.APP_FOLDER, ImageUtil.SIZE_EXPORT, SaveImageService.INTENT_EXPORT);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
            @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == ImageUtil.REQUEST_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startSaveService(ImageUtil.APP_FOLDER, ImageUtil.SIZE_EXPORT, SaveImageService.INTENT_EXPORT);
            }
        }
    }

    private void startSaveService(int folderLocation, int outputSizeFlag, int outputDestination) {

        String path = ImageUtil.getOutputFolder(this, mSourceImage.getFileName(), folderLocation);
        Rect outputSize = ImageUtil.calcTargetSize(mSourceImage.getWidth(), mSourceImage.getHeight(),
                outputSizeFlag);

        Intent intent = new Intent(this, SaveImageService.class);
        intent.putExtra(SaveImageService.SOURCE_IMAGE_URI, mSourceImage.getUri());
        intent.putExtra(SaveImageService.WATERMARK_JSON, mWatermark.toJson());
        intent.putExtra(SaveImageService.OUTPUT_PATH, path);
        intent.putExtra(SaveImageService.OUTPUT_WIDTH, outputSize.width());
        intent.putExtra(SaveImageService.OUTPUT_HEIGHT, outputSize.height());
        intent.putExtra(SaveImageService.OUTPUT_DESTINATION, outputDestination);
        startService(intent);
    }

    private void showToast(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
        case R.id.action_export:
            exportImage();
            break;
        case R.id.menu_item_share:
            shareImage();
            break;
        case R.id.menu_item_open_browser:
            getImageFromGallery();
            break;
        default:
            return super.onOptionsItemSelected(item);
        }
        return true;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString(STATE_IMAGE_URI, mSourceImage.getUri().toString());
        outState.putString(STATE_WATERMARK, mWatermark.toJson());
        outState.putString(STATE_SHARE_PATH, mShareImagePath);
        outState.putBoolean(STATE_IMAGE_CHANGED, mEditPresenter.getImageChanged());
        outState.putBoolean(STATE_WATERMARK_CHANGED, mEditPresenter.getWatermarkModified());
        outState.putSerializable(STATE_EDITOR, mEditPresenter.getEditorState());
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mBroadcastReceiver);
        mStageView.setEditingListener(null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mBroadcastReceiver, new IntentFilter(SaveImageService.NOTIFICATION));
        mStageView.setEditingListener(mEditPresenter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mEditPresenter.onDestroy();
    }

    private void onFileSaved(String filePath, int outputDestination) {
        String msg = String.format("File saved: %s", filePath);
        showToast(msg);
        Log.d(TAG, msg);

        MediaScannerConnection.OnScanCompletedListener scanListener = null;

        // if this is a share operation add post-scan listener to kick off share
        // listener is optional, not needed for export
        if (outputDestination == SaveImageService.INTENT_SHARE) {
            scanListener = mfileScanListener;
            mShareImagePath = filePath;
        }

        MediaScannerConnection.scanFile(this, new String[] { filePath }, null, scanListener);
    }

    private final MediaScannerConnection.OnScanCompletedListener mfileScanListener = new MediaScannerConnection.OnScanCompletedListener() {
        @Override
        public void onScanCompleted(String path, Uri uri) {
            runShareIntent(uri);
        }
    };

    private void onFileSaveError(String msg) {
        Log.e(TAG, "onFileSaveError:  " + msg);
        showToast(msg);
    }

    private void runShareIntent(Uri uri) {
        final Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/jpg");
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        String message = getResources().getString(R.string.action_share_photo);
        startActivity(Intent.createChooser(shareIntent, message));
    }

    private void getImageFromGallery() {
        Tracker.trackSimpleEvent(this, Tracker.Event.CHANGE_IMAGE);
        ImageUtil.getImageFromGallery(this);
    }

    private void loadImage(Uri uri, StageView view) {
        if (uri != null) {
            mSourceImage = new ImageFile();
            mSourceImage.getFileProperties(uri, getContentResolver());
            Glide.with(this).loadFromMediaStore(uri).asBitmap().into(view);
        } else {
            showToast(getResources().getString(R.string.action_image_load_problem));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        boolean dataAvailable = requestCode == ImageUtil.PICK_IMAGE_REQUEST && resultCode == RESULT_OK
                && intent != null && intent.getData() != null;

        if (dataAvailable) {
            loadImage(intent.getData(), mStageView);
            mEditPresenter.setImageChanged(true);
        }
    }
}