2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.calendar;
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;
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.EventRecurrence;
42 import android.preference.PreferenceManager;
43 import android.provider.Calendar;
44 import android.provider.ContactsContract;
45 import android.provider.Calendar.Attendees;
46 import android.provider.Calendar.Calendars;
47 import android.provider.Calendar.Events;
48 import android.provider.Calendar.Reminders;
49 import android.provider.ContactsContract.CommonDataKinds;
50 import android.provider.ContactsContract.Contacts;
51 import android.provider.ContactsContract.Data;
52 import android.provider.ContactsContract.Intents;
53 import android.provider.ContactsContract.Presence;
54 import android.provider.ContactsContract.QuickContact;
55 import android.provider.ContactsContract.CommonDataKinds.Email;
56 import android.text.TextUtils;
57 import android.text.format.DateFormat;
58 import android.text.format.DateUtils;
59 import android.text.format.Time;
60 import android.text.util.Linkify;
61 import android.text.util.Rfc822Token;
62 import android.util.Log;
63 import android.view.KeyEvent;
64 import android.view.LayoutInflater;
65 import android.view.Menu;
66 import android.view.MenuItem;
67 import android.view.MotionEvent;
68 import android.view.View;
69 import android.view.View.OnTouchListener;
70 import android.widget.AdapterView;
71 import android.widget.ArrayAdapter;
72 import android.widget.ImageButton;
73 import android.widget.ImageView;
74 import android.widget.LinearLayout;
75 import android.widget.QuickContactBadge;
76 import android.widget.Spinner;
77 import android.widget.TextView;
78 import android.widget.Toast;
80 import java.util.ArrayList;
81 import java.util.Arrays;
82 import java.util.HashMap;
83 import java.util.TimeZone;
84 import java.util.regex.Pattern;
86 public class EventInfoActivity extends Activity implements View.OnClickListener,
87 AdapterView.OnItemSelectedListener {
88 public static final boolean DEBUG = false;
90 public static final String TAG = "EventInfoActivity";
92 private static final int MAX_REMINDERS = 5;
95 * These are the corresponding indices into the array of strings
96 * "R.array.change_response_labels" in the resource file.
98 static final int UPDATE_SINGLE = 0;
99 static final int UPDATE_ALL = 1;
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
115 Events.HAS_ATTENDEE_DATA, // 13
116 Events.GUESTS_CAN_MODIFY, // 14
117 // TODO Events.GUESTS_CAN_INVITE_OTHERS has not been implemented in calendar provider
118 Events.GUESTS_CAN_INVITE_OTHERS, // 15
119 Events.ORGANIZER, // 16
121 private static final int EVENT_INDEX_ID = 0;
122 private static final int EVENT_INDEX_TITLE = 1;
123 private static final int EVENT_INDEX_RRULE = 2;
124 private static final int EVENT_INDEX_ALL_DAY = 3;
125 private static final int EVENT_INDEX_CALENDAR_ID = 4;
126 private static final int EVENT_INDEX_SYNC_ID = 6;
127 private static final int EVENT_INDEX_EVENT_TIMEZONE = 7;
128 private static final int EVENT_INDEX_DESCRIPTION = 8;
129 private static final int EVENT_INDEX_EVENT_LOCATION = 9;
130 private static final int EVENT_INDEX_HAS_ALARM = 10;
131 private static final int EVENT_INDEX_ACCESS_LEVEL = 11;
132 private static final int EVENT_INDEX_COLOR = 12;
133 private static final int EVENT_INDEX_HAS_ATTENDEE_DATA = 13;
134 private static final int EVENT_INDEX_GUESTS_CAN_MODIFY = 14;
135 private static final int EVENT_INDEX_CAN_INVITE_OTHERS = 15;
136 private static final int EVENT_INDEX_ORGANIZER = 16;
138 private static final String[] ATTENDEES_PROJECTION = new String[] {
140 Attendees.ATTENDEE_NAME, // 1
141 Attendees.ATTENDEE_EMAIL, // 2
142 Attendees.ATTENDEE_RELATIONSHIP, // 3
143 Attendees.ATTENDEE_STATUS, // 4
145 private static final int ATTENDEES_INDEX_ID = 0;
146 private static final int ATTENDEES_INDEX_NAME = 1;
147 private static final int ATTENDEES_INDEX_EMAIL = 2;
148 private static final int ATTENDEES_INDEX_RELATIONSHIP = 3;
149 private static final int ATTENDEES_INDEX_STATUS = 4;
151 private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=%d";
153 private static final String ATTENDEES_SORT_ORDER = Attendees.ATTENDEE_NAME + " ASC, "
154 + Attendees.ATTENDEE_EMAIL + " ASC";
156 static final String[] CALENDARS_PROJECTION = new String[] {
158 Calendars.DISPLAY_NAME, // 1
159 Calendars.OWNER_ACCOUNT, // 2
161 static final int CALENDARS_INDEX_DISPLAY_NAME = 1;
162 static final int CALENDARS_INDEX_OWNER_ACCOUNT = 2;
164 static final String CALENDARS_WHERE = Calendars._ID + "=%d";
166 private static final String[] REMINDERS_PROJECTION = new String[] {
168 Reminders.MINUTES, // 1
170 private static final int REMINDERS_INDEX_MINUTES = 1;
171 private static final String REMINDERS_WHERE = Reminders.EVENT_ID + "=%d AND (" +
172 Reminders.METHOD + "=" + Reminders.METHOD_ALERT + " OR " + Reminders.METHOD + "=" +
173 Reminders.METHOD_DEFAULT + ")";
174 private static final String REMINDERS_SORT = Reminders.MINUTES;
176 private static final int MENU_GROUP_REMINDER = 1;
177 private static final int MENU_GROUP_EDIT = 2;
178 private static final int MENU_GROUP_DELETE = 3;
180 private static final int MENU_ADD_REMINDER = 1;
181 private static final int MENU_EDIT = 2;
182 private static final int MENU_DELETE = 3;
184 private static final int ATTENDEE_NO_RESPONSE = -1;
185 private static final int[] ATTENDEE_VALUES = {
186 ATTENDEE_NO_RESPONSE,
187 Attendees.ATTENDEE_STATUS_ACCEPTED,
188 Attendees.ATTENDEE_STATUS_TENTATIVE,
189 Attendees.ATTENDEE_STATUS_DECLINED,
192 private LinearLayout mRemindersContainer;
193 private LinearLayout mOrganizerContainer;
194 private TextView mOrganizerView;
197 private long mEventId;
198 private Cursor mEventCursor;
199 private Cursor mAttendeesCursor;
200 private Cursor mCalendarsCursor;
202 private long mStartMillis;
203 private long mEndMillis;
205 private boolean mHasAttendeeData;
206 private boolean mIsOrganizer;
207 private long mCalendarOwnerAttendeeId = -1;
208 private String mCalendarOwnerAccount;
209 private boolean mCanModifyCalendar;
210 private boolean mIsBusyFreeCalendar;
211 private boolean mCanModifyEvent;
212 private int mNumOfAttendees;
213 private String mOrganizer;
215 private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>();
216 private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0);
217 private ArrayList<Integer> mReminderValues;
218 private ArrayList<String> mReminderLabels;
219 private int mDefaultReminderMinutes;
221 private DeleteEventHelper mDeleteEventHelper;
222 private EditResponseHelper mEditResponseHelper;
224 private int mResponseOffset;
225 private int mOriginalAttendeeResponse;
226 private int mAttendeeResponseFromIntent = ATTENDEE_NO_RESPONSE;
227 private boolean mIsRepeating;
229 private Pattern mWildcardPattern = Pattern.compile("^.*$");
230 private LayoutInflater mLayoutInflater;
231 private LinearLayout mReminderAdder;
233 // TODO This can be removed when the contacts content provider doesn't return duplicates
234 private int mUpdateCounts;
235 private static class ViewHolder {
236 QuickContactBadge badge;
240 private HashMap<String, ViewHolder> mViewHolders = new HashMap<String, ViewHolder>();
241 private PresenceQueryHandler mPresenceQueryHandler;
243 private static final Uri CONTACT_DATA_WITH_PRESENCE_URI = Data.CONTENT_URI;
245 int PRESENCE_PROJECTION_CONTACT_ID_INDEX = 0;
246 int PRESENCE_PROJECTION_PRESENCE_INDEX = 1;
247 int PRESENCE_PROJECTION_EMAIL_INDEX = 2;
248 int PRESENCE_PROJECTION_PHOTO_ID_INDEX = 3;
250 private static final String[] PRESENCE_PROJECTION = new String[] {
251 Email.CONTACT_ID, // 0
252 Email.CONTACT_PRESENCE, // 1
257 ArrayList<Attendee> mAcceptedAttendees = new ArrayList<Attendee>();
258 ArrayList<Attendee> mDeclinedAttendees = new ArrayList<Attendee>();
259 ArrayList<Attendee> mTentativeAttendees = new ArrayList<Attendee>();
262 // This is called when one of the "remove reminder" buttons is selected.
263 public void onClick(View v) {
264 LinearLayout reminderItem = (LinearLayout) v.getParent();
265 LinearLayout parent = (LinearLayout) reminderItem.getParent();
266 parent.removeView(reminderItem);
267 mReminderItems.remove(reminderItem);
268 updateRemindersVisibility();
271 public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
272 // If they selected the "No response" option, then don't display the
273 // dialog asking which events to change.
274 if (id == 0 && mResponseOffset == 0) {
278 // If this is not a repeating event, then don't display the dialog
279 // asking which events to change.
284 // If the selection is the same as the original, then don't display the
285 // dialog asking which events to change.
286 int index = findResponseIndexFor(mOriginalAttendeeResponse);
287 if (position == index + mResponseOffset) {
291 // This is a repeating event. We need to ask the user if they mean to
292 // change just this one instance or all instances.
293 mEditResponseHelper.showDialog(mEditResponseHelper.getWhichEvents());
296 public void onNothingSelected(AdapterView<?> parent) {
300 protected void onCreate(Bundle icicle) {
301 super.onCreate(icicle);
304 Intent intent = getIntent();
305 mUri = intent.getData();
306 ContentResolver cr = getContentResolver();
307 mStartMillis = intent.getLongExtra(EVENT_BEGIN_TIME, 0);
308 mEndMillis = intent.getLongExtra(EVENT_END_TIME, 0);
309 mAttendeeResponseFromIntent = intent.getIntExtra(ATTENDEE_STATUS, ATTENDEE_NO_RESPONSE);
310 mEventCursor = managedQuery(mUri, EVENT_PROJECTION, null, null, null);
311 if (initEventCursor()) {
312 // The cursor is empty. This can happen if the event was deleted.
317 setContentView(R.layout.event_info_activity);
318 mPresenceQueryHandler = new PresenceQueryHandler(this, cr);
319 mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
320 mRemindersContainer = (LinearLayout) findViewById(R.id.reminders_container);
321 mOrganizerContainer = (LinearLayout) findViewById(R.id.organizer_container);
322 mOrganizerView = (TextView) findViewById(R.id.organizer);
325 Uri uri = Calendars.CONTENT_URI;
326 String where = String.format(CALENDARS_WHERE, mEventCursor.getLong(EVENT_INDEX_CALENDAR_ID));
327 mCalendarsCursor = managedQuery(uri, CALENDARS_PROJECTION, where, null, null);
328 mCalendarOwnerAccount = "";
329 if (mCalendarsCursor != null) {
330 mCalendarsCursor.moveToFirst();
331 mCalendarOwnerAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
333 String eventOrganizer = mEventCursor.getString(EVENT_INDEX_ORGANIZER);
334 mIsOrganizer = mCalendarOwnerAccount.equalsIgnoreCase(eventOrganizer);
335 mHasAttendeeData = mEventCursor.getInt(EVENT_INDEX_HAS_ATTENDEE_DATA) != 0;
340 uri = Attendees.CONTENT_URI;
341 where = String.format(ATTENDEES_WHERE, mEventId);
342 mAttendeesCursor = managedQuery(uri, ATTENDEES_PROJECTION, where, null,
343 ATTENDEES_SORT_ORDER);
344 initAttendeesCursor();
346 mOrganizer = eventOrganizer;
348 mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) >= Calendars.CONTRIBUTOR_ACCESS;
349 mIsBusyFreeCalendar =
350 mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) == Calendars.FREEBUSY_ACCESS;
352 mCanModifyEvent = mCanModifyCalendar
353 && (mIsOrganizer || (mEventCursor.getInt(EVENT_INDEX_GUESTS_CAN_MODIFY) != 0));
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]));
363 mReminderValues = list;
364 String[] labels = r.getStringArray(R.array.reminder_minutes_labels);
365 mReminderLabels = new ArrayList<String>(Arrays.asList(labels));
367 SharedPreferences prefs = CalendarPreferenceActivity.getSharedPreferences(this);
368 String durationString =
369 prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0");
370 mDefaultReminderMinutes = Integer.parseInt(durationString);
373 boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
375 uri = Reminders.CONTENT_URI;
376 where = String.format(REMINDERS_WHERE, mEventId);
377 Cursor reminderCursor = cr.query(uri, REMINDERS_PROJECTION, where, null,
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);
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);
396 reminderCursor.close();
400 // Setup the + Add Reminder Button
401 View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
402 public void onClick(View v) {
406 ImageButton reminderAddButton = (ImageButton) findViewById(R.id.reminder_add);
407 reminderAddButton.setOnClickListener(addReminderOnClickListener);
409 mReminderAdder = (LinearLayout) findViewById(R.id.reminder_adder);
410 updateRemindersVisibility();
412 mDeleteEventHelper = new DeleteEventHelper(this, true /* exit when done */);
413 mEditResponseHelper = new EditResponseHelper(this);
417 protected void onResume() {
419 if (initEventCursor()) {
420 // The cursor is empty. This can happen if the event was deleted.
424 initCalendarsCursor();
429 private void updateTitle() {
430 Resources res = getResources();
431 if (mCanModifyCalendar && !mIsOrganizer) {
432 setTitle(res.getString(R.string.event_info_title_invite));
434 setTitle(res.getString(R.string.event_info_title));
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.
443 private boolean initEventCursor() {
444 if ((mEventCursor == null) || (mEventCursor.getCount() == 0)) {
447 mEventCursor.moveToFirst();
448 mEventId = mEventCursor.getInt(EVENT_INDEX_ID);
449 String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
450 mIsRepeating = (rRule != null);
454 private static class Attendee {
458 Attendee(String name, String email) {
464 private void initAttendeesCursor() {
465 mOriginalAttendeeResponse = ATTENDEE_NO_RESPONSE;
466 mCalendarOwnerAttendeeId = -1;
468 if (mAttendeesCursor != null) {
469 mNumOfAttendees = mAttendeesCursor.getCount();
470 if (mAttendeesCursor.moveToFirst()) {
471 mAcceptedAttendees.clear();
472 mDeclinedAttendees.clear();
473 mTentativeAttendees.clear();
476 int status = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
477 String name = mAttendeesCursor.getString(ATTENDEES_INDEX_NAME);
478 String email = mAttendeesCursor.getString(ATTENDEES_INDEX_EMAIL);
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) {
485 } else if (email != null && email.length() > 0) {
490 if (mCalendarOwnerAttendeeId == -1 &&
491 mCalendarOwnerAccount.equalsIgnoreCase(email)) {
492 mCalendarOwnerAttendeeId = mAttendeesCursor.getInt(ATTENDEES_INDEX_ID);
493 mOriginalAttendeeResponse = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
495 // Don't show your own status in the list because:
496 // 1) it doesn't make sense for event without other guests.
497 // 2) there's a spinner for that for events with guests.
499 case Attendees.ATTENDEE_STATUS_ACCEPTED:
500 mAcceptedAttendees.add(new Attendee(name, email));
502 case Attendees.ATTENDEE_STATUS_DECLINED:
503 mDeclinedAttendees.add(new Attendee(name, email));
506 mTentativeAttendees.add(new Attendee(name, email));
509 } while (mAttendeesCursor.moveToNext());
510 mAttendeesCursor.moveToFirst();
515 // only show the organizer if we're not the organizer and if
516 // we have attendee data (might have been removed by the server
517 // for events with a lot of attendees).
518 if (!mIsOrganizer && mHasAttendeeData) {
519 mOrganizerContainer.setVisibility(View.VISIBLE);
520 mOrganizerView.setText(mOrganizer);
522 mOrganizerContainer.setVisibility(View.GONE);
526 private void initCalendarsCursor() {
527 if (mCalendarsCursor != null) {
528 mCalendarsCursor.moveToFirst();
533 public void onPause() {
535 if (!isFinishing()) {
538 ContentResolver cr = getContentResolver();
539 ArrayList<Integer> reminderMinutes = EditEvent.reminderItemsToMinutes(mReminderItems,
541 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(3);
542 boolean changed = EditEvent.saveReminders(ops, mEventId, reminderMinutes, mOriginalMinutes,
543 false /* no force save */);
545 // TODO Run this in a background process.
546 cr.applyBatch(Calendars.CONTENT_URI.getAuthority(), ops);
547 // Update the "hasAlarm" field for the event
548 Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
549 int len = reminderMinutes.size();
550 ContentValues values = new ContentValues();
551 values.put(Events.HAS_ALARM, (len > 0) ? 1 : 0);
552 cr.update(uri, values, null, null);
553 } catch (RemoteException e) {
554 Log.w(TAG, "Ignoring exception: ", e);
555 } catch (OperationApplicationException e) {
556 Log.w(TAG, "Ignoring exception: ", e);
559 changed |= saveResponse(cr);
561 Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show();
566 public boolean onCreateOptionsMenu(Menu menu) {
568 item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0,
569 R.string.add_new_reminder);
570 item.setIcon(R.drawable.ic_menu_reminder);
571 item.setAlphabeticShortcut('r');
573 item = menu.add(MENU_GROUP_EDIT, MENU_EDIT, 0, R.string.edit_event_label);
574 item.setIcon(android.R.drawable.ic_menu_edit);
575 item.setAlphabeticShortcut('e');
577 item = menu.add(MENU_GROUP_DELETE, MENU_DELETE, 0, R.string.delete_event_label);
578 item.setIcon(android.R.drawable.ic_menu_delete);
580 return super.onCreateOptionsMenu(menu);
584 public boolean onPrepareOptionsMenu(Menu menu) {
585 boolean canAddReminders = canAddReminders();
586 menu.setGroupVisible(MENU_GROUP_REMINDER, canAddReminders);
587 menu.setGroupEnabled(MENU_GROUP_REMINDER, canAddReminders);
589 menu.setGroupVisible(MENU_GROUP_EDIT, mCanModifyEvent);
590 menu.setGroupEnabled(MENU_GROUP_EDIT, mCanModifyEvent);
591 menu.setGroupVisible(MENU_GROUP_DELETE, mCanModifyCalendar);
592 menu.setGroupEnabled(MENU_GROUP_DELETE, mCanModifyCalendar);
594 return super.onPrepareOptionsMenu(menu);
597 private boolean canAddReminders() {
598 return !mIsBusyFreeCalendar && mReminderItems.size() < MAX_REMINDERS;
601 private void addReminder() {
602 // TODO: when adding a new reminder, make it different from the
603 // last one in the list (if any).
604 if (mDefaultReminderMinutes == 0) {
605 EditEvent.addReminder(this, this, mReminderItems,
606 mReminderValues, mReminderLabels, 10 /* minutes */);
608 EditEvent.addReminder(this, this, mReminderItems,
609 mReminderValues, mReminderLabels, mDefaultReminderMinutes);
611 updateRemindersVisibility();
615 public boolean onOptionsItemSelected(MenuItem item) {
616 super.onOptionsItemSelected(item);
617 switch (item.getItemId()) {
618 case MENU_ADD_REMINDER:
632 public boolean onKeyDown(int keyCode, KeyEvent event) {
633 if (keyCode == KeyEvent.KEYCODE_DEL) {
637 return super.onKeyDown(keyCode, event);
640 private void updateRemindersVisibility() {
641 if (mIsBusyFreeCalendar) {
642 mRemindersContainer.setVisibility(View.GONE);
644 mRemindersContainer.setVisibility(View.VISIBLE);
645 mReminderAdder.setVisibility(canAddReminders() ? View.VISIBLE : View.GONE);
650 * Saves the response to an invitation if the user changed the response.
651 * Returns true if the database was updated.
653 * @param cr the ContentResolver
654 * @return true if the database was changed
656 private boolean saveResponse(ContentResolver cr) {
657 if (mAttendeesCursor == null || mEventCursor == null) {
660 Spinner spinner = (Spinner) findViewById(R.id.response_value);
661 int position = spinner.getSelectedItemPosition() - mResponseOffset;
666 int status = ATTENDEE_VALUES[position];
668 // If the status has not changed, then don't update the database
669 if (status == mOriginalAttendeeResponse) {
674 // This is a non-repeating event
675 updateResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
679 // This is a repeating event
680 int whichEvents = mEditResponseHelper.getWhichEvents();
681 switch (whichEvents) {
685 createExceptionResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
688 updateResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
691 Log.e(TAG, "Unexpected choice for updating invitation response");
697 private void updateResponse(ContentResolver cr, long eventId, long attendeeId, int status) {
698 // Update the attendee status in the attendees table. the provider
699 // takes care of updating the self attendance status.
700 ContentValues values = new ContentValues();
702 if (!TextUtils.isEmpty(mCalendarOwnerAccount)) {
703 values.put(Attendees.ATTENDEE_EMAIL, mCalendarOwnerAccount);
705 values.put(Attendees.ATTENDEE_STATUS, status);
706 values.put(Attendees.EVENT_ID, eventId);
708 Uri uri = ContentUris.withAppendedId(Attendees.CONTENT_URI, attendeeId);
709 cr.update(uri, values, null /* where */, null /* selection args */);
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) {
720 if(!cursor.moveToFirst()) {
726 ContentValues values = new ContentValues();
728 String title = cursor.getString(EVENT_INDEX_TITLE);
729 String timezone = cursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
730 int calendarId = cursor.getInt(EVENT_INDEX_CALENDAR_ID);
731 boolean allDay = cursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
732 String syncId = cursor.getString(EVENT_INDEX_SYNC_ID);
734 values.put(Events.TITLE, title);
735 values.put(Events.EVENT_TIMEZONE, timezone);
736 values.put(Events.ALL_DAY, allDay ? 1 : 0);
737 values.put(Events.CALENDAR_ID, calendarId);
738 values.put(Events.DTSTART, mStartMillis);
739 values.put(Events.DTEND, mEndMillis);
740 values.put(Events.ORIGINAL_EVENT, syncId);
741 values.put(Events.ORIGINAL_INSTANCE_TIME, mStartMillis);
742 values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0);
743 values.put(Events.STATUS, Events.STATUS_CONFIRMED);
744 values.put(Events.SELF_ATTENDEE_STATUS, status);
746 // Create a recurrence exception
747 cr.insert(Events.CONTENT_URI, values);
753 private int findResponseIndexFor(int response) {
754 int size = ATTENDEE_VALUES.length;
755 for (int index = 0; index < size; index++) {
756 if (ATTENDEE_VALUES[index] == response) {
763 private void doEdit() {
764 Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
765 Intent intent = new Intent(Intent.ACTION_EDIT, uri);
766 intent.putExtra(Calendar.EVENT_BEGIN_TIME, mStartMillis);
767 intent.putExtra(Calendar.EVENT_END_TIME, mEndMillis);
768 intent.setClass(EventInfoActivity.this, EditEvent.class);
769 startActivity(intent);
773 private void doDelete() {
774 mDeleteEventHelper.delete(mStartMillis, mEndMillis, mEventCursor, -1);
777 private void updateView() {
778 if (mEventCursor == null) {
782 String eventName = mEventCursor.getString(EVENT_INDEX_TITLE);
783 if (eventName == null || eventName.length() == 0) {
784 Resources res = getResources();
785 eventName = res.getString(R.string.no_title_label);
788 boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
789 String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION);
790 String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION);
791 String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
792 boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
793 String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
794 mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff;
796 View calBackground = findViewById(R.id.cal_background);
797 calBackground.setBackgroundColor(mColor);
799 TextView title = (TextView) findViewById(R.id.title);
800 title.setTextColor(mColor);
802 View divider = findViewById(R.id.divider);
803 divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
806 if (eventName != null) {
807 setTextCommon(R.id.title, eventName);
814 flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE;
816 flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE;
817 if (DateFormat.is24HourFormat(this)) {
818 flags |= DateUtils.FORMAT_24HOUR;
821 when = DateUtils.formatDateRange(this, mStartMillis, mEndMillis, flags);
822 setTextCommon(R.id.when, when);
824 // Show the event timezone if it is different from the local timezone
825 Time time = new Time();
826 String localTimezone = time.timezone;
828 localTimezone = Time.TIMEZONE_UTC;
830 if (eventTimezone != null && !localTimezone.equals(eventTimezone) && !allDay) {
832 TimeZone tz = TimeZone.getTimeZone(localTimezone);
833 if (tz == null || tz.getID().equals("GMT")) {
834 displayName = localTimezone;
836 displayName = tz.getDisplayName();
839 setTextCommon(R.id.timezone, displayName);
841 setVisibilityCommon(R.id.timezone_container, View.GONE);
846 EventRecurrence eventRecurrence = new EventRecurrence();
847 eventRecurrence.parse(rRule);
848 Time date = new Time();
850 date.timezone = Time.TIMEZONE_UTC;
852 date.set(mStartMillis);
853 eventRecurrence.setStartDate(date);
854 String repeatString = EventRecurrenceFormatter.getRepeatString(getResources(),
856 setTextCommon(R.id.repeat, repeatString);
858 setVisibilityCommon(R.id.repeat_container, View.GONE);
862 if (location == null || location.length() == 0) {
863 setVisibilityCommon(R.id.where, View.GONE);
865 final TextView textView = (TextView) findViewById(R.id.where);
866 if (textView != null) {
867 textView.setAutoLinkMask(0);
868 textView.setText(location);
869 Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
870 textView.setOnTouchListener(new OnTouchListener() {
871 public boolean onTouch(View v, MotionEvent event) {
873 return v.onTouchEvent(event);
874 } catch (ActivityNotFoundException e) {
884 if (description == null || description.length() == 0) {
885 setVisibilityCommon(R.id.description, View.GONE);
887 setTextCommon(R.id.description, description);
891 if (mCalendarsCursor != null) {
892 String calendarName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
893 setTextCommon(R.id.calendar, calendarName);
895 setVisibilityCommon(R.id.calendar_container, View.GONE);
899 private void updateAttendees() {
900 CharSequence[] entries;
901 entries = getResources().getTextArray(R.array.response_labels2);
902 LinearLayout attendeesLayout = (LinearLayout) findViewById(R.id.attendee_list);
903 attendeesLayout.removeAllViewsInLayout();
905 addAttendeesToLayout(mAcceptedAttendees, attendeesLayout, entries[0]);
906 addAttendeesToLayout(mDeclinedAttendees, attendeesLayout, entries[2]);
907 addAttendeesToLayout(mTentativeAttendees, attendeesLayout, entries[1]);
910 private void addAttendeesToLayout(ArrayList<Attendee> attendees, LinearLayout attendeeList,
911 CharSequence sectionTitle) {
912 if (attendees.size() == 0) {
916 ContentResolver cr = getContentResolver();
917 // Yes/No/Maybe Title
918 View titleView = mLayoutInflater.inflate(R.layout.contact_item, null);
919 titleView.findViewById(R.id.badge).setVisibility(View.GONE);
920 View divider = titleView.findViewById(R.id.separator);
921 divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
923 TextView title = (TextView) titleView.findViewById(R.id.name);
924 title.setText(getString(R.string.response_label, sectionTitle, attendees.size()));
925 title.setTextAppearance(this, R.style.TextAppearance_EventInfo_Label);
926 attendeeList.addView(titleView);
929 int numOfAttendees = attendees.size();
930 StringBuilder selection = new StringBuilder(Email.DATA + " IN (");
931 String[] selectionArgs = new String[numOfAttendees];
933 for (int i = 0; i < numOfAttendees; ++i) {
934 Attendee attendee = attendees.get(i);
935 selectionArgs[i] = attendee.mEmail;
937 View v = mLayoutInflater.inflate(R.layout.contact_item, null);
940 View separator = v.findViewById(R.id.separator);
941 separator.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
944 TextView tv = (TextView) v.findViewById(R.id.name);
945 String name = attendee.mName;
946 if (name == null || name.length() == 0) {
947 name = attendee.mEmail;
951 ViewHolder vh = new ViewHolder();
952 vh.badge = (QuickContactBadge) v.findViewById(R.id.badge);
953 vh.badge.assignContactFromEmail(attendee.mEmail, true);
954 vh.presence = (ImageView) v.findViewById(R.id.presence);
955 mViewHolders.put(attendee.mEmail, vh);
958 selection.append('?');
960 selection.append(", ?");
963 attendeeList.addView(v);
965 selection.append(')');
967 mPresenceQueryHandler.startQuery(mUpdateCounts, attendees, CONTACT_DATA_WITH_PRESENCE_URI,
968 PRESENCE_PROJECTION, selection.toString(), selectionArgs, null);
971 private class PresenceQueryHandler extends AsyncQueryHandler {
973 ContentResolver mContentResolver;
975 public PresenceQueryHandler(Context context, ContentResolver cr) {
977 mContentResolver = cr;
982 protected void onQueryComplete(int queryIndex, Object cookie, Cursor cursor) {
983 if (cursor == null) {
985 Log.e(TAG, "onQueryComplete: cursor == null");
991 cursor.moveToPosition(-1);
992 while (cursor.moveToNext()) {
993 String email = cursor.getString(PRESENCE_PROJECTION_EMAIL_INDEX);
994 int contactId = cursor.getInt(PRESENCE_PROJECTION_CONTACT_ID_INDEX);
995 ViewHolder vh = mViewHolders.get(email);
996 int photoId = cursor.getInt(PRESENCE_PROJECTION_PHOTO_ID_INDEX);
998 Log.e(TAG, "onQueryComplete Id: " + contactId + " PhotoId: " + photoId
999 + " Email: " + email);
1004 ImageView presenceView = vh.presence;
1005 if (presenceView != null) {
1006 int status = cursor.getInt(PRESENCE_PROJECTION_PRESENCE_INDEX);
1007 presenceView.setImageResource(Presence.getPresenceIconResourceId(status));
1008 presenceView.setVisibility(View.VISIBLE);
1011 if (photoId > 0 && vh.updateCounts < queryIndex) {
1012 vh.updateCounts = queryIndex;
1013 Uri personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
1015 // TODO, modify to batch queries together
1016 ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext, vh.badge,
1017 personUri, R.drawable.ic_contact_picture);
1026 void updateResponse() {
1027 // we only let the user accept/reject/etc. a meeting if:
1028 // a) you can edit the event's containing calendar AND
1029 // b) you're not the organizer and only attendee
1030 // (if the attendee data has been hidden, the visible number of attendees
1031 // will be 1 -- the calendar owner's).
1032 // (there are more cases involved to be 100% accurate, such as
1033 // paying attention to whether or not an attendee status was
1034 // included in the feed, but we're currently omitting those corner cases
1036 if (!mCanModifyCalendar || (mHasAttendeeData && mIsOrganizer && mNumOfAttendees <= 1)) {
1037 setVisibilityCommon(R.id.response_container, View.GONE);
1041 setVisibilityCommon(R.id.response_container, View.VISIBLE);
1043 Spinner spinner = (Spinner) findViewById(R.id.response_value);
1045 mResponseOffset = 0;
1047 /* If the user has previously responded to this event
1048 * we should not allow them to select no response again.
1049 * Switch the entries to a set of entries without the
1050 * no response option.
1052 if ((mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_INVITED)
1053 && (mOriginalAttendeeResponse != ATTENDEE_NO_RESPONSE)
1054 && (mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_NONE)) {
1055 CharSequence[] entries;
1056 entries = getResources().getTextArray(R.array.response_labels2);
1057 mResponseOffset = -1;
1058 ArrayAdapter<CharSequence> adapter =
1059 new ArrayAdapter<CharSequence>(this,
1060 android.R.layout.simple_spinner_item, entries);
1061 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
1062 spinner.setAdapter(adapter);
1066 if (mAttendeeResponseFromIntent != ATTENDEE_NO_RESPONSE) {
1067 index = findResponseIndexFor(mAttendeeResponseFromIntent);
1069 index = findResponseIndexFor(mOriginalAttendeeResponse);
1071 spinner.setSelection(index + mResponseOffset);
1072 spinner.setOnItemSelectedListener(this);
1075 private void setTextCommon(int id, CharSequence text) {
1076 TextView textView = (TextView) findViewById(id);
1077 if (textView == null)
1079 textView.setText(text);
1082 private void setVisibilityCommon(int id, int visibility) {
1083 View v = findViewById(id);
1085 v.setVisibility(visibility);
1091 * Taken from com.google.android.gm.HtmlConversationActivity
1093 * Send the intent that shows the Contact info corresponding to the email address.
1095 public void showContactInfo(Attendee attendee, Rect rect) {
1096 // First perform lookup query to find existing contact
1097 final ContentResolver resolver = getContentResolver();
1098 final String address = attendee.mEmail;
1099 final Uri dataUri = Uri.withAppendedPath(CommonDataKinds.Email.CONTENT_FILTER_URI,
1100 Uri.encode(address));
1101 final Uri lookupUri = ContactsContract.Data.getContactLookupUri(resolver, dataUri);
1103 if (lookupUri != null) {
1104 // Found matching contact, trigger QuickContact
1105 QuickContact.showQuickContact(this, rect, lookupUri, QuickContact.MODE_MEDIUM, null);
1107 // No matching contact, ask user to create one
1108 final Uri mailUri = Uri.fromParts("mailto", address, null);
1109 final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, mailUri);
1111 // Pass along full E-mail string for possible create dialog
1112 Rfc822Token sender = new Rfc822Token(attendee.mName, attendee.mEmail, null);
1113 intent.putExtra(Intents.EXTRA_CREATE_DESCRIPTION, sender.toString());
1115 // Only provide personal name hint if we have one
1116 final String senderPersonal = attendee.mName;
1117 if (!TextUtils.isEmpty(senderPersonal)) {
1118 intent.putExtra(Intents.Insert.NAME, senderPersonal);
1121 startActivity(intent);