OSDN Git Service

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