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