2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.gallery3d.util;
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;
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;
49 import java.util.Arrays;
50 import java.util.List;
51 import java.util.Locale;
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";
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_PANORAMA = "application/vnd.google.panorama360+jpg";
62 public static final String MIME_TYPE_ALL = "*/*";
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";
67 private static final String PREFIX_PHOTO_EDITOR_UPDATE = "editor-update-";
68 private static final String PREFIX_HAS_PHOTO_EDITOR = "has-editor-";
70 private static final String KEY_CAMERA_UPDATE = "camera-update";
71 private static final String KEY_HAS_CAMERA = "has-camera";
73 private static float sPixelDensity = -1f;
74 private static boolean sCameraAvailableInitialized = false;
75 private static boolean sCameraAvailable;
77 public static void initialize(Context context) {
78 if (sPixelDensity < 0) {
79 DisplayMetrics metrics = new DisplayMetrics();
80 WindowManager wm = (WindowManager)
81 context.getSystemService(Context.WINDOW_SERVICE);
82 wm.getDefaultDisplay().getMetrics(metrics);
83 sPixelDensity = metrics.density;
85 Resources r = context.getResources();
86 BitmapScreenNail.setPlaceholderColor(r.getColor(
87 R.color.bitmap_screennail_placeholder));
90 public static float[] intColorToFloatARGBArray(int from) {
92 Color.alpha(from) / 255f,
93 Color.red(from) / 255f,
94 Color.green(from) / 255f,
95 Color.blue(from) / 255f
99 public static float dpToPixel(float dp) {
100 return sPixelDensity * dp;
103 public static int dpToPixel(int dp) {
104 return Math.round(dpToPixel((float) dp));
107 public static int meterToPixel(float meter) {
108 // 1 meter = 39.37 inches, 1 inch = 160 dp.
109 return Math.round(dpToPixel(meter * 39.37f * 160));
112 public static byte[] getBytes(String in) {
113 byte[] result = new byte[in.length() * 2];
115 for (char ch : in.toCharArray()) {
116 result[output++] = (byte) (ch & 0xFF);
117 result[output++] = (byte) (ch >> 8);
122 // Below are used the detect using database in the render thread. It only
123 // works most of the time, but that's ok because it's for debugging only.
125 private static volatile Thread sCurrentThread;
126 private static volatile boolean sWarned;
128 public static void setRenderThread() {
129 sCurrentThread = Thread.currentThread();
132 public static void assertNotInRenderThread() {
134 if (Thread.currentThread() == sCurrentThread) {
136 Log.w(TAG, new Throwable("Should not do this in render thread"));
141 private static final double RAD_PER_DEG = Math.PI / 180.0;
142 private static final double EARTH_RADIUS_METERS = 6367000.0;
144 public static double fastDistanceMeters(double latRad1, double lngRad1,
145 double latRad2, double lngRad2) {
146 if ((Math.abs(latRad1 - latRad2) > RAD_PER_DEG)
147 || (Math.abs(lngRad1 - lngRad2) > RAD_PER_DEG)) {
148 return accurateDistanceMeters(latRad1, lngRad1, latRad2, lngRad2);
150 // Approximate sin(x) = x.
151 double sineLat = (latRad1 - latRad2);
153 // Approximate sin(x) = x.
154 double sineLng = (lngRad1 - lngRad2);
156 // Approximate cos(lat1) * cos(lat2) using
157 // cos((lat1 + lat2)/2) ^ 2
158 double cosTerms = Math.cos((latRad1 + latRad2) / 2.0);
159 cosTerms = cosTerms * cosTerms;
160 double trigTerm = sineLat * sineLat + cosTerms * sineLng * sineLng;
161 trigTerm = Math.sqrt(trigTerm);
163 // Approximate arcsin(x) = x
164 return EARTH_RADIUS_METERS * trigTerm;
167 public static double accurateDistanceMeters(double lat1, double lng1,
168 double lat2, double lng2) {
169 double dlat = Math.sin(0.5 * (lat2 - lat1));
170 double dlng = Math.sin(0.5 * (lng2 - lng1));
171 double x = dlat * dlat + dlng * dlng * Math.cos(lat1) * Math.cos(lat2);
172 return (2 * Math.atan2(Math.sqrt(x), Math.sqrt(Math.max(0.0,
173 1.0 - x)))) * EARTH_RADIUS_METERS;
177 public static final double toMile(double meter) {
181 // For debugging, it will block the caller for timeout millis.
182 public static void fakeBusy(JobContext jc, int timeout) {
183 final ConditionVariable cv = new ConditionVariable();
184 jc.setCancelListener(new CancelListener() {
186 public void onCancel() {
191 jc.setCancelListener(null);
194 public static boolean isEditorAvailable(Context context, String mimeType) {
195 int version = PackagesMonitor.getPackagesVersion(context);
197 String updateKey = PREFIX_PHOTO_EDITOR_UPDATE + mimeType;
198 String hasKey = PREFIX_HAS_PHOTO_EDITOR + mimeType;
200 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
201 if (prefs.getInt(updateKey, 0) != version) {
202 PackageManager packageManager = context.getPackageManager();
203 List<ResolveInfo> infos = packageManager.queryIntentActivities(
204 new Intent(Intent.ACTION_EDIT).setType(mimeType), 0);
205 prefs.edit().putInt(updateKey, version)
206 .putBoolean(hasKey, !infos.isEmpty())
210 return prefs.getBoolean(hasKey, true);
213 public static boolean isAnyCameraAvailable(Context context) {
214 int version = PackagesMonitor.getPackagesVersion(context);
215 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
216 if (prefs.getInt(KEY_CAMERA_UPDATE, 0) != version) {
217 PackageManager packageManager = context.getPackageManager();
218 List<ResolveInfo> infos = packageManager.queryIntentActivities(
219 new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA), 0);
220 prefs.edit().putInt(KEY_CAMERA_UPDATE, version)
221 .putBoolean(KEY_HAS_CAMERA, !infos.isEmpty())
224 return prefs.getBoolean(KEY_HAS_CAMERA, true);
227 public static boolean isCameraAvailable(Context context) {
228 if (sCameraAvailableInitialized) return sCameraAvailable;
229 PackageManager pm = context.getPackageManager();
230 ComponentName name = new ComponentName(context, CAMERA_LAUNCHER_NAME);
231 int state = pm.getComponentEnabledSetting(name);
232 sCameraAvailableInitialized = true;
234 (state == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)
235 || (state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
236 return sCameraAvailable;
239 public static void startCameraActivity(Context context) {
240 Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA)
241 .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
242 | Intent.FLAG_ACTIVITY_NEW_TASK);
243 context.startActivity(intent);
246 public static void startGalleryActivity(Context context) {
247 Intent intent = new Intent(context, Gallery.class);
248 context.startActivity(intent);
251 public static boolean isValidLocation(double latitude, double longitude) {
252 // TODO: change || to && after we fix the default location issue
253 return (latitude != MediaItem.INVALID_LATLNG || longitude != MediaItem.INVALID_LATLNG);
256 public static String formatLatitudeLongitude(String format, double latitude,
258 // We need to specify the locale otherwise it may go wrong in some language
259 // (e.g. Locale.FRENCH)
260 return String.format(Locale.ENGLISH, format, latitude, longitude);
263 public static void showOnMap(Context context, double latitude, double longitude) {
265 // We don't use "geo:latitude,longitude" because it only centers
266 // the MapView to the specified location, but we need a marker
267 // for further operations (routing to/from).
268 // The q=(lat, lng) syntax is suggested by geo-team.
269 String uri = formatLatitudeLongitude("http://maps.google.com/maps?f=q&q=(%f,%f)",
270 latitude, longitude);
271 ComponentName compName = new ComponentName(MAPS_PACKAGE_NAME,
273 Intent mapsIntent = new Intent(Intent.ACTION_VIEW,
274 Uri.parse(uri)).setComponent(compName);
275 context.startActivity(mapsIntent);
276 } catch (ActivityNotFoundException e) {
277 // Use the "geo intent" if no GMM is installed
278 Log.e(TAG, "GMM activity not found!", e);
279 String url = formatLatitudeLongitude("geo:%f,%f", latitude, longitude);
280 Intent mapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
281 context.startActivity(mapsIntent);
285 public static void setViewPointMatrix(
286 float matrix[], float x, float y, float z) {
292 Arrays.fill(matrix, 0, 16, 0);
293 matrix[0] = matrix[5] = matrix[15] = -z;
296 matrix[10] = matrix[11] = 1;
299 public static int getBucketId(String path) {
300 return path.toLowerCase().hashCode();
303 // Returns a (localized) string for the given duration (in seconds).
304 public static String formatDuration(final Context context, int duration) {
305 int h = duration / 3600;
306 int m = (duration - h * 3600) / 60;
307 int s = duration - (h * 3600 + m * 60);
308 String durationValue;
310 durationValue = String.format(context.getString(R.string.details_ms), m, s);
312 durationValue = String.format(context.getString(R.string.details_hms), h, m, s);
314 return durationValue;
317 @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB)
318 public static int determineTypeBits(Context context, Intent intent) {
320 String type = intent.resolveType(context);
322 if (MIME_TYPE_ALL.equals(type)) {
323 typeBits = DataManager.INCLUDE_ALL;
324 } else if (MIME_TYPE_IMAGE.equals(type) ||
325 DIR_TYPE_IMAGE.equals(type)) {
326 typeBits = DataManager.INCLUDE_IMAGE;
327 } else if (MIME_TYPE_VIDEO.equals(type) ||
328 DIR_TYPE_VIDEO.equals(type)) {
329 typeBits = DataManager.INCLUDE_VIDEO;
331 typeBits = DataManager.INCLUDE_ALL;
334 if (ApiHelper.HAS_INTENT_EXTRA_LOCAL_ONLY) {
335 if (intent.getBooleanExtra(Intent.EXTRA_LOCAL_ONLY, false)) {
336 typeBits |= DataManager.INCLUDE_LOCAL_ONLY;
343 public static int getSelectionModePrompt(int typeBits) {
344 if ((typeBits & DataManager.INCLUDE_VIDEO) != 0) {
345 return (typeBits & DataManager.INCLUDE_IMAGE) == 0
346 ? R.string.select_video
347 : R.string.select_item;
349 return R.string.select_image;
352 public static boolean hasSpaceForSize(long size) {
353 String state = Environment.getExternalStorageState();
354 if (!Environment.MEDIA_MOUNTED.equals(state)) {
358 String path = Environment.getExternalStorageDirectory().getPath();
360 StatFs stat = new StatFs(path);
361 return stat.getAvailableBlocks() * (long) stat.getBlockSize() > size;
362 } catch (Exception e) {
363 Log.i(TAG, "Fail to access external storage", e);
368 public static boolean isPanorama(MediaItem item) {
369 if (item == null) return false;
370 int w = item.getWidth();
371 int h = item.getHeight();
372 return (h > 0 && w / h >= 2);