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