OSDN Git Service

am 51ebe5f7: Share only 360-degree panoramas with new MIME type
[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.BitmapScreenNail;
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         BitmapScreenNail.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 minRows = Math.min(r.getInteger(R.integer.album_rows_land),
91                 r.getInteger(R.integer.albumset_rows_land));
92         int maxDimensionPixels = Math.max(metrics.heightPixels, metrics.widthPixels);
93         // Never need to completely fill the screen
94         maxDimensionPixels = maxDimensionPixels * 3/4;
95         MediaItem.setThumbnailSizes(maxDimensionPixels, maxDimensionPixels / minRows);
96         BitmapScreenNail.setMaxSide(maxDimensionPixels);
97     }
98
99     public static boolean isHighResolution(Context context) {
100         DisplayMetrics metrics = new DisplayMetrics();
101         WindowManager wm = (WindowManager)
102                 context.getSystemService(Context.WINDOW_SERVICE);
103         wm.getDefaultDisplay().getMetrics(metrics);
104         return metrics.heightPixels > 2048 ||  metrics.widthPixels > 2048;
105     }
106
107     public static float[] intColorToFloatARGBArray(int from) {
108         return new float[] {
109             Color.alpha(from) / 255f,
110             Color.red(from) / 255f,
111             Color.green(from) / 255f,
112             Color.blue(from) / 255f
113         };
114     }
115
116     public static float dpToPixel(float dp) {
117         return sPixelDensity * dp;
118     }
119
120     public static int dpToPixel(int dp) {
121         return Math.round(dpToPixel((float) dp));
122     }
123
124     public static int meterToPixel(float meter) {
125         // 1 meter = 39.37 inches, 1 inch = 160 dp.
126         return Math.round(dpToPixel(meter * 39.37f * 160));
127     }
128
129     public static byte[] getBytes(String in) {
130         byte[] result = new byte[in.length() * 2];
131         int output = 0;
132         for (char ch : in.toCharArray()) {
133             result[output++] = (byte) (ch & 0xFF);
134             result[output++] = (byte) (ch >> 8);
135         }
136         return result;
137     }
138
139     // Below are used the detect using database in the render thread. It only
140     // works most of the time, but that's ok because it's for debugging only.
141
142     private static volatile Thread sCurrentThread;
143     private static volatile boolean sWarned;
144
145     public static void setRenderThread() {
146         sCurrentThread = Thread.currentThread();
147     }
148
149     public static void assertNotInRenderThread() {
150         if (!sWarned) {
151             if (Thread.currentThread() == sCurrentThread) {
152                 sWarned = true;
153                 Log.w(TAG, new Throwable("Should not do this in render thread"));
154             }
155         }
156     }
157
158     private static final double RAD_PER_DEG = Math.PI / 180.0;
159     private static final double EARTH_RADIUS_METERS = 6367000.0;
160
161     public static double fastDistanceMeters(double latRad1, double lngRad1,
162             double latRad2, double lngRad2) {
163        if ((Math.abs(latRad1 - latRad2) > RAD_PER_DEG)
164              || (Math.abs(lngRad1 - lngRad2) > RAD_PER_DEG)) {
165            return accurateDistanceMeters(latRad1, lngRad1, latRad2, lngRad2);
166        }
167        // Approximate sin(x) = x.
168        double sineLat = (latRad1 - latRad2);
169
170        // Approximate sin(x) = x.
171        double sineLng = (lngRad1 - lngRad2);
172
173        // Approximate cos(lat1) * cos(lat2) using
174        // cos((lat1 + lat2)/2) ^ 2
175        double cosTerms = Math.cos((latRad1 + latRad2) / 2.0);
176        cosTerms = cosTerms * cosTerms;
177        double trigTerm = sineLat * sineLat + cosTerms * sineLng * sineLng;
178        trigTerm = Math.sqrt(trigTerm);
179
180        // Approximate arcsin(x) = x
181        return EARTH_RADIUS_METERS * trigTerm;
182     }
183
184     public static double accurateDistanceMeters(double lat1, double lng1,
185             double lat2, double lng2) {
186         double dlat = Math.sin(0.5 * (lat2 - lat1));
187         double dlng = Math.sin(0.5 * (lng2 - lng1));
188         double x = dlat * dlat + dlng * dlng * Math.cos(lat1) * Math.cos(lat2);
189         return (2 * Math.atan2(Math.sqrt(x), Math.sqrt(Math.max(0.0,
190                 1.0 - x)))) * EARTH_RADIUS_METERS;
191     }
192
193
194     public static final double toMile(double meter) {
195         return meter / 1609;
196     }
197
198     // For debugging, it will block the caller for timeout millis.
199     public static void fakeBusy(JobContext jc, int timeout) {
200         final ConditionVariable cv = new ConditionVariable();
201         jc.setCancelListener(new CancelListener() {
202             @Override
203             public void onCancel() {
204                 cv.open();
205             }
206         });
207         cv.block(timeout);
208         jc.setCancelListener(null);
209     }
210
211     public static boolean isEditorAvailable(Context context, String mimeType) {
212         int version = PackagesMonitor.getPackagesVersion(context);
213
214         String updateKey = PREFIX_PHOTO_EDITOR_UPDATE + mimeType;
215         String hasKey = PREFIX_HAS_PHOTO_EDITOR + mimeType;
216
217         SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
218         if (prefs.getInt(updateKey, 0) != version) {
219             PackageManager packageManager = context.getPackageManager();
220             List<ResolveInfo> infos = packageManager.queryIntentActivities(
221                     new Intent(Intent.ACTION_EDIT).setType(mimeType), 0);
222             prefs.edit().putInt(updateKey, version)
223                         .putBoolean(hasKey, !infos.isEmpty())
224                         .commit();
225         }
226
227         return prefs.getBoolean(hasKey, true);
228     }
229
230     public static boolean isAnyCameraAvailable(Context context) {
231         int version = PackagesMonitor.getPackagesVersion(context);
232         SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
233         if (prefs.getInt(KEY_CAMERA_UPDATE, 0) != version) {
234             PackageManager packageManager = context.getPackageManager();
235             List<ResolveInfo> infos = packageManager.queryIntentActivities(
236                     new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA), 0);
237             prefs.edit().putInt(KEY_CAMERA_UPDATE, version)
238                         .putBoolean(KEY_HAS_CAMERA, !infos.isEmpty())
239                         .commit();
240         }
241         return prefs.getBoolean(KEY_HAS_CAMERA, true);
242     }
243
244     public static boolean isCameraAvailable(Context context) {
245         if (sCameraAvailableInitialized) return sCameraAvailable;
246         PackageManager pm = context.getPackageManager();
247         ComponentName name = new ComponentName(context, CAMERA_LAUNCHER_NAME);
248         int state = pm.getComponentEnabledSetting(name);
249         sCameraAvailableInitialized = true;
250         sCameraAvailable =
251             (state == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)
252              || (state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
253         return sCameraAvailable;
254     }
255
256     public static void startCameraActivity(Context context) {
257         Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA)
258                 .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
259                         | Intent.FLAG_ACTIVITY_NEW_TASK);
260         context.startActivity(intent);
261     }
262
263     public static void startGalleryActivity(Context context) {
264         Intent intent = new Intent(context, Gallery.class);
265         context.startActivity(intent);
266     }
267
268     public static boolean isValidLocation(double latitude, double longitude) {
269         // TODO: change || to && after we fix the default location issue
270         return (latitude != MediaItem.INVALID_LATLNG || longitude != MediaItem.INVALID_LATLNG);
271     }
272
273     public static String formatLatitudeLongitude(String format, double latitude,
274             double longitude) {
275         // We need to specify the locale otherwise it may go wrong in some language
276         // (e.g. Locale.FRENCH)
277         return String.format(Locale.ENGLISH, format, latitude, longitude);
278     }
279
280     public static void showOnMap(Context context, double latitude, double longitude) {
281         try {
282             // We don't use "geo:latitude,longitude" because it only centers
283             // the MapView to the specified location, but we need a marker
284             // for further operations (routing to/from).
285             // The q=(lat, lng) syntax is suggested by geo-team.
286             String uri = formatLatitudeLongitude("http://maps.google.com/maps?f=q&q=(%f,%f)",
287                     latitude, longitude);
288             ComponentName compName = new ComponentName(MAPS_PACKAGE_NAME,
289                     MAPS_CLASS_NAME);
290             Intent mapsIntent = new Intent(Intent.ACTION_VIEW,
291                     Uri.parse(uri)).setComponent(compName);
292             context.startActivity(mapsIntent);
293         } catch (ActivityNotFoundException e) {
294             // Use the "geo intent" if no GMM is installed
295             Log.e(TAG, "GMM activity not found!", e);
296             String url = formatLatitudeLongitude("geo:%f,%f", latitude, longitude);
297             Intent mapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
298             context.startActivity(mapsIntent);
299         }
300     }
301
302     public static void setViewPointMatrix(
303             float matrix[], float x, float y, float z) {
304         // The matrix is
305         // -z,  0,  x,  0
306         //  0, -z,  y,  0
307         //  0,  0,  1,  0
308         //  0,  0,  1, -z
309         Arrays.fill(matrix, 0, 16, 0);
310         matrix[0] = matrix[5] = matrix[15] = -z;
311         matrix[8] = x;
312         matrix[9] = y;
313         matrix[10] = matrix[11] = 1;
314     }
315
316     public static int getBucketId(String path) {
317         return path.toLowerCase().hashCode();
318     }
319
320     // Returns a (localized) string for the given duration (in seconds).
321     public static String formatDuration(final Context context, int duration) {
322         int h = duration / 3600;
323         int m = (duration - h * 3600) / 60;
324         int s = duration - (h * 3600 + m * 60);
325         String durationValue;
326         if (h == 0) {
327             durationValue = String.format(context.getString(R.string.details_ms), m, s);
328         } else {
329             durationValue = String.format(context.getString(R.string.details_hms), h, m, s);
330         }
331         return durationValue;
332     }
333
334     @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB)
335     public static int determineTypeBits(Context context, Intent intent) {
336         int typeBits = 0;
337         String type = intent.resolveType(context);
338
339         if (MIME_TYPE_ALL.equals(type)) {
340             typeBits = DataManager.INCLUDE_ALL;
341         } else if (MIME_TYPE_IMAGE.equals(type) ||
342                 DIR_TYPE_IMAGE.equals(type)) {
343             typeBits = DataManager.INCLUDE_IMAGE;
344         } else if (MIME_TYPE_VIDEO.equals(type) ||
345                 DIR_TYPE_VIDEO.equals(type)) {
346             typeBits = DataManager.INCLUDE_VIDEO;
347         } else {
348             typeBits = DataManager.INCLUDE_ALL;
349         }
350
351         if (ApiHelper.HAS_INTENT_EXTRA_LOCAL_ONLY) {
352             if (intent.getBooleanExtra(Intent.EXTRA_LOCAL_ONLY, false)) {
353                 typeBits |= DataManager.INCLUDE_LOCAL_ONLY;
354             }
355         }
356
357         return typeBits;
358     }
359
360     public static int getSelectionModePrompt(int typeBits) {
361         if ((typeBits & DataManager.INCLUDE_VIDEO) != 0) {
362             return (typeBits & DataManager.INCLUDE_IMAGE) == 0
363                     ? R.string.select_video
364                     : R.string.select_item;
365         }
366         return R.string.select_image;
367     }
368
369     public static boolean hasSpaceForSize(long size) {
370         String state = Environment.getExternalStorageState();
371         if (!Environment.MEDIA_MOUNTED.equals(state)) {
372             return false;
373         }
374
375         String path = Environment.getExternalStorageDirectory().getPath();
376         try {
377             StatFs stat = new StatFs(path);
378             return stat.getAvailableBlocks() * (long) stat.getBlockSize() > size;
379         } catch (Exception e) {
380             Log.i(TAG, "Fail to access external storage", e);
381         }
382         return false;
383     }
384
385     public static boolean isPanorama(MediaItem item) {
386         if (item == null) return false;
387         int w = item.getWidth();
388         int h = item.getHeight();
389         return (h > 0 && w / h >= 2);
390     }
391 }