OSDN Git Service

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