OSDN Git Service

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