Utils.java revision 17c0cea5c4e5eee7b6c1676038e9223dd971007b
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
17package com.android.calendar;
18
19import static android.provider.CalendarContract.EXTRA_EVENT_BEGIN_TIME;
20
21import com.android.calendar.CalendarController.ViewType;
22
23import android.app.Activity;
24import android.app.SearchManager;
25import android.content.Context;
26import android.content.Intent;
27import android.content.SharedPreferences;
28import android.content.res.Configuration;
29import android.content.res.Resources;
30import android.database.Cursor;
31import android.database.MatrixCursor;
32import android.graphics.Color;
33import android.net.Uri;
34import android.os.Bundle;
35import android.text.TextUtils;
36import android.text.format.DateUtils;
37import android.text.format.Time;
38import android.util.Log;
39import android.widget.SearchView;
40
41import com.android.calendar.CalendarUtils.TimeZoneUtils;
42
43import java.util.ArrayList;
44import java.util.Arrays;
45import java.util.Calendar;
46import java.util.Formatter;
47import java.util.HashMap;
48import java.util.Iterator;
49import java.util.LinkedList;
50import java.util.List;
51import java.util.Map;
52
53public class Utils {
54    private static final boolean DEBUG = false;
55    private static final String TAG = "CalUtils";
56    // Set to 0 until we have UI to perform undo
57    public static final long UNDO_DELAY = 0;
58
59    // For recurring events which instances of the series are being modified
60    public static final int MODIFY_UNINITIALIZED = 0;
61    public static final int MODIFY_SELECTED = 1;
62    public static final int MODIFY_ALL_FOLLOWING = 2;
63    public static final int MODIFY_ALL = 3;
64
65    // When the edit event view finishes it passes back the appropriate exit
66    // code.
67    public static final int DONE_REVERT = 1 << 0;
68    public static final int DONE_SAVE = 1 << 1;
69    public static final int DONE_DELETE = 1 << 2;
70    // And should re run with DONE_EXIT if it should also leave the view, just
71    // exiting is identical to reverting
72    public static final int DONE_EXIT = 1 << 0;
73
74    public static final String OPEN_EMAIL_MARKER = " <";
75    public static final String CLOSE_EMAIL_MARKER = ">";
76
77    public static final String INTENT_KEY_DETAIL_VIEW = "DETAIL_VIEW";
78    public static final String INTENT_KEY_VIEW_TYPE = "VIEW";
79    public static final String INTENT_VALUE_VIEW_TYPE_DAY = "DAY";
80
81    public static final int MONDAY_BEFORE_JULIAN_EPOCH = Time.EPOCH_JULIAN_DAY - 3;
82
83    private static final float SATURATION_ADJUST = 0.3f;
84
85    // Defines used by the DNA generation code
86    static final int DAY_IN_MINUTES = 60 * 24;
87    static final int WEEK_IN_MINUTES = DAY_IN_MINUTES * 7;
88    // The work day is being counted as 6am to 8pm
89    static int WORK_DAY_MINUTES = 14 * 60;
90    static int WORK_DAY_START_MINUTES = 6 * 60;
91    static int WORK_DAY_END_MINUTES = 20 * 60;
92    static int WORK_DAY_END_LENGTH = (24 * 60) - WORK_DAY_END_MINUTES;
93    static int CONFLICT_COLOR = 0xFF000000;
94    static boolean mMinutesLoaded = false;
95
96    // The name of the shared preferences file. This name must be maintained for
97    // historical
98    // reasons, as it's what PreferenceManager assigned the first time the file
99    // was created.
100    private static final String SHARED_PREFS_NAME = "com.android.calendar_preferences";
101
102    public static final String APPWIDGET_DATA_TYPE = "vnd.android.data/update";
103
104    private static final TimeZoneUtils mTZUtils = new TimeZoneUtils(SHARED_PREFS_NAME);
105    private static boolean mAllowWeekForDetailView = false;
106    private static long mTardis = 0;
107
108    public static int getViewTypeFromIntentAndSharedPref(Activity activity) {
109        Intent intent = activity.getIntent();
110        Bundle extras = intent.getExtras();
111        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(activity);
112
113        if (TextUtils.equals(intent.getAction(), Intent.ACTION_EDIT)) {
114            return ViewType.EDIT;
115        }
116        if (extras != null) {
117            if (extras.getBoolean(INTENT_KEY_DETAIL_VIEW, false)) {
118                // This is the "detail" view which is either agenda or day view
119                return prefs.getInt(GeneralPreferences.KEY_DETAILED_VIEW,
120                        GeneralPreferences.DEFAULT_DETAILED_VIEW);
121            } else if (INTENT_VALUE_VIEW_TYPE_DAY.equals(extras.getString(INTENT_KEY_VIEW_TYPE))) {
122                // Not sure who uses this. This logic came from LaunchActivity
123                return ViewType.DAY;
124            }
125        }
126
127        // Default to the last view
128        return prefs.getInt(
129                GeneralPreferences.KEY_START_VIEW, GeneralPreferences.DEFAULT_START_VIEW);
130    }
131
132    /**
133     * Gets the intent action for telling the widget to update.
134     */
135    public static String getWidgetUpdateAction(Context context) {
136        return context.getPackageName() + ".APPWIDGET_UPDATE";
137    }
138
139    /**
140     * Gets the intent action for telling the widget to update.
141     */
142    public static String getWidgetScheduledUpdateAction(Context context) {
143        return context.getPackageName() + ".APPWIDGET_SCHEDULED_UPDATE";
144    }
145
146    /**
147     * Gets the intent action for telling the widget to update.
148     */
149    public static String getSearchAuthority(Context context) {
150        return context.getPackageName() + ".CalendarRecentSuggestionsProvider";
151    }
152
153    /**
154     * Writes a new home time zone to the db. Updates the home time zone in the
155     * db asynchronously and updates the local cache. Sending a time zone of
156     * **tbd** will cause it to be set to the device's time zone. null or empty
157     * tz will be ignored.
158     *
159     * @param context The calling activity
160     * @param timeZone The time zone to set Calendar to, or **tbd**
161     */
162    public static void setTimeZone(Context context, String timeZone) {
163        mTZUtils.setTimeZone(context, timeZone);
164    }
165
166    /**
167     * Gets the time zone that Calendar should be displayed in This is a helper
168     * method to get the appropriate time zone for Calendar. If this is the
169     * first time this method has been called it will initiate an asynchronous
170     * query to verify that the data in preferences is correct. The callback
171     * supplied will only be called if this query returns a value other than
172     * what is stored in preferences and should cause the calling activity to
173     * refresh anything that depends on calling this method.
174     *
175     * @param context The calling activity
176     * @param callback The runnable that should execute if a query returns new
177     *            values
178     * @return The string value representing the time zone Calendar should
179     *         display
180     */
181    public static String getTimeZone(Context context, Runnable callback) {
182        return mTZUtils.getTimeZone(context, callback);
183    }
184
185    /**
186     * Formats a date or a time range according to the local conventions.
187     *
188     * @param context the context is required only if the time is shown
189     * @param startMillis the start time in UTC milliseconds
190     * @param endMillis the end time in UTC milliseconds
191     * @param flags a bit mask of options See {@link DateUtils#formatDateRange(Context, Formatter,
192     * long, long, int, String) formatDateRange}
193     * @return a string containing the formatted date/time range.
194     */
195    public static String formatDateRange(
196            Context context, long startMillis, long endMillis, int flags) {
197        return mTZUtils.formatDateRange(context, startMillis, endMillis, flags);
198    }
199
200    public static String getSharedPreference(Context context, String key, String defaultValue) {
201        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
202        return prefs.getString(key, defaultValue);
203    }
204
205    public static int getSharedPreference(Context context, String key, int defaultValue) {
206        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
207        return prefs.getInt(key, defaultValue);
208    }
209
210    public static boolean getSharedPreference(Context context, String key, boolean defaultValue) {
211        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
212        return prefs.getBoolean(key, defaultValue);
213    }
214
215    /**
216     * Asynchronously sets the preference with the given key to the given value
217     *
218     * @param context the context to use to get preferences from
219     * @param key the key of the preference to set
220     * @param value the value to set
221     */
222    public static void setSharedPreference(Context context, String key, String value) {
223        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
224        prefs.edit().putString(key, value).apply();
225    }
226
227    protected static void tardis() {
228        mTardis = System.currentTimeMillis();
229    }
230
231    protected static long getTardis() {
232        return mTardis;
233    }
234
235    static void setSharedPreference(Context context, String key, boolean value) {
236        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
237        SharedPreferences.Editor editor = prefs.edit();
238        editor.putBoolean(key, value);
239        editor.apply();
240    }
241
242    static void setSharedPreference(Context context, String key, int value) {
243        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
244        SharedPreferences.Editor editor = prefs.edit();
245        editor.putInt(key, value);
246        editor.apply();
247    }
248
249    /**
250     * Save default agenda/day/week/month view for next time
251     *
252     * @param context
253     * @param viewId {@link CalendarController.ViewType}
254     */
255    static void setDefaultView(Context context, int viewId) {
256        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
257        SharedPreferences.Editor editor = prefs.edit();
258
259        boolean validDetailView = false;
260        if (mAllowWeekForDetailView && viewId == CalendarController.ViewType.WEEK) {
261            validDetailView = true;
262        } else {
263            validDetailView = viewId == CalendarController.ViewType.AGENDA
264                    || viewId == CalendarController.ViewType.DAY;
265        }
266
267        if (validDetailView) {
268            // Record the detail start view
269            editor.putInt(GeneralPreferences.KEY_DETAILED_VIEW, viewId);
270        }
271
272        // Record the (new) start view
273        editor.putInt(GeneralPreferences.KEY_START_VIEW, viewId);
274        editor.apply();
275    }
276
277    public static MatrixCursor matrixCursorFromCursor(Cursor cursor) {
278        MatrixCursor newCursor = new MatrixCursor(cursor.getColumnNames());
279        int numColumns = cursor.getColumnCount();
280        String data[] = new String[numColumns];
281        cursor.moveToPosition(-1);
282        while (cursor.moveToNext()) {
283            for (int i = 0; i < numColumns; i++) {
284                data[i] = cursor.getString(i);
285            }
286            newCursor.addRow(data);
287        }
288        return newCursor;
289    }
290
291    /**
292     * Compares two cursors to see if they contain the same data.
293     *
294     * @return Returns true of the cursors contain the same data and are not
295     *         null, false otherwise
296     */
297    public static boolean compareCursors(Cursor c1, Cursor c2) {
298        if (c1 == null || c2 == null) {
299            return false;
300        }
301
302        int numColumns = c1.getColumnCount();
303        if (numColumns != c2.getColumnCount()) {
304            return false;
305        }
306
307        if (c1.getCount() != c2.getCount()) {
308            return false;
309        }
310
311        c1.moveToPosition(-1);
312        c2.moveToPosition(-1);
313        while (c1.moveToNext() && c2.moveToNext()) {
314            for (int i = 0; i < numColumns; i++) {
315                if (!TextUtils.equals(c1.getString(i), c2.getString(i))) {
316                    return false;
317                }
318            }
319        }
320
321        return true;
322    }
323
324    /**
325     * If the given intent specifies a time (in milliseconds since the epoch),
326     * then that time is returned. Otherwise, the current time is returned.
327     */
328    public static final long timeFromIntentInMillis(Intent intent) {
329        // If the time was specified, then use that. Otherwise, use the current
330        // time.
331        Uri data = intent.getData();
332        long millis = intent.getLongExtra(EXTRA_EVENT_BEGIN_TIME, -1);
333        if (millis == -1 && data != null && data.isHierarchical()) {
334            List<String> path = data.getPathSegments();
335            if (path.size() == 2 && path.get(0).equals("time")) {
336                try {
337                    millis = Long.valueOf(data.getLastPathSegment());
338                } catch (NumberFormatException e) {
339                    Log.i("Calendar", "timeFromIntentInMillis: Data existed but no valid time "
340                            + "found. Using current time.");
341                }
342            }
343        }
344        if (millis <= 0) {
345            millis = System.currentTimeMillis();
346        }
347        return millis;
348    }
349
350    /**
351     * Formats the given Time object so that it gives the month and year (for
352     * example, "September 2007").
353     *
354     * @param time the time to format
355     * @return the string containing the weekday and the date
356     */
357    public static String formatMonthYear(Context context, Time time) {
358        int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY
359                | DateUtils.FORMAT_SHOW_YEAR;
360        long millis = time.toMillis(true);
361        return formatDateRange(context, millis, millis, flags);
362    }
363
364    /**
365     * Returns a list joined together by the provided delimiter, for example,
366     * ["a", "b", "c"] could be joined into "a,b,c"
367     *
368     * @param things the things to join together
369     * @param delim the delimiter to use
370     * @return a string contained the things joined together
371     */
372    public static String join(List<?> things, String delim) {
373        StringBuilder builder = new StringBuilder();
374        boolean first = true;
375        for (Object thing : things) {
376            if (first) {
377                first = false;
378            } else {
379                builder.append(delim);
380            }
381            builder.append(thing.toString());
382        }
383        return builder.toString();
384    }
385
386    /**
387     * Returns the week since {@link Time#EPOCH_JULIAN_DAY} (Jan 1, 1970)
388     * adjusted for first day of week.
389     *
390     * This takes a julian day and the week start day and calculates which
391     * week since {@link Time#EPOCH_JULIAN_DAY} that day occurs in, starting
392     * at 0. *Do not* use this to compute the ISO week number for the year.
393     *
394     * @param julianDay The julian day to calculate the week number for
395     * @param firstDayOfWeek Which week day is the first day of the week,
396     *          see {@link Time#SUNDAY}
397     * @return Weeks since the epoch
398     */
399    public static int getWeeksSinceEpochFromJulianDay(int julianDay, int firstDayOfWeek) {
400        int diff = Time.THURSDAY - firstDayOfWeek;
401        if (diff < 0) {
402            diff += 7;
403        }
404        int refDay = Time.EPOCH_JULIAN_DAY - diff;
405        return (julianDay - refDay) / 7;
406    }
407
408    /**
409     * Takes a number of weeks since the epoch and calculates the Julian day of
410     * the Monday for that week.
411     *
412     * This assumes that the week containing the {@link Time#EPOCH_JULIAN_DAY}
413     * is considered week 0. It returns the Julian day for the Monday
414     * {@code week} weeks after the Monday of the week containing the epoch.
415     *
416     * @param week Number of weeks since the epoch
417     * @return The julian day for the Monday of the given week since the epoch
418     */
419    public static int getJulianMondayFromWeeksSinceEpoch(int week) {
420        return MONDAY_BEFORE_JULIAN_EPOCH + week * 7;
421    }
422
423    /**
424     * Get first day of week as android.text.format.Time constant.
425     *
426     * @return the first day of week in android.text.format.Time
427     */
428    public static int getFirstDayOfWeek(Context context) {
429        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
430        String pref = prefs.getString(
431                GeneralPreferences.KEY_WEEK_START_DAY, GeneralPreferences.WEEK_START_DEFAULT);
432
433        int startDay;
434        if (GeneralPreferences.WEEK_START_DEFAULT.equals(pref)) {
435            startDay = Calendar.getInstance().getFirstDayOfWeek();
436        } else {
437            startDay = Integer.parseInt(pref);
438        }
439
440        if (startDay == Calendar.SATURDAY) {
441            return Time.SATURDAY;
442        } else if (startDay == Calendar.MONDAY) {
443            return Time.MONDAY;
444        } else {
445            return Time.SUNDAY;
446        }
447    }
448
449    /**
450     * @return true when week number should be shown.
451     */
452    public static boolean getShowWeekNumber(Context context) {
453        final SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
454        return prefs.getBoolean(
455                GeneralPreferences.KEY_SHOW_WEEK_NUM, GeneralPreferences.DEFAULT_SHOW_WEEK_NUM);
456    }
457
458    /**
459     * @return true when declined events should be hidden.
460     */
461    public static boolean getHideDeclinedEvents(Context context) {
462        final SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
463        return prefs.getBoolean(GeneralPreferences.KEY_HIDE_DECLINED, false);
464    }
465
466    public static int getDaysPerWeek(Context context) {
467        final SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
468        return prefs.getInt(GeneralPreferences.KEY_DAYS_PER_WEEK, 7);
469    }
470
471    /**
472     * Determine whether the column position is Saturday or not.
473     *
474     * @param column the column position
475     * @param firstDayOfWeek the first day of week in android.text.format.Time
476     * @return true if the column is Saturday position
477     */
478    public static boolean isSaturday(int column, int firstDayOfWeek) {
479        return (firstDayOfWeek == Time.SUNDAY && column == 6)
480                || (firstDayOfWeek == Time.MONDAY && column == 5)
481                || (firstDayOfWeek == Time.SATURDAY && column == 0);
482    }
483
484    /**
485     * Determine whether the column position is Sunday or not.
486     *
487     * @param column the column position
488     * @param firstDayOfWeek the first day of week in android.text.format.Time
489     * @return true if the column is Sunday position
490     */
491    public static boolean isSunday(int column, int firstDayOfWeek) {
492        return (firstDayOfWeek == Time.SUNDAY && column == 0)
493                || (firstDayOfWeek == Time.MONDAY && column == 6)
494                || (firstDayOfWeek == Time.SATURDAY && column == 1);
495    }
496
497    /**
498     * Convert given UTC time into current local time. This assumes it is for an
499     * allday event and will adjust the time to be on a midnight boundary.
500     *
501     * @param recycle Time object to recycle, otherwise null.
502     * @param utcTime Time to convert, in UTC.
503     * @param tz The time zone to convert this time to.
504     */
505    public static long convertAlldayUtcToLocal(Time recycle, long utcTime, String tz) {
506        if (recycle == null) {
507            recycle = new Time();
508        }
509        recycle.timezone = Time.TIMEZONE_UTC;
510        recycle.set(utcTime);
511        recycle.timezone = tz;
512        return recycle.normalize(true);
513    }
514
515    public static long convertAlldayLocalToUTC(Time recycle, long localTime, String tz) {
516        if (recycle == null) {
517            recycle = new Time();
518        }
519        recycle.timezone = tz;
520        recycle.set(localTime);
521        recycle.timezone = Time.TIMEZONE_UTC;
522        return recycle.normalize(true);
523    }
524
525    /**
526     * Scan through a cursor of calendars and check if names are duplicated.
527     * This travels a cursor containing calendar display names and fills in the
528     * provided map with whether or not each name is repeated.
529     *
530     * @param isDuplicateName The map to put the duplicate check results in.
531     * @param cursor The query of calendars to check
532     * @param nameIndex The column of the query that contains the display name
533     */
534    public static void checkForDuplicateNames(
535            Map<String, Boolean> isDuplicateName, Cursor cursor, int nameIndex) {
536        isDuplicateName.clear();
537        cursor.moveToPosition(-1);
538        while (cursor.moveToNext()) {
539            String displayName = cursor.getString(nameIndex);
540            // Set it to true if we've seen this name before, false otherwise
541            if (displayName != null) {
542                isDuplicateName.put(displayName, isDuplicateName.containsKey(displayName));
543            }
544        }
545    }
546
547    /**
548     * Null-safe object comparison
549     *
550     * @param s1
551     * @param s2
552     * @return
553     */
554    public static boolean equals(Object o1, Object o2) {
555        return o1 == null ? o2 == null : o1.equals(o2);
556    }
557
558    public static void setAllowWeekForDetailView(boolean allowWeekView) {
559        mAllowWeekForDetailView  = allowWeekView;
560    }
561
562    public static boolean getAllowWeekForDetailView() {
563        return mAllowWeekForDetailView;
564    }
565
566    public static boolean isMultiPaneConfiguration (Context c) {
567        return (c.getResources().getConfiguration().screenLayout &
568                Configuration.SCREENLAYOUT_SIZE_XLARGE) != 0;
569    }
570
571    public static boolean getConfigBool(Context c, int key) {
572        return c.getResources().getBoolean(key);
573    }
574
575    public static int getDisplayColorFromColor(int color) {
576        float[] hsv = new float[3];
577        Color.colorToHSV(color, hsv);
578        hsv[1] = Math.max(hsv[1] - SATURATION_ADJUST, 0.0f);
579        return Color.HSVToColor(hsv);
580    }
581
582    // A single strand represents one color of events. Events are divided up by
583    // color to make them convenient to draw. The black strand is special in
584    // that it holds conflicting events as well as color settings for allday on
585    // each day.
586    public static class DNAStrand {
587        public float[] points;
588        public int[] allDays; // color for the allday, 0 means no event
589        int position;
590        public int color;
591        int count;
592    }
593
594    // A segment is a single continuous length of time occupied by a single
595    // color. Segments should never span multiple days.
596    private static class DNASegment {
597        int startMinute; // in minutes since the start of the week
598        int endMinute;
599        int color; // Calendar color or black for conflicts
600        int day; // quick reference to the day this segment is on
601    }
602
603    /**
604     * Converts a list of events to a list of segments to draw. Assumes list is
605     * ordered by start time of the events. The function processes events for a
606     * range of days from firstJulianDay to firstJulianDay + dayXs.length - 1.
607     * The algorithm goes over all the events and creates a set of segments
608     * ordered by start time. This list of segments is then converted into a
609     * HashMap of strands which contain the draw points and are organized by
610     * color. The strands can then be drawn by setting the paint color to each
611     * strand's color and calling drawLines on its set of points. The points are
612     * set up using the following parameters.
613     * <ul>
614     * <li>Events between midnight and WORK_DAY_START_MINUTES are compressed
615     * into the first 1/8th of the space between top and bottom.</li>
616     * <li>Events between WORK_DAY_END_MINUTES and the following midnight are
617     * compressed into the last 1/8th of the space between top and bottom</li>
618     * <li>Events between WORK_DAY_START_MINUTES and WORK_DAY_END_MINUTES use
619     * the remaining 3/4ths of the space</li>
620     * <li>All segments drawn will maintain at least minPixels height, except
621     * for conflicts in the first or last 1/8th, which may be smaller</li>
622     * </ul>
623     *
624     * @param firstJulianDay The julian day of the first day of events
625     * @param events A list of events sorted by start time
626     * @param top The lowest y value the dna should be drawn at
627     * @param bottom The highest y value the dna should be drawn at
628     * @param dayXs An array of x values to draw the dna at, one for each day
629     * @param conflictColor the color to use for conflicts
630     * @return
631     */
632    public static HashMap<Integer, DNAStrand> createDNAStrands(int firstJulianDay,
633            ArrayList<Event> events, int top, int bottom, int minPixels, int[] dayXs,
634            Context context) {
635
636        if (!mMinutesLoaded) {
637            if (context == null) {
638                Log.wtf(TAG, "No context and haven't loaded parameters yet! Can't create DNA.");
639            }
640            Resources res = context.getResources();
641            CONFLICT_COLOR = res.getColor(R.color.month_dna_conflict_time_color);
642            WORK_DAY_START_MINUTES = res.getInteger(R.integer.work_start_minutes);
643            WORK_DAY_END_MINUTES = res.getInteger(R.integer.work_end_minutes);
644            WORK_DAY_END_LENGTH = DAY_IN_MINUTES - WORK_DAY_END_MINUTES;
645            WORK_DAY_MINUTES = WORK_DAY_END_MINUTES - WORK_DAY_START_MINUTES;
646            mMinutesLoaded = true;
647        }
648
649        if (events == null || events.isEmpty() || dayXs == null || dayXs.length < 1
650                || bottom - top < 8 || minPixels < 0) {
651            Log.e(TAG,
652                    "Bad values for createDNAStrands! events:" + events + " dayXs:"
653                            + Arrays.toString(dayXs) + " bot-top:" + (bottom - top) + " minPixels:"
654                            + minPixels);
655            return null;
656        }
657
658        LinkedList<DNASegment> segments = new LinkedList<DNASegment>();
659        HashMap<Integer, DNAStrand> strands = new HashMap<Integer, DNAStrand>();
660        // add a black strand by default, other colors will get added in
661        // the loop
662        DNAStrand blackStrand = new DNAStrand();
663        blackStrand.color = CONFLICT_COLOR;
664        strands.put(CONFLICT_COLOR, blackStrand);
665        // the min length is the number of minutes that will occupy
666        // MIN_SEGMENT_PIXELS in the 'work day' time slot. This computes the
667        // minutes/pixel * minpx where the number of pixels are 3/4 the total
668        // dna height: 4*(mins/(px * 3/4))
669        int minMinutes = minPixels * 4 * WORK_DAY_MINUTES / (3 * (bottom - top));
670
671        // There are slightly fewer than half as many pixels in 1/6 the space,
672        // so round to 2.5x for the min minutes in the non-work area
673        int minOtherMinutes = minMinutes * 5 / 2;
674        int lastJulianDay = firstJulianDay + dayXs.length - 1;
675
676        Event event = new Event();
677        // Go through all the events for the week
678        for (Event currEvent : events) {
679            // if this event is outside the weeks range skip it
680            if (currEvent.endDay < firstJulianDay || currEvent.startDay > lastJulianDay) {
681                continue;
682            }
683            if (currEvent.drawAsAllday()) {
684                addAllDayToStrands(currEvent, strands, firstJulianDay, dayXs.length);
685                continue;
686            }
687            // Copy the event over so we can clip its start and end to our range
688            currEvent.copyTo(event);
689            if (event.startDay < firstJulianDay) {
690                event.startDay = firstJulianDay;
691                event.startTime = 0;
692            }
693            // If it starts after the work day make sure the start is at least
694            // minPixels from midnight
695            if (event.startTime > DAY_IN_MINUTES - minOtherMinutes) {
696                event.startTime = DAY_IN_MINUTES - minOtherMinutes;
697            }
698            if (event.endDay > lastJulianDay) {
699                event.endDay = lastJulianDay;
700                event.endTime = DAY_IN_MINUTES - 1;
701            }
702            // If the end time is before the work day make sure it ends at least
703            // minPixels after midnight
704            if (event.endTime < minOtherMinutes) {
705                event.endTime = minOtherMinutes;
706            }
707            // If the start and end are on the same day make sure they are at
708            // least minPixels apart. This only needs to be done for times
709            // outside the work day as the min distance for within the work day
710            // is enforced in the segment code.
711            if (event.startDay == event.endDay &&
712                    event.endTime - event.startTime < minOtherMinutes) {
713                // If it's less than minPixels in an area before the work
714                // day
715                if (event.startTime < WORK_DAY_START_MINUTES) {
716                    // extend the end to the first easy guarantee that it's
717                    // minPixels
718                    event.endTime = Math.min(event.startTime + minOtherMinutes,
719                            WORK_DAY_START_MINUTES + minMinutes);
720                    // if it's in the area after the work day
721                } else if (event.endTime > WORK_DAY_END_MINUTES) {
722                    // First try shifting the end but not past midnight
723                    event.endTime = Math.min(event.endTime + minOtherMinutes, DAY_IN_MINUTES - 1);
724                    // if it's still too small move the start back
725                    if (event.endTime - event.startTime < minOtherMinutes) {
726                        event.startTime = event.endTime - minOtherMinutes;
727                    }
728                }
729            }
730
731            // This handles adding the first segment
732            if (segments.size() == 0) {
733                addNewSegment(segments, event, strands, firstJulianDay, 0, minMinutes);
734                continue;
735            }
736            // Now compare our current start time to the end time of the last
737            // segment in the list
738            DNASegment lastSegment = segments.getLast();
739            int startMinute = (event.startDay - firstJulianDay) * DAY_IN_MINUTES + event.startTime;
740            int endMinute = Math.max((event.endDay - firstJulianDay) * DAY_IN_MINUTES
741                    + event.endTime, startMinute + minMinutes);
742
743            if (startMinute < 0) {
744                startMinute = 0;
745            }
746            if (endMinute >= WEEK_IN_MINUTES) {
747                endMinute = WEEK_IN_MINUTES - 1;
748            }
749            // If we start before the last segment in the list ends we need to
750            // start going through the list as this may conflict with other
751            // events
752            if (startMinute < lastSegment.endMinute) {
753                int i = segments.size();
754                // find the last segment this event intersects with
755                while (--i >= 0 && endMinute < segments.get(i).startMinute);
756
757                DNASegment currSegment;
758                // for each segment this event intersects with
759                for (; i >= 0 && startMinute <= (currSegment = segments.get(i)).endMinute; i--) {
760                    // if the segment is already a conflict ignore it
761                    if (currSegment.color == CONFLICT_COLOR) {
762                        continue;
763                    }
764                    // if the event ends before the segment and wouldn't create
765                    // a segment that is too small split off the right side
766                    if (endMinute < currSegment.endMinute - minMinutes) {
767                        DNASegment rhs = new DNASegment();
768                        rhs.endMinute = currSegment.endMinute;
769                        rhs.color = currSegment.color;
770                        rhs.startMinute = endMinute + 1;
771                        rhs.day = currSegment.day;
772                        currSegment.endMinute = endMinute;
773                        segments.add(i + 1, rhs);
774                        strands.get(rhs.color).count++;
775                        if (DEBUG) {
776                            Log.d(TAG, "Added rhs, curr:" + currSegment.toString() + " i:"
777                                    + segments.get(i).toString());
778                        }
779                    }
780                    // if the event starts after the segment and wouldn't create
781                    // a segment that is too small split off the left side
782                    if (startMinute > currSegment.startMinute + minMinutes) {
783                        DNASegment lhs = new DNASegment();
784                        lhs.startMinute = currSegment.startMinute;
785                        lhs.color = currSegment.color;
786                        lhs.endMinute = startMinute - 1;
787                        lhs.day = currSegment.day;
788                        currSegment.startMinute = startMinute;
789                        // increment i so that we are at the right position when
790                        // referencing the segments to the right and left of the
791                        // current segment.
792                        segments.add(i++, lhs);
793                        strands.get(lhs.color).count++;
794                        if (DEBUG) {
795                            Log.d(TAG, "Added lhs, curr:" + currSegment.toString() + " i:"
796                                    + segments.get(i).toString());
797                        }
798                    }
799                    // if the right side is black merge this with the segment to
800                    // the right if they're on the same day and overlap
801                    if (i + 1 < segments.size()) {
802                        DNASegment rhs = segments.get(i + 1);
803                        if (rhs.color == CONFLICT_COLOR && currSegment.day == rhs.day
804                                && rhs.startMinute <= currSegment.endMinute + 1) {
805                            rhs.startMinute = Math.min(currSegment.startMinute, rhs.startMinute);
806                            segments.remove(currSegment);
807                            strands.get(currSegment.color).count--;
808                            // point at the new current segment
809                            currSegment = rhs;
810                        }
811                    }
812                    // if the left side is black merge this with the segment to
813                    // the left if they're on the same day and overlap
814                    if (i - 1 >= 0) {
815                        DNASegment lhs = segments.get(i - 1);
816                        if (lhs.color == CONFLICT_COLOR && currSegment.day == lhs.day
817                                && lhs.endMinute >= currSegment.startMinute - 1) {
818                            lhs.endMinute = Math.max(currSegment.endMinute, lhs.endMinute);
819                            segments.remove(currSegment);
820                            strands.get(currSegment.color).count--;
821                            // point at the new current segment
822                            currSegment = lhs;
823                            // point i at the new current segment in case new
824                            // code is added
825                            i--;
826                        }
827                    }
828                    // if we're still not black, decrement the count for the
829                    // color being removed, change this to black, and increment
830                    // the black count
831                    if (currSegment.color != CONFLICT_COLOR) {
832                        strands.get(currSegment.color).count--;
833                        currSegment.color = CONFLICT_COLOR;
834                        strands.get(CONFLICT_COLOR).count++;
835                    }
836                }
837
838            }
839            // If this event extends beyond the last segment add a new segment
840            if (endMinute > lastSegment.endMinute) {
841                addNewSegment(segments, event, strands, firstJulianDay, lastSegment.endMinute,
842                        minMinutes);
843            }
844        }
845        weaveDNAStrands(segments, firstJulianDay, strands, top, bottom, dayXs);
846        return strands;
847    }
848
849    // This figures out allDay colors as allDay events are found
850    private static void addAllDayToStrands(Event event, HashMap<Integer, DNAStrand> strands,
851            int firstJulianDay, int numDays) {
852        DNAStrand strand = getOrCreateStrand(strands, CONFLICT_COLOR);
853        // if we haven't initialized the allDay portion create it now
854        if (strand.allDays == null) {
855            strand.allDays = new int[numDays];
856        }
857
858        // For each day this event is on update the color
859        int end = Math.min(event.endDay - firstJulianDay, numDays - 1);
860        for (int i = Math.max(event.startDay - firstJulianDay, 0); i <= end; i++) {
861            if (strand.allDays[i] != 0) {
862                // if this day already had a color, it is now a conflict
863                strand.allDays[i] = CONFLICT_COLOR;
864            } else {
865                // else it's just the color of the event
866                strand.allDays[i] = event.color;
867            }
868        }
869    }
870
871    // This processes all the segments, sorts them by color, and generates a
872    // list of points to draw
873    private static void weaveDNAStrands(LinkedList<DNASegment> segments, int firstJulianDay,
874            HashMap<Integer, DNAStrand> strands, int top, int bottom, int[] dayXs) {
875        // First, get rid of any colors that ended up with no segments
876        Iterator<DNAStrand> strandIterator = strands.values().iterator();
877        while (strandIterator.hasNext()) {
878            DNAStrand strand = strandIterator.next();
879            if (strand.count < 1 && strand.allDays == null) {
880                strandIterator.remove();
881                continue;
882            }
883            strand.points = new float[strand.count * 4];
884            strand.position = 0;
885        }
886        // Go through each segment and compute its points
887        for (DNASegment segment : segments) {
888            // Add the points to the strand of that color
889            DNAStrand strand = strands.get(segment.color);
890            int dayIndex = segment.day - firstJulianDay;
891            int dayStartMinute = segment.startMinute % DAY_IN_MINUTES;
892            int dayEndMinute = segment.endMinute % DAY_IN_MINUTES;
893            int height = bottom - top;
894            int workDayHeight = height * 3 / 4;
895            int remainderHeight = (height - workDayHeight) / 2;
896
897            int x = dayXs[dayIndex];
898            int y0 = 0;
899            int y1 = 0;
900
901            y0 = top + getPixelOffsetFromMinutes(dayStartMinute, workDayHeight, remainderHeight);
902            y1 = top + getPixelOffsetFromMinutes(dayEndMinute, workDayHeight, remainderHeight);
903            if (DEBUG) {
904                Log.d(TAG, "Adding " + Integer.toHexString(segment.color) + " at x,y0,y1: " + x
905                        + " " + y0 + " " + y1 + " for " + dayStartMinute + " " + dayEndMinute);
906            }
907            strand.points[strand.position++] = x;
908            strand.points[strand.position++] = y0;
909            strand.points[strand.position++] = x;
910            strand.points[strand.position++] = y1;
911        }
912    }
913
914    /**
915     * Compute a pixel offset from the top for a given minute from the work day
916     * height and the height of the top area.
917     */
918    private static int getPixelOffsetFromMinutes(int minute, int workDayHeight,
919            int remainderHeight) {
920        int y;
921        if (minute < WORK_DAY_START_MINUTES) {
922            y = minute * remainderHeight / WORK_DAY_START_MINUTES;
923        } else if (minute < WORK_DAY_END_MINUTES) {
924            y = remainderHeight + (minute - WORK_DAY_START_MINUTES) * workDayHeight
925                    / WORK_DAY_MINUTES;
926        } else {
927            y = remainderHeight + workDayHeight + (minute - WORK_DAY_END_MINUTES) * remainderHeight
928                    / WORK_DAY_END_LENGTH;
929        }
930        return y;
931    }
932
933    /**
934     * Add a new segment based on the event provided. This will handle splitting
935     * segments across day boundaries and ensures a minimum size for segments.
936     */
937    private static void addNewSegment(LinkedList<DNASegment> segments, Event event,
938            HashMap<Integer, DNAStrand> strands, int firstJulianDay, int minStart, int minMinutes) {
939        if (event.startDay > event.endDay) {
940            Log.wtf(TAG, "Event starts after it ends: " + event.toString());
941        }
942        // If this is a multiday event split it up by day
943        if (event.startDay != event.endDay) {
944            Event lhs = new Event();
945            lhs.color = event.color;
946            lhs.startDay = event.startDay;
947            // the first day we want the start time to be the actual start time
948            lhs.startTime = event.startTime;
949            lhs.endDay = lhs.startDay;
950            lhs.endTime = DAY_IN_MINUTES - 1;
951            // Nearly recursive iteration!
952            while (lhs.startDay != event.endDay) {
953                addNewSegment(segments, lhs, strands, firstJulianDay, minStart, minMinutes);
954                // The days in between are all day, even though that shouldn't
955                // actually happen due to the allday filtering
956                lhs.startDay++;
957                lhs.endDay = lhs.startDay;
958                lhs.startTime = 0;
959                minStart = 0;
960            }
961            // The last day we want the end time to be the actual end time
962            lhs.endTime = event.endTime;
963            event = lhs;
964        }
965        // Create the new segment and compute its fields
966        DNASegment segment = new DNASegment();
967        int dayOffset = (event.startDay - firstJulianDay) * DAY_IN_MINUTES;
968        int endOfDay = dayOffset + DAY_IN_MINUTES - 1;
969        // clip the start if needed
970        segment.startMinute = Math.max(dayOffset + event.startTime, minStart);
971        // and extend the end if it's too small, but not beyond the end of the
972        // day
973        int minEnd = Math.min(segment.startMinute + minMinutes, endOfDay);
974        segment.endMinute = Math.max(dayOffset + event.endTime, minEnd);
975        if (segment.endMinute > endOfDay) {
976            segment.endMinute = endOfDay;
977        }
978
979        segment.color = event.color;
980        segment.day = event.startDay;
981        segments.add(segment);
982        // increment the count for the correct color or add a new strand if we
983        // don't have that color yet
984        DNAStrand strand = getOrCreateStrand(strands, segment.color);
985        strand.count++;
986    }
987
988    /**
989     * Try to get a strand of the given color. Create it if it doesn't exist.
990     */
991    private static DNAStrand getOrCreateStrand(HashMap<Integer, DNAStrand> strands, int color) {
992        DNAStrand strand = strands.get(color);
993        if (strand == null) {
994            strand = new DNAStrand();
995            strand.color = color;
996            strand.count = 0;
997            strands.put(strand.color, strand);
998        }
999        return strand;
1000    }
1001
1002    /**
1003     * Sends an intent to launch the top level Calendar view.
1004     *
1005     * @param context
1006     */
1007    public static void returnToCalendarHome(Context context) {
1008        Intent launchIntent = new Intent(context, AllInOneActivity.class);
1009        launchIntent.setAction(Intent.ACTION_VIEW);
1010        launchIntent.setData(Uri.parse("content://com.android.calendar/time"));
1011        launchIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
1012        context.startActivity(launchIntent);
1013    }
1014
1015    /**
1016     * This sets up a search view to use Calendar's search suggestions provider
1017     * and to allow refining the search.
1018     *
1019     * @param view The {@link SearchView} to set up
1020     * @param act The activity using the view
1021     */
1022    public static void setUpSearchView(SearchView view, Activity act) {
1023        SearchManager searchManager = (SearchManager) act.getSystemService(Context.SEARCH_SERVICE);
1024        view.setSearchableInfo(searchManager.getSearchableInfo(act.getComponentName()));
1025        view.setQueryRefinementEnabled(true);
1026    }
1027
1028    /**
1029     * Given a context and a time in millis since unix epoch figures out the
1030     * correct week of the year for that time.
1031     *
1032     * @param millisSinceEpoch
1033     * @return
1034     */
1035    public static int getWeekNumberFromTime(long millisSinceEpoch, Context context) {
1036        Time weekTime = new Time(getTimeZone(context, null));
1037        weekTime.set(millisSinceEpoch);
1038        weekTime.normalize(true);
1039        int firstDayOfWeek = getFirstDayOfWeek(context);
1040        // if the date is on Saturday or Sunday and the start of the week
1041        // isn't Monday we may need to shift the date to be in the correct
1042        // week
1043        if (weekTime.weekDay == Time.SUNDAY
1044                && (firstDayOfWeek == Time.SUNDAY || firstDayOfWeek == Time.SATURDAY)) {
1045            weekTime.monthDay++;
1046            weekTime.normalize(true);
1047        } else if (weekTime.weekDay == Time.SATURDAY && firstDayOfWeek == Time.SATURDAY) {
1048            weekTime.monthDay += 2;
1049            weekTime.normalize(true);
1050        }
1051        return weekTime.getWeekNumber();
1052    }
1053
1054    /**
1055     * Formats a day of the week string. This is either just the name of the day
1056     * or a combination of yesterday/today/tomorrow and the day of the week.
1057     *
1058     * @param julianDay The julian day to get the string for
1059     * @param todayJulianDay The julian day for today's date
1060     * @param millis A utc millis since epoch time that falls on julian day
1061     * @param context The calling context, used to get the timezone and do the
1062     *            formatting
1063     * @return
1064     */
1065    public static String getDayOfWeekString(int julianDay, int todayJulianDay, long millis,
1066            Context context) {
1067        String tz = getTimeZone(context, null);
1068        int flags = DateUtils.FORMAT_SHOW_WEEKDAY;
1069        String dayViewText;
1070        if (julianDay == todayJulianDay) {
1071            dayViewText = context.getString(R.string.agenda_today,
1072                    mTZUtils.formatDateRange(context, millis, millis, flags).toString());
1073        } else if (julianDay == todayJulianDay - 1) {
1074            dayViewText = context.getString(R.string.agenda_yesterday,
1075                    mTZUtils.formatDateRange(context, millis, millis, flags).toString());
1076        } else if (julianDay == todayJulianDay + 1) {
1077            dayViewText = context.getString(R.string.agenda_tomorrow,
1078                    mTZUtils.formatDateRange(context, millis, millis, flags).toString());
1079        } else {
1080            dayViewText = mTZUtils.formatDateRange(context, millis, millis, flags).toString();
1081        }
1082        dayViewText = dayViewText.toUpperCase();
1083        return dayViewText;
1084    }
1085}
1086