2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.calendar;
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;
23 import android.app.Activity;
24 import android.content.ActivityNotFoundException;
25 import android.content.AsyncQueryHandler;
26 import android.content.ContentProviderOperation;
27 import android.content.ContentResolver;
28 import android.content.ContentUris;
29 import android.content.ContentValues;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.OperationApplicationException;
33 import android.content.SharedPreferences;
34 import android.content.res.Resources;
35 import android.database.Cursor;
36 import android.graphics.PorterDuff;
37 import android.graphics.Rect;
38 import android.net.Uri;
39 import android.os.Bundle;
40 import android.os.RemoteException;
41 import android.pim.EventRecurrence;
42 import android.provider.Calendar;
43 import android.provider.ContactsContract;
44 import android.provider.Calendar.Attendees;
45 import android.provider.Calendar.Calendars;
46 import android.provider.Calendar.Events;
47 import android.provider.Calendar.Reminders;
48 import android.provider.ContactsContract.CommonDataKinds;
49 import android.provider.ContactsContract.Contacts;
50 import android.provider.ContactsContract.Data;
51 import android.provider.ContactsContract.Intents;
52 import android.provider.ContactsContract.Presence;
53 import android.provider.ContactsContract.QuickContact;
54 import android.provider.ContactsContract.CommonDataKinds.Email;
55 import android.text.TextUtils;
56 import android.text.format.DateFormat;
57 import android.text.format.DateUtils;
58 import android.text.format.Time;
59 import android.text.util.Linkify;
60 import android.text.util.Rfc822Token;
61 import android.util.Log;
62 import android.view.KeyEvent;
63 import android.view.LayoutInflater;
64 import android.view.Menu;
65 import android.view.MenuItem;
66 import android.view.MotionEvent;
67 import android.view.View;
68 import android.view.View.OnTouchListener;
69 import android.widget.AdapterView;
70 import android.widget.ArrayAdapter;
71 import android.widget.ImageButton;
72 import android.widget.ImageView;
73 import android.widget.LinearLayout;
74 import android.widget.QuickContactBadge;
75 import android.widget.Spinner;
76 import android.widget.TextView;
77 import android.widget.Toast;
79 import java.util.ArrayList;
80 import java.util.Arrays;
81 import java.util.HashMap;
82 import java.util.TimeZone;
83 import java.util.regex.Pattern;
85 public class EventInfoActivity extends Activity implements View.OnClickListener,
86 AdapterView.OnItemSelectedListener {
87 public static final boolean DEBUG = false;
89 public static final String TAG = "EventInfoActivity";
91 private static final int MAX_REMINDERS = 5;
94 * These are the corresponding indices into the array of strings
95 * "R.array.change_response_labels" in the resource file.
97 static final int UPDATE_SINGLE = 0;
98 static final int UPDATE_ALL = 1;
100 private static final String[] EVENT_PROJECTION = new String[] {
101 Events._ID, // 0 do not remove; used in DeleteEventHelper
102 Events.TITLE, // 1 do not remove; used in DeleteEventHelper
103 Events.RRULE, // 2 do not remove; used in DeleteEventHelper
104 Events.ALL_DAY, // 3 do not remove; used in DeleteEventHelper
105 Events.CALENDAR_ID, // 4 do not remove; used in DeleteEventHelper
106 Events.DTSTART, // 5 do not remove; used in DeleteEventHelper
107 Events._SYNC_ID, // 6 do not remove; used in DeleteEventHelper
108 Events.EVENT_TIMEZONE, // 7 do not remove; used in DeleteEventHelper
109 Events.DESCRIPTION, // 8
110 Events.EVENT_LOCATION, // 9
111 Events.HAS_ALARM, // 10
112 Events.ACCESS_LEVEL, // 11
114 Events.HAS_ATTENDEE_DATA, // 13
115 Events.GUESTS_CAN_MODIFY, // 14
116 // TODO Events.GUESTS_CAN_INVITE_OTHERS has not been implemented in calendar provider
117 Events.GUESTS_CAN_INVITE_OTHERS, // 15
118 Events.ORGANIZER, // 16
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_HAS_ATTENDEE_DATA = 13;
133 private static final int EVENT_INDEX_GUESTS_CAN_MODIFY = 14;
134 private static final int EVENT_INDEX_CAN_INVITE_OTHERS = 15;
135 private static final int EVENT_INDEX_ORGANIZER = 16;
137 private static final String[] ATTENDEES_PROJECTION = new String[] {
139 Attendees.ATTENDEE_NAME, // 1
140 Attendees.ATTENDEE_EMAIL, // 2
141 Attendees.ATTENDEE_RELATIONSHIP, // 3
142 Attendees.ATTENDEE_STATUS, // 4
144 private static final int ATTENDEES_INDEX_ID = 0;
145 private static final int ATTENDEES_INDEX_NAME = 1;
146 private static final int ATTENDEES_INDEX_EMAIL = 2;
147 private static final int ATTENDEES_INDEX_RELATIONSHIP = 3;
148 private static final int ATTENDEES_INDEX_STATUS = 4;
150 private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=%d";
152 private static final String ATTENDEES_SORT_ORDER = Attendees.ATTENDEE_NAME + " ASC, "
153 + Attendees.ATTENDEE_EMAIL + " ASC";
155 static final String[] CALENDARS_PROJECTION = new String[] {
157 Calendars.DISPLAY_NAME, // 1
158 Calendars.OWNER_ACCOUNT, // 2
159 Calendars.ORGANIZER_CAN_RESPOND // 3
161 static final int CALENDARS_INDEX_DISPLAY_NAME = 1;
162 static final int CALENDARS_INDEX_OWNER_ACCOUNT = 2;
163 static final int CALENDARS_INDEX_OWNER_CAN_RESPOND = 3;
165 static final String CALENDARS_WHERE = Calendars._ID + "=%d";
166 static final String CALENDARS_DUPLICATE_NAME_WHERE = Calendars.DISPLAY_NAME + "=?";
168 private static final String[] REMINDERS_PROJECTION = new String[] {
170 Reminders.MINUTES, // 1
172 private static final int REMINDERS_INDEX_MINUTES = 1;
173 private static final String REMINDERS_WHERE = Reminders.EVENT_ID + "=%d AND (" +
174 Reminders.METHOD + "=" + Reminders.METHOD_ALERT + " OR " + Reminders.METHOD + "=" +
175 Reminders.METHOD_DEFAULT + ")";
176 private static final String REMINDERS_SORT = Reminders.MINUTES;
178 private static final int MENU_GROUP_REMINDER = 1;
179 private static final int MENU_GROUP_EDIT = 2;
180 private static final int MENU_GROUP_DELETE = 3;
182 private static final int MENU_ADD_REMINDER = 1;
183 private static final int MENU_EDIT = 2;
184 private static final int MENU_DELETE = 3;
186 private static final int ATTENDEE_ID_NONE = -1;
187 private static final int ATTENDEE_NO_RESPONSE = -1;
188 private static final int[] ATTENDEE_VALUES = {
189 ATTENDEE_NO_RESPONSE,
190 Attendees.ATTENDEE_STATUS_ACCEPTED,
191 Attendees.ATTENDEE_STATUS_TENTATIVE,
192 Attendees.ATTENDEE_STATUS_DECLINED,
195 private LinearLayout mRemindersContainer;
196 private LinearLayout mOrganizerContainer;
197 private TextView mOrganizerView;
200 private long mEventId;
201 private Cursor mEventCursor;
202 private Cursor mAttendeesCursor;
203 private Cursor mCalendarsCursor;
205 private long mStartMillis;
206 private long mEndMillis;
208 private boolean mHasAttendeeData;
209 private boolean mIsOrganizer;
210 private long mCalendarOwnerAttendeeId = ATTENDEE_ID_NONE;
211 private boolean mOrganizerCanRespond;
212 private String mCalendarOwnerAccount;
213 private boolean mCanModifyCalendar;
214 private boolean mIsBusyFreeCalendar;
215 private boolean mCanModifyEvent;
216 private int mNumOfAttendees;
217 private String mOrganizer;
219 private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>();
220 private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0);
221 private ArrayList<Integer> mReminderValues;
222 private ArrayList<String> mReminderLabels;
223 private int mDefaultReminderMinutes;
224 private boolean mOriginalHasAlarm;
226 private DeleteEventHelper mDeleteEventHelper;
227 private EditResponseHelper mEditResponseHelper;
229 private int mResponseOffset;
230 private int mOriginalAttendeeResponse;
231 private int mAttendeeResponseFromIntent = ATTENDEE_NO_RESPONSE;
232 private boolean mIsRepeating;
233 private boolean mIsDuplicateName;
235 private Pattern mWildcardPattern = Pattern.compile("^.*$");
236 private LayoutInflater mLayoutInflater;
237 private LinearLayout mReminderAdder;
239 // TODO This can be removed when the contacts content provider doesn't return duplicates
240 private int mUpdateCounts;
241 private static class ViewHolder {
242 QuickContactBadge badge;
246 private HashMap<String, ViewHolder> mViewHolders = new HashMap<String, ViewHolder>();
247 private PresenceQueryHandler mPresenceQueryHandler;
249 private static final Uri CONTACT_DATA_WITH_PRESENCE_URI = Data.CONTENT_URI;
251 int PRESENCE_PROJECTION_CONTACT_ID_INDEX = 0;
252 int PRESENCE_PROJECTION_PRESENCE_INDEX = 1;
253 int PRESENCE_PROJECTION_EMAIL_INDEX = 2;
254 int PRESENCE_PROJECTION_PHOTO_ID_INDEX = 3;
256 private static final String[] PRESENCE_PROJECTION = new String[] {
257 Email.CONTACT_ID, // 0
258 Email.CONTACT_PRESENCE, // 1
263 ArrayList<Attendee> mAcceptedAttendees = new ArrayList<Attendee>();
264 ArrayList<Attendee> mDeclinedAttendees = new ArrayList<Attendee>();
265 ArrayList<Attendee> mTentativeAttendees = new ArrayList<Attendee>();
266 ArrayList<Attendee> mNoResponseAttendees = new ArrayList<Attendee>();
269 // This is called when one of the "remove reminder" buttons is selected.
270 public void onClick(View v) {
271 LinearLayout reminderItem = (LinearLayout) v.getParent();
272 LinearLayout parent = (LinearLayout) reminderItem.getParent();
273 parent.removeView(reminderItem);
274 mReminderItems.remove(reminderItem);
275 updateRemindersVisibility();
278 public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
279 // If they selected the "No response" option, then don't display the
280 // dialog asking which events to change.
281 if (id == 0 && mResponseOffset == 0) {
285 // If this is not a repeating event, then don't display the dialog
286 // asking which events to change.
291 // If the selection is the same as the original, then don't display the
292 // dialog asking which events to change.
293 int index = findResponseIndexFor(mOriginalAttendeeResponse);
294 if (position == index + mResponseOffset) {
298 // This is a repeating event. We need to ask the user if they mean to
299 // change just this one instance or all instances.
300 mEditResponseHelper.showDialog(mEditResponseHelper.getWhichEvents());
303 public void onNothingSelected(AdapterView<?> parent) {
307 protected void onCreate(Bundle icicle) {
308 super.onCreate(icicle);
311 Intent intent = getIntent();
312 mUri = intent.getData();
313 ContentResolver cr = getContentResolver();
314 mStartMillis = intent.getLongExtra(EVENT_BEGIN_TIME, 0);
315 mEndMillis = intent.getLongExtra(EVENT_END_TIME, 0);
316 mAttendeeResponseFromIntent = intent.getIntExtra(ATTENDEE_STATUS, ATTENDEE_NO_RESPONSE);
317 mEventCursor = managedQuery(mUri, EVENT_PROJECTION, null, null, null);
318 if (initEventCursor()) {
319 // The cursor is empty. This can happen if the event was deleted.
324 setContentView(R.layout.event_info_activity);
325 mPresenceQueryHandler = new PresenceQueryHandler(this, cr);
326 mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
327 mRemindersContainer = (LinearLayout) findViewById(R.id.reminders_container);
328 mOrganizerContainer = (LinearLayout) findViewById(R.id.organizer_container);
329 mOrganizerView = (TextView) findViewById(R.id.organizer);
332 Uri uri = Calendars.CONTENT_URI;
333 String where = String.format(CALENDARS_WHERE, mEventCursor.getLong(EVENT_INDEX_CALENDAR_ID));
334 mCalendarsCursor = managedQuery(uri, CALENDARS_PROJECTION, where, null, null);
335 mCalendarOwnerAccount = "";
336 if (mCalendarsCursor != null) {
337 mCalendarsCursor.moveToFirst();
338 mCalendarOwnerAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
339 mOrganizerCanRespond = mCalendarsCursor.getInt(CALENDARS_INDEX_OWNER_CAN_RESPOND) != 0;
341 String displayName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
342 mIsDuplicateName = isDuplicateName(displayName);
344 String eventOrganizer = mEventCursor.getString(EVENT_INDEX_ORGANIZER);
345 mIsOrganizer = mCalendarOwnerAccount.equalsIgnoreCase(eventOrganizer);
346 mHasAttendeeData = mEventCursor.getInt(EVENT_INDEX_HAS_ATTENDEE_DATA) != 0;
351 uri = Attendees.CONTENT_URI;
352 where = String.format(ATTENDEES_WHERE, mEventId);
353 mAttendeesCursor = managedQuery(uri, ATTENDEES_PROJECTION, where, null,
354 ATTENDEES_SORT_ORDER);
355 initAttendeesCursor();
357 mOrganizer = eventOrganizer;
359 mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) >= Calendars.CONTRIBUTOR_ACCESS;
360 mIsBusyFreeCalendar =
361 mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) == Calendars.FREEBUSY_ACCESS;
363 mCanModifyEvent = mCanModifyCalendar
364 && (mIsOrganizer || (mEventCursor.getInt(EVENT_INDEX_GUESTS_CAN_MODIFY) != 0));
366 // Initialize the reminder values array.
367 Resources r = getResources();
368 String[] strings = r.getStringArray(R.array.reminder_minutes_values);
369 int size = strings.length;
370 ArrayList<Integer> list = new ArrayList<Integer>(size);
371 for (int i = 0 ; i < size ; i++) {
372 list.add(Integer.parseInt(strings[i]));
374 mReminderValues = list;
375 String[] labels = r.getStringArray(R.array.reminder_minutes_labels);
376 mReminderLabels = new ArrayList<String>(Arrays.asList(labels));
378 SharedPreferences prefs = CalendarPreferenceActivity.getSharedPreferences(this);
379 String durationString =
380 prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0");
381 mDefaultReminderMinutes = Integer.parseInt(durationString);
384 boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
386 uri = Reminders.CONTENT_URI;
387 where = String.format(REMINDERS_WHERE, mEventId);
388 Cursor reminderCursor = cr.query(uri, REMINDERS_PROJECTION, where, null,
391 // First pass: collect all the custom reminder minutes (e.g.,
392 // a reminder of 8 minutes) into a global list.
393 while (reminderCursor.moveToNext()) {
394 int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
395 EditEvent.addMinutesToList(this, mReminderValues, mReminderLabels, minutes);
398 // Second pass: create the reminder spinners
399 reminderCursor.moveToPosition(-1);
400 while (reminderCursor.moveToNext()) {
401 int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
402 mOriginalMinutes.add(minutes);
403 EditEvent.addReminder(this, this, mReminderItems, mReminderValues,
404 mReminderLabels, minutes);
407 reminderCursor.close();
410 mOriginalHasAlarm = hasAlarm;
412 // Setup the + Add Reminder Button
413 View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
414 public void onClick(View v) {
418 ImageButton reminderAddButton = (ImageButton) findViewById(R.id.reminder_add);
419 reminderAddButton.setOnClickListener(addReminderOnClickListener);
421 mReminderAdder = (LinearLayout) findViewById(R.id.reminder_adder);
422 updateRemindersVisibility();
424 mDeleteEventHelper = new DeleteEventHelper(this, true /* exit when done */);
425 mEditResponseHelper = new EditResponseHelper(this);
429 protected void onResume() {
431 if (initEventCursor()) {
432 // The cursor is empty. This can happen if the event was deleted.
436 initCalendarsCursor();
441 private void updateTitle() {
442 Resources res = getResources();
443 if (mCanModifyCalendar && !mIsOrganizer) {
444 setTitle(res.getString(R.string.event_info_title_invite));
446 setTitle(res.getString(R.string.event_info_title));
450 boolean isDuplicateName(String displayName) {
451 Cursor dupNameCursor = managedQuery(Calendars.CONTENT_URI, CALENDARS_PROJECTION,
452 CALENDARS_DUPLICATE_NAME_WHERE, new String[] {displayName}, null);
453 boolean isDuplicateName = false;
454 if(dupNameCursor != null) {
455 if (dupNameCursor.getCount() > 1) {
456 isDuplicateName = true;
458 dupNameCursor.close();
460 return isDuplicateName;
464 * Initializes the event cursor, which is expected to point to the first
465 * (and only) result from a query.
466 * @return true if the cursor is empty.
468 private boolean initEventCursor() {
469 if ((mEventCursor == null) || (mEventCursor.getCount() == 0)) {
472 mEventCursor.moveToFirst();
473 mEventId = mEventCursor.getInt(EVENT_INDEX_ID);
474 String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
475 mIsRepeating = (rRule != null);
479 private static class Attendee {
483 Attendee(String name, String email) {
489 @SuppressWarnings("fallthrough")
490 private void initAttendeesCursor() {
491 mOriginalAttendeeResponse = ATTENDEE_NO_RESPONSE;
492 mCalendarOwnerAttendeeId = ATTENDEE_ID_NONE;
494 if (mAttendeesCursor != null) {
495 mNumOfAttendees = mAttendeesCursor.getCount();
496 if (mAttendeesCursor.moveToFirst()) {
497 mAcceptedAttendees.clear();
498 mDeclinedAttendees.clear();
499 mTentativeAttendees.clear();
500 mNoResponseAttendees.clear();
503 int status = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
504 String name = mAttendeesCursor.getString(ATTENDEES_INDEX_NAME);
505 String email = mAttendeesCursor.getString(ATTENDEES_INDEX_EMAIL);
507 if (mAttendeesCursor.getInt(ATTENDEES_INDEX_RELATIONSHIP) ==
508 Attendees.RELATIONSHIP_ORGANIZER) {
509 // Overwrites the one from Event table if available
510 if (name != null && name.length() > 0) {
512 } else if (email != null && email.length() > 0) {
517 if (mCalendarOwnerAttendeeId == ATTENDEE_ID_NONE &&
518 mCalendarOwnerAccount.equalsIgnoreCase(email)) {
519 mCalendarOwnerAttendeeId = mAttendeesCursor.getInt(ATTENDEES_INDEX_ID);
520 mOriginalAttendeeResponse = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
522 // Don't show your own status in the list because:
523 // 1) it doesn't make sense for event without other guests.
524 // 2) there's a spinner for that for events with guests.
526 case Attendees.ATTENDEE_STATUS_ACCEPTED:
527 mAcceptedAttendees.add(new Attendee(name, email));
529 case Attendees.ATTENDEE_STATUS_DECLINED:
530 mDeclinedAttendees.add(new Attendee(name, email));
532 case Attendees.ATTENDEE_STATUS_NONE:
533 mNoResponseAttendees.add(new Attendee(name, email));
534 // Fallthrough so that no response is a subset of tentative
536 mTentativeAttendees.add(new Attendee(name, email));
539 } while (mAttendeesCursor.moveToNext());
540 mAttendeesCursor.moveToFirst();
545 // only show the organizer if we're not the organizer and if
546 // we have attendee data (might have been removed by the server
547 // for events with a lot of attendees).
548 if (!mIsOrganizer && mHasAttendeeData) {
549 mOrganizerContainer.setVisibility(View.VISIBLE);
550 mOrganizerView.setText(mOrganizer);
552 mOrganizerContainer.setVisibility(View.GONE);
556 private void initCalendarsCursor() {
557 if (mCalendarsCursor != null) {
558 mCalendarsCursor.moveToFirst();
563 public void onPause() {
565 if (!isFinishing()) {
568 ContentResolver cr = getContentResolver();
569 ArrayList<Integer> reminderMinutes = EditEvent.reminderItemsToMinutes(mReminderItems,
571 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(3);
572 boolean changed = EditEvent.saveReminders(ops, mEventId, reminderMinutes, mOriginalMinutes,
573 false /* no force save */);
575 // TODO Run this in a background process.
576 cr.applyBatch(Calendars.CONTENT_URI.getAuthority(), ops);
577 // Update the "hasAlarm" field for the event
578 Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
579 int len = reminderMinutes.size();
580 boolean hasAlarm = len > 0;
581 if (hasAlarm != mOriginalHasAlarm) {
582 ContentValues values = new ContentValues();
583 values.put(Events.HAS_ALARM, hasAlarm ? 1 : 0);
584 cr.update(uri, values, null, null);
586 } catch (RemoteException e) {
587 Log.w(TAG, "Ignoring exception: ", e);
588 } catch (OperationApplicationException e) {
589 Log.w(TAG, "Ignoring exception: ", e);
592 changed |= saveResponse(cr);
594 Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show();
599 public boolean onCreateOptionsMenu(Menu menu) {
601 item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0,
602 R.string.add_new_reminder);
603 item.setIcon(R.drawable.ic_menu_reminder);
604 item.setAlphabeticShortcut('r');
606 item = menu.add(MENU_GROUP_EDIT, MENU_EDIT, 0, R.string.edit_event_label);
607 item.setIcon(android.R.drawable.ic_menu_edit);
608 item.setAlphabeticShortcut('e');
610 item = menu.add(MENU_GROUP_DELETE, MENU_DELETE, 0, R.string.delete_event_label);
611 item.setIcon(android.R.drawable.ic_menu_delete);
613 return super.onCreateOptionsMenu(menu);
617 public boolean onPrepareOptionsMenu(Menu menu) {
618 boolean canAddReminders = canAddReminders();
619 menu.setGroupVisible(MENU_GROUP_REMINDER, canAddReminders);
620 menu.setGroupEnabled(MENU_GROUP_REMINDER, canAddReminders);
622 menu.setGroupVisible(MENU_GROUP_EDIT, mCanModifyEvent);
623 menu.setGroupEnabled(MENU_GROUP_EDIT, mCanModifyEvent);
624 menu.setGroupVisible(MENU_GROUP_DELETE, mCanModifyCalendar);
625 menu.setGroupEnabled(MENU_GROUP_DELETE, mCanModifyCalendar);
627 return super.onPrepareOptionsMenu(menu);
630 private boolean canAddReminders() {
631 return !mIsBusyFreeCalendar && mReminderItems.size() < MAX_REMINDERS;
634 private void addReminder() {
635 // TODO: when adding a new reminder, make it different from the
636 // last one in the list (if any).
637 if (mDefaultReminderMinutes == 0) {
638 EditEvent.addReminder(this, this, mReminderItems,
639 mReminderValues, mReminderLabels, 10 /* minutes */);
641 EditEvent.addReminder(this, this, mReminderItems,
642 mReminderValues, mReminderLabels, mDefaultReminderMinutes);
644 updateRemindersVisibility();
648 public boolean onOptionsItemSelected(MenuItem item) {
649 super.onOptionsItemSelected(item);
650 switch (item.getItemId()) {
651 case MENU_ADD_REMINDER:
665 public boolean onKeyDown(int keyCode, KeyEvent event) {
666 if (keyCode == KeyEvent.KEYCODE_DEL) {
670 return super.onKeyDown(keyCode, event);
673 private void updateRemindersVisibility() {
674 if (mIsBusyFreeCalendar) {
675 mRemindersContainer.setVisibility(View.GONE);
677 mRemindersContainer.setVisibility(View.VISIBLE);
678 mReminderAdder.setVisibility(canAddReminders() ? View.VISIBLE : View.GONE);
683 * Saves the response to an invitation if the user changed the response.
684 * Returns true if the database was updated.
686 * @param cr the ContentResolver
687 * @return true if the database was changed
689 private boolean saveResponse(ContentResolver cr) {
690 if (mAttendeesCursor == null || mEventCursor == null) {
693 Spinner spinner = (Spinner) findViewById(R.id.response_value);
694 int position = spinner.getSelectedItemPosition() - mResponseOffset;
699 int status = ATTENDEE_VALUES[position];
701 // If the status has not changed, then don't update the database
702 if (status == mOriginalAttendeeResponse) {
706 // If we never got an owner attendee id we can't set the status
707 if (mCalendarOwnerAttendeeId == ATTENDEE_ID_NONE) {
712 // This is a non-repeating event
713 updateResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
717 // This is a repeating event
718 int whichEvents = mEditResponseHelper.getWhichEvents();
719 switch (whichEvents) {
723 createExceptionResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
726 updateResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
729 Log.e(TAG, "Unexpected choice for updating invitation response");
735 private void updateResponse(ContentResolver cr, long eventId, long attendeeId, int status) {
736 // Update the attendee status in the attendees table. the provider
737 // takes care of updating the self attendance status.
738 ContentValues values = new ContentValues();
740 if (!TextUtils.isEmpty(mCalendarOwnerAccount)) {
741 values.put(Attendees.ATTENDEE_EMAIL, mCalendarOwnerAccount);
743 values.put(Attendees.ATTENDEE_STATUS, status);
744 values.put(Attendees.EVENT_ID, eventId);
746 Uri uri = ContentUris.withAppendedId(Attendees.CONTENT_URI, attendeeId);
747 cr.update(uri, values, null /* where */, null /* selection args */);
750 private void createExceptionResponse(ContentResolver cr, long eventId,
751 long attendeeId, int status) {
752 // Fetch information about the repeating event.
753 Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
754 Cursor cursor = cr.query(uri, EVENT_PROJECTION, null, null, null);
755 if (cursor == null) {
758 if(!cursor.moveToFirst()) {
764 ContentValues values = new ContentValues();
766 String title = cursor.getString(EVENT_INDEX_TITLE);
767 String timezone = cursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
768 int calendarId = cursor.getInt(EVENT_INDEX_CALENDAR_ID);
769 boolean allDay = cursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
770 String syncId = cursor.getString(EVENT_INDEX_SYNC_ID);
772 values.put(Events.TITLE, title);
773 values.put(Events.EVENT_TIMEZONE, timezone);
774 values.put(Events.ALL_DAY, allDay ? 1 : 0);
775 values.put(Events.CALENDAR_ID, calendarId);
776 values.put(Events.DTSTART, mStartMillis);
777 values.put(Events.DTEND, mEndMillis);
778 values.put(Events.ORIGINAL_EVENT, syncId);
779 values.put(Events.ORIGINAL_INSTANCE_TIME, mStartMillis);
780 values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0);
781 values.put(Events.STATUS, Events.STATUS_CONFIRMED);
782 values.put(Events.SELF_ATTENDEE_STATUS, status);
784 // Create a recurrence exception
785 cr.insert(Events.CONTENT_URI, values);
791 private int findResponseIndexFor(int response) {
792 int size = ATTENDEE_VALUES.length;
793 for (int index = 0; index < size; index++) {
794 if (ATTENDEE_VALUES[index] == response) {
801 private void doEdit() {
802 Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
803 Intent intent = new Intent(Intent.ACTION_EDIT, uri);
804 intent.putExtra(Calendar.EVENT_BEGIN_TIME, mStartMillis);
805 intent.putExtra(Calendar.EVENT_END_TIME, mEndMillis);
806 intent.setClass(EventInfoActivity.this, EditEvent.class);
807 startActivity(intent);
811 private void doDelete() {
812 mDeleteEventHelper.delete(mStartMillis, mEndMillis, mEventCursor, -1);
815 private void updateView() {
816 if (mEventCursor == null) {
820 String eventName = mEventCursor.getString(EVENT_INDEX_TITLE);
821 if (eventName == null || eventName.length() == 0) {
822 Resources res = getResources();
823 eventName = res.getString(R.string.no_title_label);
826 boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
827 String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION);
828 String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION);
829 String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
830 boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
831 String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
832 mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff;
834 View calBackground = findViewById(R.id.cal_background);
835 calBackground.setBackgroundColor(mColor);
837 TextView title = (TextView) findViewById(R.id.title);
838 title.setTextColor(mColor);
840 View divider = findViewById(R.id.divider);
841 divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
844 if (eventName != null) {
845 setTextCommon(R.id.title, eventName);
852 flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE;
854 flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE;
855 if (DateFormat.is24HourFormat(this)) {
856 flags |= DateUtils.FORMAT_24HOUR;
859 when = DateUtils.formatDateRange(this, mStartMillis, mEndMillis, flags);
860 setTextCommon(R.id.when, when);
862 // Show the event timezone if it is different from the local timezone
863 Time time = new Time();
864 String localTimezone = time.timezone;
866 localTimezone = Time.TIMEZONE_UTC;
868 if (eventTimezone != null && !localTimezone.equals(eventTimezone) && !allDay) {
870 TimeZone tz = TimeZone.getTimeZone(localTimezone);
871 if (tz == null || tz.getID().equals("GMT")) {
872 displayName = localTimezone;
874 displayName = tz.getDisplayName();
877 setTextCommon(R.id.timezone, displayName);
879 setVisibilityCommon(R.id.timezone_container, View.GONE);
884 EventRecurrence eventRecurrence = new EventRecurrence();
885 eventRecurrence.parse(rRule);
886 Time date = new Time();
888 date.timezone = Time.TIMEZONE_UTC;
890 date.set(mStartMillis);
891 eventRecurrence.setStartDate(date);
892 String repeatString = EventRecurrenceFormatter.getRepeatString(getResources(),
894 setTextCommon(R.id.repeat, repeatString);
896 setVisibilityCommon(R.id.repeat_container, View.GONE);
900 if (location == null || location.length() == 0) {
901 setVisibilityCommon(R.id.where, View.GONE);
903 final TextView textView = (TextView) findViewById(R.id.where);
904 if (textView != null) {
905 textView.setAutoLinkMask(0);
906 textView.setText(location);
907 Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
908 textView.setOnTouchListener(new OnTouchListener() {
909 public boolean onTouch(View v, MotionEvent event) {
911 return v.onTouchEvent(event);
912 } catch (ActivityNotFoundException e) {
922 if (description == null || description.length() == 0) {
923 setVisibilityCommon(R.id.description, View.GONE);
925 setTextCommon(R.id.description, description);
929 if (mCalendarsCursor != null) {
930 String calendarName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
931 String ownerAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
932 if (mIsDuplicateName && !calendarName.equalsIgnoreCase(ownerAccount)) {
933 calendarName = new StringBuilder(calendarName)
934 .append(Utils.OPEN_EMAIL_MARKER)
935 .append(ownerAccount)
936 .append(Utils.CLOSE_EMAIL_MARKER)
939 setTextCommon(R.id.calendar, calendarName);
941 setVisibilityCommon(R.id.calendar_container, View.GONE);
945 private void updateAttendees() {
946 LinearLayout attendeesLayout = (LinearLayout) findViewById(R.id.attendee_list);
947 attendeesLayout.removeAllViewsInLayout();
949 if(mAcceptedAttendees.size() == 0 && mDeclinedAttendees.size() == 0 &&
950 mTentativeAttendees.size() == mNoResponseAttendees.size()) {
951 // If all guests have no response just list them as guests,
952 CharSequence guestsLabel = getResources().getText(R.string.attendees_label);
953 addAttendeesToLayout(mNoResponseAttendees, attendeesLayout, guestsLabel);
955 // If we have any responses then divide them up by response
956 CharSequence[] entries;
957 entries = getResources().getTextArray(R.array.response_labels2);
958 addAttendeesToLayout(mAcceptedAttendees, attendeesLayout, entries[0]);
959 addAttendeesToLayout(mDeclinedAttendees, attendeesLayout, entries[2]);
960 addAttendeesToLayout(mTentativeAttendees, attendeesLayout, entries[1]);
964 private void addAttendeesToLayout(ArrayList<Attendee> attendees, LinearLayout attendeeList,
965 CharSequence sectionTitle) {
966 if (attendees.size() == 0) {
970 ContentResolver cr = getContentResolver();
971 // Yes/No/Maybe Title
972 View titleView = mLayoutInflater.inflate(R.layout.contact_item, null);
973 titleView.findViewById(R.id.badge).setVisibility(View.GONE);
974 View divider = titleView.findViewById(R.id.separator);
975 divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
977 TextView title = (TextView) titleView.findViewById(R.id.name);
978 title.setText(getString(R.string.response_label, sectionTitle, attendees.size()));
979 title.setTextAppearance(this, R.style.TextAppearance_EventInfo_Label);
980 attendeeList.addView(titleView);
983 int numOfAttendees = attendees.size();
984 StringBuilder selection = new StringBuilder(Email.DATA + " IN (");
985 String[] selectionArgs = new String[numOfAttendees];
987 for (int i = 0; i < numOfAttendees; ++i) {
988 Attendee attendee = attendees.get(i);
989 selectionArgs[i] = attendee.mEmail;
991 View v = mLayoutInflater.inflate(R.layout.contact_item, null);
994 View separator = v.findViewById(R.id.separator);
995 separator.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
998 TextView tv = (TextView) v.findViewById(R.id.name);
999 String name = attendee.mName;
1000 if (name == null || name.length() == 0) {
1001 name = attendee.mEmail;
1005 ViewHolder vh = new ViewHolder();
1006 vh.badge = (QuickContactBadge) v.findViewById(R.id.badge);
1007 vh.badge.assignContactFromEmail(attendee.mEmail, true);
1008 vh.presence = (ImageView) v.findViewById(R.id.presence);
1009 mViewHolders.put(attendee.mEmail, vh);
1012 selection.append('?');
1014 selection.append(", ?");
1017 attendeeList.addView(v);
1019 selection.append(')');
1021 mPresenceQueryHandler.startQuery(mUpdateCounts, attendees, CONTACT_DATA_WITH_PRESENCE_URI,
1022 PRESENCE_PROJECTION, selection.toString(), selectionArgs, null);
1025 private class PresenceQueryHandler extends AsyncQueryHandler {
1027 ContentResolver mContentResolver;
1029 public PresenceQueryHandler(Context context, ContentResolver cr) {
1031 mContentResolver = cr;
1036 protected void onQueryComplete(int queryIndex, Object cookie, Cursor cursor) {
1037 if (cursor == null) {
1039 Log.e(TAG, "onQueryComplete: cursor == null");
1045 cursor.moveToPosition(-1);
1046 while (cursor.moveToNext()) {
1047 String email = cursor.getString(PRESENCE_PROJECTION_EMAIL_INDEX);
1048 int contactId = cursor.getInt(PRESENCE_PROJECTION_CONTACT_ID_INDEX);
1049 ViewHolder vh = mViewHolders.get(email);
1050 int photoId = cursor.getInt(PRESENCE_PROJECTION_PHOTO_ID_INDEX);
1052 Log.e(TAG, "onQueryComplete Id: " + contactId + " PhotoId: " + photoId
1053 + " Email: " + email);
1058 ImageView presenceView = vh.presence;
1059 if (presenceView != null) {
1060 int status = cursor.getInt(PRESENCE_PROJECTION_PRESENCE_INDEX);
1061 presenceView.setImageResource(Presence.getPresenceIconResourceId(status));
1062 presenceView.setVisibility(View.VISIBLE);
1065 if (photoId > 0 && vh.updateCounts < queryIndex) {
1066 vh.updateCounts = queryIndex;
1067 Uri personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
1069 // TODO, modify to batch queries together
1070 ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext, vh.badge,
1071 personUri, R.drawable.ic_contact_picture);
1080 void updateResponse() {
1081 // we only let the user accept/reject/etc. a meeting if:
1082 // a) you can edit the event's containing calendar AND
1083 // b) you're not the organizer and only attendee AND
1084 // c) organizerCanRespond is enabled for the calendar
1085 // (if the attendee data has been hidden, the visible number of attendees
1086 // will be 1 -- the calendar owner's).
1087 // (there are more cases involved to be 100% accurate, such as
1088 // paying attention to whether or not an attendee status was
1089 // included in the feed, but we're currently omitting those corner cases
1091 if (!mCanModifyCalendar || (mHasAttendeeData && mIsOrganizer && mNumOfAttendees <= 1) ||
1092 (mIsOrganizer && !mOrganizerCanRespond)) {
1093 setVisibilityCommon(R.id.response_container, View.GONE);
1097 setVisibilityCommon(R.id.response_container, View.VISIBLE);
1099 Spinner spinner = (Spinner) findViewById(R.id.response_value);
1101 mResponseOffset = 0;
1103 /* If the user has previously responded to this event
1104 * we should not allow them to select no response again.
1105 * Switch the entries to a set of entries without the
1106 * no response option.
1108 if ((mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_INVITED)
1109 && (mOriginalAttendeeResponse != ATTENDEE_NO_RESPONSE)
1110 && (mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_NONE)) {
1111 CharSequence[] entries;
1112 entries = getResources().getTextArray(R.array.response_labels2);
1113 mResponseOffset = -1;
1114 ArrayAdapter<CharSequence> adapter =
1115 new ArrayAdapter<CharSequence>(this,
1116 android.R.layout.simple_spinner_item, entries);
1117 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
1118 spinner.setAdapter(adapter);
1122 if (mAttendeeResponseFromIntent != ATTENDEE_NO_RESPONSE) {
1123 index = findResponseIndexFor(mAttendeeResponseFromIntent);
1125 index = findResponseIndexFor(mOriginalAttendeeResponse);
1127 spinner.setSelection(index + mResponseOffset);
1128 spinner.setOnItemSelectedListener(this);
1131 private void setTextCommon(int id, CharSequence text) {
1132 TextView textView = (TextView) findViewById(id);
1133 if (textView == null)
1135 textView.setText(text);
1138 private void setVisibilityCommon(int id, int visibility) {
1139 View v = findViewById(id);
1141 v.setVisibility(visibility);
1147 * Taken from com.google.android.gm.HtmlConversationActivity
1149 * Send the intent that shows the Contact info corresponding to the email address.
1151 public void showContactInfo(Attendee attendee, Rect rect) {
1152 // First perform lookup query to find existing contact
1153 final ContentResolver resolver = getContentResolver();
1154 final String address = attendee.mEmail;
1155 final Uri dataUri = Uri.withAppendedPath(CommonDataKinds.Email.CONTENT_FILTER_URI,
1156 Uri.encode(address));
1157 final Uri lookupUri = ContactsContract.Data.getContactLookupUri(resolver, dataUri);
1159 if (lookupUri != null) {
1160 // Found matching contact, trigger QuickContact
1161 QuickContact.showQuickContact(this, rect, lookupUri, QuickContact.MODE_MEDIUM, null);
1163 // No matching contact, ask user to create one
1164 final Uri mailUri = Uri.fromParts("mailto", address, null);
1165 final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, mailUri);
1167 // Pass along full E-mail string for possible create dialog
1168 Rfc822Token sender = new Rfc822Token(attendee.mName, attendee.mEmail, null);
1169 intent.putExtra(Intents.EXTRA_CREATE_DESCRIPTION, sender.toString());
1171 // Only provide personal name hint if we have one
1172 final String senderPersonal = attendee.mName;
1173 if (!TextUtils.isEmpty(senderPersonal)) {
1174 intent.putExtra(Intents.Insert.NAME, senderPersonal);
1177 startActivity(intent);