OSDN Git Service

dde9934e2eed6a9bfae3016a23c1b02a868e6d81
[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_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,
190     };
191
192     private LinearLayout mRemindersContainer;
193     private LinearLayout mOrganizerContainer;
194     private TextView mOrganizerView;
195
196     private Uri mUri;
197     private long mEventId;
198     private Cursor mEventCursor;
199     private Cursor mAttendeesCursor;
200     private Cursor mCalendarsCursor;
201
202     private long mStartMillis;
203     private long mEndMillis;
204
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;
214
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;
220
221     private DeleteEventHelper mDeleteEventHelper;
222     private EditResponseHelper mEditResponseHelper;
223
224     private int mResponseOffset;
225     private int mOriginalAttendeeResponse;
226     private int mAttendeeResponseFromIntent = ATTENDEE_NO_RESPONSE;
227     private boolean mIsRepeating;
228
229     private Pattern mWildcardPattern = Pattern.compile("^.*$");
230     private LayoutInflater mLayoutInflater;
231     private LinearLayout mReminderAdder;
232
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;
237         ImageView presence;
238         int updateCounts;
239     }
240     private HashMap<String, ViewHolder> mViewHolders = new HashMap<String, ViewHolder>();
241     private PresenceQueryHandler mPresenceQueryHandler;
242
243     private static final Uri CONTACT_DATA_WITH_PRESENCE_URI = Data.CONTENT_URI;
244
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;
249
250     private static final String[] PRESENCE_PROJECTION = new String[] {
251         Email.CONTACT_ID,           // 0
252         Email.CONTACT_PRESENCE,     // 1
253         Email.DATA,                 // 2
254         Email.PHOTO_ID,             // 3
255     };
256
257     ArrayList<Attendee> mAcceptedAttendees = new ArrayList<Attendee>();
258     ArrayList<Attendee> mDeclinedAttendees = new ArrayList<Attendee>();
259     ArrayList<Attendee> mTentativeAttendees = new ArrayList<Attendee>();
260     private int mColor;
261
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();
269     }
270
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) {
275             return;
276         }
277
278         // If this is not a repeating event, then don't display the dialog
279         // asking which events to change.
280         if (!mIsRepeating) {
281             return;
282         }
283
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) {
288             return;
289         }
290
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());
294     }
295
296     public void onNothingSelected(AdapterView<?> parent) {
297     }
298
299     @Override
300     protected void onCreate(Bundle icicle) {
301         super.onCreate(icicle);
302
303         // Event cursor
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.
313             finish();
314             return;
315         }
316
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);
323
324         // Calendars cursor
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);
332         }
333         String eventOrganizer = mEventCursor.getString(EVENT_INDEX_ORGANIZER);
334         mIsOrganizer = mCalendarOwnerAccount.equals(eventOrganizer);
335         mHasAttendeeData = mEventCursor.getInt(EVENT_INDEX_HAS_ATTENDEE_DATA) != 0;
336
337         updateView();
338
339         // Attendees cursor
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();
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 = CalendarPreferenceActivity.getSharedPreferences(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
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
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      */
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
458         Attendee(String name, String email) {
459             mName = name;
460             mEmail = email;
461         }
462     }
463
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
525     private void initCalendarsCursor() {
526         if (mCalendarsCursor != null) {
527             mCalendarsCursor.moveToFirst();
528         }
529     }
530
531     @Override
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             // TODO Run this in a background process.
545             cr.applyBatch(Calendars.CONTENT_URI.getAuthority(), ops);
546             // Update the "hasAlarm" field for the event
547             Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
548             int len = reminderMinutes.size();
549             ContentValues values = new ContentValues();
550             values.put(Events.HAS_ALARM, (len > 0) ? 1 : 0);
551             cr.update(uri, values, null, null);
552         } catch (RemoteException e) {
553             Log.w(TAG, "Ignoring exception: ", e);
554         } catch (OperationApplicationException e) {
555             Log.w(TAG, "Ignoring exception: ", e);
556         }
557
558         changed |= saveResponse(cr);
559         if (changed) {
560             Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show();
561         }
562     }
563
564     @Override
565     public boolean onCreateOptionsMenu(Menu menu) {
566         MenuItem item;
567         item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0,
568                 R.string.add_new_reminder);
569         item.setIcon(R.drawable.ic_menu_reminder);
570         item.setAlphabeticShortcut('r');
571
572         item = menu.add(MENU_GROUP_EDIT, MENU_EDIT, 0, R.string.edit_event_label);
573         item.setIcon(android.R.drawable.ic_menu_edit);
574         item.setAlphabeticShortcut('e');
575
576         item = menu.add(MENU_GROUP_DELETE, MENU_DELETE, 0, R.string.delete_event_label);
577         item.setIcon(android.R.drawable.ic_menu_delete);
578
579         return super.onCreateOptionsMenu(menu);
580     }
581
582     @Override
583     public boolean onPrepareOptionsMenu(Menu menu) {
584         boolean canAddReminders = canAddReminders();
585         menu.setGroupVisible(MENU_GROUP_REMINDER, canAddReminders);
586         menu.setGroupEnabled(MENU_GROUP_REMINDER, canAddReminders);
587
588         menu.setGroupVisible(MENU_GROUP_EDIT, mCanModifyEvent);
589         menu.setGroupEnabled(MENU_GROUP_EDIT, mCanModifyEvent);
590         menu.setGroupVisible(MENU_GROUP_DELETE, mCanModifyCalendar);
591         menu.setGroupEnabled(MENU_GROUP_DELETE, mCanModifyCalendar);
592
593         return super.onPrepareOptionsMenu(menu);
594     }
595
596     private boolean canAddReminders() {
597         return !mIsBusyFreeCalendar && mReminderItems.size() < MAX_REMINDERS;
598     }
599
600     private void addReminder() {
601         // TODO: when adding a new reminder, make it different from the
602         // last one in the list (if any).
603         if (mDefaultReminderMinutes == 0) {
604             EditEvent.addReminder(this, this, mReminderItems,
605                     mReminderValues, mReminderLabels, 10 /* minutes */);
606         } else {
607             EditEvent.addReminder(this, this, mReminderItems,
608                     mReminderValues, mReminderLabels, mDefaultReminderMinutes);
609         }
610         updateRemindersVisibility();
611     }
612
613     @Override
614     public boolean onOptionsItemSelected(MenuItem item) {
615         super.onOptionsItemSelected(item);
616         switch (item.getItemId()) {
617         case MENU_ADD_REMINDER:
618             addReminder();
619             break;
620         case MENU_EDIT:
621             doEdit();
622             break;
623         case MENU_DELETE:
624             doDelete();
625             break;
626         }
627         return true;
628     }
629
630     @Override
631     public boolean onKeyDown(int keyCode, KeyEvent event) {
632         if (keyCode == KeyEvent.KEYCODE_DEL) {
633             doDelete();
634             return true;
635         }
636         return super.onKeyDown(keyCode, event);
637     }
638
639     private void updateRemindersVisibility() {
640         if (mIsBusyFreeCalendar) {
641             mRemindersContainer.setVisibility(View.GONE);
642         } else {
643             mRemindersContainer.setVisibility(View.VISIBLE);
644             mReminderAdder.setVisibility(canAddReminders() ? View.VISIBLE : View.GONE);
645         }
646     }
647
648     /**
649      * Saves the response to an invitation if the user changed the response.
650      * Returns true if the database was updated.
651      *
652      * @param cr the ContentResolver
653      * @return true if the database was changed
654      */
655     private boolean saveResponse(ContentResolver cr) {
656         if (mAttendeesCursor == null || mEventCursor == null) {
657             return false;
658         }
659         Spinner spinner = (Spinner) findViewById(R.id.response_value);
660         int position = spinner.getSelectedItemPosition() - mResponseOffset;
661         if (position <= 0) {
662             return false;
663         }
664
665         int status = ATTENDEE_VALUES[position];
666
667         // If the status has not changed, then don't update the database
668         if (status == mOriginalAttendeeResponse) {
669             return false;
670         }
671
672         if (!mIsRepeating) {
673             // This is a non-repeating event
674             updateResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
675             return true;
676         }
677
678         // This is a repeating event
679         int whichEvents = mEditResponseHelper.getWhichEvents();
680         switch (whichEvents) {
681             case -1:
682                 return false;
683             case UPDATE_SINGLE:
684                 createExceptionResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
685                 return true;
686             case UPDATE_ALL:
687                 updateResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
688                 return true;
689             default:
690                 Log.e(TAG, "Unexpected choice for updating invitation response");
691                 break;
692         }
693         return false;
694     }
695
696     private void updateResponse(ContentResolver cr, long eventId, long attendeeId, int status) {
697         // Update the attendee status in the attendees table.  the provider
698         // takes care of updating the self attendance status.
699         ContentValues values = new ContentValues();
700
701         if (!TextUtils.isEmpty(mCalendarOwnerAccount)) {
702             values.put(Attendees.ATTENDEE_EMAIL, mCalendarOwnerAccount);
703         }
704         values.put(Attendees.ATTENDEE_STATUS, status);
705         values.put(Attendees.EVENT_ID, eventId);
706
707         Uri uri = ContentUris.withAppendedId(Attendees.CONTENT_URI, attendeeId);
708         cr.update(uri, values, null /* where */, null /* selection args */);
709     }
710
711     private void createExceptionResponse(ContentResolver cr, long eventId,
712             long attendeeId, int status) {
713         // Fetch information about the repeating event.
714         Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
715         Cursor cursor = cr.query(uri, EVENT_PROJECTION, null, null, null);
716         if (cursor == null) {
717             return;
718         }
719         if(!cursor.moveToFirst()) {
720             cursor.close();
721             return;
722         }
723
724         try {
725             ContentValues values = new ContentValues();
726
727             String title = cursor.getString(EVENT_INDEX_TITLE);
728             String timezone = cursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
729             int calendarId = cursor.getInt(EVENT_INDEX_CALENDAR_ID);
730             boolean allDay = cursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
731             String syncId = cursor.getString(EVENT_INDEX_SYNC_ID);
732
733             values.put(Events.TITLE, title);
734             values.put(Events.EVENT_TIMEZONE, timezone);
735             values.put(Events.ALL_DAY, allDay ? 1 : 0);
736             values.put(Events.CALENDAR_ID, calendarId);
737             values.put(Events.DTSTART, mStartMillis);
738             values.put(Events.DTEND, mEndMillis);
739             values.put(Events.ORIGINAL_EVENT, syncId);
740             values.put(Events.ORIGINAL_INSTANCE_TIME, mStartMillis);
741             values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0);
742             values.put(Events.STATUS, Events.STATUS_CONFIRMED);
743             values.put(Events.SELF_ATTENDEE_STATUS, status);
744
745             // Create a recurrence exception
746             cr.insert(Events.CONTENT_URI, values);
747         } finally {
748             cursor.close();
749         }
750     }
751
752     private int findResponseIndexFor(int response) {
753         int size = ATTENDEE_VALUES.length;
754         for (int index = 0; index < size; index++) {
755             if (ATTENDEE_VALUES[index] == response) {
756                 return index;
757             }
758         }
759         return 0;
760     }
761
762     private void doEdit() {
763         Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
764         Intent intent = new Intent(Intent.ACTION_EDIT, uri);
765         intent.putExtra(Calendar.EVENT_BEGIN_TIME, mStartMillis);
766         intent.putExtra(Calendar.EVENT_END_TIME, mEndMillis);
767         intent.setClass(EventInfoActivity.this, EditEvent.class);
768         startActivity(intent);
769         finish();
770     }
771
772     private void doDelete() {
773         mDeleteEventHelper.delete(mStartMillis, mEndMillis, mEventCursor, -1);
774     }
775
776     private void updateView() {
777         if (mEventCursor == null) {
778             return;
779         }
780
781         String eventName = mEventCursor.getString(EVENT_INDEX_TITLE);
782         if (eventName == null || eventName.length() == 0) {
783             Resources res = getResources();
784             eventName = res.getString(R.string.no_title_label);
785         }
786
787         boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
788         String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION);
789         String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION);
790         String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
791         boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
792         String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
793         mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff;
794
795         View calBackground = findViewById(R.id.cal_background);
796         calBackground.setBackgroundColor(mColor);
797
798         TextView title = (TextView) findViewById(R.id.title);
799         title.setTextColor(mColor);
800
801         View divider = findViewById(R.id.divider);
802         divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
803
804         // What
805         if (eventName != null) {
806             setTextCommon(R.id.title, eventName);
807         }
808
809         // When
810         String when;
811         int flags;
812         if (allDay) {
813             flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE;
814         } else {
815             flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE;
816             if (DateFormat.is24HourFormat(this)) {
817                 flags |= DateUtils.FORMAT_24HOUR;
818             }
819         }
820         when = DateUtils.formatDateRange(this, mStartMillis, mEndMillis, flags);
821         setTextCommon(R.id.when, when);
822
823         // Show the event timezone if it is different from the local timezone
824         Time time = new Time();
825         String localTimezone = time.timezone;
826         if (allDay) {
827             localTimezone = Time.TIMEZONE_UTC;
828         }
829         if (eventTimezone != null && !localTimezone.equals(eventTimezone) && !allDay) {
830             String displayName;
831             TimeZone tz = TimeZone.getTimeZone(localTimezone);
832             if (tz == null || tz.getID().equals("GMT")) {
833                 displayName = localTimezone;
834             } else {
835                 displayName = tz.getDisplayName();
836             }
837
838             setTextCommon(R.id.timezone, displayName);
839         } else {
840             setVisibilityCommon(R.id.timezone_container, View.GONE);
841         }
842
843         // Repeat
844         if (rRule != null) {
845             EventRecurrence eventRecurrence = new EventRecurrence();
846             eventRecurrence.parse(rRule);
847             Time date = new Time();
848             if (allDay) {
849                 date.timezone = Time.TIMEZONE_UTC;
850             }
851             date.set(mStartMillis);
852             eventRecurrence.setStartDate(date);
853             String repeatString = EventRecurrenceFormatter.getRepeatString(getResources(),
854                     eventRecurrence);
855             setTextCommon(R.id.repeat, repeatString);
856         } else {
857             setVisibilityCommon(R.id.repeat_container, View.GONE);
858         }
859
860         // Where
861         if (location == null || location.length() == 0) {
862             setVisibilityCommon(R.id.where, View.GONE);
863         } else {
864             final TextView textView = (TextView) findViewById(R.id.where);
865             if (textView != null) {
866                     textView.setAutoLinkMask(0);
867                     textView.setText(location);
868                     Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
869                     textView.setOnTouchListener(new OnTouchListener() {
870                         public boolean onTouch(View v, MotionEvent event) {
871                             try {
872                                 return v.onTouchEvent(event);
873                             } catch (ActivityNotFoundException e) {
874                                 // ignore
875                                 return true;
876                             }
877                         }
878                     });
879             }
880         }
881
882         // Description
883         if (description == null || description.length() == 0) {
884             setVisibilityCommon(R.id.description, View.GONE);
885         } else {
886             setTextCommon(R.id.description, description);
887         }
888
889         // Calendar
890         if (mCalendarsCursor != null) {
891             String calendarName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
892             setTextCommon(R.id.calendar, calendarName);
893         } else {
894             setVisibilityCommon(R.id.calendar_container, View.GONE);
895         }
896     }
897
898     private void updateAttendees() {
899         CharSequence[] entries;
900         entries = getResources().getTextArray(R.array.response_labels2);
901         LinearLayout attendeesLayout = (LinearLayout) findViewById(R.id.attendee_list);
902         attendeesLayout.removeAllViewsInLayout();
903         ++mUpdateCounts;
904         addAttendeesToLayout(mAcceptedAttendees, attendeesLayout, entries[0]);
905         addAttendeesToLayout(mDeclinedAttendees, attendeesLayout, entries[2]);
906         addAttendeesToLayout(mTentativeAttendees, attendeesLayout, entries[1]);
907     }
908
909     private void addAttendeesToLayout(ArrayList<Attendee> attendees, LinearLayout attendeeList,
910             CharSequence sectionTitle) {
911         if (attendees.size() == 0) {
912             return;
913         }
914
915         ContentResolver cr = getContentResolver();
916         // Yes/No/Maybe Title
917         View titleView = mLayoutInflater.inflate(R.layout.contact_item, null);
918         titleView.findViewById(R.id.badge).setVisibility(View.GONE);
919         View divider = titleView.findViewById(R.id.separator);
920         divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
921
922         TextView title = (TextView) titleView.findViewById(R.id.name);
923         title.setText(getString(R.string.response_label, sectionTitle, attendees.size()));
924         title.setTextAppearance(this, R.style.TextAppearance_EventInfo_Label);
925         attendeeList.addView(titleView);
926
927         // Attendees
928         int numOfAttendees = attendees.size();
929         StringBuilder selection = new StringBuilder(Email.DATA + " IN (");
930         String[] selectionArgs = new String[numOfAttendees];
931
932         for (int i = 0; i < numOfAttendees; ++i) {
933             Attendee attendee = attendees.get(i);
934             selectionArgs[i] = attendee.mEmail;
935
936             View v = mLayoutInflater.inflate(R.layout.contact_item, null);
937             v.setTag(attendee);
938
939             View separator = v.findViewById(R.id.separator);
940             separator.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
941
942             // Text
943             TextView tv = (TextView) v.findViewById(R.id.name);
944             String name = attendee.mName;
945             if (name == null || name.length() == 0) {
946                 name = attendee.mEmail;
947             }
948             tv.setText(name);
949
950             ViewHolder vh = new ViewHolder();
951             vh.badge = (QuickContactBadge) v.findViewById(R.id.badge);
952             vh.badge.assignContactFromEmail(attendee.mEmail, true);
953             vh.presence = (ImageView) v.findViewById(R.id.presence);
954             mViewHolders.put(attendee.mEmail, vh);
955
956             if (i == 0) {
957                 selection.append('?');
958             } else {
959                 selection.append(", ?");
960             }
961
962             attendeeList.addView(v);
963         }
964         selection.append(')');
965
966         mPresenceQueryHandler.startQuery(mUpdateCounts, attendees, CONTACT_DATA_WITH_PRESENCE_URI,
967                 PRESENCE_PROJECTION, selection.toString(), selectionArgs, null);
968     }
969
970     private class PresenceQueryHandler extends AsyncQueryHandler {
971         Context mContext;
972         ContentResolver mContentResolver;
973
974         public PresenceQueryHandler(Context context, ContentResolver cr) {
975             super(cr);
976             mContentResolver = cr;
977             mContext = context;
978         }
979
980         @Override
981         protected void onQueryComplete(int queryIndex, Object cookie, Cursor cursor) {
982             if (cursor == null) {
983                 if (DEBUG) {
984                     Log.e(TAG, "onQueryComplete: cursor == null");
985                 }
986                 return;
987             }
988
989             try {
990                 cursor.moveToPosition(-1);
991                 while (cursor.moveToNext()) {
992                     String email = cursor.getString(PRESENCE_PROJECTION_EMAIL_INDEX);
993                     int contactId = cursor.getInt(PRESENCE_PROJECTION_CONTACT_ID_INDEX);
994                     ViewHolder vh = mViewHolders.get(email);
995                     int photoId = cursor.getInt(PRESENCE_PROJECTION_PHOTO_ID_INDEX);
996                     if (DEBUG) {
997                         Log.e(TAG, "onQueryComplete Id: " + contactId + " PhotoId: " + photoId
998                                 + " Email: " + email);
999                     }
1000                     if (vh == null) {
1001                         continue;
1002                     }
1003                     ImageView presenceView = vh.presence;
1004                     if (presenceView != null) {
1005                         int status = cursor.getInt(PRESENCE_PROJECTION_PRESENCE_INDEX);
1006                         presenceView.setImageResource(Presence.getPresenceIconResourceId(status));
1007                         presenceView.setVisibility(View.VISIBLE);
1008                     }
1009
1010                     if (photoId > 0 && vh.updateCounts < queryIndex) {
1011                         vh.updateCounts = queryIndex;
1012                         Uri personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
1013
1014                         // TODO, modify to batch queries together
1015                         ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext, vh.badge,
1016                                 personUri, R.drawable.ic_contact_picture);
1017                     }
1018                 }
1019             } finally {
1020                 cursor.close();
1021             }
1022         }
1023     }
1024
1025     void updateResponse() {
1026         // we only let the user accept/reject/etc. a meeting if:
1027         // a) you can edit the event's containing calendar AND
1028         // b) you're not the organizer and only attendee
1029         // (if the attendee data has been hidden, the visible number of attendees
1030         // will be 1 -- the calendar owner's).
1031         // (there are more cases involved to be 100% accurate, such as
1032         // paying attention to whether or not an attendee status was
1033         // included in the feed, but we're currently omitting those corner cases
1034         // for simplicity).
1035         if (!mCanModifyCalendar || (mHasAttendeeData && mIsOrganizer && mNumOfAttendees <= 1)) {
1036             setVisibilityCommon(R.id.response_container, View.GONE);
1037             return;
1038         }
1039
1040         setVisibilityCommon(R.id.response_container, View.VISIBLE);
1041
1042         Spinner spinner = (Spinner) findViewById(R.id.response_value);
1043
1044         mResponseOffset = 0;
1045
1046         /* If the user has previously responded to this event
1047          * we should not allow them to select no response again.
1048          * Switch the entries to a set of entries without the
1049          * no response option.
1050          */
1051         if ((mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_INVITED)
1052                 && (mOriginalAttendeeResponse != ATTENDEE_NO_RESPONSE)
1053                 && (mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_NONE)) {
1054             CharSequence[] entries;
1055             entries = getResources().getTextArray(R.array.response_labels2);
1056             mResponseOffset = -1;
1057             ArrayAdapter<CharSequence> adapter =
1058                 new ArrayAdapter<CharSequence>(this,
1059                         android.R.layout.simple_spinner_item, entries);
1060             adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
1061             spinner.setAdapter(adapter);
1062         }
1063
1064         int index;
1065         if (mAttendeeResponseFromIntent != ATTENDEE_NO_RESPONSE) {
1066             index = findResponseIndexFor(mAttendeeResponseFromIntent);
1067         } else {
1068             index = findResponseIndexFor(mOriginalAttendeeResponse);
1069         }
1070         spinner.setSelection(index + mResponseOffset);
1071         spinner.setOnItemSelectedListener(this);
1072     }
1073
1074     private void setTextCommon(int id, CharSequence text) {
1075         TextView textView = (TextView) findViewById(id);
1076         if (textView == null)
1077             return;
1078         textView.setText(text);
1079     }
1080
1081     private void setVisibilityCommon(int id, int visibility) {
1082         View v = findViewById(id);
1083         if (v != null) {
1084             v.setVisibility(visibility);
1085         }
1086         return;
1087     }
1088
1089     /**
1090      * Taken from com.google.android.gm.HtmlConversationActivity
1091      *
1092      * Send the intent that shows the Contact info corresponding to the email address.
1093      */
1094     public void showContactInfo(Attendee attendee, Rect rect) {
1095         // First perform lookup query to find existing contact
1096         final ContentResolver resolver = getContentResolver();
1097         final String address = attendee.mEmail;
1098         final Uri dataUri = Uri.withAppendedPath(CommonDataKinds.Email.CONTENT_FILTER_URI,
1099                 Uri.encode(address));
1100         final Uri lookupUri = ContactsContract.Data.getContactLookupUri(resolver, dataUri);
1101
1102         if (lookupUri != null) {
1103             // Found matching contact, trigger QuickContact
1104             QuickContact.showQuickContact(this, rect, lookupUri, QuickContact.MODE_MEDIUM, null);
1105         } else {
1106             // No matching contact, ask user to create one
1107             final Uri mailUri = Uri.fromParts("mailto", address, null);
1108             final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, mailUri);
1109
1110             // Pass along full E-mail string for possible create dialog
1111             Rfc822Token sender = new Rfc822Token(attendee.mName, attendee.mEmail, null);
1112             intent.putExtra(Intents.EXTRA_CREATE_DESCRIPTION, sender.toString());
1113
1114             // Only provide personal name hint if we have one
1115             final String senderPersonal = attendee.mName;
1116             if (!TextUtils.isEmpty(senderPersonal)) {
1117                 intent.putExtra(Intents.Insert.NAME, senderPersonal);
1118             }
1119
1120             startActivity(intent);
1121         }
1122     }
1123 }