EventInfoActivity.java revision 83f7ce18540aa5b8ed2402d178d35520cd725dea
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        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.format(CALENDARS_WHERE, mEventCursor.getLong(EVENT_INDEX_CALENDAR_ID));
335        mCalendarsCursor = managedQuery(uri, CALENDARS_PROJECTION, where, null, null);
336        mCalendarOwnerAccount = "";
337        if (mCalendarsCursor != null) {
338            mCalendarsCursor.moveToFirst();
339            mCalendarOwnerAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
340            mOrganizerCanRespond = mCalendarsCursor.getInt(CALENDARS_INDEX_OWNER_CAN_RESPOND) != 0;
341
342            String displayName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
343            mIsDuplicateName = isDuplicateName(displayName);
344        }
345        String eventOrganizer = mEventCursor.getString(EVENT_INDEX_ORGANIZER);
346        mIsOrganizer = mCalendarOwnerAccount.equalsIgnoreCase(eventOrganizer);
347        mHasAttendeeData = mEventCursor.getInt(EVENT_INDEX_HAS_ATTENDEE_DATA) != 0;
348
349        updateView();
350
351        // Attendees cursor
352        uri = Attendees.CONTENT_URI;
353        where = String.format(ATTENDEES_WHERE, mEventId);
354        mAttendeesCursor = managedQuery(uri, ATTENDEES_PROJECTION, where, null,
355                ATTENDEES_SORT_ORDER);
356        initAttendeesCursor();
357
358        mOrganizer = eventOrganizer;
359        mCanModifyCalendar =
360                mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) >= Calendars.CONTRIBUTOR_ACCESS;
361        mIsBusyFreeCalendar =
362                mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) == Calendars.FREEBUSY_ACCESS;
363
364        mCanModifyEvent = mCanModifyCalendar
365                && (mIsOrganizer || (mEventCursor.getInt(EVENT_INDEX_GUESTS_CAN_MODIFY) != 0));
366
367        // Initialize the reminder values array.
368        Resources r = getResources();
369        String[] strings = r.getStringArray(R.array.reminder_minutes_values);
370        int size = strings.length;
371        ArrayList<Integer> list = new ArrayList<Integer>(size);
372        for (int i = 0 ; i < size ; i++) {
373            list.add(Integer.parseInt(strings[i]));
374        }
375        mReminderValues = list;
376        String[] labels = r.getStringArray(R.array.reminder_minutes_labels);
377        mReminderLabels = new ArrayList<String>(Arrays.asList(labels));
378
379        SharedPreferences prefs = CalendarPreferenceActivity.getSharedPreferences(this);
380        String durationString =
381                prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0");
382        mDefaultReminderMinutes = Integer.parseInt(durationString);
383
384        // Reminders cursor
385        boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
386        if (hasAlarm) {
387            uri = Reminders.CONTENT_URI;
388            where = String.format(REMINDERS_WHERE, mEventId);
389            Cursor reminderCursor = cr.query(uri, REMINDERS_PROJECTION, where, null,
390                    REMINDERS_SORT);
391            try {
392                // First pass: collect all the custom reminder minutes (e.g.,
393                // a reminder of 8 minutes) into a global list.
394                while (reminderCursor.moveToNext()) {
395                    int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
396                    EditEvent.addMinutesToList(this, mReminderValues, mReminderLabels, minutes);
397                }
398
399                // Second pass: create the reminder spinners
400                reminderCursor.moveToPosition(-1);
401                while (reminderCursor.moveToNext()) {
402                    int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
403                    mOriginalMinutes.add(minutes);
404                    EditEvent.addReminder(this, this, mReminderItems, mReminderValues,
405                            mReminderLabels, minutes);
406                }
407            } finally {
408                reminderCursor.close();
409            }
410        }
411        mOriginalHasAlarm = hasAlarm;
412
413        // Setup the + Add Reminder Button
414        View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
415            public void onClick(View v) {
416                addReminder();
417            }
418        };
419        ImageButton reminderAddButton = (ImageButton) findViewById(R.id.reminder_add);
420        reminderAddButton.setOnClickListener(addReminderOnClickListener);
421
422        mReminderAdder = (LinearLayout) findViewById(R.id.reminder_adder);
423        updateRemindersVisibility();
424
425        mDeleteEventHelper = new DeleteEventHelper(this, true /* exit when done */);
426        mEditResponseHelper = new EditResponseHelper(this);
427    }
428
429    @Override
430    protected void onResume() {
431        super.onResume();
432        if (initEventCursor()) {
433            // The cursor is empty. This can happen if the event was deleted.
434            finish();
435            return;
436        }
437        initCalendarsCursor();
438        updateResponse();
439        updateTitle();
440    }
441
442    private void updateTitle() {
443        Resources res = getResources();
444        if (mCanModifyCalendar && !mIsOrganizer) {
445            setTitle(res.getString(R.string.event_info_title_invite));
446        } else {
447            setTitle(res.getString(R.string.event_info_title));
448        }
449    }
450
451    boolean isDuplicateName(String displayName) {
452        Cursor dupNameCursor = managedQuery(Calendars.CONTENT_URI, CALENDARS_PROJECTION,
453                CALENDARS_DUPLICATE_NAME_WHERE, new String[] {displayName}, null);
454        boolean isDuplicateName = false;
455        if(dupNameCursor != null) {
456            if (dupNameCursor.getCount() > 1) {
457                isDuplicateName = true;
458            }
459            dupNameCursor.close();
460        }
461        return isDuplicateName;
462    }
463
464    /**
465     * Initializes the event cursor, which is expected to point to the first
466     * (and only) result from a query.
467     * @return true if the cursor is empty.
468     */
469    private boolean initEventCursor() {
470        if ((mEventCursor == null) || (mEventCursor.getCount() == 0)) {
471            return true;
472        }
473        mEventCursor.moveToFirst();
474        mEventId = mEventCursor.getInt(EVENT_INDEX_ID);
475        String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
476        mIsRepeating = (rRule != null);
477        return false;
478    }
479
480    private static class Attendee {
481        String mName;
482        String mEmail;
483
484        Attendee(String name, String email) {
485            mName = name;
486            mEmail = email;
487        }
488    }
489
490    @SuppressWarnings("fallthrough")
491    private void initAttendeesCursor() {
492        mOriginalAttendeeResponse = ATTENDEE_NO_RESPONSE;
493        mCalendarOwnerAttendeeId = ATTENDEE_ID_NONE;
494        mNumOfAttendees = 0;
495        if (mAttendeesCursor != null) {
496            mNumOfAttendees = mAttendeesCursor.getCount();
497            if (mAttendeesCursor.moveToFirst()) {
498                mAcceptedAttendees.clear();
499                mDeclinedAttendees.clear();
500                mTentativeAttendees.clear();
501                mNoResponseAttendees.clear();
502
503                do {
504                    int status = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
505                    String name = mAttendeesCursor.getString(ATTENDEES_INDEX_NAME);
506                    String email = mAttendeesCursor.getString(ATTENDEES_INDEX_EMAIL);
507
508                    if (mAttendeesCursor.getInt(ATTENDEES_INDEX_RELATIONSHIP) ==
509                            Attendees.RELATIONSHIP_ORGANIZER) {
510                        // Overwrites the one from Event table if available
511                        if (name != null && name.length() > 0) {
512                            mOrganizer = name;
513                        } else if (email != null && email.length() > 0) {
514                            mOrganizer = email;
515                        }
516                    }
517
518                    if (mCalendarOwnerAttendeeId == ATTENDEE_ID_NONE &&
519                            mCalendarOwnerAccount.equalsIgnoreCase(email)) {
520                        mCalendarOwnerAttendeeId = mAttendeesCursor.getInt(ATTENDEES_INDEX_ID);
521                        mOriginalAttendeeResponse = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
522                    } else {
523                        // Don't show your own status in the list because:
524                        //  1) it doesn't make sense for event without other guests.
525                        //  2) there's a spinner for that for events with guests.
526                        switch(status) {
527                            case Attendees.ATTENDEE_STATUS_ACCEPTED:
528                                mAcceptedAttendees.add(new Attendee(name, email));
529                                break;
530                            case Attendees.ATTENDEE_STATUS_DECLINED:
531                                mDeclinedAttendees.add(new Attendee(name, email));
532                                break;
533                            case Attendees.ATTENDEE_STATUS_NONE:
534                                mNoResponseAttendees.add(new Attendee(name, email));
535                                // Fallthrough so that no response is a subset of tentative
536                            default:
537                                mTentativeAttendees.add(new Attendee(name, email));
538                        }
539                    }
540                } while (mAttendeesCursor.moveToNext());
541                mAttendeesCursor.moveToFirst();
542
543                updateAttendees();
544            }
545        }
546        // only show the organizer if we're not the organizer and if
547        // we have attendee data (might have been removed by the server
548        // for events with a lot of attendees).
549        if (!mIsOrganizer && mHasAttendeeData) {
550            mOrganizerContainer.setVisibility(View.VISIBLE);
551            mOrganizerView.setText(mOrganizer);
552        } else {
553            mOrganizerContainer.setVisibility(View.GONE);
554        }
555    }
556
557    private void initCalendarsCursor() {
558        if (mCalendarsCursor != null) {
559            mCalendarsCursor.moveToFirst();
560        }
561    }
562
563    @Override
564    public void onPause() {
565        super.onPause();
566        if (!isFinishing()) {
567            return;
568        }
569        ContentResolver cr = getContentResolver();
570        ArrayList<Integer> reminderMinutes = EditEvent.reminderItemsToMinutes(mReminderItems,
571                mReminderValues);
572        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(3);
573        boolean changed = EditEvent.saveReminders(ops, mEventId, reminderMinutes, mOriginalMinutes,
574                false /* no force save */);
575        try {
576            // TODO Run this in a background process.
577            cr.applyBatch(Calendars.CONTENT_URI.getAuthority(), ops);
578            // Update the "hasAlarm" field for the event
579            Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
580            int len = reminderMinutes.size();
581            boolean hasAlarm = len > 0;
582            if (hasAlarm != mOriginalHasAlarm) {
583                ContentValues values = new ContentValues();
584                values.put(Events.HAS_ALARM, hasAlarm ? 1 : 0);
585                cr.update(uri, values, null, null);
586            }
587        } catch (RemoteException e) {
588            Log.w(TAG, "Ignoring exception: ", e);
589        } catch (OperationApplicationException e) {
590            Log.w(TAG, "Ignoring exception: ", e);
591        }
592
593        changed |= saveResponse(cr);
594        if (changed) {
595            Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show();
596        }
597    }
598
599    @Override
600    public boolean onCreateOptionsMenu(Menu menu) {
601        MenuItem item;
602        item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0,
603                R.string.add_new_reminder);
604        item.setIcon(R.drawable.ic_menu_reminder);
605        item.setAlphabeticShortcut('r');
606
607        item = menu.add(MENU_GROUP_EDIT, MENU_EDIT, 0, R.string.edit_event_label);
608        item.setIcon(android.R.drawable.ic_menu_edit);
609        item.setAlphabeticShortcut('e');
610
611        item = menu.add(MENU_GROUP_DELETE, MENU_DELETE, 0, R.string.delete_event_label);
612        item.setIcon(android.R.drawable.ic_menu_delete);
613
614        return super.onCreateOptionsMenu(menu);
615    }
616
617    @Override
618    public boolean onPrepareOptionsMenu(Menu menu) {
619        boolean canAddReminders = canAddReminders();
620        menu.setGroupVisible(MENU_GROUP_REMINDER, canAddReminders);
621        menu.setGroupEnabled(MENU_GROUP_REMINDER, canAddReminders);
622
623        menu.setGroupVisible(MENU_GROUP_EDIT, mCanModifyEvent);
624        menu.setGroupEnabled(MENU_GROUP_EDIT, mCanModifyEvent);
625        menu.setGroupVisible(MENU_GROUP_DELETE, mCanModifyCalendar);
626        menu.setGroupEnabled(MENU_GROUP_DELETE, mCanModifyCalendar);
627
628        return super.onPrepareOptionsMenu(menu);
629    }
630
631    private boolean canAddReminders() {
632        return !mIsBusyFreeCalendar && mReminderItems.size() < MAX_REMINDERS;
633    }
634
635    private void addReminder() {
636        // TODO: when adding a new reminder, make it different from the
637        // last one in the list (if any).
638        if (mDefaultReminderMinutes == 0) {
639            EditEvent.addReminder(this, this, mReminderItems,
640                    mReminderValues, mReminderLabels, 10 /* minutes */);
641        } else {
642            EditEvent.addReminder(this, this, mReminderItems,
643                    mReminderValues, mReminderLabels, mDefaultReminderMinutes);
644        }
645        updateRemindersVisibility();
646    }
647
648    @Override
649    public boolean onOptionsItemSelected(MenuItem item) {
650        super.onOptionsItemSelected(item);
651        switch (item.getItemId()) {
652        case MENU_ADD_REMINDER:
653            addReminder();
654            break;
655        case MENU_EDIT:
656            doEdit();
657            break;
658        case MENU_DELETE:
659            doDelete();
660            break;
661        }
662        return true;
663    }
664
665    @Override
666    public boolean onKeyDown(int keyCode, KeyEvent event) {
667        if (keyCode == KeyEvent.KEYCODE_DEL) {
668            doDelete();
669            return true;
670        }
671        return super.onKeyDown(keyCode, event);
672    }
673
674    private void updateRemindersVisibility() {
675        if (mIsBusyFreeCalendar) {
676            mRemindersContainer.setVisibility(View.GONE);
677        } else {
678            mRemindersContainer.setVisibility(View.VISIBLE);
679            mReminderAdder.setVisibility(canAddReminders() ? View.VISIBLE : View.GONE);
680        }
681    }
682
683    /**
684     * Saves the response to an invitation if the user changed the response.
685     * Returns true if the database was updated.
686     *
687     * @param cr the ContentResolver
688     * @return true if the database was changed
689     */
690    private boolean saveResponse(ContentResolver cr) {
691        if (mAttendeesCursor == null || mEventCursor == null) {
692            return false;
693        }
694        Spinner spinner = (Spinner) findViewById(R.id.response_value);
695        int position = spinner.getSelectedItemPosition() - mResponseOffset;
696        if (position <= 0) {
697            return false;
698        }
699
700        int status = ATTENDEE_VALUES[position];
701
702        // If the status has not changed, then don't update the database
703        if (status == mOriginalAttendeeResponse) {
704            return false;
705        }
706
707        // If we never got an owner attendee id we can't set the status
708        if (mCalendarOwnerAttendeeId == ATTENDEE_ID_NONE) {
709            return false;
710        }
711
712        if (!mIsRepeating) {
713            // This is a non-repeating event
714            updateResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
715            return true;
716        }
717
718        // This is a repeating event
719        int whichEvents = mEditResponseHelper.getWhichEvents();
720        switch (whichEvents) {
721            case -1:
722                return false;
723            case UPDATE_SINGLE:
724                createExceptionResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
725                return true;
726            case UPDATE_ALL:
727                updateResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
728                return true;
729            default:
730                Log.e(TAG, "Unexpected choice for updating invitation response");
731                break;
732        }
733        return false;
734    }
735
736    private void updateResponse(ContentResolver cr, long eventId, long attendeeId, int status) {
737        // Update the attendee status in the attendees table.  the provider
738        // takes care of updating the self attendance status.
739        ContentValues values = new ContentValues();
740
741        if (!TextUtils.isEmpty(mCalendarOwnerAccount)) {
742            values.put(Attendees.ATTENDEE_EMAIL, mCalendarOwnerAccount);
743        }
744        values.put(Attendees.ATTENDEE_STATUS, status);
745        values.put(Attendees.EVENT_ID, eventId);
746
747        Uri uri = ContentUris.withAppendedId(Attendees.CONTENT_URI, attendeeId);
748        cr.update(uri, values, null /* where */, null /* selection args */);
749    }
750
751    private void createExceptionResponse(ContentResolver cr, long eventId,
752            long attendeeId, int status) {
753        // Fetch information about the repeating event.
754        Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
755        Cursor cursor = cr.query(uri, EVENT_PROJECTION, null, null, null);
756        if (cursor == null) {
757            return;
758        }
759        if(!cursor.moveToFirst()) {
760            cursor.close();
761            return;
762        }
763
764        try {
765            ContentValues values = new ContentValues();
766
767            String title = cursor.getString(EVENT_INDEX_TITLE);
768            String timezone = cursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
769            int calendarId = cursor.getInt(EVENT_INDEX_CALENDAR_ID);
770            boolean allDay = cursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
771            String syncId = cursor.getString(EVENT_INDEX_SYNC_ID);
772
773            values.put(Events.TITLE, title);
774            values.put(Events.EVENT_TIMEZONE, timezone);
775            values.put(Events.ALL_DAY, allDay ? 1 : 0);
776            values.put(Events.CALENDAR_ID, calendarId);
777            values.put(Events.DTSTART, mStartMillis);
778            values.put(Events.DTEND, mEndMillis);
779            values.put(Events.ORIGINAL_EVENT, syncId);
780            values.put(Events.ORIGINAL_INSTANCE_TIME, mStartMillis);
781            values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0);
782            values.put(Events.STATUS, Events.STATUS_CONFIRMED);
783            values.put(Events.SELF_ATTENDEE_STATUS, status);
784
785            // Create a recurrence exception
786            cr.insert(Events.CONTENT_URI, values);
787        } finally {
788            cursor.close();
789        }
790    }
791
792    private int findResponseIndexFor(int response) {
793        int size = ATTENDEE_VALUES.length;
794        for (int index = 0; index < size; index++) {
795            if (ATTENDEE_VALUES[index] == response) {
796                return index;
797            }
798        }
799        return 0;
800    }
801
802    private void doEdit() {
803        Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
804        Intent intent = new Intent(Intent.ACTION_EDIT, uri);
805        intent.putExtra(Calendar.EVENT_BEGIN_TIME, mStartMillis);
806        intent.putExtra(Calendar.EVENT_END_TIME, mEndMillis);
807        intent.setClass(EventInfoActivity.this, EditEvent.class);
808        startActivity(intent);
809        finish();
810    }
811
812    private void doDelete() {
813        mDeleteEventHelper.delete(mStartMillis, mEndMillis, mEventCursor, -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        ContentResolver cr = getContentResolver();
973        // Yes/No/Maybe Title
974        View titleView = mLayoutInflater.inflate(R.layout.contact_item, null);
975        titleView.findViewById(R.id.badge).setVisibility(View.GONE);
976        View divider = titleView.findViewById(R.id.separator);
977        divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
978
979        TextView title = (TextView) titleView.findViewById(R.id.name);
980        title.setText(getString(R.string.response_label, sectionTitle, attendees.size()));
981        title.setTextAppearance(this, R.style.TextAppearance_EventInfo_Label);
982        attendeeList.addView(titleView);
983
984        // Attendees
985        int numOfAttendees = attendees.size();
986        StringBuilder selection = new StringBuilder(Email.DATA + " IN (");
987        String[] selectionArgs = new String[numOfAttendees];
988
989        for (int i = 0; i < numOfAttendees; ++i) {
990            Attendee attendee = attendees.get(i);
991            selectionArgs[i] = attendee.mEmail;
992
993            View v = mLayoutInflater.inflate(R.layout.contact_item, null);
994            v.setTag(attendee);
995
996            View separator = v.findViewById(R.id.separator);
997            separator.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
998
999            // Text
1000            TextView tv = (TextView) v.findViewById(R.id.name);
1001            String name = attendee.mName;
1002            if (name == null || name.length() == 0) {
1003                name = attendee.mEmail;
1004            }
1005            tv.setText(name);
1006
1007            ViewHolder vh = new ViewHolder();
1008            vh.badge = (QuickContactBadge) v.findViewById(R.id.badge);
1009            vh.badge.assignContactFromEmail(attendee.mEmail, true);
1010            vh.presence = (ImageView) v.findViewById(R.id.presence);
1011            mViewHolders.put(attendee.mEmail, vh);
1012
1013            if (i == 0) {
1014                selection.append('?');
1015            } else {
1016                selection.append(", ?");
1017            }
1018
1019            attendeeList.addView(v);
1020        }
1021        selection.append(')');
1022
1023        mPresenceQueryHandler.startQuery(mUpdateCounts, attendees, CONTACT_DATA_WITH_PRESENCE_URI,
1024                PRESENCE_PROJECTION, selection.toString(), selectionArgs, null);
1025    }
1026
1027    private class PresenceQueryHandler extends AsyncQueryHandler {
1028        Context mContext;
1029        ContentResolver mContentResolver;
1030
1031        public PresenceQueryHandler(Context context, ContentResolver cr) {
1032            super(cr);
1033            mContentResolver = cr;
1034            mContext = context;
1035        }
1036
1037        @Override
1038        protected void onQueryComplete(int queryIndex, Object cookie, Cursor cursor) {
1039            if (cursor == null) {
1040                if (DEBUG) {
1041                    Log.e(TAG, "onQueryComplete: cursor == null");
1042                }
1043                return;
1044            }
1045
1046            try {
1047                cursor.moveToPosition(-1);
1048                while (cursor.moveToNext()) {
1049                    String email = cursor.getString(PRESENCE_PROJECTION_EMAIL_INDEX);
1050                    int contactId = cursor.getInt(PRESENCE_PROJECTION_CONTACT_ID_INDEX);
1051                    ViewHolder vh = mViewHolders.get(email);
1052                    int photoId = cursor.getInt(PRESENCE_PROJECTION_PHOTO_ID_INDEX);
1053                    if (DEBUG) {
1054                        Log.e(TAG, "onQueryComplete Id: " + contactId + " PhotoId: " + photoId
1055                                + " Email: " + email);
1056                    }
1057                    if (vh == null) {
1058                        continue;
1059                    }
1060                    ImageView presenceView = vh.presence;
1061                    if (presenceView != null) {
1062                        int status = cursor.getInt(PRESENCE_PROJECTION_PRESENCE_INDEX);
1063                        presenceView.setImageResource(Presence.getPresenceIconResourceId(status));
1064                        presenceView.setVisibility(View.VISIBLE);
1065                    }
1066
1067                    if (photoId > 0 && vh.updateCounts < queryIndex) {
1068                        vh.updateCounts = queryIndex;
1069                        Uri personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
1070
1071                        // TODO, modify to batch queries together
1072                        ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext, vh.badge,
1073                                personUri, R.drawable.ic_contact_picture);
1074                    }
1075                }
1076            } finally {
1077                cursor.close();
1078            }
1079        }
1080    }
1081
1082    void updateResponse() {
1083        // we only let the user accept/reject/etc. a meeting if:
1084        // a) you can edit the event's containing calendar AND
1085        // b) you're not the organizer and only attendee AND
1086        // c) organizerCanRespond is enabled for the calendar
1087        // (if the attendee data has been hidden, the visible number of attendees
1088        // will be 1 -- the calendar owner's).
1089        // (there are more cases involved to be 100% accurate, such as
1090        // paying attention to whether or not an attendee status was
1091        // included in the feed, but we're currently omitting those corner cases
1092        // for simplicity).
1093        if (!mCanModifyCalendar || (mHasAttendeeData && mIsOrganizer && mNumOfAttendees <= 1) ||
1094                (mIsOrganizer && !mOrganizerCanRespond)) {
1095            setVisibilityCommon(R.id.response_container, View.GONE);
1096            return;
1097        }
1098
1099        setVisibilityCommon(R.id.response_container, View.VISIBLE);
1100
1101        Spinner spinner = (Spinner) findViewById(R.id.response_value);
1102
1103        mResponseOffset = 0;
1104
1105        /* If the user has previously responded to this event
1106         * we should not allow them to select no response again.
1107         * Switch the entries to a set of entries without the
1108         * no response option.
1109         */
1110        if ((mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_INVITED)
1111                && (mOriginalAttendeeResponse != ATTENDEE_NO_RESPONSE)
1112                && (mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_NONE)) {
1113            CharSequence[] entries;
1114            entries = getResources().getTextArray(R.array.response_labels2);
1115            mResponseOffset = -1;
1116            ArrayAdapter<CharSequence> adapter =
1117                new ArrayAdapter<CharSequence>(this,
1118                        android.R.layout.simple_spinner_item, entries);
1119            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
1120            spinner.setAdapter(adapter);
1121        }
1122
1123        int index;
1124        if (mAttendeeResponseFromIntent != ATTENDEE_NO_RESPONSE) {
1125            index = findResponseIndexFor(mAttendeeResponseFromIntent);
1126        } else {
1127            index = findResponseIndexFor(mOriginalAttendeeResponse);
1128        }
1129        spinner.setSelection(index + mResponseOffset);
1130        spinner.setOnItemSelectedListener(this);
1131    }
1132
1133    private void setTextCommon(int id, CharSequence text) {
1134        TextView textView = (TextView) findViewById(id);
1135        if (textView == null)
1136            return;
1137        textView.setText(text);
1138    }
1139
1140    private void setVisibilityCommon(int id, int visibility) {
1141        View v = findViewById(id);
1142        if (v != null) {
1143            v.setVisibility(visibility);
1144        }
1145        return;
1146    }
1147
1148    /**
1149     * Taken from com.google.android.gm.HtmlConversationActivity
1150     *
1151     * Send the intent that shows the Contact info corresponding to the email address.
1152     */
1153    public void showContactInfo(Attendee attendee, Rect rect) {
1154        // First perform lookup query to find existing contact
1155        final ContentResolver resolver = getContentResolver();
1156        final String address = attendee.mEmail;
1157        final Uri dataUri = Uri.withAppendedPath(CommonDataKinds.Email.CONTENT_FILTER_URI,
1158                Uri.encode(address));
1159        final Uri lookupUri = ContactsContract.Data.getContactLookupUri(resolver, dataUri);
1160
1161        if (lookupUri != null) {
1162            // Found matching contact, trigger QuickContact
1163            QuickContact.showQuickContact(this, rect, lookupUri, QuickContact.MODE_MEDIUM, null);
1164        } else {
1165            // No matching contact, ask user to create one
1166            final Uri mailUri = Uri.fromParts("mailto", address, null);
1167            final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, mailUri);
1168
1169            // Pass along full E-mail string for possible create dialog
1170            Rfc822Token sender = new Rfc822Token(attendee.mName, attendee.mEmail, null);
1171            intent.putExtra(Intents.EXTRA_CREATE_DESCRIPTION, sender.toString());
1172
1173            // Only provide personal name hint if we have one
1174            final String senderPersonal = attendee.mName;
1175            if (!TextUtils.isEmpty(senderPersonal)) {
1176                intent.putExtra(Intents.Insert.NAME, senderPersonal);
1177            }
1178
1179            startActivity(intent);
1180        }
1181    }
1182}
1183