EventInfoActivity.java revision 7d41eeb153cff835572229bc149a09376c7eddd8
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 17package com.android.calendar; 18 19import static android.provider.Calendar.EVENT_BEGIN_TIME; 20import static android.provider.Calendar.EVENT_END_TIME; 21import static android.provider.Calendar.AttendeesColumns.ATTENDEE_STATUS; 22 23import android.app.Activity; 24import android.content.ActivityNotFoundException; 25import android.content.AsyncQueryHandler; 26import android.content.ContentProviderOperation; 27import android.content.ContentResolver; 28import android.content.ContentUris; 29import android.content.ContentValues; 30import android.content.Context; 31import android.content.Intent; 32import android.content.OperationApplicationException; 33import android.content.SharedPreferences; 34import android.content.res.Resources; 35import android.database.Cursor; 36import android.graphics.PorterDuff; 37import android.graphics.Rect; 38import android.net.Uri; 39import android.os.Bundle; 40import android.os.RemoteException; 41import android.pim.ContactsAsyncHelper; 42import android.pim.EventRecurrence; 43import android.preference.PreferenceManager; 44import android.provider.Calendar; 45import android.provider.ContactsContract; 46import android.provider.Calendar.Attendees; 47import android.provider.Calendar.Calendars; 48import android.provider.Calendar.Events; 49import android.provider.Calendar.Reminders; 50import android.provider.ContactsContract.CommonDataKinds; 51import android.provider.ContactsContract.Contacts; 52import android.provider.ContactsContract.FastTrack; 53import android.provider.ContactsContract.Intents; 54import android.provider.ContactsContract.Presence; 55import android.provider.ContactsContract.CommonDataKinds.Email; 56import android.text.TextUtils; 57import android.text.format.DateFormat; 58import android.text.format.DateUtils; 59import android.text.format.Time; 60import android.text.util.Linkify; 61import android.text.util.Rfc822Token; 62import android.util.Log; 63import android.view.KeyEvent; 64import android.view.LayoutInflater; 65import android.view.Menu; 66import android.view.MenuItem; 67import android.view.MotionEvent; 68import android.view.View; 69import android.view.View.OnClickListener; 70import android.view.View.OnTouchListener; 71import android.widget.AdapterView; 72import android.widget.ArrayAdapter; 73import android.widget.ImageButton; 74import android.widget.ImageView; 75import android.widget.LinearLayout; 76import android.widget.Spinner; 77import android.widget.TextView; 78import android.widget.Toast; 79 80import java.util.ArrayList; 81import java.util.Arrays; 82import java.util.HashMap; 83import java.util.TimeZone; 84import java.util.regex.Pattern; 85 86public class EventInfoActivity extends Activity implements View.OnClickListener, 87 AdapterView.OnItemSelectedListener { 88 public static final boolean DEBUG = false; 89 90 public static final String TAG = "EventInfoActivity"; 91 92 private static final int MAX_REMINDERS = 5; 93 94 /** 95 * These are the corresponding indices into the array of strings 96 * "R.array.change_response_labels" in the resource file. 97 */ 98 static final int UPDATE_SINGLE = 0; 99 static final int UPDATE_ALL = 1; 100 101 private static final String[] EVENT_PROJECTION = new String[] { 102 Events._ID, // 0 do not remove; used in DeleteEventHelper 103 Events.TITLE, // 1 do not remove; used in DeleteEventHelper 104 Events.RRULE, // 2 do not remove; used in DeleteEventHelper 105 Events.ALL_DAY, // 3 do not remove; used in DeleteEventHelper 106 Events.CALENDAR_ID, // 4 do not remove; used in DeleteEventHelper 107 Events.DTSTART, // 5 do not remove; used in DeleteEventHelper 108 Events._SYNC_ID, // 6 do not remove; used in DeleteEventHelper 109 Events.EVENT_TIMEZONE, // 7 do not remove; used in DeleteEventHelper 110 Events.DESCRIPTION, // 8 111 Events.EVENT_LOCATION, // 9 112 Events.HAS_ALARM, // 10 113 Events.ACCESS_LEVEL, // 11 114 Events.COLOR, // 12 115 Events.GUESTS_CAN_MODIFY, // 13 116 // TODO Events.CAN_INVITE_OTHERS is broken. Investigate 117 Events.GUESTS_CAN_INVITE_OTHERS, // 14 118 Events.ORGANIZER, // 15 119 }; 120 private static final int EVENT_INDEX_ID = 0; 121 private static final int EVENT_INDEX_TITLE = 1; 122 private static final int EVENT_INDEX_RRULE = 2; 123 private static final int EVENT_INDEX_ALL_DAY = 3; 124 private static final int EVENT_INDEX_CALENDAR_ID = 4; 125 private static final int EVENT_INDEX_SYNC_ID = 6; 126 private static final int EVENT_INDEX_EVENT_TIMEZONE = 7; 127 private static final int EVENT_INDEX_DESCRIPTION = 8; 128 private static final int EVENT_INDEX_EVENT_LOCATION = 9; 129 private static final int EVENT_INDEX_HAS_ALARM = 10; 130 private static final int EVENT_INDEX_ACCESS_LEVEL = 11; 131 private static final int EVENT_INDEX_COLOR = 12; 132 private static final int EVENT_INDEX_GUESTS_CAN_MODIFY = 13; 133 private static final int EVENT_INDEX_CAN_INVITE_OTHERS = 14; 134 private static final int EVENT_INDEX_ORGANIZER = 15; 135 136 private static final String[] ATTENDEES_PROJECTION = new String[] { 137 Attendees._ID, // 0 138 Attendees.ATTENDEE_NAME, // 1 139 Attendees.ATTENDEE_EMAIL, // 2 140 Attendees.ATTENDEE_RELATIONSHIP, // 3 141 Attendees.ATTENDEE_STATUS, // 4 142 }; 143 private static final int ATTENDEES_INDEX_ID = 0; 144 private static final int ATTENDEES_INDEX_NAME = 1; 145 private static final int ATTENDEES_INDEX_EMAIL = 2; 146 private static final int ATTENDEES_INDEX_RELATIONSHIP = 3; 147 private static final int ATTENDEES_INDEX_STATUS = 4; 148 149 private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=%d"; 150 151 private static final String ATTENDEES_SORT_ORDER = Attendees.ATTENDEE_NAME + " ASC, " 152 + Attendees.ATTENDEE_EMAIL + " ASC"; 153 154 static final String[] CALENDARS_PROJECTION = new String[] { 155 Calendars._ID, // 0 156 Calendars.DISPLAY_NAME, // 1 157 Calendars.OWNER_ACCOUNT, // 2 158 }; 159 static final int CALENDARS_INDEX_DISPLAY_NAME = 1; 160 static final int CALENDARS_INDEX_OWNER_ACCOUNT = 2; 161 162 static final String CALENDARS_WHERE = Calendars._ID + "=%d"; 163 164 private static final String[] REMINDERS_PROJECTION = new String[] { 165 Reminders._ID, // 0 166 Reminders.MINUTES, // 1 167 }; 168 private static final int REMINDERS_INDEX_MINUTES = 1; 169 private static final String REMINDERS_WHERE = Reminders.EVENT_ID + "=%d AND (" + 170 Reminders.METHOD + "=" + Reminders.METHOD_ALERT + " OR " + Reminders.METHOD + "=" + 171 Reminders.METHOD_DEFAULT + ")"; 172 private static final String REMINDERS_SORT = Reminders.MINUTES; 173 174 private static final int MENU_GROUP_REMINDER = 1; 175 private static final int MENU_GROUP_EDIT = 2; 176 private static final int MENU_GROUP_DELETE = 3; 177 178 private static final int MENU_ADD_REMINDER = 1; 179 private static final int MENU_EDIT = 2; 180 private static final int MENU_DELETE = 3; 181 182 private static final int ATTENDEE_NO_RESPONSE = -1; 183 private static final int[] ATTENDEE_VALUES = { 184 ATTENDEE_NO_RESPONSE, 185 Attendees.ATTENDEE_STATUS_ACCEPTED, 186 Attendees.ATTENDEE_STATUS_TENTATIVE, 187 Attendees.ATTENDEE_STATUS_DECLINED, 188 }; 189 190 private LinearLayout mRemindersContainer; 191 private LinearLayout mOrganizerContainer; 192 private TextView mOrganizerView; 193 194 private Uri mUri; 195 private long mEventId; 196 private Cursor mEventCursor; 197 private Cursor mAttendeesCursor; 198 private Cursor mCalendarsCursor; 199 200 private long mStartMillis; 201 private long mEndMillis; 202 203 private long mCalendarOwnerAttendeeId = -1; 204 private String mCalendarOwnerAccount; 205 private boolean mCanModifyCalendar; 206 private boolean mIsBusyFreeCalendar; 207 private boolean mCanModifyEvent; 208 private int mNumOfAttendees; 209 private String mOrganizer; 210 211 private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>(); 212 private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0); 213 private ArrayList<Integer> mReminderValues; 214 private ArrayList<String> mReminderLabels; 215 private int mDefaultReminderMinutes; 216 217 private DeleteEventHelper mDeleteEventHelper; 218 private EditResponseHelper mEditResponseHelper; 219 220 private int mResponseOffset; 221 private int mOriginalAttendeeResponse; 222 private int mAttendeeResponseFromIntent = ATTENDEE_NO_RESPONSE; 223 private boolean mIsRepeating; 224 225 private Pattern mWildcardPattern = Pattern.compile("^.*$"); 226 private LayoutInflater mLayoutInflater; 227 private LinearLayout mReminderAdder; 228 229 // TODO This can be removed when the contacts content provider doesn't return duplicates 230 private int mUpdateCounts; 231 private static class ViewHolder { 232 ImageView avatar; 233 ImageView presence; 234 int updateCounts; 235 } 236 private HashMap<String, ViewHolder> mViewHolders = new HashMap<String, ViewHolder>(); 237 private PresenceQueryHandler mPresenceQueryHandler; 238 239 private static final Uri CONTACT_DATA_WITH_PRESENCE_URI = 240 Uri.withAppendedPath(ContactsContract.AUTHORITY_URI, "data_with_presence"); 241 242 int PRESENCE_PROJECTION_CONTACT_ID_INDEX = 0; 243 int PRESENCE_PROJECTION_PRESENCE_INDEX = 1; 244 int PRESENCE_PROJECTION_EMAIL_INDEX = 2; 245 int PRESENCE_PROJECTION_PHOTO_ID_INDEX = 3; 246 247 private static final String[] PRESENCE_PROJECTION = new String[] { 248 Email.CONTACT_ID, // 0 249 Email.PRESENCE_STATUS, // 1 250 Email.DATA, // 2 251 Email.PHOTO_ID, // 3 252 }; 253 254 ArrayList<Attendee> mAcceptedAttendees = new ArrayList<Attendee>(); 255 ArrayList<Attendee> mDeclinedAttendees = new ArrayList<Attendee>(); 256 ArrayList<Attendee> mTentativeAttendees = new ArrayList<Attendee>(); 257 private OnClickListener contactOnClickListener = new OnClickListener() { 258 private Rect getTargetRect(View anchor) { 259 final int[] location = new int[2]; 260 anchor.getLocationOnScreen(location); 261 262 final Rect rect = new Rect(); 263 rect.left = location[0]; 264 rect.top = location[1]; 265 rect.right = rect.left + anchor.getWidth(); 266 rect.bottom = rect.top + anchor.getHeight(); 267 return rect; 268 } 269 270 public void onClick(View avatar) { 271 final Rect target = getTargetRect(avatar); 272 View attendeeItem = (View) avatar.getParent(); 273 showContactInfo((Attendee) attendeeItem.getTag(), target); 274 } 275 }; 276 private int mColor; 277 278 // This is called when one of the "remove reminder" buttons is selected. 279 public void onClick(View v) { 280 LinearLayout reminderItem = (LinearLayout) v.getParent(); 281 LinearLayout parent = (LinearLayout) reminderItem.getParent(); 282 parent.removeView(reminderItem); 283 mReminderItems.remove(reminderItem); 284 updateRemindersVisibility(); 285 } 286 287 public void onItemSelected(AdapterView<?> parent, View v, int position, long id) { 288 // If they selected the "No response" option, then don't display the 289 // dialog asking which events to change. 290 if (id == 0 && mResponseOffset == 0) { 291 return; 292 } 293 294 // If this is not a repeating event, then don't display the dialog 295 // asking which events to change. 296 if (!mIsRepeating) { 297 return; 298 } 299 300 // If the selection is the same as the original, then don't display the 301 // dialog asking which events to change. 302 int index = findResponseIndexFor(mOriginalAttendeeResponse); 303 if (position == index + mResponseOffset) { 304 return; 305 } 306 307 // This is a repeating event. We need to ask the user if they mean to 308 // change just this one instance or all instances. 309 mEditResponseHelper.showDialog(mEditResponseHelper.getWhichEvents()); 310 } 311 312 public void onNothingSelected(AdapterView<?> parent) { 313 } 314 315 @Override 316 protected void onCreate(Bundle icicle) { 317 super.onCreate(icicle); 318 319 // Event cursor 320 Intent intent = getIntent(); 321 mUri = intent.getData(); 322 ContentResolver cr = getContentResolver(); 323 mStartMillis = intent.getLongExtra(EVENT_BEGIN_TIME, 0); 324 mEndMillis = intent.getLongExtra(EVENT_END_TIME, 0); 325 mAttendeeResponseFromIntent = intent.getIntExtra(ATTENDEE_STATUS, ATTENDEE_NO_RESPONSE); 326 mEventCursor = managedQuery(mUri, EVENT_PROJECTION, null, null); 327 if (initEventCursor()) { 328 // The cursor is empty. This can happen if the event was deleted. 329 finish(); 330 return; 331 } 332 333 setContentView(R.layout.event_info_activity); 334 335 // Attendees cursor 336 Uri uri = Attendees.CONTENT_URI; 337 String where = String.format(ATTENDEES_WHERE, mEventId); 338 mAttendeesCursor = managedQuery(uri, ATTENDEES_PROJECTION, where, ATTENDEES_SORT_ORDER); 339 340 // Calendars cursor 341 uri = Calendars.CONTENT_URI; 342 where = String.format(CALENDARS_WHERE, mEventCursor.getLong(EVENT_INDEX_CALENDAR_ID)); 343 mCalendarsCursor = managedQuery(uri, CALENDARS_PROJECTION, where, null); 344 mCalendarOwnerAccount = ""; 345 if (mCalendarsCursor != null) { 346 mCalendarsCursor.moveToFirst(); 347 mCalendarOwnerAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT); 348 } 349 350 String eventOrganizer = mEventCursor.getString(EVENT_INDEX_ORGANIZER); 351 mOrganizer = eventOrganizer; 352 mCanModifyCalendar = 353 mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) >= Calendars.CONTRIBUTOR_ACCESS; 354 mIsBusyFreeCalendar = 355 mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) == Calendars.FREEBUSY_ACCESS; 356 mCanModifyEvent = mCanModifyCalendar 357 && (mCalendarOwnerAccount.equals(eventOrganizer) 358 || mEventCursor.getInt(EVENT_INDEX_GUESTS_CAN_MODIFY) != 0); 359 360 // Initialize the reminder values array. 361 Resources r = getResources(); 362 String[] strings = r.getStringArray(R.array.reminder_minutes_values); 363 int size = strings.length; 364 ArrayList<Integer> list = new ArrayList<Integer>(size); 365 for (int i = 0 ; i < size ; i++) { 366 list.add(Integer.parseInt(strings[i])); 367 } 368 mReminderValues = list; 369 String[] labels = r.getStringArray(R.array.reminder_minutes_labels); 370 mReminderLabels = new ArrayList<String>(Arrays.asList(labels)); 371 372 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 373 String durationString = 374 prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0"); 375 mDefaultReminderMinutes = Integer.parseInt(durationString); 376 377 mRemindersContainer = (LinearLayout) findViewById(R.id.reminders_container); 378 mOrganizerContainer = (LinearLayout) findViewById(R.id.organizer_container); 379 mOrganizerView = (TextView) findViewById(R.id.organizer); 380 381 // Reminders cursor 382 boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0; 383 if (hasAlarm) { 384 uri = Reminders.CONTENT_URI; 385 where = String.format(REMINDERS_WHERE, mEventId); 386 Cursor reminderCursor = cr.query(uri, REMINDERS_PROJECTION, where, null, 387 REMINDERS_SORT); 388 try { 389 // First pass: collect all the custom reminder minutes (e.g., 390 // a reminder of 8 minutes) into a global list. 391 while (reminderCursor.moveToNext()) { 392 int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES); 393 EditEvent.addMinutesToList(this, mReminderValues, mReminderLabels, minutes); 394 } 395 396 // Second pass: create the reminder spinners 397 reminderCursor.moveToPosition(-1); 398 while (reminderCursor.moveToNext()) { 399 int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES); 400 mOriginalMinutes.add(minutes); 401 EditEvent.addReminder(this, this, mReminderItems, mReminderValues, 402 mReminderLabels, minutes); 403 } 404 } finally { 405 reminderCursor.close(); 406 } 407 } 408 409 updateView(); 410 411 // Setup the + Add Reminder Button 412 View.OnClickListener addReminderOnClickListener = new View.OnClickListener() { 413 public void onClick(View v) { 414 addReminder(); 415 } 416 }; 417 ImageButton reminderAddButton = (ImageButton) findViewById(R.id.reminder_add); 418 reminderAddButton.setOnClickListener(addReminderOnClickListener); 419 420 mReminderAdder = (LinearLayout) findViewById(R.id.reminder_adder); 421 updateRemindersVisibility(); 422 423 mDeleteEventHelper = new DeleteEventHelper(this, true /* exit when done */); 424 mEditResponseHelper = new EditResponseHelper(this); 425 426 mPresenceQueryHandler = new PresenceQueryHandler(this, cr); 427 mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 428 } 429 430 @Override 431 protected void onResume() { 432 super.onResume(); 433 if (initEventCursor()) { 434 // The cursor is empty. This can happen if the event was deleted. 435 finish(); 436 return; 437 } 438 initAttendeesCursor(); 439 initCalendarsCursor(); 440 updateResponse(); 441 updateTitle(); 442 } 443 444 private void updateTitle() { 445 Resources res = getResources(); 446 if (mCanModifyCalendar && mNumOfAttendees > 1) { 447 setTitle(res.getString(R.string.event_info_title_invite)); 448 } else { 449 setTitle(res.getString(R.string.event_info_title)); 450 } 451 } 452 453 /** 454 * Initializes the event cursor, which is expected to point to the first 455 * (and only) result from a query. 456 * @return true if the cursor is empty. 457 */ 458 private boolean initEventCursor() { 459 if ((mEventCursor == null) || (mEventCursor.getCount() == 0)) { 460 return true; 461 } 462 mEventCursor.moveToFirst(); 463 mEventId = mEventCursor.getInt(EVENT_INDEX_ID); 464 String rRule = mEventCursor.getString(EVENT_INDEX_RRULE); 465 mIsRepeating = (rRule != null); 466 return false; 467 } 468 469 private static class Attendee { 470 String mName; 471 String mEmail; 472 473 Attendee(String name, String email) { 474 mName = name; 475 mEmail = email; 476 } 477 } 478 479 private void initAttendeesCursor() { 480 mOriginalAttendeeResponse = ATTENDEE_NO_RESPONSE; 481 mCalendarOwnerAttendeeId = -1; 482 mNumOfAttendees = 0; 483 if (mAttendeesCursor != null) { 484 mNumOfAttendees = mAttendeesCursor.getCount(); 485 if (mAttendeesCursor.moveToFirst()) { 486 mAcceptedAttendees.clear(); 487 mDeclinedAttendees.clear(); 488 mTentativeAttendees.clear(); 489 490 do { 491 int status = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS); 492 String name = mAttendeesCursor.getString(ATTENDEES_INDEX_NAME); 493 String email = mAttendeesCursor.getString(ATTENDEES_INDEX_EMAIL); 494 495 if (mAttendeesCursor.getInt(ATTENDEES_INDEX_RELATIONSHIP) == 496 Attendees.RELATIONSHIP_ORGANIZER) { 497 // Overwrites the one from Event table if available 498 if (name != null && name.length() > 0) { 499 mOrganizer = name; 500 } else if (email != null && email.length() > 0) { 501 mOrganizer = email; 502 } 503 } 504 505 if (mCalendarOwnerAttendeeId == -1 && mCalendarOwnerAccount.equals(email)) { 506 mCalendarOwnerAttendeeId = mAttendeesCursor.getInt(ATTENDEES_INDEX_ID); 507 mOriginalAttendeeResponse = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS); 508 } 509 510 switch(status) { 511 case Attendees.ATTENDEE_STATUS_ACCEPTED: 512 mAcceptedAttendees.add(new Attendee(name, email)); 513 break; 514 case Attendees.ATTENDEE_STATUS_DECLINED: 515 mDeclinedAttendees.add(new Attendee(name, email)); 516 break; 517 default: 518 mTentativeAttendees.add(new Attendee(name, email)); 519 } 520 } while (mAttendeesCursor.moveToNext()); 521 mAttendeesCursor.moveToFirst(); 522 523 updateAttendees(); 524 } 525 } 526 if (mNumOfAttendees > 1) { 527 mOrganizerContainer.setVisibility(View.VISIBLE); 528 mOrganizerView.setText(mOrganizer); 529 } else { 530 mOrganizerContainer.setVisibility(View.GONE); 531 } 532 } 533 534 private void initCalendarsCursor() { 535 if (mCalendarsCursor != null) { 536 mCalendarsCursor.moveToFirst(); 537 } 538 } 539 540 @Override 541 public void onPause() { 542 super.onPause(); 543 if (!isFinishing()) { 544 return; 545 } 546 ContentResolver cr = getContentResolver(); 547 ArrayList<Integer> reminderMinutes = EditEvent.reminderItemsToMinutes(mReminderItems, 548 mReminderValues); 549 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(3); 550 boolean changed = EditEvent.saveReminders(ops, mEventId, reminderMinutes, mOriginalMinutes, 551 false /* no force save */); 552 try { 553 cr.applyBatch(Calendars.CONTENT_URI.getAuthority(), ops); 554 } catch (RemoteException e) { 555 // TODO Auto-generated catch block 556 e.printStackTrace(); 557 } catch (OperationApplicationException e) { 558 // TODO Auto-generated catch block 559 e.printStackTrace(); 560 } 561 562 changed |= saveResponse(cr); 563 if (changed) { 564 Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show(); 565 } 566 } 567 568 @Override 569 public boolean onCreateOptionsMenu(Menu menu) { 570 MenuItem item; 571 item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0, 572 R.string.add_new_reminder); 573 item.setIcon(R.drawable.ic_menu_reminder); 574 item.setAlphabeticShortcut('r'); 575 576 item = menu.add(MENU_GROUP_EDIT, MENU_EDIT, 0, R.string.edit_event_label); 577 item.setIcon(android.R.drawable.ic_menu_edit); 578 item.setAlphabeticShortcut('e'); 579 580 item = menu.add(MENU_GROUP_DELETE, MENU_DELETE, 0, R.string.delete_event_label); 581 item.setIcon(android.R.drawable.ic_menu_delete); 582 583 return super.onCreateOptionsMenu(menu); 584 } 585 586 @Override 587 public boolean onPrepareOptionsMenu(Menu menu) { 588 boolean canAddReminders = canAddReminders(); 589 menu.setGroupVisible(MENU_GROUP_REMINDER, canAddReminders); 590 menu.setGroupEnabled(MENU_GROUP_REMINDER, canAddReminders); 591 592 menu.setGroupVisible(MENU_GROUP_EDIT, mCanModifyEvent); 593 menu.setGroupEnabled(MENU_GROUP_EDIT, mCanModifyEvent); 594 menu.setGroupVisible(MENU_GROUP_DELETE, mCanModifyCalendar); 595 menu.setGroupEnabled(MENU_GROUP_DELETE, mCanModifyCalendar); 596 597 return super.onPrepareOptionsMenu(menu); 598 } 599 600 private boolean canAddReminders() { 601 return !mIsBusyFreeCalendar && mReminderItems.size() < MAX_REMINDERS; 602 } 603 604 private void addReminder() { 605 // TODO: when adding a new reminder, make it different from the 606 // last one in the list (if any). 607 if (mDefaultReminderMinutes == 0) { 608 EditEvent.addReminder(this, this, mReminderItems, 609 mReminderValues, mReminderLabels, 10 /* minutes */); 610 } else { 611 EditEvent.addReminder(this, this, mReminderItems, 612 mReminderValues, mReminderLabels, mDefaultReminderMinutes); 613 } 614 updateRemindersVisibility(); 615 } 616 617 @Override 618 public boolean onOptionsItemSelected(MenuItem item) { 619 super.onOptionsItemSelected(item); 620 switch (item.getItemId()) { 621 case MENU_ADD_REMINDER: 622 addReminder(); 623 break; 624 case MENU_EDIT: 625 doEdit(); 626 break; 627 case MENU_DELETE: 628 doDelete(); 629 break; 630 } 631 return true; 632 } 633 634 @Override 635 public boolean onKeyDown(int keyCode, KeyEvent event) { 636 if (keyCode == KeyEvent.KEYCODE_DEL) { 637 doDelete(); 638 return true; 639 } 640 return super.onKeyDown(keyCode, event); 641 } 642 643 private void updateRemindersVisibility() { 644 if (mIsBusyFreeCalendar) { 645 mRemindersContainer.setVisibility(View.GONE); 646 } else { 647 mRemindersContainer.setVisibility(View.VISIBLE); 648 mReminderAdder.setVisibility(canAddReminders() ? View.VISIBLE : View.GONE); 649 } 650 } 651 652 /** 653 * Saves the response to an invitation if the user changed the response. 654 * Returns true if the database was updated. 655 * 656 * @param cr the ContentResolver 657 * @return true if the database was changed 658 */ 659 private boolean saveResponse(ContentResolver cr) { 660 if (mAttendeesCursor == null || mEventCursor == null) { 661 return false; 662 } 663 Spinner spinner = (Spinner) findViewById(R.id.response_value); 664 int position = spinner.getSelectedItemPosition() - mResponseOffset; 665 if (position <= 0) { 666 return false; 667 } 668 669 int status = ATTENDEE_VALUES[position]; 670 671 // If the status has not changed, then don't update the database 672 if (status == mOriginalAttendeeResponse) { 673 return false; 674 } 675 676 if (!mIsRepeating) { 677 // This is a non-repeating event 678 updateResponse(cr, mEventId, mCalendarOwnerAttendeeId, status); 679 return true; 680 } 681 682 // This is a repeating event 683 int whichEvents = mEditResponseHelper.getWhichEvents(); 684 switch (whichEvents) { 685 case -1: 686 return false; 687 case UPDATE_SINGLE: 688 createExceptionResponse(cr, mEventId, mCalendarOwnerAttendeeId, status); 689 return true; 690 case UPDATE_ALL: 691 updateResponse(cr, mEventId, mCalendarOwnerAttendeeId, status); 692 return true; 693 default: 694 Log.e("Calendar", "Unexpected choice for updating invitation response"); 695 break; 696 } 697 return false; 698 } 699 700 private void updateResponse(ContentResolver cr, long eventId, long attendeeId, int status) { 701 // Update the "selfAttendeeStatus" field for the event 702 ContentValues values = new ContentValues(); 703 704 // Will need to add email when MULTIPLE_ATTENDEES_PER_EVENT supported. 705 values.put(Attendees.ATTENDEE_STATUS, status); 706 values.put(Attendees.EVENT_ID, eventId); 707 708 Uri uri = ContentUris.withAppendedId(Attendees.CONTENT_URI, attendeeId); 709 cr.update(uri, values, null /* where */, null /* selection args */); 710 } 711 712 private void createExceptionResponse(ContentResolver cr, long eventId, 713 long attendeeId, int status) { 714 // Fetch information about the repeating event. 715 Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId); 716 Cursor cursor = cr.query(uri, EVENT_PROJECTION, null, null, null); 717 if (cursor == null) { 718 return; 719 } 720 721 try { 722 cursor.moveToFirst(); 723 ContentValues values = new ContentValues(); 724 725 String title = cursor.getString(EVENT_INDEX_TITLE); 726 String timezone = cursor.getString(EVENT_INDEX_EVENT_TIMEZONE); 727 int calendarId = cursor.getInt(EVENT_INDEX_CALENDAR_ID); 728 boolean allDay = cursor.getInt(EVENT_INDEX_ALL_DAY) != 0; 729 String syncId = cursor.getString(EVENT_INDEX_SYNC_ID); 730 731 values.put(Events.TITLE, title); 732 values.put(Events.EVENT_TIMEZONE, timezone); 733 values.put(Events.ALL_DAY, allDay ? 1 : 0); 734 values.put(Events.CALENDAR_ID, calendarId); 735 values.put(Events.DTSTART, mStartMillis); 736 values.put(Events.DTEND, mEndMillis); 737 values.put(Events.ORIGINAL_EVENT, syncId); 738 values.put(Events.ORIGINAL_INSTANCE_TIME, mStartMillis); 739 values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0); 740 values.put(Events.STATUS, Events.STATUS_CONFIRMED); 741 values.put(Events.SELF_ATTENDEE_STATUS, status); 742 743 // Create a recurrence exception 744 cr.insert(Events.CONTENT_URI, values); 745 } finally { 746 cursor.close(); 747 } 748 } 749 750 private int findResponseIndexFor(int response) { 751 int size = ATTENDEE_VALUES.length; 752 for (int index = 0; index < size; index++) { 753 if (ATTENDEE_VALUES[index] == response) { 754 return index; 755 } 756 } 757 return 0; 758 } 759 760 private void doEdit() { 761 Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId); 762 Intent intent = new Intent(Intent.ACTION_EDIT, uri); 763 intent.putExtra(Calendar.EVENT_BEGIN_TIME, mStartMillis); 764 intent.putExtra(Calendar.EVENT_END_TIME, mEndMillis); 765 intent.setClass(EventInfoActivity.this, EditEvent.class); 766 startActivity(intent); 767 finish(); 768 } 769 770 private void doDelete() { 771 mDeleteEventHelper.delete(mStartMillis, mEndMillis, mEventCursor, -1); 772 } 773 774 private void updateView() { 775 if (mEventCursor == null) { 776 return; 777 } 778 Resources res = getResources(); 779 780 String eventName = mEventCursor.getString(EVENT_INDEX_TITLE); 781 if (eventName == null || eventName.length() == 0) { 782 eventName = res.getString(R.string.no_title_label); 783 } 784 785 boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0; 786 String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION); 787 String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION); 788 String rRule = mEventCursor.getString(EVENT_INDEX_RRULE); 789 boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0; 790 String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE); 791 mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff; 792 793 View calBackground = findViewById(R.id.cal_background); 794 calBackground.setBackgroundColor(mColor); 795 796 TextView title = (TextView) findViewById(R.id.title); 797 title.setTextColor(mColor); 798 799 View divider = findViewById(R.id.divider); 800 divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN); 801 802 // What 803 if (eventName != null) { 804 setTextCommon(R.id.title, eventName); 805 } 806 807 // When 808 String when; 809 int flags; 810 if (allDay) { 811 flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE; 812 } else { 813 flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE; 814 if (DateFormat.is24HourFormat(this)) { 815 flags |= DateUtils.FORMAT_24HOUR; 816 } 817 } 818 when = DateUtils.formatDateRange(this, mStartMillis, mEndMillis, flags); 819 setTextCommon(R.id.when, when); 820 821 // Show the event timezone if it is different from the local timezone 822 Time time = new Time(); 823 String localTimezone = time.timezone; 824 if (allDay) { 825 localTimezone = Time.TIMEZONE_UTC; 826 } 827 if (eventTimezone != null && !localTimezone.equals(eventTimezone) && !allDay) { 828 String displayName; 829 TimeZone tz = TimeZone.getTimeZone(localTimezone); 830 if (tz == null || tz.getID().equals("GMT")) { 831 displayName = localTimezone; 832 } else { 833 displayName = tz.getDisplayName(); 834 } 835 836 setTextCommon(R.id.timezone, displayName); 837 } else { 838 setVisibilityCommon(R.id.timezone_container, View.GONE); 839 } 840 841 // Repeat 842 if (rRule != null) { 843 EventRecurrence eventRecurrence = new EventRecurrence(); 844 eventRecurrence.parse(rRule); 845 Time date = new Time(); 846 if (allDay) { 847 date.timezone = Time.TIMEZONE_UTC; 848 } 849 date.set(mStartMillis); 850 eventRecurrence.setStartDate(date); 851 String repeatString = eventRecurrence.getRepeatString(); 852 setTextCommon(R.id.repeat, repeatString); 853 } else { 854 setVisibilityCommon(R.id.repeat_container, View.GONE); 855 } 856 857 // Where 858 if (location == null || location.length() == 0) { 859 setVisibilityCommon(R.id.where, View.GONE); 860 } else { 861 final TextView textView = (TextView) findViewById(R.id.where); 862 if (textView != null) { 863 textView.setAutoLinkMask(0); 864 textView.setText(location); 865 Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q="); 866 textView.setOnTouchListener(new OnTouchListener() { 867 public boolean onTouch(View v, MotionEvent event) { 868 try { 869 return v.onTouchEvent(event); 870 } catch (ActivityNotFoundException e) { 871 // ignore 872 return true; 873 } 874 } 875 }); 876 } 877 } 878 879 // Description 880 if (description == null || description.length() == 0) { 881 setVisibilityCommon(R.id.description, View.GONE); 882 } else { 883 setTextCommon(R.id.description, description); 884 } 885 886 // Calendar 887 if (mCalendarsCursor != null) { 888 String calendarName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME); 889 setTextCommon(R.id.calendar, calendarName); 890 } else { 891 setVisibilityCommon(R.id.calendar_container, View.GONE); 892 } 893 } 894 895 private void updateAttendees() { 896 CharSequence[] entries; 897 entries = getResources().getTextArray(R.array.response_labels2); 898 LinearLayout attendeesLayout = (LinearLayout) findViewById(R.id.attendee_list); 899 attendeesLayout.removeAllViewsInLayout(); 900 ++mUpdateCounts; 901 addAttendeesToLayout(mAcceptedAttendees, attendeesLayout, entries[0]); 902 addAttendeesToLayout(mDeclinedAttendees, attendeesLayout, entries[2]); 903 addAttendeesToLayout(mTentativeAttendees, attendeesLayout, entries[1]); 904 } 905 906 private void addAttendeesToLayout(ArrayList<Attendee> attendees, LinearLayout attendeeList, 907 CharSequence sectionTitle) { 908 if (attendees.size() == 0) { 909 return; 910 } 911 912 ContentResolver cr = getContentResolver(); 913 // Yes/No/Maybe Title 914 View titleView = mLayoutInflater.inflate(R.layout.contact_item, null); 915 titleView.findViewById(R.id.avatar).setVisibility(View.GONE); 916 View divider = titleView.findViewById(R.id.separator); 917 divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN); 918 919 TextView title = (TextView) titleView.findViewById(R.id.name); 920 title.setText(getString(R.string.response_label, sectionTitle, attendees.size())); 921 title.setTextAppearance(this, R.style.TextAppearance_EventInfo_Label); 922 attendeeList.addView(titleView); 923 924 // Attendees 925 int numOfAttendees = attendees.size(); 926 StringBuilder selection = new StringBuilder(Email.DATA + " IN ("); 927 String[] selectionArgs = new String[numOfAttendees]; 928 929 for (int i = 0; i < numOfAttendees; ++i) { 930 Attendee attendee = attendees.get(i); 931 selectionArgs[i] = attendee.mEmail; 932 933 View v = mLayoutInflater.inflate(R.layout.contact_item, null); 934 v.setTag(attendee); 935 936 View separator = v.findViewById(R.id.separator); 937 separator.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN); 938 939 // Text 940 TextView tv = (TextView) v.findViewById(R.id.name); 941 String name = attendee.mName; 942 if (name == null || name.length() == 0) { 943 name = attendee.mEmail; 944 } 945 tv.setText(name); 946 947 ViewHolder vh = new ViewHolder(); 948 vh.avatar = (ImageView) v.findViewById(R.id.avatar); 949 vh.avatar.setOnClickListener(contactOnClickListener); 950 vh.presence = (ImageView) v.findViewById(R.id.presence); 951 mViewHolders.put(attendee.mEmail, vh); 952 953 if (i == 0) { 954 selection.append('?'); 955 } else { 956 selection.append(", ?"); 957 } 958 959 attendeeList.addView(v); 960 } 961 selection.append(')'); 962 963 mPresenceQueryHandler.startQuery(mUpdateCounts, attendees, CONTACT_DATA_WITH_PRESENCE_URI, 964 PRESENCE_PROJECTION, selection.toString(), selectionArgs, null); 965 } 966 967 private class PresenceQueryHandler extends AsyncQueryHandler { 968 Context mContext; 969 ContentResolver mContentResolver; 970 971 public PresenceQueryHandler(Context context, ContentResolver cr) { 972 super(cr); 973 mContentResolver = cr; 974 mContext = context; 975 } 976 977 @Override 978 protected void onQueryComplete(int queryIndex, Object cookie, Cursor cursor) { 979 if (cursor == null) { 980 if (DEBUG) { 981 Log.e(TAG, "onQueryComplete: cursor == null"); 982 } 983 return; 984 } 985 986 try { 987 988 cursor.moveToPosition(-1); 989 while (cursor.moveToNext()) { 990 String email = cursor.getString(PRESENCE_PROJECTION_EMAIL_INDEX); 991 int contactId = cursor.getInt(PRESENCE_PROJECTION_CONTACT_ID_INDEX); 992 ViewHolder vh = mViewHolders.get(email); 993 int photoId = cursor.getInt(PRESENCE_PROJECTION_PHOTO_ID_INDEX); 994 if (DEBUG) { 995 Log.e(TAG, "onQueryComplete Id: " + contactId + " PhotoId: " + photoId 996 + " Email: " + email); 997 } 998 if (vh == null) { 999 continue; 1000 } 1001 ImageView presenceView = vh.presence; 1002 if (presenceView != null) { 1003 int status = cursor.getInt(PRESENCE_PROJECTION_PRESENCE_INDEX); 1004 presenceView.setImageResource(Presence.getPresenceIconResourceId(status)); 1005 presenceView.setVisibility(View.VISIBLE); 1006 } 1007 1008 if (photoId > 0 && vh.updateCounts < queryIndex) { 1009 vh.updateCounts = queryIndex; 1010 Uri personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); 1011 ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext, vh.avatar, 1012 personUri, R.drawable.ic_contact_picture); 1013 } 1014 } 1015 } finally { 1016 cursor.close(); 1017 } 1018 } 1019 } 1020 1021 void updateResponse() { 1022 if (!mCanModifyCalendar || mNumOfAttendees <= 1) { 1023 setVisibilityCommon(R.id.response_container, View.GONE); 1024 return; 1025 } 1026 1027 setVisibilityCommon(R.id.response_container, View.VISIBLE); 1028 1029 Spinner spinner = (Spinner) findViewById(R.id.response_value); 1030 1031 mResponseOffset = 0; 1032 1033 /* If the user has previously responded to this event 1034 * we should not allow them to select no response again. 1035 * Switch the entries to a set of entries without the 1036 * no response option. 1037 */ 1038 if ((mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_INVITED) 1039 && (mOriginalAttendeeResponse != ATTENDEE_NO_RESPONSE) 1040 && (mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_NONE)) { 1041 CharSequence[] entries; 1042 entries = getResources().getTextArray(R.array.response_labels2); 1043 mResponseOffset = -1; 1044 ArrayAdapter<CharSequence> adapter = 1045 new ArrayAdapter<CharSequence>(this, 1046 android.R.layout.simple_spinner_item, entries); 1047 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 1048 spinner.setAdapter(adapter); 1049 } 1050 1051 int index; 1052 if (mAttendeeResponseFromIntent != ATTENDEE_NO_RESPONSE) { 1053 index = findResponseIndexFor(mAttendeeResponseFromIntent); 1054 } else { 1055 index = findResponseIndexFor(mOriginalAttendeeResponse); 1056 } 1057 spinner.setSelection(index + mResponseOffset); 1058 spinner.setOnItemSelectedListener(this); 1059 } 1060 1061 private void setTextCommon(int id, CharSequence text) { 1062 TextView textView = (TextView) findViewById(id); 1063 if (textView == null) 1064 return; 1065 textView.setText(text); 1066 } 1067 1068 private void setVisibilityCommon(int id, int visibility) { 1069 View v = findViewById(id); 1070 if (v != null) { 1071 v.setVisibility(visibility); 1072 } 1073 return; 1074 } 1075 1076 /** 1077 * Taken from com.google.android.gm.HtmlConversationActivity 1078 * 1079 * Send the intent that shows the Contact info corresponding to the email address. 1080 */ 1081 public void showContactInfo(Attendee attendee, Rect rect) { 1082 // First perform lookup query to find existing contact 1083 final ContentResolver resolver = getContentResolver(); 1084 final String address = attendee.mEmail; 1085 final Uri dataUri = Uri.withAppendedPath(CommonDataKinds.Email.CONTENT_FILTER_URI, 1086 Uri.encode(address)); 1087 final Uri lookupUri = ContactsContract.Data.getContactLookupUri(resolver, dataUri); 1088 1089 if (lookupUri != null) { 1090 // Found matching contact, trigger FastTrack 1091 FastTrack.showFastTrack(this, rect, lookupUri, FastTrack.MODE_MEDIUM, null); 1092 } else { 1093 // No matching contact, ask user to create one 1094 final Uri mailUri = Uri.fromParts("mailto", address, null); 1095 final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, mailUri); 1096 1097 // Pass along full E-mail string for possible create dialog 1098 Rfc822Token sender = new Rfc822Token(attendee.mName, attendee.mEmail, null); 1099 intent.putExtra(Intents.EXTRA_CREATE_DESCRIPTION, sender.toString()); 1100 1101 // Only provide personal name hint if we have one 1102 final String senderPersonal = attendee.mName; 1103 if (!TextUtils.isEmpty(senderPersonal)) { 1104 intent.putExtra(Intents.Insert.NAME, senderPersonal); 1105 } 1106 1107 startActivity(intent); 1108 } 1109 } 1110} 1111