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