OSDN Git Service

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