Better naming of shared barcode files and deal with case where SD card is mounted
[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,
162                                             BarcodeFormat.QR_CODE,
163                                             SHARE_BARCODE_DIMENSION,
164                                             SHARE_BARCODE_DIMENSION);
165     } catch (WriterException we) {
166       Log.w(TAG, we.toString());
167       return true;
168     }
169
170     File barcodeFile;
171     try {
172       File bsRoot = new File(Environment.getExternalStorageDirectory(), "BarcodeScanner");
173       File barcodesRoot = new File(bsRoot, "Barcodes");
174       if (!barcodesRoot.mkdirs()) {
175         Log.v(TAG, "Couldn't make dir " + barcodesRoot);
176         showErrorMessage(R.string.msg_unmount_usb);
177         return true;
178       }
179       barcodeFile = new File(barcodesRoot, makeBarcodeFileName(contents) + ".png");
180       barcodeFile.delete();
181       FileOutputStream fos = null;
182       try {
183         fos = new FileOutputStream(barcodeFile);
184         bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos);
185       } catch (FileNotFoundException fnfe) {
186         Log.v(TAG, "Couldn't access file " + barcodeFile + " due to " + fnfe);
187         showErrorMessage(R.string.msg_unmount_usb);
188         return true;
189       } finally {
190         if (fos != null) {
191           fos.close();
192         }
193       }
194     } catch (IOException ioe) {
195       Log.w(TAG, ioe.toString());
196       return true;
197     }
198
199     Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
200     intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name) + " - " + qrCodeEncoder.getTitle());
201     intent.putExtra(Intent.EXTRA_TEXT, qrCodeEncoder.getContents());
202     intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + barcodeFile.getAbsolutePath()));
203     intent.setType("image/png");
204     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
205     startActivity(Intent.createChooser(intent, null));
206     return true;
207   }
208
209   private static CharSequence makeBarcodeFileName(CharSequence contents) {
210     int fileNameLength = Math.min(MAX_BARCODE_FILENAME_LENGTH, contents.length());
211     StringBuilder fileName = new StringBuilder(fileNameLength);
212     for (int i = 0; i < fileNameLength; i++) {
213       char c = contents.charAt(i);
214       if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) {
215         fileName.append(c);
216       } else {
217         fileName.append('_');
218       }
219     }
220     return fileName;
221   }
222
223   @Override
224   protected void onResume() {
225     super.onResume();
226
227     View layout = findViewById(R.id.encode_view);
228     layout.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
229     firstLayout = true;
230   }
231
232   private void showErrorMessage(int message) {
233     if (progressDialog != null) {
234       progressDialog.dismiss();
235       progressDialog = null;
236     }
237     AlertDialog.Builder builder = new AlertDialog.Builder(this);
238     builder.setMessage(message);
239     builder.setPositiveButton(R.string.button_ok, clickListener);
240     builder.show();
241   }
242 }