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.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;
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;
45 import java.util.Arrays;
46 import java.util.List;
47 import java.util.Locale;
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";
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";
60 private static final String PREFIX_PHOTO_EDITOR_UPDATE = "editor-update-";
61 private static final String PREFIX_HAS_PHOTO_EDITOR = "has-editor-";
63 private static final String KEY_CAMERA_UPDATE = "camera-update";
64 private static final String KEY_HAS_CAMERA = "has-camera";
66 private static Context sContext;
69 static float sPixelDensity = -1f;
71 public static void initialize(Context context) {
73 if (sPixelDensity < 0) {
74 DisplayMetrics metrics = new DisplayMetrics();
75 WindowManager wm = (WindowManager)
76 context.getSystemService(Context.WINDOW_SERVICE);
77 wm.getDefaultDisplay().getMetrics(metrics);
78 sPixelDensity = metrics.density;
82 public static float dpToPixel(float dp) {
83 return sPixelDensity * dp;
86 public static int dpToPixel(int dp) {
87 return Math.round(dpToPixel((float) dp));
90 public static int meterToPixel(float meter) {
91 // 1 meter = 39.37 inches, 1 inch = 160 dp.
92 return Math.round(dpToPixel(meter * 39.37f * 160));
95 public static byte[] getBytes(String in) {
96 byte[] result = new byte[in.length() * 2];
98 for (char ch : in.toCharArray()) {
99 result[output++] = (byte) (ch & 0xFF);
100 result[output++] = (byte) (ch >> 8);
105 // Below are used the detect using database in the render thread. It only
106 // works most of the time, but that's ok because it's for debugging only.
108 private static volatile Thread sCurrentThread;
109 private static volatile boolean sWarned;
111 public static void setRenderThread() {
112 sCurrentThread = Thread.currentThread();
115 public static void assertNotInRenderThread() {
117 if (Thread.currentThread() == sCurrentThread) {
119 Log.w(TAG, new Throwable("Should not do this in render thread"));
124 private static final double RAD_PER_DEG = Math.PI / 180.0;
125 private static final double EARTH_RADIUS_METERS = 6367000.0;
127 public static double fastDistanceMeters(double latRad1, double lngRad1,
128 double latRad2, double lngRad2) {
129 if ((Math.abs(latRad1 - latRad2) > RAD_PER_DEG)
130 || (Math.abs(lngRad1 - lngRad2) > RAD_PER_DEG)) {
131 return accurateDistanceMeters(latRad1, lngRad1, latRad2, lngRad2);
133 // Approximate sin(x) = x.
134 double sineLat = (latRad1 - latRad2);
136 // Approximate sin(x) = x.
137 double sineLng = (lngRad1 - lngRad2);
139 // Approximate cos(lat1) * cos(lat2) using
140 // cos((lat1 + lat2)/2) ^ 2
141 double cosTerms = Math.cos((latRad1 + latRad2) / 2.0);
142 cosTerms = cosTerms * cosTerms;
143 double trigTerm = sineLat * sineLat + cosTerms * sineLng * sineLng;
144 trigTerm = Math.sqrt(trigTerm);
146 // Approximate arcsin(x) = x
147 return EARTH_RADIUS_METERS * trigTerm;
150 public static double accurateDistanceMeters(double lat1, double lng1,
151 double lat2, double lng2) {
152 double dlat = Math.sin(0.5 * (lat2 - lat1));
153 double dlng = Math.sin(0.5 * (lng2 - lng1));
154 double x = dlat * dlat + dlng * dlng * Math.cos(lat1) * Math.cos(lat2);
155 return (2 * Math.atan2(Math.sqrt(x), Math.sqrt(Math.max(0.0,
156 1.0 - x)))) * EARTH_RADIUS_METERS;
160 public static final double toMile(double meter) {
164 // For debugging, it will block the caller for timeout millis.
165 public static void fakeBusy(JobContext jc, int timeout) {
166 final ConditionVariable cv = new ConditionVariable();
167 jc.setCancelListener(new CancelListener() {
168 public void onCancel() {
173 jc.setCancelListener(null);
176 public static boolean isEditorAvailable(Context context, String mimeType) {
177 int version = PackagesMonitor.getPackagesVersion(context);
179 String updateKey = PREFIX_PHOTO_EDITOR_UPDATE + mimeType;
180 String hasKey = PREFIX_HAS_PHOTO_EDITOR + mimeType;
182 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
183 if (prefs.getInt(updateKey, 0) != version) {
184 PackageManager packageManager = context.getPackageManager();
185 List<ResolveInfo> infos = packageManager.queryIntentActivities(
186 new Intent(Intent.ACTION_EDIT).setType(mimeType), 0);
187 prefs.edit().putInt(updateKey, version)
188 .putBoolean(hasKey, !infos.isEmpty())
192 return prefs.getBoolean(hasKey, true);
195 public static boolean isCameraAvailable(Context context) {
196 int version = PackagesMonitor.getPackagesVersion(context);
197 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
198 if (prefs.getInt(KEY_CAMERA_UPDATE, 0) != version) {
199 PackageManager packageManager = context.getPackageManager();
200 List<ResolveInfo> infos = packageManager.queryIntentActivities(
201 new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA), 0);
202 prefs.edit().putInt(KEY_CAMERA_UPDATE, version)
203 .putBoolean(KEY_HAS_CAMERA, !infos.isEmpty())
206 return prefs.getBoolean(KEY_HAS_CAMERA, true);
209 public static void startCameraActivity(Context context) {
210 Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA)
211 .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
212 | Intent.FLAG_ACTIVITY_NEW_TASK);
213 context.startActivity(intent);
216 public static boolean isValidLocation(double latitude, double longitude) {
217 // TODO: change || to && after we fix the default location issue
218 return (latitude != MediaItem.INVALID_LATLNG || longitude != MediaItem.INVALID_LATLNG);
221 public static String formatLatitudeLongitude(String format, double latitude,
223 // We need to specify the locale otherwise it may go wrong in some language
224 // (e.g. Locale.FRENCH)
225 return String.format(Locale.ENGLISH, format, latitude, longitude);
228 public static void showOnMap(Context context, double latitude, double longitude) {
230 // We don't use "geo:latitude,longitude" because it only centers
231 // the MapView to the specified location, but we need a marker
232 // for further operations (routing to/from).
233 // The q=(lat, lng) syntax is suggested by geo-team.
234 String uri = formatLatitudeLongitude("http://maps.google.com/maps?f=q&q=(%f,%f)",
235 latitude, longitude);
236 ComponentName compName = new ComponentName(MAPS_PACKAGE_NAME,
238 Intent mapsIntent = new Intent(Intent.ACTION_VIEW,
239 Uri.parse(uri)).setComponent(compName);
240 context.startActivity(mapsIntent);
241 } catch (ActivityNotFoundException e) {
242 // Use the "geo intent" if no GMM is installed
243 Log.e(TAG, "GMM activity not found!", e);
244 String url = formatLatitudeLongitude("geo:%f,%f", latitude, longitude);
245 Intent mapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
246 context.startActivity(mapsIntent);
250 public static void setViewPointMatrix(
251 float matrix[], float x, float y, float z) {
257 Arrays.fill(matrix, 0, 16, 0);
258 matrix[0] = matrix[5] = matrix[15] = -z;
261 matrix[10] = matrix[11] = 1;
264 public static int getBucketId(String path) {
265 return path.toLowerCase().hashCode();
268 // Returns a (localized) string for the given duration (in seconds).
269 public static String formatDuration(final Context context, int duration) {
270 int h = duration / 3600;
271 int m = (duration - h * 3600) / 60;
272 int s = duration - (h * 3600 + m * 60);
273 String durationValue;
275 durationValue = String.format(context.getString(R.string.details_ms), m, s);
277 durationValue = String.format(context.getString(R.string.details_hms), h, m, s);
279 return durationValue;
282 public static void setSpinnerVisibility(final Activity activity,
283 final boolean visible) {
284 SpinnerVisibilitySetter.getInstance(activity).setSpinnerVisibility(visible);
287 public static int determineTypeBits(Context context, Intent intent) {
289 String type = intent.resolveType(context);
291 if (MIME_TYPE_ALL.equals(type)) {
292 typeBits = DataManager.INCLUDE_ALL;
293 } else if (MIME_TYPE_IMAGE.equals(type) ||
294 DIR_TYPE_IMAGE.equals(type)) {
295 typeBits = DataManager.INCLUDE_IMAGE;
296 } else if (MIME_TYPE_VIDEO.equals(type) ||
297 DIR_TYPE_VIDEO.equals(type)) {
298 typeBits = DataManager.INCLUDE_VIDEO;
300 typeBits = DataManager.INCLUDE_ALL;
303 if (intent.getBooleanExtra(Intent.EXTRA_LOCAL_ONLY, false)) {
304 typeBits |= DataManager.INCLUDE_LOCAL_ONLY;
310 public static int getSelectionModePrompt(int typeBits) {
311 if ((typeBits & DataManager.INCLUDE_VIDEO) != 0) {
312 return (typeBits & DataManager.INCLUDE_IMAGE) == 0
313 ? R.string.select_video
314 : R.string.select_item;
316 return R.string.select_image;
319 public static boolean hasSpaceForSize(long size) {
320 String state = Environment.getExternalStorageState();
321 if (!Environment.MEDIA_MOUNTED.equals(state)) {
325 String path = Environment.getExternalStorageDirectory().getPath();
327 StatFs stat = new StatFs(path);
328 return stat.getAvailableBlocks() * (long) stat.getBlockSize() > size;
329 } catch (Exception e) {
330 Log.i(TAG, "Fail to access external storage", e);
335 public static boolean isPanorama(MediaItem item) {
336 if (item == null) return false;
337 int w = item.getWidth();
338 int h = item.getHeight();
339 return (h > 0 && w / h >= 2);
342 public static Intent getHelpIntent(int helpUrlResId, Context context) {
343 Resources res = context.getResources();
344 String url = res.getString(helpUrlResId)
345 + "&hl=" + res.getConfiguration().locale.getLanguage();
347 Intent i = new Intent(Intent.ACTION_VIEW);
348 i.setData(Uri.parse(url));
349 i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
350 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
351 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);