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