OSDN Git Service

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