OSDN Git Service

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