41f3c5b119f936633995078d52825e0041ad5329
[zxing.git] / android / src / com / google / zxing / client / android / encode / QRCodeEncoder.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.MultiFormatWriter;
21 import com.google.zxing.Result;
22 import com.google.zxing.WriterException;
23 import com.google.zxing.client.android.Contents;
24 import com.google.zxing.client.android.Intents;
25 import com.google.zxing.client.android.R;
26 import com.google.zxing.client.result.AddressBookParsedResult;
27 import com.google.zxing.client.result.ParsedResult;
28 import com.google.zxing.client.result.ResultParser;
29 import com.google.zxing.common.BitMatrix;
30
31 import android.app.Activity;
32 import android.content.Intent;
33 import android.graphics.Bitmap;
34 import android.net.Uri;
35 import android.os.Bundle;
36 import android.os.Handler;
37 import android.os.Message;
38 import android.provider.Contacts;
39 import android.telephony.PhoneNumberUtils;
40 import android.util.Log;
41
42 import java.io.FileNotFoundException;
43 import java.io.IOException;
44 import java.io.InputStream;
45
46 /**
47  * This class does the work of decoding the user's request and extracting all the data
48  * to be encoded in a barcode.
49  *
50  * @author dswitkin@google.com (Daniel Switkin)
51  */
52 final class QRCodeEncoder {
53
54   private static final String TAG = QRCodeEncoder.class.getSimpleName();
55
56   private static final int WHITE = 0xFFFFFFFF;
57   private static final int BLACK = 0xFF000000;
58
59   private final Activity activity;
60   private String contents;
61   private String displayContents;
62   private String title;
63   private BarcodeFormat format;
64
65   QRCodeEncoder(Activity activity, Intent intent) {
66     this.activity = activity;
67     if (intent == null) {
68       throw new IllegalArgumentException("No valid data to encode.");
69     }
70
71     String action = intent.getAction();
72     if (action.equals(Intents.Encode.ACTION)) {
73       if (!encodeContentsFromZXingIntent(intent)) {
74         throw new IllegalArgumentException("No valid data to encode.");
75       }
76     } else if (action.equals(Intent.ACTION_SEND)) {
77       if (!encodeContentsFromShareIntent(intent)) {
78         throw new IllegalArgumentException("No valid data to encode.");
79       }
80     }
81   }
82
83   public void requestBarcode(Handler handler, int pixelResolution) {
84     Thread encodeThread = new EncodeThread(contents, handler, pixelResolution,
85         format);
86     encodeThread.start();
87   }
88
89   public String getContents() {
90     return contents;
91   }
92
93   public String getDisplayContents() {
94     return displayContents;
95   }
96
97   public String getTitle() {
98     return title;
99   }
100
101   public String getFormat() {
102     return format.toString();
103   }
104
105   // It would be nice if the string encoding lived in the core ZXing library,
106   // but we use platform specific code like PhoneNumberUtils, so it can't.
107   private boolean encodeContentsFromZXingIntent(Intent intent) {
108      // Default to QR_CODE if no format given.
109     String formatString = intent.getStringExtra(Intents.Encode.FORMAT);
110     try {
111       format = BarcodeFormat.valueOf(formatString);
112     } catch (IllegalArgumentException iae) {
113       // Ignore it then
114       format = null;
115       formatString = null;
116     }
117     if (format == null || BarcodeFormat.QR_CODE.equals(format)) {
118       String type = intent.getStringExtra(Intents.Encode.TYPE);
119       if (type == null || type.length() == 0) {
120         return false;
121       }
122       this.format = BarcodeFormat.QR_CODE;
123       encodeQRCodeContents(intent, type);
124     } else {
125       String data = intent.getStringExtra(Intents.Encode.DATA);
126       if (data != null && data.length() != 0) {
127         contents = data;
128         displayContents = data;
129         title = activity.getString(R.string.contents_text);
130       }
131     }
132     return contents != null && contents.length() > 0;
133   }
134
135   // Handles send intents from the Contacts app, retrieving a contact as a VCARD.
136   private boolean encodeContentsFromShareIntent(Intent intent) {
137     format = BarcodeFormat.QR_CODE;
138     try {
139       Uri uri = (Uri)intent.getExtras().getParcelable(Intent.EXTRA_STREAM);
140       InputStream stream = activity.getContentResolver().openInputStream(uri);
141       int length = stream.available();
142       byte[] vcard = new byte[length];
143       stream.read(vcard, 0, length);
144       String vcardString = new String(vcard, "UTF-8");
145       Log.d(TAG, "Encoding share intent content: " + vcardString);
146       Result result = new Result(vcardString, vcard, null, BarcodeFormat.QR_CODE);
147       ParsedResult parsedResult = ResultParser.parseResult(result);
148       if (!(parsedResult instanceof AddressBookParsedResult)) {
149         return false;
150       }
151       if (!encodeQRCodeContents((AddressBookParsedResult) parsedResult)) {
152         return false;
153       }
154     } catch (FileNotFoundException e) {
155       return false;
156     } catch (IOException e) {
157       return false;
158     } catch (NullPointerException e) {
159       // In case the uri was not found in the Intent.
160       return false;
161     }
162     return contents != null && contents.length() > 0;
163   }
164
165   private void encodeQRCodeContents(Intent intent, String type) {
166     if (type.equals(Contents.Type.TEXT)) {
167       String data = intent.getStringExtra(Intents.Encode.DATA);
168       if (data != null && data.length() > 0) {
169         contents = data;
170         displayContents = data;
171         title = activity.getString(R.string.contents_text);
172       }
173     } else if (type.equals(Contents.Type.EMAIL)) {
174       String data = intent.getStringExtra(Intents.Encode.DATA);
175       if (data != null && data.length() > 0) {
176         contents = "mailto:" + data;
177         displayContents = data;
178         title = activity.getString(R.string.contents_email);
179       }
180     } else if (type.equals(Contents.Type.PHONE)) {
181       String data = intent.getStringExtra(Intents.Encode.DATA);
182       if (data != null && data.length() > 0) {
183         contents = "tel:" + data;
184         displayContents = PhoneNumberUtils.formatNumber(data);
185         title = activity.getString(R.string.contents_phone);
186       }
187     } else if (type.equals(Contents.Type.SMS)) {
188       String data = intent.getStringExtra(Intents.Encode.DATA);
189       if (data != null && data.length() > 0) {
190         contents = "sms:" + data;
191         displayContents = PhoneNumberUtils.formatNumber(data);
192         title = activity.getString(R.string.contents_sms);
193       }
194     } else if (type.equals(Contents.Type.CONTACT)) {
195       Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
196       if (bundle != null) {
197         StringBuilder newContents = new StringBuilder();
198         StringBuilder newDisplayContents = new StringBuilder();
199         newContents.append("MECARD:");
200         String name = bundle.getString(Contacts.Intents.Insert.NAME);
201         if (name != null && name.length() > 0) {
202           newContents.append("N:").append(name).append(';');
203           newDisplayContents.append(name);
204         }
205         String address = bundle.getString(Contacts.Intents.Insert.POSTAL);
206         if (address != null && address.length() > 0) {
207           newContents.append("ADR:").append(address).append(';');
208           newDisplayContents.append('\n').append(address);
209         }
210         for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
211           String phone = bundle.getString(Contents.PHONE_KEYS[x]);
212           if (phone != null && phone.length() > 0) {
213             newContents.append("TEL:").append(phone).append(';');
214             newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
215           }
216         }
217         for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
218           String email = bundle.getString(Contents.EMAIL_KEYS[x]);
219           if (email != null && email.length() > 0) {
220             newContents.append("EMAIL:").append(email).append(';');
221             newDisplayContents.append('\n').append(email);
222           }
223         }
224         // Make sure we've encoded at least one field.
225         if (newDisplayContents.length() > 0) {
226           newContents.append(';');
227           contents = newContents.toString();
228           displayContents = newDisplayContents.toString();
229           title = activity.getString(R.string.contents_contact);
230         } else {
231           contents = null;
232           displayContents = null;
233         }
234       }
235     } else if (type.equals(Contents.Type.LOCATION)) {
236       Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
237       if (bundle != null) {
238         // These must use Bundle.getFloat(), not getDouble(), it's part of the API.
239         float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
240         float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
241         if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
242           contents = "geo:" + latitude + ',' + longitude;
243           displayContents = latitude + "," + longitude;
244           title = activity.getString(R.string.contents_location);
245         }
246       }
247     }
248   }
249
250   private boolean encodeQRCodeContents(AddressBookParsedResult contact) {
251     StringBuilder newContents = new StringBuilder();
252     StringBuilder newDisplayContents = new StringBuilder();
253     newContents.append("MECARD:");
254     String[] names = contact.getNames();
255     if (names != null && names.length > 0) {
256       newContents.append("N:").append(names[0]).append(';');
257       newDisplayContents.append(names[0]);
258     }
259     String[] addresses = contact.getAddresses();
260     if (addresses != null) {
261       for (int x = 0; x < addresses.length; x++) {
262         if (addresses[x] != null && addresses[x].length() > 0) {
263           newContents.append("ADR:").append(addresses[x]).append(';');
264           newDisplayContents.append('\n').append(addresses[x]);
265         }
266       }
267     }
268     String[] phoneNumbers = contact.getPhoneNumbers();
269     if (phoneNumbers != null) {
270       for (int x = 0; x < phoneNumbers.length; x++) {
271         String phone = phoneNumbers[x];
272         if (phone != null && phone.length() > 0) {
273           newContents.append("TEL:").append(phone).append(';');
274           newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
275         }
276       }
277     }
278     String[] emails = contact.getEmails();
279     if (emails != null) {
280       for (int x = 0; x < emails.length; x++) {
281         String email = emails[x];
282         if (email != null && email.length() > 0) {
283           newContents.append("EMAIL:").append(email).append(';');
284           newDisplayContents.append('\n').append(email);
285         }
286       }
287     }
288     String url = contact.getURL();
289     if (url != null && url.length() > 0) {
290       newContents.append("URL:").append(url).append(';');
291       newDisplayContents.append('\n').append(url);
292     }
293     // Make sure we've encoded at least one field.
294     if (newDisplayContents.length() > 0) {
295       newContents.append(';');
296       contents = newContents.toString();
297       displayContents = newDisplayContents.toString();
298       title = activity.getString(R.string.contents_contact);
299       return true;
300     } else {
301       contents = null;
302       displayContents = null;
303       return false;
304     }
305   }
306
307   static Bitmap encodeAsBitmap(String contents,
308                                BarcodeFormat format,
309                                int desiredWidth,
310                                int desiredHeight) throws WriterException {
311     BitMatrix result = new MultiFormatWriter().encode(contents, format,
312         desiredWidth, desiredHeight);
313     int width = result.getWidth();
314     int height = result.getHeight();
315     int[] pixels = new int[width * height];
316     // All are 0, or black, by default
317     for (int y = 0; y < height; y++) {
318       int offset = y * width;
319       for (int x = 0; x < width; x++) {
320         pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
321       }
322     }
323
324     Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
325     bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
326     return bitmap;
327   }
328
329   private static final class EncodeThread extends Thread {
330
331     private static final String TAG = EncodeThread.class.getSimpleName();
332
333     private final String contents;
334     private final Handler handler;
335     private final int pixelResolution;
336     private final BarcodeFormat format;
337
338     EncodeThread(String contents, Handler handler, int pixelResolution,
339         BarcodeFormat format) {
340       this.contents = contents;
341       this.handler = handler;
342       this.pixelResolution = pixelResolution;
343       this.format = format;
344     }
345
346     @Override
347     public void run() {
348       try {
349         Bitmap bitmap = encodeAsBitmap(contents, format, pixelResolution, pixelResolution);
350         Message message = Message.obtain(handler, R.id.encode_succeeded);
351         message.obj = bitmap;
352         message.sendToTarget();
353       } catch (WriterException e) {
354         Log.e(TAG, e.toString());
355         Message message = Message.obtain(handler, R.id.encode_failed);
356         message.sendToTarget();
357       } catch (IllegalArgumentException e) {
358         Log.e(TAG, e.toString());
359         Message message = Message.obtain(handler, R.id.encode_failed);
360         message.sendToTarget();
361       }
362     }
363   }
364 }