OSDN Git Service

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