Add more unit tests for client.result, and more small code tweaks.
[zxing.git] / android / src / com / google / zxing / client / android / result / ResultHandler.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.result;
18
19 import android.app.Activity;
20 import android.content.Intent;
21 import android.net.Uri;
22 import android.provider.Contacts;
23 import com.google.zxing.client.android.Intents;
24 import com.google.zxing.client.android.R;
25 import com.google.zxing.client.android.SearchBookContentsActivity;
26 import com.google.zxing.client.android.LocaleManager;
27 import com.google.zxing.client.android.Contents;
28 import com.google.zxing.client.result.ParsedResult;
29 import com.google.zxing.client.result.ParsedResultType;
30
31 import java.text.ParsePosition;
32 import java.text.SimpleDateFormat;
33 import java.util.Calendar;
34 import java.text.DateFormat;
35 import java.util.Date;
36 import java.util.GregorianCalendar;
37
38 public abstract class ResultHandler {
39
40   private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
41   private static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
42
43   public static final int MAX_BUTTON_COUNT = 4;
44
45   protected final ParsedResult mResult;
46   private final Activity mActivity;
47
48   protected ResultHandler(Activity activity, ParsedResult result) {
49     mResult = result;
50     mActivity = activity;
51   }
52
53   /**
54    * Indicates how many buttons the derived class wants shown.
55    *
56    * @return The integer button count.
57    */
58   public abstract int getButtonCount();
59
60   /**
61    * The text of the nth action button.
62    *
63    * @param index From 0 to getButtonCount() - 1
64    * @return The button text as a resource ID
65    */
66   public abstract int getButtonText(int index);
67
68
69   /**
70    * Execute the action which corresponds to the nth button.
71    *
72    * @param index The button that was clicked.
73    */
74   public abstract void handleButtonPress(int index);
75
76   /**
77    * Create a possibly styled string for the contents of the current barcode.
78    *
79    * @return The text to be displayed.
80    */
81   public CharSequence getDisplayContents() {
82     String contents = mResult.getDisplayResult();
83     return contents.replace("\r", "");
84   }
85
86   /**
87    * A string describing the kind of barcode that was found, e.g. "Found contact info".
88    *
89    * @return The resource ID of the string.
90    */
91   public abstract int getDisplayTitle();
92
93   /**
94    * A convenience method to get the parsed type. Should not be overridden.
95    *
96    * @return The parsed type, e.g. URI or ISBN
97    */
98   public final ParsedResultType getType() {
99     return mResult.getType();
100   }
101
102   /**
103    * Sends an intent to create a new calendar event by prepopulating the Add Event UI. Older
104    * versions of the system have a bug where the event title will not be filled out.
105    *
106    * @param summary A description of the event
107    * @param start   The start time as yyyyMMdd or yyyyMMdd'T'HHmmss or yyyyMMdd'T'HHmmss'Z'
108    * @param end     The end time as yyyyMMdd or yyyyMMdd'T'HHmmss or yyyyMMdd'T'HHmmss'Z'
109    */
110   public final void addCalendarEvent(String summary, String start, String end) {
111     Intent intent = new Intent(Intent.ACTION_EDIT);
112     intent.setType("vnd.android.cursor.item/event");
113     intent.putExtra("beginTime", calculateMilliseconds(start));
114     if (start.length() == 8) {
115       intent.putExtra("allDay", true);
116     }
117     intent.putExtra("endTime", calculateMilliseconds(end));
118     intent.putExtra("title", summary);
119     launchIntent(intent);
120   }
121
122   private static long calculateMilliseconds(String when) {
123     if (when.length() == 8) {
124       // Only contains year/month/day
125       Date date;
126       synchronized (DATE_FORMAT) {
127         date = DATE_FORMAT.parse(when, new ParsePosition(0));
128       }
129       return date.getTime();
130     } else {
131       // The when string can be local time, or UTC if it ends with a Z
132       Date date;
133       synchronized (DATE_TIME_FORMAT) {
134        date = DATE_TIME_FORMAT.parse(when.substring(0, 15), new ParsePosition(0));
135       }
136       long milliseconds = date.getTime();
137       if (when.length() == 16 && when.charAt(15) == 'Z') {
138         Calendar calendar = new GregorianCalendar();
139         int offset = (calendar.get(java.util.Calendar.ZONE_OFFSET) +
140             calendar.get(java.util.Calendar.DST_OFFSET));
141         milliseconds += offset;
142       }
143       return milliseconds;
144     }
145   }
146
147   public final void addContact(String[] names, String[] phoneNumbers, String[] emails, String note,
148                          String address, String org, String title) {
149
150     Intent intent = new Intent(Contacts.Intents.Insert.ACTION, Contacts.People.CONTENT_URI);
151     putExtra(intent, Contacts.Intents.Insert.NAME, names);
152
153     int phoneCount = Math.min((phoneNumbers != null) ? phoneNumbers.length : 0,
154         Contents.PHONE_KEYS.length);
155     for (int x = 0; x < phoneCount; x++) {
156       putExtra(intent, Contents.PHONE_KEYS[x], phoneNumbers[x]);
157     }
158
159     int emailCount = Math.min((emails != null) ? emails.length : 0, Contents.EMAIL_KEYS.length);
160     for (int x = 0; x < emailCount; x++) {
161       putExtra(intent, Contents.EMAIL_KEYS[x], emails[x]);
162     }
163
164     putExtra(intent, Contacts.Intents.Insert.NOTES, note);
165     putExtra(intent, Contacts.Intents.Insert.POSTAL, address);
166     putExtra(intent, Contacts.Intents.Insert.COMPANY, org);
167     putExtra(intent, Contacts.Intents.Insert.JOB_TITLE, title);
168     launchIntent(intent);
169   }
170
171   public final void shareByEmail(String contents) {
172     sendEmailFromUri("mailto:", mActivity.getString(R.string.msg_share_subject_line), contents);
173   }
174
175   public final void sendEmail(String address, String subject, String body) {
176     sendEmailFromUri("mailto:" + address, subject, body);
177   }
178
179   public final void sendEmailFromUri(String uri, String subject, String body) {
180     Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
181     putExtra(intent, "subject", subject);
182     putExtra(intent, "body", body);
183     launchIntent(intent);
184   }
185
186   public final void shareBySMS(String contents) {
187     sendSMSFromUri("smsto:", mActivity.getString(R.string.msg_share_subject_line) + ":\n" + contents);
188   }
189
190   public final void sendSMS(String phoneNumber, String body) {
191     sendSMSFromUri("smsto:" + phoneNumber, body);
192   }
193
194   public final void sendSMSFromUri(String uri, String body) {
195     Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
196     putExtra(intent, "sms_body", body);
197     // Exit the app once the SMS is sent
198     intent.putExtra("compose_mode", true);
199     launchIntent(intent);
200   }
201
202   public final void sendMMS(String phoneNumber, String subject, String body) {
203     sendMMSFromUri("mmsto:" + phoneNumber, subject, body);
204   }
205
206   public final void sendMMSFromUri(String uri, String subject, String body) {
207     Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
208     // The Messaging app needs to see a valid subject or else it will treat this an an SMS.
209     if (subject == null || subject.length() == 0) {
210       putExtra(intent, "subject", mActivity.getString(R.string.msg_default_mms_subject));
211     } else {
212       putExtra(intent, "subject", subject);
213     }
214     putExtra(intent, "sms_body", body);
215     intent.putExtra("compose_mode", true);
216     launchIntent(intent);
217   }
218
219   public final void dialPhone(String phoneNumber) {
220     launchIntent(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));
221   }
222
223   public final void dialPhoneFromUri(String uri) {
224     launchIntent(new Intent(Intent.ACTION_DIAL, Uri.parse(uri)));
225   }
226
227   public final void openMap(String geoURI) {
228     launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(geoURI)));
229   }
230
231   /**
232    * Do a geo search using the address as the query.
233    *
234    * @param address The address to find
235    * @param title An optional title, e.g. the name of the business at this address
236    */
237   public final void searchMap(String address, String title) {
238     String query = address;
239     if (title != null && title.length() > 0) {
240       query = query + " (" + title + ')';
241     }
242     launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(query))));
243   }
244
245   public final void getDirections(float latitude, float longitude) {
246     launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google." +
247         LocaleManager.getCountryTLD() + "/maps?f=d&daddr=" + latitude + ',' + longitude)));
248   }
249
250   public final void openProductSearch(String upc) {
251     Uri uri = Uri.parse("http://www.google." + LocaleManager.getCountryTLD() + "/products?q=" + upc);
252     launchIntent(new Intent(Intent.ACTION_VIEW, uri));
253   }
254
255   public final void openBookSearch(String isbn) {
256     Uri uri = Uri.parse("http://books.google." + LocaleManager.getCountryTLD() + "/books?vid=isbn" +
257         isbn);
258     launchIntent(new Intent(Intent.ACTION_VIEW, uri));
259   }
260
261   public final void searchBookContents(String isbn) {
262     Intent intent = new Intent(Intents.SearchBookContents.ACTION);
263     intent.setClassName(mActivity, SearchBookContentsActivity.class.getName());
264     putExtra(intent, Intents.SearchBookContents.ISBN, isbn);
265     launchIntent(intent);
266   }
267
268   public final void openURL(String url) {
269     launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
270   }
271
272   public final void webSearch(String query) {
273     Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
274     intent.putExtra("query", query);
275     launchIntent(intent);
276   }
277
278   private void launchIntent(Intent intent) {
279     if (intent != null) {
280       mActivity.startActivity(intent);
281     }
282   }
283
284   private static void putExtra(Intent intent, String key, String value) {
285     if (value != null && value.length() > 0) {
286       intent.putExtra(key, value);
287     }
288   }
289
290   // TODO: This is only used by the names field, and only the first name will be taken.
291   private static void putExtra(Intent intent, String key, String[] value) {
292     if (value != null && value.length > 0) {
293       putExtra(intent, key, value[0]);
294     }
295   }
296
297 }