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.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;
48 import java.util.Arrays;
49 import java.util.List;
50 import java.util.Locale;
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";
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";
64 private static final String PREFIX_PHOTO_EDITOR_UPDATE = "editor-update-";
65 private static final String PREFIX_HAS_PHOTO_EDITOR = "has-editor-";
67 private static final String KEY_CAMERA_UPDATE = "camera-update";
68 private static final String KEY_HAS_CAMERA = "has-camera";
70 private static float sPixelDensity = -1f;
71 private static boolean sCameraAvailableInitialized = false;
72 private static boolean sCameraAvailable;
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;
82 Resources r = context.getResources();
83 BitmapScreenNail.setPlaceholderColor(r.getColor(
84 R.color.bitmap_screennail_placeholder));
87 public static float[] intColorToFloatARGBArray(int from) {
89 Color.alpha(from) / 255f,
90 Color.red(from) / 255f,
91 Color.green(from) / 255f,
92 Color.blue(from) / 255f
96 public static float dpToPixel(float dp) {
97 return sPixelDensity * dp;
100 public static int dpToPixel(int dp) {
101 return Math.round(dpToPixel((float) dp));
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));
109 public static byte[] getBytes(String in) {
110 byte[] result = new byte[in.length() * 2];
112 for (char ch : in.toCharArray()) {
113 result[output++] = (byte) (ch & 0xFF);
114 result[output++] = (byte) (ch >> 8);
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.
122 private static volatile Thread sCurrentThread;
123 private static volatile boolean sWarned;
125 public static void setRenderThread() {
126 sCurrentThread = Thread.currentThread();
129 public static void assertNotInRenderThread() {
131 if (Thread.currentThread() == sCurrentThread) {
133 Log.w(TAG, new Throwable("Should not do this in render thread"));
138 private static final double RAD_PER_DEG = Math.PI / 180.0;
139 private static final double EARTH_RADIUS_METERS = 6367000.0;
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);
147 // Approximate sin(x) = x.
148 double sineLat = (latRad1 - latRad2);
150 // Approximate sin(x) = x.
151 double sineLng = (lngRad1 - lngRad2);
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);
160 // Approximate arcsin(x) = x
161 return EARTH_RADIUS_METERS * trigTerm;
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;
174 public static final double toMile(double meter) {
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() {
183 public void onCancel() {
188 jc.setCancelListener(null);
191 public static boolean isEditorAvailable(Context context, String mimeType) {
192 int version = PackagesMonitor.getPackagesVersion(context);
194 String updateKey = PREFIX_PHOTO_EDITOR_UPDATE + mimeType;
195 String hasKey = PREFIX_HAS_PHOTO_EDITOR + mimeType;
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())
207 return prefs.getBoolean(hasKey, true);
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())
221 return prefs.getBoolean(KEY_HAS_CAMERA, true);
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;
231 (state == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)
232 || (state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
233 return sCameraAvailable;
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);
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);
248 public static String formatLatitudeLongitude(String format, double latitude,
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);
255 public static void showOnMap(Context context, double latitude, double longitude) {
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,
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);
277 public static void setViewPointMatrix(
278 float matrix[], float x, float y, float z) {
284 Arrays.fill(matrix, 0, 16, 0);
285 matrix[0] = matrix[5] = matrix[15] = -z;
288 matrix[10] = matrix[11] = 1;
291 public static int getBucketId(String path) {
292 return path.toLowerCase().hashCode();
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;
302 durationValue = String.format(context.getString(R.string.details_ms), m, s);
304 durationValue = String.format(context.getString(R.string.details_hms), h, m, s);
306 return durationValue;
309 @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB)
310 public static int determineTypeBits(Context context, Intent intent) {
312 String type = intent.resolveType(context);
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;
323 typeBits = DataManager.INCLUDE_ALL;
326 if (ApiHelper.HAS_INTENT_EXTRA_LOCAL_ONLY) {
327 if (intent.getBooleanExtra(Intent.EXTRA_LOCAL_ONLY, false)) {
328 typeBits |= DataManager.INCLUDE_LOCAL_ONLY;
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;
341 return R.string.select_image;
344 public static boolean hasSpaceForSize(long size) {
345 String state = Environment.getExternalStorageState();
346 if (!Environment.MEDIA_MOUNTED.equals(state)) {
350 String path = Environment.getExternalStorageDirectory().getPath();
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);
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);