Updated the zxing folder with the latest SVN version, changed the CameraImageWrapper...
[zxing.git] / android / src / com / google / zxing / client / android / encode / EncodeActivity.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.encode;
18
19 import com.google.zxing.BarcodeFormat;
20 import com.google.zxing.WriterException;
21 import com.google.zxing.client.android.Intents;
22 import com.google.zxing.client.android.R;
23
24 import android.app.Activity;
25 import android.app.AlertDialog;
26 import android.app.ProgressDialog;
27 import android.content.DialogInterface;
28 import android.content.DialogInterface.OnCancelListener;
29 import android.content.DialogInterface.OnClickListener;
30 import android.content.Intent;
31 import android.graphics.Bitmap;
32 import android.net.Uri;
33 import android.os.Bundle;
34 import android.os.Handler;
35 import android.os.Environment;
36 import android.os.Message;
37 import android.util.Log;
38 import android.view.Menu;
39 import android.view.MenuItem;
40 import android.view.View;
41 import android.view.ViewTreeObserver.OnGlobalLayoutListener;
42 import android.widget.ImageView;
43 import android.widget.TextView;
44
45 import java.io.File;
46 import java.io.FileNotFoundException;
47 import java.io.FileOutputStream;
48 import java.io.IOException;
49
50 /**
51  * This class encodes data from an Intent into a QR code, and then displays it full screen so that
52  * another person can scan it with their device.
53  *
54  * @author dswitkin@google.com (Daniel Switkin)
55  */
56 public final class EncodeActivity extends Activity {
57
58   private static final String TAG = EncodeActivity.class.getSimpleName();
59
60   private static final int SHARE_BARCODE_DIMENSION = 300;
61   private static final int MAX_BARCODE_FILENAME_LENGTH = 24;
62
63   private QRCodeEncoder qrCodeEncoder;
64   private ProgressDialog progressDialog;
65   private boolean firstLayout;
66
67   /**
68    * This needs to be delayed until after the first layout so that the view dimensions will be
69    * available.
70    */
71   private final OnGlobalLayoutListener layoutListener = new OnGlobalLayoutListener() {
72     public void onGlobalLayout() {
73       if (firstLayout) {
74         View layout = findViewById(R.id.encode_view);
75         int width = layout.getWidth();
76         int height = layout.getHeight();
77         int smallerDimension = width < height ? width : height;
78         smallerDimension = smallerDimension * 7 / 8;
79
80         Intent intent = getIntent();
81         try {
82           qrCodeEncoder = new QRCodeEncoder(EncodeActivity.this, intent);
83           setTitle(getString(R.string.app_name) + " - " + qrCodeEncoder.getTitle());
84           qrCodeEncoder.requestBarcode(handler, smallerDimension);
85           progressDialog = ProgressDialog.show(EncodeActivity.this, null,
86               getString(R.string.msg_encode_in_progress), true, true, cancelListener);
87         } catch (IllegalArgumentException e) {
88           showErrorMessage(R.string.msg_encode_contents_failed);
89         }
90         firstLayout = false;
91       }
92     }
93   };
94
95   private final Handler handler = new Handler() {
96     @Override
97     public void handleMessage(Message message) {
98       switch (message.what) {
99         case R.id.encode_succeeded:
100           progressDialog.dismiss();
101           progressDialog = null;
102           Bitmap image = (Bitmap) message.obj;
103           ImageView view = (ImageView) findViewById(R.id.image_view);
104           view.setImageBitmap(image);
105           TextView contents = (TextView) findViewById(R.id.contents_text_view);
106           contents.setText(qrCodeEncoder.getDisplayContents());
107           //qrCodeEncoder = null;
108           break;
109         case R.id.encode_failed:
110           showErrorMessage(R.string.msg_encode_barcode_failed);
111           qrCodeEncoder = null;
112           break;
113       }
114     }
115   };
116
117   private final OnClickListener clickListener = new OnClickListener() {
118     public void onClick(DialogInterface dialog, int which) {
119       finish();
120     }
121   };
122
123   private final OnCancelListener cancelListener = new OnCancelListener() {
124     public void onCancel(DialogInterface dialog) {
125       finish();
126     }
127   };
128
129   @Override
130   public void onCreate(Bundle icicle) {
131     super.onCreate(icicle);
132
133     Intent intent = getIntent();
134     if (intent != null) {
135       String action = intent.getAction();
136       if (action.equals(Intents.Encode.ACTION) || action.equals(Intent.ACTION_SEND)) {
137         setContentView(R.layout.encode);
138         return;
139       }
140     }
141     finish();
142   }
143
144   @Override
145   public boolean onCreateOptionsMenu(Menu menu) {
146     super.onCreateOptionsMenu(menu);
147     menu.add(0, Menu.FIRST, 0, R.string.menu_share).setIcon(android.R.drawable.ic_menu_share);
148     return true;
149   }
150
151   @Override
152   public boolean onOptionsItemSelected(MenuItem item) {
153     if (qrCodeEncoder == null) { // Odd
154       Log.w(TAG, "No existing barcode to send?");
155       return true;
156     }
157
158     String contents = qrCodeEncoder.getContents();
159     Bitmap bitmap;
160     try {
161       bitmap = QRCodeEncoder.encodeAsBitmap(contents, BarcodeFormat.QR_CODE,
162           SHARE_BARCODE_DIMENSION, SHARE_BARCODE_DIMENSION);
163     } catch (WriterException we) {
164       Log.w(TAG, we.toString());
165       return true;
166     }
167
168     File bsRoot = new File(Environment.getExternalStorageDirectory(), "BarcodeScanner");
169     File barcodesRoot = new File(bsRoot, "Barcodes");
170     if (!barcodesRoot.exists() && !barcodesRoot.mkdirs()) {
171       Log.v(TAG, "Couldn't make dir " + barcodesRoot);
172       showErrorMessage(R.string.msg_unmount_usb);
173       return true;
174     }
175     File barcodeFile = new File(barcodesRoot, makeBarcodeFileName(contents) + ".png");
176     barcodeFile.delete();
177     FileOutputStream fos = null;
178     try {
179       fos = new FileOutputStream(barcodeFile);
180       bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos);
181     } catch (FileNotFoundException fnfe) {
182       Log.v(TAG, "Couldn't access file " + barcodeFile + " due to " + fnfe);
183       showErrorMessage(R.string.msg_unmount_usb);
184       return true;
185     } finally {
186       if (fos != null) {
187         try {
188           fos.close();
189         } catch (IOException ioe) {
190           // do nothing
191         }
192       }
193     }
194
195     Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
196     intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name) + " - " +
197         qrCodeEncoder.getTitle());
198     intent.putExtra(Intent.EXTRA_TEXT, qrCodeEncoder.getContents());
199     intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + barcodeFile.getAbsolutePath()));
200     intent.setType("image/png");
201     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
202     startActivity(Intent.createChooser(intent, null));
203     return true;
204   }
205
206   private static CharSequence makeBarcodeFileName(CharSequence contents) {
207     int fileNameLength = Math.min(MAX_BARCODE_FILENAME_LENGTH, contents.length());
208     StringBuilder fileName = new StringBuilder(fileNameLength);
209     for (int i = 0; i < fileNameLength; i++) {
210       char c = contents.charAt(i);
211       if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) {
212         fileName.append(c);
213       } else {
214         fileName.append('_');
215       }
216     }
217     return fileName;
218   }
219
220   @Override
221   protected void onResume() {
222     super.onResume();
223
224     View layout = findViewById(R.id.encode_view);
225     layout.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
226     firstLayout = true;
227   }
228
229   private void showErrorMessage(int message) {
230     if (progressDialog != null) {
231       progressDialog.dismiss();
232       progressDialog = null;
233     }
234     AlertDialog.Builder builder = new AlertDialog.Builder(this);
235     builder.setMessage(message);
236     builder.setPositiveButton(R.string.button_ok, clickListener);
237     builder.show();
238   }
239 }