OSDN Git Service

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