Draft of 'thinking' visualization for barcode scanning. Works for 1D and QR codes.
[zxing.git] / android / src / com / google / zxing / client / android / CaptureActivity.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 com.google.zxing.Result;
20 import com.google.zxing.ResultPoint;
21 import com.google.zxing.client.android.history.HistoryManager;
22 import com.google.zxing.client.android.result.ResultButtonListener;
23 import com.google.zxing.client.android.result.ResultHandler;
24 import com.google.zxing.client.android.result.ResultHandlerFactory;
25 import com.google.zxing.client.android.share.ShareActivity;
26
27 import android.app.Activity;
28 import android.app.AlertDialog;
29 import android.content.DialogInterface;
30 import android.content.Intent;
31 import android.content.SharedPreferences;
32 import android.content.pm.PackageInfo;
33 import android.content.pm.PackageManager;
34 import android.content.res.AssetFileDescriptor;
35 import android.content.res.Configuration;
36 import android.graphics.Bitmap;
37 import android.graphics.Canvas;
38 import android.graphics.Paint;
39 import android.graphics.Rect;
40 import android.graphics.drawable.BitmapDrawable;
41 import android.media.AudioManager;
42 import android.media.MediaPlayer;
43 import android.media.MediaPlayer.OnCompletionListener;
44 import android.net.Uri;
45 import android.os.Bundle;
46 import android.os.Handler;
47 import android.os.Message;
48 import android.os.Vibrator;
49 import android.preference.PreferenceManager;
50 import android.text.ClipboardManager;
51 import android.text.SpannableStringBuilder;
52 import android.text.style.UnderlineSpan;
53 import android.util.Log;
54 import android.view.Gravity;
55 import android.view.KeyEvent;
56 import android.view.Menu;
57 import android.view.MenuItem;
58 import android.view.SurfaceHolder;
59 import android.view.SurfaceView;
60 import android.view.View;
61 import android.view.ViewGroup;
62 import android.view.Window;
63 import android.view.WindowManager;
64 import android.widget.ImageView;
65 import android.widget.TextView;
66
67 import java.io.IOException;
68
69 /**
70  * The barcode reader activity itself. This is loosely based on the CameraPreview
71  * example included in the Android SDK.
72  *
73  * @author dswitkin@google.com (Daniel Switkin)
74  */
75 public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
76   private static final String TAG = "CaptureActivity";
77
78   private static final int SHARE_ID = Menu.FIRST;
79   private static final int HISTORY_ID = Menu.FIRST + 1;
80   private static final int SETTINGS_ID = Menu.FIRST + 2;
81   private static final int HELP_ID = Menu.FIRST + 3;
82   private static final int ABOUT_ID = Menu.FIRST + 4;
83
84   private static final int MAX_RESULT_IMAGE_SIZE = 150;
85   private static final long INTENT_RESULT_DURATION = 1500L;
86   private static final float BEEP_VOLUME = 0.10f;
87   private static final long VIBRATE_DURATION = 200L;
88
89   private static final String PACKAGE_NAME = "com.google.zxing.client.android";
90   private static final String PRODUCT_SEARCH_URL_PREFIX = "http://www.google";
91   private static final String PRODUCT_SEARCH_URL_SUFFIX = "/m/products/scan";
92   private static final String ZXING_URL = "http://zxing.appspot.com/scan";
93
94   private enum Source {
95     NATIVE_APP_INTENT,
96     PRODUCT_SEARCH_LINK,
97     ZXING_LINK,
98     NONE
99   }
100
101   private CaptureActivityHandler handler;
102
103   private ViewfinderView viewfinderView;
104   private View statusView;
105   private View resultView;
106   private MediaPlayer mediaPlayer;
107   private Result lastResult;
108   private boolean hasSurface;
109   private boolean playBeep;
110   private boolean vibrate;
111   private boolean copyToClipboard;
112   private Source source;
113   private String sourceUrl;
114   private String decodeMode;
115   private String versionName;
116   private HistoryManager historyManager;
117   
118   private final OnCompletionListener beepListener = new BeepListener();
119
120   private final DialogInterface.OnClickListener aboutListener =
121       new DialogInterface.OnClickListener() {
122     public void onClick(DialogInterface dialogInterface, int i) {
123       Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.zxing_url)));
124       startActivity(intent);
125     }
126   };
127
128   ViewfinderView getViewfinderView() {
129     return viewfinderView;
130   }
131
132   public Handler getHandler() {
133     return handler;
134   }
135
136   @Override
137   public void onCreate(Bundle icicle) {
138     super.onCreate(icicle);
139
140     Window window = getWindow();
141     window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
142     setContentView(R.layout.capture);
143
144     CameraManager.init(getApplication());
145     viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
146     resultView = findViewById(R.id.result_view);
147     statusView = findViewById(R.id.status_view);
148     handler = null;
149     lastResult = null;
150     hasSurface = false;
151     historyManager = new HistoryManager(this);
152     historyManager.trimHistory();
153
154     showHelpOnFirstLaunch();
155   }
156
157   @Override
158   protected void onResume() {
159     super.onResume();
160
161     SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
162     SurfaceHolder surfaceHolder = surfaceView.getHolder();
163     if (hasSurface) {
164       // The activity was paused but not stopped, so the surface still exists. Therefore
165       // surfaceCreated() won't be called, so init the camera here.
166       initCamera(surfaceHolder);
167     } else {
168       // Install the callback and wait for surfaceCreated() to init the camera.
169       surfaceHolder.addCallback(this);
170       surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
171     }
172
173     Intent intent = getIntent();
174     String action = intent == null ? null : intent.getAction();
175     String dataString = intent == null ? null : intent.getDataString();
176     if (intent != null && action != null) {
177       if (action.equals(Intents.Scan.ACTION)) {
178         // Scan the formats the intent requested, and return the result to the calling activity.
179         source = Source.NATIVE_APP_INTENT;
180         decodeMode = intent.getStringExtra(Intents.Scan.MODE);
181         resetStatusView();
182       } else if (dataString != null && dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
183           dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
184         // Scan only products and send the result to mobile Product Search.
185         source = Source.PRODUCT_SEARCH_LINK;
186         sourceUrl = dataString;
187         decodeMode = Intents.Scan.PRODUCT_MODE;
188         resetStatusView();
189       } else if (dataString != null && dataString.equals(ZXING_URL)) {
190         // Scan all formats and handle the results ourselves.
191         // TODO: In the future we could allow the hyperlink to include a URL to send the results to.
192         source = Source.ZXING_LINK;
193         sourceUrl = dataString;
194         decodeMode = null;
195         resetStatusView();
196       } else {
197         // Scan all formats and handle the results ourselves (launched from Home).
198         source = Source.NONE;
199         decodeMode = null;
200         resetStatusView();
201       }
202     } else {
203       source = Source.NONE;
204       decodeMode = null;
205       if (lastResult == null) {
206         resetStatusView();
207       }
208     }
209
210     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
211     playBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
212     vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
213     copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);
214     initBeepSound();
215   }
216
217   @Override
218   protected void onPause() {
219     super.onPause();
220     if (handler != null) {
221       handler.quitSynchronously();
222       handler = null;
223     }
224     CameraManager.get().closeDriver();
225   }
226
227   @Override
228   public boolean onKeyDown(int keyCode, KeyEvent event) {
229     if (keyCode == KeyEvent.KEYCODE_BACK) {
230       if (source == Source.NATIVE_APP_INTENT) {
231         setResult(RESULT_CANCELED);
232         finish();
233         return true;
234       } else if ((source == Source.NONE || source == Source.ZXING_LINK) && lastResult != null) {
235         resetStatusView();
236         handler.sendEmptyMessage(R.id.restart_preview);
237         return true;
238       }
239     } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
240       // Handle these events so they don't launch the Camera app
241       return true;
242     }
243     return super.onKeyDown(keyCode, event);
244   }
245
246   @Override
247   public boolean onCreateOptionsMenu(Menu menu) {
248     super.onCreateOptionsMenu(menu);
249     menu.add(0, SHARE_ID, 0, R.string.menu_share).setIcon(R.drawable.share_menu_item);
250     menu.add(0, HISTORY_ID, 0, R.string.menu_history)
251         .setIcon(android.R.drawable.ic_menu_recent_history);
252     menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
253         .setIcon(android.R.drawable.ic_menu_preferences);
254     menu.add(0, HELP_ID, 0, R.string.menu_help)
255         .setIcon(android.R.drawable.ic_menu_help);
256     menu.add(0, ABOUT_ID, 0, R.string.menu_about)
257         .setIcon(android.R.drawable.ic_menu_info_details);
258     return true;
259   }
260
261   // Don't display the share menu item if the result overlay is showing.
262   @Override
263   public boolean onPrepareOptionsMenu(Menu menu) {
264     super.onPrepareOptionsMenu(menu);
265     menu.findItem(SHARE_ID).setVisible(lastResult == null);
266     return true;
267   }
268
269   @Override
270   public boolean onOptionsItemSelected(MenuItem item) {
271     switch (item.getItemId()) {
272       case SHARE_ID: {
273         Intent intent = new Intent(Intent.ACTION_VIEW);
274         intent.setClassName(this, ShareActivity.class.getName());
275         startActivity(intent);
276         break;
277       }
278       case HISTORY_ID: {
279         AlertDialog historyAlert = historyManager.buildAlert();
280         historyAlert.show();
281         break;
282       }
283       case SETTINGS_ID: {
284         Intent intent = new Intent(Intent.ACTION_VIEW);
285         intent.setClassName(this, PreferencesActivity.class.getName());
286         startActivity(intent);
287         break;
288       }
289       case HELP_ID: {
290         Intent intent = new Intent(Intent.ACTION_VIEW);
291         intent.setClassName(this, HelpActivity.class.getName());
292         startActivity(intent);
293         break;
294       }
295       case ABOUT_ID:
296         AlertDialog.Builder builder = new AlertDialog.Builder(this);
297         builder.setTitle(getString(R.string.title_about) + versionName);
298         builder.setMessage(getString(R.string.msg_about) + "\n\n" + getString(R.string.zxing_url));
299         builder.setIcon(R.drawable.zxing_icon);
300         builder.setPositiveButton(R.string.button_open_browser, aboutListener);
301         builder.setNegativeButton(R.string.button_cancel, null);
302         builder.show();
303         break;
304     }
305     return super.onOptionsItemSelected(item);
306   }
307
308   @Override
309   public void onConfigurationChanged(Configuration config) {
310     // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
311     super.onConfigurationChanged(config);
312   }
313
314   public void surfaceCreated(SurfaceHolder holder) {
315     if (!hasSurface) {
316       hasSurface = true;
317       initCamera(holder);
318     }
319   }
320
321   public void surfaceDestroyed(SurfaceHolder holder) {
322     hasSurface = false;
323   }
324
325   public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
326
327   }
328
329   /**
330    * A valid barcode has been found, so give an indication of success and show the results.
331    *
332    * @param rawResult The contents of the barcode.
333    * @param barcode   A greyscale bitmap of the camera data which was decoded.
334    */
335   public void handleDecode(Result rawResult, Bitmap barcode) {
336     lastResult = rawResult;
337     historyManager.addHistoryItem(rawResult);
338     if (barcode == null) {
339       // This is from history -- no saved barcode
340       handleDecodeInternally(rawResult, null);
341     } else {
342       playBeepSoundAndVibrate();
343       drawResultPoints(barcode, rawResult);
344       switch (source) {
345         case NATIVE_APP_INTENT:
346         case PRODUCT_SEARCH_LINK:
347           handleDecodeExternally(rawResult, barcode);
348           break;
349         case ZXING_LINK:
350         case NONE:
351           handleDecodeInternally(rawResult, barcode);
352           break;
353       }
354     }
355   }
356
357   /**
358    * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
359    *
360    * @param barcode   A bitmap of the captured image.
361    * @param rawResult The decoded results which contains the points to draw.
362    */
363   private void drawResultPoints(Bitmap barcode, Result rawResult) {
364     ResultPoint[] points = rawResult.getResultPoints();
365     if (points != null && points.length > 0) {
366       Canvas canvas = new Canvas(barcode);
367       Paint paint = new Paint();
368       paint.setColor(getResources().getColor(R.color.result_image_border));
369       paint.setStrokeWidth(3.0f);
370       paint.setStyle(Paint.Style.STROKE);
371       Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
372       canvas.drawRect(border, paint);
373
374       paint.setColor(getResources().getColor(R.color.result_points));
375       if (points.length == 2) {
376         paint.setStrokeWidth(4.0f);
377         canvas.drawLine(points[0].getX(), points[0].getY(), points[1].getX(),
378             points[1].getY(), paint);
379       } else {
380         paint.setStrokeWidth(10.0f);
381         for (ResultPoint point : points) {
382           canvas.drawPoint(point.getX(), point.getY(), paint);
383         }
384       }
385     }
386   }
387
388   // Put up our own UI for how to handle the decoded contents.
389   private void handleDecodeInternally(Result rawResult, Bitmap barcode) {
390     statusView.setVisibility(View.GONE);
391     viewfinderView.setVisibility(View.GONE);
392     resultView.setVisibility(View.VISIBLE);
393
394     if (barcode == null) {
395       barcode = ((BitmapDrawable) getResources().getDrawable(R.drawable.unknown_barcode)).getBitmap();
396     }
397     ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
398     barcodeImageView.setVisibility(View.VISIBLE);
399     barcodeImageView.setMaxWidth(MAX_RESULT_IMAGE_SIZE);
400     barcodeImageView.setMaxHeight(MAX_RESULT_IMAGE_SIZE);
401     barcodeImageView.setImageBitmap(barcode);
402
403     TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
404     formatTextView.setVisibility(View.VISIBLE);
405     formatTextView.setText(getString(R.string.msg_default_format) + ": " +
406         rawResult.getBarcodeFormat().toString());
407
408     ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
409     TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
410     typeTextView.setText(getString(R.string.msg_default_type) + ": " +
411         resultHandler.getType().toString());
412
413     TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
414     CharSequence title = getString(resultHandler.getDisplayTitle());
415     SpannableStringBuilder styled = new SpannableStringBuilder(title + "\n\n");
416     styled.setSpan(new UnderlineSpan(), 0, title.length(), 0);
417     CharSequence displayContents = resultHandler.getDisplayContents();
418     styled.append(displayContents);
419     contentsTextView.setText(styled);
420
421     int buttonCount = resultHandler.getButtonCount();
422     ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
423     buttonView.requestFocus();
424     for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
425       TextView button = (TextView) buttonView.getChildAt(x);
426       if (x < buttonCount) {
427         button.setVisibility(View.VISIBLE);
428         button.setText(resultHandler.getButtonText(x));
429         button.setOnClickListener(new ResultButtonListener(resultHandler, x));
430       } else {
431         button.setVisibility(View.GONE);
432       }
433     }
434
435     if (copyToClipboard) {
436       ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
437       clipboard.setText(displayContents);
438     }
439   }
440
441   // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
442   private void handleDecodeExternally(Result rawResult, Bitmap barcode) {
443     viewfinderView.drawResultBitmap(barcode);
444
445     // Since this message will only be shown for a second, just tell the user what kind of
446     // barcode was found (e.g. contact info) rather than the full contents, which they won't
447     // have time to read.
448     ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
449     TextView textView = (TextView) findViewById(R.id.status_text_view);
450     textView.setGravity(Gravity.CENTER);
451     textView.setTextSize(18.0f);
452     textView.setText(getString(resultHandler.getDisplayTitle()));
453
454     statusView.setBackgroundColor(getResources().getColor(R.color.transparent));
455
456     if (copyToClipboard) {
457       ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
458       clipboard.setText(resultHandler.getDisplayContents());
459     }
460
461     if (source == Source.NATIVE_APP_INTENT) {
462       // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
463       // the deprecated intent is retired.
464       Intent intent = new Intent(getIntent().getAction());
465       intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
466       intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
467       Message message = Message.obtain(handler, R.id.return_scan_result);
468       message.obj = intent;
469       handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
470     } else if (source == Source.PRODUCT_SEARCH_LINK) {
471       // Reformulate the URL which triggered us into a query, so that the request goes to the same
472       // TLD as the scan URL.
473       Message message = Message.obtain(handler, R.id.launch_product_query);
474       int end = sourceUrl.lastIndexOf("/scan");
475       message.obj = sourceUrl.substring(0, end) + "?q=" +
476           resultHandler.getDisplayContents().toString() + "&source=zxing";
477       handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
478     }
479   }
480
481   /**
482    * We want the help screen to be shown automatically the first time a new version of the app is
483    * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
484    * it to a value stored as a preference.
485    */
486   private boolean showHelpOnFirstLaunch() {
487     try {
488       PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
489       int currentVersion = info.versionCode;
490       // Since we're paying to talk to the PackageManager anyway, it makes sense to cache the app
491       // version name here for display in the about box later.
492       this.versionName = info.versionName;
493       SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
494       int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
495       if (currentVersion > lastVersion) {
496         prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
497         Intent intent = new Intent(Intent.ACTION_VIEW);
498         intent.setClassName(this, HelpActivity.class.getName());
499         startActivity(intent);
500         return true;
501       }
502     } catch (PackageManager.NameNotFoundException e) {
503       Log.w(TAG, e);
504     }
505     return false;
506   }
507
508   /**
509    * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least
510    * latency possible.
511    */
512   private void initBeepSound() {
513     if (playBeep && mediaPlayer == null) {
514       // The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
515       // so we now play on the music stream.
516       setVolumeControlStream(AudioManager.STREAM_MUSIC);
517       mediaPlayer = new MediaPlayer();
518       mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
519       mediaPlayer.setOnCompletionListener(beepListener);
520
521       AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
522       try {
523         mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
524             file.getLength());
525         file.close();
526         mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
527         mediaPlayer.prepare();
528       } catch (IOException e) {
529         mediaPlayer = null;
530       }
531     }
532   }
533
534   private void playBeepSoundAndVibrate() {
535     if (playBeep && mediaPlayer != null) {
536       mediaPlayer.start();
537     }
538     if (vibrate) {
539       Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
540       vibrator.vibrate(VIBRATE_DURATION);
541     }
542   }
543
544   private void initCamera(SurfaceHolder surfaceHolder) {
545     try {
546       CameraManager.get().openDriver(surfaceHolder);
547     } catch (IOException ioe) {
548       Log.w(TAG, ioe);
549       return;
550     }
551     if (handler == null) {
552       boolean beginScanning = lastResult == null;
553       handler = new CaptureActivityHandler(this, decodeMode, beginScanning);
554     }
555   }
556
557   private void resetStatusView() {
558     resultView.setVisibility(View.GONE);
559     statusView.setVisibility(View.VISIBLE);
560     statusView.setBackgroundColor(getResources().getColor(R.color.status_view));
561     viewfinderView.setVisibility(View.VISIBLE);
562
563     TextView textView = (TextView) findViewById(R.id.status_text_view);
564     textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
565     textView.setTextSize(14.0f);
566     textView.setText(R.string.msg_default_status);
567     lastResult = null;
568   }
569
570   public void drawViewfinder() {
571     viewfinderView.drawViewfinder();
572   }
573
574   /**
575    * When the beep has finished playing, rewind to queue up another one.
576    */
577   private static class BeepListener implements OnCompletionListener {
578     public void onCompletion(MediaPlayer mediaPlayer) {
579       mediaPlayer.seekTo(0);
580     }
581   }
582 }