OSDN Git Service

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