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