Util.java revision 0fad45d0d64569098f4daf34ff7e5ae785601304
1/* 2 * Copyright (C) 2009 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 17package com.android.camera; 18 19import com.android.camera.gallery.IImage; 20 21import android.app.Activity; 22import android.app.AlertDialog; 23import android.content.Context; 24import android.content.DialogInterface; 25import android.graphics.Bitmap; 26import android.graphics.BitmapFactory; 27import android.graphics.Matrix; 28import android.hardware.Camera; 29import android.hardware.Camera.Parameters; 30import android.hardware.Camera.Size; 31import android.telephony.TelephonyManager; 32import android.util.Log; 33import android.view.Display; 34import android.view.Surface; 35import android.view.View; 36import android.view.animation.Animation; 37import android.view.animation.TranslateAnimation; 38 39import java.io.Closeable; 40import java.lang.reflect.Method; 41import java.util.List; 42import java.util.StringTokenizer; 43 44/** 45 * Collection of utility functions used in this package. 46 */ 47public class Util { 48 private static final String TAG = "Util"; 49 public static final int DIRECTION_LEFT = 0; 50 public static final int DIRECTION_RIGHT = 1; 51 public static final int DIRECTION_UP = 2; 52 public static final int DIRECTION_DOWN = 3; 53 54 public static final String REVIEW_ACTION = "com.android.camera.action.REVIEW"; 55 56 private Util() { 57 } 58 59 // Rotates the bitmap by the specified degree. 60 // If a new bitmap is created, the original bitmap is recycled. 61 public static Bitmap rotate(Bitmap b, int degrees) { 62 return rotateAndMirror(b, degrees, false); 63 } 64 65 // Rotates and/or mirrors the bitmap. If a new bitmap is created, the 66 // original bitmap is recycled. 67 public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) { 68 if ((degrees != 0 || mirror) && b != null) { 69 Matrix m = new Matrix(); 70 m.setRotate(degrees, 71 (float) b.getWidth() / 2, (float) b.getHeight() / 2); 72 if (mirror) { 73 m.postScale(-1, 1); 74 degrees = (degrees + 360) % 360; 75 if (degrees == 0 || degrees == 180) { 76 m.postTranslate((float) b.getWidth(), 0); 77 } else if (degrees == 90 || degrees == 270) { 78 m.postTranslate((float) b.getHeight(), 0); 79 } else { 80 throw new IllegalArgumentException("Invalid degrees=" + degrees); 81 } 82 } 83 84 try { 85 Bitmap b2 = Bitmap.createBitmap( 86 b, 0, 0, b.getWidth(), b.getHeight(), m, true); 87 if (b != b2) { 88 b.recycle(); 89 b = b2; 90 } 91 } catch (OutOfMemoryError ex) { 92 // We have no memory to rotate. Return the original bitmap. 93 } 94 } 95 return b; 96 } 97 98 /* 99 * Compute the sample size as a function of minSideLength 100 * and maxNumOfPixels. 101 * minSideLength is used to specify that minimal width or height of a 102 * bitmap. 103 * maxNumOfPixels is used to specify the maximal size in pixels that is 104 * tolerable in terms of memory usage. 105 * 106 * The function returns a sample size based on the constraints. 107 * Both size and minSideLength can be passed in as IImage.UNCONSTRAINED, 108 * which indicates no care of the corresponding constraint. 109 * The functions prefers returning a sample size that 110 * generates a smaller bitmap, unless minSideLength = IImage.UNCONSTRAINED. 111 * 112 * Also, the function rounds up the sample size to a power of 2 or multiple 113 * of 8 because BitmapFactory only honors sample size this way. 114 * For example, BitmapFactory downsamples an image by 2 even though the 115 * request is 3. So we round up the sample size to avoid OOM. 116 */ 117 public static int computeSampleSize(BitmapFactory.Options options, 118 int minSideLength, int maxNumOfPixels) { 119 int initialSize = computeInitialSampleSize(options, minSideLength, 120 maxNumOfPixels); 121 122 int roundedSize; 123 if (initialSize <= 8) { 124 roundedSize = 1; 125 while (roundedSize < initialSize) { 126 roundedSize <<= 1; 127 } 128 } else { 129 roundedSize = (initialSize + 7) / 8 * 8; 130 } 131 132 return roundedSize; 133 } 134 135 private static int computeInitialSampleSize(BitmapFactory.Options options, 136 int minSideLength, int maxNumOfPixels) { 137 double w = options.outWidth; 138 double h = options.outHeight; 139 140 int lowerBound = (maxNumOfPixels == IImage.UNCONSTRAINED) ? 1 : 141 (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); 142 int upperBound = (minSideLength == IImage.UNCONSTRAINED) ? 128 : 143 (int) Math.min(Math.floor(w / minSideLength), 144 Math.floor(h / minSideLength)); 145 146 if (upperBound < lowerBound) { 147 // return the larger one when there is no overlapping zone. 148 return lowerBound; 149 } 150 151 if ((maxNumOfPixels == IImage.UNCONSTRAINED) && 152 (minSideLength == IImage.UNCONSTRAINED)) { 153 return 1; 154 } else if (minSideLength == IImage.UNCONSTRAINED) { 155 return lowerBound; 156 } else { 157 return upperBound; 158 } 159 } 160 161 public static <T> int indexOf(T [] array, T s) { 162 for (int i = 0; i < array.length; i++) { 163 if (array[i].equals(s)) { 164 return i; 165 } 166 } 167 return -1; 168 } 169 170 public static void closeSilently(Closeable c) { 171 if (c == null) return; 172 try { 173 c.close(); 174 } catch (Throwable t) { 175 // do nothing 176 } 177 } 178 179 public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) { 180 try { 181 BitmapFactory.Options options = new BitmapFactory.Options(); 182 options.inJustDecodeBounds = true; 183 BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, 184 options); 185 if (options.mCancel || options.outWidth == -1 186 || options.outHeight == -1) { 187 return null; 188 } 189 options.inSampleSize = computeSampleSize( 190 options, IImage.UNCONSTRAINED, maxNumOfPixels); 191 options.inJustDecodeBounds = false; 192 193 options.inDither = false; 194 options.inPreferredConfig = Bitmap.Config.ARGB_8888; 195 return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, 196 options); 197 } catch (OutOfMemoryError ex) { 198 Log.e(TAG, "Got oom exception ", ex); 199 return null; 200 } 201 } 202 203 public static void Assert(boolean cond) { 204 if (!cond) { 205 throw new AssertionError(); 206 } 207 } 208 209 public static void showFatalErrorAndFinish( 210 final Activity activity, String title, String message) { 211 DialogInterface.OnClickListener buttonListener = 212 new DialogInterface.OnClickListener() { 213 public void onClick(DialogInterface dialog, int which) { 214 activity.finish(); 215 } 216 }; 217 new AlertDialog.Builder(activity) 218 .setCancelable(false) 219 .setIcon(android.R.drawable.ic_dialog_alert) 220 .setTitle(title) 221 .setMessage(message) 222 .setNeutralButton(R.string.details_ok, buttonListener) 223 .show(); 224 } 225 226 public static Animation slideOut(View view, int to) { 227 view.setVisibility(View.INVISIBLE); 228 Animation anim; 229 switch (to) { 230 case DIRECTION_LEFT: 231 anim = new TranslateAnimation(0, -view.getWidth(), 0, 0); 232 break; 233 case DIRECTION_RIGHT: 234 anim = new TranslateAnimation(0, view.getWidth(), 0, 0); 235 break; 236 case DIRECTION_UP: 237 anim = new TranslateAnimation(0, 0, 0, -view.getHeight()); 238 break; 239 case DIRECTION_DOWN: 240 anim = new TranslateAnimation(0, 0, 0, view.getHeight()); 241 break; 242 default: 243 throw new IllegalArgumentException(Integer.toString(to)); 244 } 245 anim.setDuration(500); 246 view.startAnimation(anim); 247 return anim; 248 } 249 250 public static Animation slideIn(View view, int from) { 251 view.setVisibility(View.VISIBLE); 252 Animation anim; 253 switch (from) { 254 case DIRECTION_LEFT: 255 anim = new TranslateAnimation(-view.getWidth(), 0, 0, 0); 256 break; 257 case DIRECTION_RIGHT: 258 anim = new TranslateAnimation(view.getWidth(), 0, 0, 0); 259 break; 260 case DIRECTION_UP: 261 anim = new TranslateAnimation(0, 0, -view.getHeight(), 0); 262 break; 263 case DIRECTION_DOWN: 264 anim = new TranslateAnimation(0, 0, view.getHeight(), 0); 265 break; 266 default: 267 throw new IllegalArgumentException(Integer.toString(from)); 268 } 269 anim.setDuration(500); 270 view.startAnimation(anim); 271 return anim; 272 } 273 274 public static <T> T checkNotNull(T object) { 275 if (object == null) throw new NullPointerException(); 276 return object; 277 } 278 279 public static boolean equals(Object a, Object b) { 280 return (a == b) || (a == null ? false : a.equals(b)); 281 } 282 283 public static boolean isPowerOf2(int n) { 284 return (n & -n) == n; 285 } 286 287 public static int nextPowerOf2(int n) { 288 n -= 1; 289 n |= n >>> 16; 290 n |= n >>> 8; 291 n |= n >>> 4; 292 n |= n >>> 2; 293 n |= n >>> 1; 294 return n + 1; 295 } 296 297 public static float distance(float x, float y, float sx, float sy) { 298 float dx = x - sx; 299 float dy = y - sy; 300 return (float) Math.sqrt(dx * dx + dy * dy); 301 } 302 303 public static int clamp(int x, int min, int max) { 304 if (x > max) return max; 305 if (x < min) return min; 306 return x; 307 } 308 309 public static int getDisplayRotation(Activity activity) { 310 int rotation = activity.getWindowManager().getDefaultDisplay() 311 .getRotation(); 312 switch (rotation) { 313 case Surface.ROTATION_0: return 0; 314 case Surface.ROTATION_90: return 90; 315 case Surface.ROTATION_180: return 180; 316 case Surface.ROTATION_270: return 270; 317 } 318 return 0; 319 } 320 321 public static void setCameraDisplayOrientation(Activity activity, 322 int cameraId, Camera camera) { 323 // See android.hardware.Camera.setCameraDisplayOrientation for 324 // documentation. 325 Camera.CameraInfo info = new Camera.CameraInfo(); 326 Camera.getCameraInfo(cameraId, info); 327 int degrees = getDisplayRotation(activity); 328 int result; 329 if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { 330 result = (info.orientation + degrees) % 360; 331 result = (360 - result) % 360; // compensate the mirror 332 } else { // back-facing 333 result = (info.orientation - degrees + 360) % 360; 334 } 335 camera.setDisplayOrientation(result); 336 } 337 338 public static Size getOptimalPreviewSize(Activity currentActivity, 339 List<Size> sizes, double targetRatio) { 340 // Use a very small tolerance because we want an exact match. 341 final double ASPECT_TOLERANCE = 0.001; 342 if (sizes == null) return null; 343 344 Size optimalSize = null; 345 double minDiff = Double.MAX_VALUE; 346 347 // Because of bugs of overlay and layout, we sometimes will try to 348 // layout the viewfinder in the portrait orientation and thus get the 349 // wrong size of mSurfaceView. When we change the preview size, the 350 // new overlay will be created before the old one closed, which causes 351 // an exception. For now, just get the screen size 352 353 Display display = currentActivity.getWindowManager().getDefaultDisplay(); 354 int targetHeight = Math.min(display.getHeight(), display.getWidth()); 355 356 if (targetHeight <= 0) { 357 // We don't know the size of SurfaceView, use screen height 358 targetHeight = display.getHeight(); 359 } 360 361 // Try to find an size match aspect ratio and size 362 for (Size size : sizes) { 363 double ratio = (double) size.width / size.height; 364 if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue; 365 if (Math.abs(size.height - targetHeight) < minDiff) { 366 optimalSize = size; 367 minDiff = Math.abs(size.height - targetHeight); 368 } 369 } 370 371 // Cannot find the one match the aspect ratio. This should not happen. 372 // Ignore the requirement. 373 if (optimalSize == null) { 374 Log.w(TAG, "No preview size match the aspect ratio"); 375 minDiff = Double.MAX_VALUE; 376 for (Size size : sizes) { 377 if (Math.abs(size.height - targetHeight) < minDiff) { 378 optimalSize = size; 379 minDiff = Math.abs(size.height - targetHeight); 380 } 381 } 382 } 383 return optimalSize; 384 } 385 386 public static void dumpParameters(Parameters parameters) { 387 String flattened = parameters.flatten(); 388 StringTokenizer tokenizer = new StringTokenizer(flattened, ";"); 389 Log.d(TAG, "Dump all camera parameters:"); 390 while (tokenizer.hasMoreElements()) { 391 Log.d(TAG, tokenizer.nextToken()); 392 } 393 } 394 395 /** 396 * Returns whether the device is voice-capable (meaning, it can do MMS). 397 */ 398 public static boolean isMmsCapable(Context context) { 399 TelephonyManager telephonyManager = (TelephonyManager) 400 context.getSystemService(Context.TELEPHONY_SERVICE); 401 if (telephonyManager == null) { 402 return false; 403 } 404 405 try { 406 Class partypes[] = new Class[0]; 407 Method sIsVoiceCapable = TelephonyManager.class.getMethod( 408 "isVoiceCapable", partypes); 409 410 Object arglist[] = new Object[0]; 411 Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist); 412 return (Boolean) retobj; 413 } catch (java.lang.reflect.InvocationTargetException ite) { 414 // Failure, must be another device. 415 // Assume that it is voice capable. 416 } catch (java.lang.IllegalAccessException iae) { 417 // Failure, must be an other device. 418 // Assume that it is voice capable. 419 } catch (NoSuchMethodException nsme) { 420 } 421 return true; 422 } 423} 424