aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/ImageSelectActivity.java
blob: 0f68c65d3fd4c9df60c718c76808186d7d268a95 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package cgeo.geocaching;

import butterknife.ButterKnife;
import butterknife.Bind;

import cgeo.geocaching.activity.AbstractActionBarActivity;
import cgeo.geocaching.files.LocalStorage;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.ImageUtils;
import cgeo.geocaching.utils.Log;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.Nullable;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class ImageSelectActivity extends AbstractActionBarActivity {

    @Bind(R.id.caption) protected EditText captionView;
    @Bind(R.id.description) protected EditText descriptionView;
    @Bind(R.id.logImageScale) protected Spinner scaleView;
    @Bind(R.id.camera) protected Button cameraButton;
    @Bind(R.id.stored) protected Button storedButton;
    @Bind(R.id.save) protected Button saveButton;
    @Bind(R.id.cancel) protected Button clearButton;
    @Bind(R.id.image_preview) protected ImageView imagePreview;

    private static final String SAVED_STATE_IMAGE = "cgeo.geocaching.saved_state_image";
    private static final String SAVED_STATE_IMAGE_SCALE = "cgeo.geocaching.saved_state_image_scale";

    private static final int SELECT_NEW_IMAGE = 1;
    private static final int SELECT_STORED_IMAGE = 2;

    // Data to be saved while reconfiguring
    private Image image;
    private int scaleChoiceIndex;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        onCreate(savedInstanceState, R.layout.imageselect_activity);
        ButterKnife.bind(this);

        scaleChoiceIndex = Settings.getLogImageScale();

        // Get parameters from intent and basic cache information from database
        final Bundle extras = getIntent().getExtras();
        if (extras != null) {
            image = extras.getParcelable(Intents.EXTRA_IMAGE);
            scaleChoiceIndex = extras.getInt(Intents.EXTRA_SCALE, scaleChoiceIndex);
        }

        // Restore previous state
        if (savedInstanceState != null) {
            image = savedInstanceState.getParcelable(SAVED_STATE_IMAGE);
            scaleChoiceIndex = savedInstanceState.getInt(SAVED_STATE_IMAGE_SCALE);
        }

        if (image == null) {
            image = Image.NONE;
        }

        cameraButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(final View view) {
                selectImageFromCamera();
            }
        });

        storedButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(final View view) {
                selectImageFromStorage();
            }
        });

        if (image.hasTitle()) {
            captionView.setText(image.getTitle());
            Dialogs.moveCursorToEnd(captionView);
        }

        if (image.hasDescription()) {
            descriptionView.setText(image.getDescription());
            Dialogs.moveCursorToEnd(captionView);
        }

        scaleView.setSelection(scaleChoiceIndex);
        scaleView.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(final AdapterView<?> arg0, final View arg1, final int arg2, final long arg3) {
                scaleChoiceIndex = scaleView.getSelectedItemPosition();
                Settings.setLogImageScale(scaleChoiceIndex);
            }

            @Override
            public void onNothingSelected(final AdapterView<?> arg0) {
            }
        });

        saveButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(final View v) {
                saveImageInfo(true);
            }
        });

        clearButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(final View v) {
                saveImageInfo(false);
            }
        });

        loadImagePreview();
    }

    @Override
    protected void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        syncEditTexts();
        outState.putParcelable(SAVED_STATE_IMAGE, image);
        outState.putInt(SAVED_STATE_IMAGE_SCALE, scaleChoiceIndex);
    }

    public void saveImageInfo(final boolean saveInfo) {
        if (saveInfo) {
            new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(final Void... params) {
                    return writeScaledImage(image.getPath());
                }

                @Override
                protected void onPostExecute(final String filename) {
                    if (filename != null) {
                        image = new Image.Builder(filename).build();
                        final Intent intent = new Intent();
                        syncEditTexts();
                        intent.putExtra(Intents.EXTRA_IMAGE, image);
                        intent.putExtra(Intents.EXTRA_SCALE, scaleChoiceIndex);
                        setResult(RESULT_OK, intent);
                    } else {
                        showToast(res.getString(R.string.err_select_logimage_failed));
                        setResult(RESULT_CANCELED);
                    }
                    finish();
                }
            }.execute();
        } else {
            setResult(RESULT_CANCELED);
            finish();
        }
    }

    private void syncEditTexts() {
        final Image.Builder imageBuilder = new Image.Builder(image);
        imageBuilder.setTitle(captionView.getText().toString());
        imageBuilder.setDescription(descriptionView.getText().toString());
        image = imageBuilder.build();
        scaleChoiceIndex = scaleView.getSelectedItemPosition();
    }

    private void selectImageFromCamera() {
        // create Intent to take a picture and return control to the calling application
        final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        image = new Image.Builder(ImageUtils.getOutputImageFileUri()).build();

        if (image.isEmpty()) {
            showFailure();
            return;
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, image.getUri()); // set the image file name

        // start the image capture Intent
        startActivityForResult(intent, SELECT_NEW_IMAGE);
    }

    private void selectImageFromStorage() {
        final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/jpeg");

        startActivityForResult(Intent.createChooser(intent, "Select Image"), SELECT_STORED_IMAGE);
    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
            showToast(getResources().getString(R.string.info_select_logimage_cancelled));
            return;
        }

        if (resultCode != RESULT_OK) {
            // Image capture failed, advise user
            showFailure();
            return;
        }

        // null is an acceptable result if the image has been placed in the imageUri file by the
        // camera application.
        if (data != null) {
            final Uri selectedImage = data.getData();
            if (Build.VERSION.SDK_INT < VERSION_CODES.KITKAT) {
                final String[] filePathColumn = { MediaColumns.DATA };

                Cursor cursor = null;
                try {
                    cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    if (cursor == null) {
                        showFailure();
                        return;
                    }
                    cursor.moveToFirst();

                    final int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    final String filePath = cursor.getString(columnIndex);
                    if (StringUtils.isBlank(filePath)) {
                        showFailure();
                        return;
                    }
                    image = new Image.Builder(filePath).build();
                } catch (final Exception e) {
                    Log.e("ImageSelectActivity.onActivityResult", e);
                    showFailure();
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }

                Log.d("SELECT IMAGE data = " + data.toString());
            } else {
                InputStream input = null;
                OutputStream output = null;
                try {
                    input = getContentResolver().openInputStream(selectedImage);
                    final File outputFile = ImageUtils.getOutputImageFile();
                    output = new FileOutputStream(outputFile);
                    LocalStorage.copy(input, output);
                    image = new Image.Builder(outputFile).build();
                } catch (final FileNotFoundException e) {
                    Log.e("ImageSelectActivity.onStartResult", e);
                } finally {
                    IOUtils.closeQuietly(input);
                    IOUtils.closeQuietly(output);
                }
            }
        }

        if (requestCode == SELECT_NEW_IMAGE) {
            showToast(getResources().getString(R.string.info_stored_image) + '\n' + image.getUrl());
        }

        loadImagePreview();
    }

    /**
     * Scales and writes the scaled image.
     *
     * @return the scaled image path, or <tt>null</tt> if the image cannot be decoded
     */
    @Nullable
    private String writeScaledImage(@Nullable final String filePath) {
        if (filePath == null) {
            return null;
        }
        scaleChoiceIndex = scaleView.getSelectedItemPosition();
        final int maxXY = getResources().getIntArray(R.array.log_image_scale_values)[scaleChoiceIndex];
        return ImageUtils.readScaleAndWriteImage(filePath, maxXY);
    }

    private void showFailure() {
        showToast(getResources().getString(R.string.err_acquire_image_failed));
    }

    private void loadImagePreview() {
        if (image.isEmpty()) {
            return;
        }
        if (!image.existsLocal()) {
            Log.i("Image does not exist");
            return;
        }

        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(final Void... params) {
                return ImageUtils.readAndScaleImageToFitDisplay(image.getPath());
            }

            @Override
            protected void onPostExecute(final Bitmap bitmap) {
                imagePreview.setImageBitmap(bitmap);
                imagePreview.setVisibility(View.VISIBLE);
            }
        }.execute();
    }
}