com.richtodd.android.quiltdesign.app.QuiltEditActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.richtodd.android.quiltdesign.app.QuiltEditActivity.java

Source

/* Copyright (c) 2013 Richard G. Todd.
 * Licensed under the terms of the GNU General Public License (GPL) Version 3.0.
 */

package com.richtodd.android.quiltdesign.app;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.Date;
import java.util.List;

import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.richtodd.android.pdf.DocumentInformation;
import com.richtodd.android.pdf.DocumentWriter;
import com.richtodd.android.pdf.Rectangle;
import com.richtodd.android.quiltdesign.block.BlockContainer;
import com.richtodd.android.quiltdesign.block.BlockContainerEntry;
import com.richtodd.android.quiltdesign.block.JSONRepository;
import com.richtodd.android.quiltdesign.block.NestedLinearLayout;
import com.richtodd.android.quiltdesign.block.Quilt;
import com.richtodd.android.quiltdesign.block.QuiltContainer;
import com.richtodd.android.quiltdesign.block.QuiltDocumentFormatter;
import com.richtodd.android.quiltdesign.block.RenderFormats;
import com.richtodd.android.quiltdesign.block.RenderOptions;
import com.richtodd.android.quiltdesign.block.RenderStyles;
import com.richtodd.android.quiltdesign.block.Repository;
import com.richtodd.android.repository.JSONUtility;
import com.richtodd.android.repository.RepositoryException;

