Issue 155: allow custom product search, and, other small tweaks I think nobody will...
[zxing.git] / android / src / com / google / zxing / client / android / CameraManager.java
1 /*
2  * Copyright (C) 2008 ZXing authors
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.google.zxing.client.android;
18
19 import android.content.Context;
20 import android.graphics.Point;
21 import android.graphics.Rect;
22 import android.hardware.Camera;
23 import android.os.Handler;
24 import android.os.Message;
25 import android.util.Log;
26 import android.view.Display;
27 import android.view.SurfaceHolder;
28 import android.view.WindowManager;
29 import com.google.zxing.ResultPoint;
30
31 import java.io.IOException;
32
33 /**
34  * This object wraps the Camera service object and expects to be the only one talking to it. The
35  * implementation encapsulates the steps needed to take preview-sized images, which are used for
36  * both preview and decoding.
37  */
38 final class CameraManager {
39
40   private static final String TAG = "CameraManager";
41
42   private static CameraManager mCameraManager;
43   private Camera mCamera;
44   private final Context mContext;
45   private Point mScreenResolution;
46   private Rect mFramingRect;
47   private Handler mPreviewHandler;
48   private int mPreviewMessage;
49   private Handler mAutoFocusHandler;
50   private int mAutoFocusMessage;
51   private boolean mInitialized;
52   private boolean mPreviewing;
53
54   public static void init(Context context) {
55     if (mCameraManager == null) {
56       mCameraManager = new CameraManager(context);
57     }
58   }
59
60   public static CameraManager get() {
61     return mCameraManager;
62   }
63
64   private CameraManager(Context context) {
65     mContext = context;
66     mCamera = null;
67     mInitialized = false;
68     mPreviewing = false;
69   }
70
71   public void openDriver(SurfaceHolder holder) throws IOException {
72     if (mCamera == null) {
73       mCamera = Camera.open();
74       mCamera.setPreviewDisplay(holder);
75
76       if (!mInitialized) {
77         mInitialized = true;
78         getScreenResolution();
79       }
80
81       setCameraParameters();
82     }
83   }
84
85   public void closeDriver() {
86     if (mCamera != null) {
87       mCamera.release();
88       mCamera = null;
89     }
90   }
91
92   public void startPreview() {
93     if (mCamera != null && !mPreviewing) {
94       mCamera.startPreview();
95       mPreviewing = true;
96     }
97   }
98
99   public void stopPreview() {
100     if (mCamera != null && mPreviewing) {
101       mCamera.setPreviewCallback(null);
102       mCamera.stopPreview();
103       mPreviewHandler = null;
104       mAutoFocusHandler = null;
105       mPreviewing = false;
106     }
107   }
108
109   /**
110    * A single preview frame will be returned to the handler supplied. The data will arrive as byte[]
111    * in the message.obj field, with width and height encoded as message.arg1 and message.arg2,
112    * respectively.
113    *
114    * @param handler The handler to send the message to.
115    * @param message The what field of the message to be sent.
116    */
117   public void requestPreviewFrame(Handler handler, int message) {
118     if (mCamera != null && mPreviewing) {
119       mPreviewHandler = handler;
120       mPreviewMessage = message;
121       mCamera.setPreviewCallback(previewCallback);
122     }
123   }
124
125   public void requestAutoFocus(Handler handler, int message) {
126     if (mCamera != null && mPreviewing) {
127       mAutoFocusHandler = handler;
128       mAutoFocusMessage = message;
129       mCamera.autoFocus(autoFocusCallback);
130     }
131   }
132
133   /**
134    * Calculates the framing rect which the UI should draw to show the user where to place the
135    * barcode. The actual captured image should be a bit larger than indicated because they might
136    * frame the shot too tightly. This target helps with alignment as well as forces the user to hold
137    * the device far enough away to ensure the image will be in focus.
138    *
139    * @return The rectangle to draw on screen in window coordinates.
140    */
141   public Rect getFramingRect() {
142     if (mFramingRect == null) {
143       int size = (mScreenResolution.x < mScreenResolution.y ? mScreenResolution.x :
144           mScreenResolution.y) * 3 / 4;
145       int leftOffset = (mScreenResolution.x - size) / 2;
146       int topOffset = (mScreenResolution.y - size) / 2;
147       mFramingRect = new Rect(leftOffset, topOffset, leftOffset + size, topOffset + size);
148       Log.v(TAG, "Calculated framing rect: " + mFramingRect);
149     }
150     return mFramingRect;
151   }
152
153   /**
154    * Converts the result points from still resolution coordinates to screen coordinates.
155    *
156    * @param points The points returned by the Reader subclass through Result.getResultPoints().
157    * @return An array of Points scaled to the size of the framing rect and offset appropriately
158    *         so they can be drawn in screen coordinates.
159    */
160   public Point[] convertResultPoints(ResultPoint[] points) {
161     Rect frame = getFramingRect();
162     int count = points.length;
163     Point[] output = new Point[count];
164     for (int x = 0; x < count; x++) {
165       output[x] = new Point();
166       output[x].x = frame.left + (int) (points[x].getX() + 0.5f);
167       output[x].y = frame.top + (int) (points[x].getY() + 0.5f);
168     }
169     return output;
170   }
171
172   /**
173    * Preview frames are delivered here, which we pass on to the registered handler. Make sure to
174    * clear the handler so it will only receive one message.
175    */
176   private final Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
177     public void onPreviewFrame(byte[] data, Camera camera) {
178       camera.setPreviewCallback(null);
179       if (mPreviewHandler != null) {
180         Message message = mPreviewHandler.obtainMessage(mPreviewMessage, mScreenResolution.x,
181             mScreenResolution.y, data);
182         message.sendToTarget();
183         mPreviewHandler = null;
184       }
185     }
186   };
187
188   private final Camera.AutoFocusCallback autoFocusCallback = new Camera.AutoFocusCallback() {
189     public void onAutoFocus(boolean success, Camera camera) {
190       if (mAutoFocusHandler != null) {
191         Message message = mAutoFocusHandler.obtainMessage(mAutoFocusMessage, success);
192         // Simulate continuous autofocus by sending a focus request every 1.5 seconds.
193         mAutoFocusHandler.sendMessageDelayed(message, 1500L);
194         mAutoFocusHandler = null;
195       }
196     }
197   };
198
199   /**
200    * Sets the camera up to take preview images which are used for both preview and decoding. We're
201    * counting on the default YUV420 semi-planar data. If that changes in the future, we'll need to
202    * specify it explicitly with setPreviewFormat().
203    */
204   private void setCameraParameters() {
205     Camera.Parameters parameters = mCamera.getParameters();
206     parameters.setPreviewSize(mScreenResolution.x, mScreenResolution.y);
207     mCamera.setParameters(parameters);
208     Log.v(TAG, "Setting params for preview: width " + mScreenResolution.x + " height " +
209         mScreenResolution.y);
210   }
211
212   private Point getScreenResolution() {
213     if (mScreenResolution == null) {
214       WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
215       Display display = manager.getDefaultDisplay();
216       mScreenResolution = new Point(display.getWidth(), display.getHeight());
217     }
218     return mScreenResolution;
219   }
220
221 }