OSDN Git Service

Gallery in separate task for up button in Camera filmstrip
[android-x86/packages-apps-Gallery2.git] / src / com / android / gallery3d / util / GalleryUtils.java
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.android.gallery3d.util;
18
19 import android.annotation.TargetApi;
20 import android.content.ActivityNotFoundException;
21 import android.content.ComponentName;
22 import android.content.Context;
23 import android.content.Intent;
24 import android.content.SharedPreferences;
25 import android.content.pm.PackageManager;
26 import android.content.pm.ResolveInfo;
27 import android.content.res.Resources;
28 import android.graphics.Color;
29 import android.net.Uri;
30 import android.os.ConditionVariable;
31 import android.os.Environment;
32 import android.os.StatFs;
33 import android.preference.PreferenceManager;
34 import android.provider.MediaStore;
35 import android.util.DisplayMetrics;
36 import android.util.Log;
37 import android.view.WindowManager;
38
39 import com.android.gallery3d.R;
40 import com.android.gallery3d.app.Gallery;
41 import com.android.gallery3d.app.PackagesMonitor;
42 import com.android.gallery3d.common.ApiHelper;
43 import com.android.gallery3d.data.DataManager;
44 import com.android.gallery3d.data.MediaItem;
45 import com.android.gallery3d.ui.TiledScreenNail;
46 import com.android.gallery3d.util.ThreadPool.CancelListener;
47 import com.android.gallery3d.util.ThreadPool.JobContext;
48
49 import java.util.Arrays;
50 import java.util.List;
51 import java.util.Locale;
52
53 public class GalleryUtils {
54     private static final String TAG = "GalleryUtils";
55     private static final String MAPS_PACKAGE_NAME = "com.google.android.apps.maps";
56     private static final String MAPS_CLASS_NAME = "com.google.android.maps.MapsActivity";
57     private static final String CAMERA_LAUNCHER_NAME = "com.android.camera.CameraLauncher";
58
59     public static final String MIME_TYPE_IMAGE = "image/*";
60     public static final String MIME_TYPE_VIDEO = "video/*";
61     public static final String MIME_TYPE_PANORAMA360 = "application/vnd.google.panorama360+jpg";
62     public static final String MIME_TYPE_ALL = "*/*";
63
64     private static final String DIR_TYPE_IMAGE = "vnd.android.cursor.dir/image";
65     private static final String DIR_TYPE_VIDEO = "vnd.android.cursor.dir/video";
66
67     private static final String PREFIX_PHOTO_EDITOR_UPDATE = "editor-update-";
68     private static final String PREFIX_HAS_PHOTO_EDITOR = "has-editor-";
69
70     private static final String KEY_CAMERA_UPDATE = "camera-update";
71     private static final String KEY_HAS_CAMERA = "has-camera";
72
73     private static float sPixelDensity = -1f;
74     private static boolean sCameraAvailableInitialized = false;
75     private static boolean sCameraAvailable;
76
77     public static void initialize(Context context) {
78         DisplayMetrics metrics = new DisplayMetrics();
79         WindowManager wm = (WindowManager)
80                 context.getSystemService(Context.WINDOW_SERVICE);
81         wm.getDefaultDisplay().getMetrics(metrics);
82         sPixelDensity = metrics.density;
83         Resources r = context.getResources();
84         TiledScreenNail.setPlaceholderColor(r.getColor(
85                 R.color.bitmap_screennail_placeholder));
86         initializeThumbnailSizes(metrics, r);
87     }
88
89     private static void initializeThumbnailSizes(DisplayMetrics metrics, Resources r) {
90         int maxPixels = Math.max(metrics.heightPixels, metrics.widthPixels);
91
92         // For screen-nails, we never need to completely fill the screen
93         MediaItem.setThumbnailSizes(maxPixels / 2, maxPixels / 5);
94         TiledScreenNail.setMaxSide(maxPixels / 2);
95     }
96
97     public static float[] intColorToFloatARGBArray(int from) {
98         return new float[] {
99             Color.alpha(from) / 255f,
100             Color.red(from) / 255f,
101             Color.green(from) / 255f,
102             Color.blue(from) / 255f
103         };
104     }
105
106     public static float dpToPixel(float dp) {
107         return sPixelDensity * dp;
108     }
109
110     public static int dpToPixel(int dp) {
111         return Math.round(dpToPixel((float) dp));
112     }
113
114     public static int meterToPixel(float meter) {
115         // 1 meter = 39.37 inches, 1 inch = 160 dp.
116         return Math.round(dpToPixel(meter * 39.37f * 160));
117     }
118
119     public static byte[] getBytes(String in) {
120         byte[] result = new byte[in.length() * 2];
121         int output = 0;
122         for (char ch : in.toCharArray()) {
123             result[output++] = (byte) (ch & 0xFF);
124             result[output++] = (byte) (ch >> 8);
125         }
126         return result;
127     }
128
129     // Below are used the detect using database in the render thread. It only
130     // works most of the time, but that's ok because it's for debugging only.
131
132     private static volatile Thread sCurrentThread;
133     private static volatile boolean sWarned;
134
135     public static void setRenderThread() {
136         sCurrentThread = Thread.currentThread();
137     }
138
139     public static void assertNotInRenderThread() {
140         if (!sWarned) {
141             if (Thread.currentThread() == sCurrentThread) {
142                 sWarned = true;
143                 Log.w(TAG, new Throwable("Should not do this in render thread"));
144             }
145         }
146     }
147
148     private static final double RAD_PER_DEG = Math.PI / 180.0;
149     private static final double EARTH_RADIUS_METERS = 6367000.0;
150
151     public static double fastDistanceMeters(double latRad1, double lngRad1,
152             double latRad2, double lngRad2) {
153        if ((Math.abs(latRad1 - latRad2) > RAD_PER_DEG)
154              || (Math.abs(lngRad1 - lngRad2) > RAD_PER_DEG)) {
155            return accurateDistanceMeters(latRad1, lngRad1, latRad2, lngRad2);
156        }
157        // Approximate sin(x) = x.
158        double sineLat = (latRad1 - latRad2);
159
160        // Approximate sin(x) = x.
161        double sineLng = (lngRad1 - lngRad2);
162
163        // Approximate cos(lat1) * cos(lat2) using
164        // cos((lat1 + lat2)/2) ^ 2
165        double cosTerms = Math.cos((latRad1 + latRad2) / 2.0);
166        cosTerms = cosTerms * cosTerms;
167        double trigTerm = sineLat * sineLat + cosTerms * sineLng * sineLng;
168        trigTerm = Math.sqrt(trigTerm);
169
170        // Approximate arcsin(x) = x
171        return EARTH_RADIUS_METERS * trigTerm;
172     }
173
174     public static double accurateDistanceMeters(double lat1, double lng1,
175             double lat2, double lng2) {
176         double dlat = Math.sin(0.5 * (lat2 - lat1));
177         double dlng = Math.sin(0.5 * (lng2 - lng1));
178         double x = dlat * dlat + dlng * dlng * Math.cos(lat1) * Math.cos(lat2);
179         return (2 * Math.atan2(Math.sqrt(x), Math.sqrt(Math.max(0.0,
180                 1.0 - x)))) * EARTH_RADIUS_METERS;
181     }
182
183
184     public static final double toMile(double meter) {
185         return meter / 1609;
186     }
187
188     // For debugging, it will block the caller for timeout millis.
189     public static void fakeBusy(JobContext jc, int timeout) {
190         final ConditionVariable cv = new ConditionVariable();
191         jc.setCancelListener(new CancelListener() {
192             @Override
193             public void onCancel() {
194                 cv.open();
195             }
196         });
197         cv.block(timeout);
198         jc.setCancelListener(null);
199     }
200
201     public static boolean isEditorAvailable(Context context, String mimeType) {
202         int version = PackagesMonitor.getPackagesVersion(context);
203
204         String updateKey = PREFIX_PHOTO_EDITOR_UPDATE + mimeType;
205         String hasKey = PREFIX_HAS_PHOTO_EDITOR + mimeType;
206
207         SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
208         if (prefs.getInt(updateKey, 0) != version) {
209             PackageManager packageManager = context.getPackageManager();
210             List<ResolveInfo> infos = packageManager.queryIntentActivities(
211                     new Intent(Intent.ACTION_EDIT).setType(mimeType), 0);
212             prefs.edit().putInt(updateKey, version)
213                         .putBoolean(hasKey, !infos.isEmpty())
214                         .commit();
215         }
216
217         return prefs.getBoolean(hasKey, true);
218     }
219
220     public static boolean isAnyCameraAvailable(Context context) {
221         int version = PackagesMonitor.getPackagesVersion(context);
222         SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
223         if (prefs.getInt(KEY_CAMERA_UPDATE, 0) != version) {
224             PackageManager packageManager = context.getPackageManager();
225             List<ResolveInfo> infos = packageManager.queryIntentActivities(
226                     new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA), 0);
227             prefs.edit().putInt(KEY_CAMERA_UPDATE, version)
228                         .putBoolean(KEY_HAS_CAMERA, !infos.isEmpty())
229                         .commit();
230         }
231         return prefs.getBoolean(KEY_HAS_CAMERA, true);
232     }
233
234     public static boolean isCameraAvailable(Context context) {
235         if (sCameraAvailableInitialized) return sCameraAvailable;
236         PackageManager pm = context.getPackageManager();
237         ComponentName name = new ComponentName(context, CAMERA_LAUNCHER_NAME);
238         int state = pm.getComponentEnabledSetting(name);
239         sCameraAvailableInitialized = true;
240         sCameraAvailable =
241             (state == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)
242              || (state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
243         return sCameraAvailable;
244     }
245
246     public static void startCameraActivity(Context context) {
247         Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA)
248                 .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
249                         | Intent.FLAG_ACTIVITY_NEW_TASK);
250         context.startActivity(intent);
251     }
252
253     public static void startGalleryActivity(Context context) {
254         Intent intent = new Intent(context, Gallery.class)
255                 .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
256                 | Intent.FLAG_ACTIVITY_NEW_TASK);
257         context.startActivity(intent);
258     }
259
260     public static boolean isValidLocation(double latitude, double longitude) {
261         // TODO: change || to && after we fix the default location issue
262         return (latitude != MediaItem.INVALID_LATLNG || longitude != MediaItem.INVALID_LATLNG);
263     }
264
265     public static String formatLatitudeLongitude(String format, double latitude,
266             double longitude) {
267         // We need to specify the locale otherwise it may go wrong in some language
268         // (e.g. Locale.FRENCH)
269         return String.format(Locale.ENGLISH, format, latitude, longitude);
270     }
271
272     public static void showOnMap(Context context, double latitude, double longitude) {
273         try {
274             // We don't use "geo:latitude,longitude" because it only centers
275             // the MapView to the specified location, but we need a marker
276             // for further operations (routing to/from).
277             // The q=(lat, lng) syntax is suggested by geo-team.
278             String uri = formatLatitudeLongitude("http://maps.google.com/maps?f=q&q=(%f,%f)",
279                     latitude, longitude);
280             ComponentName compName = new ComponentName(MAPS_PACKAGE_NAME,
281                     MAPS_CLASS_NAME);
282             Intent mapsIntent = new Intent(Intent.ACTION_VIEW,
283                     Uri.parse(uri)).setComponent(compName);
284             context.startActivity(mapsIntent);
285         } catch (ActivityNotFoundException e) {
286             // Use the "geo intent" if no GMM is installed
287             Log.e(TAG, "GMM activity not found!", e);
288             String url = formatLatitudeLongitude("geo:%f,%f", latitude, longitude);
289             Intent mapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
290             context.startActivity(mapsIntent);
291         }
292     }
293
294     public static void setViewPointMatrix(
295             float matrix[], float x, float y, float z) {
296         // The matrix is
297         // -z,  0,  x,  0
298         //  0, -z,  y,  0
299         //  0,  0,  1,  0
300         //  0,  0,  1, -z
301         Arrays.fill(matrix, 0, 16, 0);
302         matrix[0] = matrix[5] = matrix[15] = -z;
303         matrix[8] = x;
304         matrix[9] = y;
305         matrix[10] = matrix[11] = 1;
306     }
307
308     public static int getBucketId(String path) {
309         return path.toLowerCase().hashCode();
310     }
311
312     // Returns a (localized) string for the given duration (in seconds).
313     public static String formatDuration(final Context context, int duration) {
314         int h = duration / 3600;
315         int m = (duration - h * 3600) / 60;
316         int s = duration - (h * 3600 + m * 60);
317         String durationValue;
318         if (h == 0) {
319             durationValue = String.format(context.getString(R.string.details_ms), m, s);
320         } else {
321             durationValue = String.format(context.getString(R.string.details_hms), h, m, s);
322         }
323         return durationValue;
324     }
325
326     @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB)
327     public static int determineTypeBits(Context context, Intent intent) {
328         int typeBits = 0;
329         String type = intent.resolveType(context);
330
331         if (MIME_TYPE_ALL.equals(type)) {
332             typeBits = DataManager.INCLUDE_ALL;
333         } else if (MIME_TYPE_IMAGE.equals(type) ||
334                 DIR_TYPE_IMAGE.equals(type)) {
335             typeBits = DataManager.INCLUDE_IMAGE;
336         } else if (MIME_TYPE_VIDEO.equals(type) ||
337                 DIR_TYPE_VIDEO.equals(type)) {
338             typeBits = DataManager.INCLUDE_VIDEO;
339         } else {
340             typeBits = DataManager.INCLUDE_ALL;
341         }
342
343         if (ApiHelper.HAS_INTENT_EXTRA_LOCAL_ONLY) {
344             if (intent.getBooleanExtra(Intent.EXTRA_LOCAL_ONLY, false)) {
345                 typeBits |= DataManager.INCLUDE_LOCAL_ONLY;
346             }
347         }
348
349         return typeBits;
350     }
351
352     public static int getSelectionModePrompt(int typeBits) {
353         if ((typeBits & DataManager.INCLUDE_VIDEO) != 0) {
354             return (typeBits & DataManager.INCLUDE_IMAGE) == 0
355                     ? R.string.select_video
356                     : R.string.select_item;
357         }
358         return R.string.select_image;
359     }
360
361     public static boolean hasSpaceForSize(long size) {
362         String state = Environment.getExternalStorageState();
363         if (!Environment.MEDIA_MOUNTED.equals(state)) {
364             return false;
365         }
366
367         String path = Environment.getExternalStorageDirectory().getPath();
368         try {
369             StatFs stat = new StatFs(path);
370             return stat.getAvailableBlocks() * (long) stat.getBlockSize() > size;
371         } catch (Exception e) {
372             Log.i(TAG, "Fail to access external storage", e);
373         }
374         return false;
375     }
376
377     public static boolean isPanorama(MediaItem item) {
378         if (item == null) return false;
379         int w = item.getWidth();
380         int h = item.getHeight();
381         return (h > 0 && w / h >= 2);
382     }
383 }