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.CALENDAR_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 while (cEvents.moveToNext()) { 354 Event e = generateEventFromCursor(cEvents); 355 if (e.startDay > endDay || e.endDay < startDay) { 356 continue; 357 } 358 events.add(e); 359 } 360 } 361 362 /** 363 * @param cEvents Cursor pointing at event 364 * @return An event created from the cursor 365 */ 366 private static Event generateEventFromCursor(Cursor cEvents) { 367 Event e = new Event(); 368 369 e.id = cEvents.getLong(PROJECTION_EVENT_ID_INDEX); 370 e.title = cEvents.getString(PROJECTION_TITLE_INDEX); 371 e.location = cEvents.getString(PROJECTION_LOCATION_INDEX); 372 e.allDay = cEvents.getInt(PROJECTION_ALL_DAY_INDEX) != 0; 373 e.organizer = cEvents.getString(PROJECTION_ORGANIZER_INDEX); 374 e.guestsCanModify = cEvents.getInt(PROJECTION_GUESTS_CAN_INVITE_OTHERS_INDEX) != 0; 375 376 if (e.title == null || e.title.length() == 0) { 377 e.title = mNoTitleString; 378 } 379 380 if (!cEvents.isNull(PROJECTION_COLOR_INDEX)) { 381 // Read the color from the database 382 e.color = Utils.getDisplayColorFromColor(cEvents.getInt(PROJECTION_COLOR_INDEX)); 383 } else { 384 e.color = mNoColorColor; 385 } 386 387 long eStart = cEvents.getLong(PROJECTION_BEGIN_INDEX); 388 long eEnd = cEvents.getLong(PROJECTION_END_INDEX); 389 390 e.startMillis = eStart; 391 e.startTime = cEvents.getInt(PROJECTION_START_MINUTE_INDEX); 392 e.startDay = cEvents.getInt(PROJECTION_START_DAY_INDEX); 393 394 e.endMillis = eEnd; 395 e.endTime = cEvents.getInt(PROJECTION_END_MINUTE_INDEX); 396 e.endDay = cEvents.getInt(PROJECTION_END_DAY_INDEX); 397 398 e.hasAlarm = cEvents.getInt(PROJECTION_HAS_ALARM_INDEX) != 0; 399 400 // Check if this is a repeating event 401 String rrule = cEvents.getString(PROJECTION_RRULE_INDEX); 402 String rdate = cEvents.getString(PROJECTION_RDATE_INDEX); 403 if (!TextUtils.isEmpty(rrule) || !TextUtils.isEmpty(rdate)) { 404 e.isRepeating = true; 405 } else { 406 e.isRepeating = false; 407 } 408 409 e.selfAttendeeStatus = cEvents.getInt(PROJECTION_SELF_ATTENDEE_STATUS_INDEX); 410 return e; 411 } 412 413 /** 414 * Computes a position for each event. Each event is displayed 415 * as a non-overlapping rectangle. For normal events, these rectangles 416 * are displayed in separate columns in the week view and day view. For 417 * all-day events, these rectangles are displayed in separate rows along 418 * the top. In both cases, each event is assigned two numbers: N, and 419 * Max, that specify that this event is the Nth event of Max number of 420 * events that are displayed in a group. The width and position of each 421 * rectangle depend on the maximum number of rectangles that occur at 422 * the same time. 423 * 424 * @param eventsList the list of events, sorted into increasing time order 425 * @param minimumDurationMillis minimum duration acceptable as cell height of each event 426 * rectangle in millisecond. Should be 0 when it is not determined. 427 */ 428 /* package */ static void computePositions(ArrayList<Event> eventsList, 429 long minimumDurationMillis) { 430 if (eventsList == null) { 431 return; 432 } 433 434 // Compute the column positions separately for the all-day events 435 doComputePositions(eventsList, minimumDurationMillis, false); 436 doComputePositions(eventsList, minimumDurationMillis, true); 437 } 438 439 private static void doComputePositions(ArrayList<Event> eventsList, 440 long minimumDurationMillis, boolean doAlldayEvents) { 441 final ArrayList<Event> activeList = new ArrayList<Event>(); 442 final ArrayList<Event> groupList = new ArrayList<Event>(); 443 444 if (minimumDurationMillis < 0) { 445 minimumDurationMillis = 0; 446 } 447 448 long colMask = 0; 449 int maxCols = 0; 450 for (Event event : eventsList) { 451 // Process all-day events separately 452 if (event.drawAsAllday() != doAlldayEvents) 453 continue; 454 455 if (!doAlldayEvents) { 456 colMask = removeNonAlldayActiveEvents( 457 event, activeList.iterator(), minimumDurationMillis, colMask); 458 } else { 459 colMask = removeAlldayActiveEvents(event, activeList.iterator(), colMask); 460 } 461 462 // If the active list is empty, then reset the max columns, clear 463 // the column bit mask, and empty the groupList. 464 if (activeList.isEmpty()) { 465 for (Event ev : groupList) { 466 ev.setMaxColumns(maxCols); 467 } 468 maxCols = 0; 469 colMask = 0; 470 groupList.clear(); 471 } 472 473 // Find the first empty column. Empty columns are represented by 474 // zero bits in the column mask "colMask". 475 int col = findFirstZeroBit(colMask); 476 if (col == 64) 477 col = 63; 478 colMask |= (1L << col); 479 event.setColumn(col); 480 activeList.add(event); 481 groupList.add(event); 482 int len = activeList.size(); 483 if (maxCols < len) 484 maxCols = len; 485 } 486 for (Event ev : groupList) { 487 ev.setMaxColumns(maxCols); 488 } 489 } 490 491 private static long removeAlldayActiveEvents(Event event, Iterator<Event> iter, long colMask) { 492 // Remove the inactive allday events. An event on the active list 493 // becomes inactive when the end day is less than the current event's 494 // start day. 495 while (iter.hasNext()) { 496 final Event active = iter.next(); 497 if (active.endDay < event.startDay) { 498 colMask &= ~(1L << active.getColumn()); 499 iter.remove(); 500 } 501 } 502 return colMask; 503 } 504 505 private static long removeNonAlldayActiveEvents( 506 Event event, Iterator<Event> iter, long minDurationMillis, long colMask) { 507 long start = event.getStartMillis(); 508 // Remove the inactive events. An event on the active list 509 // becomes inactive when its end time is less than or equal to 510 // the current event's start time. 511 while (iter.hasNext()) { 512 final Event active = iter.next(); 513 514 final long duration = Math.max( 515 active.getEndMillis() - active.getStartMillis(), minDurationMillis); 516 if ((active.getStartMillis() + duration) <= start) { 517 colMask &= ~(1L << active.getColumn()); 518 iter.remove(); 519 } 520 } 521 return colMask; 522 } 523 524 public static int findFirstZeroBit(long val) { 525 for (int ii = 0; ii < 64; ++ii) { 526 if ((val & (1L << ii)) == 0) 527 return ii; 528 } 529 return 64; 530 } 531 532 public final void dump() { 533 Log.e("Cal", "+-----------------------------------------+"); 534 Log.e("Cal", "+ id = " + id); 535 Log.e("Cal", "+ color = " + color); 536 Log.e("Cal", "+ title = " + title); 537 Log.e("Cal", "+ location = " + location); 538 Log.e("Cal", "+ allDay = " + allDay); 539 Log.e("Cal", "+ startDay = " + startDay); 540 Log.e("Cal", "+ endDay = " + endDay); 541 Log.e("Cal", "+ startTime = " + startTime); 542 Log.e("Cal", "+ endTime = " + endTime); 543 Log.e("Cal", "+ organizer = " + organizer); 544 Log.e("Cal", "+ guestwrt = " + guestsCanModify); 545 } 546 547 public final boolean intersects(int julianDay, int startMinute, 548 int endMinute) { 549 if (endDay < julianDay) { 550 return false; 551 } 552 553 if (startDay > julianDay) { 554 return false; 555 } 556 557 if (endDay == julianDay) { 558 if (endTime < startMinute) { 559 return false; 560 } 561 // An event that ends at the start minute should not be considered 562 // as intersecting the given time span, but don't exclude 563 // zero-length (or very short) events. 564 if (endTime == startMinute 565 && (startTime != endTime || startDay != endDay)) { 566 return false; 567 } 568 } 569 570 if (startDay == julianDay && startTime > endMinute) { 571 return false; 572 } 573 574 return true; 575 } 576 577 /** 578 * Returns the event title and location separated by a comma. If the 579 * location is already part of the title (at the end of the title), then 580 * just the title is returned. 581 * 582 * @return the event title and location as a String 583 */ 584 public String getTitleAndLocation() { 585 String text = title.toString(); 586 587 // Append the location to the title, unless the title ends with the 588 // location (for example, "meeting in building 42" ends with the 589 // location). 590 if (location != null) { 591 String locationString = location.toString(); 592 if (!text.endsWith(locationString)) { 593 text += ", " + locationString; 594 } 595 } 596 return text; 597 } 598 599 public void setColumn(int column) { 600 mColumn = column; 601 } 602 603 public int getColumn() { 604 return mColumn; 605 } 606 607 public void setMaxColumns(int maxColumns) { 608 mMaxColumns = maxColumns; 609 } 610 611 public int getMaxColumns() { 612 return mMaxColumns; 613 } 614 615 public void setStartMillis(long startMillis) { 616 this.startMillis = startMillis; 617 } 618 619 public long getStartMillis() { 620 return startMillis; 621 } 622 623 public void setEndMillis(long endMillis) { 624 this.endMillis = endMillis; 625 } 626 627 public long getEndMillis() { 628 return endMillis; 629 } 630 631 public boolean drawAsAllday() { 632 // Use >= so we'll pick up Exchange allday events 633 return allDay || endMillis - startMillis >= DateUtils.DAY_IN_MILLIS; 634 } 635 } 636