OSDN Git Service

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