OSDN Git Service

Merge "b/2496984 Pulled out -1 attendee id into a constant"
[android-x86/packages-apps-Calendar.git] / src / com / android / calendar / EventInfoActivity.java
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.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;
79
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;
85
86 public 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.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
120     };
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;
137
138     private static final String[] ATTENDEES_PROJECTION = new String[] {
139         Attendees._ID,                      // 0
140         Attendees.ATTENDEE_NAME,            // 1
141         Attendees.ATTENDEE_EMAIL,           // 2
142         Attendees.ATTENDEE_RELATIONSHIP,    // 3
143         Attendees.ATTENDEE_STATUS,          // 4
144     };
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;
150
151     private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=%d";
152
153     private static final String ATTENDEES_SORT_ORDER = Attendees.ATTENDEE_NAME + " ASC, "
154             + Attendees.ATTENDEE_EMAIL + " ASC";
155
156     static final String[] CALENDARS_PROJECTION = new String[] {
157         Calendars._ID,           // 0
158         Calendars.DISPLAY_NAME,  // 1
159         Calendars.OWNER_ACCOUNT, // 2
160     };
161     static final int CALENDARS_INDEX_DISPLAY_NAME = 1;
162     static final int CALENDARS_INDEX_OWNER_ACCOUNT = 2;
163
164     static final String CALENDARS_WHERE = Calendars._ID + "=%d";
165
166     private static final String[] REMINDERS_PROJECTION = new String[] {
167         Reminders._ID,      // 0
168         Reminders.MINUTES,  // 1
169     };
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;
175
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;
179
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;
183
184     private static final int ATTENDEE_ID_NONE = -1;
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 = ATTENDEE_ID_NONE;
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     ArrayList<Attendee> mNoResponseAttendees = new ArrayList<Attendee>();
262     private int mColor;
263
264     // This is called when one of the "remove reminder" buttons is selected.
265     public void onClick(View v) {
266         LinearLayout reminderItem = (LinearLayout) v.getParent();
267         LinearLayout parent = (LinearLayout) reminderItem.getParent();
268         parent.removeView(reminderItem);
269         mReminderItems.remove(reminderItem);
270         updateRemindersVisibility();
271     }
272
273     public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
274         // If they selected the "No response" option, then don't display the
275         // dialog asking which events to change.
276         if (id == 0 && mResponseOffset == 0) {
277             return;
278         }
279
280         // If this is not a repeating event, then don't display the dialog
281         // asking which events to change.
282         if (!mIsRepeating) {
283             return;
284         }
285
286         // If the selection is the same as the original, then don't display the
287         // dialog asking which events to change.
288         int index = findResponseIndexFor(mOriginalAttendeeResponse);
289         if (position == index + mResponseOffset) {
290             return;
291         }
292
293         // This is a repeating event. We need to ask the user if they mean to
294         // change just this one instance or all instances.
295         mEditResponseHelper.showDialog(mEditResponseHelper.getWhichEvents());
296     }
297
298     public void onNothingSelected(AdapterView<?> parent) {
299     }
300
301     @Override
302     protected void onCreate(Bundle icicle) {
303         super.onCreate(icicle);
304
305         // Event cursor
306         Intent intent = getIntent();
307         mUri = intent.getData();
308         ContentResolver cr = getContentResolver();
309         mStartMillis = intent.getLongExtra(EVENT_BEGIN_TIME, 0);
310         mEndMillis = intent.getLongExtra(EVENT_END_TIME, 0);
311         mAttendeeResponseFromIntent = intent.getIntExtra(ATTENDEE_STATUS, ATTENDEE_NO_RESPONSE);
312         mEventCursor = managedQuery(mUri, EVENT_PROJECTION, null, null, null);
313         if (initEventCursor()) {
314             // The cursor is empty. This can happen if the event was deleted.
315             finish();
316             return;
317         }
318
319         setContentView(R.layout.event_info_activity);
320         mPresenceQueryHandler = new PresenceQueryHandler(this, cr);
321         mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
322         mRemindersContainer = (LinearLayout) findViewById(R.id.reminders_container);
323         mOrganizerContainer = (LinearLayout) findViewById(R.id.organizer_container);
324         mOrganizerView = (TextView) findViewById(R.id.organizer);
325
326         // Calendars cursor
327         Uri uri = Calendars.CONTENT_URI;
328         String where = String.format(CALENDARS_WHERE, mEventCursor.getLong(EVENT_INDEX_CALENDAR_ID));
329         mCalendarsCursor = managedQuery(uri, CALENDARS_PROJECTION, where, null, null);
330         mCalendarOwnerAccount = "";
331         if (mCalendarsCursor != null) {
332             mCalendarsCursor.moveToFirst();
333             mCalendarOwnerAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
334         }
335         String eventOrganizer = mEventCursor.getString(EVENT_INDEX_ORGANIZER);
336         mIsOrganizer = mCalendarOwnerAccount.equalsIgnoreCase(eventOrganizer);
337         mHasAttendeeData = mEventCursor.getInt(EVENT_INDEX_HAS_ATTENDEE_DATA) != 0;
338
339         updateView();
340
341         // Attendees cursor
342         uri = Attendees.CONTENT_URI;
343         where = String.format(ATTENDEES_WHERE, mEventId);
344         mAttendeesCursor = managedQuery(uri, ATTENDEES_PROJECTION, where, null,
345                 ATTENDEES_SORT_ORDER);
346         initAttendeesCursor();
347
348         mOrganizer = eventOrganizer;
349         mCanModifyCalendar =
350                 mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) >= Calendars.CONTRIBUTOR_ACCESS;
351         mIsBusyFreeCalendar =
352                 mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) == Calendars.FREEBUSY_ACCESS;
353
354         mCanModifyEvent = mCanModifyCalendar
355                 && (mIsOrganizer || (mEventCursor.getInt(EVENT_INDEX_GUESTS_CAN_MODIFY) != 0));
356
357         // Initialize the reminder values array.
358         Resources r = getResources();
359         String[] strings = r.getStringArray(R.array.reminder_minutes_values);
360         int size = strings.length;
361         ArrayList<Integer> list = new ArrayList<Integer>(size);
362         for (int i = 0 ; i < size ; i++) {
363             list.add(Integer.parseInt(strings[i]));
364         }
365         mReminderValues = list;
366         String[] labels = r.getStringArray(R.array.reminder_minutes_labels);
367         mReminderLabels = new ArrayList<String>(Arrays.asList(labels));
368
369         SharedPreferences prefs = CalendarPreferenceActivity.getSharedPreferences(this);
370         String durationString =
371                 prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0");
372         mDefaultReminderMinutes = Integer.parseInt(durationString);
373
374         // Reminders cursor
375         boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
376         if (hasAlarm) {
377             uri = Reminders.CONTENT_URI;
378             where = String.format(REMINDERS_WHERE, mEventId);
379             Cursor reminderCursor = cr.query(uri, REMINDERS_PROJECTION, where, null,
380                     REMINDERS_SORT);
381             try {
382                 // First pass: collect all the custom reminder minutes (e.g.,
383                 // a reminder of 8 minutes) into a global list.
384                 while (reminderCursor.moveToNext()) {
385                     int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
386                     EditEvent.addMinutesToList(this, mReminderValues, mReminderLabels, minutes);
387                 }
388
389                 // Second pass: create the reminder spinners
390                 reminderCursor.moveToPosition(-1);
391                 while (reminderCursor.moveToNext()) {
392                     int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
393                     mOriginalMinutes.add(minutes);
394                     EditEvent.addReminder(this, this, mReminderItems, mReminderValues,
395                             mReminderLabels, minutes);
396                 }
397             } finally {
398                 reminderCursor.close();
399             }
400         }
401
402         // Setup the + Add Reminder Button
403         View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
404             public void onClick(View v) {
405                 addReminder();
406             }
407         };
408         ImageButton reminderAddButton = (ImageButton) findViewById(R.id.reminder_add);
409         reminderAddButton.setOnClickListener(addReminderOnClickListener);
410
411         mReminderAdder = (LinearLayout) findViewById(R.id.reminder_adder);
412         updateRemindersVisibility();
413
414         mDeleteEventHelper = new DeleteEventHelper(this, true /* exit when done */);
415         mEditResponseHelper = new EditResponseHelper(this);
416     }
417
418     @Override
419     protected void onResume() {
420         super.onResume();
421         if (initEventCursor()) {
422             // The cursor is empty. This can happen if the event was deleted.
423             finish();
424             return;
425         }
426         initCalendarsCursor();
427         updateResponse();
428         updateTitle();
429     }
430
431     private void updateTitle() {
432         Resources res = getResources();
433         if (mCanModifyCalendar && !mIsOrganizer) {
434             setTitle(res.getString(R.string.event_info_title_invite));
435         } else {
436             setTitle(res.getString(R.string.event_info_title));
437         }
438     }
439
440     /**
441      * Initializes the event cursor, which is expected to point to the first
442      * (and only) result from a query.
443      * @return true if the cursor is empty.
444      */
445     private boolean initEventCursor() {
446         if ((mEventCursor == null) || (mEventCursor.getCount() == 0)) {
447             return true;
448         }
449         mEventCursor.moveToFirst();
450         mEventId = mEventCursor.getInt(EVENT_INDEX_ID);
451         String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
452         mIsRepeating = (rRule != null);
453         return false;
454     }
455
456     private static class Attendee {
457         String mName;
458         String mEmail;
459
460         Attendee(String name, String email) {
461             mName = name;
462             mEmail = email;
463         }
464     }
465
466     @SuppressWarnings("fallthrough")
467     private void initAttendeesCursor() {
468         mOriginalAttendeeResponse = ATTENDEE_NO_RESPONSE;
469         mCalendarOwnerAttendeeId = ATTENDEE_ID_NONE;
470         mNumOfAttendees = 0;
471         if (mAttendeesCursor != null) {
472             mNumOfAttendees = mAttendeesCursor.getCount();
473             if (mAttendeesCursor.moveToFirst()) {
474                 mAcceptedAttendees.clear();
475                 mDeclinedAttendees.clear();
476                 mTentativeAttendees.clear();
477                 mNoResponseAttendees.clear();
478
479                 do {
480                     int status = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
481                     String name = mAttendeesCursor.getString(ATTENDEES_INDEX_NAME);
482                     String email = mAttendeesCursor.getString(ATTENDEES_INDEX_EMAIL);
483
484                     if (mAttendeesCursor.getInt(ATTENDEES_INDEX_RELATIONSHIP) ==
485                             Attendees.RELATIONSHIP_ORGANIZER) {
486                         // Overwrites the one from Event table if available
487                         if (name != null && name.length() > 0) {
488                             mOrganizer = name;
489                         } else if (email != null && email.length() > 0) {
490                             mOrganizer = email;
491                         }
492                     }
493
494                     if (mCalendarOwnerAttendeeId == ATTENDEE_ID_NONE &&
495                             mCalendarOwnerAccount.equalsIgnoreCase(email)) {
496                         mCalendarOwnerAttendeeId = mAttendeesCursor.getInt(ATTENDEES_INDEX_ID);
497                         mOriginalAttendeeResponse = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
498                     } else {
499                         // Don't show your own status in the list because:
500                         //  1) it doesn't make sense for event without other guests.
501                         //  2) there's a spinner for that for events with guests.
502                         switch(status) {
503                             case Attendees.ATTENDEE_STATUS_ACCEPTED:
504                                 mAcceptedAttendees.add(new Attendee(name, email));
505                                 break;
506                             case Attendees.ATTENDEE_STATUS_DECLINED:
507                                 mDeclinedAttendees.add(new Attendee(name, email));
508                                 break;
509                             case Attendees.ATTENDEE_STATUS_NONE:
510                                 mNoResponseAttendees.add(new Attendee(name, email));
511                                 // Fallthrough so that no response is a subset of tentative
512                             default:
513                                 mTentativeAttendees.add(new Attendee(name, email));
514                         }
515                     }
516                 } while (mAttendeesCursor.moveToNext());
517                 mAttendeesCursor.moveToFirst();
518
519                 updateAttendees();
520             }
521         }
522         // only show the organizer if we're not the organizer and if
523         // we have attendee data (might have been removed by the server
524         // for events with a lot of attendees).
525         if (!mIsOrganizer && mHasAttendeeData) {
526             mOrganizerContainer.setVisibility(View.VISIBLE);
527             mOrganizerView.setText(mOrganizer);
528         } else {
529             mOrganizerContainer.setVisibility(View.GONE);
530         }
531     }
532
533     private void initCalendarsCursor() {
534         if (mCalendarsCursor != null) {
535             mCalendarsCursor.moveToFirst();
536         }
537     }
538
539     @Override
540     public void onPause() {
541         super.onPause();
542         if (!isFinishing()) {
543             return;
544         }
545         ContentResolver cr = getContentResolver();
546         ArrayList<Integer> reminderMinutes = EditEvent.reminderItemsToMinutes(mReminderItems,
547                 mReminderValues);
548         ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(3);
549         boolean changed = EditEvent.saveReminders(ops, mEventId, reminderMinutes, mOriginalMinutes,
550                 false /* no force save */);
551         try {
552             // TODO Run this in a background process.
553             cr.applyBatch(Calendars.CONTENT_URI.getAuthority(), ops);
554             // Update the "hasAlarm" field for the event
555             Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
556             int len = reminderMinutes.size();
557             ContentValues values = new ContentValues();
558             values.put(Events.HAS_ALARM, (len > 0) ? 1 : 0);
559             cr.update(uri, values, null, null);
560         } catch (RemoteException e) {
561             Log.w(TAG, "Ignoring exception: ", e);
562         } catch (OperationApplicationException e) {
563             Log.w(TAG, "Ignoring exception: ", e);
564         }
565
566         changed |= saveResponse(cr);
567         if (changed) {
568             Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show();
569         }
570     }
571
572     @Override
573     public boolean onCreateOptionsMenu(Menu menu) {
574         MenuItem item;
575         item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0,
576                 R.string.add_new_reminder);
577         item.setIcon(R.drawable.ic_menu_reminder);
578         item.setAlphabeticShortcut('r');
579
580         item = menu.add(MENU_GROUP_EDIT, MENU_EDIT, 0, R.string.edit_event_label);
581         item.setIcon(android.R.drawable.ic_menu_edit);
582         item.setAlphabeticShortcut('e');
583
584         item = menu.add(MENU_GROUP_DELETE, MENU_DELETE, 0, R.string.delete_event_label);
585         item.setIcon(android.R.drawable.ic_menu_delete);
586
587         return super.onCreateOptionsMenu(menu);
588     }
589
590     @Override
591     public boolean onPrepareOptionsMenu(Menu menu) {
592         boolean canAddReminders = canAddReminders();
593         menu.setGroupVisible(MENU_GROUP_REMINDER, canAddReminders);
594         menu.setGroupEnabled(MENU_GROUP_REMINDER, canAddReminders);
595
596         menu.setGroupVisible(MENU_GROUP_EDIT, mCanModifyEvent);
597         menu.setGroupEnabled(MENU_GROUP_EDIT, mCanModifyEvent);
598         menu.setGroupVisible(MENU_GROUP_DELETE, mCanModifyCalendar);
599         menu.setGroupEnabled(MENU_GROUP_DELETE, mCanModifyCalendar);
600
601         return super.onPrepareOptionsMenu(menu);
602     }
603
604     private boolean canAddReminders() {
605         return !mIsBusyFreeCalendar && mReminderItems.size() < MAX_REMINDERS;
606     }
607
608     private void addReminder() {
609         // TODO: when adding a new reminder, make it different from the
610         // last one in the list (if any).
611         if (mDefaultReminderMinutes == 0) {
612             EditEvent.addReminder(this, this, mReminderItems,
613                     mReminderValues, mReminderLabels, 10 /* minutes */);
614         } else {
615             EditEvent.addReminder(this, this, mReminderItems,
616                     mReminderValues, mReminderLabels, mDefaultReminderMinutes);
617         }
618         updateRemindersVisibility();
619     }
620
621     @Override
622     public boolean onOptionsItemSelected(MenuItem item) {
623         super.onOptionsItemSelected(item);
624         switch (item.getItemId()) {
625         case MENU_ADD_REMINDER:
626             addReminder();
627             break;
628         case MENU_EDIT:
629             doEdit();
630             break;
631         case MENU_DELETE:
632             doDelete();
633             break;
634         }
635         return true;
636     }
637
638     @Override
639     public boolean onKeyDown(int keyCode, KeyEvent event) {
640         if (keyCode == KeyEvent.KEYCODE_DEL) {
641             doDelete();
642             return true;
643         }
644         return super.onKeyDown(keyCode, event);
645     }
646
647     private void updateRemindersVisibility() {
648         if (mIsBusyFreeCalendar) {
649             mRemindersContainer.setVisibility(View.GONE);
650         } else {
651             mRemindersContainer.setVisibility(View.VISIBLE);
652             mReminderAdder.setVisibility(canAddReminders() ? View.VISIBLE : View.GONE);
653         }
654     }
655
656     /**
657      * Saves the response to an invitation if the user changed the response.
658      * Returns true if the database was updated.
659      *
660      * @param cr the ContentResolver
661      * @return true if the database was changed
662      */
663     private boolean saveResponse(ContentResolver cr) {
664         if (mAttendeesCursor == null || mEventCursor == null) {
665             return false;
666         }
667         Spinner spinner = (Spinner) findViewById(R.id.response_value);
668         int position = spinner.getSelectedItemPosition() - mResponseOffset;
669         if (position <= 0) {
670             return false;
671         }
672
673         int status = ATTENDEE_VALUES[position];
674
675         // If the status has not changed, then don't update the database
676         if (status == mOriginalAttendeeResponse) {
677             return false;
678         }
679
680         // If we never got an owner attendee id we can't set the status
681         if (mCalendarOwnerAttendeeId == ATTENDEE_ID_NONE) {
682             return false;
683         }
684
685         if (!mIsRepeating) {
686             // This is a non-repeating event
687             updateResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
688             return true;
689         }
690
691         // This is a repeating event
692         int whichEvents = mEditResponseHelper.getWhichEvents();
693         switch (whichEvents) {
694             case -1:
695                 return false;
696             case UPDATE_SINGLE:
697                 createExceptionResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
698                 return true;
699             case UPDATE_ALL:
700                 updateResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
701                 return true;
702             default:
703                 Log.e(TAG, "Unexpected choice for updating invitation response");
704                 break;
705         }
706         return false;
707     }
708
709     private void updateResponse(ContentResolver cr, long eventId, long attendeeId, int status) {
710         // Update the attendee status in the attendees table.  the provider
711         // takes care of updating the self attendance status.
712         ContentValues values = new ContentValues();
713
714         if (!TextUtils.isEmpty(mCalendarOwnerAccount)) {
715             values.put(Attendees.ATTENDEE_EMAIL, mCalendarOwnerAccount);
716         }
717         values.put(Attendees.ATTENDEE_STATUS, status);
718         values.put(Attendees.EVENT_ID, eventId);
719
720         Uri uri = ContentUris.withAppendedId(Attendees.CONTENT_URI, attendeeId);
721         cr.update(uri, values, null /* where */, null /* selection args */);
722     }
723
724     private void createExceptionResponse(ContentResolver cr, long eventId,
725             long attendeeId, int status) {
726         // Fetch information about the repeating event.
727         Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
728         Cursor cursor = cr.query(uri, EVENT_PROJECTION, null, null, null);
729         if (cursor == null) {
730             return;
731         }
732         if(!cursor.moveToFirst()) {
733             cursor.close();
734             return;
735         }
736
737         try {
738             ContentValues values = new ContentValues();
739
740             String title = cursor.getString(EVENT_INDEX_TITLE);
741             String timezone = cursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
742             int calendarId = cursor.getInt(EVENT_INDEX_CALENDAR_ID);
743             boolean allDay = cursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
744             String syncId = cursor.getString(EVENT_INDEX_SYNC_ID);
745
746             values.put(Events.TITLE, title);
747             values.put(Events.EVENT_TIMEZONE, timezone);
748             values.put(Events.ALL_DAY, allDay ? 1 : 0);
749             values.put(Events.CALENDAR_ID, calendarId);
750             values.put(Events.DTSTART, mStartMillis);
751             values.put(Events.DTEND, mEndMillis);
752             values.put(Events.ORIGINAL_EVENT, syncId);
753             values.put(Events.ORIGINAL_INSTANCE_TIME, mStartMillis);
754             values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0);
755             values.put(Events.STATUS, Events.STATUS_CONFIRMED);
756             values.put(Events.SELF_ATTENDEE_STATUS, status);
757
758             // Create a recurrence exception
759             cr.insert(Events.CONTENT_URI, values);
760         } finally {
761             cursor.close();
762         }
763     }
764
765     private int findResponseIndexFor(int response) {
766         int size = ATTENDEE_VALUES.length;
767         for (int index = 0; index < size; index++) {
768             if (ATTENDEE_VALUES[index] == response) {
769                 return index;
770             }
771         }
772         return 0;
773     }
774
775     private void doEdit() {
776         Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
777         Intent intent = new Intent(Intent.ACTION_EDIT, uri);
778         intent.putExtra(Calendar.EVENT_BEGIN_TIME, mStartMillis);
779         intent.putExtra(Calendar.EVENT_END_TIME, mEndMillis);
780         intent.setClass(EventInfoActivity.this, EditEvent.class);
781         startActivity(intent);
782         finish();
783     }
784
785     private void doDelete() {
786         mDeleteEventHelper.delete(mStartMillis, mEndMillis, mEventCursor, -1);
787     }
788
789     private void updateView() {
790         if (mEventCursor == null) {
791             return;
792         }
793
794         String eventName = mEventCursor.getString(EVENT_INDEX_TITLE);
795         if (eventName == null || eventName.length() == 0) {
796             Resources res = getResources();
797             eventName = res.getString(R.string.no_title_label);
798         }
799
800         boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
801         String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION);
802         String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION);
803         String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
804         boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
805         String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
806         mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff;
807
808         View calBackground = findViewById(R.id.cal_background);
809         calBackground.setBackgroundColor(mColor);
810
811         TextView title = (TextView) findViewById(R.id.title);
812         title.setTextColor(mColor);
813
814         View divider = findViewById(R.id.divider);
815         divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
816
817         // What
818         if (eventName != null) {
819             setTextCommon(R.id.title, eventName);
820         }
821
822         // When
823         String when;
824         int flags;
825         if (allDay) {
826             flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE;
827         } else {
828             flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE;
829             if (DateFormat.is24HourFormat(this)) {
830                 flags |= DateUtils.FORMAT_24HOUR;
831             }
832         }
833         when = DateUtils.formatDateRange(this, mStartMillis, mEndMillis, flags);
834         setTextCommon(R.id.when, when);
835
836         // Show the event timezone if it is different from the local timezone
837         Time time = new Time();
838         String localTimezone = time.timezone;
839         if (allDay) {
840             localTimezone = Time.TIMEZONE_UTC;
841         }
842         if (eventTimezone != null && !localTimezone.equals(eventTimezone) && !allDay) {
843             String displayName;
844             TimeZone tz = TimeZone.getTimeZone(localTimezone);
845             if (tz == null || tz.getID().equals("GMT")) {
846                 displayName = localTimezone;
847             } else {
848                 displayName = tz.getDisplayName();
849             }
850
851             setTextCommon(R.id.timezone, displayName);
852         } else {
853             setVisibilityCommon(R.id.timezone_container, View.GONE);
854         }
855
856         // Repeat
857         if (rRule != null) {
858             EventRecurrence eventRecurrence = new EventRecurrence();
859             eventRecurrence.parse(rRule);
860             Time date = new Time();
861             if (allDay) {
862                 date.timezone = Time.TIMEZONE_UTC;
863             }
864             date.set(mStartMillis);
865             eventRecurrence.setStartDate(date);
866             String repeatString = EventRecurrenceFormatter.getRepeatString(getResources(),
867                     eventRecurrence);
868             setTextCommon(R.id.repeat, repeatString);
869         } else {
870             setVisibilityCommon(R.id.repeat_container, View.GONE);
871         }
872
873         // Where
874         if (location == null || location.length() == 0) {
875             setVisibilityCommon(R.id.where, View.GONE);
876         } else {
877             final TextView textView = (TextView) findViewById(R.id.where);
878             if (textView != null) {
879                     textView.setAutoLinkMask(0);
880                     textView.setText(location);
881                     Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
882                     textView.setOnTouchListener(new OnTouchListener() {
883                         public boolean onTouch(View v, MotionEvent event) {
884                             try {
885                                 return v.onTouchEvent(event);
886                             } catch (ActivityNotFoundException e) {
887                                 // ignore
888                                 return true;
889                             }
890                         }
891                     });
892             }
893         }
894
895         // Description
896         if (description == null || description.length() == 0) {
897             setVisibilityCommon(R.id.description, View.GONE);
898         } else {
899             setTextCommon(R.id.description, description);
900         }
901
902         // Calendar
903         if (mCalendarsCursor != null) {
904             String calendarName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
905             setTextCommon(R.id.calendar, calendarName);
906         } else {
907             setVisibilityCommon(R.id.calendar_container, View.GONE);
908         }
909     }
910
911     private void updateAttendees() {
912         LinearLayout attendeesLayout = (LinearLayout) findViewById(R.id.attendee_list);
913         attendeesLayout.removeAllViewsInLayout();
914         ++mUpdateCounts;
915         if(mAcceptedAttendees.size() == 0 && mDeclinedAttendees.size() == 0 &&
916                 mTentativeAttendees.size() == mNoResponseAttendees.size()) {
917             // If all guests have no response just list them as guests,
918             CharSequence guestsLabel = getResources().getText(R.string.attendees_label);
919             addAttendeesToLayout(mNoResponseAttendees, attendeesLayout, guestsLabel);
920         } else {
921             // If we have any responses then divide them up by response
922             CharSequence[] entries;
923             entries = getResources().getTextArray(R.array.response_labels2);
924             addAttendeesToLayout(mAcceptedAttendees, attendeesLayout, entries[0]);
925             addAttendeesToLayout(mDeclinedAttendees, attendeesLayout, entries[2]);
926             addAttendeesToLayout(mTentativeAttendees, attendeesLayout, entries[1]);
927         }
928     }
929
930     private void addAttendeesToLayout(ArrayList<Attendee> attendees, LinearLayout attendeeList,
931             CharSequence sectionTitle) {
932         if (attendees.size() == 0) {
933             return;
934         }
935
936         ContentResolver cr = getContentResolver();
937         // Yes/No/Maybe Title
938         View titleView = mLayoutInflater.inflate(R.layout.contact_item, null);
939         titleView.findViewById(R.id.badge).setVisibility(View.GONE);
940         View divider = titleView.findViewById(R.id.separator);
941         divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
942
943         TextView title = (TextView) titleView.findViewById(R.id.name);
944         title.setText(getString(R.string.response_label, sectionTitle, attendees.size()));
945         title.setTextAppearance(this, R.style.TextAppearance_EventInfo_Label);
946         attendeeList.addView(titleView);
947
948         // Attendees
949         int numOfAttendees = attendees.size();
950         StringBuilder selection = new StringBuilder(Email.DATA + " IN (");
951         String[] selectionArgs = new String[numOfAttendees];
952
953         for (int i = 0; i < numOfAttendees; ++i) {
954             Attendee attendee = attendees.get(i);
955             selectionArgs[i] = attendee.mEmail;
956
957             View v = mLayoutInflater.inflate(R.layout.contact_item, null);
958             v.setTag(attendee);
959
960             View separator = v.findViewById(R.id.separator);
961             separator.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
962
963             // Text
964             TextView tv = (TextView) v.findViewById(R.id.name);
965             String name = attendee.mName;
966             if (name == null || name.length() == 0) {
967                 name = attendee.mEmail;
968             }
969             tv.setText(name);
970
971             ViewHolder vh = new ViewHolder();
972             vh.badge = (QuickContactBadge) v.findViewById(R.id.badge);
973             vh.badge.assignContactFromEmail(attendee.mEmail, true);
974             vh.presence = (ImageView) v.findViewById(R.id.presence);
975             mViewHolders.put(attendee.mEmail, vh);
976
977             if (i == 0) {
978                 selection.append('?');
979             } else {
980                 selection.append(", ?");
981             }
982
983             attendeeList.addView(v);
984         }
985         selection.append(')');
986
987         mPresenceQueryHandler.startQuery(mUpdateCounts, attendees, CONTACT_DATA_WITH_PRESENCE_URI,
988                 PRESENCE_PROJECTION, selection.toString(), selectionArgs, null);
989     }
990
991     private class PresenceQueryHandler extends AsyncQueryHandler {
992         Context mContext;
993         ContentResolver mContentResolver;
994
995         public PresenceQueryHandler(Context context, ContentResolver cr) {
996             super(cr);
997             mContentResolver = cr;
998             mContext = context;
999         }
1000
1001         @Override
1002         protected void onQueryComplete(int queryIndex, Object cookie, Cursor cursor) {
1003             if (cursor == null) {
1004                 if (DEBUG) {
1005                     Log.e(TAG, "onQueryComplete: cursor == null");
1006                 }
1007                 return;
1008             }
1009
1010             try {
1011                 cursor.moveToPosition(-1);
1012                 while (cursor.moveToNext()) {
1013                     String email = cursor.getString(PRESENCE_PROJECTION_EMAIL_INDEX);
1014                     int contactId = cursor.getInt(PRESENCE_PROJECTION_CONTACT_ID_INDEX);
1015                     ViewHolder vh = mViewHolders.get(email);
1016                     int photoId = cursor.getInt(PRESENCE_PROJECTION_PHOTO_ID_INDEX);
1017                     if (DEBUG) {
1018                         Log.e(TAG, "onQueryComplete Id: " + contactId + " PhotoId: " + photoId
1019                                 + " Email: " + email);
1020                     }
1021                     if (vh == null) {
1022                         continue;
1023                     }
1024                     ImageView presenceView = vh.presence;
1025                     if (presenceView != null) {
1026                         int status = cursor.getInt(PRESENCE_PROJECTION_PRESENCE_INDEX);
1027                         presenceView.setImageResource(Presence.getPresenceIconResourceId(status));
1028                         presenceView.setVisibility(View.VISIBLE);
1029                     }
1030
1031                     if (photoId > 0 && vh.updateCounts < queryIndex) {
1032                         vh.updateCounts = queryIndex;
1033                         Uri personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
1034
1035                         // TODO, modify to batch queries together
1036                         ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext, vh.badge,
1037                                 personUri, R.drawable.ic_contact_picture);
1038                     }
1039                 }
1040             } finally {
1041                 cursor.close();
1042             }
1043         }
1044     }
1045
1046     void updateResponse() {
1047         // we only let the user accept/reject/etc. a meeting if:
1048         // a) you can edit the event's containing calendar AND
1049         // b) you're not the organizer and only attendee
1050         // (if the attendee data has been hidden, the visible number of attendees
1051         // will be 1 -- the calendar owner's).
1052         // (there are more cases involved to be 100% accurate, such as
1053         // paying attention to whether or not an attendee status was
1054         // included in the feed, but we're currently omitting those corner cases
1055         // for simplicity).
1056         if (!mCanModifyCalendar || (mHasAttendeeData && mIsOrganizer && mNumOfAttendees <= 1)) {
1057             setVisibilityCommon(R.id.response_container, View.GONE);
1058             return;
1059         }
1060
1061         setVisibilityCommon(R.id.response_container, View.VISIBLE);
1062
1063         Spinner spinner = (Spinner) findViewById(R.id.response_value);
1064
1065         mResponseOffset = 0;
1066
1067         /* If the user has previously responded to this event
1068          * we should not allow them to select no response again.
1069          * Switch the entries to a set of entries without the
1070          * no response option.
1071          */
1072         if ((mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_INVITED)
1073                 && (mOriginalAttendeeResponse != ATTENDEE_NO_RESPONSE)
1074                 && (mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_NONE)) {
1075             CharSequence[] entries;
1076             entries = getResources().getTextArray(R.array.response_labels2);
1077             mResponseOffset = -1;
1078             ArrayAdapter<CharSequence> adapter =
1079                 new ArrayAdapter<CharSequence>(this,
1080                         android.R.layout.simple_spinner_item, entries);
1081             adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
1082             spinner.setAdapter(adapter);
1083         }
1084
1085         int index;
1086         if (mAttendeeResponseFromIntent != ATTENDEE_NO_RESPONSE) {
1087             index = findResponseIndexFor(mAttendeeResponseFromIntent);
1088         } else {
1089             index = findResponseIndexFor(mOriginalAttendeeResponse);
1090         }
1091         spinner.setSelection(index + mResponseOffset);
1092         spinner.setOnItemSelectedListener(this);
1093     }
1094
1095     private void setTextCommon(int id, CharSequence text) {
1096         TextView textView = (TextView) findViewById(id);
1097         if (textView == null)
1098             return;
1099         textView.setText(text);
1100     }
1101
1102     private void setVisibilityCommon(int id, int visibility) {
1103         View v = findViewById(id);
1104         if (v != null) {
1105             v.setVisibility(visibility);
1106         }
1107         return;
1108     }
1109
1110     /**
1111      * Taken from com.google.android.gm.HtmlConversationActivity
1112      *
1113      * Send the intent that shows the Contact info corresponding to the email address.
1114      */
1115     public void showContactInfo(Attendee attendee, Rect rect) {
1116         // First perform lookup query to find existing contact
1117         final ContentResolver resolver = getContentResolver();
1118         final String address = attendee.mEmail;
1119         final Uri dataUri = Uri.withAppendedPath(CommonDataKinds.Email.CONTENT_FILTER_URI,
1120                 Uri.encode(address));
1121         final Uri lookupUri = ContactsContract.Data.getContactLookupUri(resolver, dataUri);
1122
1123         if (lookupUri != null) {
1124             // Found matching contact, trigger QuickContact
1125             QuickContact.showQuickContact(this, rect, lookupUri, QuickContact.MODE_MEDIUM, null);
1126         } else {
1127             // No matching contact, ask user to create one
1128             final Uri mailUri = Uri.fromParts("mailto", address, null);
1129             final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, mailUri);
1130
1131             // Pass along full E-mail string for possible create dialog
1132             Rfc822Token sender = new Rfc822Token(attendee.mName, attendee.mEmail, null);
1133             intent.putExtra(Intents.EXTRA_CREATE_DESCRIPTION, sender.toString());
1134
1135             // Only provide personal name hint if we have one
1136             final String senderPersonal = attendee.mName;
1137             if (!TextUtils.isEmpty(senderPersonal)) {
1138                 intent.putExtra(Intents.Insert.NAME, senderPersonal);
1139             }
1140
1141             startActivity(intent);
1142         }
1143     }
1144 }