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