activities.PaintActivity.java Source code

Java tutorial

Introduction

Here is the source code for activities.PaintActivity.java

Source

package activities;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.LabeledIntent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;

import com.cambriantech.CBImagePainter;
import com.flurry.android.FlurryAgent;

import colorlife.arbiec.com.colorlife.R;
import data.ColorCategory;
import data.CoreSQL;
import data.PaintColor;
import data.PaintColorDataSource;
import ui.BottomButtons;
import ui.CircleView;
import ui.LayerMenuItem;
import ui.MenuButtons;
import ui.PaintCheckBox;
import ui.PaintSwatch;
import ui.PaletaColores;
import ui.ShareChooserAdapter;
import ui.SwatchesFilter;
import ui.TopBarPainting;
import util.PaintUtility;

import static colorlife.arbiec.com.colorlife.R.*;
import static colorlife.arbiec.com.colorlife.R.string.*;

//import com.google.ads.AdRequest;
//import com.google.ads.AdView;

public abstract class PaintActivity extends BaseActivity implements PaletaColores.PaletaColoresListener,
        /*MenuSidebar.MenuSidebarListener,*/
        TopBarPainting.TopBarPaintingListener, CBImagePainter.CBImagePainterListener,
        //        BottomButtons.BottomButtonsListener,
        //        MenuButtons.MenuButtonsListener,
        //        EditLayerMenuItem.EditLayerMenuItemListener,
        LayerMenuItem.LayerMenuItemListener, SwatchesFilter.SwatchesFilterListener {

    private final String TAG = "PaintActivity";
    private final String DEFAULT_IMAGE = "img_base_comex.png";

    // Eventos Flurry
    private static final String FLURRY_EV_COLOR = "Home - Decorador - ColorSeleccionado";
    private static final String FLURRY_EV_SHARE_FB = "Compartir - Facebook";
    private static final String FLURRY_EV_SHARE_TWITTER = "Compartir - Twitter";
    private static final String FLURRY_EV_SHARE_EMAIL = "Compartir - Email";

    //Result Codes
    private final int RS_CODE_SHARE_GMAIL = 1;
    private final int RS_CODE_SHARE_FB = 2;
    private final int RS_CODE_SHARE_TWITTER = 3;

    //Uri de la imagen temporal a compartir;
    private Uri uriTempImage;

    private SharedPreferences sharedPreferences;
    private static final String FIRSTOPENPALETA_PREF = "firstopenpaleta";
    //    private final String EMAIL_FEEDBACK_ADDRESS = "contact@cambriantech.com";
    //    private final String EMAIL_FEEDBACK_SUBJECT =
    // " Suggestion - Android";

    private boolean commitInterrupted;
    /**
     *  Para saber si proviene del flujo de agregar un nuevo layer a travs del botn Agregar Color
     *  para despues seleccionar el color.
     */
    private boolean isAddingNewLayer = false;
    //    private ViewGroup paint_tutorial;
    //    private Button paint_tutorial_button;
    private LinearLayout paint_fullscreen_content;
    private CBImagePainter painter;
    //    private PanelSlideAnimation drawerAnimation;
    //    private AlphaAnimation alphaUp;

    //    private MenuTabs paint_tabs;
    //    private MenuSidebar paint_drawer;

    private PaletaColores paletaColores;
    private LinearLayout paletaColoresContainer;
    private SwatchesFilter swatchesFilter;

    //    private Button paint_color_name_button;
    //    private View paint_color_view;
    //    private ImageButton paint_color_details_button;

    //    private ViewGroup _paint_rect_options_view;
    //    private ImageButton _paint_rect_options_commit_button;
    //    private ImageButton _paint_rect_options_decommit_button;

    //    private ViewGroup _paint_brush_size;
    //    private SeekBar _paint_brush_size_seekBar;
    //    private ImageView _paint_brush_image;
    //    private PaintCheckBox _paint_brush_auto_checkbox;
    //    private PaintCheckBox _paint_brush_smart_checkbox;

    //    private BottomButtons _bottomButtons;
    //    private MenuButtons _paint_menu_buttons;
    private TopBarPainting _topbarpainting;

    //    private ViewGroup layers_menu;
    private ViewGroup layers_menu_content;
    //    private Button layers_menu_add_button;
    //    private LayerMenuItem layers_menu_add_button;
    //    private Button layers_menu_edit_button;

    //    private ViewGroup layers_edit_menu;
    //    private ViewGroup layers_edit_menu_content;
    //    private Button layers_edit_menu_cancel_button;

    private static ProgressDialog progressDialog = null;

    //Your License Key:
    @Override
    public abstract String getCBLicenseKey();

    @Override
    public void onHistoryChanged() {
        _topbarpainting._topbarpainting_deshacer.setEnabled(painter.canStepBackward());
        //        _bottomButtons._paint_undo_button.setEnabled(painter.canStepBackward());
        //        toggleBrushSize(false);
        closeOptionsMenu();
    }

    //    private final int MIN_FILL_THRESHOLD = 2;

    @Override
    public void onStartedTool(int toolMode) {

        finishedCommitting();

        //        if (toolMode==CBImagePainter.PAINT_TOOL_RECTANGLE) {
        //            _paint_rect_options_view.setVisibility(View.VISIBLE);
        //        }
    }

    @Override
    public void onFinishedTool(int toolMode) {

        finishedCommitting();

        //        if (toolMode==CBImagePainter.PAINT_TOOL_RECTANGLE) {
        //            _paint_rect_options_view.setVisibility(View.INVISIBLE);
        //        }
    }

    @Override
    public void onImageTouched() {
        Log.d(TAG, "image touched!");

        if (progressDialog == null) {
            String message = getResources().getString(string.imagepainter_processing);
            //        progressDialog = ProgressDialog.show(this,"",message ,true);
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage(message);
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(true);

        }

        progressDialog.show();
    }

    @Override
    public void onImageProcessed() {
        Log.d("imageview", "actualizando imagen..");
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    @Override
    public boolean shouldStartTool(int toolMode) {
        return true;
    }

    private Timer _scheduledCommit;
    //    private void scheduleCommit(long delay) {
    //        commitInterrupted = false;
    //        if (_scheduledCommit != null) {
    //            _scheduledCommit.cancel();
    //        }
    //        _scheduledCommit = new Timer();
    //        _scheduledCommit.schedule(new TimerTask() {
    //            @Override
    //            public void run() {
    //                runOnUiThread(new Runnable() {
    //                    @Override
    //                    public void run() {
    //                        if (!commitInterrupted) {
    //                            commitChanges();
    //                        }
    //                    }
    //                });
    //            }
    //        }, delay);
    //    }

    private void commitChanges() {
        Handler handler = new Handler();

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    painter.commitChanges();
                    finishedCommitting();
                } catch (Exception e) {
                    Log.e("TAG", "Exception committing", e);
                    // TODO get this out to library clients
                }
            }
        }, 250);
    }

    private void decommitChanges() {
        painter.decommitChanges();
        finishedCommitting();
    }

    private void finishedCommitting() {
        commitInterrupted = false;
        if (_scheduledCommit != null) {
            _scheduledCommit.cancel();
            _scheduledCommit = null;
        }
        //        if (painter.getToolMode()==CBImagePainter.PAINT_TOOL_FILL) {
        //            _paint_rect_options_view.setVisibility(View.INVISIBLE);
        //        }
    }

    /**
     * Interface definition for a callback to be invoked when a view is clicked.
     */
    //    public interface PaintActivityListener {
    //        void onColorChanged();
    //    }

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

        Log.d(TAG, "onCreate");

        //        UserSettings.initialize(getBaseContext());
        CoreSQL.initialize(getBaseContext());

        setContentView(layout.activity_paint);

        this.painter = (CBImagePainter) findViewById(id.paint_image_view);
        this.painter.setToolMode(CBImagePainter.PAINT_TOOL_PAINT);
        this.painter.setCBImagePainterListener(this);

        paint_fullscreen_content = (LinearLayout) findViewById(id.paint_fullscreen_content);
        if (paint_fullscreen_content.isInEditMode()) {
            return;
        }

        //        paint_ads = (AdView) findViewById(R.id.paint_ads);
        //        if (PaintUtility.isLite(getBaseContext())) {
        //            AdRequest adRequest = new AdRequest();
        //            adRequest.addKeyword("home depot behr diy sherwin williams dunn edwards hardware lowes decorator design");
        //            paint_ads.loadAd(adRequest);
        //        } else {
        //            paint_ads.setVisibility(View.GONE);
        //        }

        //alpha effect
        //        alphaUp = new AlphaAnimation(0.3f, 1.0f);
        //        alphaUp.setDuration(200);
        //        alphaUp.setFillAfter(true);

        //        paint_tutorial = (ViewGroup) findViewById(R.id.paint_tutorial);
        //        paint_tutorial.setOnTouchListener(new View.OnTouchListener() {
        //            @Override
        //            public boolean onTouch(View v, MotionEvent event) {
        //                return true;
        //            }
        //        });
        //        if (UserSettings.getInstance().hasSeenTutorial()) {
        //            paint_tutorial.setVisibility(View.GONE);
        //        }
        //        paint_tutorial_button = (Button) findViewById(R.id.paint_tutorial_button);
        //        paint_tutorial_button.setOnClickListener(new View.OnClickListener() {
        //            @Override
        //            public void onClick(View view) {
        //                paint_tutorial.setVisibility(View.GONE);
        //                UserSettings.getInstance().setHasSeenTutorial(true);
        //            }
        //        });

        //        paint_color_name_button = (Button) findViewById(R.id.paint_color_name_button);
        //        paint_color_view = (View) findViewById(R.id.paint_color_view);
        //        paint_color_details_button = (ImageButton) findViewById(R.id.paint_color_details_button);

        //        paint_tabs  =  (MenuTabs) findViewById(R.id.paint_tabs);
        //        paint_tabs.setMenuTabsListener(this);

        //        paint_drawer  =  (MenuSidebar) findViewById(R.id.paint_drawer);
        //        //setup width
        //        int widthAvailable = PaintUtility.getScreenSize(getBaseContext()).x;
        //        float density = PaintUtility.getScreenDensity(getBaseContext());
        //        float deviceWidth = ((float) widthAvailable) / density;
        //
        //        if (PaintUtility.isLandscape(getBaseContext())) {
        //            int menuWidth =  (int) (300.0f * density);
        //            int rightMargin = widthAvailable - menuWidth;
        //            FrameLayout.LayoutParams pdLayoutParams = (FrameLayout.LayoutParams) paint_drawer.getLayoutParams();
        //            pdLayoutParams.setMargins(pdLayoutParams.leftMargin, pdLayoutParams.topMargin, rightMargin, pdLayoutParams.bottomMargin);
        //            paint_drawer.setVisibility(View.VISIBLE);
        //            paint_drawer.setLayoutParams(pdLayoutParams);
        //
        //            FrameLayout.LayoutParams fLayoutParams = (FrameLayout.LayoutParams) paint_fullscreen_content.getLayoutParams();
        //            fLayoutParams.setMargins(menuWidth, fLayoutParams.topMargin, 0, fLayoutParams.bottomMargin);
        //            paint_fullscreen_content.setLayoutParams(fLayoutParams);
        //        }
        //
        //        paint_drawer.setMenuSidebarListener(this);

        if (PaintSwatch.currentSwatch != null) {
            PaintSwatch.currentSwatch.setIsHighlighted(false);
        }

        //Setup drawer
        //        paint_fullscreen_content.setOnClickListener(new View.OnClickListener() {
        //            @Override
        //            public void onClick(View view) {
        //                if (drawerIsOpen()) {
        //                    toggleDrawer(false);
        //                }
        //            }
        //        });

        //        drawerAnimation = new PanelSlideAnimation(paint_fullscreen_content, PanelSlideAnimation.LEFT_MARGIN);
        //        drawerAnimation.setAnimationListener(new Animation.AnimationListener(){
        //            @Override
        //            public void onAnimationStart(Animation arg0) {
        //                paint_drawer.setVisibility(View.VISIBLE);
        //                if (drawerAnimation.endOffset != 0) {
        //                    paint_drawer.willOpen();
        //                } else {
        //                    paint_drawer.willClose();
        //                }
        //            }
        //            @Override
        //            public void onAnimationRepeat(Animation arg0) {
        //            }
        //            @Override
        //            public void onAnimationEnd(Animation arg0) {
        //                if (drawerAnimation.endOffset == 0) {
        //                    drawerClosed();
        //                } else {
        //                    drawerOpened();
        //                }
        //            }
        //        });

        /*** UI Elements Cambrian, barra bottom ***/

        //        _bottomButtons = (BottomButtons) findViewById(R.id.paint_bottom_buttons);
        //        _bottomButtons.setListener(this);

        _topbarpainting = (TopBarPainting) findViewById(id.toppaintingbar);
        _topbarpainting.setListener(this);

        swatchesFilter = (SwatchesFilter) findViewById(id.swatches_filter);
        swatchesFilter.setListener(this);
        //        _paint_menu_buttons = (MenuButtons) findViewById(R.id.paint_menu_buttons);
        //        _paint_menu_buttons.setListener(this);

        paletaColores = (PaletaColores) findViewById(id.paleta_colores);
        paletaColoresContainer = (LinearLayout) findViewById(id.swatches_container);

        paletaColoresContainer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                Log.d(TAG, "paletaColoresContainer touched");
                paletaColores.setVisibility(View.GONE);
                enableChildsOnTouch(paint_fullscreen_content, true);
                //En caso de estar en proceso de agregar un nuevo color, entonces se elimina el
                //layer previamente creado (el ltimo)
                Log.d(TAG, "current layer" + painter.editLayerIndex());
                Log.d(TAG, "num Layers " + painter.numLayers());

                if (isAddingNewLayer) {
                    painter.removeLayerAtIndex(painter.editLayerIndex());
                    Log.d(TAG, "edit Layer index : " + painter.editLayerIndex());
                    Log.d(TAG, "num Layers " + painter.numLayers());
                    isAddingNewLayer = false;
                    //Refrescamos
                    buildLayersMenu();
                }

                return true;
            }
        });

        //        _paint_rect_options_view = (ViewGroup) findViewById(R.id.paint_rect_options_view);
        //
        //        _paint_rect_options_commit_button = (ImageButton) findViewById(R.id.paint_rect_options_commit_button );
        //        _paint_rect_options_commit_button.setOnClickListener(new View.OnClickListener() {
        //            @Override
        //            public void onClick(View view) {
        //                _paint_rect_options_view.setVisibility(View.INVISIBLE);
        //                commitChanges();
        //            }
        //        });
        //
        //        _paint_rect_options_decommit_button = (ImageButton) findViewById(R.id.paint_rect_options_decommit_button);
        //        _paint_rect_options_decommit_button.setOnClickListener(new View.OnClickListener() {
        //            @Override
        //            public void onClick(View view) {
        //                _paint_rect_options_view.setVisibility(View.INVISIBLE);
        //                decommitChanges();
        //            }
        //        });

        //        _paint_brush_size  = (ViewGroup) findViewById(R.id.paint_brush_size);
        //        _paint_brush_size_seekBar  = (SeekBar) findViewById(R.id.paint_brush_size_seekBar);
        //        _paint_brush_size_seekBar.setMax(this.painter.getMaxBrushSize() - this.painter.getMinBrushSize());
        //        _paint_brush_size_seekBar.setOnSeekBarChangeListener(_brushSizeChanged);
        //        _paint_brush_image = (ImageView) findViewById(R.id.paint_brush_image);
        //        _paint_brush_auto_checkbox = (PaintCheckBox) findViewById(R.id.paint_brush_auto_checkbox);
        //        _paint_brush_auto_checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        //            @Override
        //            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        //                painter.setAutoBrushSizeEnabled(isChecked);
        //                updateBrushSizeOptions();
        //            }
        //        });

        //        _paint_brush_smart_checkbox = (PaintCheckBox) findViewById(R.id.paint_brush_smart_checkbox);
        //        _paint_brush_smart_checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        //            @Override
        //            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        //                painter.setSmartBrushEnabled(isChecked);
        //            }
        //        });

        //        layers_menu = (LinearLayout) findViewById(R.id.paint_layers_menu);
        layers_menu_content = (LinearLayout) findViewById(id.paint_layers_menu_content);
        //        layers_menu_add_button = (LayerMenuItem) findViewById(R.id.paint_layers_menu_add_button);
        //        layers_menu_add_button.setOnClickListener(new View.OnClickListener() {
        //            @Override
        //            public void onClick(View view) {
        //                closeAllOverlays(null);
        //                appendNewLayer();
        //            }
        //        });
        //        layers_menu_edit_button = (Button) findViewById(R.id.paint_layers_menu_edit_button);
        //        layers_menu_edit_button.setOnClickListener(new View.OnClickListener() {
        //            @Override
        //            public void onClick(View view) {
        //                closeAllOverlays(layers_edit_menu);
        //                showLayersEditMenu(true);
        //            }
        //        });

        //        layers_edit_menu = (LinearLayout) findViewById(R.id.paint_layers_edit_menu);
        //        layers_edit_menu_content = (LinearLayout) findViewById(R.id.paint_layers_edit_menu_content);
        //        layers_edit_menu_cancel_button = (Button) findViewById(R.id.paint_layers_edit_menu_cancel_button);
        //        layers_edit_menu_cancel_button.setOnClickListener(new View.OnClickListener() {
        //            @Override
        //            public void onClick(View view) {
        //                closeAllOverlays(null);
        //            }
        //        });

        //        updateBrushSizeOptions();
    }

    public void enableChildsOnTouch(ViewGroup viewGroup, boolean enabled) {
        int cnt = viewGroup.getChildCount();
        for (int i = 0; i < cnt; i++) {
            View v = viewGroup.getChildAt(i);
            if (v instanceof ViewGroup) {
                enableChildsOnTouch((ViewGroup) v, enabled);
            } else {
                v.setEnabled(enabled);

            }
        }
    }

    //    SeekBar.OnSeekBarChangeListener _brushSizeChanged = new SeekBar.OnSeekBarChangeListener() {
    //        @Override
    //        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
    //            painter.setBrushSize(seekBar.getProgress() + painter.getMinBrushSize());
    //            displayBrushSize();
    //        }
    //
    //        @Override
    //        public void onStartTrackingTouch(SeekBar seekBar) {}
    //
    //        @Override
    //        public void onStopTrackingTouch(SeekBar seekBar) {}
    //    };

    //    private void showLayersMenu(boolean show) {
    //        if (show) {
    //            closeAllOverlays(null);
    ////            buildLayersMenu();
    //        }
    //
    ////        layers_menu.setVisibility(show ? View.VISIBLE : View.INVISIBLE);
    //    }

    private void buildLayersMenu() {

        layers_menu_content.removeAllViews();
        int currentLayerIndex = painter.editLayerIndex();

        for (int i = painter.numLayers() - 1; i > 0; i--) {

            boolean isCurrentLayer = i == currentLayerIndex;

            int currentColor = painter.getPaintColorAtIndex(i);
            LayerMenuItem menuItem = new LayerMenuItem(getBaseContext());

            PaintColor paintColor = PaintColorDataSource.getPaintColor(painter, i);

            menuItem.setInfo(this, i, currentColor, getColorDescription(paintColor, currentColor));
            menuItem.setSelected(isCurrentLayer);

            layers_menu_content.addView(menuItem, layers_menu_content.getChildCount() - 1);
        }
        Drawable addBackground = getResources().getDrawable(drawable.button_calcular);
        if (painter.canAppendNewLayer()) {
            LayerMenuItem layers_menu_add_button = new LayerMenuItem(this);
            String addColorText = getResources().getString(addcolor_text);
            layers_menu_add_button.setInfo(this, -1, android.R.color.white, "", "Agregar Color", Color.BLUE,
                    color.transparent_button_disabled, (float) 1.5);

            layers_menu_content.addView(layers_menu_add_button);
        }

        //        layers_menu_edit_button.setVisibility(painter.numLayers() > 2 ? View.VISIBLE : View.GONE);
    }

    private String getColorDescription(PaintColor paintColor, int color) {
        if (paintColor != null)
            return paintColor.getName() + " " + paintColor.getCode();

        String hexColor = String.format("#%06X", (0xFFFFFF & color));
        return "RGB: " + hexColor;
    }

    public void LayerMenuItem_Selected(int index) {
        //Button Agregar
        if (index == -1) {
            closeAllOverlays(null);
            appendNewLayer();
        } else {
            invalidateSelectionLayerMenuItems(index);
            setLayerIndex(index);

            Log.d(TAG, "Seleccionado : " + index);
        }

    }

    @Override
    public void LayerMenuItem_LongPressed(int index) {
        //Button Agregar
        if (index == -1)
            return;

        /** S+olo se puede eliminar un color si hay ms de uno en la bandeja**/
        if (painter.numLayers() > 2) {
            AlertDialog.Builder builder = new AlertDialog.Builder(PaintActivity.this);
            final int _index = index;
            builder.setMessage("Eliminar color?").setCancelable(true)
                    .setPositiveButton("Si", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Log.d("LayerMenuItem", "Eliminando : " + _index);
                            deleteLayer(_index);
                        }
                    }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.cancel();
                        }
                    });

            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        }

    }

    @Override
    public void LayerManuItem_DoubleClicked(int index) {
        Log.d(TAG, "double click sobre " + index);
        //        //Button Agregar
        //        if(index == -1)
        //            return;

        openPaletaColores();
    }

    private void deleteLayer(int index) {
        painter.removeLayerAtIndex(index);
        buildLayersMenu();
    }

    /*
    Refresca el estado de seleccion de todos los elementos invalidando toda la seleccion  dandole el estado de focus slo
    slo al excepto
     */

    private void invalidateSelectionLayerMenuItems(int exception) {
        for (int i = 0; i < layers_menu_content.getChildCount(); i++) {
            LayerMenuItem menuItem = (LayerMenuItem) layers_menu_content.getChildAt(i);
            //AddButton y Boton Exception  siempre van a estar seleccionados (con boarder)
            if (menuItem.get_index() != -1)
                menuItem.setSelected(false);
        }
    }

    //    private void showLayersEditMenu(boolean show) {
    //        if (show) {
    //            closeAllOverlays(null);
    ////            buildLayersEditMenu();
    //        }
    //
    ////        layers_edit_menu.setVisibility(show ? View.VISIBLE : View.GONE);
    //    }

    private void setLayerIndex(int index) {
        painter.setEditLayerIndex(index);
    }

    //    private void buildLayersEditMenu() {
    //
    //        layers_edit_menu_content.removeAllViews();
    //        int currentLayerIndex = painter.editLayerIndex();
    //
    //        for (int ipainter.numLayers()-1; i>0; i--) {
    //
    //            boolean isCurrentLayer = i == currentLayerIndex;
    //
    //            PaintColor paintColor = PaintColorDataSource.getPaintColor(painter, i);
    //
    //            int currentColor = painter.getPaintColorAtIndex(i);
    //
    //            EditLayerMenuItem menuItem = new EditLayerMenuItem(getBaseContext());
    //            menuItem.setInfo(this, i, currentColor, getColorDescription(paintColor, currentColor));
    //
    //            layers_edit_menu_content.addView(menuItem);
    //        }
    //    }

    //    public void EditLayerMenuItem_Deleted(int index) {
    ////        showLayersEditMenu(false);
    //        painter.removeLayerAtIndex(index);
    //    }

    private void appendNewLayer() {
        if (!painter.canAppendNewLayer())
            return;

        isAddingNewLayer = true;
        painter.appendNewLayer();

        //        if (UserSettings.getInstance().hasSeenLayerDirections()) {
        //            Toast toast = Toast.makeText(this, "A new color layer has been created.", Toast.LENGTH_SHORT);
        //            toast.setGravity(Gravity.CENTER,0,0);
        //            toast.show();
        //        } else {
        //alert
        //            AlertDialog.Builder alert = new AlertDialog.Builder(this);
        //
        //            alert.setTitle("New Layer Created");
        //
        //            TextView myMsg = new TextView(this);
        //
        //            myMsg.setText("A new color layer has been created.\n" +
        //                    "Changes in color will not affect the existing paint below it.\n" +
        //                    "Feel free to select a new color and paint either new walls or existing areas.");
        //            myMsg.setPadding(10, 10, 10, 10);
        //            myMsg.setMinimumHeight(300);
        //
        //            myMsg.setGravity(Gravity.LEFT);
        //
        //            alert.setView(myMsg);
        //
        //            alert.setNeutralButton("OK", null);
        //            alert.show();
        //            UserSettings.getInstance().setHasSeenLayerDirections(true);
        //        }

        //        paint_tabs.openTab(paint_tabs.MENU_TAB_SWATCHES, true);

        //Abre la paleta de colores para que el usuario seleccione un color por default
        openPaletaColores();

    }

    //    private void displayBrushSize() {
    //        int size = painter.getBrushSize();
    //
    //        if (_paint_brush_image.getVisibility() == View.VISIBLE) {
    //            float imageWidth = _paint_brush_image.getMeasuredWidth();
    //            float normalizedSize = ((float) size) / (float) painter.getMaxBrushSize();
    //            int padding = (int) (imageWidth * (1.0f - normalizedSize)) / 2;
    //            _paint_brush_image.setPadding(padding, padding, padding, padding);
    //            _paint_brush_image.invalidate();
    //        }
    //    }
    //
    //    private void updateBrushSizeOptions() {
    //        boolean enabled = !painter.autoBrushSizeEnabled();
    //        _paint_brush_size_seekBar.setEnabled(enabled);
    //        _paint_brush_size_seekBar.setAlpha(enabled ? 1.0f : 0.3f);
    //        _paint_brush_image.setAlpha(enabled ? 1.0f : 0.3f);
    //    }
    //
    //    private void toggleBrushSize(boolean show) {
    //        if (show) {
    //            _paint_brush_size.setVisibility(View.VISIBLE);
    ////            paint_color_name_button.setVisibility(View.GONE);
    ////            paint_color_view.setVisibility(View.GONE);
    ////            paint_color_details_button.setVisibility(View.GONE);
    //            _paint_brush_size_seekBar.setProgress(painter.getBrushSize() - painter.getMinBrushSize());
    //            _paint_brush_size_seekBar.setEnabled(!painter.autoBrushSizeEnabled());
    //            _paint_brush_auto_checkbox.setChecked(painter.autoBrushSizeEnabled());
    //            _paint_brush_smart_checkbox.setChecked(painter.smartBrushEnabled());
    //
    //            displayBrushSize();
    //        } else {
    //            _paint_brush_size.setVisibility(View.GONE);
    //
    //            if (PaintUtility.getCurrentPaintColor() != null) {
    ////                paint_color_name_button.setVisibility(View.VISIBLE);
    ////                paint_color_details_button.setVisibility(View.VISIBLE);
    //            }
    ////            paint_color_view.setVisibility(View.VISIBLE);
    //        }
    //    }

    public void saveImage() {
        //save changes
        Bitmap image = painter.getImageBitmap();

        //        String description = null;
        //        PaintColor currentColor = PaintUtility.getCurrentPaintColor();

        //        if (null != currentColor) {
        //            ColorCategory category = currentColor.getColorCategory();
        //            description = category.getBrand().getName() + ", " + category.getName() + " - " + currentColor.getName();
        //        }
        String saveText = getResources().getString(save_image_text);
        final ProgressDialog dialog = PaintUtility.showProgressDialog(PaintActivity.this, saveText);
        dialog.show();

        //add branding
        //        Bitmap mutableBitmap = image.copy(Bitmap.Config.ARGB_8888, true);
        //        Canvas canvas = new Canvas(mutableBitmap);
        //        addBranding(canvas, description);

        //        PaintUtility.savePhoto(PaintActivity.this, mutableBitmap);
        PaintUtility.savePhoto(PaintActivity.this, image);
        PaintUtility.hideDialogAfterDelay(dialog, 1200);

    }

    //    private void addBranding(Canvas canvas, String description) {
    //        Paint paint = new Paint();
    //
    //        int rectStart = canvas.getHeight() - 30;
    //
    //        paint.setColor(0x99000000);
    //        paint.setStyle(Paint.Style.FILL);
    //        canvas.drawRect(0, rectStart, canvas.getWidth(), canvas.getHeight(), paint);
    //
    //        paint.setColor(Color.WHITE);
    //        paint.setTextSize(15);
    //
    //        float width = 0;
    //        if (description != null && description.length() > 0) {
    //            width = paint.measureText(description);
    //            canvas.drawText(description, 10, canvas.getHeight() - 10, paint);
    //        }
    //
    //        String promoText = PaintUtility.getProductName(getBaseContext()) +" for Android";
    //        float promoWidth = paint.measureText(promoText);
    //        if (promoWidth + width + 40 <= canvas.getWidth()) {
    //            canvas.drawText(promoText, canvas.getWidth() - promoWidth - 10, canvas.getHeight() - 10, paint);
    //        }
    //    }
    //
    //        int rectStart = canvas.getHeight() - 30;
    //
    //        paint.setColor(0x99000000);
    //        paint.setStyle(Paint.Style.FILL);
    //        canvas.drawRect(0, rectStart, canvas.getWidth(), canvas.getHeight(), paint);
    //
    //        paint.setColor(Color.WHITE);
    //        paint.setTextSize(15);
    //
    //        float width = 0;
    //        if (description != null && description.length() > 0) {
    //            width = paint.measureText(description);
    //            canvas.drawText(description, 10, canvas.getHeight() - 10, paint);
    //        }
    //
    //        String promoText = PaintUtility.getProductName(getBaseContext()) +" for Android";
    //        float promoWidth = paint.measureText(promoText);
    //        if (promoWidth + width + 40 <= canvas.getWidth()) {
    //            canvas.drawText(promoText, canvas.getWidth() - promoWidth - 10, canvas.getHeight() - 10, paint);
    //        }
    //    }

    @Override
    protected void onStart() {
        super.onStart();

        LocalBroadcastManager.getInstance(this.getBaseContext()).registerReceiver(_paintColorReceiver,
                new IntentFilter(PaintUtility.COLOR_CHANGED_NOTIFICATION));

        FlurryAgent.onStartSession(this, getResources().getString(R.string.flurry_app_id));

        Log.d(TAG, "onStart");

        if (paint_fullscreen_content.isInEditMode()) {
            return;
        }
    }

    //    String workingDirectory() {
    //        //return "/sdcard/ph";
    //        return getBaseContext().getFilesDir().getAbsolutePath() + "/current_project";
    //    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (outState != null) {
            Log.d("JOEL", "save state");
            PaintColor paintColor = PaintUtility.getCurrentPaintColor();
            //outState.putLong(PaintUtility.PAINT_COLOR_EXTRA_KEY, paintColor.getId());

            //            HashMap<String, String> test = new HashMap<String, String>();
            //            test.put("test", "testing 1");
            //            this.painter.setLayerUserData(test, 1);
            //this.painter.saveToDirectory(workingDirectory());
        }
    }

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

        //if already loaded, forget it
        //        if (PaintUtility.getCurrentPaintColor() != null) {
        //            return;
        //        }

        if (outState != null) {
            //this.painter.loadFromDirectory(workingDirectory());
            //            Map<String,String> data = this.painter.getLayerUserData(1);
            //            Log.d("JOEL", "Got back " + data.get("test"));

            if (PaintUtility.getCurrentPaintColor() == null) {
                Log.d("JOEL", "loading paint color from saved state");
                long paintColorId = outState.getLong(PaintUtility.PAINT_COLOR_EXTRA_KEY, 0);

                if (paintColorId > 0) {
                    PaintColorDataSource datasource = new PaintColorDataSource();
                    datasource.open();
                    PaintColor paintColor = datasource.getPaintColor(paintColorId);
                    datasource.close();

                    PaintUtility.setCurrentPaintColor(paintColor);
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (paint_fullscreen_content.isInEditMode()) {
            return;
        }

        PaintColor paintColor = PaintUtility.getCurrentPaintColor();

        if (paintColor == null) {
            getRandomColor();
        } else {
            this.setPaintColor(paintColor, paintColor.getColor(), true);
            //            paint_tabs.loadColorCategory(paintColor.getColorCategory());
            paletaColores.loadColorCategory(paintColor.getColorCategory());
        }

        boolean hasImage = this.painter.hasLoadedImage();

        if (!hasImage) {
            reloadImage();
        }

        //        toolModeChanged();
        //        this.paint_drawer.loadContent();

    }

    @Override
    protected void onStop() {
        super.onStop();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(_paintColorReceiver);
        FlurryAgent.onEndSession(this);
        Log.d(TAG, "onStop");

    }

    @Override
    protected void onPause() {
        super.onPause();
        //saveState();

    }

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

        Log.d(TAG, "onDestroy");
    }

    /**
     * Back button listener.
     * Will close the application if the back button pressed twice.
     */
    static int backButtonCount = 0;
    static Toast toast = null;

    @Override
    public void onBackPressed() {
        if (backButtonCount >= 1) {
            if (toast != null)
                toast.cancel();
            toast = null;
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            backButtonCount = 0;
        } else {
            toast = Toast.makeText(this, "Press the back button once again to close the application.",
                    Toast.LENGTH_LONG);
            toast.show();
            backButtonCount++;
        }
    }

    private BroadcastReceiver _paintColorReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (PaintUtility.isSender(intent, this))
                return;

            PaintColor paintColor = (PaintColor) intent.getSerializableExtra(PaintUtility.PAINT_COLOR_EXTRA_KEY);
            int color = intent.getIntExtra(PaintUtility.COLOR_EXTRA_KEY, 0);

            //Color Seleccionado
            Map<String, String> colorSetting = new HashMap<String, String>();
            colorSetting.put("colorName", paintColor.getName());
            FlurryAgent.logEvent(FLURRY_EV_COLOR, colorSetting);
            setPaintColor(paintColor, color, false);
        }
    };

    private boolean gotRandomColor;

    private void getRandomColor() {
        PaintColorDataSource datasource = new PaintColorDataSource();
        datasource.open();
        PaintColor paintColor = datasource.getRandomColor();
        datasource.close();

        setPaintColor(paintColor, paintColor.getColor(), true);
        //        paint_tabs.loadColorCategory(paintColor.getColorCategory());
        paletaColores.loadColorCategory(paintColor.getColorCategory());
        gotRandomColor = true;
    }

    public void setPaintColor(PaintColor paintColor, int color, boolean broadcast) {

        setPaintColor(paintColor);
        if (paintColor == null) {
            setColor(color);
        } else {
            if (PaintSwatch.currentSwatch != null
                    && PaintSwatch.currentSwatch.getColor() != paintColor.getColor()) {
                PaintSwatch.currentSwatch.setIsHighlighted(false);
            }
        }

        if (broadcast) {
            PaintUtility.broadcastPaintColor(paintColor, color, getBaseContext(), this);
        }

    }

    /*
    Este metodo solo actualiza el elemento nombre,paintswatch,->  y registra
    info en painter a travs de metadata
     */
    public void setPaintColor(PaintColor paintColor) {

        if (paintColor != null) {
            this.setColor(paintColor.getColor());
            //
            //            paint_color_name_button.setVisibility(View.VISIBLE);
            //            paint_color_details_button.setVisibility(View.VISIBLE);

            //            paint_color_name_button.setText(paintColor.getName());

            PaintColorDataSource.setPaintColorIDMetaData(painter, painter.editLayerIndex(), paintColor.getId());
            buildLayersMenu();
        } else {
            //once invisible, forever gone
            //            paint_color_name_button.setVisibility(View.INVISIBLE);
            //            paint_color_details_button.setVisibility(View.INVISIBLE);
        }

        //        paint_color_name_button.getParent().requestLayout();
    }

    //    private int getColor() {
    //        return this.painter.getPaintColor();
    //    }

    public void setColor(int color) {
        //        paint_color_view.setBackgroundColor(color);
        if (this.painter.getToolMode() == CBImagePainter.PAINT_TOOL_ERASER)
            setDefaultToolMode();
        this.painter.setPaintColor(color, true);
        closePaletaColores();
        Log.d(TAG, "Changed color to " + color);
    }

    //    private boolean drawerIsOpen()
    //    {
    //        return View.VISIBLE == paint_drawer.getVisibility();
    //    }

    //    private void toggleDrawer() {
    //        toggleDrawer(!drawerIsOpen());
    //    }

    //    private void toggleDrawer(boolean open) {
    //
    //        if (PaintUtility.isLandscape(getBaseContext())) {
    //            return;
    //        }
    //
    //        if (open == drawerIsOpen()) return;
    //
    //        int paint_drawer_width = paint_drawer.getMeasuredWidth();
    //
    //        float openOffset = paint_drawer_width;
    //
    //        if (open) {
    //            closeOptionsMenu();
    //        }
    //
    //        Log.d("JOEL", "drawer will " + (open ? "OPEN" : "CLOSE"));
    //
    //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    //            if (open) {
    //                drawerAnimation.prepareForAnimation(200, 0, openOffset);
    //            } else {
    //                drawerAnimation.prepareForAnimation(200, openOffset, 0);
    //            }
    //            paint_drawer.startAnimation(drawerAnimation);
    //        }
    //        else {
    //            if (open) {
    //                paint_drawer.setVisibility(View.VISIBLE);
    //                paint_drawer.bringToFront();
    //                drawerOpened();
    //            } else {
    //                paint_drawer.setVisibility(View.GONE);
    //                paint_fullscreen_content.bringToFront();
    //                drawerClosed();
    //            }
    //        }
    //
    //    }

    //    private void drawerOpened() {
    //        painter.setClickable(false);
    //        _bottomButtons.setClickable(false);
    //        paint_tabs.setClickable(false);
    //        paint_drawer.opened();
    //    }

    //    private void drawerClosed() {
    //        painter.setClickable(true);
    //        _bottomButtons.setClickable(true);
    //        paint_tabs.setClickable(true);
    //        paint_drawer.setVisibility(View.GONE);
    //        paint_drawer.closed();
    //    }

    private void reloadImage() {
        this.painter.loadAsset(DEFAULT_IMAGE, true);
        setDefaultToolMode();
        if (PaintUtility.getCurrentPaintColor() != null) {
            this.setPaintColor(PaintUtility.getCurrentPaintColor());
        }
    }

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

    public void colorButtonClicked(View button) {
        if (null == PaintUtility.getCurrentPaintColor())
            return;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            //            paint_color_name_button.startAnimation(alphaUp);
            //            paint_color_view.startAnimation(alphaUp);
            //            paint_color_details_button.startAnimation(alphaUp);
        }

        //        Intent intent = new Intent(this, ColorViewActivity.class);
        //        startActivity(intent);
    }

    //Camera and sharing
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
        case PaintUtility.CAMERA_PIC_REQUEST:
        case PaintUtility.LIBRARY_PIC_REQUEST:

            int orientation = ExifInterface.ORIENTATION_UNDEFINED;
            if (data != null) {
                orientation = data.getIntExtra(MediaStore.Images.ImageColumns.ORIENTATION,
                        ExifInterface.ORIENTATION_UNDEFINED);
            }
            Uri imageUri = PaintUtility.getPhotoUri(this, requestCode, resultCode, data);
            this.painter.closedCamera();

            if (imageUri != null) {
                this.painter.loadCompressedImage(imageUri, requestCode == PaintUtility.CAMERA_PIC_REQUEST,
                        orientation);
            }
            setDefaultToolMode();
            break;
        case RS_CODE_SHARE_FB:
            deleteTempImage();
            FlurryAgent.logEvent(FLURRY_EV_SHARE_FB);

            break;
        case RS_CODE_SHARE_GMAIL:
            deleteTempImage();
            FlurryAgent.logEvent(FLURRY_EV_SHARE_EMAIL);

            break;
        case RS_CODE_SHARE_TWITTER:
            deleteTempImage();
            //en caso de que si haya compartido
            if (resultCode == -1)
                FlurryAgent.logEvent(FLURRY_EV_SHARE_TWITTER);

            break;
        }

    }

    private void deleteTempImage() {
        if (uriTempImage != null) {
            //            File tempImage = new File(String.valueOf(uriTempImage));
        }
    }
    //    @Override
    //    public void onDrawerClicked() {

    ////        toggleDrawer();
    ////        closeAllOverlays(paint_tabs);
    //    }
    //
    //    @Override
    //    public void onTabOpened(int tab) {

    //        //toggleDrawer();
    ////        closeAllOverlays(paint_tabs);
    //    }
    //
    //    @Override
    //    public void onTabClosed(int tab) {

    //        //toggleDrawer();
    //    }

    @Override
    public void onColorChosen(PaintColor paintColor, int color) {
        setPaintColor(paintColor, color, false);
        closePaletaColores();
    }

    @Override
    public void onOutPaletaTouched() {

    }

    //    @Override
    //    public void onAction(int action)
    //    {
    //
    //    }

    //    @Override
    //    public void onLibraryChosen() {
    //        PaintUtility.launchLibraryIntent(this);
    //        toggleDrawer(false);
    //    }
    //
    //    @Override
    //    public void onCameraColorChosen() {
    //        Intent intent = new Intent(this, HarmonyActivity.class);
    //        intent.putExtra(HarmonyActivity.USE_LIBRARY_EXTRA, false);
    //        startActivity(intent);
    //        toggleDrawer(false);
    //    }
    //
    //    @Override
    //    public void onLibraryColorChosen() {
    //        Intent intent = new Intent(this, HarmonyActivity.class);
    //        intent.putExtra(HarmonyActivity.USE_LIBRARY_EXTRA, true);
    //        startActivity(intent);
    //        toggleDrawer(false);
    //    }
    //
    //    @Override
    //    public void onExampleChosen() {
    //        reloadImage();
    //        toggleDrawer(false);
    //    }
    //
    //    @Override
    //    public void onColorCategoryChosen(ColorCategory colorCategory) {
    ////        paint_tabs.loadColorCategory(colorCategory);
    ////        PaintUtility.broadcastColorCategory(colorCategory, getBaseContext(), this);
    ////        toggleDrawer(false);
    ////        paint_tabs.openTab(paint_tabs.MENU_TAB_SWATCHES, true);
    //
    //    }
    //
    //    @Override
    //    public void onPaintColorChosen(PaintColor color)
    //    {
    //        setPaintColor(color, color.getColor(), true);
    //        toggleDrawer(false);
    //    }
    //
    //    @Override
    //    public void onMoreChosen() {
    //        if (PaintUtility.isLite(getBaseContext())) {
    //            //get app
    //            final Context context = getApplicationContext();
    //
    //            Uri uri = Uri.parse((PaintUtility.isAmazon
    //                    ? "http://www.amazon.com/gp/mas/dl/android?p="
    //                    : "market://details?id=")
    //                    + PaintUtility.PRO_BUNDLE_ID);
    //
    //            Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri);
    //            startActivity(browserIntent);
    //        } else {
    //            //email
    //            final Intent emailIntent = new Intent(Intent.ACTION_SEND);
    //            emailIntent.setType("plain/text");
    //            emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ EMAIL_FEEDBACK_ADDRESS});
    //            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, PaintUtility.getProductName(getBaseContext()) + EMAIL_FEEDBACK_SUBJECT);
    //            startActivity(Intent.createChooser(emailIntent, "Send mail..."));
    //        }
    //    }

    /*** Implementacion del TopPaintingListener ***/
    @Override
    public void onDeshacerButtonClicked() {
        finishedCommitting();
        painter.stepBackward();
        _topbarpainting._topbarpainting_deshacer.setEnabled(painter.canStepBackward());
    }

    @Override
    public void onHerramientaButtonClicked() {

    }

    @Override
    public void onCompartirButtonClicked() {

        final Resources resources = getResources();

        PackageManager pm = getPackageManager();
        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setType("text/plain");

        final List<String> listStringPackages = new ArrayList<String>();

        List<ResolveInfo> apps = pm.queryIntentActivities(sendIntent, PackageManager.MATCH_DEFAULT_ONLY);
        Iterator i = apps.iterator();
        //Aca creamos nuestro filtro de apps especificas
        while (i.hasNext()) {
            ResolveInfo app = (ResolveInfo) i.next();
            String packageName = app.activityInfo.applicationInfo.packageName;
            if (packageName.contains("facebook") || packageName.contains("twitter") || packageName.contains("gm")) {
                listStringPackages.add(packageName);
            }

        }

        ArrayAdapter<String> adapter = new ShareChooserAdapter(this, android.R.layout.select_dialog_item,
                android.R.id.text1, listStringPackages);

        new AlertDialog.Builder(this).setTitle(string.sharechooser_title)
                .setAdapter(adapter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        invokeApplication(listStringPackages.get(i), resources);
                    }
                }).setCancelable(true).setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        Log.d("DialogShare", "canceled, se borra la imagen...");
                    }
                }).show();

    }

    private void invokeApplication(String packageName, Resources resources) {

        int requestCode = 0;
        Log.d("DialogShare", "Seleccionado ... " + packageName);
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.setType("image/*");

        shareIntent.setPackage(packageName);

        //Image
        Bitmap bitmap = painter.getImageBitmap();

        if ((uriTempImage = PaintUtility.saveTempPhoto(this, bitmap)) == null)
            Toast.makeText(this, "Error al crear imagonen ", Toast.LENGTH_SHORT).show();

        shareIntent.putExtra(Intent.EXTRA_STREAM, uriTempImage);

        if (packageName.contains("twitter")) {
            shareIntent.putExtra(Intent.EXTRA_TEXT, resources.getString(string.sharecontent_twitter_text));
            requestCode = RS_CODE_SHARE_TWITTER;

        } else if (packageName.contains("facebook")) {
            // Warning: Facebook IGNORES our text. They say "These fields are intended for users to express themselves. Pre-filling these fields erodes the authenticity of the user voice."
            // One workaround is to use the Facebook SDK to post, but that doesn't allow the user to choose how they want to share. We can also make a custom landing page, and the link
            // will show the <meta content ="..."> text from that page with our link in Facebook.
            shareIntent.putExtra(Intent.EXTRA_TEXT, resources.getString(string.sharecontent_fb_text));
            requestCode = RS_CODE_SHARE_FB;
        } else if (packageName.contains("gm")) {

            shareIntent.putExtra(Intent.EXTRA_TEXT, resources.getString(string.sharecontent_email_text));
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, resources.getString(string.sharecontent_subject));
            shareIntent.setType("message/rfc822");
            requestCode = RS_CODE_SHARE_GMAIL;
        }

        startActivityForResult(shareIntent, requestCode);
    }

    /*** Implementacin de las Herramientas ***/
    @Override
    public void onBucketSelected() {
        setToolMode(painter.PAINT_TOOL_FILL);
    }

    @Override
    public void onRectangleSelected() {
        setToolMode(painter.PAINT_TOOL_RECTANGLE);
    }

    @Override
    public void onSmartBrushSelected() {
        setToolMode(painter.PAINT_TOOL_PAINT);
    }

    @Override
    public void onEraserSelected() {
        setToolMode(painter.PAINT_TOOL_ERASER);
    }

    public void cameraClicked() {

        String[] pictureOptions = getResources().getStringArray(array.picture_choose);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item,
                android.R.id.text1, pictureOptions);

        new AlertDialog.Builder(this).setTitle(string.picturechooser_title)
                .setAdapter(adapter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch (i) {
                        case 0: //Camara
                            //Toma la foto
                            PaintUtility.launchCameraIntent(PaintActivity.this);
                            painter.openedCamera();
                            break;
                        case 1: //Gallera
                            PaintUtility.launchLibraryIntent(PaintActivity.this);
                            break;
                        }
                    }
                }).setCancelable(true).show();

    }

    /*** Implementacion de los botones bajos ***/

    //    public void onCameraButtonClicked()
    //    {
    //        //take photo
    ////        toggleBrushSize(false);
    //        PaintUtility.launchCameraIntent(PaintActivity.this);
    //        painter.openedCamera();
    //    }

    //    public void onUndoButtonClicked()
    //    {
    ////        toggleBrushSize(false);
    //        finishedCommitting();
    //        painter.stepBackward();
    ////        _bottomButtons._paint_undo_button.setEnabled(painter.canStepBackward());
    //        _topbarpainting._topbarpainting_deshacer.setEnabled(painter.canStepBackward());
    //    }

    //    public void onToolButtonClicked()
    //    {
    //        toggleBrushSize(false);
    //        if (_paint_menu_buttons.getVisibility() == View.VISIBLE) {
    //            closeOptionsMenu();
    //        } else {
    //            openOptionsMenu();
    //        }
    //    }

    //    public void onBrushSizeButtonClicked()
    //    {
    //        toggleBrushSize(_paint_brush_size.getVisibility() != View.VISIBLE);
    //    }

    //    public void onLayersButtonClicked()
    //    {
    ////        showLayersMenu(layers_menu.getVisibility() != View.VISIBLE);
    //    }

    //    public void onSaveButtonClicked()
    //    {
    //        saveImage();
    //    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //        onToolButtonClicked();
        return false;
    }

    private void closeAllOverlays(Object except) {
        //        if (except != layers_menu) showLayersMenu(false);
        //        if (except != layers_edit_menu) showLayersEditMenu(false);
        //        if (except != _paint_brush_size) toggleBrushSize(false);
        //        if (except != _paint_menu_buttons) closeOptionsMenu();
        //if (except != paint_tabs) paint_tabs.hid
    }

    //    @Override
    //    public void openOptionsMenu()
    //    {
    //        _paint_menu_buttons.bringToFront();
    //        _paint_menu_buttons.setVisibility(View.VISIBLE);
    //    }

    //    @Override
    //    public void closeOptionsMenu()
    //    {
    //        _paint_menu_buttons.setVisibility(View.INVISIBLE);
    //    }

    public void openPaletaColores() {
        sharedPreferences = getPreferences(0);

        boolean alreadyPaletaLaunched = sharedPreferences.getBoolean(FIRSTOPENPALETA_PREF, false);

        if (!alreadyPaletaLaunched) {

            showPopup();
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean(FIRSTOPENPALETA_PREF, true);
            editor.commit();
        }
        paletaColores.bringToFront();
        paletaColores.setVisibility(View.VISIBLE);
        enableChildsOnTouch(paint_fullscreen_content, false);
    }

    private void showPopup() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        AlertDialog avisoDialog = builder.setCancelable(false).setMessage(aviso_paleta)
                .setPositiveButton(aviso_paleta_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).create();

        avisoDialog.show();
    }

    public void closePaletaColores() {
        paletaColores.setVisibility(View.GONE);
        enableChildsOnTouch(paint_fullscreen_content, true);
        //Se ha cumplido el flujo de seleccion de color voluntario
        isAddingNewLayer = false;

    }

    public boolean isPaletaColoresOpened() {
        return (paletaColores.getVisibility() == View.VISIBLE);
    }

    private void setDefaultToolMode() {
        setToolMode(CBImagePainter.PAINT_TOOL_PAINT);
    }

    private void setToolMode(int toolMode) {
        painter.setToolMode(toolMode);
        //        toolModeChanged();
        closeOptionsMenu();
    }

    @Override
    public void onCategorySelected(ColorCategory category) {
        Log.d(TAG, "Categoria seleccionada : " + category.getId() + " " + category.getName());
        paletaColores.loadColorCategory(category);
    }

    //    public void onBucketButtonClicked()
    //    {
    //        setToolMode(CBImagePainter.PAINT_TOOL_FILL);
    //    }
    //
    //    public void onRectangleButtonClicked()
    //    {
    //        setToolMode(CBImagePainter.PAINT_TOOL_RECTANGLE);
    //    }
    //
    //    public void onPaintbrushButtonClicked()
    //    {
    //        setToolMode(CBImagePainter.PAINT_TOOL_PAINT);
    //    }
    //
    //    public void onEraserButtonClicked()
    //    {
    //        setToolMode(CBImagePainter.PAINT_TOOL_ERASER);
    //    }

    //    private void toolModeChanged() {
    ////        _bottomButtons._paint_brush_size_button.setEnabled(false);
    //        switch (painter.getToolMode()) {
    //            case (CBImagePainter.PAINT_TOOL_FILL):
    //                PaintUtility.setViewBackground(_bottomButtons._paint_tool_button, getResources().getDrawable(R.drawable.bucket_button));
    //                break;
    //            case (CBImagePainter.PAINT_TOOL_RECTANGLE):
    //                PaintUtility.setViewBackground(_bottomButtons._paint_tool_button, getResources().getDrawable(R.drawable.rect_button));
    //                break;
    //            case (CBImagePainter.PAINT_TOOL_PAINT):
    //                _bottomButtons._paint_brush_size_button.setEnabled(true);
    //                if (this.painter.autoBrushSizeEnabled()) {
    //                    _bottomButtons._paint_brush_size_button.setText("auto");
    //                } else {
    //                    _bottomButtons._paint_brush_size_button.setText("" + this.painter.getBrushSize());
    //                }
    //                PaintUtility.setViewBackground(_bottomButtons._paint_tool_button, getResources().getDrawable(R.drawable.paint_button));
    //                break;
    //            case (CBImagePainter.PAINT_TOOL_ERASER):
    //                PaintUtility.setViewBackground(_bottomButtons._paint_tool_button, getResources().getDrawable(R.drawable.eraser_button));
    //                break;
    //        }
    //    }

}