public class QuiltEditActivity extends Activity implements AlertDialogFragment.AlertDialogListener,
        EditNameDialogFragment.EditNameDialogListener, ShareOptionsDialogFragment.ShareOptionsDialogListener,
        QuiltOptionsDialogFragment.QuiltOptionsDialogListener {

    //
    // Fields
    //

    public static final String ARG_QUILT_NAME = "com.richtodd.android.quiltdesign.app.QuiltEditActivity.quiltName";
    private static final String KEY_CONFIRM_DELETE = "confirmDelete";
    private static final String KEY_FILE_EXISTS = "fileExists";

    private String m_quiltNameArgument;

    private NestedLinearLayout m_layout_blocks;

    private String m_saveAsQuiltName;

    //
    // Overrides
    //

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quilt_edit);
        getActionBar().setDisplayHomeAsUpEnabled(true);

        m_quiltNameArgument = getIntent().getStringExtra(ARG_QUILT_NAME);

        if (savedInstanceState != null) {
            m_saveAsQuiltName = savedInstanceState.getString("saveAsQuiltName");
        }

        ActionBar ab = getActionBar();
        ab.setTitle("Edit Quilt");
        ab.setSubtitle(getCurrentQuiltName());

        FragmentManager fm = getFragmentManager();

        // Create color settings fragment.
        {
            Fragment fragment = fm.findFragmentById(R.id.layout_quiltEditFragment);
            if (fragment == null) {
                fragment = QuiltEditFragment.create(m_quiltNameArgument);
                fm.beginTransaction().add(R.id.layout_quiltEditFragment, fragment).commit();
            }
        }

        m_layout_blocks = (NestedLinearLayout) findViewById(R.id.layout_blocks);

        populateLayoutBlocks();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putString("saveAsQuiltName", m_saveAsQuiltName);
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        switch (itemId) {
        case android.R.id.home: {
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        case R.id.menu_quiltOptions: {
            Quilt quilt = getQuiltEditFragment().getQuilt();
            QuiltOptionsDialogFragment dialog = QuiltOptionsDialogFragment.create(quilt.getRowCount(),
                    quilt.getColumnCount(), (int) quilt.getWidth());
            dialog.show(getFragmentManager(), null);
            return true;
        }
        case R.id.menu_shareQuilt: {
            ShareOptionsDialogFragment dialog = ShareOptionsDialogFragment.create(Intent.ACTION_SEND);
            dialog.show(getFragmentManager(), null);
            return true;
        }
        case R.id.menu_viewQuilt: {
            ShareOptionsDialogFragment dialog = ShareOptionsDialogFragment.create(Intent.ACTION_VIEW);
            dialog.show(getFragmentManager(), null);
            return true;
        }
        case R.id.menu_renameQuilt: {
            showEditNameDialog();
            return true;
        }
        case R.id.menu_deleteQuilt: {
            AlertDialogFragment dialog = AlertDialogFragment.create(KEY_CONFIRM_DELETE,
                    getString(R.string.alert_message_confirmQuiltDelete), getString(R.string.alert_button_yes),
                    getString(R.string.alert_button_no));
            dialog.show(getFragmentManager(), null);
            return true;
        }
        case R.id.menu_cancelChanges: {
            getQuiltEditFragment().setSaveSuppressed(true);
            finish();
            return true;
        }
        case R.id.menu_settings: {
            Intent intent = new Intent(this, QuiltPreferenceActivity.class);
            startActivity(intent);
            return true;
        }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onAlertDialogPositiveClick(DialogFragment dialog, String key) throws Exception {

        if (key.equals(KEY_CONFIRM_DELETE)) {
            getQuiltEditFragment().setSaveSuppressed(true);

            Repository repository = Repository.getDefaultRepository(this);
            QuiltContainer quilts = repository.getQuilts();
            quilts.deleteQuilt(m_quiltNameArgument);

            finish();

        } else if (key.equals(KEY_FILE_EXISTS)) {
            showEditNameDialog();

        } else {
            throw new InvalidParameterException("Unknown key " + key);
        }
    }

    @Override
    public void onAlertDialogNegativeClick(DialogFragment dialog, String key) {
        // No action required.
    }

    @Override
    public void onEditNamePositiveClick(DialogFragment dialog, String name) throws Exception {
        Repository repository = Repository.getDefaultRepository(this);
        QuiltContainer quilts = repository.getQuilts();
        if (quilts.quiltExists(name)) {
            AlertDialogFragment alertDialog = AlertDialogFragment.create(KEY_FILE_EXISTS,
                    getString(R.string.alert_message_quiltAlreadyExists),
                    getString(R.string.alert_button_acknowledge), null);
            alertDialog.show(getFragmentManager(), null);
        } else {
            m_saveAsQuiltName = name;
            getQuiltEditFragment().setSaveAsQuiltName(m_saveAsQuiltName);
        }

        ActionBar ab = getActionBar();
        ab.setSubtitle(getCurrentQuiltName());
    }

    @Override
    public void onEditNameNegativeClick(DialogFragment dialog) {
        // No action required.
    }

    @Override
    public void onShareOptionsPositiveClick(DialogFragment dialog, RenderStyles renderStyle,
            RenderFormats renderFormat, String intentAction) throws Exception {

        Uri uriFile;
        String type;
        switch (renderFormat) {
        case Bitmap:
            uriFile = saveBitmap(renderStyle);
            type = "image/png";
            break;
        case PDF:
            uriFile = savePDF(renderStyle);
            type = "application/pdf";
            break;
        case QuiltDesign:
            uriFile = saveQuiltDesign();
            type = "application/vnd.richtodd.quiltdesign";
            break;
        default:
            throw new IllegalArgumentException("Unknown render format " + renderFormat);
        }

        Intent intent = new Intent(intentAction);
        if (intentAction.equals(Intent.ACTION_SEND)) {
            intent.putExtra(Intent.EXTRA_STREAM, uriFile);
            intent.setType(type);
            startActivity(Intent.createChooser(intent, "Share With"));
        } else {
            intent.setDataAndType(uriFile, type);
            startActivity(Intent.createChooser(intent, "View With"));
        }
    }

    @Override
    public void onShareOptionsNegativeClick(DialogFragment dialog) {
        // No action required.
    }

    @Override
    public void onQuiltOptionsPositiveClick(DialogFragment dialog, int rowCount, int columnCount, int width) {
        QuiltEditFragment fragment = getQuiltEditFragment();
        fragment.setRowCount(rowCount);
        fragment.setColumnCount(columnCount);
        fragment.setWidth(width);
    }

    @Override
    public void onQuiltOptionsNegativeClick(DialogFragment dialog) {
        // No action required.
    }

    //
    // Private Methods
    //

    private String getCurrentQuiltName() {
        if (m_saveAsQuiltName != null) {
            return m_saveAsQuiltName;
        } else {
            return m_quiltNameArgument;
        }
    }

    private Uri saveBitmap(RenderStyles renderStyle) throws Exception {
        QuiltEditFragment fragment = getQuiltEditFragment();
        Quilt quilt = fragment.getQuilt();

        File file = new File(StorageUtility.getPublicFolder(), getCurrentQuiltName() + ".png");

        saveBitmap(quilt, file, renderStyle);

        Uri uriFile = Uri.fromFile(file);
        return uriFile;
    }

    private void saveBitmap(Quilt quilt, File file, RenderStyles renderStyle) throws Exception {
        int imageSize = getResources().getInteger(R.integer.quilt_image_size);
        int marginSize = getResources().getInteger(R.integer.quilt_margin_size);
        int shareDensity = Preferences.getEffectiveShareDensity(this,
                PreferenceManager.getDefaultSharedPreferences(this));

        RenderOptions renderOptions = new RenderOptions();
        renderOptions.setWidth(imageSize * shareDensity);
        renderOptions.setHeight(imageSize * shareDensity);
        renderOptions.setLeft(marginSize);
        renderOptions.setTop(marginSize);
        renderOptions.setStrokeWidth(2);
        renderOptions.setRenderStyle(renderStyle);

        Bitmap bitmap = renderOptions.createBitmap();

        quilt.draw(bitmap, renderOptions);

        FileOutputStream stream = new FileOutputStream(file);
        try {
            bitmap.compress(CompressFormat.PNG, 100, stream);
        } finally {
            stream.close();
        }
    }

    private Uri savePDF(RenderStyles renderStyle) throws IOException {

        QuiltEditFragment fragment = getQuiltEditFragment();
        Quilt quilt = fragment.getQuilt();

        File file = new File(StorageUtility.getPublicFolder(), getCurrentQuiltName() + ".pdf");

        savePDF(quilt, file, renderStyle, getCurrentQuiltName());

        Uri uri = Uri.fromFile(file);

        return uri;
    }

    private void savePDF(Quilt quilt, File file, RenderStyles renderStyle, String title) throws IOException {

        DocumentWriter writer = new DocumentWriter(new BufferedOutputStream(new FileOutputStream(file)));
        try {
            writer.beginDocument(Rectangle.getLetterPageBoundary(), Rectangle.getLetterContentBoundary());

            writer.beginPage();

            QuiltDocumentFormatter formatter = new QuiltDocumentFormatter();
            formatter.formatQuiltAndBlocks(quilt, title, writer, renderStyle);

            writer.endPage();

            DocumentInformation documentInformation = new DocumentInformation();
            documentInformation.setCreationDate(new Date());
            documentInformation.setTitle(title);
            writer.endDocument(documentInformation);
        } finally {
            writer.close();
        }
    }

    private Uri saveQuiltDesign() throws IOException, RepositoryException {

        QuiltEditFragment fragment = getQuiltEditFragment();
        Quilt quilt = fragment.getQuilt();

        File file = new File(StorageUtility.getPublicFolder(), getCurrentQuiltName() + ".quiltdesign");

        saveQuiltDesign(quilt, file);

        Uri uri = Uri.fromFile(file);

        return uri;
    }

    private void saveQuiltDesign(Quilt quilt, File file) throws RepositoryException {
        JSONObject jsonRepository = new JSONObject();
        JSONRepository repository = new JSONRepository(jsonRepository, null);
        repository.getQuilts().saveQuilt(getCurrentQuiltName(), quilt, null);
        JSONUtility.saveJSONObject(file, jsonRepository);
    }

    private void showEditNameDialog() {
        String quiltName = getCurrentQuiltName();
        EditNameDialogFragment dialog = EditNameDialogFragment.create("Quilt", quiltName);
        dialog.show(getFragmentManager(), null);
    }

    private void populateLayoutBlocks() {
        List<BlockContainerEntry> entries;
        try {
            Repository repository = Repository.getDefaultRepository(this);
            BlockContainer blocks = repository.getBlocks();
            entries = blocks.getEntries(true);
        } catch (RepositoryException ex) {
            return;
        }

        LinearLayout layoutRow = null;

        for (BlockContainerEntry entry : entries) {
            View view = QuiltEditActivity.this.getLayoutInflater().inflate(R.layout.listentry_block_selector, null);

            ImageView image_thumbnail = (ImageView) view.findViewById(R.id.image_thumbnail);
            image_thumbnail.setImageBitmap(entry.getThumbnail());

            view.setTag(entry.getBlockName());
            view.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    String blockName = (String) v.getTag();
                    try {
                        getQuiltEditFragment().setBlock(blockName);
                    } catch (Exception e) {
                        Handle.asRuntimeError(e);
                    }
                }
            });

            if (m_layout_blocks.getOrientation() == LinearLayout.HORIZONTAL) {
                m_layout_blocks.addView(view);
            } else {
                if (layoutRow != null && layoutRow.getChildCount() == m_layout_blocks.getNumColumns()) {
                    layoutRow = null;
                }
                if (layoutRow == null) {
                    layoutRow = new LinearLayout(this);
                    layoutRow.setOrientation(LinearLayout.HORIZONTAL);
                    m_layout_blocks.addView(layoutRow);
                }
                layoutRow.addView(view);
            }
        }
    }

    private QuiltEditFragment getQuiltEditFragment() {
        return (QuiltEditFragment) getFragmentManager().findFragmentById(R.id.layout_quiltEditFragment);
    }

}