diff --git a/README.md b/README.md index 9bbf20bb..95fe8842 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,18 @@ cordova-imagePicker =================== -Cordova Plugin For Multiple Image Selection - implemented for iOS and Android 4.0 and above. +Forked from: [wymsee/cordova-imagePicker](https://github.com/wymsee/cordova-imagePicker) + +Cordova Plugin For Multiple Image Selection - implemented for iOS and Android 3.0 and above. ## Installing the plugin The plugin conforms to the Cordova plugin specification, it can be installed using the Cordova / Phonegap command line interface. - phonegap plugin add cordova-plugin-image-picker + phonegap plugin add https://github.com/antonyalkmim/cordova-imagePicker - cordova plugin add cordova-plugin-image-picker + cordova plugin add https://github.com/antonyalkmim/cordova-imagePicker ## Using the plugin @@ -58,11 +60,12 @@ window.imagePicker.getPictures( // will be at most 800 pixels wide and 800 pixels tall. If the width is // 800 and height 0 the image will be 800 pixels wide if the source // is at least that wide. - width: int, + // only iOS => check Android issues below + width: int, height: int, // quality of resized image, defaults to 100 - quality: int (0-100) + quality: int (0-100) //only iOS => check Android issues below }; ### iOS 10 issues @@ -76,10 +79,13 @@ Example: `cordova plugin add cordova-plugin-image-picker --variable PHOTO_LIBRARY_USAGE_DESCRIPTION="your message"` Empty string will be added as value if you dont pass the variable - -### Note for Android Use -The plugin returns images that are stored in a temporary directory. These images will often not be deleted automatically though. The files should be moved or deleted after you get their filepaths in javascript. +### Android issues + +There is a few things that must be implemented: + [ ] Matisse Filter to resize images witdh and height. + [ ] Matisse Filter to decrease images quality. + ## Libraries used @@ -89,17 +95,10 @@ For iOS this plugin uses the ELCImagePickerController, with slight modifications https://github.com/B-Sides/ELCImagePickerController -#### MultiImageChooser - -For Android this plugin uses MultiImageChooser, with modifications. MultiImageChooser uses the BSD 2-Clause License which can be found in the file BSD_LICENSE. Some code inside MultImageChooser is licensed under the Apache license which can be found in the file APACHE_LICENSE. - -https://github.com/derosa/MultiImageChooser - -#### FakeR - -Code(FakeR) was also taken from the phonegap BarCodeScanner plugin. This code uses the MIT license. +#### Matisse -https://github.com/wildabeast/BarcodeScanner +For Android this plugin uses Matisse. Matisse uses the Apache License which can be found in the file APACHE_LICENSE. +https://github.com/zhihu/Matisse ## License diff --git a/package.json b/package.json index ad3330e3..29df31a5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cordova-plugin-image-picker", - "version": "1.1.3", + "version": "1.1.4", "description": "This plugin allows selection of multiple images from the camera roll / gallery in a phonegap app", "cordova": { "id": "cordova-plugin-image-picker", @@ -21,7 +21,7 @@ "engines": [ { "name": "cordova", - "version": ">=3.0.0" + "version": ">=6.2.3" } ], "author": "Wymsee", diff --git a/plugin.xml b/plugin.xml index 55c3d0c6..9f7a16fb 100644 --- a/plugin.xml +++ b/plugin.xml @@ -2,19 +2,20 @@ + version="1.1.5"> ImagePicker - + This plugin allows selection of multiple images from the camera roll / gallery in a phonegap app - + MIT - + + @@ -62,53 +63,34 @@ - + + - + - + - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + diff --git a/src/android/Library/res/anim/image_pop_in.xml b/src/android/Library/res/anim/image_pop_in.xml deleted file mode 100644 index 3b1f7e9d..00000000 --- a/src/android/Library/res/anim/image_pop_in.xml +++ /dev/null @@ -1,11 +0,0 @@ - - diff --git a/src/android/Library/res/drawable-hdpi/icon.png b/src/android/Library/res/drawable-hdpi/icon.png deleted file mode 100644 index 8074c4c5..00000000 Binary files a/src/android/Library/res/drawable-hdpi/icon.png and /dev/null differ diff --git a/src/android/Library/res/drawable-hdpi/image_bg.9.png b/src/android/Library/res/drawable-hdpi/image_bg.9.png deleted file mode 100644 index 9835be61..00000000 Binary files a/src/android/Library/res/drawable-hdpi/image_bg.9.png and /dev/null differ diff --git a/src/android/Library/res/drawable-hdpi/loading_icon.png b/src/android/Library/res/drawable-hdpi/loading_icon.png deleted file mode 100644 index 3490f83d..00000000 Binary files a/src/android/Library/res/drawable-hdpi/loading_icon.png and /dev/null differ diff --git a/src/android/Library/res/drawable-ldpi/icon.png b/src/android/Library/res/drawable-ldpi/icon.png deleted file mode 100644 index 1095584e..00000000 Binary files a/src/android/Library/res/drawable-ldpi/icon.png and /dev/null differ diff --git a/src/android/Library/res/drawable-mdpi/ic_action_discard_dark.png b/src/android/Library/res/drawable-mdpi/ic_action_discard_dark.png deleted file mode 100644 index b65f4c66..00000000 Binary files a/src/android/Library/res/drawable-mdpi/ic_action_discard_dark.png and /dev/null differ diff --git a/src/android/Library/res/drawable-mdpi/ic_action_discard_light.png b/src/android/Library/res/drawable-mdpi/ic_action_discard_light.png deleted file mode 100644 index d74c9d5f..00000000 Binary files a/src/android/Library/res/drawable-mdpi/ic_action_discard_light.png and /dev/null differ diff --git a/src/android/Library/res/drawable-mdpi/ic_action_done_dark.png b/src/android/Library/res/drawable-mdpi/ic_action_done_dark.png deleted file mode 100644 index b8fb4f84..00000000 Binary files a/src/android/Library/res/drawable-mdpi/ic_action_done_dark.png and /dev/null differ diff --git a/src/android/Library/res/drawable-mdpi/ic_action_done_light.png b/src/android/Library/res/drawable-mdpi/ic_action_done_light.png deleted file mode 100644 index e5d82fdf..00000000 Binary files a/src/android/Library/res/drawable-mdpi/ic_action_done_light.png and /dev/null differ diff --git a/src/android/Library/res/drawable-mdpi/ic_launcher.png b/src/android/Library/res/drawable-mdpi/ic_launcher.png deleted file mode 100644 index 9dc7f218..00000000 Binary files a/src/android/Library/res/drawable-mdpi/ic_launcher.png and /dev/null differ diff --git a/src/android/Library/res/drawable-mdpi/icon.png b/src/android/Library/res/drawable-mdpi/icon.png deleted file mode 100644 index a07c69fa..00000000 Binary files a/src/android/Library/res/drawable-mdpi/icon.png and /dev/null differ diff --git a/src/android/Library/res/drawable-xhdpi/ic_action_discard_dark.png b/src/android/Library/res/drawable-xhdpi/ic_action_discard_dark.png deleted file mode 100644 index 4bfac666..00000000 Binary files a/src/android/Library/res/drawable-xhdpi/ic_action_discard_dark.png and /dev/null differ diff --git a/src/android/Library/res/drawable-xhdpi/ic_action_discard_light.png b/src/android/Library/res/drawable-xhdpi/ic_action_discard_light.png deleted file mode 100644 index 24256f15..00000000 Binary files a/src/android/Library/res/drawable-xhdpi/ic_action_discard_light.png and /dev/null differ diff --git a/src/android/Library/res/drawable-xhdpi/ic_action_done_dark.png b/src/android/Library/res/drawable-xhdpi/ic_action_done_dark.png deleted file mode 100644 index f70a494f..00000000 Binary files a/src/android/Library/res/drawable-xhdpi/ic_action_done_dark.png and /dev/null differ diff --git a/src/android/Library/res/drawable-xhdpi/ic_action_done_light.png b/src/android/Library/res/drawable-xhdpi/ic_action_done_light.png deleted file mode 100644 index 71094a09..00000000 Binary files a/src/android/Library/res/drawable-xhdpi/ic_action_done_light.png and /dev/null differ diff --git a/src/android/Library/res/drawable-xhdpi/ic_launcher.png b/src/android/Library/res/drawable-xhdpi/ic_launcher.png deleted file mode 100644 index 75578f40..00000000 Binary files a/src/android/Library/res/drawable-xhdpi/ic_launcher.png and /dev/null differ diff --git a/src/android/Library/res/drawable/grid_background.xml b/src/android/Library/res/drawable/grid_background.xml deleted file mode 100644 index d57bb389..00000000 --- a/src/android/Library/res/drawable/grid_background.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - \ No newline at end of file diff --git a/src/android/Library/res/layout/actionbar_custom_view_done_discard.xml b/src/android/Library/res/layout/actionbar_custom_view_done_discard.xml deleted file mode 100644 index 0b61fb97..00000000 --- a/src/android/Library/res/layout/actionbar_custom_view_done_discard.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - diff --git a/src/android/Library/res/layout/actionbar_discard_button.xml b/src/android/Library/res/layout/actionbar_discard_button.xml deleted file mode 100644 index bbe6321e..00000000 --- a/src/android/Library/res/layout/actionbar_discard_button.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - diff --git a/src/android/Library/res/layout/actionbar_done_button.xml b/src/android/Library/res/layout/actionbar_done_button.xml deleted file mode 100644 index 907b9a13..00000000 --- a/src/android/Library/res/layout/actionbar_done_button.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - diff --git a/src/android/Library/res/layout/multiselectorgrid.xml b/src/android/Library/res/layout/multiselectorgrid.xml deleted file mode 100644 index 01f8e2d6..00000000 --- a/src/android/Library/res/layout/multiselectorgrid.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/android/Library/res/values-de/multiimagechooser_strings_de.xml b/src/android/Library/res/values-de/multiimagechooser_strings_de.xml deleted file mode 100644 index 0c808d29..00000000 --- a/src/android/Library/res/values-de/multiimagechooser_strings_de.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - MultiImageChooser - Kostenlose Version - Sie können noch %d Bilder wählen - Beim Öffnen der Bilder-Datenbank kam es zu einem Fehler. - Lade Vorschaubilder, bitte warten - Verarbeite Bildauswahl - Dies kann einen kurzen Augenblick dauern. - Auswahllimit erreicht - Sie können maximal %d Bilder auf einmal auswählen. - Abbrechen - OK - diff --git a/src/android/Library/res/values-es/multiimagechooser_strings_es.xml b/src/android/Library/res/values-es/multiimagechooser_strings_es.xml deleted file mode 100644 index 0a2b6e3f..00000000 --- a/src/android/Library/res/values-es/multiimagechooser_strings_es.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - MultiImageChooser - Solicitando miniaturas. Por favor, espere… - Versión gratuita - Imágenes restantes: %d - Error al abrir la base de datos de imágenes. - Processing Images - This may take a few moments - Limit reached - You can only select %d photos at once. - Cancelar - OK - diff --git a/src/android/Library/res/values-fr/multiimagechooser_strings_fr.xml b/src/android/Library/res/values-fr/multiimagechooser_strings_fr.xml deleted file mode 100644 index 86029948..00000000 --- a/src/android/Library/res/values-fr/multiimagechooser_strings_fr.xml +++ /dev/null @@ -1,12 +0,0 @@ - - MultiImageChooser - Version gratuite - Images restantes:%d" - "Il y eu une erreur avec les images. Veuillez nous signaler le problème." - Récupération des vignettes, soyez patient - Processing Images - This may take a few moments - Limit reached - You can only select %d photos at once. - Annuler - OK - diff --git a/src/android/Library/res/values-hu/multiimagechooser_strings_hu.xml b/src/android/Library/res/values-hu/multiimagechooser_strings_hu.xml deleted file mode 100644 index 0fefc17d..00000000 --- a/src/android/Library/res/values-hu/multiimagechooser_strings_hu.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - MultiImageChooser - Ingyenes verzió - hátralévő képek: %d - Képadatbázis megnyitási hiba történt. Kérjük, jelentse a problémát. - Miniatűrök lekérése, kérjük legyen türelemmel - Processing Images - This may take a few moments - Limit reached - You can only select %d photos at once. - Cancel - OK - diff --git a/src/android/Library/res/values-ja/multiimagechooser_strings_ja.xml b/src/android/Library/res/values-ja/multiimagechooser_strings_ja.xml deleted file mode 100644 index c96dc1cf..00000000 --- a/src/android/Library/res/values-ja/multiimagechooser_strings_ja.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - MultiImageChooser - 無料版 - 残りの画像: %d - 画像データベースを開く際にエラーがありました。問題を報告してください。 - サムネイルをリクエスト中です。お待ちください。 - Processing Images - This may take a few moments - Limit reached - You can only select %d photos at once. - Cancel - OK - diff --git a/src/android/Library/res/values-ko/multiimagechooser_strings_ko.xml b/src/android/Library/res/values-ko/multiimagechooser_strings_ko.xml deleted file mode 100644 index d08b41ed..00000000 --- a/src/android/Library/res/values-ko/multiimagechooser_strings_ko.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - MultiImageChooser - 무료 버전 - 남은 이미지: %d - 이미지 데이터베이스를 여는 데 오류가 발생했습니다. 문제를 보고하세요. - 썸네일 요청 중. 기다려주세요 - Processing Images - This may take a few moments - Limit reached - You can only select %d photos at once. - Cancel - OK - diff --git a/src/android/Library/res/values/multiimagechooser_strings_en.xml b/src/android/Library/res/values/multiimagechooser_strings_en.xml deleted file mode 100644 index 6776c9b1..00000000 --- a/src/android/Library/res/values/multiimagechooser_strings_en.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - MultiImageChooser - Free version - Images left: %d - There was an error opening the images database. Please report the problem. - Requesting thumbnails, please be patient - Processing Images - This may take a few moments - Limit reached - You can only select %d photos at once. - Cancel - OK - diff --git a/src/android/Library/res/values/themes.xml b/src/android/Library/res/values/themes.xml deleted file mode 100644 index 2ec73cf1..00000000 --- a/src/android/Library/res/values/themes.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/src/android/Library/src/ImageFetcher.java b/src/android/Library/src/ImageFetcher.java deleted file mode 100644 index 88255bd8..00000000 --- a/src/android/Library/src/ImageFetcher.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * 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. - */ - -package com.synconset; - -import java.lang.ref.SoftReference; -import java.lang.ref.WeakReference; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.RejectedExecutionException; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Color; -import android.graphics.drawable.ColorDrawable; -import android.graphics.drawable.Drawable; -import android.graphics.Matrix; -import android.os.AsyncTask; -import android.os.Build; -import android.os.Handler; -import android.provider.MediaStore; -import android.util.Log; -import android.view.View; -import android.view.animation.Animation; -import android.view.animation.AnimationUtils; -import android.widget.ImageView; - -/** - * This helper class download images from the Internet and binds those with the - * provided ImageView. - * - *

- * It requires the INTERNET permission, which should be added to your - * application's manifest file. - *

- * - * A local cache of downloaded images is maintained internally to improve - * performance. - */ -public class ImageFetcher { - - private int colWidth; - private long origId; - private ExecutorService executor; - - public ImageFetcher() { - executor = Executors.newCachedThreadPool(); - } - - public void fetch(Integer id, ImageView imageView, int colWidth, int rotate) { - resetPurgeTimer(); - this.colWidth = colWidth; - this.origId = id; - Bitmap bitmap = getBitmapFromCache(id); - - if (bitmap == null) { - forceDownload(id, imageView, rotate); - } else { - cancelPotentialDownload(id, imageView); - imageView.setImageBitmap(bitmap); - } - } - - /** - * Same as download but the image is always downloaded and the cache is not - * used. Kept private at the moment as its interest is not clear. - */ - private void forceDownload(Integer position, ImageView imageView, int rotate) { - if (position == null) { - imageView.setImageDrawable(null); - return; - } - - if (cancelPotentialDownload(position, imageView)) { - BitmapFetcherTask task = new BitmapFetcherTask(imageView.getContext(), imageView, rotate); - DownloadedDrawable downloadedDrawable = new DownloadedDrawable(imageView.getContext(), task, origId); - imageView.setImageDrawable(downloadedDrawable); - imageView.setMinimumHeight(colWidth); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { - task.executeOnExecutor(executor, position); - } else { - try { - task.execute(position); - } catch (RejectedExecutionException e) { - // Oh :( - } - } - - } - } - - /** - * Returns true if the current download has been canceled or if there was no - * download in progress on this image view. Returns false if the download in - * progress deals with the same url. The download is not stopped in that - * case. - */ - private static boolean cancelPotentialDownload(Integer position, ImageView imageView) { - BitmapFetcherTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView); - long origId = getOrigId(imageView); - - if (bitmapDownloaderTask != null) { - Integer bitmapPosition = bitmapDownloaderTask.position; - if ((bitmapPosition == null) || (!bitmapPosition.equals(position))) { - // Log.d("DAVID", "Canceling..."); - MediaStore.Images.Thumbnails.cancelThumbnailRequest(imageView.getContext().getContentResolver(), - origId, 12345); - bitmapDownloaderTask.cancel(true); - } else { - return false; - } - } - return true; - } - - /** - * @param imageView - * Any imageView - * @return Retrieve the currently active download task (if any) associated - * with this imageView. null if there is no such task. - */ - private static BitmapFetcherTask getBitmapDownloaderTask(ImageView imageView) { - if (imageView != null) { - Drawable drawable = imageView.getDrawable(); - if (drawable instanceof DownloadedDrawable) { - DownloadedDrawable downloadedDrawable = (DownloadedDrawable) drawable; - return downloadedDrawable.getBitmapDownloaderTask(); - } - } - return null; - } - - private static long getOrigId(ImageView imageView) { - if (imageView != null) { - Drawable drawable = imageView.getDrawable(); - if (drawable instanceof DownloadedDrawable) { - DownloadedDrawable downloadedDrawable = (DownloadedDrawable) drawable; - return downloadedDrawable.getOrigId(); - } - } - return -1; - } - - /** - * The actual AsyncTask that will asynchronously download the image. - */ - class BitmapFetcherTask extends AsyncTask { - private Integer position; - private final WeakReference imageViewReference; - private final Context mContext; - private final int rotate; - - public BitmapFetcherTask(Context context, ImageView imageView, int rotate) { - imageViewReference = new WeakReference(imageView); - mContext = context; - this.rotate = rotate; - } - - /** - * Actual download method. - */ - @Override - protected Bitmap doInBackground(Integer... params) { - try { - position = params[0]; - if (isCancelled()) { - return null; - } - Bitmap thumb = MediaStore.Images.Thumbnails.getThumbnail(mContext.getContentResolver(), position, 12345, - MediaStore.Images.Thumbnails.MINI_KIND, null); - if (isCancelled()) { - return null; - } - if (thumb == null) { - return null; - } else { - if (isCancelled()) { - return null; - } else { - if (rotate != 0) { - Matrix matrix = new Matrix(); - matrix.setRotate(rotate); - thumb = Bitmap.createBitmap(thumb, 0, 0, thumb.getWidth(), thumb.getHeight(), matrix, true); - } - return thumb; - } - } - }catch(OutOfMemoryError error) { - clearCache(); - return null; - } - - } - - private void setInvisible() { - // Log.d("COLLAGE", "Setting something invisible..."); - if (imageViewReference != null) { - final ImageView imageView = imageViewReference.get(); - BitmapFetcherTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView); - if (this == bitmapDownloaderTask) { - imageView.setVisibility(View.GONE); - imageView.setClickable(false); - imageView.setEnabled(false); - } - } - } - - /** - * Once the image is downloaded, associates it to the imageView - */ - @Override - protected void onPostExecute(Bitmap bitmap) { - if (isCancelled()) { - bitmap = null; - } - addBitmapToCache(position, bitmap); - if (imageViewReference != null) { - ImageView imageView = imageViewReference.get(); - BitmapFetcherTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView); - if (this == bitmapDownloaderTask) { - imageView.setImageBitmap(bitmap); - Animation anim = AnimationUtils.loadAnimation(imageView.getContext(), android.R.anim.fade_in); - imageView.setAnimation(anim); - anim.start(); - } - } else { - setInvisible(); - } - } - } - - /** - * A fake Drawable that will be attached to the imageView while the download - * is in progress. - * - *

- * Contains a reference to the actual download task, so that a download task - * can be stopped if a new binding is required, and makes sure that only the - * last started download process can bind its result, independently of the - * download finish order. - *

- */ - static class DownloadedDrawable extends ColorDrawable { - private final WeakReference bitmapDownloaderTaskReference; - private long origId; - - public DownloadedDrawable(Context mContext, BitmapFetcherTask bitmapDownloaderTask, long origId) { - super(Color.TRANSPARENT); - bitmapDownloaderTaskReference = new WeakReference(bitmapDownloaderTask); - this.origId = origId; - } - - public long getOrigId() { - return origId; - } - - public BitmapFetcherTask getBitmapDownloaderTask() { - return bitmapDownloaderTaskReference.get(); - } - } - - /* - * Cache-related fields and methods. - * - * We use a hard and a soft cache. A soft reference cache is too aggressively cleared by the - * Garbage Collector. - */ - - private static final int HARD_CACHE_CAPACITY = 100; - private static final int DELAY_BEFORE_PURGE = 10 * 1000; // in milliseconds - - // Hard cache, with a fixed maximum capacity and a life duration - private final HashMap sHardBitmapCache = new LinkedHashMap( - HARD_CACHE_CAPACITY / 2, 0.75f, true) { - @Override - protected boolean removeEldestEntry(LinkedHashMap.Entry eldest) { - if (size() > HARD_CACHE_CAPACITY) { - // Entries push-out of hard reference cache are transferred to - // soft reference cache - sSoftBitmapCache.put(eldest.getKey(), new SoftReference(eldest.getValue())); - return true; - } else - return false; - } - }; - - // Soft cache for bitmaps kicked out of hard cache - private final static ConcurrentHashMap> sSoftBitmapCache = new ConcurrentHashMap>( - HARD_CACHE_CAPACITY / 2); - - private final Handler purgeHandler = new Handler(); - - private final Runnable purger = new Runnable() { - public void run() { - clearCache(); - } - }; - - /** - * Adds this bitmap to the cache. - * - * @param bitmap - * The newly downloaded bitmap. - */ - private void addBitmapToCache(Integer position, Bitmap bitmap) { - if (bitmap != null) { - synchronized (sHardBitmapCache) { - sHardBitmapCache.put(position, bitmap); - } - } - } - - /** - * @param position - * The URL of the image that will be retrieved from the cache. - * @return The cached bitmap or null if it was not found. - */ - private Bitmap getBitmapFromCache(Integer position) { - // First try the hard reference cache - synchronized (sHardBitmapCache) { - final Bitmap bitmap = sHardBitmapCache.get(position); - if (bitmap != null) { - // Log.d("CACHE ****** ", "Hard hit!"); - // Bitmap found in hard cache - // Move element to first position, so that it is removed last - return bitmap; - } - } - - // Then try the soft reference cache - SoftReference bitmapReference = sSoftBitmapCache.get(position); - if (bitmapReference != null) { - final Bitmap bitmap = bitmapReference.get(); - if (bitmap != null) { - // Bitmap found in soft cache - // Log.d("CACHE ****** ", "Soft hit!"); - return bitmap; - } else { - // Soft reference has been Garbage Collected - sSoftBitmapCache.remove(position); - } - } - - return null; - } - - /** - * Clears the image cache used internally to improve performance. Note that - * for memory efficiency reasons, the cache will automatically be cleared - * after a certain inactivity delay. - */ - public void clearCache() { - sHardBitmapCache.clear(); - sSoftBitmapCache.clear(); - } - - /** - * Allow a new delay before the automatic cache clear is done. - */ - private void resetPurgeTimer() { - // purgeHandler.removeCallbacks(purger); - // purgeHandler.postDelayed(purger, DELAY_BEFORE_PURGE); - } -} diff --git a/src/android/Library/src/MultiImageChooserActivity.java b/src/android/Library/src/MultiImageChooserActivity.java deleted file mode 100644 index 25ca388e..00000000 --- a/src/android/Library/src/MultiImageChooserActivity.java +++ /dev/null @@ -1,696 +0,0 @@ -/* - * Copyright (c) 2012, David Erosa - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDIN G NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE - * - * Code modified by Andrew Stephan for Sync OnSet - * - */ - -package com.synconset; - -import java.net.URI; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import com.synconset.FakeR; -import android.app.Activity; -import android.app.ActionBar; -import android.app.AlertDialog; -import android.app.LoaderManager; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.CursorLoader; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.Loader; -import android.database.Cursor; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Color; -import android.graphics.Matrix; -import android.net.Uri; -import android.os.AsyncTask; -import android.os.Bundle; -import android.provider.MediaStore; -import android.util.Log; -import android.util.SparseBooleanArray; -import android.view.Display; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AbsListView; -import android.widget.AbsListView.OnScrollListener; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemClickListener; -import android.widget.BaseAdapter; -import android.widget.GridView; -import android.widget.ImageView; -import android.widget.TextView; - -public class MultiImageChooserActivity extends Activity implements OnItemClickListener, - LoaderManager.LoaderCallbacks { - private static final String TAG = "ImagePicker"; - - public static final int NOLIMIT = -1; - public static final String MAX_IMAGES_KEY = "MAX_IMAGES"; - public static final String WIDTH_KEY = "WIDTH"; - public static final String HEIGHT_KEY = "HEIGHT"; - public static final String QUALITY_KEY = "QUALITY"; - - private ImageAdapter ia; - - private Cursor imagecursor, actualimagecursor; - private int image_column_index, image_column_orientation, actual_image_column_index, orientation_column_index; - private int colWidth; - - private static final int CURSORLOADER_THUMBS = 0; - private static final int CURSORLOADER_REAL = 1; - - private Map fileNames = new HashMap(); - - private SparseBooleanArray checkStatus = new SparseBooleanArray(); - - private int maxImages; - private int maxImageCount; - - private int desiredWidth; - private int desiredHeight; - private int quality; - - private GridView gridView; - - private final ImageFetcher fetcher = new ImageFetcher(); - - private int selectedColor = 0xff32b2e1; - private boolean shouldRequestThumb = true; - - private FakeR fakeR; - - private ProgressDialog progress; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - fakeR = new FakeR(this); - setContentView(fakeR.getId("layout", "multiselectorgrid")); - fileNames.clear(); - - maxImages = getIntent().getIntExtra(MAX_IMAGES_KEY, NOLIMIT); - desiredWidth = getIntent().getIntExtra(WIDTH_KEY, 0); - desiredHeight = getIntent().getIntExtra(HEIGHT_KEY, 0); - quality = getIntent().getIntExtra(QUALITY_KEY, 0); - maxImageCount = maxImages; - - Display display = getWindowManager().getDefaultDisplay(); - int width = display.getWidth(); - - colWidth = width / 4; - - gridView = (GridView) findViewById(fakeR.getId("id", "gridview")); - gridView.setOnItemClickListener(this); - gridView.setOnScrollListener(new OnScrollListener() { - private int lastFirstItem = 0; - private long timestamp = System.currentTimeMillis(); - - @Override - public void onScrollStateChanged(AbsListView view, int scrollState) { - if (scrollState == SCROLL_STATE_IDLE) { - shouldRequestThumb = true; - ia.notifyDataSetChanged(); - } - } - - @Override - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - float dt = System.currentTimeMillis() - timestamp; - if (firstVisibleItem != lastFirstItem) { - double speed = 1 / dt * 1000; - lastFirstItem = firstVisibleItem; - timestamp = System.currentTimeMillis(); - - // Limit if we go faster than a page a second - shouldRequestThumb = speed < visibleItemCount; - } - } - }); - - ia = new ImageAdapter(this); - gridView.setAdapter(ia); - - LoaderManager.enableDebugLogging(false); - getLoaderManager().initLoader(CURSORLOADER_THUMBS, null, this); - getLoaderManager().initLoader(CURSORLOADER_REAL, null, this); - setupHeader(); - updateAcceptButton(); - progress = new ProgressDialog(this); - progress.setTitle("Processing Images"); - progress.setMessage("This may take a few moments"); - } - - @Override - public void onItemClick(AdapterView arg0, View view, int position, long id) { - String name = getImageName(position); - int rotation = getImageRotation(position); - - if (name == null) { - return; - } - boolean isChecked = !isChecked(position); - if (maxImages == 0 && isChecked) { - isChecked = false; - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setTitle("Maximum " + maxImageCount + " Photos"); - builder.setMessage("You can only select " + maxImageCount + " photos at a time."); - builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - dialog.cancel(); - } - }); - AlertDialog alert = builder.create(); - alert.show(); - } else if (isChecked) { - fileNames.put(name, new Integer(rotation)); - if (maxImageCount == 1) { - this.selectClicked(null); - } else { - maxImages--; - ImageView imageView = (ImageView)view; - if (android.os.Build.VERSION.SDK_INT>=16) { - imageView.setImageAlpha(128); - } else { - imageView.setAlpha(128); - } - view.setBackgroundColor(selectedColor); - } - } else { - fileNames.remove(name); - maxImages++; - ImageView imageView = (ImageView)view; - if (android.os.Build.VERSION.SDK_INT>=16) { - imageView.setImageAlpha(255); - } else { - imageView.setAlpha(255); - } - view.setBackgroundColor(Color.TRANSPARENT); - } - - checkStatus.put(position, isChecked); - updateAcceptButton(); - } - - @Override - public Loader onCreateLoader(int cursorID, Bundle arg1) { - CursorLoader cl = null; - - ArrayList img = new ArrayList(); - switch (cursorID) { - - case CURSORLOADER_THUMBS: - img.add(MediaStore.Images.Media._ID); - img.add(MediaStore.Images.Media.ORIENTATION); - break; - case CURSORLOADER_REAL: - img.add(MediaStore.Images.Thumbnails.DATA); - img.add(MediaStore.Images.Media.ORIENTATION); - break; - default: - break; - } - - cl = new CursorLoader(MultiImageChooserActivity.this, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, - img.toArray(new String[img.size()]), null, null, "DATE_MODIFIED DESC"); - return cl; - } - - @Override - public void onLoadFinished(Loader loader, Cursor cursor) { - if (cursor == null) { - // NULL cursor. This usually means there's no image database yet.... - return; - } - - switch (loader.getId()) { - case CURSORLOADER_THUMBS: - imagecursor = cursor; - image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID); - image_column_orientation = imagecursor.getColumnIndex(MediaStore.Images.Media.ORIENTATION); - ia.notifyDataSetChanged(); - break; - case CURSORLOADER_REAL: - actualimagecursor = cursor; - String[] columns = actualimagecursor.getColumnNames(); - actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); - orientation_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.ORIENTATION); - break; - default: - break; - } - } - - @Override - public void onLoaderReset(Loader loader) { - if (loader.getId() == CURSORLOADER_THUMBS) { - imagecursor = null; - } else if (loader.getId() == CURSORLOADER_REAL) { - actualimagecursor = null; - } - } - - public void cancelClicked(View ignored) { - setResult(RESULT_CANCELED); - finish(); - } - - public void selectClicked(View ignored) { - ((TextView) getActionBar().getCustomView().findViewById(fakeR.getId("id", "actionbar_done_textview"))).setEnabled(false); - getActionBar().getCustomView().findViewById(fakeR.getId("id", "actionbar_done")).setEnabled(false); - progress.show(); - Intent data = new Intent(); - if (fileNames.isEmpty()) { - this.setResult(RESULT_CANCELED); - progress.dismiss(); - finish(); - } else { - new ResizeImagesTask().execute(fileNames.entrySet()); - } - } - - - /********************* - * Helper Methods - ********************/ - private void updateAcceptButton() { - ((TextView) getActionBar().getCustomView().findViewById(fakeR.getId("id", "actionbar_done_textview"))) - .setEnabled(fileNames.size() != 0); - getActionBar().getCustomView().findViewById(fakeR.getId("id", "actionbar_done")).setEnabled(fileNames.size() != 0); - } - - private void setupHeader() { - // From Roman Nkk's code - // https://plus.google.com/113735310430199015092/posts/R49wVvcDoEW - // Inflate a "Done/Discard" custom action bar view - /* - * Copyright 2013 The Android Open Source Project - * - * 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. - */ - LayoutInflater inflater = (LayoutInflater) getActionBar().getThemedContext().getSystemService( - LAYOUT_INFLATER_SERVICE); - final View customActionBarView = inflater.inflate(fakeR.getId("layout", "actionbar_custom_view_done_discard"), null); - customActionBarView.findViewById(fakeR.getId("id", "actionbar_done")).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - // "Done" - selectClicked(null); - } - }); - customActionBarView.findViewById(fakeR.getId("id", "actionbar_discard")).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - finish(); - } - }); - - // Show the custom action bar view and hide the normal Home icon and title. - final ActionBar actionBar = getActionBar(); - actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM - | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE); - actionBar.setCustomView(customActionBarView, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.MATCH_PARENT)); - } - - private String getImageName(int position) { - actualimagecursor.moveToPosition(position); - String name = null; - - try { - name = actualimagecursor.getString(actual_image_column_index); - } catch (Exception e) { - return null; - } - return name; - } - - private int getImageRotation(int position) { - actualimagecursor.moveToPosition(position); - int rotation = 0; - - try { - rotation = actualimagecursor.getInt(orientation_column_index); - } catch (Exception e) { - return rotation; - } - return rotation; - } - - public boolean isChecked(int position) { - boolean ret = checkStatus.get(position); - return ret; - } - - - /********************* - * Nested Classes - ********************/ - private class SquareImageView extends ImageView { - public SquareImageView(Context context) { - super(context); - } - - @Override - public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - super.onMeasure(widthMeasureSpec, widthMeasureSpec); - } - } - - - private class ImageAdapter extends BaseAdapter { - private final Bitmap mPlaceHolderBitmap; - - public ImageAdapter(Context c) { - Bitmap tmpHolderBitmap = BitmapFactory.decodeResource(getResources(), fakeR.getId("drawable", "loading_icon")); - mPlaceHolderBitmap = Bitmap.createScaledBitmap(tmpHolderBitmap, colWidth, colWidth, false); - if (tmpHolderBitmap != mPlaceHolderBitmap) { - tmpHolderBitmap.recycle(); - tmpHolderBitmap = null; - } - } - - public int getCount() { - if (imagecursor != null) { - return imagecursor.getCount(); - } else { - return 0; - } - } - - public Object getItem(int position) { - return position; - } - - public long getItemId(int position) { - return position; - } - - // create a new ImageView for each item referenced by the Adapter - public View getView(int pos, View convertView, ViewGroup parent) { - - if (convertView == null) { - ImageView temp = new SquareImageView(MultiImageChooserActivity.this); - temp.setScaleType(ImageView.ScaleType.CENTER_CROP); - convertView = (View)temp; - } - - ImageView imageView = (ImageView)convertView; - imageView.setImageBitmap(null); - - final int position = pos; - - if (!imagecursor.moveToPosition(position)) { - return imageView; - } - - if (image_column_index == -1) { - return imageView; - } - - final int id = imagecursor.getInt(image_column_index); - final int rotate = imagecursor.getInt(image_column_orientation); - if (isChecked(pos)) { - if (android.os.Build.VERSION.SDK_INT>=16) { - imageView.setImageAlpha(128); - } else { - imageView.setAlpha(128); - } - imageView.setBackgroundColor(selectedColor); - } else { - if (android.os.Build.VERSION.SDK_INT>=16) { - imageView.setImageAlpha(255); - } else { - imageView.setAlpha(255); - } - imageView.setBackgroundColor(Color.TRANSPARENT); - } - if (shouldRequestThumb) { - fetcher.fetch(Integer.valueOf(id), imageView, colWidth, rotate); - } - - return imageView; - } - } - - - private class ResizeImagesTask extends AsyncTask>, Void, ArrayList> { - private Exception asyncTaskError = null; - - @Override - protected ArrayList doInBackground(Set>... fileSets) { - Set> fileNames = fileSets[0]; - ArrayList al = new ArrayList(); - try { - Iterator> i = fileNames.iterator(); - Bitmap bmp; - while(i.hasNext()) { - Entry imageInfo = i.next(); - File file = new File(imageInfo.getKey()); - int rotate = imageInfo.getValue().intValue(); - BitmapFactory.Options options = new BitmapFactory.Options(); - options.inSampleSize = 1; - options.inJustDecodeBounds = true; - BitmapFactory.decodeFile(file.getAbsolutePath(), options); - int width = options.outWidth; - int height = options.outHeight; - float scale = calculateScale(width, height); - if (scale < 1) { - int finalWidth = (int)(width * scale); - int finalHeight = (int)(height * scale); - int inSampleSize = calculateInSampleSize(options, finalWidth, finalHeight); - options = new BitmapFactory.Options(); - options.inSampleSize = inSampleSize; - try { - bmp = this.tryToGetBitmap(file, options, rotate, true); - } catch (OutOfMemoryError e) { - options.inSampleSize = calculateNextSampleSize(options.inSampleSize); - try { - bmp = this.tryToGetBitmap(file, options, rotate, false); - } catch (OutOfMemoryError e2) { - throw new IOException("Unable to load image into memory."); - } - } - } else { - try { - bmp = this.tryToGetBitmap(file, null, rotate, false); - } catch(OutOfMemoryError e) { - options = new BitmapFactory.Options(); - options.inSampleSize = 2; - try { - bmp = this.tryToGetBitmap(file, options, rotate, false); - } catch(OutOfMemoryError e2) { - options = new BitmapFactory.Options(); - options.inSampleSize = 4; - try { - bmp = this.tryToGetBitmap(file, options, rotate, false); - } catch (OutOfMemoryError e3) { - throw new IOException("Unable to load image into memory."); - } - } - } - } - - file = this.storeImage(bmp, file.getName()); - al.add(Uri.fromFile(file).toString()); - } - return al; - } catch(IOException e) { - try { - asyncTaskError = e; - for (int i = 0; i < al.size(); i++) { - URI uri = new URI(al.get(i)); - File file = new File(uri); - file.delete(); - } - } catch(Exception exception) { - // the finally does what we want to do - } finally { - return new ArrayList(); - } - } - } - - @Override - protected void onPostExecute(ArrayList al) { - Intent data = new Intent(); - - if (asyncTaskError != null) { - Bundle res = new Bundle(); - res.putString("ERRORMESSAGE", asyncTaskError.getMessage()); - data.putExtras(res); - setResult(RESULT_CANCELED, data); - } else if (al.size() > 0) { - Bundle res = new Bundle(); - res.putStringArrayList("MULTIPLEFILENAMES", al); - if (imagecursor != null) { - res.putInt("TOTALFILES", imagecursor.getCount()); - } - data.putExtras(res); - setResult(RESULT_OK, data); - } else { - setResult(RESULT_CANCELED, data); - } - - progress.dismiss(); - finish(); - } - - private Bitmap tryToGetBitmap(File file, BitmapFactory.Options options, int rotate, boolean shouldScale) throws IOException, OutOfMemoryError { - Bitmap bmp; - if (options == null) { - bmp = BitmapFactory.decodeFile(file.getAbsolutePath()); - } else { - bmp = BitmapFactory.decodeFile(file.getAbsolutePath(), options); - } - if (bmp == null) { - throw new IOException("The image file could not be opened."); - } - if (options != null && shouldScale) { - float scale = calculateScale(options.outWidth, options.outHeight); - bmp = this.getResizedBitmap(bmp, scale); - } - if (rotate != 0) { - Matrix matrix = new Matrix(); - matrix.setRotate(rotate); - bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true); - } - return bmp; - } - - /* - * The following functions are originally from - * https://github.com/raananw/PhoneGap-Image-Resizer - * - * They have been modified by Andrew Stephan for Sync OnSet - * - * The software is open source, MIT Licensed. - * Copyright (C) 2012, webXells GmbH All Rights Reserved. - */ - private File storeImage(Bitmap bmp, String fileName) throws IOException { - int index = fileName.lastIndexOf('.'); - String name = fileName.substring(0, index); - String ext = fileName.substring(index); - File file = File.createTempFile("tmp_" + name, ext); - OutputStream outStream = new FileOutputStream(file); - if (ext.compareToIgnoreCase(".png") == 0) { - bmp.compress(Bitmap.CompressFormat.PNG, quality, outStream); - } else { - bmp.compress(Bitmap.CompressFormat.JPEG, quality, outStream); - } - outStream.flush(); - outStream.close(); - return file; - } - - private Bitmap getResizedBitmap(Bitmap bm, float factor) { - int width = bm.getWidth(); - int height = bm.getHeight(); - // create a matrix for the manipulation - Matrix matrix = new Matrix(); - // resize the bit map - matrix.postScale(factor, factor); - // recreate the new Bitmap - Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false); - return resizedBitmap; - } - } - - private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { - // Raw height and width of image - final int height = options.outHeight; - final int width = options.outWidth; - int inSampleSize = 1; - - if (height > reqHeight || width > reqWidth) { - final int halfHeight = height / 2; - final int halfWidth = width / 2; - - // Calculate the largest inSampleSize value that is a power of 2 and keeps both - // height and width larger than the requested height and width. - while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { - inSampleSize *= 2; - } - } - - return inSampleSize; - } - - private int calculateNextSampleSize(int sampleSize) { - double logBaseTwo = (int)(Math.log(sampleSize) / Math.log(2)); - return (int)Math.pow(logBaseTwo + 1, 2); - } - - private float calculateScale(int width, int height) { - float widthScale = 1.0f; - float heightScale = 1.0f; - float scale = 1.0f; - if (desiredWidth > 0 || desiredHeight > 0) { - if (desiredHeight == 0 && desiredWidth < width) { - scale = (float)desiredWidth/width; - } else if (desiredWidth == 0 && desiredHeight < height) { - scale = (float)desiredHeight/height; - } else { - if (desiredWidth > 0 && desiredWidth < width) { - widthScale = (float)desiredWidth/width; - } - if (desiredHeight > 0 && desiredHeight < height) { - heightScale = (float)desiredHeight/height; - } - if (widthScale < heightScale) { - scale = widthScale; - } else { - scale = heightScale; - } - } - } - - return scale; - } -} diff --git a/src/android/com/synconset/ImagePicker/FakeR.java b/src/android/com/synconset/ImagePicker/FakeR.java deleted file mode 100644 index 465b64f5..00000000 --- a/src/android/com/synconset/ImagePicker/FakeR.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -The MIT License - -Copyright (c) 2010 Matt Kane - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Code taken from: https://github.com/wildabeast/BarcodeScanner -*/ -package com.synconset; - -import android.app.Activity; -import android.content.Context; - -/** - * R replacement for PhoneGap Build. - * - * ([^.\w])R\.(\w+)\.(\w+) - * $1fakeR("$2", "$3") - * - * @author Maciej Nux Jaros - */ -public class FakeR { - private Context context; - private String packageName; - - public FakeR(Activity activity) { - context = activity.getApplicationContext(); - packageName = context.getPackageName(); - } - - public FakeR(Context context) { - this.context = context; - packageName = context.getPackageName(); - } - - public int getId(String group, String key) { - return context.getResources().getIdentifier(key, group, packageName); - } - - public static int getId(Context context, String group, String key) { - return context.getResources().getIdentifier(key, group, context.getPackageName()); - } -} diff --git a/src/android/com/synconset/ImagePicker/ImagePicker.java b/src/android/com/synconset/ImagePicker/ImagePicker.java index b1ad18d7..886e9e65 100644 --- a/src/android/com/synconset/ImagePicker/ImagePicker.java +++ b/src/android/com/synconset/ImagePicker/ImagePicker.java @@ -3,6 +3,9 @@ */ package com.synconset; +import android.Manifest; +import android.content.pm.PackageManager; + import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; @@ -14,59 +17,94 @@ import android.app.Activity; import android.content.Intent; -import android.util.Log; public class ImagePicker extends CordovaPlugin { - public static String TAG = "ImagePicker"; - + + //required permissions + String [] permissions = { + Manifest.permission.WRITE_EXTERNAL_STORAGE, + Manifest.permission.READ_EXTERNAL_STORAGE + }; + private CallbackContext callbackContext; - private JSONObject params; - + + private Integer max = 20; + private Integer desiredWidth = 0; + private Integer desiredHeight = 0; + private Integer quality = 100; + public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { - this.callbackContext = callbackContext; - this.params = args.getJSONObject(0); - if (action.equals("getPictures")) { - Intent intent = new Intent(cordova.getActivity(), MultiImageChooserActivity.class); - int max = 20; - int desiredWidth = 0; - int desiredHeight = 0; - int quality = 100; - if (this.params.has("maximumImagesCount")) { - max = this.params.getInt("maximumImagesCount"); + this.callbackContext = callbackContext; + + JSONObject params = args.getJSONObject(0); + + if (action.equals("getPictures")) { + + if (params.has("maximumImagesCount")) { + max = params.getInt("maximumImagesCount"); } - if (this.params.has("width")) { - desiredWidth = this.params.getInt("width"); + if (params.has("width")) { + desiredWidth = params.getInt("width"); } - if (this.params.has("height")) { - desiredHeight = this.params.getInt("height"); + if (params.has("height")) { + desiredHeight = params.getInt("height"); } - if (this.params.has("quality")) { - quality = this.params.getInt("quality"); + if (params.has("quality")) { + quality = params.getInt("quality"); } - intent.putExtra("MAX_IMAGES", max); - intent.putExtra("WIDTH", desiredWidth); - intent.putExtra("HEIGHT", desiredHeight); - intent.putExtra("QUALITY", quality); - if (this.cordova != null) { - this.cordova.startActivityForResult((CordovaPlugin) this, intent, 0); + + if(cordova.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) && cordova.hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) { + selectImages(); + } else { + getReadPermission(); } } return true; } - + + private void selectImages() { + /* + * ATENTION: + * Starts an extra activity because Matisse requires an Activity context + * and passing `this.cordova.getActivity()` context, it doesn't return activity result + * for this instance of CordovaPlugin + * */ + Intent intent = new Intent(this.cordova.getActivity(), ImgPickerActivity.class); + intent.putExtra(ImgPickerActivity.MAX_IMAGES_KEY, max); + intent.putExtra(ImgPickerActivity.WIDTH_KEY, desiredWidth); + intent.putExtra(ImgPickerActivity.HEIGHT_KEY, desiredHeight); + intent.putExtra(ImgPickerActivity.QUALITY_KEY, quality); + this.cordova.startActivityForResult(this, intent, 0); + } + + + @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (resultCode == Activity.RESULT_OK && data != null) { - ArrayList fileNames = data.getStringArrayListExtra("MULTIPLEFILENAMES"); - JSONArray res = new JSONArray(fileNames); - this.callbackContext.success(res); - } else if (resultCode == Activity.RESULT_CANCELED && data != null) { - String error = data.getStringExtra("ERRORMESSAGE"); - this.callbackContext.error(error); - } else if (resultCode == Activity.RESULT_CANCELED) { - JSONArray res = new JSONArray(); + ArrayList names = data.getStringArrayListExtra("MULTIPLEFILENAMES"); + JSONArray res = new JSONArray(names); this.callbackContext.success(res); } else { this.callbackContext.error("No images selected"); } } + + + protected void getReadPermission() { + cordova.requestPermissions(this, 0, permissions); + } + + public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException { + for(int r:grantResults) { + if(r == PackageManager.PERMISSION_DENIED) { + this.callbackContext.error("Permission denied!"); + return; + } + } + + selectImages(); + } + } diff --git a/src/android/com/synconset/ImagePicker/ImgPickerActivity.java b/src/android/com/synconset/ImagePicker/ImgPickerActivity.java new file mode 100644 index 00000000..f8d210d3 --- /dev/null +++ b/src/android/com/synconset/ImagePicker/ImgPickerActivity.java @@ -0,0 +1,74 @@ +package com.synconset; + +import android.app.Activity; +import android.content.Intent; +import android.content.pm.ActivityInfo; +import android.net.Uri; +import android.os.Bundle; +import android.support.annotation.Nullable; + +import com.zhihu.matisse.Matisse; +import com.zhihu.matisse.MimeType; +import com.zhihu.matisse.engine.impl.GlideEngine; + +import java.util.ArrayList; +import java.util.List; + +public class ImgPickerActivity extends Activity { + + private static int REQUEST_CODE_CHOOSE = 12340012; + + //Params + public static String MAX_IMAGES_KEY = "MAX_IMAGES"; + public static String WIDTH_KEY = "WIDTH"; + public static String HEIGHT_KEY = "HEIGHT"; + public static String QUALITY_KEY = "QUALITY"; + + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + int maxImages = getIntent().getIntExtra(MAX_IMAGES_KEY, 200); + int desiredWidth = getIntent().getIntExtra(WIDTH_KEY, 0); + int desiredHeight = getIntent().getIntExtra(HEIGHT_KEY, 0); + int quality = getIntent().getIntExtra(QUALITY_KEY, 0); + selectImages(maxImages, desiredWidth, desiredHeight, quality); + } + + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (resultCode == Activity.RESULT_OK) { + + List fileUris = Matisse.obtainResult(data); + ArrayList files = new ArrayList(); + + for(Uri uri:fileUris) { + files.add(uri.toString()); + } + + Intent res = new Intent(); + res.putStringArrayListExtra("MULTIPLEFILENAMES", files); + data.putExtras(res); + + setResult(RESULT_OK, data); + } else { + setResult(RESULT_CANCELED); + } + finish(); + } + + + private void selectImages(int max, int desiredWidth, int desiredHeight, int quality) { + Matisse.from(this) + .choose(MimeType.of(MimeType.JPEG, MimeType.PNG, MimeType.GIF)) + .countable(true) + .maxSelectable(max) + .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) + .thumbnailScale(0.85f) + .imageEngine(new GlideEngine()) + .forResult(REQUEST_CODE_CHOOSE); + } +}