Home | History | Annotate | Download | only in calendar
      1 /*
      2  * Copyright (C) 2006 The Android Open Source Project
      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.android.calendar;
     18 
     19 import static android.provider.CalendarContract.EXTRA_EVENT_BEGIN_TIME;
     20 
     21 import android.accounts.Account;
     22 import android.app.Activity;
     23 import android.app.SearchManager;
     24 import android.content.BroadcastReceiver;
     25 import android.content.ContentResolver;
     26 import android.content.Context;
     27 import android.content.Intent;
     28 import android.content.IntentFilter;
     29 import android.content.SharedPreferences;
     30 import android.content.pm.PackageManager;
     31 import android.content.res.Resources;
     32 import android.database.Cursor;
     33 import android.database.MatrixCursor;
     34 import android.graphics.Color;
     35 import android.graphics.drawable.Drawable;
     36 import android.graphics.drawable.LayerDrawable;
     37 import android.net.Uri;
     38 import android.os.Build;
     39 import android.os.Bundle;
     40 import android.os.Handler;
     41 import android.provider.CalendarContract.Calendars;
     42 import android.text.Spannable;
     43 import android.text.SpannableString;
     44 import android.text.Spanned;
     45 import android.text.TextUtils;
     46 import android.text.format.DateFormat;
     47 import android.text.format.DateUtils;
     48 import android.text.format.Time;
     49 import android.text.style.URLSpan;
     50 import android.text.util.Linkify;
     51 import android.util.Log;
     52 import android.widget.SearchView;
     53 
     54 import com.android.calendar.CalendarController.ViewType;
     55 import com.android.calendar.CalendarEventModel.ReminderEntry;
     56 import com.android.calendar.CalendarUtils.TimeZoneUtils;
     57 
     58 import java.util.ArrayList;
     59 import java.util.Arrays;
     60 import java.util.Calendar;
     61 import java.util.Formatter;
     62 import java.util.HashMap;
     63 import java.util.Iterator;
     64 import java.util.LinkedHashSet;
     65 import java.util.LinkedList;
     66 import java.util.List;
     67 import java.util.Locale;
     68 import java.util.Map;
     69 import java.util.Set;
     70 import java.util.TimeZone;
     71 import java.util.regex.Matcher;
     72 import java.util.regex.Pattern;
     73 
     74 public class Utils {
     75     private static final boolean DEBUG = false;
     76     private static final String TAG = "CalUtils";
     77 
     78     // Set to 0 until we have UI to perform undo
     79     public static final long UNDO_DELAY = 0;
     80 
     81     // For recurring events which instances of the series are being modified
     82     public static final int MODIFY_UNINITIALIZED = 0;
     83     public static final int MODIFY_SELECTED = 1;
     84     public static final int MODIFY_ALL_FOLLOWING = 2;
     85     public static final int MODIFY_ALL = 3;
     86 
     87     // When the edit event view finishes it passes back the appropriate exit
     88     // code.
     89     public static final int DONE_REVERT = 1 << 0;
     90     public static final int DONE_SAVE = 1 << 1;
     91     public static final int DONE_DELETE = 1 << 2;
     92     // And should re run with DONE_EXIT if it should also leave the view, just
     93     // exiting is identical to reverting
     94     public static final int DONE_EXIT = 1 << 0;
     95 
     96     public static final String OPEN_EMAIL_MARKER = " <";
     97     public static final String CLOSE_EMAIL_MARKER = ">";
     98 
     99     public static final String INTENT_KEY_DETAIL_VIEW = "DETAIL_VIEW";
    100     public static final String INTENT_KEY_VIEW_TYPE = "VIEW";
    101     public static final String INTENT_VALUE_VIEW_TYPE_DAY = "DAY";
    102     public static final String INTENT_KEY_HOME = "KEY_HOME";
    103 
    104     public static final int MONDAY_BEFORE_JULIAN_EPOCH = Time.EPOCH_JULIAN_DAY - 3;
    105     public static final int DECLINED_EVENT_ALPHA = 0x66;
    106     public static final int DECLINED_EVENT_TEXT_ALPHA = 0xC0;
    107 
    108     private static final float SATURATION_ADJUST = 1.3f;
    109     private static final float INTENSITY_ADJUST = 0.8f;
    110 
    111     // Defines used by the DNA generation code
    112     static final int DAY_IN_MINUTES = 60 * 24;
    113     static final int WEEK_IN_MINUTES = DAY_IN_MINUTES * 7;
    114     // The work day is being counted as 6am to 8pm
    115     static int WORK_DAY_MINUTES = 14 * 60;
    116     static int WORK_DAY_START_MINUTES = 6 * 60;
    117     static int WORK_DAY_END_MINUTES = 20 * 60;
    118     static int WORK_DAY_END_LENGTH = (24 * 60) - WORK_DAY_END_MINUTES;
    119     static int CONFLICT_COLOR = 0xFF000000;
    120     static boolean mMinutesLoaded = false;
    121 
    122     public static final int YEAR_MIN = 1970;
    123     public static final int YEAR_MAX = 2036;
    124 
    125     // The name of the shared preferences file. This name must be maintained for
    126     // historical
    127     // reasons, as it's what PreferenceManager assigned the first time the file
    128     // was created.
    129     static final String SHARED_PREFS_NAME = "com.android.calendar_preferences";
    130 
    131     public static final String KEY_QUICK_RESPONSES = "preferences_quick_responses";
    132 
    133     public static final String KEY_ALERTS_VIBRATE_WHEN = "preferences_alerts_vibrateWhen";
    134 
    135     public static final String APPWIDGET_DATA_TYPE = "vnd.android.data/update";
    136 
    137     static final String MACHINE_GENERATED_ADDRESS = "calendar.google.com";
    138 
    139     private static final TimeZoneUtils mTZUtils = new TimeZoneUtils(SHARED_PREFS_NAME);
    140     private static boolean mAllowWeekForDetailView = false;
    141     private static long mTardis = 0;
    142     private static String sVersion = null;
    143 
    144     private static final Pattern mWildcardPattern = Pattern.compile("^.*$");
    145 
    146     /**
    147     * A coordinate must be of the following form for Google Maps to correctly use it:
    148     * Latitude, Longitude
    149     *
    150     * This may be in decimal form:
    151     * Latitude: {-90 to 90}
    152     * Longitude: {-180 to 180}
    153     *
    154     * Or, in degrees, minutes, and seconds:
    155     * Latitude: {-90 to 90} {0 to 59}' {0 to 59}"
    156     * Latitude: {-180 to 180} {0 to 59}' {0 to 59}"
    157     * + or - degrees may also be represented with N or n, S or s for latitude, and with
    158     * E or e, W or w for longitude, where the direction may either precede or follow the value.
    159     *
    160     * Some examples of coordinates that will be accepted by the regex:
    161     * 37.422081, -122.084576
    162     * 37.422081,-122.084576
    163     * +3725'19.49", -1225'4.47"
    164     * 3725'19.49"N, 1225'4.47"W
    165     * N 37 25' 19.49",  W 122 5' 4.47"
    166     **/
    167     private static final String COORD_DEGREES_LATITUDE =
    168             "([-+NnSs]" + "(\\s)*)?"
    169             + "[1-9]?[0-9](\u00B0)" + "(\\s)*"
    170             + "([1-5]?[0-9]\')?" + "(\\s)*"
    171             + "([1-5]?[0-9]" + "(\\.[0-9]+)?\")?"
    172             + "((\\s)*" + "[NnSs])?";
    173     private static final String COORD_DEGREES_LONGITUDE =
    174             "([-+EeWw]" + "(\\s)*)?"
    175             + "(1)?[0-9]?[0-9](\u00B0)" + "(\\s)*"
    176             + "([1-5]?[0-9]\')?" + "(\\s)*"
    177             + "([1-5]?[0-9]" + "(\\.[0-9]+)?\")?"
    178             + "((\\s)*" + "[EeWw])?";
    179     private static final String COORD_DEGREES_PATTERN =
    180             COORD_DEGREES_LATITUDE
    181             + "(\\s)*" + "," + "(\\s)*"
    182             + COORD_DEGREES_LONGITUDE;
    183     private static final String COORD_DECIMAL_LATITUDE =
    184             "[+-]?"
    185             + "[1-9]?[0-9]" + "(\\.[0-9]+)"
    186             + "(\u00B0)?";
    187     private static final String COORD_DECIMAL_LONGITUDE =
    188             "[+-]?"
    189             + "(1)?[0-9]?[0-9]" + "(\\.[0-9]+)"
    190             + "(\u00B0)?";
    191     private static final String COORD_DECIMAL_PATTERN =
    192             COORD_DECIMAL_LATITUDE
    193             + "(\\s)*" + "," + "(\\s)*"
    194             + COORD_DECIMAL_LONGITUDE;
    195     private static final Pattern COORD_PATTERN =
    196             Pattern.compile(COORD_DEGREES_PATTERN + "|" + COORD_DECIMAL_PATTERN);
    197 
    198     private static final String NANP_ALLOWED_SYMBOLS = "()+-*#.";
    199     private static final int NANP_MIN_DIGITS = 7;
    200     private static final int NANP_MAX_DIGITS = 11;
    201 
    202 
    203     /**
    204      * Returns whether the SDK is the Jellybean release or later.
    205      */
    206     public static boolean isJellybeanOrLater() {
    207       return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
    208     }
    209 
    210     public static int getViewTypeFromIntentAndSharedPref(Activity activity) {
    211         Intent intent = activity.getIntent();
    212         Bundle extras = intent.getExtras();
    213         SharedPreferences prefs = GeneralPreferences.getSharedPreferences(activity);
    214 
    215         if (TextUtils.equals(intent.getAction(), Intent.ACTION_EDIT)) {
    216             return ViewType.EDIT;
    217         }
    218         if (extras != null) {
    219             if (extras.getBoolean(INTENT_KEY_DETAIL_VIEW, false)) {
    220                 // This is the "detail" view which is either agenda or day view
    221                 return prefs.getInt(GeneralPreferences.KEY_DETAILED_VIEW,
    222                         GeneralPreferences.DEFAULT_DETAILED_VIEW);
    223             } else if (INTENT_VALUE_VIEW_TYPE_DAY.equals(extras.getString(INTENT_KEY_VIEW_TYPE))) {
    224                 // Not sure who uses this. This logic came from LaunchActivity
    225                 return ViewType.DAY;
    226             }
    227         }
    228 
    229         // Default to the last view
    230         return prefs.getInt(
    231                 GeneralPreferences.KEY_START_VIEW, GeneralPreferences.DEFAULT_START_VIEW);
    232     }
    233 
    234     /**
    235      * Gets the intent action for telling the widget to update.
    236      */
    237     public static String getWidgetUpdateAction(Context context) {
    238         return context.getPackageName() + ".APPWIDGET_UPDATE";
    239     }
    240 
    241     /**
    242      * Gets the intent action for telling the widget to update.
    243      */
    244     public static String getWidgetScheduledUpdateAction(Context context) {
    245         return context.getPackageName() + ".APPWIDGET_SCHEDULED_UPDATE";
    246     }
    247 
    248     /**
    249      * Gets the intent action for telling the widget to update.
    250      */
    251     public static String getSearchAuthority(Context context) {
    252         return context.getPackageName() + ".CalendarRecentSuggestionsProvider";
    253     }
    254 
    255     /**
    256      * Writes a new home time zone to the db. Updates the home time zone in the
    257      * db asynchronously and updates the local cache. Sending a time zone of
    258      * **tbd** will cause it to be set to the device's time zone. null or empty
    259      * tz will be ignored.
    260      *
    261      * @param context The calling activity
    262      * @param timeZone The time zone to set Calendar to, or **tbd**
    263      */
    264     public static void setTimeZone(Context context, String timeZone) {
    265         mTZUtils.setTimeZone(context, timeZone);
    266     }
    267 
    268     /**
    269      * Gets the time zone that Calendar should be displayed in This is a helper
    270      * method to get the appropriate time zone for Calendar. If this is the
    271      * first time this method has been called it will initiate an asynchronous
    272      * query to verify that the data in preferences is correct. The callback
    273      * supplied will only be called if this query returns a value other than
    274      * what is stored in preferences and should cause the calling activity to
    275      * refresh anything that depends on calling this method.
    276      *
    277      * @param context The calling activity
    278      * @param callback The runnable that should execute if a query returns new
    279      *            values
    280      * @return The string value representing the time zone Calendar should
    281      *         display
    282      */
    283     public static String getTimeZone(Context context, Runnable callback) {
    284         return mTZUtils.getTimeZone(context, callback);
    285     }
    286 
    287     /**
    288      * Formats a date or a time range according to the local conventions.
    289      *
    290      * @param context the context is required only if the time is shown
    291      * @param startMillis the start time in UTC milliseconds
    292      * @param endMillis the end time in UTC milliseconds
    293      * @param flags a bit mask of options See {@link DateUtils#formatDateRange(Context, Formatter,
    294      * long, long, int, String) formatDateRange}
    295      * @return a string containing the formatted date/time range.
    296      */
    297     public static String formatDateRange(
    298             Context context, long startMillis, long endMillis, int flags) {
    299         return mTZUtils.formatDateRange(context, startMillis, endMillis, flags);
    300     }
    301 
    302     public static boolean getDefaultVibrate(Context context, SharedPreferences prefs) {
    303         boolean vibrate;
    304         if (prefs.contains(KEY_ALERTS_VIBRATE_WHEN)) {
    305             // Migrate setting to new 4.2 behavior
    306             //
    307             // silent and never -> off
    308             // always -> on
    309             String vibrateWhen = prefs.getString(KEY_ALERTS_VIBRATE_WHEN, null);
    310             vibrate = vibrateWhen != null && vibrateWhen.equals(context
    311                     .getString(R.string.prefDefault_alerts_vibrate_true));
    312             prefs.edit().remove(KEY_ALERTS_VIBRATE_WHEN).commit();
    313             Log.d(TAG, "Migrating KEY_ALERTS_VIBRATE_WHEN(" + vibrateWhen
    314                     + ") to KEY_ALERTS_VIBRATE = " + vibrate);
    315         } else {
    316             vibrate = prefs.getBoolean(GeneralPreferences.KEY_ALERTS_VIBRATE,
    317                     false);
    318         }
    319         return vibrate;
    320     }
    321 
    322     public static String[] getSharedPreference(Context context, String key, String[] defaultValue) {
    323         SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
    324         Set<String> ss = prefs.getStringSet(key, null);
    325         if (ss != null) {
    326             String strings[] = new String[ss.size()];
    327             return ss.toArray(strings);
    328         }
    329         return defaultValue;
    330     }
    331 
    332     public static String getSharedPreference(Context context, String key, String defaultValue) {
    333         SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
    334         return prefs.getString(key, defaultValue);
    335     }
    336 
    337     public static int getSharedPreference(Context context, String key, int defaultValue) {
    338         SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
    339         return prefs.getInt(key, defaultValue);
    340     }
    341 
    342     public static boolean getSharedPreference(Context context, String key, boolean defaultValue) {
    343         SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
    344         return prefs.getBoolean(key, defaultValue);
    345     }
    346 
    347     /**
    348      * Asynchronously sets the preference with the given key to the given value
    349      *
    350      * @param context the context to use to get preferences from
    351      * @param key the key of the preference to set
    352      * @param value the value to set
    353      */
    354     public static void setSharedPreference(Context context, String key, String value) {
    355         SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
    356         prefs.edit().putString(key, value).apply();
    357     }
    358 
    359     public static void setSharedPreference(Context context, String key, String[] values) {
    360         SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
    361         LinkedHashSet<String> set = new LinkedHashSet<String>();
    362         for (String value : values) {
    363             set.add(value);
    364         }
    365         prefs.edit().putStringSet(key, set).apply();
    366     }
    367 
    368     protected static void tardis() {
    369         mTardis = System.currentTimeMillis();
    370     }
    371 
    372     protected static long getTardis() {
    373         return mTardis;
    374     }
    375 
    376     public static void setSharedPreference(Context context, String key, boolean value) {
    377         SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
    378         SharedPreferences.Editor editor = prefs.edit();
    379         editor.putBoolean(key, value);
    380         editor.apply();
    381     }
    382 
    383     static void setSharedPreference(Context context, String key, int value) {
    384         SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
    385         SharedPreferences.Editor editor = prefs.edit();
    386         editor.putInt(key, value);
    387         editor.apply();
    388     }
    389 
    390     public static void removeSharedPreference(Context context, String key) {
    391         SharedPreferences prefs = context.getSharedPreferences(
    392                 GeneralPreferences.SHARED_PREFS_NAME, Context.MODE_PRIVATE);
    393         prefs.edit().remove(key).apply();
    394     }
    395 
    396     // The backed up ring tone preference should not used because it is a device
    397     // specific Uri. The preference now lives in a separate non-backed-up
    398     // shared_pref file (SHARED_PREFS_NAME_NO_BACKUP). The preference in the old
    399     // backed-up shared_pref file (SHARED_PREFS_NAME) is used only to control the
    400     // default value when the ringtone dialog opens up.
    401     //
    402     // At backup manager "restore" time (which should happen before launcher
    403     // comes up for the first time), the value will be set/reset to default
    404     // ringtone.
    405     public static String getRingTonePreference(Context context) {
    406         SharedPreferences prefs = context.getSharedPreferences(
    407                 GeneralPreferences.SHARED_PREFS_NAME_NO_BACKUP, Context.MODE_PRIVATE);
    408         String ringtone = prefs.getString(GeneralPreferences.KEY_ALERTS_RINGTONE, null);
    409 
    410         // If it hasn't been populated yet, that means new code is running for
    411         // the first time and restore hasn't happened. Migrate value from
    412         // backed-up shared_pref to non-shared_pref.
    413         if (ringtone == null) {
    414             // Read from the old place with a default of DEFAULT_RINGTONE
    415             ringtone = getSharedPreference(context, GeneralPreferences.KEY_ALERTS_RINGTONE,
    416                     GeneralPreferences.DEFAULT_RINGTONE);
    417 
    418             // Write it to the new place
    419             setRingTonePreference(context, ringtone);
    420         }
    421 
    422         return ringtone;
    423     }
    424 
    425     public static void setRingTonePreference(Context context, String value) {
    426         SharedPreferences prefs = context.getSharedPreferences(
    427                 GeneralPreferences.SHARED_PREFS_NAME_NO_BACKUP, Context.MODE_PRIVATE);
    428         prefs.edit().putString(GeneralPreferences.KEY_ALERTS_RINGTONE, value).apply();
    429     }
    430 
    431     /**
    432      * Save default agenda/day/week/month view for next time
    433      *
    434      * @param context
    435      * @param viewId {@link CalendarController.ViewType}
    436      */
    437     static void setDefaultView(Context context, int viewId) {
    438         SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
    439         SharedPreferences.Editor editor = prefs.edit();
    440 
    441         boolean validDetailView = false;
    442         if (mAllowWeekForDetailView && viewId == CalendarController.ViewType.WEEK) {
    443             validDetailView = true;
    444         } else {
    445             validDetailView = viewId == CalendarController.ViewType.AGENDA
    446                     || viewId == CalendarController.ViewType.DAY;
    447         }
    448 
    449         if (validDetailView) {
    450             // Record the detail start view
    451             editor.putInt(GeneralPreferences.KEY_DETAILED_VIEW, viewId);
    452         }
    453 
    454         // Record the (new) start view
    455         editor.putInt(GeneralPreferences.KEY_START_VIEW, viewId);
    456         editor.apply();
    457     }
    458 
    459     public static MatrixCursor matrixCursorFromCursor(Cursor cursor) {
    460         if (cursor == null) {
    461             return null;
    462         }
    463 
    464         String[] columnNames = cursor.getColumnNames();
    465         if (columnNames == null) {
    466             columnNames = new String[] {};
    467         }
    468         MatrixCursor newCursor = new MatrixCursor(columnNames);
    469         int numColumns = cursor.getColumnCount();
    470         String data[] = new String[numColumns];
    471         cursor.moveToPosition(-1);
    472         while (cursor.moveToNext()) {
    473             for (int i = 0; i < numColumns; i++) {
    474                 data[i] = cursor.getString(i);
    475             }
    476             newCursor.addRow(data);
    477         }
    478         return newCursor;
    479     }
    480 
    481     /**
    482      * Compares two cursors to see if they contain the same data.
    483      *
    484      * @return Returns true of the cursors contain the same data and are not
    485      *         null, false otherwise
    486      */
    487     public static boolean compareCursors(Cursor c1, Cursor c2) {
    488         if (c1 == null || c2 == null) {
    489             return false;
    490         }
    491 
    492         int numColumns = c1.getColumnCount();
    493         if (numColumns != c2.getColumnCount()) {
    494             return false;
    495         }
    496 
    497         if (c1.getCount() != c2.getCount()) {
    498             return false;
    499         }
    500 
    501         c1.moveToPosition(-1);
    502         c2.moveToPosition(-1);
    503         while (c1.moveToNext() && c2.moveToNext()) {
    504             for (int i = 0; i < numColumns; i++) {
    505                 if (!TextUtils.equals(c1.getString(i), c2.getString(i))) {
    506                     return false;
    507                 }
    508             }
    509         }
    510 
    511         return true;
    512     }
    513 
    514     /**
    515      * If the given intent specifies a time (in milliseconds since the epoch),
    516      * then that time is returned. Otherwise, the current time is returned.
    517      */
    518     public static final long timeFromIntentInMillis(Intent intent) {
    519         // If the time was specified, then use that. Otherwise, use the current
    520         // time.
    521         Uri data = intent.getData();
    522         long millis = intent.getLongExtra(EXTRA_EVENT_BEGIN_TIME, -1);
    523         if (millis == -1 && data != null && data.isHierarchical()) {
    524             List<String> path = data.getPathSegments();
    525             if (path.size() == 2 && path.get(0).equals("time")) {
    526                 try {
    527                     millis = Long.valueOf(data.getLastPathSegment());
    528                 } catch (NumberFormatException e) {
    529                     Log.i("Calendar", "timeFromIntentInMillis: Data existed but no valid time "
    530                             + "found. Using current time.");
    531                 }
    532             }
    533         }
    534         if (millis <= 0) {
    535             millis = System.currentTimeMillis();
    536         }
    537         return millis;
    538     }
    539 
    540     /**
    541      * Formats the given Time object so that it gives the month and year (for
    542      * example, "September 2007").
    543      *
    544      * @param time the time to format
    545      * @return the string containing the weekday and the date
    546      */
    547     public static String formatMonthYear(Context context, Time time) {
    548         int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY
    549                 | DateUtils.FORMAT_SHOW_YEAR;
    550         long millis = time.toMillis(true);
    551         return formatDateRange(context, millis, millis, flags);
    552     }
    553 
    554     /**
    555      * Returns a list joined together by the provided delimiter, for example,
    556      * ["a", "b", "c"] could be joined into "a,b,c"
    557      *
    558      * @param things the things to join together
    559      * @param delim the delimiter to use
    560      * @return a string contained the things joined together
    561      */
    562     public static String join(List<?> things, String delim) {
    563         StringBuilder builder = new StringBuilder();
    564         boolean first = true;
    565         for (Object thing : things) {
    566             if (first) {
    567                 first = false;
    568             } else {
    569                 builder.append(delim);
    570             }
    571             builder.append(thing.toString());
    572         }
    573         return builder.toString();
    574     }
    575 
    576     /**
    577      * Returns the week since {@link Time#EPOCH_JULIAN_DAY} (Jan 1, 1970)
    578      * adjusted for first day of week.
    579      *
    580      * This takes a julian day and the week start day and calculates which
    581      * week since {@link Time#EPOCH_JULIAN_DAY} that day occurs in, starting
    582      * at 0. *Do not* use this to compute the ISO week number for the year.
    583      *
    584      * @param julianDay The julian day to calculate the week number for
    585      * @param firstDayOfWeek Which week day is the first day of the week,
    586      *          see {@link Time#SUNDAY}
    587      * @return Weeks since the epoch
    588      */
    589     public static int getWeeksSinceEpochFromJulianDay(int julianDay, int firstDayOfWeek) {
    590         int diff = Time.THURSDAY - firstDayOfWeek;
    591         if (diff < 0) {
    592             diff += 7;
    593         }
    594         int refDay = Time.EPOCH_JULIAN_DAY - diff;
    595         return (julianDay - refDay) / 7;
    596     }
    597 
    598     /**
    599      * Takes a number of weeks since the epoch and calculates the Julian day of
    600      * the Monday for that week.
    601      *
    602      * This assumes that the week containing the {@link Time#EPOCH_JULIAN_DAY}
    603      * is considered week 0. It returns the Julian day for the Monday
    604      * {@code week} weeks after the Monday of the week containing the epoch.
    605      *
    606      * @param week Number of weeks since the epoch
    607      * @return The julian day for the Monday of the given week since the epoch
    608      */
    609     public static int getJulianMondayFromWeeksSinceEpoch(int week) {
    610         return MONDAY_BEFORE_JULIAN_EPOCH + week * 7;
    611     }
    612 
    613     /**
    614      * Get first day of week as android.text.format.Time constant.
    615      *
    616      * @return the first day of week in android.text.format.Time
    617      */
    618     public static int getFirstDayOfWeek(Context context) {
    619         SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
    620         String pref = prefs.getString(
    621                 GeneralPreferences.KEY_WEEK_START_DAY, GeneralPreferences.WEEK_START_DEFAULT);
    622 
    623         int startDay;
    624         if (GeneralPreferences.WEEK_START_DEFAULT.equals(pref)) {
    625             startDay = Calendar.getInstance().getFirstDayOfWeek();
    626         } else {
    627             startDay = Integer.parseInt(pref);
    628         }
    629 
    630         if (startDay == Calendar.SATURDAY) {
    631             return Time.SATURDAY;
    632         } else if (startDay == Calendar.MONDAY) {
    633             return Time.MONDAY;
    634         } else {
    635             return Time.SUNDAY;
    636         }
    637     }
    638 
    639     /**
    640      * Get first day of week as java.util.Calendar constant.
    641      *
    642      * @return the first day of week as a java.util.Calendar constant
    643      */
    644     public static int getFirstDayOfWeekAsCalendar(Context context) {
    645         return convertDayOfWeekFromTimeToCalendar(getFirstDayOfWeek(context));
    646     }
    647 
    648     /**
    649      * Converts the day of the week from android.text.format.Time to java.util.Calendar
    650      */
    651     public static int convertDayOfWeekFromTimeToCalendar(int timeDayOfWeek) {
    652         switch (timeDayOfWeek) {
    653             case Time.MONDAY:
    654                 return Calendar.MONDAY;
    655             case Time.TUESDAY:
    656                 return Calendar.TUESDAY;
    657             case Time.WEDNESDAY:
    658                 return Calendar.WEDNESDAY;
    659             case Time.THURSDAY:
    660                 return Calendar.THURSDAY;
    661             case Time.FRIDAY:
    662                 return Calendar.FRIDAY;
    663             case Time.SATURDAY:
    664                 return Calendar.SATURDAY;
    665             case Time.SUNDAY:
    666                 return Calendar.SUNDAY;
    667             default:
    668                 throw new IllegalArgumentException("Argument must be between Time.SUNDAY and " +
    669                         "Time.SATURDAY");
    670         }
    671     }
    672 
    673     /**
    674      * @return true when week number should be shown.
    675      */
    676     public static boolean getShowWeekNumber(Context context) {
    677         final SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
    678         return prefs.getBoolean(
    679                 GeneralPreferences.KEY_SHOW_WEEK_NUM, GeneralPreferences.DEFAULT_SHOW_WEEK_NUM);
    680     }
    681 
    682     /**
    683      * @return true when declined events should be hidden.
    684      */
    685     public static boolean getHideDeclinedEvents(Context context) {
    686         final SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
    687         return prefs.getBoolean(GeneralPreferences.KEY_HIDE_DECLINED, false);
    688     }
    689 
    690     public static int getDaysPerWeek(Context context) {
    691         final SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
    692         return prefs.getInt(GeneralPreferences.KEY_DAYS_PER_WEEK, 7);
    693     }
    694 
    695     /**
    696      * Determine whether the column position is Saturday or not.
    697      *
    698      * @param column the column position
    699      * @param firstDayOfWeek the first day of week in android.text.format.Time
    700      * @return true if the column is Saturday position
    701      */
    702     public static boolean isSaturday(int column, int firstDayOfWeek) {
    703         return (firstDayOfWeek == Time.SUNDAY && column == 6)
    704                 || (firstDayOfWeek == Time.MONDAY && column == 5)
    705                 || (firstDayOfWeek == Time.SATURDAY && column == 0);
    706     }
    707 
    708     /**
    709      * Determine whether the column position is Sunday or not.
    710      *
    711      * @param column the column position
    712      * @param firstDayOfWeek the first day of week in android.text.format.Time
    713      * @return true if the column is Sunday position
    714      */
    715     public static boolean isSunday(int column, int firstDayOfWeek) {
    716         return (firstDayOfWeek == Time.SUNDAY && column == 0)
    717                 || (firstDayOfWeek == Time.MONDAY && column == 6)
    718                 || (firstDayOfWeek == Time.SATURDAY && column == 1);
    719     }
    720 
    721     /**
    722      * Convert given UTC time into current local time. This assumes it is for an
    723      * allday event and will adjust the time to be on a midnight boundary.
    724      *
    725      * @param recycle Time object to recycle, otherwise null.
    726      * @param utcTime Time to convert, in UTC.
    727      * @param tz The time zone to convert this time to.
    728      */
    729     public static long convertAlldayUtcToLocal(Time recycle, long utcTime, String tz) {
    730         if (recycle == null) {
    731             recycle = new Time();
    732         }
    733         recycle.timezone = Time.TIMEZONE_UTC;
    734         recycle.set(utcTime);
    735         recycle.timezone = tz;
    736         return recycle.normalize(true);
    737     }
    738 
    739     public static long convertAlldayLocalToUTC(Time recycle, long localTime, String tz) {
    740         if (recycle == null) {
    741             recycle = new Time();
    742         }
    743         recycle.timezone = tz;
    744         recycle.set(localTime);
    745         recycle.timezone = Time.TIMEZONE_UTC;
    746         return recycle.normalize(true);
    747     }
    748 
    749     /**
    750      * Finds and returns the next midnight after "theTime" in milliseconds UTC
    751      *
    752      * @param recycle - Time object to recycle, otherwise null.
    753      * @param theTime - Time used for calculations (in UTC)
    754      * @param tz The time zone to convert this time to.
    755      */
    756     public static long getNextMidnight(Time recycle, long theTime, String tz) {
    757         if (recycle == null) {
    758             recycle = new Time();
    759         }
    760         recycle.timezone = tz;
    761         recycle.set(theTime);
    762         recycle.monthDay ++;
    763         recycle.hour = 0;
    764         recycle.minute = 0;
    765         recycle.second = 0;
    766         return recycle.normalize(true);
    767     }
    768 
    769     /**
    770      * Scan through a cursor of calendars and check if names are duplicated.
    771      * This travels a cursor containing calendar display names and fills in the
    772      * provided map with whether or not each name is repeated.
    773      *
    774      * @param isDuplicateName The map to put the duplicate check results in.
    775      * @param cursor The query of calendars to check
    776      * @param nameIndex The column of the query that contains the display name
    777      */
    778     public static void checkForDuplicateNames(
    779             Map<String, Boolean> isDuplicateName, Cursor cursor, int nameIndex) {
    780         isDuplicateName.clear();
    781         cursor.moveToPosition(-1);
    782         while (cursor.moveToNext()) {
    783             String displayName = cursor.getString(nameIndex);
    784             // Set it to true if we've seen this name before, false otherwise
    785             if (displayName != null) {
    786                 isDuplicateName.put(displayName, isDuplicateName.containsKey(displayName));
    787             }
    788         }
    789     }
    790 
    791     /**
    792      * Null-safe object comparison
    793      *
    794      * @param s1
    795      * @param s2
    796      * @return
    797      */
    798     public static boolean equals(Object o1, Object o2) {
    799         return o1 == null ? o2 == null : o1.equals(o2);
    800     }
    801 
    802     public static void setAllowWeekForDetailView(boolean allowWeekView) {
    803         mAllowWeekForDetailView  = allowWeekView;
    804     }
    805 
    806     public static boolean getAllowWeekForDetailView() {
    807         return mAllowWeekForDetailView;
    808     }
    809 
    810     public static boolean getConfigBool(Context c, int key) {
    811         return c.getResources().getBoolean(key);
    812     }
    813 
    814     /**
    815      * For devices with Jellybean or later, darkens the given color to ensure that white text is
    816      * clearly visible on top of it.  For devices prior to Jellybean, does nothing, as the
    817      * sync adapter handles the color change.
    818      *
    819      * @param color
    820      */
    821     public static int getDisplayColorFromColor(int color) {
    822         if (!isJellybeanOrLater()) {
    823             return color;
    824         }
    825 
    826         float[] hsv = new float[3];
    827         Color.colorToHSV(color, hsv);
    828         hsv[1] = Math.min(hsv[1] * SATURATION_ADJUST, 1.0f);
    829         hsv[2] = hsv[2] * INTENSITY_ADJUST;
    830         return Color.HSVToColor(hsv);
    831     }
    832 
    833     // This takes a color and computes what it would look like blended with
    834     // white. The result is the color that should be used for declined events.
    835     public static int getDeclinedColorFromColor(int color) {
    836         int bg = 0xffffffff;
    837         int a = DECLINED_EVENT_ALPHA;
    838         int r = (((color & 0x00ff0000) * a) + ((bg & 0x00ff0000) * (0xff - a))) & 0xff000000;
    839         int g = (((color & 0x0000ff00) * a) + ((bg & 0x0000ff00) * (0xff - a))) & 0x00ff0000;
    840         int b = (((color & 0x000000ff) * a) + ((bg & 0x000000ff) * (0xff - a))) & 0x0000ff00;
    841         return (0xff000000) | ((r | g | b) >> 8);
    842     }
    843 
    844     // A single strand represents one color of events. Events are divided up by
    845     // color to make them convenient to draw. The black strand is special in
    846     // that it holds conflicting events as well as color settings for allday on
    847     // each day.
    848     public static class DNAStrand {
    849         public float[] points;
    850         public int[] allDays; // color for the allday, 0 means no event
    851         int position;
    852         public int color;
    853         int count;
    854     }
    855 
    856     // A segment is a single continuous length of time occupied by a single
    857     // color. Segments should never span multiple days.
    858     private static class DNASegment {
    859         int startMinute; // in minutes since the start of the week
    860         int endMinute;
    861         int color; // Calendar color or black for conflicts
    862         int day; // quick reference to the day this segment is on
    863     }
    864 
    865     /**
    866      * Converts a list of events to a list of segments to draw. Assumes list is
    867      * ordered by start time of the events. The function processes events for a
    868      * range of days from firstJulianDay to firstJulianDay + dayXs.length - 1.
    869      * The algorithm goes over all the events and creates a set of segments
    870      * ordered by start time. This list of segments is then converted into a
    871      * HashMap of strands which contain the draw points and are organized by
    872      * color. The strands can then be drawn by setting the paint color to each
    873      * strand's color and calling drawLines on its set of points. The points are
    874      * set up using the following parameters.
    875      * <ul>
    876      * <li>Events between midnight and WORK_DAY_START_MINUTES are compressed
    877      * into the first 1/8th of the space between top and bottom.</li>
    878      * <li>Events between WORK_DAY_END_MINUTES and the following midnight are
    879      * compressed into the last 1/8th of the space between top and bottom</li>
    880      * <li>Events between WORK_DAY_START_MINUTES and WORK_DAY_END_MINUTES use
    881      * the remaining 3/4ths of the space</li>
    882      * <li>All segments drawn will maintain at least minPixels height, except
    883      * for conflicts in the first or last 1/8th, which may be smaller</li>
    884      * </ul>
    885      *
    886      * @param firstJulianDay The julian day of the first day of events
    887      * @param events A list of events sorted by start time
    888      * @param top The lowest y value the dna should be drawn at
    889      * @param bottom The highest y value the dna should be drawn at
    890      * @param dayXs An array of x values to draw the dna at, one for each day
    891      * @param conflictColor the color to use for conflicts
    892      * @return
    893      */
    894     public static HashMap<Integer, DNAStrand> createDNAStrands(int firstJulianDay,
    895             ArrayList<Event> events, int top, int bottom, int minPixels, int[] dayXs,
    896             Context context) {
    897 
    898         if (!mMinutesLoaded) {
    899             if (context == null) {
    900                 Log.wtf(TAG, "No context and haven't loaded parameters yet! Can't create DNA.");
    901             }
    902             Resources res = context.getResources();
    903             CONFLICT_COLOR = res.getColor(R.color.month_dna_conflict_time_color);
    904             WORK_DAY_START_MINUTES = res.getInteger(R.integer.work_start_minutes);
    905             WORK_DAY_END_MINUTES = res.getInteger(R.integer.work_end_minutes);
    906             WORK_DAY_END_LENGTH = DAY_IN_MINUTES - WORK_DAY_END_MINUTES;
    907             WORK_DAY_MINUTES = WORK_DAY_END_MINUTES - WORK_DAY_START_MINUTES;
    908             mMinutesLoaded = true;
    909         }
    910 
    911         if (events == null || events.isEmpty() || dayXs == null || dayXs.length < 1
    912                 || bottom - top < 8 || minPixels < 0) {
    913             Log.e(TAG,
    914                     "Bad values for createDNAStrands! events:" + events + " dayXs:"
    915                             + Arrays.toString(dayXs) + " bot-top:" + (bottom - top) + " minPixels:"
    916                             + minPixels);
    917             return null;
    918         }
    919 
    920         LinkedList<DNASegment> segments = new LinkedList<DNASegment>();
    921         HashMap<Integer, DNAStrand> strands = new HashMap<Integer, DNAStrand>();
    922         // add a black strand by default, other colors will get added in
    923         // the loop
    924         DNAStrand blackStrand = new DNAStrand();
    925         blackStrand.color = CONFLICT_COLOR;
    926         strands.put(CONFLICT_COLOR, blackStrand);
    927         // the min length is the number of minutes that will occupy
    928         // MIN_SEGMENT_PIXELS in the 'work day' time slot. This computes the
    929         // minutes/pixel * minpx where the number of pixels are 3/4 the total
    930         // dna height: 4*(mins/(px * 3/4))
    931         int minMinutes = minPixels * 4 * WORK_DAY_MINUTES / (3 * (bottom - top));
    932 
    933         // There are slightly fewer than half as many pixels in 1/6 the space,
    934         // so round to 2.5x for the min minutes in the non-work area
    935         int minOtherMinutes = minMinutes * 5 / 2;
    936         int lastJulianDay = firstJulianDay + dayXs.length - 1;
    937 
    938         Event event = new Event();
    939         // Go through all the events for the week
    940         for (Event currEvent : events) {
    941             // if this event is outside the weeks range skip it
    942             if (currEvent.endDay < firstJulianDay || currEvent.startDay > lastJulianDay) {
    943                 continue;
    944             }
    945             if (currEvent.drawAsAllday()) {
    946                 addAllDayToStrands(currEvent, strands, firstJulianDay, dayXs.length);
    947                 continue;
    948             }
    949             // Copy the event over so we can clip its start and end to our range
    950             currEvent.copyTo(event);
    951             if (event.startDay < firstJulianDay) {
    952                 event.startDay = firstJulianDay;
    953                 event.startTime = 0;
    954             }
    955             // If it starts after the work day make sure the start is at least
    956             // minPixels from midnight
    957             if (event.startTime > DAY_IN_MINUTES - minOtherMinutes) {
    958                 event.startTime = DAY_IN_MINUTES - minOtherMinutes;
    959             }
    960             if (event.endDay > lastJulianDay) {
    961                 event.endDay = lastJulianDay;
    962                 event.endTime = DAY_IN_MINUTES - 1;
    963             }
    964             // If the end time is before the work day make sure it ends at least
    965             // minPixels after midnight
    966             if (event.endTime < minOtherMinutes) {
    967                 event.endTime = minOtherMinutes;
    968             }
    969             // If the start and end are on the same day make sure they are at
    970             // least minPixels apart. This only needs to be done for times
    971             // outside the work day as the min distance for within the work day
    972             // is enforced in the segment code.
    973             if (event.startDay == event.endDay &&
    974                     event.endTime - event.startTime < minOtherMinutes) {
    975                 // If it's less than minPixels in an area before the work
    976                 // day
    977                 if (event.startTime < WORK_DAY_START_MINUTES) {
    978                     // extend the end to the first easy guarantee that it's
    979                     // minPixels
    980                     event.endTime = Math.min(event.startTime + minOtherMinutes,
    981                             WORK_DAY_START_MINUTES + minMinutes);
    982                     // if it's in the area after the work day
    983                 } else if (event.endTime > WORK_DAY_END_MINUTES) {
    984                     // First try shifting the end but not past midnight
    985                     event.endTime = Math.min(event.endTime + minOtherMinutes, DAY_IN_MINUTES - 1);
    986                     // if it's still too small move the start back
    987                     if (event.endTime - event.startTime < minOtherMinutes) {
    988                         event.startTime = event.endTime - minOtherMinutes;
    989                     }
    990                 }
    991             }
    992 
    993             // This handles adding the first segment
    994             if (segments.size() == 0) {
    995                 addNewSegment(segments, event, strands, firstJulianDay, 0, minMinutes);
    996                 continue;
    997             }
    998             // Now compare our current start time to the end time of the last
    999             // segment in the list
   1000             DNASegment lastSegment = segments.getLast();
   1001             int startMinute = (event.startDay - firstJulianDay) * DAY_IN_MINUTES + event.startTime;
   1002             int endMinute = Math.max((event.endDay - firstJulianDay) * DAY_IN_MINUTES
   1003                     + event.endTime, startMinute + minMinutes);
   1004 
   1005             if (startMinute < 0) {
   1006                 startMinute = 0;
   1007             }
   1008             if (endMinute >= WEEK_IN_MINUTES) {
   1009                 endMinute = WEEK_IN_MINUTES - 1;
   1010             }
   1011             // If we start before the last segment in the list ends we need to
   1012             // start going through the list as this may conflict with other
   1013             // events
   1014             if (startMinute < lastSegment.endMinute) {
   1015                 int i = segments.size();
   1016                 // find the last segment this event intersects with
   1017                 while (--i >= 0 && endMinute < segments.get(i).startMinute);
   1018 
   1019                 DNASegment currSegment;
   1020                 // for each segment this event intersects with
   1021                 for (; i >= 0 && startMinute <= (currSegment = segments.get(i)).endMinute; i--) {
   1022                     // if the segment is already a conflict ignore it
   1023                     if (currSegment.color == CONFLICT_COLOR) {
   1024                         continue;
   1025                     }
   1026                     // if the event ends before the segment and wouldn't create
   1027                     // a segment that is too small split off the right side
   1028                     if (endMinute < currSegment.endMinute - minMinutes) {
   1029                         DNASegment rhs = new DNASegment();
   1030                         rhs.endMinute = currSegment.endMinute;
   1031                         rhs.color = currSegment.color;
   1032                         rhs.startMinute = endMinute + 1;
   1033                         rhs.day = currSegment.day;
   1034                         currSegment.endMinute = endMinute;
   1035                         segments.add(i + 1, rhs);
   1036                         strands.get(rhs.color).count++;
   1037                         if (DEBUG) {
   1038                             Log.d(TAG, "Added rhs, curr:" + currSegment.toString() + " i:"
   1039                                     + segments.get(i).toString());
   1040                         }
   1041                     }
   1042                     // if the event starts after the segment and wouldn't create
   1043                     // a segment that is too small split off the left side
   1044                     if (startMinute > currSegment.startMinute + minMinutes) {
   1045                         DNASegment lhs = new DNASegment();
   1046                         lhs.startMinute = currSegment.startMinute;
   1047                         lhs.color = currSegment.color;
   1048                         lhs.endMinute = startMinute - 1;
   1049                         lhs.day = currSegment.day;
   1050                         currSegment.startMinute = startMinute;
   1051                         // increment i so that we are at the right position when
   1052                         // referencing the segments to the right and left of the
   1053                         // current segment.
   1054                         segments.add(i++, lhs);
   1055                         strands.get(lhs.color).count++;
   1056                         if (DEBUG) {
   1057                             Log.d(TAG, "Added lhs, curr:" + currSegment.toString() + " i:"
   1058                                     + segments.get(i).toString());
   1059                         }
   1060                     }
   1061                     // if the right side is black merge this with the segment to
   1062                     // the right if they're on the same day and overlap
   1063                     if (i + 1 < segments.size()) {
   1064                         DNASegment rhs = segments.get(i + 1);
   1065                         if (rhs.color == CONFLICT_COLOR && currSegment.day == rhs.day
   1066                                 && rhs.startMinute <= currSegment.endMinute + 1) {
   1067                             rhs.startMinute = Math.min(currSegment.startMinute, rhs.startMinute);
   1068                             segments.remove(currSegment);
   1069                             strands.get(currSegment.color).count--;
   1070                             // point at the new current segment
   1071                             currSegment = rhs;
   1072                         }
   1073                     }
   1074                     // if the left side is black merge this with the segment to
   1075                     // the left if they're on the same day and overlap
   1076                     if (i - 1 >= 0) {
   1077                         DNASegment lhs = segments.get(i - 1);
   1078                         if (lhs.color == CONFLICT_COLOR && currSegment.day == lhs.day
   1079                                 && lhs.endMinute >= currSegment.startMinute - 1) {
   1080                             lhs.endMinute = Math.max(currSegment.endMinute, lhs.endMinute);
   1081                             segments.remove(currSegment);
   1082                             strands.get(currSegment.color).count--;
   1083                             // point at the new current segment
   1084                             currSegment = lhs;
   1085                             // point i at the new current segment in case new
   1086                             // code is added
   1087                             i--;
   1088                         }
   1089                     }
   1090                     // if we're still not black, decrement the count for the
   1091                     // color being removed, change this to black, and increment
   1092                     // the black count
   1093                     if (currSegment.color != CONFLICT_COLOR) {
   1094                         strands.get(currSegment.color).count--;
   1095                         currSegment.color = CONFLICT_COLOR;
   1096                         strands.get(CONFLICT_COLOR).count++;
   1097                     }
   1098                 }
   1099 
   1100             }
   1101             // If this event extends beyond the last segment add a new segment
   1102             if (endMinute > lastSegment.endMinute) {
   1103                 addNewSegment(segments, event, strands, firstJulianDay, lastSegment.endMinute,
   1104                         minMinutes);
   1105             }
   1106         }
   1107         weaveDNAStrands(segments, firstJulianDay, strands, top, bottom, dayXs);
   1108         return strands;
   1109     }
   1110 
   1111     // This figures out allDay colors as allDay events are found
   1112     private static void addAllDayToStrands(Event event, HashMap<Integer, DNAStrand> strands,
   1113             int firstJulianDay, int numDays) {
   1114         DNAStrand strand = getOrCreateStrand(strands, CONFLICT_COLOR);
   1115         // if we haven't initialized the allDay portion create it now
   1116         if (strand.allDays == null) {
   1117             strand.allDays = new int[numDays];
   1118         }
   1119 
   1120         // For each day this event is on update the color
   1121         int end = Math.min(event.endDay - firstJulianDay, numDays - 1);
   1122         for (int i = Math.max(event.startDay - firstJulianDay, 0); i <= end; i++) {
   1123             if (strand.allDays[i] != 0) {
   1124                 // if this day already had a color, it is now a conflict
   1125                 strand.allDays[i] = CONFLICT_COLOR;
   1126             } else {
   1127                 // else it's just the color of the event
   1128                 strand.allDays[i] = event.color;
   1129             }
   1130         }
   1131     }
   1132 
   1133     // This processes all the segments, sorts them by color, and generates a
   1134     // list of points to draw
   1135     private static void weaveDNAStrands(LinkedList<DNASegment> segments, int firstJulianDay,
   1136             HashMap<Integer, DNAStrand> strands, int top, int bottom, int[] dayXs) {
   1137         // First, get rid of any colors that ended up with no segments
   1138         Iterator<DNAStrand> strandIterator = strands.values().iterator();
   1139         while (strandIterator.hasNext()) {
   1140             DNAStrand strand = strandIterator.next();
   1141             if (strand.count < 1 && strand.allDays == null) {
   1142                 strandIterator.remove();
   1143                 continue;
   1144             }
   1145             strand.points = new float[strand.count * 4];
   1146             strand.position = 0;
   1147         }
   1148         // Go through each segment and compute its points
   1149         for (DNASegment segment : segments) {
   1150             // Add the points to the strand of that color
   1151             DNAStrand strand = strands.get(segment.color);
   1152             int dayIndex = segment.day - firstJulianDay;
   1153             int dayStartMinute = segment.startMinute % DAY_IN_MINUTES;
   1154             int dayEndMinute = segment.endMinute % DAY_IN_MINUTES;
   1155             int height = bottom - top;
   1156             int workDayHeight = height * 3 / 4;
   1157             int remainderHeight = (height - workDayHeight) / 2;
   1158 
   1159             int x = dayXs[dayIndex];
   1160             int y0 = 0;
   1161             int y1 = 0;
   1162 
   1163             y0 = top + getPixelOffsetFromMinutes(dayStartMinute, workDayHeight, remainderHeight);
   1164             y1 = top + getPixelOffsetFromMinutes(dayEndMinute, workDayHeight, remainderHeight);
   1165             if (DEBUG) {
   1166                 Log.d(TAG, "Adding " + Integer.toHexString(segment.color) + " at x,y0,y1: " + x
   1167                         + " " + y0 + " " + y1 + " for " + dayStartMinute + " " + dayEndMinute);
   1168             }
   1169             strand.points[strand.position++] = x;
   1170             strand.points[strand.position++] = y0;
   1171             strand.points[strand.position++] = x;
   1172             strand.points[strand.position++] = y1;
   1173         }
   1174     }
   1175 
   1176     /**
   1177      * Compute a pixel offset from the top for a given minute from the work day
   1178      * height and the height of the top area.
   1179      */
   1180     private static int getPixelOffsetFromMinutes(int minute, int workDayHeight,
   1181             int remainderHeight) {
   1182         int y;
   1183         if (minute < WORK_DAY_START_MINUTES) {
   1184             y = minute * remainderHeight / WORK_DAY_START_MINUTES;
   1185         } else if (minute < WORK_DAY_END_MINUTES) {
   1186             y = remainderHeight + (minute - WORK_DAY_START_MINUTES) * workDayHeight
   1187                     / WORK_DAY_MINUTES;
   1188         } else {
   1189             y = remainderHeight + workDayHeight + (minute - WORK_DAY_END_MINUTES) * remainderHeight
   1190                     / WORK_DAY_END_LENGTH;
   1191         }
   1192         return y;
   1193     }
   1194 
   1195     /**
   1196      * Add a new segment based on the event provided. This will handle splitting
   1197      * segments across day boundaries and ensures a minimum size for segments.
   1198      */
   1199     private static void addNewSegment(LinkedList<DNASegment> segments, Event event,
   1200             HashMap<Integer, DNAStrand> strands, int firstJulianDay, int minStart, int minMinutes) {
   1201         if (event.startDay > event.endDay) {
   1202             Log.wtf(TAG, "Event starts after it ends: " + event.toString());
   1203         }
   1204         // If this is a multiday event split it up by day
   1205         if (event.startDay != event.endDay) {
   1206             Event lhs = new Event();
   1207             lhs.color = event.color;
   1208             lhs.startDay = event.startDay;
   1209             // the first day we want the start time to be the actual start time
   1210             lhs.startTime = event.startTime;
   1211             lhs.endDay = lhs.startDay;
   1212             lhs.endTime = DAY_IN_MINUTES - 1;
   1213             // Nearly recursive iteration!
   1214             while (lhs.startDay != event.endDay) {
   1215                 addNewSegment(segments, lhs, strands, firstJulianDay, minStart, minMinutes);
   1216                 // The days in between are all day, even though that shouldn't
   1217                 // actually happen due to the allday filtering
   1218                 lhs.startDay++;
   1219                 lhs.endDay = lhs.startDay;
   1220                 lhs.startTime = 0;
   1221                 minStart = 0;
   1222             }
   1223             // The last day we want the end time to be the actual end time
   1224             lhs.endTime = event.endTime;
   1225             event = lhs;
   1226         }
   1227         // Create the new segment and compute its fields
   1228         DNASegment segment = new DNASegment();
   1229         int dayOffset = (event.startDay - firstJulianDay) * DAY_IN_MINUTES;
   1230         int endOfDay = dayOffset + DAY_IN_MINUTES - 1;
   1231         // clip the start if needed
   1232         segment.startMinute = Math.max(dayOffset + event.startTime, minStart);
   1233         // and extend the end if it's too small, but not beyond the end of the
   1234         // day
   1235         int minEnd = Math.min(segment.startMinute + minMinutes, endOfDay);
   1236         segment.endMinute = Math.max(dayOffset + event.endTime, minEnd);
   1237         if (segment.endMinute > endOfDay) {
   1238             segment.endMinute = endOfDay;
   1239         }
   1240 
   1241         segment.color = event.color;
   1242         segment.day = event.startDay;
   1243         segments.add(segment);
   1244         // increment the count for the correct color or add a new strand if we
   1245         // don't have that color yet
   1246         DNAStrand strand = getOrCreateStrand(strands, segment.color);
   1247         strand.count++;
   1248     }
   1249 
   1250     /**
   1251      * Try to get a strand of the given color. Create it if it doesn't exist.
   1252      */
   1253     private static DNAStrand getOrCreateStrand(HashMap<Integer, DNAStrand> strands, int color) {
   1254         DNAStrand strand = strands.get(color);
   1255         if (strand == null) {
   1256             strand = new DNAStrand();
   1257             strand.color = color;
   1258             strand.count = 0;
   1259             strands.put(strand.color, strand);
   1260         }
   1261         return strand;
   1262     }
   1263 
   1264     /**
   1265      * Sends an intent to launch the top level Calendar view.
   1266      *
   1267      * @param context
   1268      */
   1269     public static void returnToCalendarHome(Context context) {
   1270         Intent launchIntent = new Intent(context, AllInOneActivity.class);
   1271         launchIntent.setAction(Intent.ACTION_DEFAULT);
   1272         launchIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
   1273         launchIntent.putExtra(INTENT_KEY_HOME, true);
   1274         context.startActivity(launchIntent);
   1275     }
   1276 
   1277     /**
   1278      * This sets up a search view to use Calendar's search suggestions provider
   1279      * and to allow refining the search.
   1280      *
   1281      * @param view The {@link SearchView} to set up
   1282      * @param act The activity using the view
   1283      */
   1284     public static void setUpSearchView(SearchView view, Activity act) {
   1285         SearchManager searchManager = (SearchManager) act.getSystemService(Context.SEARCH_SERVICE);
   1286         view.setSearchableInfo(searchManager.getSearchableInfo(act.getComponentName()));
   1287         view.setQueryRefinementEnabled(true);
   1288     }
   1289 
   1290     /**
   1291      * Given a context and a time in millis since unix epoch figures out the
   1292      * correct week of the year for that time.
   1293      *
   1294      * @param millisSinceEpoch
   1295      * @return
   1296      */
   1297     public static int getWeekNumberFromTime(long millisSinceEpoch, Context context) {
   1298         Time weekTime = new Time(getTimeZone(context, null));
   1299         weekTime.set(millisSinceEpoch);
   1300         weekTime.normalize(true);
   1301         int firstDayOfWeek = getFirstDayOfWeek(context);
   1302         // if the date is on Saturday or Sunday and the start of the week
   1303         // isn't Monday we may need to shift the date to be in the correct
   1304         // week
   1305         if (weekTime.weekDay == Time.SUNDAY
   1306                 && (firstDayOfWeek == Time.SUNDAY || firstDayOfWeek == Time.SATURDAY)) {
   1307             weekTime.monthDay++;
   1308             weekTime.normalize(true);
   1309         } else if (weekTime.weekDay == Time.SATURDAY && firstDayOfWeek == Time.SATURDAY) {
   1310             weekTime.monthDay += 2;
   1311             weekTime.normalize(true);
   1312         }
   1313         return weekTime.getWeekNumber();
   1314     }
   1315 
   1316     /**
   1317      * Formats a day of the week string. This is either just the name of the day
   1318      * or a combination of yesterday/today/tomorrow and the day of the week.
   1319      *
   1320      * @param julianDay The julian day to get the string for
   1321      * @param todayJulianDay The julian day for today's date
   1322      * @param millis A utc millis since epoch time that falls on julian day
   1323      * @param context The calling context, used to get the timezone and do the
   1324      *            formatting
   1325      * @return
   1326      */
   1327     public static String getDayOfWeekString(int julianDay, int todayJulianDay, long millis,
   1328             Context context) {
   1329         getTimeZone(context, null);
   1330         int flags = DateUtils.FORMAT_SHOW_WEEKDAY;
   1331         String dayViewText;
   1332         if (julianDay == todayJulianDay) {
   1333             dayViewText = context.getString(R.string.agenda_today,
   1334                     mTZUtils.formatDateRange(context, millis, millis, flags).toString());
   1335         } else if (julianDay == todayJulianDay - 1) {
   1336             dayViewText = context.getString(R.string.agenda_yesterday,
   1337                     mTZUtils.formatDateRange(context, millis, millis, flags).toString());
   1338         } else if (julianDay == todayJulianDay + 1) {
   1339             dayViewText = context.getString(R.string.agenda_tomorrow,
   1340                     mTZUtils.formatDateRange(context, millis, millis, flags).toString());
   1341         } else {
   1342             dayViewText = mTZUtils.formatDateRange(context, millis, millis, flags).toString();
   1343         }
   1344         dayViewText = dayViewText.toUpperCase();
   1345         return dayViewText;
   1346     }
   1347 
   1348     // Calculate the time until midnight + 1 second and set the handler to
   1349     // do run the runnable
   1350     public static void setMidnightUpdater(Handler h, Runnable r, String timezone) {
   1351         if (h == null || r == null || timezone == null) {
   1352             return;
   1353         }
   1354         long now = System.currentTimeMillis();
   1355         Time time = new Time(timezone);
   1356         time.set(now);
   1357         long runInMillis = (24 * 3600 - time.hour * 3600 - time.minute * 60 -
   1358                 time.second + 1) * 1000;
   1359         h.removeCallbacks(r);
   1360         h.postDelayed(r, runInMillis);
   1361     }
   1362 
   1363     // Stop the midnight update thread
   1364     public static void resetMidnightUpdater(Handler h, Runnable r) {
   1365         if (h == null || r == null) {
   1366             return;
   1367         }
   1368         h.removeCallbacks(r);
   1369     }
   1370 
   1371     /**
   1372      * Returns a string description of the specified time interval.
   1373      */
   1374     public static String getDisplayedDatetime(long startMillis, long endMillis, long currentMillis,
   1375             String localTimezone, boolean allDay, Context context) {
   1376         // Configure date/time formatting.
   1377         int flagsDate = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
   1378         int flagsTime = DateUtils.FORMAT_SHOW_TIME;
   1379         if (DateFormat.is24HourFormat(context)) {
   1380             flagsTime |= DateUtils.FORMAT_24HOUR;
   1381         }
   1382 
   1383         Time currentTime = new Time(localTimezone);
   1384         currentTime.set(currentMillis);
   1385         Resources resources = context.getResources();
   1386         String datetimeString = null;
   1387         if (allDay) {
   1388             // All day events require special timezone adjustment.
   1389             long localStartMillis = convertAlldayUtcToLocal(null, startMillis, localTimezone);
   1390             long localEndMillis = convertAlldayUtcToLocal(null, endMillis, localTimezone);
   1391             if (singleDayEvent(localStartMillis, localEndMillis, currentTime.gmtoff)) {
   1392                 // If possible, use "Today" or "Tomorrow" instead of a full date string.
   1393                 int todayOrTomorrow = isTodayOrTomorrow(context.getResources(),
   1394                         localStartMillis, currentMillis, currentTime.gmtoff);
   1395                 if (TODAY == todayOrTomorrow) {
   1396                     datetimeString = resources.getString(R.string.today);
   1397                 } else if (TOMORROW == todayOrTomorrow) {
   1398                     datetimeString = resources.getString(R.string.tomorrow);
   1399                 }
   1400             }
   1401             if (datetimeString == null) {
   1402                 // For multi-day allday events or single-day all-day events that are not
   1403                 // today or tomorrow, use framework formatter.
   1404                 Formatter f = new Formatter(new StringBuilder(50), Locale.getDefault());
   1405                 datetimeString = DateUtils.formatDateRange(context, f, startMillis,
   1406                         endMillis, flagsDate, Time.TIMEZONE_UTC).toString();
   1407             }
   1408         } else {
   1409             if (singleDayEvent(startMillis, endMillis, currentTime.gmtoff)) {
   1410                 // Format the time.
   1411                 String timeString = Utils.formatDateRange(context, startMillis, endMillis,
   1412                         flagsTime);
   1413 
   1414                 // If possible, use "Today" or "Tomorrow" instead of a full date string.
   1415                 int todayOrTomorrow = isTodayOrTomorrow(context.getResources(), startMillis,
   1416                         currentMillis, currentTime.gmtoff);
   1417                 if (TODAY == todayOrTomorrow) {
   1418                     // Example: "Today at 1:00pm - 2:00 pm"
   1419                     datetimeString = resources.getString(R.string.today_at_time_fmt,
   1420                             timeString);
   1421                 } else if (TOMORROW == todayOrTomorrow) {
   1422                     // Example: "Tomorrow at 1:00pm - 2:00 pm"
   1423                     datetimeString = resources.getString(R.string.tomorrow_at_time_fmt,
   1424                             timeString);
   1425                 } else {
   1426                     // Format the full date. Example: "Thursday, April 12, 1:00pm - 2:00pm"
   1427                     String dateString = Utils.formatDateRange(context, startMillis, endMillis,
   1428                             flagsDate);
   1429                     datetimeString = resources.getString(R.string.date_time_fmt, dateString,
   1430                             timeString);
   1431                 }
   1432             } else {
   1433                 // For multiday events, shorten day/month names.
   1434                 // Example format: "Fri Apr 6, 5:00pm - Sun, Apr 8, 6:00pm"
   1435                 int flagsDatetime = flagsDate | flagsTime | DateUtils.FORMAT_ABBREV_MONTH |
   1436                         DateUtils.FORMAT_ABBREV_WEEKDAY;
   1437                 datetimeString = Utils.formatDateRange(context, startMillis, endMillis,
   1438                         flagsDatetime);
   1439             }
   1440         }
   1441         return datetimeString;
   1442     }
   1443 
   1444     /**
   1445      * Returns the timezone to display in the event info, if the local timezone is different
   1446      * from the event timezone.  Otherwise returns null.
   1447      */
   1448     public static String getDisplayedTimezone(long startMillis, String localTimezone,
   1449             String eventTimezone) {
   1450         String tzDisplay = null;
   1451         if (!TextUtils.equals(localTimezone, eventTimezone)) {
   1452             // Figure out if this is in DST
   1453             TimeZone tz = TimeZone.getTimeZone(localTimezone);
   1454             if (tz == null || tz.getID().equals("GMT")) {
   1455                 tzDisplay = localTimezone;
   1456             } else {
   1457                 Time startTime = new Time(localTimezone);
   1458                 startTime.set(startMillis);
   1459                 tzDisplay = tz.getDisplayName(startTime.isDst != 0, TimeZone.SHORT);
   1460             }
   1461         }
   1462         return tzDisplay;
   1463     }
   1464 
   1465     /**
   1466      * Returns whether the specified time interval is in a single day.
   1467      */
   1468     private static boolean singleDayEvent(long startMillis, long endMillis, long localGmtOffset) {
   1469         if (startMillis == endMillis) {
   1470             return true;
   1471         }
   1472 
   1473         // An event ending at midnight should still be a single-day event, so check
   1474         // time end-1.
   1475         int startDay = Time.getJulianDay(startMillis, localGmtOffset);
   1476         int endDay = Time.getJulianDay(endMillis - 1, localGmtOffset);
   1477         return startDay == endDay;
   1478     }
   1479 
   1480     // Using int constants as a return value instead of an enum to minimize resources.
   1481     private static final int TODAY = 1;
   1482     private static final int TOMORROW = 2;
   1483     private static final int NONE = 0;
   1484 
   1485     /**
   1486      * Returns TODAY or TOMORROW if applicable.  Otherwise returns NONE.
   1487      */
   1488     private static int isTodayOrTomorrow(Resources r, long dayMillis,
   1489             long currentMillis, long localGmtOffset) {
   1490         int startDay = Time.getJulianDay(dayMillis, localGmtOffset);
   1491         int currentDay = Time.getJulianDay(currentMillis, localGmtOffset);
   1492 
   1493         int days = startDay - currentDay;
   1494         if (days == 1) {
   1495             return TOMORROW;
   1496         } else if (days == 0) {
   1497             return TODAY;
   1498         } else {
   1499             return NONE;
   1500         }
   1501     }
   1502 
   1503     /**
   1504      * Create an intent for emailing attendees of an event.
   1505      *
   1506      * @param resources The resources for translating strings.
   1507      * @param eventTitle The title of the event to use as the email subject.
   1508      * @param body The default text for the email body.
   1509      * @param toEmails The list of emails for the 'to' line.
   1510      * @param ccEmails The list of emails for the 'cc' line.
   1511      * @param ownerAccount The owner account to use as the email sender.
   1512      */
   1513     public static Intent createEmailAttendeesIntent(Resources resources, String eventTitle,
   1514             String body, List<String> toEmails, List<String> ccEmails, String ownerAccount) {
   1515         List<String> toList = toEmails;
   1516         List<String> ccList = ccEmails;
   1517         if (toEmails.size() <= 0) {
   1518             if (ccEmails.size() <= 0) {
   1519                 // TODO: Return a SEND intent if no one to email to, to at least populate
   1520                 // a draft email with the subject (and no recipients).
   1521                 throw new IllegalArgumentException("Both toEmails and ccEmails are empty.");
   1522             }
   1523 
   1524             // Email app does not work with no "to" recipient.  Move all 'cc' to 'to'
   1525             // in this case.
   1526             toList = ccEmails;
   1527             ccList = null;
   1528         }
   1529 
   1530         // Use the event title as the email subject (prepended with 'Re: ').
   1531         String subject = null;
   1532         if (eventTitle != null) {
   1533             subject = resources.getString(R.string.email_subject_prefix) + eventTitle;
   1534         }
   1535 
   1536         // Use the SENDTO intent with a 'mailto' URI, because using SEND will cause
   1537         // the picker to show apps like text messaging, which does not make sense
   1538         // for email addresses.  We put all data in the URI instead of using the extra
   1539         // Intent fields (ie. EXTRA_CC, etc) because some email apps might not handle
   1540         // those (though gmail does).
   1541         Uri.Builder uriBuilder = new Uri.Builder();
   1542         uriBuilder.scheme("mailto");
   1543 
   1544         // We will append the first email to the 'mailto' field later (because the
   1545         // current state of the Email app requires it).  Add the remaining 'to' values
   1546         // here.  When the email codebase is updated, we can simplify this.
   1547         if (toList.size() > 1) {
   1548             for (int i = 1; i < toList.size(); i++) {
   1549                 // The Email app requires repeated parameter settings instead of
   1550                 // a single comma-separated list.
   1551                 uriBuilder.appendQueryParameter("to", toList.get(i));
   1552             }
   1553         }
   1554 
   1555         // Add the subject parameter.
   1556         if (subject != null) {
   1557             uriBuilder.appendQueryParameter("subject", subject);
   1558         }
   1559 
   1560         // Add the subject parameter.
   1561         if (body != null) {
   1562             uriBuilder.appendQueryParameter("body", body);
   1563         }
   1564 
   1565         // Add the cc parameters.
   1566         if (ccList != null && ccList.size() > 0) {
   1567             for (String email : ccList) {
   1568                 uriBuilder.appendQueryParameter("cc", email);
   1569             }
   1570         }
   1571 
   1572         // Insert the first email after 'mailto:' in the URI manually since Uri.Builder
   1573         // doesn't seem to have a way to do this.
   1574         String uri = uriBuilder.toString();
   1575         if (uri.startsWith("mailto:")) {
   1576             StringBuilder builder = new StringBuilder(uri);
   1577             builder.insert(7, Uri.encode(toList.get(0)));
   1578             uri = builder.toString();
   1579         }
   1580 
   1581         // Start the email intent.  Email from the account of the calendar owner in case there
   1582         // are multiple email accounts.
   1583         Intent emailIntent = new Intent(android.content.Intent.ACTION_SENDTO, Uri.parse(uri));
   1584         emailIntent.putExtra("fromAccountString", ownerAccount);
   1585 
   1586         // Workaround a Email bug that overwrites the body with this intent extra.  If not
   1587         // set, it clears the body.
   1588         if (body != null) {
   1589             emailIntent.putExtra(Intent.EXTRA_TEXT, body);
   1590         }
   1591 
   1592         return Intent.createChooser(emailIntent, resources.getString(R.string.email_picker_label));
   1593     }
   1594 
   1595     /**
   1596      * Example fake email addresses used as attendee emails are resources like conference rooms,
   1597      * or another calendar, etc.  These all end in "calendar.google.com".
   1598      */
   1599     public static boolean isValidEmail(String email) {
   1600         return email != null && !email.endsWith(MACHINE_GENERATED_ADDRESS);
   1601     }
   1602 
   1603     /**
   1604      * Returns true if:
   1605      *   (1) the email is not a resource like a conference room or another calendar.
   1606      *       Catch most of these by filtering out suffix calendar.google.com.
   1607      *   (2) the email is not equal to the sync account to prevent mailing himself.
   1608      */
   1609     public static boolean isEmailableFrom(String email, String syncAccountName) {
   1610         return Utils.isValidEmail(email) && !email.equals(syncAccountName);
   1611     }
   1612 
   1613     /**
   1614      * Inserts a drawable with today's day into the today's icon in the option menu
   1615      * @param icon - today's icon from the options menu
   1616      */
   1617     public static void setTodayIcon(LayerDrawable icon, Context c, String timezone) {
   1618         DayOfMonthDrawable today;
   1619 
   1620         // Reuse current drawable if possible
   1621         Drawable currentDrawable = icon.findDrawableByLayerId(R.id.today_icon_day);
   1622         if (currentDrawable != null && currentDrawable instanceof DayOfMonthDrawable) {
   1623             today = (DayOfMonthDrawable)currentDrawable;
   1624         } else {
   1625             today = new DayOfMonthDrawable(c);
   1626         }
   1627         // Set the day and update the icon
   1628         Time now =  new Time(timezone);
   1629         now.setToNow();
   1630         now.normalize(false);
   1631         today.setDayOfMonth(now.monthDay);
   1632         icon.mutate();
   1633         icon.setDrawableByLayerId(R.id.today_icon_day, today);
   1634     }
   1635 
   1636     private static class CalendarBroadcastReceiver extends BroadcastReceiver {
   1637 
   1638         Runnable mCallBack;
   1639 
   1640         public CalendarBroadcastReceiver(Runnable callback) {
   1641             super();
   1642             mCallBack = callback;
   1643         }
   1644         @Override
   1645         public void onReceive(Context context, Intent intent) {
   1646             if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED) ||
   1647                     intent.getAction().equals(Intent.ACTION_TIME_CHANGED) ||
   1648                     intent.getAction().equals(Intent.ACTION_LOCALE_CHANGED) ||
   1649                     intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {
   1650                 if (mCallBack != null) {
   1651                     mCallBack.run();
   1652                 }
   1653             }
   1654         }
   1655     }
   1656 
   1657     public static BroadcastReceiver setTimeChangesReceiver(Context c, Runnable callback) {
   1658         IntentFilter filter = new IntentFilter();
   1659         filter.addAction(Intent.ACTION_TIME_CHANGED);
   1660         filter.addAction(Intent.ACTION_DATE_CHANGED);
   1661         filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
   1662         filter.addAction(Intent.ACTION_LOCALE_CHANGED);
   1663 
   1664         CalendarBroadcastReceiver r = new CalendarBroadcastReceiver(callback);
   1665         c.registerReceiver(r, filter);
   1666         return r;
   1667     }
   1668 
   1669     public static void clearTimeChangesReceiver(Context c, BroadcastReceiver r) {
   1670         c.unregisterReceiver(r);
   1671     }
   1672 
   1673     /**
   1674      * Get a list of quick responses used for emailing guests from the
   1675      * SharedPreferences. If not are found, get the hard coded ones that shipped
   1676      * with the app
   1677      *
   1678      * @param context
   1679      * @return a list of quick responses.
   1680      */
   1681     public static String[] getQuickResponses(Context context) {
   1682         String[] s = Utils.getSharedPreference(context, KEY_QUICK_RESPONSES, (String[]) null);
   1683 
   1684         if (s == null) {
   1685             s = context.getResources().getStringArray(R.array.quick_response_defaults);
   1686         }
   1687 
   1688         return s;
   1689     }
   1690 
   1691     /**
   1692      * Return the app version code.
   1693      */
   1694     public static String getVersionCode(Context context) {
   1695         if (sVersion == null) {
   1696             try {
   1697                 sVersion = context.getPackageManager().getPackageInfo(
   1698                         context.getPackageName(), 0).versionName;
   1699             } catch (PackageManager.NameNotFoundException e) {
   1700                 // Can't find version; just leave it blank.
   1701                 Log.e(TAG, "Error finding package " + context.getApplicationInfo().packageName);
   1702             }
   1703         }
   1704         return sVersion;
   1705     }
   1706 
   1707     /**
   1708      * Checks the server for an updated list of Calendars (in the background).
   1709      *
   1710      * If a Calendar is added on the web (and it is selected and not
   1711      * hidden) then it will be added to the list of calendars on the phone
   1712      * (when this finishes).  When a new calendar from the
   1713      * web is added to the phone, then the events for that calendar are also
   1714      * downloaded from the web.
   1715      *
   1716      * This sync is done automatically in the background when the
   1717      * SelectCalendars activity and fragment are started.
   1718      *
   1719      * @param account - The account to sync. May be null to sync all accounts.
   1720      */
   1721     public static void startCalendarMetafeedSync(Account account) {
   1722         Bundle extras = new Bundle();
   1723         extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
   1724         extras.putBoolean("metafeedonly", true);
   1725         ContentResolver.requestSync(account, Calendars.CONTENT_URI.getAuthority(), extras);
   1726     }
   1727 
   1728     /**
   1729      * Replaces stretches of text that look like addresses and phone numbers with clickable
   1730      * links. If lastDitchGeo is true, then if no links are found in the textview, the entire
   1731      * string will be converted to a single geo link. Any spans that may have previously been
   1732      * in the text will be cleared out.
   1733      * <p>
   1734      * This is really just an enhanced version of Linkify.addLinks().
   1735      *
   1736      * @param text - The string to search for links.
   1737      * @param lastDitchGeo - If no links are found, turn the entire string into one geo link.
   1738      * @return Spannable object containing the list of URL spans found.
   1739      */
   1740     public static Spannable extendedLinkify(String text, boolean lastDitchGeo) {
   1741         // We use a copy of the string argument so it's available for later if necessary.
   1742         Spannable spanText = SpannableString.valueOf(text);
   1743 
   1744         /*
   1745          * If the text includes a street address like "1600 Amphitheater Parkway, 94043",
   1746          * the current Linkify code will identify "94043" as a phone number and invite
   1747          * you to dial it (and not provide a map link for the address).  For outside US,
   1748          * use Linkify result iff it spans the entire text.  Otherwise send the user to maps.
   1749          */
   1750         String defaultPhoneRegion = System.getProperty("user.region", "US");
   1751         if (!defaultPhoneRegion.equals("US")) {
   1752             Linkify.addLinks(spanText, Linkify.ALL);
   1753 
   1754             // If Linkify links the entire text, use that result.
   1755             URLSpan[] spans = spanText.getSpans(0, spanText.length(), URLSpan.class);
   1756             if (spans.length == 1) {
   1757                 int linkStart = spanText.getSpanStart(spans[0]);
   1758                 int linkEnd = spanText.getSpanEnd(spans[0]);
   1759                 if (linkStart <= indexFirstNonWhitespaceChar(spanText) &&
   1760                         linkEnd >= indexLastNonWhitespaceChar(spanText) + 1) {
   1761                     return spanText;
   1762                 }
   1763             }
   1764 
   1765             // Otherwise, to be cautious and to try to prevent false positives, reset the spannable.
   1766             spanText = SpannableString.valueOf(text);
   1767             // If lastDitchGeo is true, default the entire string to geo.
   1768             if (lastDitchGeo && !text.isEmpty()) {
   1769                 Linkify.addLinks(spanText, mWildcardPattern, "geo:0,0?q=");
   1770             }
   1771             return spanText;
   1772         }
   1773 
   1774         /*
   1775          * For within US, we want to have better recognition of phone numbers without losing
   1776          * any of the existing annotations.  Ideally this would be addressed by improving Linkify.
   1777          * For now we manage it as a second pass over the text.
   1778          *
   1779          * URIs and e-mail addresses are pretty easy to pick out of text.  Phone numbers
   1780          * are a bit tricky because they have radically different formats in different
   1781          * countries, in terms of both the digits and the way in which they are commonly
   1782          * written or presented (e.g. the punctuation and spaces in "(650) 555-1212").
   1783          * The expected format of a street address is defined in WebView.findAddress().  It's
   1784          * pretty narrowly defined, so it won't often match.
   1785          *
   1786          * The RFC 3966 specification defines the format of a "tel:" URI.
   1787          *
   1788          * Start by letting Linkify find anything that isn't a phone number.  We have to let it
   1789          * run first because every invocation removes all previous URLSpan annotations.
   1790          *
   1791          * Ideally we'd use the external/libphonenumber routines, but those aren't available
   1792          * to unbundled applications.
   1793          */
   1794         boolean linkifyFoundLinks = Linkify.addLinks(spanText,
   1795                 Linkify.ALL & ~(Linkify.PHONE_NUMBERS));
   1796 
   1797         /*
   1798          * Get a list of any spans created by Linkify, for the coordinate overlapping span check.
   1799          */
   1800         URLSpan[] existingSpans = spanText.getSpans(0, spanText.length(), URLSpan.class);
   1801 
   1802         /*
   1803          * Check for coordinates.
   1804          * This must be done before phone numbers because longitude may look like a phone number.
   1805          */
   1806         Matcher coordMatcher = COORD_PATTERN.matcher(spanText);
   1807         int coordCount = 0;
   1808         while (coordMatcher.find()) {
   1809             int start = coordMatcher.start();
   1810             int end = coordMatcher.end();
   1811             if (spanWillOverlap(spanText, existingSpans, start, end)) {
   1812                 continue;
   1813             }
   1814 
   1815             URLSpan span = new URLSpan("geo:0,0?q=" + coordMatcher.group());
   1816             spanText.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
   1817             coordCount++;
   1818         }
   1819 
   1820         /*
   1821          * Update the list of existing spans, for the phone number overlapping span check.
   1822          */
   1823         existingSpans = spanText.getSpans(0, spanText.length(), URLSpan.class);
   1824 
   1825         /*
   1826          * Search for phone numbers.
   1827          *
   1828          * Some URIs contain strings of digits that look like phone numbers.  If both the URI
   1829          * scanner and the phone number scanner find them, we want the URI link to win.  Since
   1830          * the URI scanner runs first, we just need to avoid creating overlapping spans.
   1831          */
   1832         int[] phoneSequences = findNanpPhoneNumbers(text);
   1833 
   1834         /*
   1835          * Insert spans for the numbers we found.  We generate "tel:" URIs.
   1836          */
   1837         int phoneCount = 0;
   1838         for (int match = 0; match < phoneSequences.length / 2; match++) {
   1839             int start = phoneSequences[match*2];
   1840             int end = phoneSequences[match*2 + 1];
   1841 
   1842             if (spanWillOverlap(spanText, existingSpans, start, end)) {
   1843                 continue;
   1844             }
   1845 
   1846             /*
   1847              * The Linkify code takes the matching span and strips out everything that isn't a
   1848              * digit or '+' sign.  We do the same here.  Extension numbers will get appended
   1849              * without a separator, but the dialer wasn't doing anything useful with ";ext="
   1850              * anyway.
   1851              */
   1852 
   1853             //String dialStr = phoneUtil.format(match.number(),
   1854             //        PhoneNumberUtil.PhoneNumberFormat.RFC3966);
   1855             StringBuilder dialBuilder = new StringBuilder();
   1856             for (int i = start; i < end; i++) {
   1857                 char ch = spanText.charAt(i);
   1858                 if (ch == '+' || Character.isDigit(ch)) {
   1859                     dialBuilder.append(ch);
   1860                 }
   1861             }
   1862             URLSpan span = new URLSpan("tel:" + dialBuilder.toString());
   1863 
   1864             spanText.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
   1865             phoneCount++;
   1866         }
   1867 
   1868         /*
   1869          * If lastDitchGeo, and no other links have been found, set the entire string as a geo link.
   1870          */
   1871         if (lastDitchGeo && !text.isEmpty() &&
   1872                 !linkifyFoundLinks && phoneCount == 0 && coordCount == 0) {
   1873             if (Log.isLoggable(TAG, Log.VERBOSE)) {
   1874                 Log.v(TAG, "No linkification matches, using geo default");
   1875             }
   1876             Linkify.addLinks(spanText, mWildcardPattern, "geo:0,0?q=");
   1877         }
   1878 
   1879         return spanText;
   1880     }
   1881 
   1882     private static int indexFirstNonWhitespaceChar(CharSequence str) {
   1883         for (int i = 0; i < str.length(); i++) {
   1884             if (!Character.isWhitespace(str.charAt(i))) {
   1885                 return i;
   1886             }
   1887         }
   1888         return -1;
   1889     }
   1890 
   1891     private static int indexLastNonWhitespaceChar(CharSequence str) {
   1892         for (int i = str.length() - 1; i >= 0; i--) {
   1893             if (!Character.isWhitespace(str.charAt(i))) {
   1894                 return i;
   1895             }
   1896         }
   1897         return -1;
   1898     }
   1899 
   1900     /**
   1901      * Finds North American Numbering Plan (NANP) phone numbers in the input text.
   1902      *
   1903      * @param text The text to scan.
   1904      * @return A list of [start, end) pairs indicating the positions of phone numbers in the input.
   1905      */
   1906     // @VisibleForTesting
   1907     static int[] findNanpPhoneNumbers(CharSequence text) {
   1908         ArrayList<Integer> list = new ArrayList<Integer>();
   1909 
   1910         int startPos = 0;
   1911         int endPos = text.length() - NANP_MIN_DIGITS + 1;
   1912         if (endPos < 0) {
   1913             return new int[] {};
   1914         }
   1915 
   1916         /*
   1917          * We can't just strip the whitespace out and crunch it down, because the whitespace
   1918          * is significant.  March through, trying to figure out where numbers start and end.
   1919          */
   1920         while (startPos < endPos) {
   1921             // skip whitespace
   1922             while (Character.isWhitespace(text.charAt(startPos)) && startPos < endPos) {
   1923                 startPos++;
   1924             }
   1925             if (startPos == endPos) {
   1926                 break;
   1927             }
   1928 
   1929             // check for a match at this position
   1930             int matchEnd = findNanpMatchEnd(text, startPos);
   1931             if (matchEnd > startPos) {
   1932                 list.add(startPos);
   1933                 list.add(matchEnd);
   1934                 startPos = matchEnd;    // skip past match
   1935             } else {
   1936                 // skip to next whitespace char
   1937                 while (!Character.isWhitespace(text.charAt(startPos)) && startPos < endPos) {
   1938                     startPos++;
   1939                 }
   1940             }
   1941         }
   1942 
   1943         int[] result = new int[list.size()];
   1944         for (int i = list.size() - 1; i >= 0; i--) {
   1945             result[i] = list.get(i);
   1946         }
   1947         return result;
   1948     }
   1949 
   1950     /**
   1951      * Checks to see if there is a valid phone number in the input, starting at the specified
   1952      * offset.  If so, the index of the last character + 1 is returned.  The input is assumed
   1953      * to begin with a non-whitespace character.
   1954      *
   1955      * @return Exclusive end position, or -1 if not a match.
   1956      */
   1957     private static int findNanpMatchEnd(CharSequence text, int startPos) {
   1958         /*
   1959          * A few interesting cases:
   1960          *   94043                              # too short, ignore
   1961          *   123456789012                       # too long, ignore
   1962          *   +1 (650) 555-1212                  # 11 digits, spaces
   1963          *   (650) 555 5555                     # Second space, only when first is present.
   1964          *   (650) 555-1212, (650) 555-1213     # two numbers, return first
   1965          *   1-650-555-1212                     # 11 digits with leading '1'
   1966          *   *#650.555.1212#*!                  # 10 digits, include #*, ignore trailing '!'
   1967          *   555.1212                           # 7 digits
   1968          *
   1969          * For the most part we want to break on whitespace, but it's common to leave a space
   1970          * between the initial '1' and/or after the area code.
   1971          */
   1972 
   1973         // Check for "tel:" URI prefix.
   1974         if (text.length() > startPos+4
   1975                 && text.subSequence(startPos, startPos+4).toString().equalsIgnoreCase("tel:")) {
   1976             startPos += 4;
   1977         }
   1978 
   1979         int endPos = text.length();
   1980         int curPos = startPos;
   1981         int foundDigits = 0;
   1982         char firstDigit = 'x';
   1983         boolean foundWhiteSpaceAfterAreaCode = false;
   1984 
   1985         while (curPos <= endPos) {
   1986             char ch;
   1987             if (curPos < endPos) {
   1988                 ch = text.charAt(curPos);
   1989             } else {
   1990                 ch = 27;    // fake invalid symbol at end to trigger loop break
   1991             }
   1992 
   1993             if (Character.isDigit(ch)) {
   1994                 if (foundDigits == 0) {
   1995                     firstDigit = ch;
   1996                 }
   1997                 foundDigits++;
   1998                 if (foundDigits > NANP_MAX_DIGITS) {
   1999                     // too many digits, stop early
   2000                     return -1;
   2001                 }
   2002             } else if (Character.isWhitespace(ch)) {
   2003                 if ( (firstDigit == '1' && foundDigits == 4) ||
   2004                         (foundDigits == 3)) {
   2005                     foundWhiteSpaceAfterAreaCode = true;
   2006                 } else if (firstDigit == '1' && foundDigits == 1) {
   2007                 } else if (foundWhiteSpaceAfterAreaCode
   2008                         && ( (firstDigit == '1' && (foundDigits == 7)) || (foundDigits == 6))) {
   2009                 } else {
   2010                     break;
   2011                 }
   2012             } else if (NANP_ALLOWED_SYMBOLS.indexOf(ch) == -1) {
   2013                 break;
   2014             }
   2015             // else it's an allowed symbol
   2016 
   2017             curPos++;
   2018         }
   2019 
   2020         if ((firstDigit != '1' && (foundDigits == 7 || foundDigits == 10)) ||
   2021                 (firstDigit == '1' && foundDigits == 11)) {
   2022             // match
   2023             return curPos;
   2024         }
   2025 
   2026         return -1;
   2027     }
   2028 
   2029     /**
   2030      * Determines whether a new span at [start,end) will overlap with any existing span.
   2031      */
   2032     private static boolean spanWillOverlap(Spannable spanText, URLSpan[] spanList, int start,
   2033             int end) {
   2034         if (start == end) {
   2035             // empty span, ignore
   2036             return false;
   2037         }
   2038         for (URLSpan span : spanList) {
   2039             int existingStart = spanText.getSpanStart(span);
   2040             int existingEnd = spanText.getSpanEnd(span);
   2041             if ((start >= existingStart && start < existingEnd) ||
   2042                     end > existingStart && end <= existingEnd) {
   2043                 if (Log.isLoggable(TAG, Log.VERBOSE)) {
   2044                     CharSequence seq = spanText.subSequence(start, end);
   2045                     Log.v(TAG, "Not linkifying " + seq + " as phone number due to overlap");
   2046                 }
   2047                 return true;
   2048             }
   2049         }
   2050 
   2051         return false;
   2052     }
   2053 
   2054     /**
   2055      * @param bundle The incoming bundle that contains the reminder info.
   2056      * @return ArrayList<ReminderEntry> of the reminder minutes and methods.
   2057      */
   2058     public static ArrayList<ReminderEntry> readRemindersFromBundle(Bundle bundle) {
   2059         ArrayList<ReminderEntry> reminders = null;
   2060 
   2061         ArrayList<Integer> reminderMinutes = bundle.getIntegerArrayList(
   2062                         EventInfoFragment.BUNDLE_KEY_REMINDER_MINUTES);
   2063         ArrayList<Integer> reminderMethods = bundle.getIntegerArrayList(
   2064                 EventInfoFragment.BUNDLE_KEY_REMINDER_METHODS);
   2065         if (reminderMinutes == null || reminderMethods == null) {
   2066             if (reminderMinutes != null || reminderMethods != null) {
   2067                 String nullList = (reminderMinutes == null?
   2068                         "reminderMinutes" : "reminderMethods");
   2069                 Log.d(TAG, String.format("Error resolving reminders: %s was null",
   2070                         nullList));
   2071             }
   2072             return null;
   2073         }
   2074 
   2075         int numReminders = reminderMinutes.size();
   2076         if (numReminders == reminderMethods.size()) {
   2077             // Only if the size of the reminder minutes we've read in is
   2078             // the same as the size of the reminder methods. Otherwise,
   2079             // something went wrong with bundling them.
   2080             reminders = new ArrayList<ReminderEntry>(numReminders);
   2081             for (int reminder_i = 0; reminder_i < numReminders;
   2082                     reminder_i++) {
   2083                 int minutes = reminderMinutes.get(reminder_i);
   2084                 int method = reminderMethods.get(reminder_i);
   2085                 reminders.add(ReminderEntry.valueOf(minutes, method));
   2086             }
   2087         } else {
   2088             Log.d(TAG, String.format("Error resolving reminders." +
   2089                         " Found %d reminderMinutes, but %d reminderMethods.",
   2090                     numReminders, reminderMethods.size()));
   2091         }
   2092 
   2093         return reminders;
   2094     }
   2095 
   2096 }
   2097