1 /* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.calendar; 18 19 import android.content.ContentResolver; 20 import android.content.ContentUris; 21 import android.content.Context; 22 import android.content.SharedPreferences; 23 import android.content.res.Resources; 24 import android.database.Cursor; 25 import android.net.Uri; 26 import android.os.Debug; 27 import android.provider.CalendarContract.Attendees; 28 import android.provider.CalendarContract.Calendars; 29 import android.provider.CalendarContract.Events; 30 import android.provider.CalendarContract.Instances; 31 import android.text.TextUtils; 32 import android.text.format.DateUtils; 33 import android.util.Log; 34 35 import java.util.ArrayList; 36 import java.util.Arrays; 37 import java.util.Iterator; 38 import java.util.concurrent.atomic.AtomicInteger; 39 40 // TODO: should Event be Parcelable so it can be passed via Intents? 41 public class Event implements Cloneable { 42 43 private static final String TAG = "CalEvent"; 44 private static final boolean PROFILE = false; 45 46 /** 47 * The sort order is: 48 * 1) events with an earlier start (begin for normal events, startday for allday) 49 * 2) events with a later end (end for normal events, endday for allday) 50 * 3) the title (unnecessary, but nice) 51 * 52 * The start and end day is sorted first so that all day events are 53 * sorted correctly with respect to events that are >24 hours (and 54 * therefore show up in the allday area). 55 */ 56 private static final String SORT_EVENTS_BY = 57 "begin ASC, end DESC, title ASC"; 58 private static final String SORT_ALLDAY_BY = 59 "startDay ASC, endDay DESC, title ASC"; 60 private static final String DISPLAY_AS_ALLDAY = "dispAllday"; 61 62 private static final String EVENTS_WHERE = DISPLAY_AS_ALLDAY + "=0"; 63 private static final String ALLDAY_WHERE = DISPLAY_AS_ALLDAY + "=1"; 64 65 // The projection to use when querying instances to build a list of events 66 public static final String[] EVENT_PROJECTION = new String[] { 67 Instances.TITLE, // 0 68 Instances.EVENT_LOCATION, // 1 69 Instances.ALL_DAY, // 2 70 Instances.DISPLAY_COLOR, // 3 71 Instances.EVENT_TIMEZONE, // 4 72 Instances.EVENT_ID, // 5 73 Instances.BEGIN, // 6 74 Instances.END, // 7 75 Instances._ID, // 8 76 Instances.START_DAY, // 9 77 Instances.END_DAY, // 10 78 Instances.START_MINUTE, // 11 79 Instances.END_MINUTE, // 12 80 Instances.HAS_ALARM, // 13 81 Instances.RRULE, // 14 82 Instances.RDATE, // 15 83 Instances.SELF_ATTENDEE_STATUS, // 16 84 Events.ORGANIZER, // 17 85 Events.GUESTS_CAN_MODIFY, // 18 86 Instances.ALL_DAY + "=1 OR (" + Instances.END + "-" + Instances.BEGIN + ")>=" 87 + DateUtils.DAY_IN_MILLIS + " AS " + DISPLAY_AS_ALLDAY, // 19 88 }; 89 90 // The indices for the projection array above. 91 private static final int PROJECTION_TITLE_INDEX = 0; 92 private static final int PROJECTION_LOCATION_INDEX = 1; 93 private static final int PROJECTION_ALL_DAY_INDEX = 2; 94 private static final int PROJECTION_COLOR_INDEX = 3; 95 private static final int PROJECTION_TIMEZONE_INDEX = 4; 96 private static final int PROJECTION_EVENT_ID_INDEX = 5; 97 private static final int PROJECTION_BEGIN_INDEX = 6; 98 private static final int PROJECTION_END_INDEX = 7; 99 private static final int PROJECTION_START_DAY_INDEX = 9; 100 private static final int PROJECTION_END_DAY_INDEX = 10; 101 private static final int PROJECTION_START_MINUTE_INDEX = 11; 102 private static final int PROJECTION_END_MINUTE_INDEX = 12; 103 private static final int PROJECTION_HAS_ALARM_INDEX = 13; 104 private static final int PROJECTION_RRULE_INDEX = 14; 105 private static final int PROJECTION_RDATE_INDEX = 15; 106 private static final int PROJECTION_SELF_ATTENDEE_STATUS_INDEX = 16; 107 private static final int PROJECTION_ORGANIZER_INDEX = 17; 108 private static final int PROJECTION_GUESTS_CAN_INVITE_OTHERS_INDEX = 18; 109 private static final int PROJECTION_DISPLAY_AS_ALLDAY = 19; 110 111 private static String mNoTitleString; 112 private static int mNoColorColor; 113 114 public long id; 115 public int color; 116 public CharSequence title; 117 public CharSequence location; 118 public boolean allDay; 119 public String organizer; 120 public boolean guestsCanModify; 121 122 public int startDay; // start Julian day 123 public int endDay; // end Julian day 124 public int startTime; // Start and end time are in minutes since midnight 125 public int endTime; 126 127 public long startMillis; // UTC milliseconds since the epoch 128 public long endMillis; // UTC milliseconds since the epoch 129 private int mColumn; 130 private int mMaxColumns; 131 132 public boolean hasAlarm; 133 public boolean isRepeating; 134 135 public int selfAttendeeStatus; 136 137 // The coordinates of the event rectangle drawn on the screen. 138 public float left; 139 public float right; 140 public float top; 141 public float bottom; 142 143 // These 4 fields are used for navigating among events within the selected 144 // hour in the Day and Week view. 145 public Event nextRight; 146 public Event nextLeft; 147 public Event nextUp; 148 public Event nextDown; 149 150 @Override 151 public final Object clone() throws CloneNotSupportedException { 152 super.clone(); 153 Event e = new Event(); 154 155 e.title = title; 156 e.color = color; 157 e.location = location; 158 e.allDay = allDay; 159 e.startDay = startDay; 160 e.endDay = endDay; 161 e.startTime = startTime; 162 e.endTime = endTime; 163 e.startMillis = startMillis; 164 e.endMillis = endMillis; 165 e.hasAlarm = hasAlarm; 166 e.isRepeating = isRepeating; 167 e.selfAttendeeStatus = selfAttendeeStatus; 168 e.organizer = organizer; 169 e.guestsCanModify = guestsCanModify; 170 171 return e; 172 } 173 174 public final void copyTo(Event dest) { 175 dest.id = id; 176 dest.title = title; 177 dest.color = color; 178 dest.location = location; 179 dest.allDay = allDay; 180 dest.startDay = startDay; 181 dest.endDay = endDay; 182 dest.startTime = startTime; 183 dest.endTime = endTime; 184 dest.startMillis = startMillis; 185 dest.endMillis = endMillis; 186 dest.hasAlarm = hasAlarm; 187 dest.isRepeating = isRepeating; 188 dest.selfAttendeeStatus = selfAttendeeStatus; 189 dest.organizer = organizer; 190 dest.guestsCanModify = guestsCanModify; 191 } 192 193 public static final Event newInstance() { 194 Event e = new Event(); 195 196 e.id = 0; 197 e.title = null; 198 e.color = 0; 199 e.location = null; 200 e.allDay = false; 201 e.startDay = 0; 202 e.endDay = 0; 203 e.startTime = 0; 204 e.endTime = 0; 205 e.startMillis = 0; 206 e.endMillis = 0; 207 e.hasAlarm = false; 208 e.isRepeating = false; 209 e.selfAttendeeStatus = Attendees.ATTENDEE_STATUS_NONE; 210 211 return e; 212 } 213 214 /** 215 * Loads <i>days</i> days worth of instances starting at <i>startDay</i>. 216 */ 217 public static void loadEvents(Context context, ArrayList<Event> events, int startDay, int days, 218 int requestId, AtomicInteger sequenceNumber) { 219 220 if (PROFILE) { 221 Debug.startMethodTracing("loadEvents"); 222 } 223 224 Cursor cEvents = null; 225 Cursor cAllday = null; 226 227 events.clear(); 228 try { 229 int endDay = startDay + days - 1; 230 231 // We use the byDay instances query to get a list of all events for 232 // the days we're interested in. 233 // The sort order is: events with an earlier start time occur 234 // first and if the start times are the same, then events with 235 // a later end time occur first. The later end time is ordered 236 // first so that long rectangles in the calendar views appear on 237 // the left side. If the start and end times of two events are 238 // the same then we sort alphabetically on the title. This isn't 239 // required for correctness, it just adds a nice touch. 240 241 // Respect the preference to show/hide declined events 242 SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); 243 boolean hideDeclined = prefs.getBoolean(GeneralPreferences.KEY_HIDE_DECLINED, 244 false); 245 246 String where = EVENTS_WHERE; 247 String whereAllday = ALLDAY_WHERE; 248 if (hideDeclined) { 249 String hideString = " AND " + Instances.SELF_ATTENDEE_STATUS + "!=" 250 + Attendees.ATTENDEE_STATUS_DECLINED; 251 where += hideString; 252 whereAllday += hideString; 253 } 254 255 cEvents = instancesQuery(context.getContentResolver(), EVENT_PROJECTION, startDay, 256 endDay, where, null, SORT_EVENTS_BY); 257 cAllday = instancesQuery(context.getContentResolver(), EVENT_PROJECTION, startDay, 258 endDay, whereAllday, null, SORT_ALLDAY_BY); 259 260 // Check if we should return early because there are more recent 261 // load requests waiting. 262 if (requestId != sequenceNumber.get()) { 263 return; 264 } 265 266 buildEventsFromCursor(events, cEvents, context, startDay, endDay); 267 buildEventsFromCursor(events, cAllday, context, startDay, endDay); 268 269 } finally { 270 if (cEvents != null) { 271 cEvents.close(); 272 } 273 if (cAllday != null) { 274 cAllday.close(); 275 } 276 if (PROFILE) { 277 Debug.stopMethodTracing(); 278 } 279 } 280 } 281 282 /** 283 * Performs a query to return all visible instances in the given range 284 * that match the given selection. This is a blocking function and 285 * should not be done on the UI thread. This will cause an expansion of 286 * recurring events to fill this time range if they are not already 287 * expanded and will slow down for larger time ranges with many 288 * recurring events. 289 * 290 * @param cr The ContentResolver to use for the query 291 * @param projection The columns to return 292 * @param begin The start of the time range to query in UTC millis since 293 * epoch 294 * @param end The end of the time range to query in UTC millis since 295 * epoch 296 * @param selection Filter on the query as an SQL WHERE statement 297 * @param selectionArgs Args to replace any '?'s in the selection 298 * @param orderBy How to order the rows as an SQL ORDER BY statement 299 * @return A Cursor of instances matching the selection 300 */ 301 private static final Cursor instancesQuery(ContentResolver cr, String[] projection, 302 int startDay, int endDay, String selection, String[] selectionArgs, String orderBy) { 303 String WHERE_CALENDARS_SELECTED = Calendars.VISIBLE + "=?"; 304 String[] WHERE_CALENDARS_ARGS = {"1"}; 305 String DEFAULT_SORT_ORDER = "begin ASC"; 306 307 Uri.Builder builder = Instances.CONTENT_BY_DAY_URI.buildUpon(); 308 ContentUris.appendId(builder, startDay); 309 ContentUris.appendId(builder, endDay); 310 if (TextUtils.isEmpty(selection)) { 311 selection = WHERE_CALENDARS_SELECTED; 312 selectionArgs = WHERE_CALENDARS_ARGS; 313 } else { 314 selection = "(" + selection + ") AND " + WHERE_CALENDARS_SELECTED; 315 if (selectionArgs != null && selectionArgs.length > 0) { 316 selectionArgs = Arrays.copyOf(selectionArgs, selectionArgs.length + 1); 317 selectionArgs[selectionArgs.length - 1] = WHERE_CALENDARS_ARGS[0]; 318 } else { 319 selectionArgs = WHERE_CALENDARS_ARGS; 320 } 321 } 322 return cr.query(builder.build(), projection, selection, selectionArgs, 323 orderBy == null ? DEFAULT_SORT_ORDER : orderBy); 324 } 325 326 /** 327 * Adds all the events from the cursors to the events list. 328 * 329 * @param events The list of events 330 * @param cEvents Events to add to the list 331 * @param context 332 * @param startDay 333 * @param endDay 334 */ 335 public static void buildEventsFromCursor( 336 ArrayList<Event> events, Cursor cEvents, Context context, int startDay, int endDay) { 337 if (cEvents == null || events == null) { 338 Log.e(TAG, "buildEventsFromCursor: null cursor or null events list!"); 339 return; 340 } 341 342 int count = cEvents.getCount(); 343 344 if (count == 0) { 345 return; 346 } 347 348 Resources res = context.getResources(); 349 mNoTitleString = res.getString(R.string.no_title_label); 350 mNoColorColor = res.getColor(R.color.event_center); 351 // Sort events in two passes so we ensure the allday and standard events 352 // get sorted in the correct order 353 cEvents.moveToPosition(-1); 354 while (cEvents.moveToNext()) { 355 Event e = generateEventFromCursor(cEvents); 356 if (e.startDay > endDay || e.endDay < startDay) { 357 continue; 358 } 359 events.add(e); 360 } 361 } 362 363 /** 364 * @param cEvents Cursor pointing at event 365 * @return An event created from the cursor 366 */ 367 private static Event generateEventFromCursor(Cursor cEvents) { 368 Event e = new Event(); 369 370 e.id = cEvents.getLong(PROJECTION_EVENT_ID_INDEX); 371 e.title = cEvents.getString(PROJECTION_TITLE_INDEX); 372 e.location = cEvents.getString(PROJECTION_LOCATION_INDEX); 373 e.allDay = cEvents.getInt(PROJECTION_ALL_DAY_INDEX) != 0; 374 e.organizer = cEvents.getString(PROJECTION_ORGANIZER_INDEX); 375 e.guestsCanModify = cEvents.getInt(PROJECTION_GUESTS_CAN_INVITE_OTHERS_INDEX) != 0; 376 377 if (e.title == null || e.title.length() == 0) { 378 e.title = mNoTitleString; 379 } 380 381 if (!cEvents.isNull(PROJECTION_COLOR_INDEX)) { 382 // Read the color from the database 383 e.color = Utils.getDisplayColorFromColor(cEvents.getInt(PROJECTION_COLOR_INDEX)); 384 } else { 385 e.color = mNoColorColor; 386 } 387 388 long eStart = cEvents.getLong(PROJECTION_BEGIN_INDEX); 389 long eEnd = cEvents.getLong(PROJECTION_END_INDEX); 390 391 e.startMillis = eStart; 392 e.startTime = cEvents.getInt(PROJECTION_START_MINUTE_INDEX); 393 e.startDay = cEvents.getInt(PROJECTION_START_DAY_INDEX); 394 395 e.endMillis = eEnd; 396 e.endTime = cEvents.getInt(PROJECTION_END_MINUTE_INDEX); 397 e.endDay = cEvents.getInt(PROJECTION_END_DAY_INDEX); 398 399 e.hasAlarm = cEvents.getInt(PROJECTION_HAS_ALARM_INDEX) != 0; 400 401 // Check if this is a repeating event 402 String rrule = cEvents.getString(PROJECTION_RRULE_INDEX); 403 String rdate = cEvents.getString(PROJECTION_RDATE_INDEX); 404 if (!TextUtils.isEmpty(rrule) || !TextUtils.isEmpty(rdate)) { 405 e.isRepeating = true; 406 } else { 407 e.isRepeating = false; 408 } 409 410 e.selfAttendeeStatus = cEvents.getInt(PROJECTION_SELF_ATTENDEE_STATUS_INDEX); 411 return e; 412 } 413 414 /** 415 * Computes a position for each event. Each event is displayed 416 * as a non-overlapping rectangle. For normal events, these rectangles 417 * are displayed in separate columns in the week view and day view. For 418 * all-day events, these rectangles are displayed in separate rows along 419 * the top. In both cases, each event is assigned two numbers: N, and 420 * Max, that specify that this event is the Nth event of Max number of 421 * events that are displayed in a group. The width and position of each 422 * rectangle depend on the maximum number of rectangles that occur at 423 * the same time. 424 * 425 * @param eventsList the list of events, sorted into increasing time order 426 * @param minimumDurationMillis minimum duration acceptable as cell height of each event 427 * rectangle in millisecond. Should be 0 when it is not determined. 428 */ 429 /* package */ static void computePositions(ArrayList<Event> eventsList, 430 long minimumDurationMillis) { 431 if (eventsList == null) { 432 return; 433 } 434 435 // Compute the column positions separately for the all-day events 436 doComputePositions(eventsList, minimumDurationMillis, false); 437 doComputePositions(eventsList, minimumDurationMillis, true); 438 } 439 440 private static void doComputePositions(ArrayList<Event> eventsList, 441 long minimumDurationMillis, boolean doAlldayEvents) { 442 final ArrayList<Event> activeList = new ArrayList<Event>(); 443 final ArrayList<Event> groupList = new ArrayList<Event>(); 444 445 if (minimumDurationMillis < 0) { 446 minimumDurationMillis = 0; 447 } 448 449 long colMask = 0; 450 int maxCols = 0; 451 for (Event event : eventsList) { 452 // Process all-day events separately 453 if (event.drawAsAllday() != doAlldayEvents) 454 continue; 455 456 if (!doAlldayEvents) { 457 colMask = removeNonAlldayActiveEvents( 458 event, activeList.iterator(), minimumDurationMillis, colMask); 459 } else { 460 colMask = removeAlldayActiveEvents(event, activeList.iterator(), colMask); 461 } 462 463 // If the active list is empty, then reset the max columns, clear 464 // the column bit mask, and empty the groupList. 465 if (activeList.isEmpty()) { 466 for (Event ev : groupList) { 467 ev.setMaxColumns(maxCols); 468 } 469 maxCols = 0; 470 colMask = 0; 471 groupList.clear(); 472 } 473 474 // Find the first empty column. Empty columns are represented by 475 // zero bits in the column mask "colMask". 476 int col = findFirstZeroBit(colMask); 477 if (col == 64) 478 col = 63; 479 colMask |= (1L << col); 480 event.setColumn(col); 481 activeList.add(event); 482 groupList.add(event); 483 int len = activeList.size(); 484 if (maxCols < len) 485 maxCols = len; 486 } 487 for (Event ev : groupList) { 488 ev.setMaxColumns(maxCols); 489 } 490 } 491 492 private static long removeAlldayActiveEvents(Event event, Iterator<Event> iter, long colMask) { 493 // Remove the inactive allday events. An event on the active list 494 // becomes inactive when the end day is less than the current event's 495 // start day. 496 while (iter.hasNext()) { 497 final Event active = iter.next(); 498 if (active.endDay < event.startDay) { 499 colMask &= ~(1L << active.getColumn()); 500 iter.remove(); 501 } 502 } 503 return colMask; 504 } 505 506 private static long removeNonAlldayActiveEvents( 507 Event event, Iterator<Event> iter, long minDurationMillis, long colMask) { 508 long start = event.getStartMillis(); 509 // Remove the inactive events. An event on the active list 510 // becomes inactive when its end time is less than or equal to 511 // the current event's start time. 512 while (iter.hasNext()) { 513 final Event active = iter.next(); 514 515 final long duration = Math.max( 516 active.getEndMillis() - active.getStartMillis(), minDurationMillis); 517 if ((active.getStartMillis() + duration) <= start) { 518 colMask &= ~(1L << active.getColumn()); 519 iter.remove(); 520 } 521 } 522 return colMask; 523 } 524 525 public static int findFirstZeroBit(long val) { 526 for (int ii = 0; ii < 64; ++ii) { 527 if ((val & (1L << ii)) == 0) 528 return ii; 529 } 530 return 64; 531 } 532 533 public final void dump() { 534 Log.e("Cal", "+-----------------------------------------+"); 535 Log.e("Cal", "+ id = " + id); 536 Log.e("Cal", "+ color = " + color); 537 Log.e("Cal", "+ title = " + title); 538 Log.e("Cal", "+ location = " + location); 539 Log.e("Cal", "+ allDay = " + allDay); 540 Log.e("Cal", "+ startDay = " + startDay); 541 Log.e("Cal", "+ endDay = " + endDay); 542 Log.e("Cal", "+ startTime = " + startTime); 543 Log.e("Cal", "+ endTime = " + endTime); 544 Log.e("Cal", "+ organizer = " + organizer); 545 Log.e("Cal", "+ guestwrt = " + guestsCanModify); 546 } 547 548 public final boolean intersects(int julianDay, int startMinute, 549 int endMinute) { 550 if (endDay < julianDay) { 551 return false; 552 } 553 554 if (startDay > julianDay) { 555 return false; 556 } 557 558 if (endDay == julianDay) { 559 if (endTime < startMinute) { 560 return false; 561 } 562 // An event that ends at the start minute should not be considered 563 // as intersecting the given time span, but don't exclude 564 // zero-length (or very short) events. 565 if (endTime == startMinute 566 && (startTime != endTime || startDay != endDay)) { 567 return false; 568 } 569 } 570 571 if (startDay == julianDay && startTime > endMinute) { 572 return false; 573 } 574 575 return true; 576 } 577 578 /** 579 * Returns the event title and location separated by a comma. If the 580 * location is already part of the title (at the end of the title), then 581 * just the title is returned. 582 * 583 * @return the event title and location as a String 584 */ 585 public String getTitleAndLocation() { 586 String text = title.toString(); 587 588 // Append the location to the title, unless the title ends with the 589 // location (for example, "meeting in building 42" ends with the 590 // location). 591 if (location != null) { 592 String locationString = location.toString(); 593 if (!text.endsWith(locationString)) { 594 text += ", " + locationString; 595 } 596 } 597 return text; 598 } 599 600 public void setColumn(int column) { 601 mColumn = column; 602 } 603 604 public int getColumn() { 605 return mColumn; 606 } 607 608 public void setMaxColumns(int maxColumns) { 609 mMaxColumns = maxColumns; 610 } 611 612 public int getMaxColumns() { 613 return mMaxColumns; 614 } 615 616 public void setStartMillis(long startMillis) { 617 this.startMillis = startMillis; 618 } 619 620 public long getStartMillis() { 621 return startMillis; 622 } 623 624 public void setEndMillis(long endMillis) { 625 this.endMillis = endMillis; 626 } 627 628 public long getEndMillis() { 629 return endMillis; 630 } 631 632 public boolean drawAsAllday() { 633 // Use >= so we'll pick up Exchange allday events 634 return allDay || endMillis - startMillis >= DateUtils.DAY_IN_MILLIS; 635 } 636 } 637