OSDN Git Service

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