Utils.java revision dacfb663d63253880090151fde87bd9da9a59347
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 android.app.Activity; 22import android.app.SearchManager; 23import android.content.BroadcastReceiver; 24import android.content.Context; 25import android.content.Intent; 26import android.content.IntentFilter; 27import android.content.SharedPreferences; 28import android.content.pm.PackageManager; 29import android.content.res.Resources; 30import android.database.Cursor; 31import android.database.MatrixCursor; 32import android.graphics.Color; 33import android.graphics.drawable.Drawable; 34import android.graphics.drawable.LayerDrawable; 35import android.net.Uri; 36import android.os.Build; 37import android.os.Bundle; 38import android.os.Handler; 39import android.text.TextUtils; 40import android.text.format.DateFormat; 41import android.text.format.DateUtils; 42import android.text.format.Time; 43import android.util.Log; 44import android.widget.SearchView; 45 46import com.android.calendar.CalendarController.ViewType; 47import com.android.calendar.CalendarUtils.TimeZoneUtils; 48 49import java.util.ArrayList; 50import java.util.Arrays; 51import java.util.Calendar; 52import java.util.Formatter; 53import java.util.HashMap; 54import java.util.Iterator; 55import java.util.LinkedHashSet; 56import java.util.LinkedList; 57import java.util.List; 58import java.util.Locale; 59import java.util.Map; 60import java.util.Set; 61import java.util.TimeZone; 62 63public class Utils { 64 private static final boolean DEBUG = false; 65 private static final String TAG = "CalUtils"; 66 67 // Set to 0 until we have UI to perform undo 68 public static final long UNDO_DELAY = 0; 69 70 // For recurring events which instances of the series are being modified 71 public static final int MODIFY_UNINITIALIZED = 0; 72 public static final int MODIFY_SELECTED = 1; 73 public static final int MODIFY_ALL_FOLLOWING = 2; 74 public static final int MODIFY_ALL = 3; 75 76 // When the edit event view finishes it passes back the appropriate exit 77 // code. 78 public static final int DONE_REVERT = 1 << 0; 79 public static final int DONE_SAVE = 1 << 1; 80 public static final int DONE_DELETE = 1 << 2; 81 // And should re run with DONE_EXIT if it should also leave the view, just 82 // exiting is identical to reverting 83 public static final int DONE_EXIT = 1 << 0; 84 85 public static final String OPEN_EMAIL_MARKER = " <"; 86 public static final String CLOSE_EMAIL_MARKER = ">"; 87 88 public static final String INTENT_KEY_DETAIL_VIEW = "DETAIL_VIEW"; 89 public static final String INTENT_KEY_VIEW_TYPE = "VIEW"; 90 public static final String INTENT_VALUE_VIEW_TYPE_DAY = "DAY"; 91 public static final String INTENT_KEY_HOME = "KEY_HOME"; 92 93 public static final int MONDAY_BEFORE_JULIAN_EPOCH = Time.EPOCH_JULIAN_DAY - 3; 94 public static final int DECLINED_EVENT_ALPHA = 0x66; 95 public static final int DECLINED_EVENT_TEXT_ALPHA = 0xC0; 96 97 private static final float SATURATION_ADJUST = 1.3f; 98 private static final float INTENSITY_ADJUST = 0.8f; 99 100 // Defines used by the DNA generation code 101 static final int DAY_IN_MINUTES = 60 * 24; 102 static final int WEEK_IN_MINUTES = DAY_IN_MINUTES * 7; 103 // The work day is being counted as 6am to 8pm 104 static int WORK_DAY_MINUTES = 14 * 60; 105 static int WORK_DAY_START_MINUTES = 6 * 60; 106 static int WORK_DAY_END_MINUTES = 20 * 60; 107 static int WORK_DAY_END_LENGTH = (24 * 60) - WORK_DAY_END_MINUTES; 108 static int CONFLICT_COLOR = 0xFF000000; 109 static boolean mMinutesLoaded = false; 110 111 // The name of the shared preferences file. This name must be maintained for 112 // historical 113 // reasons, as it's what PreferenceManager assigned the first time the file 114 // was created. 115 static final String SHARED_PREFS_NAME = "com.android.calendar_preferences"; 116 117 public static final String KEY_QUICK_RESPONSES = "preferences_quick_responses"; 118 119 public static final String APPWIDGET_DATA_TYPE = "vnd.android.data/update"; 120 121 static final String MACHINE_GENERATED_ADDRESS = "calendar.google.com"; 122 123 private static final TimeZoneUtils mTZUtils = new TimeZoneUtils(SHARED_PREFS_NAME); 124 private static boolean mAllowWeekForDetailView = false; 125 private static long mTardis = 0; 126 private static String sVersion = null; 127 128 /** 129 * Returns whether the SDK is the Jellybean release or later. 130 */ 131 public static boolean isJellybeanOrLater() { 132 return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; 133 } 134 135 public static int getViewTypeFromIntentAndSharedPref(Activity activity) { 136 Intent intent = activity.getIntent(); 137 Bundle extras = intent.getExtras(); 138 SharedPreferences prefs = GeneralPreferences.getSharedPreferences(activity); 139 140 if (TextUtils.equals(intent.getAction(), Intent.ACTION_EDIT)) { 141 return ViewType.EDIT; 142 } 143 if (extras != null) { 144 if (extras.getBoolean(INTENT_KEY_DETAIL_VIEW, false)) { 145 // This is the "detail" view which is either agenda or day view 146 return prefs.getInt(GeneralPreferences.KEY_DETAILED_VIEW, 147 GeneralPreferences.DEFAULT_DETAILED_VIEW); 148 } else if (INTENT_VALUE_VIEW_TYPE_DAY.equals(extras.getString(INTENT_KEY_VIEW_TYPE))) { 149 // Not sure who uses this. This logic came from LaunchActivity 150 return ViewType.DAY; 151 } 152 } 153 154 // Default to the last view 155 return prefs.getInt( 156 GeneralPreferences.KEY_START_VIEW, GeneralPreferences.DEFAULT_START_VIEW); 157 } 158 159 /** 160 * Gets the intent action for telling the widget to update. 161 */ 162 public static String getWidgetUpdateAction(Context context) { 163 return context.getPackageName() + ".APPWIDGET_UPDATE"; 164 } 165 166 /** 167 * Gets the intent action for telling the widget to update. 168 */ 169 public static String getWidgetScheduledUpdateAction(Context context) { 170 return context.getPackageName() + ".APPWIDGET_SCHEDULED_UPDATE"; 171 } 172 173 /** 174 * Gets the intent action for telling the widget to update. 175 */ 176 public static String getSearchAuthority(Context context) { 177 return context.getPackageName() + ".CalendarRecentSuggestionsProvider"; 178 } 179 180 /** 181 * Writes a new home time zone to the db. Updates the home time zone in the 182 * db asynchronously and updates the local cache. Sending a time zone of 183 * **tbd** will cause it to be set to the device's time zone. null or empty 184 * tz will be ignored. 185 * 186 * @param context The calling activity 187 * @param timeZone The time zone to set Calendar to, or **tbd** 188 */ 189 public static void setTimeZone(Context context, String timeZone) { 190 mTZUtils.setTimeZone(context, timeZone); 191 } 192 193 /** 194 * Gets the time zone that Calendar should be displayed in This is a helper 195 * method to get the appropriate time zone for Calendar. If this is the 196 * first time this method has been called it will initiate an asynchronous 197 * query to verify that the data in preferences is correct. The callback 198 * supplied will only be called if this query returns a value other than 199 * what is stored in preferences and should cause the calling activity to 200 * refresh anything that depends on calling this method. 201 * 202 * @param context The calling activity 203 * @param callback The runnable that should execute if a query returns new 204 * values 205 * @return The string value representing the time zone Calendar should 206 * display 207 */ 208 public static String getTimeZone(Context context, Runnable callback) { 209 return mTZUtils.getTimeZone(context, callback); 210 } 211 212 /** 213 * Formats a date or a time range according to the local conventions. 214 * 215 * @param context the context is required only if the time is shown 216 * @param startMillis the start time in UTC milliseconds 217 * @param endMillis the end time in UTC milliseconds 218 * @param flags a bit mask of options See {@link DateUtils#formatDateRange(Context, Formatter, 219 * long, long, int, String) formatDateRange} 220 * @return a string containing the formatted date/time range. 221 */ 222 public static String formatDateRange( 223 Context context, long startMillis, long endMillis, int flags) { 224 return mTZUtils.formatDateRange(context, startMillis, endMillis, flags); 225 } 226 227 public static String[] getSharedPreference(Context context, String key, String[] defaultValue) { 228 SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); 229 Set<String> ss = prefs.getStringSet(key, null); 230 if (ss != null) { 231 String strings[] = new String[ss.size()]; 232 return ss.toArray(strings); 233 } 234 return defaultValue; 235 } 236 237 public static String getSharedPreference(Context context, String key, String defaultValue) { 238 SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); 239 return prefs.getString(key, defaultValue); 240 } 241 242 public static int getSharedPreference(Context context, String key, int defaultValue) { 243 SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); 244 return prefs.getInt(key, defaultValue); 245 } 246 247 public static boolean getSharedPreference(Context context, String key, boolean defaultValue) { 248 SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); 249 return prefs.getBoolean(key, defaultValue); 250 } 251 252 /** 253 * Asynchronously sets the preference with the given key to the given value 254 * 255 * @param context the context to use to get preferences from 256 * @param key the key of the preference to set 257 * @param value the value to set 258 */ 259 public static void setSharedPreference(Context context, String key, String value) { 260 SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); 261 prefs.edit().putString(key, value).apply(); 262 } 263 264 public static void setSharedPreference(Context context, String key, String[] values) { 265 SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); 266 LinkedHashSet<String> set = new LinkedHashSet<String>(); 267 for (int i = 0; i < values.length; i++) { 268 set.add(values[i]); 269 } 270 prefs.edit().putStringSet(key, set).apply(); 271 } 272 273 protected static void tardis() { 274 mTardis = System.currentTimeMillis(); 275 } 276 277 protected static long getTardis() { 278 return mTardis; 279 } 280 281 static void setSharedPreference(Context context, String key, boolean value) { 282 SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); 283 SharedPreferences.Editor editor = prefs.edit(); 284 editor.putBoolean(key, value); 285 editor.apply(); 286 } 287 288 static void setSharedPreference(Context context, String key, int value) { 289 SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); 290 SharedPreferences.Editor editor = prefs.edit(); 291 editor.putInt(key, value); 292 editor.apply(); 293 } 294 295 /** 296 * Save default agenda/day/week/month view for next time 297 * 298 * @param context 299 * @param viewId {@link CalendarController.ViewType} 300 */ 301 static void setDefaultView(Context context, int viewId) { 302 SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); 303 SharedPreferences.Editor editor = prefs.edit(); 304 305 boolean validDetailView = false; 306 if (mAllowWeekForDetailView && viewId == CalendarController.ViewType.WEEK) { 307 validDetailView = true; 308 } else { 309 validDetailView = viewId == CalendarController.ViewType.AGENDA 310 || viewId == CalendarController.ViewType.DAY; 311 } 312 313 if (validDetailView) { 314 // Record the detail start view 315 editor.putInt(GeneralPreferences.KEY_DETAILED_VIEW, viewId); 316 } 317 318 // Record the (new) start view 319 editor.putInt(GeneralPreferences.KEY_START_VIEW, viewId); 320 editor.apply(); 321 } 322 323 public static MatrixCursor matrixCursorFromCursor(Cursor cursor) { 324 String[] columnNames = cursor.getColumnNames(); 325 if (columnNames == null) { 326 columnNames = new String[] {}; 327 } 328 MatrixCursor newCursor = new MatrixCursor(columnNames); 329 int numColumns = cursor.getColumnCount(); 330 String data[] = new String[numColumns]; 331 cursor.moveToPosition(-1); 332 while (cursor.moveToNext()) { 333 for (int i = 0; i < numColumns; i++) { 334 data[i] = cursor.getString(i); 335 } 336 newCursor.addRow(data); 337 } 338 return newCursor; 339 } 340 341 /** 342 * Compares two cursors to see if they contain the same data. 343 * 344 * @return Returns true of the cursors contain the same data and are not 345 * null, false otherwise 346 */ 347 public static boolean compareCursors(Cursor c1, Cursor c2) { 348 if (c1 == null || c2 == null) { 349 return false; 350 } 351 352 int numColumns = c1.getColumnCount(); 353 if (numColumns != c2.getColumnCount()) { 354 return false; 355 } 356 357 if (c1.getCount() != c2.getCount()) { 358 return false; 359 } 360 361 c1.moveToPosition(-1); 362 c2.moveToPosition(-1); 363 while (c1.moveToNext() && c2.moveToNext()) { 364 for (int i = 0; i < numColumns; i++) { 365 if (!TextUtils.equals(c1.getString(i), c2.getString(i))) { 366 return false; 367 } 368 } 369 } 370 371 return true; 372 } 373 374 /** 375 * If the given intent specifies a time (in milliseconds since the epoch), 376 * then that time is returned. Otherwise, the current time is returned. 377 */ 378 public static final long timeFromIntentInMillis(Intent intent) { 379 // If the time was specified, then use that. Otherwise, use the current 380 // time. 381 Uri data = intent.getData(); 382 long millis = intent.getLongExtra(EXTRA_EVENT_BEGIN_TIME, -1); 383 if (millis == -1 && data != null && data.isHierarchical()) { 384 List<String> path = data.getPathSegments(); 385 if (path.size() == 2 && path.get(0).equals("time")) { 386 try { 387 millis = Long.valueOf(data.getLastPathSegment()); 388 } catch (NumberFormatException e) { 389 Log.i("Calendar", "timeFromIntentInMillis: Data existed but no valid time " 390 + "found. Using current time."); 391 } 392 } 393 } 394 if (millis <= 0) { 395 millis = System.currentTimeMillis(); 396 } 397 return millis; 398 } 399 400 /** 401 * Formats the given Time object so that it gives the month and year (for 402 * example, "September 2007"). 403 * 404 * @param time the time to format 405 * @return the string containing the weekday and the date 406 */ 407 public static String formatMonthYear(Context context, Time time) { 408 int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY 409 | DateUtils.FORMAT_SHOW_YEAR; 410 long millis = time.toMillis(true); 411 return formatDateRange(context, millis, millis, flags); 412 } 413 414 /** 415 * Returns a list joined together by the provided delimiter, for example, 416 * ["a", "b", "c"] could be joined into "a,b,c" 417 * 418 * @param things the things to join together 419 * @param delim the delimiter to use 420 * @return a string contained the things joined together 421 */ 422 public static String join(List<?> things, String delim) { 423 StringBuilder builder = new StringBuilder(); 424 boolean first = true; 425 for (Object thing : things) { 426 if (first) { 427 first = false; 428 } else { 429 builder.append(delim); 430 } 431 builder.append(thing.toString()); 432 } 433 return builder.toString(); 434 } 435 436 /** 437 * Returns the week since {@link Time#EPOCH_JULIAN_DAY} (Jan 1, 1970) 438 * adjusted for first day of week. 439 * 440 * This takes a julian day and the week start day and calculates which 441 * week since {@link Time#EPOCH_JULIAN_DAY} that day occurs in, starting 442 * at 0. *Do not* use this to compute the ISO week number for the year. 443 * 444 * @param julianDay The julian day to calculate the week number for 445 * @param firstDayOfWeek Which week day is the first day of the week, 446 * see {@link Time#SUNDAY} 447 * @return Weeks since the epoch 448 */ 449 public static int getWeeksSinceEpochFromJulianDay(int julianDay, int firstDayOfWeek) { 450 int diff = Time.THURSDAY - firstDayOfWeek; 451 if (diff < 0) { 452 diff += 7; 453 } 454 int refDay = Time.EPOCH_JULIAN_DAY - diff; 455 return (julianDay - refDay) / 7; 456 } 457 458 /** 459 * Takes a number of weeks since the epoch and calculates the Julian day of 460 * the Monday for that week. 461 * 462 * This assumes that the week containing the {@link Time#EPOCH_JULIAN_DAY} 463 * is considered week 0. It returns the Julian day for the Monday 464 * {@code week} weeks after the Monday of the week containing the epoch. 465 * 466 * @param week Number of weeks since the epoch 467 * @return The julian day for the Monday of the given week since the epoch 468 */ 469 public static int getJulianMondayFromWeeksSinceEpoch(int week) { 470 return MONDAY_BEFORE_JULIAN_EPOCH + week * 7; 471 } 472 473 /** 474 * Get first day of week as android.text.format.Time constant. 475 * 476 * @return the first day of week in android.text.format.Time 477 */ 478 public static int getFirstDayOfWeek(Context context) { 479 SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); 480 String pref = prefs.getString( 481 GeneralPreferences.KEY_WEEK_START_DAY, GeneralPreferences.WEEK_START_DEFAULT); 482 483 int startDay; 484 if (GeneralPreferences.WEEK_START_DEFAULT.equals(pref)) { 485 startDay = Calendar.getInstance().getFirstDayOfWeek(); 486 } else { 487 startDay = Integer.parseInt(pref); 488 } 489 490 if (startDay == Calendar.SATURDAY) { 491 return Time.SATURDAY; 492 } else if (startDay == Calendar.MONDAY) { 493 return Time.MONDAY; 494 } else { 495 return Time.SUNDAY; 496 } 497 } 498 499 /** 500 * @return true when week number should be shown. 501 */ 502 public static boolean getShowWeekNumber(Context context) { 503 final SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); 504 return prefs.getBoolean( 505 GeneralPreferences.KEY_SHOW_WEEK_NUM, GeneralPreferences.DEFAULT_SHOW_WEEK_NUM); 506 } 507 508 /** 509 * @return true when declined events should be hidden. 510 */ 511 public static boolean getHideDeclinedEvents(Context context) { 512 final SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); 513 return prefs.getBoolean(GeneralPreferences.KEY_HIDE_DECLINED, false); 514 } 515 516 public static int getDaysPerWeek(Context context) { 517 final SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); 518 return prefs.getInt(GeneralPreferences.KEY_DAYS_PER_WEEK, 7); 519 } 520 521 /** 522 * Determine whether the column position is Saturday or not. 523 * 524 * @param column the column position 525 * @param firstDayOfWeek the first day of week in android.text.format.Time 526 * @return true if the column is Saturday position 527 */ 528 public static boolean isSaturday(int column, int firstDayOfWeek) { 529 return (firstDayOfWeek == Time.SUNDAY && column == 6) 530 || (firstDayOfWeek == Time.MONDAY && column == 5) 531 || (firstDayOfWeek == Time.SATURDAY && column == 0); 532 } 533 534 /** 535 * Determine whether the column position is Sunday or not. 536 * 537 * @param column the column position 538 * @param firstDayOfWeek the first day of week in android.text.format.Time 539 * @return true if the column is Sunday position 540 */ 541 public static boolean isSunday(int column, int firstDayOfWeek) { 542 return (firstDayOfWeek == Time.SUNDAY && column == 0) 543 || (firstDayOfWeek == Time.MONDAY && column == 6) 544 || (firstDayOfWeek == Time.SATURDAY && column == 1); 545 } 546 547 /** 548 * Convert given UTC time into current local time. This assumes it is for an 549 * allday event and will adjust the time to be on a midnight boundary. 550 * 551 * @param recycle Time object to recycle, otherwise null. 552 * @param utcTime Time to convert, in UTC. 553 * @param tz The time zone to convert this time to. 554 */ 555 public static long convertAlldayUtcToLocal(Time recycle, long utcTime, String tz) { 556 if (recycle == null) { 557 recycle = new Time(); 558 } 559 recycle.timezone = Time.TIMEZONE_UTC; 560 recycle.set(utcTime); 561 recycle.timezone = tz; 562 return recycle.normalize(true); 563 } 564 565 public static long convertAlldayLocalToUTC(Time recycle, long localTime, String tz) { 566 if (recycle == null) { 567 recycle = new Time(); 568 } 569 recycle.timezone = tz; 570 recycle.set(localTime); 571 recycle.timezone = Time.TIMEZONE_UTC; 572 return recycle.normalize(true); 573 } 574 575 /** 576 * Finds and returns the next midnight after "theTime" in milliseconds UTC 577 * 578 * @param recycle - Time object to recycle, otherwise null. 579 * @param theTime - Time used for calculations (in UTC) 580 * @param tz The time zone to convert this time to. 581 */ 582 public static long getNextMidnight(Time recycle, long theTime, String tz) { 583 if (recycle == null) { 584 recycle = new Time(); 585 } 586 recycle.timezone = tz; 587 recycle.set(theTime); 588 recycle.monthDay ++; 589 recycle.hour = 0; 590 recycle.minute = 0; 591 recycle.second = 0; 592 return recycle.normalize(true); 593 } 594 595 /** 596 * Scan through a cursor of calendars and check if names are duplicated. 597 * This travels a cursor containing calendar display names and fills in the 598 * provided map with whether or not each name is repeated. 599 * 600 * @param isDuplicateName The map to put the duplicate check results in. 601 * @param cursor The query of calendars to check 602 * @param nameIndex The column of the query that contains the display name 603 */ 604 public static void checkForDuplicateNames( 605 Map<String, Boolean> isDuplicateName, Cursor cursor, int nameIndex) { 606 isDuplicateName.clear(); 607 cursor.moveToPosition(-1); 608 while (cursor.moveToNext()) { 609 String displayName = cursor.getString(nameIndex); 610 // Set it to true if we've seen this name before, false otherwise 611 if (displayName != null) { 612 isDuplicateName.put(displayName, isDuplicateName.containsKey(displayName)); 613 } 614 } 615 } 616 617 /** 618 * Null-safe object comparison 619 * 620 * @param s1 621 * @param s2 622 * @return 623 */ 624 public static boolean equals(Object o1, Object o2) { 625 return o1 == null ? o2 == null : o1.equals(o2); 626 } 627 628 public static void setAllowWeekForDetailView(boolean allowWeekView) { 629 mAllowWeekForDetailView = allowWeekView; 630 } 631 632 public static boolean getAllowWeekForDetailView() { 633 return mAllowWeekForDetailView; 634 } 635 636 public static boolean getConfigBool(Context c, int key) { 637 return c.getResources().getBoolean(key); 638 } 639 640 public static int getDisplayColorFromColor(int color) { 641 if (!isJellybeanOrLater()) { 642 return color; 643 } 644 645 float[] hsv = new float[3]; 646 Color.colorToHSV(color, hsv); 647 hsv[1] = Math.min(hsv[1] * SATURATION_ADJUST, 1.0f); 648 hsv[2] = hsv[2] * INTENSITY_ADJUST; 649 return Color.HSVToColor(hsv); 650 } 651 652 // This takes a color and computes what it would look like blended with 653 // white. The result is the color that should be used for declined events. 654 public static int getDeclinedColorFromColor(int color) { 655 int bg = 0xffffffff; 656 int a = DECLINED_EVENT_ALPHA; 657 int r = (((color & 0x00ff0000) * a) + ((bg & 0x00ff0000) * (0xff - a))) & 0xff000000; 658 int g = (((color & 0x0000ff00) * a) + ((bg & 0x0000ff00) * (0xff - a))) & 0x00ff0000; 659 int b = (((color & 0x000000ff) * a) + ((bg & 0x000000ff) * (0xff - a))) & 0x0000ff00; 660 return (0xff000000) | ((r | g | b) >> 8); 661 } 662 663 // A single strand represents one color of events. Events are divided up by 664 // color to make them convenient to draw. The black strand is special in 665 // that it holds conflicting events as well as color settings for allday on 666 // each day. 667 public static class DNAStrand { 668 public float[] points; 669 public int[] allDays; // color for the allday, 0 means no event 670 int position; 671 public int color; 672 int count; 673 } 674 675 // A segment is a single continuous length of time occupied by a single 676 // color. Segments should never span multiple days. 677 private static class DNASegment { 678 int startMinute; // in minutes since the start of the week 679 int endMinute; 680 int color; // Calendar color or black for conflicts 681 int day; // quick reference to the day this segment is on 682 } 683 684 /** 685 * Converts a list of events to a list of segments to draw. Assumes list is 686 * ordered by start time of the events. The function processes events for a 687 * range of days from firstJulianDay to firstJulianDay + dayXs.length - 1. 688 * The algorithm goes over all the events and creates a set of segments 689 * ordered by start time. This list of segments is then converted into a 690 * HashMap of strands which contain the draw points and are organized by 691 * color. The strands can then be drawn by setting the paint color to each 692 * strand's color and calling drawLines on its set of points. The points are 693 * set up using the following parameters. 694 * <ul> 695 * <li>Events between midnight and WORK_DAY_START_MINUTES are compressed 696 * into the first 1/8th of the space between top and bottom.</li> 697 * <li>Events between WORK_DAY_END_MINUTES and the following midnight are 698 * compressed into the last 1/8th of the space between top and bottom</li> 699 * <li>Events between WORK_DAY_START_MINUTES and WORK_DAY_END_MINUTES use 700 * the remaining 3/4ths of the space</li> 701 * <li>All segments drawn will maintain at least minPixels height, except 702 * for conflicts in the first or last 1/8th, which may be smaller</li> 703 * </ul> 704 * 705 * @param firstJulianDay The julian day of the first day of events 706 * @param events A list of events sorted by start time 707 * @param top The lowest y value the dna should be drawn at 708 * @param bottom The highest y value the dna should be drawn at 709 * @param dayXs An array of x values to draw the dna at, one for each day 710 * @param conflictColor the color to use for conflicts 711 * @return 712 */ 713 public static HashMap<Integer, DNAStrand> createDNAStrands(int firstJulianDay, 714 ArrayList<Event> events, int top, int bottom, int minPixels, int[] dayXs, 715 Context context) { 716 717 if (!mMinutesLoaded) { 718 if (context == null) { 719 Log.wtf(TAG, "No context and haven't loaded parameters yet! Can't create DNA."); 720 } 721 Resources res = context.getResources(); 722 CONFLICT_COLOR = res.getColor(R.color.month_dna_conflict_time_color); 723 WORK_DAY_START_MINUTES = res.getInteger(R.integer.work_start_minutes); 724 WORK_DAY_END_MINUTES = res.getInteger(R.integer.work_end_minutes); 725 WORK_DAY_END_LENGTH = DAY_IN_MINUTES - WORK_DAY_END_MINUTES; 726 WORK_DAY_MINUTES = WORK_DAY_END_MINUTES - WORK_DAY_START_MINUTES; 727 mMinutesLoaded = true; 728 } 729 730 if (events == null || events.isEmpty() || dayXs == null || dayXs.length < 1 731 || bottom - top < 8 || minPixels < 0) { 732 Log.e(TAG, 733 "Bad values for createDNAStrands! events:" + events + " dayXs:" 734 + Arrays.toString(dayXs) + " bot-top:" + (bottom - top) + " minPixels:" 735 + minPixels); 736 return null; 737 } 738 739 LinkedList<DNASegment> segments = new LinkedList<DNASegment>(); 740 HashMap<Integer, DNAStrand> strands = new HashMap<Integer, DNAStrand>(); 741 // add a black strand by default, other colors will get added in 742 // the loop 743 DNAStrand blackStrand = new DNAStrand(); 744 blackStrand.color = CONFLICT_COLOR; 745 strands.put(CONFLICT_COLOR, blackStrand); 746 // the min length is the number of minutes that will occupy 747 // MIN_SEGMENT_PIXELS in the 'work day' time slot. This computes the 748 // minutes/pixel * minpx where the number of pixels are 3/4 the total 749 // dna height: 4*(mins/(px * 3/4)) 750 int minMinutes = minPixels * 4 * WORK_DAY_MINUTES / (3 * (bottom - top)); 751 752 // There are slightly fewer than half as many pixels in 1/6 the space, 753 // so round to 2.5x for the min minutes in the non-work area 754 int minOtherMinutes = minMinutes * 5 / 2; 755 int lastJulianDay = firstJulianDay + dayXs.length - 1; 756 757 Event event = new Event(); 758 // Go through all the events for the week 759 for (Event currEvent : events) { 760 // if this event is outside the weeks range skip it 761 if (currEvent.endDay < firstJulianDay || currEvent.startDay > lastJulianDay) { 762 continue; 763 } 764 if (currEvent.drawAsAllday()) { 765 addAllDayToStrands(currEvent, strands, firstJulianDay, dayXs.length); 766 continue; 767 } 768 // Copy the event over so we can clip its start and end to our range 769 currEvent.copyTo(event); 770 if (event.startDay < firstJulianDay) { 771 event.startDay = firstJulianDay; 772 event.startTime = 0; 773 } 774 // If it starts after the work day make sure the start is at least 775 // minPixels from midnight 776 if (event.startTime > DAY_IN_MINUTES - minOtherMinutes) { 777 event.startTime = DAY_IN_MINUTES - minOtherMinutes; 778 } 779 if (event.endDay > lastJulianDay) { 780 event.endDay = lastJulianDay; 781 event.endTime = DAY_IN_MINUTES - 1; 782 } 783 // If the end time is before the work day make sure it ends at least 784 // minPixels after midnight 785 if (event.endTime < minOtherMinutes) { 786 event.endTime = minOtherMinutes; 787 } 788 // If the start and end are on the same day make sure they are at 789 // least minPixels apart. This only needs to be done for times 790 // outside the work day as the min distance for within the work day 791 // is enforced in the segment code. 792 if (event.startDay == event.endDay && 793 event.endTime - event.startTime < minOtherMinutes) { 794 // If it's less than minPixels in an area before the work 795 // day 796 if (event.startTime < WORK_DAY_START_MINUTES) { 797 // extend the end to the first easy guarantee that it's 798 // minPixels 799 event.endTime = Math.min(event.startTime + minOtherMinutes, 800 WORK_DAY_START_MINUTES + minMinutes); 801 // if it's in the area after the work day 802 } else if (event.endTime > WORK_DAY_END_MINUTES) { 803 // First try shifting the end but not past midnight 804 event.endTime = Math.min(event.endTime + minOtherMinutes, DAY_IN_MINUTES - 1); 805 // if it's still too small move the start back 806 if (event.endTime - event.startTime < minOtherMinutes) { 807 event.startTime = event.endTime - minOtherMinutes; 808 } 809 } 810 } 811 812 // This handles adding the first segment 813 if (segments.size() == 0) { 814 addNewSegment(segments, event, strands, firstJulianDay, 0, minMinutes); 815 continue; 816 } 817 // Now compare our current start time to the end time of the last 818 // segment in the list 819 DNASegment lastSegment = segments.getLast(); 820 int startMinute = (event.startDay - firstJulianDay) * DAY_IN_MINUTES + event.startTime; 821 int endMinute = Math.max((event.endDay - firstJulianDay) * DAY_IN_MINUTES 822 + event.endTime, startMinute + minMinutes); 823 824 if (startMinute < 0) { 825 startMinute = 0; 826 } 827 if (endMinute >= WEEK_IN_MINUTES) { 828 endMinute = WEEK_IN_MINUTES - 1; 829 } 830 // If we start before the last segment in the list ends we need to 831 // start going through the list as this may conflict with other 832 // events 833 if (startMinute < lastSegment.endMinute) { 834 int i = segments.size(); 835 // find the last segment this event intersects with 836 while (--i >= 0 && endMinute < segments.get(i).startMinute); 837 838 DNASegment currSegment; 839 // for each segment this event intersects with 840 for (; i >= 0 && startMinute <= (currSegment = segments.get(i)).endMinute; i--) { 841 // if the segment is already a conflict ignore it 842 if (currSegment.color == CONFLICT_COLOR) { 843 continue; 844 } 845 // if the event ends before the segment and wouldn't create 846 // a segment that is too small split off the right side 847 if (endMinute < currSegment.endMinute - minMinutes) { 848 DNASegment rhs = new DNASegment(); 849 rhs.endMinute = currSegment.endMinute; 850 rhs.color = currSegment.color; 851 rhs.startMinute = endMinute + 1; 852 rhs.day = currSegment.day; 853 currSegment.endMinute = endMinute; 854 segments.add(i + 1, rhs); 855 strands.get(rhs.color).count++; 856 if (DEBUG) { 857 Log.d(TAG, "Added rhs, curr:" + currSegment.toString() + " i:" 858 + segments.get(i).toString()); 859 } 860 } 861 // if the event starts after the segment and wouldn't create 862 // a segment that is too small split off the left side 863 if (startMinute > currSegment.startMinute + minMinutes) { 864 DNASegment lhs = new DNASegment(); 865 lhs.startMinute = currSegment.startMinute; 866 lhs.color = currSegment.color; 867 lhs.endMinute = startMinute - 1; 868 lhs.day = currSegment.day; 869 currSegment.startMinute = startMinute; 870 // increment i so that we are at the right position when 871 // referencing the segments to the right and left of the 872 // current segment. 873 segments.add(i++, lhs); 874 strands.get(lhs.color).count++; 875 if (DEBUG) { 876 Log.d(TAG, "Added lhs, curr:" + currSegment.toString() + " i:" 877 + segments.get(i).toString()); 878 } 879 } 880 // if the right side is black merge this with the segment to 881 // the right if they're on the same day and overlap 882 if (i + 1 < segments.size()) { 883 DNASegment rhs = segments.get(i + 1); 884 if (rhs.color == CONFLICT_COLOR && currSegment.day == rhs.day 885 && rhs.startMinute <= currSegment.endMinute + 1) { 886 rhs.startMinute = Math.min(currSegment.startMinute, rhs.startMinute); 887 segments.remove(currSegment); 888 strands.get(currSegment.color).count--; 889 // point at the new current segment 890 currSegment = rhs; 891 } 892 } 893 // if the left side is black merge this with the segment to 894 // the left if they're on the same day and overlap 895 if (i - 1 >= 0) { 896 DNASegment lhs = segments.get(i - 1); 897 if (lhs.color == CONFLICT_COLOR && currSegment.day == lhs.day 898 && lhs.endMinute >= currSegment.startMinute - 1) { 899 lhs.endMinute = Math.max(currSegment.endMinute, lhs.endMinute); 900 segments.remove(currSegment); 901 strands.get(currSegment.color).count--; 902 // point at the new current segment 903 currSegment = lhs; 904 // point i at the new current segment in case new 905 // code is added 906 i--; 907 } 908 } 909 // if we're still not black, decrement the count for the 910 // color being removed, change this to black, and increment 911 // the black count 912 if (currSegment.color != CONFLICT_COLOR) { 913 strands.get(currSegment.color).count--; 914 currSegment.color = CONFLICT_COLOR; 915 strands.get(CONFLICT_COLOR).count++; 916 } 917 } 918 919 } 920 // If this event extends beyond the last segment add a new segment 921 if (endMinute > lastSegment.endMinute) { 922 addNewSegment(segments, event, strands, firstJulianDay, lastSegment.endMinute, 923 minMinutes); 924 } 925 } 926 weaveDNAStrands(segments, firstJulianDay, strands, top, bottom, dayXs); 927 return strands; 928 } 929 930 // This figures out allDay colors as allDay events are found 931 private static void addAllDayToStrands(Event event, HashMap<Integer, DNAStrand> strands, 932 int firstJulianDay, int numDays) { 933 DNAStrand strand = getOrCreateStrand(strands, CONFLICT_COLOR); 934 // if we haven't initialized the allDay portion create it now 935 if (strand.allDays == null) { 936 strand.allDays = new int[numDays]; 937 } 938 939 // For each day this event is on update the color 940 int end = Math.min(event.endDay - firstJulianDay, numDays - 1); 941 for (int i = Math.max(event.startDay - firstJulianDay, 0); i <= end; i++) { 942 if (strand.allDays[i] != 0) { 943 // if this day already had a color, it is now a conflict 944 strand.allDays[i] = CONFLICT_COLOR; 945 } else { 946 // else it's just the color of the event 947 strand.allDays[i] = event.color; 948 } 949 } 950 } 951 952 // This processes all the segments, sorts them by color, and generates a 953 // list of points to draw 954 private static void weaveDNAStrands(LinkedList<DNASegment> segments, int firstJulianDay, 955 HashMap<Integer, DNAStrand> strands, int top, int bottom, int[] dayXs) { 956 // First, get rid of any colors that ended up with no segments 957 Iterator<DNAStrand> strandIterator = strands.values().iterator(); 958 while (strandIterator.hasNext()) { 959 DNAStrand strand = strandIterator.next(); 960 if (strand.count < 1 && strand.allDays == null) { 961 strandIterator.remove(); 962 continue; 963 } 964 strand.points = new float[strand.count * 4]; 965 strand.position = 0; 966 } 967 // Go through each segment and compute its points 968 for (DNASegment segment : segments) { 969 // Add the points to the strand of that color 970 DNAStrand strand = strands.get(segment.color); 971 int dayIndex = segment.day - firstJulianDay; 972 int dayStartMinute = segment.startMinute % DAY_IN_MINUTES; 973 int dayEndMinute = segment.endMinute % DAY_IN_MINUTES; 974 int height = bottom - top; 975 int workDayHeight = height * 3 / 4; 976 int remainderHeight = (height - workDayHeight) / 2; 977 978 int x = dayXs[dayIndex]; 979 int y0 = 0; 980 int y1 = 0; 981 982 y0 = top + getPixelOffsetFromMinutes(dayStartMinute, workDayHeight, remainderHeight); 983 y1 = top + getPixelOffsetFromMinutes(dayEndMinute, workDayHeight, remainderHeight); 984 if (DEBUG) { 985 Log.d(TAG, "Adding " + Integer.toHexString(segment.color) + " at x,y0,y1: " + x 986 + " " + y0 + " " + y1 + " for " + dayStartMinute + " " + dayEndMinute); 987 } 988 strand.points[strand.position++] = x; 989 strand.points[strand.position++] = y0; 990 strand.points[strand.position++] = x; 991 strand.points[strand.position++] = y1; 992 } 993 } 994 995 /** 996 * Compute a pixel offset from the top for a given minute from the work day 997 * height and the height of the top area. 998 */ 999 private static int getPixelOffsetFromMinutes(int minute, int workDayHeight, 1000 int remainderHeight) { 1001 int y; 1002 if (minute < WORK_DAY_START_MINUTES) { 1003 y = minute * remainderHeight / WORK_DAY_START_MINUTES; 1004 } else if (minute < WORK_DAY_END_MINUTES) { 1005 y = remainderHeight + (minute - WORK_DAY_START_MINUTES) * workDayHeight 1006 / WORK_DAY_MINUTES; 1007 } else { 1008 y = remainderHeight + workDayHeight + (minute - WORK_DAY_END_MINUTES) * remainderHeight 1009 / WORK_DAY_END_LENGTH; 1010 } 1011 return y; 1012 } 1013 1014 /** 1015 * Add a new segment based on the event provided. This will handle splitting 1016 * segments across day boundaries and ensures a minimum size for segments. 1017 */ 1018 private static void addNewSegment(LinkedList<DNASegment> segments, Event event, 1019 HashMap<Integer, DNAStrand> strands, int firstJulianDay, int minStart, int minMinutes) { 1020 if (event.startDay > event.endDay) { 1021 Log.wtf(TAG, "Event starts after it ends: " + event.toString()); 1022 } 1023 // If this is a multiday event split it up by day 1024 if (event.startDay != event.endDay) { 1025 Event lhs = new Event(); 1026 lhs.color = event.color; 1027 lhs.startDay = event.startDay; 1028 // the first day we want the start time to be the actual start time 1029 lhs.startTime = event.startTime; 1030 lhs.endDay = lhs.startDay; 1031 lhs.endTime = DAY_IN_MINUTES - 1; 1032 // Nearly recursive iteration! 1033 while (lhs.startDay != event.endDay) { 1034 addNewSegment(segments, lhs, strands, firstJulianDay, minStart, minMinutes); 1035 // The days in between are all day, even though that shouldn't 1036 // actually happen due to the allday filtering 1037 lhs.startDay++; 1038 lhs.endDay = lhs.startDay; 1039 lhs.startTime = 0; 1040 minStart = 0; 1041 } 1042 // The last day we want the end time to be the actual end time 1043 lhs.endTime = event.endTime; 1044 event = lhs; 1045 } 1046 // Create the new segment and compute its fields 1047 DNASegment segment = new DNASegment(); 1048 int dayOffset = (event.startDay - firstJulianDay) * DAY_IN_MINUTES; 1049 int endOfDay = dayOffset + DAY_IN_MINUTES - 1; 1050 // clip the start if needed 1051 segment.startMinute = Math.max(dayOffset + event.startTime, minStart); 1052 // and extend the end if it's too small, but not beyond the end of the 1053 // day 1054 int minEnd = Math.min(segment.startMinute + minMinutes, endOfDay); 1055 segment.endMinute = Math.max(dayOffset + event.endTime, minEnd); 1056 if (segment.endMinute > endOfDay) { 1057 segment.endMinute = endOfDay; 1058 } 1059 1060 segment.color = event.color; 1061 segment.day = event.startDay; 1062 segments.add(segment); 1063 // increment the count for the correct color or add a new strand if we 1064 // don't have that color yet 1065 DNAStrand strand = getOrCreateStrand(strands, segment.color); 1066 strand.count++; 1067 } 1068 1069 /** 1070 * Try to get a strand of the given color. Create it if it doesn't exist. 1071 */ 1072 private static DNAStrand getOrCreateStrand(HashMap<Integer, DNAStrand> strands, int color) { 1073 DNAStrand strand = strands.get(color); 1074 if (strand == null) { 1075 strand = new DNAStrand(); 1076 strand.color = color; 1077 strand.count = 0; 1078 strands.put(strand.color, strand); 1079 } 1080 return strand; 1081 } 1082 1083 /** 1084 * Sends an intent to launch the top level Calendar view. 1085 * 1086 * @param context 1087 */ 1088 public static void returnToCalendarHome(Context context) { 1089 Intent launchIntent = new Intent(context, AllInOneActivity.class); 1090 launchIntent.setAction(Intent.ACTION_DEFAULT); 1091 launchIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 1092 launchIntent.putExtra(INTENT_KEY_HOME, true); 1093 context.startActivity(launchIntent); 1094 } 1095 1096 /** 1097 * This sets up a search view to use Calendar's search suggestions provider 1098 * and to allow refining the search. 1099 * 1100 * @param view The {@link SearchView} to set up 1101 * @param act The activity using the view 1102 */ 1103 public static void setUpSearchView(SearchView view, Activity act) { 1104 SearchManager searchManager = (SearchManager) act.getSystemService(Context.SEARCH_SERVICE); 1105 view.setSearchableInfo(searchManager.getSearchableInfo(act.getComponentName())); 1106 view.setQueryRefinementEnabled(true); 1107 } 1108 1109 /** 1110 * Given a context and a time in millis since unix epoch figures out the 1111 * correct week of the year for that time. 1112 * 1113 * @param millisSinceEpoch 1114 * @return 1115 */ 1116 public static int getWeekNumberFromTime(long millisSinceEpoch, Context context) { 1117 Time weekTime = new Time(getTimeZone(context, null)); 1118 weekTime.set(millisSinceEpoch); 1119 weekTime.normalize(true); 1120 int firstDayOfWeek = getFirstDayOfWeek(context); 1121 // if the date is on Saturday or Sunday and the start of the week 1122 // isn't Monday we may need to shift the date to be in the correct 1123 // week 1124 if (weekTime.weekDay == Time.SUNDAY 1125 && (firstDayOfWeek == Time.SUNDAY || firstDayOfWeek == Time.SATURDAY)) { 1126 weekTime.monthDay++; 1127 weekTime.normalize(true); 1128 } else if (weekTime.weekDay == Time.SATURDAY && firstDayOfWeek == Time.SATURDAY) { 1129 weekTime.monthDay += 2; 1130 weekTime.normalize(true); 1131 } 1132 return weekTime.getWeekNumber(); 1133 } 1134 1135 /** 1136 * Formats a day of the week string. This is either just the name of the day 1137 * or a combination of yesterday/today/tomorrow and the day of the week. 1138 * 1139 * @param julianDay The julian day to get the string for 1140 * @param todayJulianDay The julian day for today's date 1141 * @param millis A utc millis since epoch time that falls on julian day 1142 * @param context The calling context, used to get the timezone and do the 1143 * formatting 1144 * @return 1145 */ 1146 public static String getDayOfWeekString(int julianDay, int todayJulianDay, long millis, 1147 Context context) { 1148 getTimeZone(context, null); 1149 int flags = DateUtils.FORMAT_SHOW_WEEKDAY; 1150 String dayViewText; 1151 if (julianDay == todayJulianDay) { 1152 dayViewText = context.getString(R.string.agenda_today, 1153 mTZUtils.formatDateRange(context, millis, millis, flags).toString()); 1154 } else if (julianDay == todayJulianDay - 1) { 1155 dayViewText = context.getString(R.string.agenda_yesterday, 1156 mTZUtils.formatDateRange(context, millis, millis, flags).toString()); 1157 } else if (julianDay == todayJulianDay + 1) { 1158 dayViewText = context.getString(R.string.agenda_tomorrow, 1159 mTZUtils.formatDateRange(context, millis, millis, flags).toString()); 1160 } else { 1161 dayViewText = mTZUtils.formatDateRange(context, millis, millis, flags).toString(); 1162 } 1163 dayViewText = dayViewText.toUpperCase(); 1164 return dayViewText; 1165 } 1166 1167 // Calculate the time until midnight + 1 second and set the handler to 1168 // do run the runnable 1169 public static void setMidnightUpdater(Handler h, Runnable r, String timezone) { 1170 if (h == null || r == null || timezone == null) { 1171 return; 1172 } 1173 long now = System.currentTimeMillis(); 1174 Time time = new Time(timezone); 1175 time.set(now); 1176 long runInMillis = (24 * 3600 - time.hour * 3600 - time.minute * 60 - 1177 time.second + 1) * 1000; 1178 h.removeCallbacks(r); 1179 h.postDelayed(r, runInMillis); 1180 } 1181 1182 // Stop the midnight update thread 1183 public static void resetMidnightUpdater(Handler h, Runnable r) { 1184 if (h == null || r == null) { 1185 return; 1186 } 1187 h.removeCallbacks(r); 1188 } 1189 1190 /** 1191 * Returns a string description of the specified time interval. 1192 */ 1193 public static String getDisplayedDatetime(long startMillis, long endMillis, long currentMillis, 1194 String localTimezone, boolean allDay, Context context) { 1195 // Configure date/time formatting. 1196 int flagsDate = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 1197 int flagsTime = DateUtils.FORMAT_SHOW_TIME; 1198 if (DateFormat.is24HourFormat(context)) { 1199 flagsTime |= DateUtils.FORMAT_24HOUR; 1200 } 1201 1202 Time currentTime = new Time(localTimezone); 1203 currentTime.set(currentMillis); 1204 Resources resources = context.getResources(); 1205 String datetimeString = null; 1206 if (allDay) { 1207 // All day events require special timezone adjustment. 1208 long localStartMillis = convertAlldayUtcToLocal(null, startMillis, localTimezone); 1209 long localEndMillis = convertAlldayUtcToLocal(null, endMillis, localTimezone); 1210 if (singleDayEvent(localStartMillis, localEndMillis, currentTime.gmtoff)) { 1211 // If possible, use "Today" or "Tomorrow" instead of a full date string. 1212 int todayOrTomorrow = isTodayOrTomorrow(context.getResources(), 1213 localStartMillis, currentMillis, currentTime.gmtoff); 1214 if (TODAY == todayOrTomorrow) { 1215 datetimeString = resources.getString(R.string.today); 1216 } else if (TOMORROW == todayOrTomorrow) { 1217 datetimeString = resources.getString(R.string.tomorrow); 1218 } 1219 } 1220 if (datetimeString == null) { 1221 // For multi-day allday events or single-day all-day events that are not 1222 // today or tomorrow, use framework formatter. 1223 Formatter f = new Formatter(new StringBuilder(50), Locale.getDefault()); 1224 datetimeString = DateUtils.formatDateRange(context, f, startMillis, 1225 endMillis, flagsDate, Time.TIMEZONE_UTC).toString(); 1226 } 1227 } else { 1228 if (singleDayEvent(startMillis, endMillis, currentTime.gmtoff)) { 1229 // Format the time. 1230 String timeString = Utils.formatDateRange(context, startMillis, endMillis, 1231 flagsTime); 1232 1233 // If possible, use "Today" or "Tomorrow" instead of a full date string. 1234 int todayOrTomorrow = isTodayOrTomorrow(context.getResources(), startMillis, 1235 currentMillis, currentTime.gmtoff); 1236 if (TODAY == todayOrTomorrow) { 1237 // Example: "Today at 1:00pm - 2:00 pm" 1238 datetimeString = resources.getString(R.string.today_at_time_fmt, 1239 timeString); 1240 } else if (TOMORROW == todayOrTomorrow) { 1241 // Example: "Tomorrow at 1:00pm - 2:00 pm" 1242 datetimeString = resources.getString(R.string.tomorrow_at_time_fmt, 1243 timeString); 1244 } else { 1245 // Format the full date. Example: "Thursday, April 12, 1:00pm - 2:00pm" 1246 String dateString = Utils.formatDateRange(context, startMillis, endMillis, 1247 flagsDate); 1248 datetimeString = resources.getString(R.string.date_time_fmt, dateString, 1249 timeString); 1250 } 1251 } else { 1252 // For multiday events, shorten day/month names. 1253 // Example format: "Fri Apr 6, 5:00pm - Sun, Apr 8, 6:00pm" 1254 int flagsDatetime = flagsDate | flagsTime | DateUtils.FORMAT_ABBREV_MONTH | 1255 DateUtils.FORMAT_ABBREV_WEEKDAY; 1256 datetimeString = Utils.formatDateRange(context, startMillis, endMillis, 1257 flagsDatetime); 1258 } 1259 } 1260 return datetimeString; 1261 } 1262 1263 /** 1264 * Returns the timezone to display in the event info, if the local timezone is different 1265 * from the event timezone. Otherwise returns null. 1266 */ 1267 public static String getDisplayedTimezone(long startMillis, String localTimezone, 1268 String eventTimezone) { 1269 String tzDisplay = null; 1270 if (!TextUtils.equals(localTimezone, eventTimezone)) { 1271 // Figure out if this is in DST 1272 TimeZone tz = TimeZone.getTimeZone(localTimezone); 1273 if (tz == null || tz.getID().equals("GMT")) { 1274 tzDisplay = localTimezone; 1275 } else { 1276 Time startTime = new Time(localTimezone); 1277 startTime.set(startMillis); 1278 tzDisplay = tz.getDisplayName(startTime.isDst != 0, TimeZone.SHORT); 1279 } 1280 } 1281 return tzDisplay; 1282 } 1283 1284 /** 1285 * Returns whether the specified time interval is in a single day. 1286 */ 1287 private static boolean singleDayEvent(long startMillis, long endMillis, long localGmtOffset) { 1288 if (startMillis == endMillis) { 1289 return true; 1290 } 1291 1292 // An event ending at midnight should still be a single-day event, so check 1293 // time end-1. 1294 int startDay = Time.getJulianDay(startMillis, localGmtOffset); 1295 int endDay = Time.getJulianDay(endMillis - 1, localGmtOffset); 1296 return startDay == endDay; 1297 } 1298 1299 // Using int constants as a return value instead of an enum to minimize resources. 1300 private static final int TODAY = 1; 1301 private static final int TOMORROW = 2; 1302 private static final int NONE = 0; 1303 1304 /** 1305 * Returns TODAY or TOMORROW if applicable. Otherwise returns NONE. 1306 */ 1307 private static int isTodayOrTomorrow(Resources r, long dayMillis, 1308 long currentMillis, long localGmtOffset) { 1309 int startDay = Time.getJulianDay(dayMillis, localGmtOffset); 1310 int currentDay = Time.getJulianDay(currentMillis, localGmtOffset); 1311 1312 int days = startDay - currentDay; 1313 if (days == 1) { 1314 return TOMORROW; 1315 } else if (days == 0) { 1316 return TODAY; 1317 } else { 1318 return NONE; 1319 } 1320 } 1321 1322 /** 1323 * Create an intent for emailing attendees of an event. 1324 * 1325 * @param resources The resources for translating strings. 1326 * @param eventTitle The title of the event to use as the email subject. 1327 * @param body The default text for the email body. 1328 * @param toEmails The list of emails for the 'to' line. 1329 * @param ccEmails The list of emails for the 'cc' line. 1330 * @param ownerAccount The owner account to use as the email sender. 1331 */ 1332 public static Intent createEmailAttendeesIntent(Resources resources, String eventTitle, 1333 String body, List<String> toEmails, List<String> ccEmails, String ownerAccount) { 1334 List<String> toList = toEmails; 1335 List<String> ccList = ccEmails; 1336 if (toEmails.size() <= 0) { 1337 if (ccEmails.size() <= 0) { 1338 // TODO: Return a SEND intent if no one to email to, to at least populate 1339 // a draft email with the subject (and no recipients). 1340 throw new IllegalArgumentException("Both toEmails and ccEmails are empty."); 1341 } 1342 1343 // Email app does not work with no "to" recipient. Move all 'cc' to 'to' 1344 // in this case. 1345 toList = ccEmails; 1346 ccList = null; 1347 } 1348 1349 // Use the event title as the email subject (prepended with 'Re: '). 1350 String subject = null; 1351 if (eventTitle != null) { 1352 subject = resources.getString(R.string.email_subject_prefix) + eventTitle; 1353 } 1354 1355 // Use the SENDTO intent with a 'mailto' URI, because using SEND will cause 1356 // the picker to show apps like text messaging, which does not make sense 1357 // for email addresses. We put all data in the URI instead of using the extra 1358 // Intent fields (ie. EXTRA_CC, etc) because some email apps might not handle 1359 // those (though gmail does). 1360 Uri.Builder uriBuilder = new Uri.Builder(); 1361 uriBuilder.scheme("mailto"); 1362 1363 // We will append the first email to the 'mailto' field later (because the 1364 // current state of the Email app requires it). Add the remaining 'to' values 1365 // here. When the email codebase is updated, we can simplify this. 1366 if (toList.size() > 1) { 1367 for (int i = 1; i < toList.size(); i++) { 1368 // The Email app requires repeated parameter settings instead of 1369 // a single comma-separated list. 1370 uriBuilder.appendQueryParameter("to", toList.get(i)); 1371 } 1372 } 1373 1374 // Add the subject parameter. 1375 if (subject != null) { 1376 uriBuilder.appendQueryParameter("subject", subject); 1377 } 1378 1379 // Add the subject parameter. 1380 if (body != null) { 1381 uriBuilder.appendQueryParameter("body", body); 1382 } 1383 1384 // Add the cc parameters. 1385 if (ccList != null && ccList.size() > 0) { 1386 for (String email : ccList) { 1387 uriBuilder.appendQueryParameter("cc", email); 1388 } 1389 } 1390 1391 // Insert the first email after 'mailto:' in the URI manually since Uri.Builder 1392 // doesn't seem to have a way to do this. 1393 String uri = uriBuilder.toString(); 1394 if (uri.startsWith("mailto:")) { 1395 StringBuilder builder = new StringBuilder(uri); 1396 builder.insert(7, Uri.encode(toList.get(0))); 1397 uri = builder.toString(); 1398 } 1399 1400 // Start the email intent. Email from the account of the calendar owner in case there 1401 // are multiple email accounts. 1402 Intent emailIntent = new Intent(android.content.Intent.ACTION_SENDTO, Uri.parse(uri)); 1403 emailIntent.putExtra("fromAccountString", ownerAccount); 1404 return Intent.createChooser(emailIntent, resources.getString(R.string.email_picker_label)); 1405 } 1406 1407 /** 1408 * Example fake email addresses used as attendee emails are resources like conference rooms, 1409 * or another calendar, etc. These all end in "calendar.google.com". 1410 */ 1411 public static boolean isValidEmail(String email) { 1412 return email != null && !email.endsWith(MACHINE_GENERATED_ADDRESS); 1413 } 1414 1415 /** 1416 * Returns true if: 1417 * (1) the email is not a resource like a conference room or another calendar. 1418 * Catch most of these by filtering out suffix calendar.google.com. 1419 * (2) the email is not equal to the sync account to prevent mailing himself. 1420 */ 1421 public static boolean isEmailableFrom(String email, String syncAccountName) { 1422 return Utils.isValidEmail(email) && !email.equals(syncAccountName); 1423 } 1424 1425 /** 1426 * Inserts a drawable with today's day into the today's icon in the option menu 1427 * @param icon - today's icon from the options menu 1428 */ 1429 public static void setTodayIcon(LayerDrawable icon, Context c, String timezone) { 1430 DayOfMonthDrawable today; 1431 1432 // Reuse current drawable if possible 1433 Drawable currentDrawable = icon.findDrawableByLayerId(R.id.today_icon_day); 1434 if (currentDrawable != null && currentDrawable instanceof DayOfMonthDrawable) { 1435 today = (DayOfMonthDrawable)currentDrawable; 1436 } else { 1437 today = new DayOfMonthDrawable(c); 1438 } 1439 // Set the day and update the icon 1440 Time now = new Time(timezone); 1441 now.setToNow(); 1442 now.normalize(false); 1443 today.setDayOfMonth(now.monthDay); 1444 icon.mutate(); 1445 icon.setDrawableByLayerId(R.id.today_icon_day, today); 1446 } 1447 1448 private static class CalendarBroadcastReceiver extends BroadcastReceiver { 1449 1450 Runnable mCallBack; 1451 1452 public CalendarBroadcastReceiver(Runnable callback) { 1453 super(); 1454 mCallBack = callback; 1455 } 1456 @Override 1457 public void onReceive(Context context, Intent intent) { 1458 if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED) || 1459 intent.getAction().equals(Intent.ACTION_TIME_CHANGED) || 1460 intent.getAction().equals(Intent.ACTION_LOCALE_CHANGED) || 1461 intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) { 1462 if (mCallBack != null) { 1463 mCallBack.run(); 1464 } 1465 } 1466 } 1467 } 1468 1469 public static BroadcastReceiver setTimeChangesReceiver(Context c, Runnable callback) { 1470 IntentFilter filter = new IntentFilter(); 1471 filter.addAction(Intent.ACTION_TIME_CHANGED); 1472 filter.addAction(Intent.ACTION_DATE_CHANGED); 1473 filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); 1474 filter.addAction(Intent.ACTION_LOCALE_CHANGED); 1475 1476 CalendarBroadcastReceiver r = new CalendarBroadcastReceiver(callback); 1477 c.registerReceiver(r, filter); 1478 return r; 1479 } 1480 1481 public static void clearTimeChangesReceiver(Context c, BroadcastReceiver r) { 1482 c.unregisterReceiver(r); 1483 } 1484 1485 /** 1486 * Get a list of quick responses used for emailing guests from the 1487 * SharedPreferences. If not are found, get the hard coded ones that shipped 1488 * with the app 1489 * 1490 * @param context 1491 * @return a list of quick responses. 1492 */ 1493 public static String[] getQuickResponses(Context context) { 1494 String[] s = Utils.getSharedPreference(context, KEY_QUICK_RESPONSES, (String[]) null); 1495 1496 if (s == null) { 1497 s = context.getResources().getStringArray(R.array.quick_response_defaults); 1498 } 1499 1500 return s; 1501 } 1502 1503 /** 1504 * Return the app version code. 1505 */ 1506 public static String getVersionCode(Context context) { 1507 if (sVersion == null) { 1508 try { 1509 sVersion = context.getPackageManager().getPackageInfo( 1510 context.getPackageName(), 0).versionName; 1511 } catch (PackageManager.NameNotFoundException e) { 1512 // Can't find version; just leave it blank. 1513 Log.e(TAG, "Error finding package " + context.getApplicationInfo().packageName); 1514 } 1515 } 1516 return sVersion; 1517 } 1518} 1519