/*
 * Copyright (C) 2012 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.zxing.client.android.camera;

import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;

import java.util.ArrayList;
import java.util.Collection;

import com.google.zxing.client.android.PreferencesActivity;

final class AutoFocusManager implements Camera.AutoFocusCallback {

  private static final String TAG = AutoFocusManager.class.getSimpleName();

  private static final long AUTO_FOCUS_INTERVAL_MS = 2000L;
  private static final Collection<String> FOCUS_MODES_CALLING_AF;
  static {
    FOCUS_MODES_CALLING_AF = new ArrayList<>(2);
    FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_AUTO);
    FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_MACRO);
  }

  private boolean active;
  private final boolean useAutoFocus;
  private final Camera camera;
  private AsyncTask<?,?,?> outstandingTask;

  AutoFocusManager(Context context, Camera camera) {
    this.camera = camera;
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    String currentFocusMode = camera.getParameters().getFocusMode();
    useAutoFocus =
        sharedPrefs.getBoolean(PreferencesActivity.KEY_AUTO_FOCUS, true) &&
        FOCUS_MODES_CALLING_AF.contains(currentFocusMode);
    Log.i(TAG, "Current focus mode '" + currentFocusMode + "'; use auto focus? " + useAutoFocus);
    start();
  }

  @Override
  public synchronized void onAutoFocus(boolean success, Camera theCamera) {
    if (active) {
      outstandingTask = new AutoFocusTask();
      outstandingTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
  }

  synchronized void start() {
    if (useAutoFocus) {
      active = true;
      try {
        camera.autoFocus(this);
      } catch (RuntimeException re) {
        // Have heard RuntimeException reported in Android 4.0.x+; continue?
        Log.w(TAG, "Unexpected exception while focusing", re);
      }
    }
  }

  synchronized void stop() {
    if (useAutoFocus) {
      try {
        camera.cancelAutoFocus();
      } catch (RuntimeException re) {
        // Have heard RuntimeException reported in Android 4.0.x+; continue?
        Log.w(TAG, "Unexpected exception while cancelling focusing", re);
      }
    }
    if (outstandingTask != null) {
      outstandingTask.cancel(true);
      outstandingTask = null;
    }
    active = false;
  }

  private final class AutoFocusTask extends AsyncTask<Object,Object,Object> {
    @Override
    protected Object doInBackground(Object... voids) {
      try {
        Thread.sleep(AUTO_FOCUS_INTERVAL_MS);
      } catch (InterruptedException e) {
        // continue
      }
      synchronized (AutoFocusManager.this) {
        if (active) {
          start();
        }
      }
      return null;
    }
  }

}

@@ -907,16 +907,72 @@
 lection;
+%0Aimport java.util.concurrent.RejectedExecutionException;
 %0A%0Aimport
@@ -1515,22 +1515,51 @@
 boolean 
-active
+stopped;%0A  private boolean focusing
 ;%0A  priv
@@ -2272,39 +2272,167 @@
     
-if (active) %7B%0A      outstanding
+focusing = false;%0A    autoFocusAgainLater();%0A  %7D%0A%0A  private void autoFocusAgainLater() %7B%0A    if (!stopped && outstandingTask == null) %7B%0A      AutoFocusTask new
 Task
@@ -2457,35 +2457,41 @@
 sk();%0A      
-outstanding
+try %7B%0A        new
 Task.execute
@@ -2534,16 +2534,165 @@
 CUTOR);%0A
+        outstandingTask = newTask;%0A      %7D catch (RejectedExecutionException ree) %7B%0A        Log.w(TAG, %22Could not request auto focus%22, ree);%0A      %7D%0A
     %7D%0A  
@@ -2758,35 +2758,84 @@
     
-active = true;%0A
+cancelOutstandingTask();%0A      if (!stopped && !focusing) %7B%0A 
       
+ 
 try %7B%0A
+  
     
@@ -2858,24 +2858,53 @@
 ocus(this);%0A
+          focusing = true;%0A  
       %7D catc
@@ -2921,32 +2921,34 @@
 Exception re) %7B%0A
+  
         // Have 
@@ -3008,32 +3008,34 @@
 ntinue?%0A        
+ 
+ 
 Log.w(TAG, %22Unex
@@ -3071,33 +3071,358 @@
 ng%22, re);%0A      
-%7D
+    // Try again later to keep cycle going%0A          autoFocusAgainLater();%0A        %7D%0A      %7D%0A    %7D%0A  %7D%0A%0A  private void cancelOutstandingTask() %7B%0A    if (outstandingTask != null) %7B%0A      if (outstandingTask.getStatus() != AsyncTask.Status.FINISHED) %7B%0A        outstandingTask.cancel(true);%0A      %7D%0A      outstandingTask = null;
 %0A    %7D%0A  %7D%0A%0A  sy
@@ -3442,24 +3442,44 @@
 id stop() %7B%0A
+    stopped = true;%0A
     if (useA
@@ -3486,24 +3486,111 @@
 utoFocus) %7B%0A
+      cancelOutstandingTask();%0A      // Doesn't hurt to call this even if not focusing%0A
       try %7B%0A
@@ -3830,135 +3830,8 @@
   %7D%0A
-    if (outstandingTask != null) %7B%0A      outstandingTask.cancel(true);%0A      outstandingTask = null;%0A    %7D%0A    active = false;%0A
   %7D%0A
@@ -4116,104 +4116,15 @@
    s
-ynchronized (AutoFocusManager.this) %7B%0A        if (active) %7B%0A          start();%0A        %7D%0A      %7D
+tart();
 %0A   

Rewrite auto-focus loop to be more robust, like continuing even if camera driver errors