OSDN Git Service

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