ScanActivity.java

  1/*
  2 * Copyright 2012-2015 the original author or authors.
  3 *
  4 * This program is free software: you can redistribute it and/or modify
  5 * it under the terms of the GNU General Public License as published by
  6 * the Free Software Foundation, either version 3 of the License, or
  7 * (at your option) any later version.
  8 *
  9 * This program is distributed in the hope that it will be useful,
 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 12 * GNU General Public License for more details.
 13 *
 14 * You should have received a copy of the GNU General Public License
 15 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 16 */
 17
 18package eu.siacs.conversations.ui;
 19
 20import android.Manifest;
 21import android.app.Activity;
 22import android.content.Context;
 23import android.content.Intent;
 24import android.content.pm.PackageManager;
 25import android.graphics.Rect;
 26import android.graphics.RectF;
 27import android.graphics.SurfaceTexture;
 28import android.hardware.Camera;
 29import android.hardware.Camera.CameraInfo;
 30import android.os.Build;
 31import android.os.Bundle;
 32import android.os.Handler;
 33import android.os.HandlerThread;
 34import android.os.Process;
 35import android.os.Vibrator;
 36import android.preference.PreferenceManager;
 37import android.util.Log;
 38import android.view.KeyEvent;
 39import android.view.Surface;
 40import android.view.TextureView;
 41import android.view.TextureView.SurfaceTextureListener;
 42import android.view.View;
 43import android.view.WindowManager;
 44import android.widget.Toast;
 45
 46import androidx.core.app.ActivityCompat;
 47import androidx.core.content.ContextCompat;
 48
 49import com.google.zxing.BinaryBitmap;
 50import com.google.zxing.DecodeHintType;
 51import com.google.zxing.PlanarYUVLuminanceSource;
 52import com.google.zxing.ReaderException;
 53import com.google.zxing.Result;
 54import com.google.zxing.ResultPointCallback;
 55import com.google.zxing.common.HybridBinarizer;
 56import com.google.zxing.qrcode.QRCodeReader;
 57
 58import java.util.EnumMap;
 59import java.util.Map;
 60
 61import eu.siacs.conversations.Config;
 62import eu.siacs.conversations.R;
 63import eu.siacs.conversations.ui.service.CameraManager;
 64import eu.siacs.conversations.ui.widget.ScannerView;
 65import eu.siacs.conversations.ui.util.SettingsUtils;
 66
 67/**
 68 * @author Andreas Schildbach
 69 */
 70@SuppressWarnings("deprecation")
 71public final class ScanActivity extends Activity implements SurfaceTextureListener, ActivityCompat.OnRequestPermissionsResultCallback {
 72	public static final String INTENT_EXTRA_RESULT = "result";
 73
 74	public static final int REQUEST_SCAN_QR_CODE = 0x0987;
 75	private static final int REQUEST_CAMERA_PERMISSIONS_TO_SCAN = 0x6789;
 76
 77	private static final long VIBRATE_DURATION = 50L;
 78	private static final long AUTO_FOCUS_INTERVAL_MS = 2500L;
 79	private static final boolean DISABLE_CONTINUOUS_AUTOFOCUS = Build.MODEL.equals("GT-I9100") // Galaxy S2
 80			|| Build.MODEL.equals("SGH-T989") // Galaxy S2
 81			|| Build.MODEL.equals("SGH-T989D") // Galaxy S2 X
 82			|| Build.MODEL.equals("SAMSUNG-SGH-I727") // Galaxy S2 Skyrocket
 83			|| Build.MODEL.equals("GT-I9300") // Galaxy S3
 84			|| Build.MODEL.equals("GT-N7000"); // Galaxy Note
 85	private final CameraManager cameraManager = new CameraManager();
 86	private ScannerView scannerView;
 87	private TextureView previewView;
 88	private volatile boolean surfaceCreated = false;
 89	private Vibrator vibrator;
 90	private HandlerThread cameraThread;
 91	private volatile Handler cameraHandler;
 92	private final Runnable closeRunnable = new Runnable() {
 93		@Override
 94		public void run() {
 95			cameraHandler.removeCallbacksAndMessages(null);
 96			cameraManager.close();
 97		}
 98	};
 99	private final Runnable fetchAndDecodeRunnable = new Runnable() {
100		private final QRCodeReader reader = new QRCodeReader();
101		private final Map<DecodeHintType, Object> hints = new EnumMap<DecodeHintType, Object>(DecodeHintType.class);
102
103		@Override
104		public void run() {
105			cameraManager.requestPreviewFrame((data, camera) -> decode(data));
106		}
107
108		private void decode(final byte[] data) {
109			final PlanarYUVLuminanceSource source = cameraManager.buildLuminanceSource(data);
110			final BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
111
112			try {
113				hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, (ResultPointCallback) dot -> runOnUiThread(() -> scannerView.addDot(dot)));
114				final Result scanResult = reader.decode(bitmap, hints);
115
116				runOnUiThread(() -> handleResult(scanResult));
117			} catch (final ReaderException x) {
118				// retry
119				cameraHandler.post(fetchAndDecodeRunnable);
120			} finally {
121				reader.reset();
122			}
123		}
124	};
125	private final Runnable openRunnable = new Runnable() {
126		@Override
127		public void run() {
128			try {
129				final Camera camera = cameraManager.open(previewView, displayRotation(), !DISABLE_CONTINUOUS_AUTOFOCUS);
130
131				final Rect framingRect = cameraManager.getFrame();
132				final RectF framingRectInPreview = new RectF(cameraManager.getFramePreview());
133				framingRectInPreview.offsetTo(0, 0);
134				final boolean cameraFlip = cameraManager.getFacing() == CameraInfo.CAMERA_FACING_FRONT;
135				final int cameraRotation = cameraManager.getOrientation();
136
137				runOnUiThread(() -> scannerView.setFraming(framingRect, framingRectInPreview, displayRotation(), cameraRotation, cameraFlip));
138
139				final String focusMode = camera.getParameters().getFocusMode();
140				final boolean nonContinuousAutoFocus = Camera.Parameters.FOCUS_MODE_AUTO.equals(focusMode)
141						|| Camera.Parameters.FOCUS_MODE_MACRO.equals(focusMode);
142
143				if (nonContinuousAutoFocus)
144					cameraHandler.post(new AutoFocusRunnable(camera));
145
146				cameraHandler.post(fetchAndDecodeRunnable);
147			} catch (final Exception x) {
148				Log.d(Config.LOGTAG, "problem opening camera", x);
149			}
150		}
151
152		private int displayRotation() {
153			final int rotation = getWindowManager().getDefaultDisplay().getRotation();
154			if (rotation == Surface.ROTATION_0)
155				return 0;
156			else if (rotation == Surface.ROTATION_90)
157				return 90;
158			else if (rotation == Surface.ROTATION_180)
159				return 180;
160			else if (rotation == Surface.ROTATION_270)
161				return 270;
162			else
163				throw new IllegalStateException("rotation: " + rotation);
164		}
165	};
166
167	@Override
168	public void onCreate(final Bundle savedInstanceState) {
169		super.onCreate(savedInstanceState);
170
171		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
172
173		setContentView(R.layout.activity_scan);
174		scannerView = findViewById(R.id.scan_activity_mask);
175		previewView = findViewById(R.id.scan_activity_preview);
176		previewView.setSurfaceTextureListener(this);
177
178		cameraThread = new HandlerThread("cameraThread", Process.THREAD_PRIORITY_BACKGROUND);
179		cameraThread.start();
180		cameraHandler = new Handler(cameraThread.getLooper());
181	}
182
183	@Override
184	protected void onResume() {
185		super.onResume();
186		SettingsUtils.applyScreenshotPreventionSetting(this);
187		maybeOpenCamera();
188	}
189
190	@Override
191	protected void onPause() {
192		cameraHandler.post(closeRunnable);
193
194		super.onPause();
195	}
196
197	@Override
198	protected void onDestroy() {
199		// cancel background thread
200		cameraHandler.removeCallbacksAndMessages(null);
201		cameraThread.quit();
202
203		previewView.setSurfaceTextureListener(null);
204
205		super.onDestroy();
206	}
207
208	private void maybeOpenCamera() {
209		if (surfaceCreated && ContextCompat.checkSelfPermission(this,
210				Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
211			cameraHandler.post(openRunnable);
212	}
213
214	@Override
215	public void onSurfaceTextureAvailable(final SurfaceTexture surface, final int width, final int height) {
216		surfaceCreated = true;
217		maybeOpenCamera();
218	}
219
220	@Override
221	public boolean onSurfaceTextureDestroyed(final SurfaceTexture surface) {
222		surfaceCreated = false;
223		return true;
224	}
225
226	@Override
227	public void onSurfaceTextureSizeChanged(final SurfaceTexture surface, final int width, final int height) {
228	}
229
230	@Override
231	public void onSurfaceTextureUpdated(final SurfaceTexture surface) {
232	}
233
234	@Override
235	public void onAttachedToWindow() {
236		getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
237	}
238
239	@Override
240	public void onBackPressed() {
241		scannerView.setVisibility(View.GONE);
242		setResult(RESULT_CANCELED);
243		postFinish();
244	}
245
246	@Override
247	public boolean onKeyDown(final int keyCode, final KeyEvent event) {
248		switch (keyCode) {
249			case KeyEvent.KEYCODE_FOCUS:
250			case KeyEvent.KEYCODE_CAMERA:
251				// don't launch camera app
252				return true;
253			case KeyEvent.KEYCODE_VOLUME_DOWN:
254			case KeyEvent.KEYCODE_VOLUME_UP:
255				cameraHandler.post(() -> cameraManager.setTorch(keyCode == KeyEvent.KEYCODE_VOLUME_UP));
256				return true;
257		}
258
259		return super.onKeyDown(keyCode, event);
260	}
261
262	public void handleResult(final Result scanResult) {
263		vibrator.vibrate(VIBRATE_DURATION);
264
265		scannerView.setIsResult(true);
266
267		final Intent result = new Intent();
268		result.putExtra(INTENT_EXTRA_RESULT, scanResult.getText());
269		setResult(RESULT_OK, result);
270		postFinish();
271	}
272
273	private void postFinish() {
274		new Handler().postDelayed(this::finish, 50);
275	}
276
277	public static void scan(Activity activity) {
278		if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
279			Intent intent = new Intent(activity, ScanActivity.class);
280			activity.startActivityForResult(intent, REQUEST_SCAN_QR_CODE);
281		} else {
282			ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSIONS_TO_SCAN);
283		}
284
285	}
286
287	public static void onRequestPermissionResult(Activity activity, int requestCode, int[] grantResults) {
288		if (requestCode != REQUEST_CAMERA_PERMISSIONS_TO_SCAN) {
289			return;
290		}
291		if (grantResults.length > 0) {
292			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
293				scan(activity);
294			} else {
295				Toast.makeText(activity, R.string.qr_code_scanner_needs_access_to_camera, Toast.LENGTH_SHORT).show();
296			}
297		}
298	}
299
300	private final class AutoFocusRunnable implements Runnable {
301		private final Camera camera;
302		private final Camera.AutoFocusCallback autoFocusCallback = new Camera.AutoFocusCallback() {
303			@Override
304			public void onAutoFocus(final boolean success, final Camera camera) {
305				// schedule again
306				cameraHandler.postDelayed(AutoFocusRunnable.this, AUTO_FOCUS_INTERVAL_MS);
307			}
308		};
309
310		public AutoFocusRunnable(final Camera camera) {
311			this.camera = camera;
312		}
313
314		@Override
315		public void run() {
316			try {
317				camera.autoFocus(autoFocusCallback);
318			} catch (final Exception x) {
319				Log.d(Config.LOGTAG, "problem with auto-focus, will not schedule again", x);
320			}
321		}
322	}
323}