1. Set up all strings in res/*/strings.xml rather than as string
[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 com.google.zxing.Result;
20 import com.google.zxing.client.android.Contents;
21 import com.google.zxing.client.android.Intents;
22 import com.google.zxing.client.android.LocaleManager;
23 import com.google.zxing.client.android.PreferencesActivity;
24 import com.google.zxing.client.android.R;
25 import com.google.zxing.client.android.book.SearchBookContentsActivity;
26 import com.google.zxing.client.android.wifi.WifiActivity;
27 import com.google.zxing.client.result.ParsedResult;
28 import com.google.zxing.client.result.ParsedResultType;
29 import com.google.zxing.client.result.WifiParsedResult;
30
31 import android.app.Activity;
32 import android.app.AlertDialog;
33 import android.app.SearchManager;
34 import android.content.ActivityNotFoundException;
35 import android.content.DialogInterface;
36 import android.content.Intent;
37 import android.content.SharedPreferences;
38 import android.content.pm.PackageManager;
39 import android.net.Uri;
40 import android.preference.PreferenceManager;
41 import android.provider.Contacts;
42
43 import java.text.DateFormat;
44 import java.text.ParsePosition;
45 import java.text.SimpleDateFormat;
46 import java.util.Calendar;
47 import java.util.Date;
48 import java.util.GregorianCalendar;
49
50 /**
51  * A base class for the Android-specific barcode handlers. These allow the app to polymorphically
52  * suggest the appropriate actions for each data type.
53  *
54  * This class also contains a bunch of utility methods to take common actions like opening a URL.
55  * They could easily be moved into a helper object, but it can't be static because the Activity
56  * instance is needed to launch an intent.
57  *
58  * @author dswitkin@google.com (Daniel Switkin)
59  */
60 public abstract class ResultHandler {
61   private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
62   private static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
63
64   private static final String GOOGLE_SHOPPER_PACKAGE = "com.google.android.apps.shopper";
65   private static final String GOOGLE_SHOPPER_ACTIVITY = GOOGLE_SHOPPER_PACKAGE +
66       ".results.SearchResultsActivity";
67   private static final String MARKET_URI_PREFIX = "market://search?q=pname:";
68   private static final String MARKET_REFERRER_SUFFIX =
69       "&referrer=utm_source%3Dbarcodescanner%26utm_medium%3Dapps%26utm_campaign%3Dscan";
70
71   public static final int MAX_BUTTON_COUNT = 4;
72
73   private final ParsedResult result;
74   private final Activity activity;
75   private final Result rawResult;
76   private final String customProductSearch;
77
78   private final DialogInterface.OnClickListener shopperMarketListener =
79       new DialogInterface.OnClickListener() {
80     public void onClick(DialogInterface dialogInterface, int which) {
81       launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_URI_PREFIX +
82           GOOGLE_SHOPPER_PACKAGE + MARKET_REFERRER_SUFFIX)));
83     }
84   };
85
86   ResultHandler(Activity activity, ParsedResult result) {
87     this(activity, result, null);
88   }
89
90   ResultHandler(Activity activity, ParsedResult result, Result rawResult) {
91     this.result = result;
92     this.activity = activity;
93     this.rawResult = rawResult;
94     this.customProductSearch = parseCustomSearchURL();
95   }
96
97   ParsedResult getResult() {
98     return result;
99   }
100
101   boolean hasCustomProductSearch() {
102     return customProductSearch != null;
103   }
104
105   /**
106    * Indicates how many buttons the derived class wants shown.
107    *
108    * @return The integer button count.
109    */
110   public abstract int getButtonCount();
111
112   /**
113    * The text of the nth action button.
114    *
115    * @param index From 0 to getButtonCount() - 1
116    * @return The button text as a resource ID
117    */
118   public abstract int getButtonText(int index);
119
120
121   /**
122    * Execute the action which corresponds to the nth button.
123    *
124    * @param index The button that was clicked.
125    */
126   public abstract void handleButtonPress(int index);
127
128   /**
129    * Create a possibly styled string for the contents of the current barcode.
130    *
131    * @return The text to be displayed.
132    */
133   public CharSequence getDisplayContents() {
134     String contents = result.getDisplayResult();
135     return contents.replace("\r", "");
136   }
137
138   /**
139    * A string describing the kind of barcode that was found, e.g. "Found contact info".
140    *
141    * @return The resource ID of the string.
142    */
143   public abstract int getDisplayTitle();
144
145   /**
146    * A convenience method to get the parsed type. Should not be overridden.
147    *
148    * @return The parsed type, e.g. URI or ISBN
149    */
150   public final ParsedResultType getType() {
151     return result.getType();
152   }
153
154   /**
155    * Sends an intent to create a new calendar event by prepopulating the Add Event UI. Older
156    * versions of the system have a bug where the event title will not be filled out.
157    *
158    * @param summary A description of the event
159    * @param start   The start time as yyyyMMdd or yyyyMMdd'T'HHmmss or yyyyMMdd'T'HHmmss'Z'
160    * @param end     The end time as yyyyMMdd or yyyyMMdd'T'HHmmss or yyyyMMdd'T'HHmmss'Z'
161    * @param location a text description of the event location
162    * @param description a text description of the event itself
163    */
164   final void addCalendarEvent(String summary, 
165                               String start,
166                               String end,
167                               String location,
168                               String description) {
169     Intent intent = new Intent(Intent.ACTION_EDIT);
170     intent.setType("vnd.android.cursor.item/event");
171     intent.putExtra("beginTime", calculateMilliseconds(start));
172     if (start.length() == 8) {
173       intent.putExtra("allDay", true);
174     }
175     if (end == null) {
176       end = start;
177     }
178     intent.putExtra("endTime", calculateMilliseconds(end));
179     intent.putExtra("title", summary);
180     intent.putExtra("eventLocation", location);
181     intent.putExtra("description", description);
182     launchIntent(intent);
183   }
184
185   private static long calculateMilliseconds(String when) {
186     if (when.length() == 8) {
187       // Only contains year/month/day
188       Date date;
189       synchronized (DATE_FORMAT) {
190         date = DATE_FORMAT.parse(when, new ParsePosition(0));
191       }
192       return date.getTime();
193     } else {
194       // The when string can be local time, or UTC if it ends with a Z
195       Date date;
196       synchronized (DATE_TIME_FORMAT) {
197        date = DATE_TIME_FORMAT.parse(when.substring(0, 15), new ParsePosition(0));
198       }
199       long milliseconds = date.getTime();
200       if (when.length() == 16 && when.charAt(15) == 'Z') {
201         Calendar calendar = new GregorianCalendar();
202         int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
203         milliseconds += offset;
204       }
205       return milliseconds;
206     }
207   }
208
209   final void addContact(String[] names, String[] phoneNumbers, String[] emails, String note,
210                          String address, String org, String title) {
211
212     // Only use the first name in the array, if present.
213     Intent intent = new Intent(Contacts.Intents.Insert.ACTION, Contacts.People.CONTENT_URI);
214     putExtra(intent, Contacts.Intents.Insert.NAME, names != null ? names[0] : null);
215
216     int phoneCount = Math.min((phoneNumbers != null) ? phoneNumbers.length : 0,
217         Contents.PHONE_KEYS.length);
218     for (int x = 0; x < phoneCount; x++) {
219       putExtra(intent, Contents.PHONE_KEYS[x], phoneNumbers[x]);
220     }
221
222     int emailCount = Math.min((emails != null) ? emails.length : 0, Contents.EMAIL_KEYS.length);
223     for (int x = 0; x < emailCount; x++) {
224       putExtra(intent, Contents.EMAIL_KEYS[x], emails[x]);
225     }
226
227     putExtra(intent, Contacts.Intents.Insert.NOTES, note);
228     putExtra(intent, Contacts.Intents.Insert.POSTAL, address);
229     putExtra(intent, Contacts.Intents.Insert.COMPANY, org);
230     putExtra(intent, Contacts.Intents.Insert.JOB_TITLE, title);
231     launchIntent(intent);
232   }
233
234   final void shareByEmail(String contents) {
235     sendEmailFromUri("mailto:", null, activity.getString(R.string.msg_share_subject_line), contents);
236   }
237
238   final void sendEmail(String address, String subject, String body) {
239     sendEmailFromUri("mailto:" + address, address, subject, body);
240   }
241
242   // Use public Intent fields rather than private GMail app fields to specify subject and body.
243   final void sendEmailFromUri(String uri, String email, String subject, String body) {
244     Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse(uri));
245     if (email != null) {
246       intent.putExtra(Intent.EXTRA_EMAIL, new String[] {email});
247     }
248     putExtra(intent, Intent.EXTRA_SUBJECT, subject);
249     putExtra(intent, Intent.EXTRA_TEXT, body);
250     intent.setType("text/plain");
251     launchIntent(intent);
252   }
253
254   final void shareBySMS(String contents) {
255     sendSMSFromUri("smsto:", activity.getString(R.string.msg_share_subject_line) + ":\n" +
256         contents);
257   }
258
259   final void sendSMS(String phoneNumber, String body) {
260     sendSMSFromUri("smsto:" + phoneNumber, body);
261   }
262
263   final void sendSMSFromUri(String uri, String body) {
264     Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
265     putExtra(intent, "sms_body", body);
266     // Exit the app once the SMS is sent
267     intent.putExtra("compose_mode", true);
268     launchIntent(intent);
269   }
270
271   final void sendMMS(String phoneNumber, String subject, String body) {
272     sendMMSFromUri("mmsto:" + phoneNumber, subject, body);
273   }
274
275   final void sendMMSFromUri(String uri, String subject, String body) {
276     Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));
277     // The Messaging app needs to see a valid subject or else it will treat this an an SMS.
278     if (subject == null || subject.length() == 0) {
279       putExtra(intent, "subject", activity.getString(R.string.msg_default_mms_subject));
280     } else {
281       putExtra(intent, "subject", subject);
282     }
283     putExtra(intent, "sms_body", body);
284     intent.putExtra("compose_mode", true);
285     launchIntent(intent);
286   }
287
288   final void dialPhone(String phoneNumber) {
289     launchIntent(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));
290   }
291
292   final void dialPhoneFromUri(String uri) {
293     launchIntent(new Intent(Intent.ACTION_DIAL, Uri.parse(uri)));
294   }
295
296   final void openMap(String geoURI) {
297     launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(geoURI)));
298   }
299
300   /**
301    * Do a geo search using the address as the query.
302    *
303    * @param address The address to find
304    * @param title An optional title, e.g. the name of the business at this address
305    */
306   final void searchMap(String address, String title) {
307     String query = address;
308     if (title != null && title.length() > 0) {
309       query = query + " (" + title + ')';
310     }
311     launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(query))));
312   }
313
314   final void getDirections(double latitude, double longitude) {
315     launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google." +
316         LocaleManager.getCountryTLD() + "/maps?f=d&daddr=" + latitude + ',' + longitude)));
317   }
318
319   // Uses the mobile-specific version of Product Search, which is formatted for small screens.
320   final void openProductSearch(String upc) {
321     Uri uri = Uri.parse("http://www.google." + LocaleManager.getProductSearchCountryTLD() +
322         "/m/products?q=" + upc + "&source=zxing");
323     launchIntent(new Intent(Intent.ACTION_VIEW, uri));
324   }
325
326   final void openBookSearch(String isbn) {
327     Uri uri = Uri.parse("http://books.google." + LocaleManager.getBookSearchCountryTLD() +
328         "/books?vid=isbn" + isbn);
329     launchIntent(new Intent(Intent.ACTION_VIEW, uri));
330   }
331
332   final void searchBookContents(String isbn) {
333     Intent intent = new Intent(Intents.SearchBookContents.ACTION);
334     intent.setClassName(activity, SearchBookContentsActivity.class.getName());
335     putExtra(intent, Intents.SearchBookContents.ISBN, isbn);
336     launchIntent(intent);
337   }
338
339   final void wifiConnect(WifiParsedResult wifiResult) {
340     Intent intent = new Intent(Intents.WifiConnect.ACTION);
341     intent.setClassName(activity, WifiActivity.class.getName());
342     putExtra(intent, Intents.WifiConnect.SSID, wifiResult.getSsid());
343     putExtra(intent, Intents.WifiConnect.TYPE, wifiResult.getNetworkEncryption());
344     putExtra(intent, Intents.WifiConnect.PASSWORD, wifiResult.getPassword());
345     launchIntent(intent);
346   }
347
348   final void openURL(String url) {
349     launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
350   }
351
352   final void webSearch(String query) {
353     Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
354     intent.putExtra("query", query);
355     launchIntent(intent);
356   }
357
358   final void openGoogleShopper(String query) {
359     try {
360       activity.getPackageManager().getPackageInfo(GOOGLE_SHOPPER_PACKAGE, 0);
361       // If we didn't throw, Shopper is installed, so launch it.
362       Intent intent = new Intent(Intent.ACTION_SEARCH);
363       intent.setClassName(GOOGLE_SHOPPER_PACKAGE, GOOGLE_SHOPPER_ACTIVITY);
364       intent.putExtra(SearchManager.QUERY, query);
365       activity.startActivity(intent);
366     } catch (PackageManager.NameNotFoundException e) {
367       // Otherwise offer to install it from Market.
368       AlertDialog.Builder builder = new AlertDialog.Builder(activity);
369       builder.setTitle(R.string.msg_google_shopper_missing);
370       builder.setMessage(R.string.msg_install_google_shopper);
371       builder.setIcon(R.drawable.shopper_icon);
372       builder.setPositiveButton(R.string.button_ok, shopperMarketListener);
373       builder.setNegativeButton(R.string.button_cancel, null);
374       builder.show();
375     }
376   }
377
378   void launchIntent(Intent intent) {
379     if (intent != null) {
380       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
381       try {
382         activity.startActivity(intent);
383       } catch (ActivityNotFoundException e) {
384         AlertDialog.Builder builder = new AlertDialog.Builder(activity);
385         builder.setTitle(R.string.app_name);
386         builder.setMessage(R.string.msg_intent_failed);
387         builder.setPositiveButton(R.string.button_ok, null);
388         builder.show();
389       }
390     }
391   }
392
393   private static void putExtra(Intent intent, String key, String value) {
394     if (value != null && value.length() > 0) {
395       intent.putExtra(key, value);
396     }
397   }
398
399   protected void showNotOurResults(int index, AlertDialog.OnClickListener proceedListener) {
400     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
401     if (prefs.getBoolean(PreferencesActivity.KEY_NOT_OUR_RESULTS_SHOWN, false)) {
402       // already seen it, just proceed
403       proceedListener.onClick(null, index);
404     } else {
405       // note the user has seen it
406       prefs.edit().putBoolean(PreferencesActivity.KEY_NOT_OUR_RESULTS_SHOWN, true).commit();
407       AlertDialog.Builder builder = new AlertDialog.Builder(activity);
408       builder.setMessage(R.string.msg_not_our_results);
409       builder.setPositiveButton(R.string.button_ok, proceedListener);
410       builder.show();
411     }
412   }
413
414   private String parseCustomSearchURL() {
415     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
416     String customProductSearch = prefs.getString(PreferencesActivity.KEY_CUSTOM_PRODUCT_SEARCH, null);
417     if (customProductSearch != null && customProductSearch.trim().length() == 0) {
418       return null;
419     }
420     return customProductSearch;
421   }
422
423   String fillInCustomSearchURL(String text) {
424     String url = customProductSearch.replace("%s", text);
425     if (rawResult != null) {
426       url = url.replace("%f", rawResult.getBarcodeFormat().toString());
427     }
428     return url;
429   }
430
431 }