OSDN Git Service

am b4e38c9a: Merge "Fix 6213053 Add Help entry point to Gallery (targeted for J relea...
[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.app.Activity;
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.net.Uri;
29 import android.os.ConditionVariable;
30 import android.os.Environment;
31 import android.os.StatFs;
32 import android.preference.PreferenceManager;
33 import android.provider.MediaStore;
34 import android.util.DisplayMetrics;
35 import android.util.Log;
36 import android.view.WindowManager;
37
38 import com.android.gallery3d.R;
39 import com.android.gallery3d.app.PackagesMonitor;
40 import com.android.gallery3d.data.DataManager;
41 import com.android.gallery3d.data.MediaItem;
42 import com.android.gallery3d.util.ThreadPool.CancelListener;
43 import com.android.gallery3d.util.ThreadPool.JobContext;
44
45 import java.util.Arrays;
46 import java.util.List;
47 import java.util.Locale;
48
49 public class GalleryUtils {
50     private static final String TAG = "GalleryUtils";
51     private static final String MAPS_PACKAGE_NAME = "com.google.android.apps.maps";
52     private static final String MAPS_CLASS_NAME = "com.google.android.maps.MapsActivity";
53
54     private static final String MIME_TYPE_IMAGE = "image/*";
55     private static final String MIME_TYPE_VIDEO = "video/*";
56     private static final String MIME_TYPE_ALL = "*/*";
57     private static final String DIR_TYPE_IMAGE = "vnd.android.cursor.dir/image";
58     private static final String DIR_TYPE_VIDEO = "vnd.android.cursor.dir/video";
59
60     private static final String PREFIX_PHOTO_EDITOR_UPDATE = "editor-update-";
61     private static final String PREFIX_HAS_PHOTO_EDITOR = "has-editor-";
62
63     private static final String KEY_CAMERA_UPDATE = "camera-update";
64     private static final String KEY_HAS_CAMERA = "has-camera";
65
66     static float sPixelDensity = -1f;
67
68     public static void initialize(Context context) {
69         if (sPixelDensity < 0) {
70             DisplayMetrics metrics = new DisplayMetrics();
71             WindowManager wm = (WindowManager)
72                     context.getSystemService(Context.WINDOW_SERVICE);
73             wm.getDefaultDisplay().getMetrics(metrics);
74             sPixelDensity = metrics.density;
75         }
76     }
77
78     public static float dpToPixel(float dp) {
79         return sPixelDensity * dp;
80     }
81
82     public static int dpToPixel(int dp) {
83         return Math.round(dpToPixel((float) dp));
84     }
85
86     public static int meterToPixel(float meter) {
87         // 1 meter = 39.37 inches, 1 inch = 160 dp.
88         return Math.round(dpToPixel(meter * 39.37f * 160));
89     }
90
91     public static byte[] getBytes(String in) {
92         byte[] result = new byte[in.length() * 2];
93         int output = 0;
94         for (char ch : in.toCharArray()) {
95             result[output++] = (byte) (ch & 0xFF);
96             result[output++] = (byte) (ch >> 8);
97         }
98         return result;
99     }
100
101     // Below are used the detect using database in the render thread. It only
102     // works most of the time, but that's ok because it's for debugging only.
103
104     private static volatile Thread sCurrentThread;
105     private static volatile boolean sWarned;
106
107     public static void setRenderThread() {
108         sCurrentThread = Thread.currentThread();
109     }
110
111     public static void assertNotInRenderThread() {
112         if (!sWarned) {
113             if (Thread.currentThread() == sCurrentThread) {
114                 sWarned = true;
115                 Log.w(TAG, new Throwable("Should not do this in render thread"));
116             }
117         }
118     }
119
120     private static final double RAD_PER_DEG = Math.PI / 180.0;
121     private static final double EARTH_RADIUS_METERS = 6367000.0;
122
123     public static double fastDistanceMeters(double latRad1, double lngRad1,
124             double latRad2, double lngRad2) {
125        if ((Math.abs(latRad1 - latRad2) > RAD_PER_DEG)
126              || (Math.abs(lngRad1 - lngRad2) > RAD_PER_DEG)) {
127            return accurateDistanceMeters(latRad1, lngRad1, latRad2, lngRad2);
128        }
129        // Approximate sin(x) = x.
130        double sineLat = (latRad1 - latRad2);
131
132        // Approximate sin(x) = x.
133        double sineLng = (lngRad1 - lngRad2);
134
135        // Approximate cos(lat1) * cos(lat2) using
136        // cos((lat1 + lat2)/2) ^ 2
137        double cosTerms = Math.cos((latRad1 + latRad2) / 2.0);
138        cosTerms = cosTerms * cosTerms;
139        double trigTerm = sineLat * sineLat + cosTerms * sineLng * sineLng;
140        trigTerm = Math.sqrt(trigTerm);
141
142        // Approximate arcsin(x) = x
143        return EARTH_RADIUS_METERS * trigTerm;
144     }
145
146     public static double accurateDistanceMeters(double lat1, double lng1,
147             double lat2, double lng2) {
148         double dlat = Math.sin(0.5 * (lat2 - lat1));
149         double dlng = Math.sin(0.5 * (lng2 - lng1));
150         double x = dlat * dlat + dlng * dlng * Math.cos(lat1) * Math.cos(lat2);
151         return (2 * Math.atan2(Math.sqrt(x), Math.sqrt(Math.max(0.0,
152                 1.0 - x)))) * EARTH_RADIUS_METERS;
153     }
154
155
156     public static final double toMile(double meter) {
157         return meter / 1609;
158     }
159
160     // For debugging, it will block the caller for timeout millis.
161     public static void fakeBusy(JobContext jc, int timeout) {
162         final ConditionVariable cv = new ConditionVariable();
163         jc.setCancelListener(new CancelListener() {
164             public void onCancel() {
165                 cv.open();
166             }
167         });
168         cv.block(timeout);
169         jc.setCancelListener(null);
170     }
171
172     public static boolean isEditorAvailable(Context context, String mimeType) {
173         int version = PackagesMonitor.getPackagesVersion(context);
174
175         String updateKey = PREFIX_PHOTO_EDITOR_UPDATE + mimeType;
176         String hasKey = PREFIX_HAS_PHOTO_EDITOR + mimeType;
177
178         SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
179         if (prefs.getInt(updateKey, 0) != version) {
180             PackageManager packageManager = context.getPackageManager();
181             List<ResolveInfo> infos = packageManager.queryIntentActivities(
182                     new Intent(Intent.ACTION_EDIT).setType(mimeType), 0);
183             prefs.edit().putInt(updateKey, version)
184                         .putBoolean(hasKey, !infos.isEmpty())
185                         .commit();
186         }
187
188         return prefs.getBoolean(hasKey, true);
189     }
190
191     public static boolean isCameraAvailable(Context context) {
192         int version = PackagesMonitor.getPackagesVersion(context);
193         SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
194         if (prefs.getInt(KEY_CAMERA_UPDATE, 0) != version) {
195             PackageManager packageManager = context.getPackageManager();
196             List<ResolveInfo> infos = packageManager.queryIntentActivities(
197                     new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA), 0);
198             prefs.edit().putInt(KEY_CAMERA_UPDATE, version)
199                         .putBoolean(KEY_HAS_CAMERA, !infos.isEmpty())
200                         .commit();
201         }
202         return prefs.getBoolean(KEY_HAS_CAMERA, true);
203     }
204
205     public static void startCameraActivity(Context context) {
206         Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA)
207                 .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
208                         | Intent.FLAG_ACTIVITY_NEW_TASK);
209         context.startActivity(intent);
210     }
211
212     public static boolean isValidLocation(double latitude, double longitude) {
213         // TODO: change || to && after we fix the default location issue
214         return (latitude != MediaItem.INVALID_LATLNG || longitude != MediaItem.INVALID_LATLNG);
215     }
216
217     public static String formatLatitudeLongitude(String format, double latitude,
218             double longitude) {
219         // We need to specify the locale otherwise it may go wrong in some language
220         // (e.g. Locale.FRENCH)
221         return String.format(Locale.ENGLISH, format, latitude, longitude);
222     }
223
224     public static void showOnMap(Context context, double latitude, double longitude) {
225         try {
226             // We don't use "geo:latitude,longitude" because it only centers
227             // the MapView to the specified location, but we need a marker
228             // for further operations (routing to/from).
229             // The q=(lat, lng) syntax is suggested by geo-team.
230             String uri = formatLatitudeLongitude("http://maps.google.com/maps?f=q&q=(%f,%f)",
231                     latitude, longitude);
232             ComponentName compName = new ComponentName(MAPS_PACKAGE_NAME,
233                     MAPS_CLASS_NAME);
234             Intent mapsIntent = new Intent(Intent.ACTION_VIEW,
235                     Uri.parse(uri)).setComponent(compName);
236             context.startActivity(mapsIntent);
237         } catch (ActivityNotFoundException e) {
238             // Use the "geo intent" if no GMM is installed
239             Log.e(TAG, "GMM activity not found!", e);
240             String url = formatLatitudeLongitude("geo:%f,%f", latitude, longitude);
241             Intent mapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
242             context.startActivity(mapsIntent);
243         }
244     }
245
246     public static void setViewPointMatrix(
247             float matrix[], float x, float y, float z) {
248         // The matrix is
249         // -z,  0,  x,  0
250         //  0, -z,  y,  0
251         //  0,  0,  1,  0
252         //  0,  0,  1, -z
253         Arrays.fill(matrix, 0, 16, 0);
254         matrix[0] = matrix[5] = matrix[15] = -z;
255         matrix[8] = x;
256         matrix[9] = y;
257         matrix[10] = matrix[11] = 1;
258     }
259
260     public static int getBucketId(String path) {
261         return path.toLowerCase().hashCode();
262     }
263
264     // Returns a (localized) string for the given duration (in seconds).
265     public static String formatDuration(final Context context, int duration) {
266         int h = duration / 3600;
267         int m = (duration - h * 3600) / 60;
268         int s = duration - (h * 3600 + m * 60);
269         String durationValue;
270         if (h == 0) {
271             durationValue = String.format(context.getString(R.string.details_ms), m, s);
272         } else {
273             durationValue = String.format(context.getString(R.string.details_hms), h, m, s);
274         }
275         return durationValue;
276     }
277
278     public static int determineTypeBits(Context context, Intent intent) {
279         int typeBits = 0;
280         String type = intent.resolveType(context);
281
282         if (MIME_TYPE_ALL.equals(type)) {
283             typeBits = DataManager.INCLUDE_ALL;
284         } else if (MIME_TYPE_IMAGE.equals(type) ||
285                 DIR_TYPE_IMAGE.equals(type)) {
286             typeBits = DataManager.INCLUDE_IMAGE;
287         } else if (MIME_TYPE_VIDEO.equals(type) ||
288                 DIR_TYPE_VIDEO.equals(type)) {
289             typeBits = DataManager.INCLUDE_VIDEO;
290         } else {
291             typeBits = DataManager.INCLUDE_ALL;
292         }
293
294         if (intent.getBooleanExtra(Intent.EXTRA_LOCAL_ONLY, false)) {
295             typeBits |= DataManager.INCLUDE_LOCAL_ONLY;
296         }
297
298         return typeBits;
299     }
300
301     public static int getSelectionModePrompt(int typeBits) {
302         if ((typeBits & DataManager.INCLUDE_VIDEO) != 0) {
303             return (typeBits & DataManager.INCLUDE_IMAGE) == 0
304                     ? R.string.select_video
305                     : R.string.select_item;
306         }
307         return R.string.select_image;
308     }
309
310     public static boolean hasSpaceForSize(long size) {
311         String state = Environment.getExternalStorageState();
312         if (!Environment.MEDIA_MOUNTED.equals(state)) {
313             return false;
314         }
315
316         String path = Environment.getExternalStorageDirectory().getPath();
317         try {
318             StatFs stat = new StatFs(path);
319             return stat.getAvailableBlocks() * (long) stat.getBlockSize() > size;
320         } catch (Exception e) {
321             Log.i(TAG, "Fail to access external storage", e);
322         }
323         return false;
324     }
325
326     public static boolean isPanorama(MediaItem item) {
327         if (item == null) return false;
328         int w = item.getWidth();
329         int h = item.getHeight();
330         return (h > 0 && w / h >= 2);
331     }
332 }