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