OSDN Git Service

Merge change 26789 into eclair
[android-x86/packages-apps-Calendar.git] / src / com / android / calendar / EditEvent.java
1 /*
2  * Copyright (C) 2008 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
22 import android.accounts.Account;
23 import android.accounts.AccountManager;
24 import android.accounts.AuthenticatorException;
25 import android.accounts.OperationCanceledException;
26 import android.app.Activity;
27 import android.app.AlertDialog;
28 import android.app.DatePickerDialog;
29 import android.app.ProgressDialog;
30 import android.app.TimePickerDialog;
31 import android.app.DatePickerDialog.OnDateSetListener;
32 import android.app.TimePickerDialog.OnTimeSetListener;
33 import android.content.AsyncQueryHandler;
34 import android.content.ContentProviderOperation;
35 import android.content.ContentProviderResult;
36 import android.content.ContentResolver;
37 import android.content.ContentUris;
38 import android.content.ContentValues;
39 import android.content.Context;
40 import android.content.DialogInterface;
41 import android.content.Intent;
42 import android.content.OperationApplicationException;
43 import android.content.SharedPreferences;
44 import android.content.ContentProviderOperation.Builder;
45 import android.content.DialogInterface.OnCancelListener;
46 import android.content.DialogInterface.OnClickListener;
47 import android.content.res.Resources;
48 import android.database.Cursor;
49 import android.net.Uri;
50 import android.os.Bundle;
51 import android.os.RemoteException;
52 import android.pim.EventRecurrence;
53 import android.preference.PreferenceManager;
54 import android.provider.Calendar.Attendees;
55 import android.provider.Calendar.Calendars;
56 import android.provider.Calendar.Events;
57 import android.provider.Calendar.Reminders;
58 import android.text.Editable;
59 import android.text.InputFilter;
60 import android.text.TextUtils;
61 import android.text.format.DateFormat;
62 import android.text.format.DateUtils;
63 import android.text.format.Time;
64 import android.text.util.Rfc822Token;
65 import android.text.util.Rfc822Tokenizer;
66 import android.text.util.Rfc822Validator;
67 import android.text.util.Rfc822InputFilter;
68 import android.util.Log;
69 import android.view.KeyEvent;
70 import android.view.LayoutInflater;
71 import android.view.Menu;
72 import android.view.MenuItem;
73 import android.view.View;
74 import android.view.Window;
75 import android.widget.ArrayAdapter;
76 import android.widget.Button;
77 import android.widget.CheckBox;
78 import android.widget.CompoundButton;
79 import android.widget.DatePicker;
80 import android.widget.ImageButton;
81 import android.widget.LinearLayout;
82 import android.widget.MultiAutoCompleteTextView;
83 import android.widget.ResourceCursorAdapter;
84 import android.widget.Spinner;
85 import android.widget.TextView;
86 import android.widget.TimePicker;
87 import android.widget.Toast;
88
89 import com.google.android.googlelogin.GoogleLoginServiceConstants;
90 import com.google.android.collect.Lists;
91
92 import java.io.IOException;
93 import java.util.ArrayList;
94 import java.util.Arrays;
95 import java.util.Calendar;
96 import java.util.TimeZone;
97 import java.util.HashSet;
98 import java.util.LinkedHashSet;
99
100 public class EditEvent extends Activity implements View.OnClickListener,
101         DialogInterface.OnCancelListener, DialogInterface.OnClickListener {
102     private static final String TAG = "EditEvent";
103     private static final boolean DEBUG = false;
104
105     /**
106      * This is the symbolic name for the key used to pass in the boolean
107      * for creating all-day events that is part of the extra data of the intent.
108      * This is used only for creating new events and is set to true if
109      * the default for the new event should be an all-day event.
110      */
111     public static final String EVENT_ALL_DAY = "allDay";
112
113     private static final int MAX_REMINDERS = 5;
114
115     private static final int MENU_GROUP_REMINDER = 1;
116     private static final int MENU_GROUP_SHOW_OPTIONS = 2;
117     private static final int MENU_GROUP_HIDE_OPTIONS = 3;
118
119     private static final int MENU_ADD_REMINDER = 1;
120     private static final int MENU_SHOW_EXTRA_OPTIONS = 2;
121     private static final int MENU_HIDE_EXTRA_OPTIONS = 3;
122
123     private static final String[] EVENT_PROJECTION = new String[] {
124             Events._ID,             // 0
125             Events.TITLE,           // 1
126             Events.DESCRIPTION,     // 2
127             Events.EVENT_LOCATION,  // 3
128             Events.ALL_DAY,         // 4
129             Events.HAS_ALARM,       // 5
130             Events.CALENDAR_ID,     // 6
131             Events.DTSTART,         // 7
132             Events.DURATION,        // 8
133             Events.EVENT_TIMEZONE,  // 9
134             Events.RRULE,           // 10
135             Events._SYNC_ID,        // 11
136             Events.TRANSPARENCY,    // 12
137             Events.VISIBILITY,      // 13
138             Events.OWNER_ACCOUNT,   // 14
139     };
140     private static final int EVENT_INDEX_ID = 0;
141     private static final int EVENT_INDEX_TITLE = 1;
142     private static final int EVENT_INDEX_DESCRIPTION = 2;
143     private static final int EVENT_INDEX_EVENT_LOCATION = 3;
144     private static final int EVENT_INDEX_ALL_DAY = 4;
145     private static final int EVENT_INDEX_HAS_ALARM = 5;
146     private static final int EVENT_INDEX_CALENDAR_ID = 6;
147     private static final int EVENT_INDEX_DTSTART = 7;
148     private static final int EVENT_INDEX_DURATION = 8;
149     private static final int EVENT_INDEX_TIMEZONE = 9;
150     private static final int EVENT_INDEX_RRULE = 10;
151     private static final int EVENT_INDEX_SYNC_ID = 11;
152     private static final int EVENT_INDEX_TRANSPARENCY = 12;
153     private static final int EVENT_INDEX_VISIBILITY = 13;
154     private static final int EVENT_INDEX_OWNER_ACCOUNT = 14;
155
156     private static final String[] CALENDARS_PROJECTION = new String[] {
157             Calendars._ID,           // 0
158             Calendars.DISPLAY_NAME,  // 1
159             Calendars.OWNER_ACCOUNT, // 2
160     };
161     private static final int CALENDARS_INDEX_DISPLAY_NAME = 1;
162     private static final int CALENDARS_INDEX_OWNER_ACCOUNT = 2;
163     private static final String CALENDARS_WHERE = Calendars.ACCESS_LEVEL + ">=" +
164             Calendars.CONTRIBUTOR_ACCESS + " AND " + Calendars.SYNC_EVENTS + "=1";
165
166     private static final String[] REMINDERS_PROJECTION = new String[] {
167             Reminders._ID,      // 0
168             Reminders.MINUTES,  // 1
169     };
170     private static final int REMINDERS_INDEX_MINUTES = 1;
171     private static final String REMINDERS_WHERE = Reminders.EVENT_ID + "=%d AND (" +
172             Reminders.METHOD + "=" + Reminders.METHOD_ALERT + " OR " + Reminders.METHOD + "=" +
173             Reminders.METHOD_DEFAULT + ")";
174
175     private static final String[] ATTENDEES_PROJECTION = new String[] {
176         Attendees.ATTENDEE_NAME,            // 0
177         Attendees.ATTENDEE_EMAIL,           // 1
178     };
179     private static final int ATTENDEES_INDEX_NAME = 0;
180     private static final int ATTENDEES_INDEX_EMAIL = 1;
181     private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=? AND "
182             + Attendees.ATTENDEE_RELATIONSHIP + "<>" + Attendees.RELATIONSHIP_ORGANIZER;
183     private static final String ATTENDEES_DELETE_PREFIX = Attendees.EVENT_ID + "=? AND " +
184             Attendees.ATTENDEE_EMAIL + " IN (";
185
186     private static final int DOES_NOT_REPEAT = 0;
187     private static final int REPEATS_DAILY = 1;
188     private static final int REPEATS_EVERY_WEEKDAY = 2;
189     private static final int REPEATS_WEEKLY_ON_DAY = 3;
190     private static final int REPEATS_MONTHLY_ON_DAY_COUNT = 4;
191     private static final int REPEATS_MONTHLY_ON_DAY = 5;
192     private static final int REPEATS_YEARLY = 6;
193     private static final int REPEATS_CUSTOM = 7;
194
195     private static final int MODIFY_UNINITIALIZED = 0;
196     private static final int MODIFY_SELECTED = 1;
197     private static final int MODIFY_ALL = 2;
198     private static final int MODIFY_ALL_FOLLOWING = 3;
199
200     private static final int DAY_IN_SECONDS = 24 * 60 * 60;
201
202     private int mFirstDayOfWeek; // cached in onCreate
203     private Uri mUri;
204     private Cursor mEventCursor;
205     private Cursor mCalendarsCursor;
206
207     private Button mStartDateButton;
208     private Button mEndDateButton;
209     private Button mStartTimeButton;
210     private Button mEndTimeButton;
211     private Button mSaveButton;
212     private Button mDeleteButton;
213     private Button mDiscardButton;
214     private CheckBox mAllDayCheckBox;
215     private Spinner mCalendarsSpinner;
216     private Spinner mRepeatsSpinner;
217     private Spinner mAvailabilitySpinner;
218     private Spinner mVisibilitySpinner;
219     private TextView mTitleTextView;
220     private TextView mLocationTextView;
221     private TextView mDescriptionTextView;
222     private View mRemindersSeparator;
223     private LinearLayout mRemindersContainer;
224     private LinearLayout mExtraOptions;
225     private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>();
226     private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0);
227     private Rfc822Validator mEmailValidator;
228     private MultiAutoCompleteTextView mAttendeesList;
229     private EmailAddressAdapter mAddressAdapter;
230     private String mOriginalAttendees = "";
231
232     private EventRecurrence mEventRecurrence = new EventRecurrence();
233     private String mRrule;
234     private boolean mCalendarsQueryComplete;
235     private boolean mSaveAfterQueryComplete;
236     private ProgressDialog mLoadingCalendarsDialog;
237     private AlertDialog mNoCalendarsDialog;
238     private ContentValues mInitialValues;
239
240     /**
241      * If the repeating event is created on the phone and it hasn't been
242      * synced yet to the web server, then there is a bug where you can't
243      * delete or change an instance of the repeating event.  This case
244      * can be detected with mSyncId.  If mSyncId == null, then the repeating
245      * event has not been synced to the phone, in which case we won't allow
246      * the user to change one instance.
247      */
248     private String mSyncId;
249
250     private ArrayList<Integer> mRecurrenceIndexes = new ArrayList<Integer> (0);
251     private ArrayList<Integer> mReminderValues;
252     private ArrayList<String> mReminderLabels;
253
254     private Time mStartTime;
255     private Time mEndTime;
256     private int mModification = MODIFY_UNINITIALIZED;
257     private int mDefaultReminderMinutes;
258
259     private DeleteEventHelper mDeleteEventHelper;
260     private QueryHandler mQueryHandler;
261     private AccountManager mAccountManager;
262
263     /* This class is used to update the time buttons. */
264     private class TimeListener implements OnTimeSetListener {
265         private View mView;
266
267         public TimeListener(View view) {
268             mView = view;
269         }
270
271         public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
272             // Cache the member variables locally to avoid inner class overhead.
273             Time startTime = mStartTime;
274             Time endTime = mEndTime;
275
276             // Cache the start and end millis so that we limit the number
277             // of calls to normalize() and toMillis(), which are fairly
278             // expensive.
279             long startMillis;
280             long endMillis;
281             if (mView == mStartTimeButton) {
282                 // The start time was changed.
283                 int hourDuration = endTime.hour - startTime.hour;
284                 int minuteDuration = endTime.minute - startTime.minute;
285
286                 startTime.hour = hourOfDay;
287                 startTime.minute = minute;
288                 startMillis = startTime.normalize(true);
289
290                 // Also update the end time to keep the duration constant.
291                 endTime.hour = hourOfDay + hourDuration;
292                 endTime.minute = minute + minuteDuration;
293                 endMillis = endTime.normalize(true);
294             } else {
295                 // The end time was changed.
296                 startMillis = startTime.toMillis(true);
297                 endTime.hour = hourOfDay;
298                 endTime.minute = minute;
299                 endMillis = endTime.normalize(true);
300
301                 // Do not allow an event to have an end time before the start time.
302                 if (endTime.before(startTime)) {
303                     endTime.set(startTime);
304                     endMillis = startMillis;
305                 }
306             }
307
308             setDate(mEndDateButton, endMillis);
309             setTime(mStartTimeButton, startMillis);
310             setTime(mEndTimeButton, endMillis);
311         }
312     }
313
314     private class TimeClickListener implements View.OnClickListener {
315         private Time mTime;
316
317         public TimeClickListener(Time time) {
318             mTime = time;
319         }
320
321         public void onClick(View v) {
322             new TimePickerDialog(EditEvent.this, new TimeListener(v),
323                     mTime.hour, mTime.minute,
324                     DateFormat.is24HourFormat(EditEvent.this)).show();
325         }
326     }
327
328     private class DateListener implements OnDateSetListener {
329         View mView;
330
331         public DateListener(View view) {
332             mView = view;
333         }
334
335         public void onDateSet(DatePicker view, int year, int month, int monthDay) {
336             // Cache the member variables locally to avoid inner class overhead.
337             Time startTime = mStartTime;
338             Time endTime = mEndTime;
339
340             // Cache the start and end millis so that we limit the number
341             // of calls to normalize() and toMillis(), which are fairly
342             // expensive.
343             long startMillis;
344             long endMillis;
345             if (mView == mStartDateButton) {
346                 // The start date was changed.
347                 int yearDuration = endTime.year - startTime.year;
348                 int monthDuration = endTime.month - startTime.month;
349                 int monthDayDuration = endTime.monthDay - startTime.monthDay;
350
351                 startTime.year = year;
352                 startTime.month = month;
353                 startTime.monthDay = monthDay;
354                 startMillis = startTime.normalize(true);
355
356                 // Also update the end date to keep the duration constant.
357                 endTime.year = year + yearDuration;
358                 endTime.month = month + monthDuration;
359                 endTime.monthDay = monthDay + monthDayDuration;
360                 endMillis = endTime.normalize(true);
361
362                 // If the start date has changed then update the repeats.
363                 populateRepeats();
364             } else {
365                 // The end date was changed.
366                 startMillis = startTime.toMillis(true);
367                 endTime.year = year;
368                 endTime.month = month;
369                 endTime.monthDay = monthDay;
370                 endMillis = endTime.normalize(true);
371
372                 // Do not allow an event to have an end time before the start time.
373                 if (endTime.before(startTime)) {
374                     endTime.set(startTime);
375                     endMillis = startMillis;
376                 }
377             }
378
379             setDate(mStartDateButton, startMillis);
380             setDate(mEndDateButton, endMillis);
381             setTime(mEndTimeButton, endMillis); // In case end time had to be reset
382         }
383     }
384
385     private class DateClickListener implements View.OnClickListener {
386         private Time mTime;
387
388         public DateClickListener(Time time) {
389             mTime = time;
390         }
391
392         public void onClick(View v) {
393             new DatePickerDialog(EditEvent.this, new DateListener(v), mTime.year,
394                     mTime.month, mTime.monthDay).show();
395         }
396     }
397
398     static private class CalendarsAdapter extends ResourceCursorAdapter {
399         public CalendarsAdapter(Context context, Cursor c) {
400             super(context, R.layout.calendars_item, c);
401             setDropDownViewResource(R.layout.calendars_dropdown_item);
402         }
403
404         @Override
405         public void bindView(View view, Context context, Cursor cursor) {
406             TextView name = (TextView) view.findViewById(R.id.calendar_name);
407             name.setText(cursor.getString(CALENDARS_INDEX_DISPLAY_NAME));
408         }
409     }
410
411     // This is called if the user clicks on one of the buttons: "Save",
412     // "Discard", or "Delete".  This is also called if the user clicks
413     // on the "remove reminder" button.
414     public void onClick(View v) {
415         if (v == mSaveButton) {
416             if (save()) {
417                 finish();
418             }
419             return;
420         }
421
422         if (v == mDeleteButton) {
423             long begin = mStartTime.toMillis(false /* use isDst */);
424             long end = mEndTime.toMillis(false /* use isDst */);
425             int which = -1;
426             switch (mModification) {
427             case MODIFY_SELECTED:
428                 which = DeleteEventHelper.DELETE_SELECTED;
429                 break;
430             case MODIFY_ALL_FOLLOWING:
431                 which = DeleteEventHelper.DELETE_ALL_FOLLOWING;
432                 break;
433             case MODIFY_ALL:
434                 which = DeleteEventHelper.DELETE_ALL;
435                 break;
436             }
437             mDeleteEventHelper.delete(begin, end, mEventCursor, which);
438             return;
439         }
440
441         if (v == mDiscardButton) {
442             finish();
443             return;
444         }
445
446         // This must be a click on one of the "remove reminder" buttons
447         LinearLayout reminderItem = (LinearLayout) v.getParent();
448         LinearLayout parent = (LinearLayout) reminderItem.getParent();
449         parent.removeView(reminderItem);
450         mReminderItems.remove(reminderItem);
451         updateRemindersVisibility();
452     }
453
454     // This is called if the user cancels a popup dialog.  There are two
455     // dialogs: the "Loading calendars" dialog, and the "No calendars"
456     // dialog.  The "Loading calendars" dialog is shown if there is a delay
457     // in loading the calendars (needed when creating an event) and the user
458     // tries to save the event before the calendars have finished loading.
459     // The "No calendars" dialog is shown if there are no syncable calendars.
460     public void onCancel(DialogInterface dialog) {
461         if (dialog == mLoadingCalendarsDialog) {
462             mSaveAfterQueryComplete = false;
463         } else if (dialog == mNoCalendarsDialog) {
464             finish();
465         }
466     }
467
468     // This is called if the user clicks on a dialog button.
469     public void onClick(DialogInterface dialog, int which) {
470         if (dialog == mNoCalendarsDialog) {
471             finish();
472         }
473     }
474
475     private class QueryHandler extends AsyncQueryHandler {
476         public QueryHandler(ContentResolver cr) {
477             super(cr);
478         }
479
480         @Override
481         protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
482             // If the Activity is finishing, then close the cursor.
483             // Otherwise, use the new cursor in the adapter.
484             if (isFinishing()) {
485                 stopManagingCursor(cursor);
486                 cursor.close();
487             } else {
488                 mCalendarsCursor = cursor;
489                 startManagingCursor(cursor);
490
491                 // Stop the spinner
492                 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
493                         Window.PROGRESS_VISIBILITY_OFF);
494
495                 // If there are no syncable calendars, then we cannot allow
496                 // creating a new event.
497                 if (cursor.getCount() == 0) {
498                     // Cancel the "loading calendars" dialog if it exists
499                     if (mSaveAfterQueryComplete) {
500                         mLoadingCalendarsDialog.cancel();
501                     }
502
503                     // Create an error message for the user that, when clicked,
504                     // will exit this activity without saving the event.
505                     AlertDialog.Builder builder = new AlertDialog.Builder(EditEvent.this);
506                     builder.setTitle(R.string.no_syncable_calendars)
507                         .setIcon(android.R.drawable.ic_dialog_alert)
508                         .setMessage(R.string.no_calendars_found)
509                         .setPositiveButton(android.R.string.ok, EditEvent.this)
510                         .setOnCancelListener(EditEvent.this);
511                     mNoCalendarsDialog = builder.show();
512                     return;
513                 }
514
515                 int primaryCalendarPosition = findPrimaryCalendarPosition();
516
517                 // populate the calendars spinner
518                 CalendarsAdapter adapter = new CalendarsAdapter(EditEvent.this, mCalendarsCursor);
519                 mCalendarsSpinner.setAdapter(adapter);
520                 mCalendarsSpinner.setSelection(primaryCalendarPosition);
521                 mCalendarsQueryComplete = true;
522                 if (mSaveAfterQueryComplete) {
523                     mLoadingCalendarsDialog.cancel();
524                     save();
525                     finish();
526                 }
527
528                 // Find user domain and set it to the validator.
529                 // TODO: we may want to update this validator if the user actually picks
530                 // a different calendar.  maybe not.  depends on what we want for the
531                 // user experience.  this may change when we add support for multiple
532                 // accounts, anyway.
533                 if (cursor.moveToPosition(primaryCalendarPosition)) {
534                     String ownEmail = cursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
535                     if (ownEmail != null) {
536                         String domain = extractDomain(ownEmail);
537                         if (domain != null) {
538                             mEmailValidator = new Rfc822Validator(domain);
539                             mAttendeesList.setValidator(mEmailValidator);
540                         }
541                     }
542                 }
543             }
544         }
545
546         // Find the calendar position in the cursor that matches the signed-in
547         // account
548         private int findPrimaryCalendarPosition() {
549             int primaryCalendarPosition = -1;
550             try {
551                 Account[] accounts = mAccountManager.getAccountsByTypeAndFeatures(
552                         GoogleLoginServiceConstants.ACCOUNT_TYPE, new String[] {
553                             GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE
554                         }, null, null).getResult();
555                 if (accounts.length > 0) {
556                     for (int i = 0; i < accounts.length && primaryCalendarPosition == -1; ++i) {
557                         String name = accounts[i].name;
558                         if (name == null) {
559                             continue;
560                         }
561
562                         int position = 0;
563                         mCalendarsCursor.moveToPosition(-1);
564                         while (mCalendarsCursor.moveToNext()) {
565                             if (name.equals(mCalendarsCursor
566                                     .getString(CALENDARS_INDEX_OWNER_ACCOUNT))) {
567                                 primaryCalendarPosition = position;
568                                 break;
569                             }
570                             position++;
571                         }
572                     }
573                 }
574             } catch (OperationCanceledException e) {
575                 Log.w(TAG, "Ignoring unexpected exception", e);
576             } catch (IOException e) {
577                 Log.w(TAG, "Ignoring unexpected exception", e);
578             } catch (AuthenticatorException e) {
579                 Log.w(TAG, "Ignoring unexpected exception", e);
580             } finally {
581                 if (primaryCalendarPosition != -1) {
582                     return primaryCalendarPosition;
583                 } else {
584                     return 0;
585                 }
586             }
587         }
588     }
589
590     private static String extractDomain(String email) {
591         int separator = email.lastIndexOf('@');
592         if (separator != -1 && ++separator < email.length()) {
593             return email.substring(separator);
594         }
595         return null;
596     }
597
598     @Override
599     protected void onCreate(Bundle icicle) {
600         super.onCreate(icicle);
601         requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
602         setContentView(R.layout.edit_event);
603         mAccountManager = AccountManager.get(this);
604
605         boolean newEvent = false;
606
607         mFirstDayOfWeek = Calendar.getInstance().getFirstDayOfWeek();
608
609         mStartTime = new Time();
610         mEndTime = new Time();
611
612         Intent intent = getIntent();
613         mUri = intent.getData();
614
615         if (mUri != null) {
616             mEventCursor = managedQuery(mUri, EVENT_PROJECTION, null, null);
617             if (mEventCursor == null || mEventCursor.getCount() == 0) {
618                 // The cursor is empty. This can happen if the event was deleted.
619                 finish();
620                 return;
621             }
622         }
623
624         long begin = intent.getLongExtra(EVENT_BEGIN_TIME, 0);
625         long end = intent.getLongExtra(EVENT_END_TIME, 0);
626
627         String domain = "gmail.com";
628
629         boolean allDay = false;
630         if (mEventCursor != null) {
631             // The event already exists so fetch the all-day status
632             mEventCursor.moveToFirst();
633             allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
634             String rrule = mEventCursor.getString(EVENT_INDEX_RRULE);
635             String timezone = mEventCursor.getString(EVENT_INDEX_TIMEZONE);
636             long calendarId = mEventCursor.getInt(EVENT_INDEX_CALENDAR_ID);
637             String ownerAccount = mEventCursor.getString(EVENT_INDEX_OWNER_ACCOUNT);
638             if (!TextUtils.isEmpty(ownerAccount)) {
639                 String ownerDomain = extractDomain(ownerAccount);
640                 if (ownerDomain != null) {
641                     domain = ownerDomain;
642                 }
643             }
644
645             // Remember the initial values
646             mInitialValues = new ContentValues();
647             mInitialValues.put(EVENT_BEGIN_TIME, begin);
648             mInitialValues.put(EVENT_END_TIME, end);
649             mInitialValues.put(Events.ALL_DAY, allDay ? 1 : 0);
650             mInitialValues.put(Events.RRULE, rrule);
651             mInitialValues.put(Events.EVENT_TIMEZONE, timezone);
652             mInitialValues.put(Events.CALENDAR_ID, calendarId);
653         } else {
654             newEvent = true;
655             // We are creating a new event, so set the default from the
656             // intent (if specified).
657             allDay = intent.getBooleanExtra(EVENT_ALL_DAY, false);
658
659             // Start the spinner
660             getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
661                     Window.PROGRESS_VISIBILITY_ON);
662
663             // Start a query in the background to read the list of calendars
664             mQueryHandler = new QueryHandler(getContentResolver());
665             mQueryHandler.startQuery(0, null, Calendars.CONTENT_URI, CALENDARS_PROJECTION,
666                     CALENDARS_WHERE, null /* selection args */, null /* sort order */);
667         }
668
669         // If the event is all-day, read the times in UTC timezone
670         if (begin != 0) {
671             if (allDay) {
672                 String tz = mStartTime.timezone;
673                 mStartTime.timezone = Time.TIMEZONE_UTC;
674                 mStartTime.set(begin);
675                 mStartTime.timezone = tz;
676
677                 // Calling normalize to calculate isDst
678                 mStartTime.normalize(true);
679             } else {
680                 mStartTime.set(begin);
681             }
682         }
683
684         if (end != 0) {
685             if (allDay) {
686                 String tz = mStartTime.timezone;
687                 mEndTime.timezone = Time.TIMEZONE_UTC;
688                 mEndTime.set(end);
689                 mEndTime.timezone = tz;
690
691                 // Calling normalize to calculate isDst
692                 mEndTime.normalize(true);
693             } else {
694                 mEndTime.set(end);
695             }
696         }
697
698         // cache all the widgets
699         mTitleTextView = (TextView) findViewById(R.id.title);
700         mLocationTextView = (TextView) findViewById(R.id.location);
701         mDescriptionTextView = (TextView) findViewById(R.id.description);
702         mStartDateButton = (Button) findViewById(R.id.start_date);
703         mEndDateButton = (Button) findViewById(R.id.end_date);
704         mStartTimeButton = (Button) findViewById(R.id.start_time);
705         mEndTimeButton = (Button) findViewById(R.id.end_time);
706         mAllDayCheckBox = (CheckBox) findViewById(R.id.is_all_day);
707         mCalendarsSpinner = (Spinner) findViewById(R.id.calendars);
708         mRepeatsSpinner = (Spinner) findViewById(R.id.repeats);
709         mAvailabilitySpinner = (Spinner) findViewById(R.id.availability);
710         mVisibilitySpinner = (Spinner) findViewById(R.id.visibility);
711         mRemindersSeparator = findViewById(R.id.reminders_separator);
712         mRemindersContainer = (LinearLayout) findViewById(R.id.reminder_items_container);
713         mExtraOptions = (LinearLayout) findViewById(R.id.extra_options_container);
714
715         mAddressAdapter = new EmailAddressAdapter(this);
716         mEmailValidator = new Rfc822Validator(domain);
717         mAttendeesList = initMultiAutoCompleteTextView(R.id.attendees);
718
719         mAllDayCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
720             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
721                 if (isChecked) {
722                     if (mEndTime.hour == 0 && mEndTime.minute == 0) {
723                         mEndTime.monthDay--;
724                         long endMillis = mEndTime.normalize(true);
725
726                         // Do not allow an event to have an end time before the start time.
727                         if (mEndTime.before(mStartTime)) {
728                             mEndTime.set(mStartTime);
729                             endMillis = mEndTime.normalize(true);
730                         }
731                         setDate(mEndDateButton, endMillis);
732                         setTime(mEndTimeButton, endMillis);
733                     }
734
735                     mStartTimeButton.setVisibility(View.GONE);
736                     mEndTimeButton.setVisibility(View.GONE);
737                 } else {
738                     if (mEndTime.hour == 0 && mEndTime.minute == 0) {
739                         mEndTime.monthDay++;
740                         long endMillis = mEndTime.normalize(true);
741                         setDate(mEndDateButton, endMillis);
742                         setTime(mEndTimeButton, endMillis);
743                     }
744
745                     mStartTimeButton.setVisibility(View.VISIBLE);
746                     mEndTimeButton.setVisibility(View.VISIBLE);
747                 }
748             }
749         });
750
751         if (allDay) {
752             mAllDayCheckBox.setChecked(true);
753         } else {
754             mAllDayCheckBox.setChecked(false);
755         }
756
757         mSaveButton = (Button) findViewById(R.id.save);
758         mSaveButton.setOnClickListener(this);
759
760         mDeleteButton = (Button) findViewById(R.id.delete);
761         mDeleteButton.setOnClickListener(this);
762
763         mDiscardButton = (Button) findViewById(R.id.discard);
764         mDiscardButton.setOnClickListener(this);
765
766         // Initialize the reminder values array.
767         Resources r = getResources();
768         String[] strings = r.getStringArray(R.array.reminder_minutes_values);
769         int size = strings.length;
770         ArrayList<Integer> list = new ArrayList<Integer>(size);
771         for (int i = 0 ; i < size ; i++) {
772             list.add(Integer.parseInt(strings[i]));
773         }
774         mReminderValues = list;
775         String[] labels = r.getStringArray(R.array.reminder_minutes_labels);
776         mReminderLabels = new ArrayList<String>(Arrays.asList(labels));
777
778         SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
779         String durationString =
780                 prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0");
781         mDefaultReminderMinutes = Integer.parseInt(durationString);
782
783         if (newEvent && mDefaultReminderMinutes != 0) {
784             addReminder(this, this, mReminderItems, mReminderValues,
785                     mReminderLabels, mDefaultReminderMinutes);
786         }
787
788         long eventId = (mEventCursor == null) ? -1 : mEventCursor.getLong(EVENT_INDEX_ID);
789         ContentResolver cr = getContentResolver();
790
791         // Reminders cursor
792         boolean hasAlarm = (mEventCursor != null)
793                 && (mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0);
794         if (hasAlarm) {
795             Uri uri = Reminders.CONTENT_URI;
796             String where = String.format(REMINDERS_WHERE, eventId);
797             Cursor reminderCursor = cr.query(uri, REMINDERS_PROJECTION, where, null, null);
798             try {
799                 // First pass: collect all the custom reminder minutes (e.g.,
800                 // a reminder of 8 minutes) into a global list.
801                 while (reminderCursor.moveToNext()) {
802                     int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
803                     EditEvent.addMinutesToList(this, mReminderValues, mReminderLabels, minutes);
804                 }
805
806                 // Second pass: create the reminder spinners
807                 reminderCursor.moveToPosition(-1);
808                 while (reminderCursor.moveToNext()) {
809                     int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
810                     mOriginalMinutes.add(minutes);
811                     EditEvent.addReminder(this, this, mReminderItems, mReminderValues,
812                             mReminderLabels, minutes);
813                 }
814             } finally {
815                 reminderCursor.close();
816             }
817         }
818         updateRemindersVisibility();
819
820         // Setup the + Add Reminder Button
821         View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
822             public void onClick(View v) {
823                 addReminder();
824             }
825         };
826         ImageButton reminderRemoveButton = (ImageButton) findViewById(R.id.reminder_add);
827         reminderRemoveButton.setOnClickListener(addReminderOnClickListener);
828
829         mDeleteEventHelper = new DeleteEventHelper(this, true /* exit when done */);
830
831        // Attendees cursor
832         if (eventId != -1) {
833             Uri uri = Attendees.CONTENT_URI;
834             String[] whereArgs = {Long.toString(eventId)};
835             Cursor attendeeCursor = cr.query(uri, ATTENDEES_PROJECTION, ATTENDEES_WHERE, whereArgs,
836                     null);
837             try {
838                 StringBuilder b = new StringBuilder();
839                 while (attendeeCursor.moveToNext()) {
840                     String name = attendeeCursor.getString(ATTENDEES_INDEX_NAME);
841                     String email = attendeeCursor.getString(ATTENDEES_INDEX_EMAIL);
842                     if (email != null) {
843                         if (name != null && name.length() > 0 && !name.equals(email)) {
844                             b.append('"').append(name).append("\" ");
845                         }
846                         b.append('<').append(email).append(">, ");
847                     }
848                 }
849                 if (b.length() > 0) {
850                     mOriginalAttendees = b.toString();
851                     mAttendeesList.setText(mOriginalAttendees);
852                 }
853             } finally {
854                 attendeeCursor.close();
855             }
856         }
857         if (mEventCursor == null) {
858             // Allow the intent to specify the fields in the event.
859             // This will allow other apps to create events easily.
860             initFromIntent(intent);
861         }
862     }
863
864     private LinkedHashSet<Rfc822Token> getAddressesFromList(MultiAutoCompleteTextView list) {
865         list.clearComposingText();
866         LinkedHashSet<Rfc822Token> addresses = new LinkedHashSet<Rfc822Token>();
867         Rfc822Tokenizer.tokenize(list.getText(), addresses);
868
869         // validate the emails, out of paranoia.  they should already be
870         // validated on input, but drop any invalid emails just to be safe.
871         for (Rfc822Token address : addresses) {
872             if (!mEmailValidator.isValid(address.getAddress())) {
873                 Log.w(TAG, "Dropping invalid attendee email address: " + address);
874                 addresses.remove(address);
875             }
876         }
877         return addresses;
878     }
879
880     // From com.google.android.gm.ComposeActivity
881     private MultiAutoCompleteTextView initMultiAutoCompleteTextView(int res) {
882         MultiAutoCompleteTextView list = (MultiAutoCompleteTextView) findViewById(res);
883         list.setAdapter(mAddressAdapter);
884         list.setTokenizer(new Rfc822Tokenizer());
885         list.setValidator(mEmailValidator);
886
887         // NOTE: assumes no other filters are set
888         list.setFilters(sRecipientFilters);
889
890         return list;
891     }
892
893     /**
894      * From com.google.android.gm.ComposeActivity
895      * Implements special address cleanup rules:
896      * The first space key entry following an "@" symbol that is followed by any combination
897      * of letters and symbols, including one+ dots and zero commas, should insert an extra
898      * comma (followed by the space).
899      */
900     private static InputFilter[] sRecipientFilters = new InputFilter[] { new Rfc822InputFilter() };
901
902     private void initFromIntent(Intent intent) {
903         String title = intent.getStringExtra(Events.TITLE);
904         if (title != null) {
905             mTitleTextView.setText(title);
906         }
907
908         String location = intent.getStringExtra(Events.EVENT_LOCATION);
909         if (location != null) {
910             mLocationTextView.setText(location);
911         }
912
913         String description = intent.getStringExtra(Events.DESCRIPTION);
914         if (description != null) {
915             mDescriptionTextView.setText(description);
916         }
917
918         int availability = intent.getIntExtra(Events.TRANSPARENCY, -1);
919         if (availability != -1) {
920             mAvailabilitySpinner.setSelection(availability);
921         }
922
923         int visibility = intent.getIntExtra(Events.VISIBILITY, -1);
924         if (visibility != -1) {
925             mVisibilitySpinner.setSelection(visibility);
926         }
927
928         String rrule = intent.getStringExtra(Events.RRULE);
929         if (rrule != null) {
930             mRrule = rrule;
931             mEventRecurrence.parse(rrule);
932         }
933     }
934
935     @Override
936     protected void onResume() {
937         super.onResume();
938
939         if (mUri != null) {
940             if (mEventCursor == null || mEventCursor.getCount() == 0) {
941                 // The cursor is empty. This can happen if the event was deleted.
942                 finish();
943                 return;
944             }
945         }
946
947         if (mEventCursor != null) {
948             Cursor cursor = mEventCursor;
949             cursor.moveToFirst();
950
951             mRrule = cursor.getString(EVENT_INDEX_RRULE);
952             String title = cursor.getString(EVENT_INDEX_TITLE);
953             String description = cursor.getString(EVENT_INDEX_DESCRIPTION);
954             String location = cursor.getString(EVENT_INDEX_EVENT_LOCATION);
955             int availability = cursor.getInt(EVENT_INDEX_TRANSPARENCY);
956             int visibility = cursor.getInt(EVENT_INDEX_VISIBILITY);
957             if (visibility > 0) {
958                 // For now we the array contains the values 0, 2, and 3. We subtract one to match.
959                 visibility--;
960             }
961
962             if (!TextUtils.isEmpty(mRrule) && mModification == MODIFY_UNINITIALIZED) {
963                 // If this event has not been synced, then don't allow deleting
964                 // or changing a single instance.
965                 mSyncId = cursor.getString(EVENT_INDEX_SYNC_ID);
966                 mEventRecurrence.parse(mRrule);
967
968                 // If we haven't synced this repeating event yet, then don't
969                 // allow the user to change just one instance.
970                 int itemIndex = 0;
971                 CharSequence[] items;
972                 if (mSyncId == null) {
973                     items = new CharSequence[2];
974                 } else {
975                     items = new CharSequence[3];
976                     items[itemIndex++] = getText(R.string.modify_event);
977                 }
978                 items[itemIndex++] = getText(R.string.modify_all);
979                 items[itemIndex++] = getText(R.string.modify_all_following);
980
981                 // Display the modification dialog.
982                 new AlertDialog.Builder(this)
983                         .setOnCancelListener(new OnCancelListener() {
984                             public void onCancel(DialogInterface dialog) {
985                                 finish();
986                             }
987                         })
988                         .setTitle(R.string.edit_event_label)
989                         .setItems(items, new OnClickListener() {
990                             public void onClick(DialogInterface dialog, int which) {
991                                 if (which == 0) {
992                                     mModification =
993                                             (mSyncId == null) ? MODIFY_ALL : MODIFY_SELECTED;
994                                 } else if (which == 1) {
995                                     mModification =
996                                         (mSyncId == null) ? MODIFY_ALL_FOLLOWING : MODIFY_ALL;
997                                 } else if (which == 2) {
998                                     mModification = MODIFY_ALL_FOLLOWING;
999                                 }
1000
1001                                 // If we are modifying all the events in a
1002                                 // series then disable and ignore the date.
1003                                 if (mModification == MODIFY_ALL) {
1004                                     mStartDateButton.setEnabled(false);
1005                                     mEndDateButton.setEnabled(false);
1006                                 } else if (mModification == MODIFY_SELECTED) {
1007                                     mRepeatsSpinner.setEnabled(false);
1008                                 }
1009                             }
1010                         })
1011                         .show();
1012             }
1013
1014             mTitleTextView.setText(title);
1015             mLocationTextView.setText(location);
1016             mDescriptionTextView.setText(description);
1017             mAvailabilitySpinner.setSelection(availability);
1018             mVisibilitySpinner.setSelection(visibility);
1019
1020             // This is an existing event so hide the calendar spinner
1021             // since we can't change the calendar.
1022             View calendarGroup = findViewById(R.id.calendar_group);
1023             calendarGroup.setVisibility(View.GONE);
1024         } else {
1025             // New event
1026             if (Time.isEpoch(mStartTime) && Time.isEpoch(mEndTime)) {
1027                 mStartTime.setToNow();
1028
1029                 // Round the time to the nearest half hour.
1030                 mStartTime.second = 0;
1031                 int minute = mStartTime.minute;
1032                 if (minute > 0 && minute <= 30) {
1033                     mStartTime.minute = 30;
1034                 } else {
1035                     mStartTime.minute = 0;
1036                     mStartTime.hour += 1;
1037                 }
1038
1039                 long startMillis = mStartTime.normalize(true /* ignore isDst */);
1040                 mEndTime.set(startMillis + DateUtils.HOUR_IN_MILLIS);
1041             }
1042
1043             // Hide delete button
1044             mDeleteButton.setVisibility(View.GONE);
1045         }
1046
1047         updateRemindersVisibility();
1048         populateWhen();
1049         populateRepeats();
1050     }
1051
1052     @Override
1053     public boolean onCreateOptionsMenu(Menu menu) {
1054         MenuItem item;
1055         item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0,
1056                 R.string.add_new_reminder);
1057         item.setIcon(R.drawable.ic_menu_reminder);
1058         item.setAlphabeticShortcut('r');
1059
1060         item = menu.add(MENU_GROUP_SHOW_OPTIONS, MENU_SHOW_EXTRA_OPTIONS, 0,
1061                 R.string.edit_event_show_extra_options);
1062         item.setIcon(R.drawable.ic_menu_show_list);
1063         item = menu.add(MENU_GROUP_HIDE_OPTIONS, MENU_HIDE_EXTRA_OPTIONS, 0,
1064                 R.string.edit_event_hide_extra_options);
1065         item.setIcon(R.drawable.ic_menu_show_list);
1066
1067         return super.onCreateOptionsMenu(menu);
1068     }
1069
1070     @Override
1071     public boolean onPrepareOptionsMenu(Menu menu) {
1072         if (mReminderItems.size() < MAX_REMINDERS) {
1073             menu.setGroupVisible(MENU_GROUP_REMINDER, true);
1074             menu.setGroupEnabled(MENU_GROUP_REMINDER, true);
1075         } else {
1076             menu.setGroupVisible(MENU_GROUP_REMINDER, false);
1077             menu.setGroupEnabled(MENU_GROUP_REMINDER, false);
1078         }
1079
1080         if (mExtraOptions.getVisibility() == View.VISIBLE) {
1081             menu.setGroupVisible(MENU_GROUP_SHOW_OPTIONS, false);
1082             menu.setGroupVisible(MENU_GROUP_HIDE_OPTIONS, true);
1083         } else {
1084             menu.setGroupVisible(MENU_GROUP_SHOW_OPTIONS, true);
1085             menu.setGroupVisible(MENU_GROUP_HIDE_OPTIONS, false);
1086         }
1087
1088         return super.onPrepareOptionsMenu(menu);
1089     }
1090
1091     private void addReminder() {
1092         // TODO: when adding a new reminder, make it different from the
1093         // last one in the list (if any).
1094         if (mDefaultReminderMinutes == 0) {
1095             addReminder(this, this, mReminderItems, mReminderValues,
1096                     mReminderLabels, 10 /* minutes */);
1097         } else {
1098             addReminder(this, this, mReminderItems, mReminderValues,
1099                     mReminderLabels, mDefaultReminderMinutes);
1100         }
1101         updateRemindersVisibility();
1102     }
1103
1104     @Override
1105     public boolean onOptionsItemSelected(MenuItem item) {
1106         switch (item.getItemId()) {
1107         case MENU_ADD_REMINDER:
1108             addReminder();
1109             return true;
1110         case MENU_SHOW_EXTRA_OPTIONS:
1111             mExtraOptions.setVisibility(View.VISIBLE);
1112             return true;
1113         case MENU_HIDE_EXTRA_OPTIONS:
1114             mExtraOptions.setVisibility(View.GONE);
1115             return true;
1116         }
1117         return super.onOptionsItemSelected(item);
1118     }
1119
1120     @Override
1121     public void onBackPressed() {
1122         // If we are creating a new event, do not create it if the
1123         // title, location and description are all empty, in order to
1124         // prevent accidental "no subject" event creations.
1125         if (mUri != null || !isEmpty()) {
1126             if (!save()) {
1127                 // We cannot exit this activity because the calendars
1128                 // are still loading.
1129                 return;
1130             }
1131         }
1132         finish();
1133     }
1134
1135     private void populateWhen() {
1136         long startMillis = mStartTime.toMillis(false /* use isDst */);
1137         long endMillis = mEndTime.toMillis(false /* use isDst */);
1138         setDate(mStartDateButton, startMillis);
1139         setDate(mEndDateButton, endMillis);
1140
1141         setTime(mStartTimeButton, startMillis);
1142         setTime(mEndTimeButton, endMillis);
1143
1144         mStartDateButton.setOnClickListener(new DateClickListener(mStartTime));
1145         mEndDateButton.setOnClickListener(new DateClickListener(mEndTime));
1146
1147         mStartTimeButton.setOnClickListener(new TimeClickListener(mStartTime));
1148         mEndTimeButton.setOnClickListener(new TimeClickListener(mEndTime));
1149     }
1150
1151     private void populateRepeats() {
1152         Time time = mStartTime;
1153         Resources r = getResources();
1154         int resource = android.R.layout.simple_spinner_item;
1155
1156         String[] days = new String[] {
1157             DateUtils.getDayOfWeekString(Calendar.SUNDAY, DateUtils.LENGTH_MEDIUM),
1158             DateUtils.getDayOfWeekString(Calendar.MONDAY, DateUtils.LENGTH_MEDIUM),
1159             DateUtils.getDayOfWeekString(Calendar.TUESDAY, DateUtils.LENGTH_MEDIUM),
1160             DateUtils.getDayOfWeekString(Calendar.WEDNESDAY, DateUtils.LENGTH_MEDIUM),
1161             DateUtils.getDayOfWeekString(Calendar.THURSDAY, DateUtils.LENGTH_MEDIUM),
1162             DateUtils.getDayOfWeekString(Calendar.FRIDAY, DateUtils.LENGTH_MEDIUM),
1163             DateUtils.getDayOfWeekString(Calendar.SATURDAY, DateUtils.LENGTH_MEDIUM),
1164         };
1165         String[] ordinals = r.getStringArray(R.array.ordinal_labels);
1166
1167         // Only display "Custom" in the spinner if the device does not support the
1168         // recurrence functionality of the event. Only display every weekday if
1169         // the event starts on a weekday.
1170         boolean isCustomRecurrence = isCustomRecurrence();
1171         boolean isWeekdayEvent = isWeekdayEvent();
1172
1173         ArrayList<String> repeatArray = new ArrayList<String>(0);
1174         ArrayList<Integer> recurrenceIndexes = new ArrayList<Integer>(0);
1175
1176         repeatArray.add(r.getString(R.string.does_not_repeat));
1177         recurrenceIndexes.add(DOES_NOT_REPEAT);
1178
1179         repeatArray.add(r.getString(R.string.daily));
1180         recurrenceIndexes.add(REPEATS_DAILY);
1181
1182         if (isWeekdayEvent) {
1183             repeatArray.add(r.getString(R.string.every_weekday));
1184             recurrenceIndexes.add(REPEATS_EVERY_WEEKDAY);
1185         }
1186
1187         String format = r.getString(R.string.weekly);
1188         repeatArray.add(String.format(format, time.format("%A")));
1189         recurrenceIndexes.add(REPEATS_WEEKLY_ON_DAY);
1190
1191         // Calculate whether this is the 1st, 2nd, 3rd, 4th, or last appearance of the given day.
1192         int dayNumber = (time.monthDay - 1) / 7;
1193         format = r.getString(R.string.monthly_on_day_count);
1194         repeatArray.add(String.format(format, ordinals[dayNumber], days[time.weekDay]));
1195         recurrenceIndexes.add(REPEATS_MONTHLY_ON_DAY_COUNT);
1196
1197         format = r.getString(R.string.monthly_on_day);
1198         repeatArray.add(String.format(format, time.monthDay));
1199         recurrenceIndexes.add(REPEATS_MONTHLY_ON_DAY);
1200
1201         long when = time.toMillis(false);
1202         format = r.getString(R.string.yearly);
1203         int flags = 0;
1204         if (DateFormat.is24HourFormat(this)) {
1205             flags |= DateUtils.FORMAT_24HOUR;
1206         }
1207         repeatArray.add(String.format(format, DateUtils.formatDateTime(this, when, flags)));
1208         recurrenceIndexes.add(REPEATS_YEARLY);
1209
1210         if (isCustomRecurrence) {
1211             repeatArray.add(r.getString(R.string.custom));
1212             recurrenceIndexes.add(REPEATS_CUSTOM);
1213         }
1214         mRecurrenceIndexes = recurrenceIndexes;
1215
1216         int position = recurrenceIndexes.indexOf(DOES_NOT_REPEAT);
1217         if (mRrule != null) {
1218             if (isCustomRecurrence) {
1219                 position = recurrenceIndexes.indexOf(REPEATS_CUSTOM);
1220             } else {
1221                 switch (mEventRecurrence.freq) {
1222                     case EventRecurrence.DAILY:
1223                         position = recurrenceIndexes.indexOf(REPEATS_DAILY);
1224                         break;
1225                     case EventRecurrence.WEEKLY:
1226                         if (mEventRecurrence.repeatsOnEveryWeekDay()) {
1227                             position = recurrenceIndexes.indexOf(REPEATS_EVERY_WEEKDAY);
1228                         } else {
1229                             position = recurrenceIndexes.indexOf(REPEATS_WEEKLY_ON_DAY);
1230                         }
1231                         break;
1232                     case EventRecurrence.MONTHLY:
1233                         if (mEventRecurrence.repeatsMonthlyOnDayCount()) {
1234                             position = recurrenceIndexes.indexOf(REPEATS_MONTHLY_ON_DAY_COUNT);
1235                         } else {
1236                             position = recurrenceIndexes.indexOf(REPEATS_MONTHLY_ON_DAY);
1237                         }
1238                         break;
1239                     case EventRecurrence.YEARLY:
1240                         position = recurrenceIndexes.indexOf(REPEATS_YEARLY);
1241                         break;
1242                 }
1243             }
1244         }
1245         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, resource, repeatArray);
1246         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
1247         mRepeatsSpinner.setAdapter(adapter);
1248         mRepeatsSpinner.setSelection(position);
1249     }
1250
1251     // Adds a reminder to the displayed list of reminders.
1252     // Returns true if successfully added reminder, false if no reminders can
1253     // be added.
1254     static boolean addReminder(Activity activity, View.OnClickListener listener,
1255             ArrayList<LinearLayout> items, ArrayList<Integer> values,
1256             ArrayList<String> labels, int minutes) {
1257
1258         if (items.size() >= MAX_REMINDERS) {
1259             return false;
1260         }
1261
1262         LayoutInflater inflater = activity.getLayoutInflater();
1263         LinearLayout parent = (LinearLayout) activity.findViewById(R.id.reminder_items_container);
1264         LinearLayout reminderItem = (LinearLayout) inflater.inflate(R.layout.edit_reminder_item, null);
1265         parent.addView(reminderItem);
1266
1267         Spinner spinner = (Spinner) reminderItem.findViewById(R.id.reminder_value);
1268         Resources res = activity.getResources();
1269         spinner.setPrompt(res.getString(R.string.reminders_label));
1270         int resource = android.R.layout.simple_spinner_item;
1271         ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, resource, labels);
1272         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
1273         spinner.setAdapter(adapter);
1274
1275         ImageButton reminderRemoveButton;
1276         reminderRemoveButton = (ImageButton) reminderItem.findViewById(R.id.reminder_remove);
1277         reminderRemoveButton.setOnClickListener(listener);
1278
1279         int index = findMinutesInReminderList(values, minutes);
1280         spinner.setSelection(index);
1281         items.add(reminderItem);
1282
1283         return true;
1284     }
1285
1286     static void addMinutesToList(Context context, ArrayList<Integer> values,
1287             ArrayList<String> labels, int minutes) {
1288         int index = values.indexOf(minutes);
1289         if (index != -1) {
1290             return;
1291         }
1292
1293         // The requested "minutes" does not exist in the list, so insert it
1294         // into the list.
1295
1296         String label = constructReminderLabel(context, minutes, false);
1297         int len = values.size();
1298         for (int i = 0; i < len; i++) {
1299             if (minutes < values.get(i)) {
1300                 values.add(i, minutes);
1301                 labels.add(i, label);
1302                 return;
1303             }
1304         }
1305
1306         values.add(minutes);
1307         labels.add(len, label);
1308     }
1309
1310     /**
1311      * Finds the index of the given "minutes" in the "values" list.
1312      *
1313      * @param values the list of minutes corresponding to the spinner choices
1314      * @param minutes the minutes to search for in the values list
1315      * @return the index of "minutes" in the "values" list
1316      */
1317     private static int findMinutesInReminderList(ArrayList<Integer> values, int minutes) {
1318         int index = values.indexOf(minutes);
1319         if (index == -1) {
1320             // This should never happen.
1321             Log.e("Cal", "Cannot find minutes (" + minutes + ") in list");
1322             return 0;
1323         }
1324         return index;
1325     }
1326
1327     // Constructs a label given an arbitrary number of minutes.  For example,
1328     // if the given minutes is 63, then this returns the string "63 minutes".
1329     // As another example, if the given minutes is 120, then this returns
1330     // "2 hours".
1331     static String constructReminderLabel(Context context, int minutes, boolean abbrev) {
1332         Resources resources = context.getResources();
1333         int value, resId;
1334
1335         if (minutes % 60 != 0) {
1336             value = minutes;
1337             if (abbrev) {
1338                 resId = R.plurals.Nmins;
1339             } else {
1340                 resId = R.plurals.Nminutes;
1341             }
1342         } else if (minutes % (24 * 60) != 0) {
1343             value = minutes / 60;
1344             resId = R.plurals.Nhours;
1345         } else {
1346             value = minutes / ( 24 * 60);
1347             resId = R.plurals.Ndays;
1348         }
1349
1350         String format = resources.getQuantityString(resId, value);
1351         return String.format(format, value);
1352     }
1353
1354     private void updateRemindersVisibility() {
1355         if (mReminderItems.size() == 0) {
1356             mRemindersSeparator.setVisibility(View.GONE);
1357             mRemindersContainer.setVisibility(View.GONE);
1358         } else {
1359             mRemindersSeparator.setVisibility(View.VISIBLE);
1360             mRemindersContainer.setVisibility(View.VISIBLE);
1361         }
1362     }
1363
1364     private void setDate(TextView view, long millis) {
1365         int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
1366                 DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_MONTH |
1367                 DateUtils.FORMAT_ABBREV_WEEKDAY;
1368         view.setText(DateUtils.formatDateTime(this, millis, flags));
1369     }
1370
1371     private void setTime(TextView view, long millis) {
1372         int flags = DateUtils.FORMAT_SHOW_TIME;
1373         if (DateFormat.is24HourFormat(this)) {
1374             flags |= DateUtils.FORMAT_24HOUR;
1375         }
1376         view.setText(DateUtils.formatDateTime(this, millis, flags));
1377     }
1378
1379     // Saves the event.  Returns true if it is okay to exit this activity.
1380     private boolean save() {
1381         boolean forceSaveReminders = false;
1382
1383         // If we are creating a new event, then make sure we wait until the
1384         // query to fetch the list of calendars has finished.
1385         if (mEventCursor == null) {
1386             if (!mCalendarsQueryComplete) {
1387                 // Wait for the calendars query to finish.
1388                 if (mLoadingCalendarsDialog == null) {
1389                     // Create the progress dialog
1390                     mLoadingCalendarsDialog = ProgressDialog.show(this,
1391                             getText(R.string.loading_calendars_title),
1392                             getText(R.string.loading_calendars_message),
1393                             true, true, this);
1394                     mSaveAfterQueryComplete = true;
1395                 }
1396                 return false;
1397             }
1398
1399             // Avoid creating a new event if the calendars cursor is empty. This
1400             // shouldn't ever happen since the setup wizard should ensure the user
1401             // has a calendar.
1402             if (mCalendarsCursor == null || mCalendarsCursor.getCount() == 0) {
1403                 Log.w("Cal", "The calendars table does not contain any calendars."
1404                         + " New event was not created.");
1405                 return true;
1406             }
1407             Toast.makeText(this, R.string.creating_event, Toast.LENGTH_SHORT).show();
1408         } else {
1409             Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show();
1410         }
1411
1412         ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
1413         int eventIdIndex = -1;
1414
1415         ContentValues values = getContentValuesFromUi();
1416         Uri uri = mUri;
1417
1418         // Update the "hasAlarm" field for the event
1419         ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems,
1420                 mReminderValues);
1421         int len = reminderMinutes.size();
1422         values.put(Events.HAS_ALARM, (len > 0) ? 1 : 0);
1423
1424         // For recurring events, we must make sure that we use duration rather
1425         // than dtend.
1426         if (uri == null) {
1427             // Create new event with new contents
1428             addRecurrenceRule(values);
1429             eventIdIndex = ops.size();
1430             Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values);
1431             ops.add(b.build());
1432             forceSaveReminders = true;
1433
1434         } else if (mRrule == null) {
1435             // Modify contents of a non-repeating event
1436             addRecurrenceRule(values);
1437             checkTimeDependentFields(values);
1438             ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
1439
1440         } else if (mInitialValues.getAsString(Events.RRULE) == null) {
1441             // This event was changed from a non-repeating event to a
1442             // repeating event.
1443             addRecurrenceRule(values);
1444             values.remove(Events.DTEND);
1445             ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
1446
1447         } else if (mModification == MODIFY_SELECTED) {
1448             // Modify contents of the current instance of repeating event
1449
1450             // Create a recurrence exception
1451             long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
1452             values.put(Events.ORIGINAL_EVENT, mEventCursor.getString(EVENT_INDEX_SYNC_ID));
1453             values.put(Events.ORIGINAL_INSTANCE_TIME, begin);
1454             boolean allDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0;
1455             values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0);
1456
1457             eventIdIndex = ops.size();
1458             Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values);
1459             ops.add(b.build());
1460             forceSaveReminders = true;
1461
1462         } else if (mModification == MODIFY_ALL_FOLLOWING) {
1463             // Modify this instance and all future instances of repeating event
1464             addRecurrenceRule(values);
1465
1466             if (mRrule == null) {
1467                 // We've changed a recurring event to a non-recurring event.
1468                 // If the event we are editing is the first in the series,
1469                 // then delete the whole series.  Otherwise, update the series
1470                 // to end at the new start time.
1471                 if (isFirstEventInSeries()) {
1472                     ops.add(ContentProviderOperation.newDelete(uri).build());
1473                 } else {
1474                     // Update the current repeating event to end at the new
1475                     // start time.
1476                     updatePastEvents(ops, uri);
1477                 }
1478                 eventIdIndex = ops.size();
1479                 ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values)
1480                         .build());
1481             } else {
1482                 if (isFirstEventInSeries()) {
1483                     checkTimeDependentFields(values);
1484                     values.remove(Events.DTEND);
1485                     Builder b = ContentProviderOperation.newUpdate(uri).withValues(values);
1486                     ops.add(b.build());
1487                 } else {
1488                     // Update the current repeating event to end at the new
1489                     // start time.
1490                     updatePastEvents(ops, uri);
1491
1492                     // Create a new event with the user-modified fields
1493                     values.remove(Events.DTEND);
1494                     eventIdIndex = ops.size();
1495                     ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(
1496                             values).build());
1497                 }
1498             }
1499             forceSaveReminders = true;
1500
1501         } else if (mModification == MODIFY_ALL) {
1502
1503             // Modify all instances of repeating event
1504             addRecurrenceRule(values);
1505
1506             if (mRrule == null) {
1507                 // We've changed a recurring event to a non-recurring event.
1508                 // Delete the whole series and replace it with a new
1509                 // non-recurring event.
1510                 ops.add(ContentProviderOperation.newDelete(uri).build());
1511
1512                 eventIdIndex = ops.size();
1513                 ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values)
1514                         .build());
1515                 forceSaveReminders = true;
1516             } else {
1517                 checkTimeDependentFields(values);
1518                 values.remove(Events.DTEND);
1519                 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
1520             }
1521         }
1522
1523         if (eventIdIndex != -1) {
1524             saveRemindersWithBackRef(ops, eventIdIndex, reminderMinutes, mOriginalMinutes,
1525                     forceSaveReminders);
1526         } else if (uri != null) {
1527             long eventId = ContentUris.parseId(uri);
1528             saveReminders(ops, eventId, reminderMinutes, mOriginalMinutes,
1529                     forceSaveReminders);
1530         }
1531
1532         Builder b;
1533
1534         // New event/instance - Set Organizer's response as yes
1535         if (eventIdIndex != -1) {
1536             values.clear();
1537             int calendarCursorPosition = mCalendarsSpinner.getSelectedItemPosition();
1538             if (mCalendarsCursor.moveToPosition(calendarCursorPosition)) {
1539                 String ownerEmail = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
1540                 if (ownerEmail != null) {
1541                     String displayName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
1542                     if (displayName != null) {
1543                         values.put(Attendees.ATTENDEE_NAME, displayName);
1544                     }
1545                     values.put(Attendees.ATTENDEE_EMAIL, ownerEmail);
1546                     values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER);
1547                     values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);
1548                     values.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_ACCEPTED);
1549
1550                     b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
1551                             .withValues(values);
1552                     b.withValueBackReference(Reminders.EVENT_ID, eventIdIndex);
1553                     ops.add(b.build());
1554                 }
1555             }
1556         }
1557
1558         // TODO: is this the right test?  this currently checks if this is
1559         // a new event or an existing event.  or is this a paranoia check?
1560         if (eventIdIndex != -1 || uri != null) {
1561             Editable attendeesText = mAttendeesList.getText();
1562             // Hit the content provider only if the user has changed it
1563             if (!mOriginalAttendees.equals(attendeesText.toString())) {
1564                 // figure out which attendees need to be added and which ones
1565                 // need to be deleted.  use a linked hash set, so we maintain
1566                 // order (but also remove duplicates).
1567                 LinkedHashSet<Rfc822Token> newAttendees = getAddressesFromList(mAttendeesList);
1568
1569                 // the eventId is only used if eventIdIndex is -1.
1570                 // TODO: clean up this code.
1571                 long eventId = uri != null ? ContentUris.parseId(uri) : -1;
1572
1573                 // only compute deltas if this is an existing event.
1574                 // new events (being inserted into the Events table) won't
1575                 // have any existing attendees.
1576                 if (eventIdIndex == -1) {
1577                     HashSet<Rfc822Token> removedAttendees = new HashSet<Rfc822Token>();
1578                     HashSet<Rfc822Token> originalAttendees = new HashSet<Rfc822Token>();
1579                     Rfc822Tokenizer.tokenize(mOriginalAttendees, originalAttendees);
1580                     for (Rfc822Token originalAttendee : originalAttendees) {
1581                         if (newAttendees.contains(originalAttendee)) {
1582                             // existing attendee.  remove from new attendees set.
1583                             newAttendees.remove(originalAttendee);
1584                         } else {
1585                             // no longer in attendees.  mark as removed.
1586                             removedAttendees.add(originalAttendee);
1587                         }
1588                     }
1589
1590                     // delete removed attendees
1591                     b = ContentProviderOperation.newDelete(Attendees.CONTENT_URI);
1592
1593                     String[] args = new String[removedAttendees.size() + 1];
1594                     args[0] = Long.toString(eventId);
1595                     int i = 1;
1596                     StringBuilder deleteWhere = new StringBuilder(ATTENDEES_DELETE_PREFIX);
1597                     for (Rfc822Token removedAttendee : removedAttendees) {
1598                         if (i > 1) {
1599                             deleteWhere.append(",");
1600                         }
1601                         deleteWhere.append("?");
1602                         args[i++] = removedAttendee.getAddress();
1603                     }
1604                     deleteWhere.append(")");
1605                     b.withSelection(deleteWhere.toString(), args);
1606                     ops.add(b.build());
1607                 }
1608
1609                 if (newAttendees.size() > 0) {
1610                     // Insert the new attendees
1611                     for (Rfc822Token attendee : newAttendees) {
1612                         values.clear();
1613                         values.put(Attendees.ATTENDEE_NAME, attendee.getName());
1614                         values.put(Attendees.ATTENDEE_EMAIL, attendee.getAddress());
1615                         values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE);
1616                         values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);
1617                         values.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_NONE);
1618
1619                         if (eventIdIndex != -1) {
1620                             b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
1621                                     .withValues(values);
1622                             b.withValueBackReference(Attendees.EVENT_ID, eventIdIndex);
1623                         } else {
1624                             values.put(Attendees.EVENT_ID, eventId);
1625                             b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
1626                                     .withValues(values);
1627                         }
1628                         ops.add(b.build());
1629                     }
1630                 }
1631             }
1632         }
1633
1634         try {
1635             // TODO Move this to background thread
1636             ContentProviderResult[] results =
1637                 getContentResolver().applyBatch(android.provider.Calendar.AUTHORITY, ops);
1638             if (DEBUG) {
1639                 for (int i = 0; i < results.length; i++) {
1640                     Log.v(TAG, "results = " + results[i].toString());
1641                 }
1642             }
1643         } catch (RemoteException e) {
1644             Log.w(TAG, "Ignoring unexpected remote exception", e);
1645         } catch (OperationApplicationException e) {
1646             Log.w(TAG, "Ignoring unexpected exception", e);
1647         }
1648
1649         return true;
1650     }
1651
1652     private boolean isFirstEventInSeries() {
1653         int dtStart = mEventCursor.getColumnIndexOrThrow(Events.DTSTART);
1654         long start = mEventCursor.getLong(dtStart);
1655         return start == mStartTime.toMillis(true);
1656     }
1657
1658     private void updatePastEvents(ArrayList<ContentProviderOperation> ops, Uri uri) {
1659         long oldStartMillis = mEventCursor.getLong(EVENT_INDEX_DTSTART);
1660         String oldDuration = mEventCursor.getString(EVENT_INDEX_DURATION);
1661         boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
1662         String oldRrule = mEventCursor.getString(EVENT_INDEX_RRULE);
1663         mEventRecurrence.parse(oldRrule);
1664
1665         Time untilTime = new Time();
1666         long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
1667         ContentValues oldValues = new ContentValues();
1668
1669         // The "until" time must be in UTC time in order for Google calendar
1670         // to display it properly.  For all-day events, the "until" time string
1671         // must include just the date field, and not the time field.  The
1672         // repeating events repeat up to and including the "until" time.
1673         untilTime.timezone = Time.TIMEZONE_UTC;
1674
1675         // Subtract one second from the old begin time to get the new
1676         // "until" time.
1677         untilTime.set(begin - 1000);  // subtract one second (1000 millis)
1678         if (allDay) {
1679             untilTime.hour = 0;
1680             untilTime.minute = 0;
1681             untilTime.second = 0;
1682             untilTime.allDay = true;
1683             untilTime.normalize(false);
1684
1685             // For all-day events, the duration must be in days, not seconds.
1686             // Otherwise, Google Calendar will (mistakenly) change this event
1687             // into a non-all-day event.
1688             int len = oldDuration.length();
1689             if (oldDuration.charAt(0) == 'P' && oldDuration.charAt(len - 1) == 'S') {
1690                 int seconds = Integer.parseInt(oldDuration.substring(1, len - 1));
1691                 int days = (seconds + DAY_IN_SECONDS - 1) / DAY_IN_SECONDS;
1692                 oldDuration = "P" + days + "D";
1693             }
1694         }
1695         mEventRecurrence.until = untilTime.format2445();
1696
1697         oldValues.put(Events.DTSTART, oldStartMillis);
1698         oldValues.put(Events.DURATION, oldDuration);
1699         oldValues.put(Events.RRULE, mEventRecurrence.toString());
1700         Builder b = ContentProviderOperation.newUpdate(uri).withValues(oldValues);
1701         ops.add(b.build());
1702     }
1703
1704     private void checkTimeDependentFields(ContentValues values) {
1705         long oldBegin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
1706         long oldEnd = mInitialValues.getAsLong(EVENT_END_TIME);
1707         boolean oldAllDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0;
1708         String oldRrule = mInitialValues.getAsString(Events.RRULE);
1709         String oldTimezone = mInitialValues.getAsString(Events.EVENT_TIMEZONE);
1710
1711         long newBegin = values.getAsLong(Events.DTSTART);
1712         long newEnd = values.getAsLong(Events.DTEND);
1713         boolean newAllDay = values.getAsInteger(Events.ALL_DAY) != 0;
1714         String newRrule = values.getAsString(Events.RRULE);
1715         String newTimezone = values.getAsString(Events.EVENT_TIMEZONE);
1716
1717         // If none of the time-dependent fields changed, then remove them.
1718         if (oldBegin == newBegin && oldEnd == newEnd && oldAllDay == newAllDay
1719                 && TextUtils.equals(oldRrule, newRrule)
1720                 && TextUtils.equals(oldTimezone, newTimezone)) {
1721             values.remove(Events.DTSTART);
1722             values.remove(Events.DTEND);
1723             values.remove(Events.DURATION);
1724             values.remove(Events.ALL_DAY);
1725             values.remove(Events.RRULE);
1726             values.remove(Events.EVENT_TIMEZONE);
1727             return;
1728         }
1729
1730         if (oldRrule == null || newRrule == null) {
1731             return;
1732         }
1733
1734         // If we are modifying all events then we need to set DTSTART to the
1735         // start time of the first event in the series, not the current
1736         // date and time.  If the start time of the event was changed
1737         // (from, say, 3pm to 4pm), then we want to add the time difference
1738         // to the start time of the first event in the series (the DTSTART
1739         // value).  If we are modifying one instance or all following instances,
1740         // then we leave the DTSTART field alone.
1741         if (mModification == MODIFY_ALL) {
1742             long oldStartMillis = mEventCursor.getLong(EVENT_INDEX_DTSTART);
1743             if (oldBegin != newBegin) {
1744                 // The user changed the start time of this event
1745                 long offset = newBegin - oldBegin;
1746                 oldStartMillis += offset;
1747             }
1748             values.put(Events.DTSTART, oldStartMillis);
1749         }
1750     }
1751
1752     static ArrayList<Integer> reminderItemsToMinutes(ArrayList<LinearLayout> reminderItems,
1753             ArrayList<Integer> reminderValues) {
1754         int len = reminderItems.size();
1755         ArrayList<Integer> reminderMinutes = new ArrayList<Integer>(len);
1756         for (int index = 0; index < len; index++) {
1757             LinearLayout layout = reminderItems.get(index);
1758             Spinner spinner = (Spinner) layout.findViewById(R.id.reminder_value);
1759             int minutes = reminderValues.get(spinner.getSelectedItemPosition());
1760             reminderMinutes.add(minutes);
1761         }
1762         return reminderMinutes;
1763     }
1764
1765     /**
1766      * Saves the reminders, if they changed.  Returns true if the database
1767      * was updated.
1768      *
1769      * @param ops the array of ContentProviderOperations
1770      * @param eventId the id of the event whose reminders are being updated
1771      * @param reminderMinutes the array of reminders set by the user
1772      * @param originalMinutes the original array of reminders
1773      * @param forceSave if true, then save the reminders even if they didn't
1774      *   change
1775      * @return true if the database was updated
1776      */
1777     static boolean saveReminders(ArrayList<ContentProviderOperation> ops, long eventId,
1778             ArrayList<Integer> reminderMinutes, ArrayList<Integer> originalMinutes,
1779             boolean forceSave) {
1780         // If the reminders have not changed, then don't update the database
1781         if (reminderMinutes.equals(originalMinutes) && !forceSave) {
1782             return false;
1783         }
1784
1785         // Delete all the existing reminders for this event
1786         String where = Reminders.EVENT_ID + "=?";
1787         String[] args = new String[] { Long.toString(eventId) };
1788         Builder b = ContentProviderOperation.newDelete(Reminders.CONTENT_URI);
1789         b.withSelection(where, args);
1790         ops.add(b.build());
1791
1792         ContentValues values = new ContentValues();
1793         int len = reminderMinutes.size();
1794
1795         // Insert the new reminders, if any
1796         for (int i = 0; i < len; i++) {
1797             int minutes = reminderMinutes.get(i);
1798
1799             values.clear();
1800             values.put(Reminders.MINUTES, minutes);
1801             values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
1802             values.put(Reminders.EVENT_ID, eventId);
1803             b = ContentProviderOperation.newInsert(Reminders.CONTENT_URI).withValues(values);
1804             ops.add(b.build());
1805         }
1806         return true;
1807     }
1808
1809     static boolean saveRemindersWithBackRef(ArrayList<ContentProviderOperation> ops,
1810             int eventIdIndex, ArrayList<Integer> reminderMinutes,
1811             ArrayList<Integer> originalMinutes, boolean forceSave) {
1812         // If the reminders have not changed, then don't update the database
1813         if (reminderMinutes.equals(originalMinutes) && !forceSave) {
1814             return false;
1815         }
1816
1817         // Delete all the existing reminders for this event
1818         Builder b = ContentProviderOperation.newDelete(Reminders.CONTENT_URI);
1819         b.withSelection(Reminders.EVENT_ID + "=?", new String[1]);
1820         b.withSelectionBackReference(0, eventIdIndex);
1821         ops.add(b.build());
1822
1823         ContentValues values = new ContentValues();
1824         int len = reminderMinutes.size();
1825
1826         // Insert the new reminders, if any
1827         for (int i = 0; i < len; i++) {
1828             int minutes = reminderMinutes.get(i);
1829
1830             values.clear();
1831             values.put(Reminders.MINUTES, minutes);
1832             values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
1833             b = ContentProviderOperation.newInsert(Reminders.CONTENT_URI).withValues(values);
1834             b.withValueBackReference(Reminders.EVENT_ID, eventIdIndex);
1835             ops.add(b.build());
1836         }
1837         return true;
1838     }
1839
1840     private void addRecurrenceRule(ContentValues values) {
1841         updateRecurrenceRule();
1842
1843         if (mRrule == null) {
1844             return;
1845         }
1846
1847         values.put(Events.RRULE, mRrule);
1848         long end = mEndTime.toMillis(true /* ignore dst */);
1849         long start = mStartTime.toMillis(true /* ignore dst */);
1850         String duration;
1851
1852         boolean isAllDay = mAllDayCheckBox.isChecked();
1853         if (isAllDay) {
1854             long days = (end - start + DateUtils.DAY_IN_MILLIS - 1) / DateUtils.DAY_IN_MILLIS;
1855             duration = "P" + days + "D";
1856         } else {
1857             long seconds = (end - start) / DateUtils.SECOND_IN_MILLIS;
1858             duration = "P" + seconds + "S";
1859         }
1860         values.put(Events.DURATION, duration);
1861     }
1862
1863     private void updateRecurrenceRule() {
1864         int position = mRepeatsSpinner.getSelectedItemPosition();
1865         int selection = mRecurrenceIndexes.get(position);
1866
1867         if (selection == DOES_NOT_REPEAT) {
1868             mRrule = null;
1869             return;
1870         } else if (selection == REPEATS_CUSTOM) {
1871             // Keep custom recurrence as before.
1872             return;
1873         } else if (selection == REPEATS_DAILY) {
1874             mEventRecurrence.freq = EventRecurrence.DAILY;
1875         } else if (selection == REPEATS_EVERY_WEEKDAY) {
1876             mEventRecurrence.freq = EventRecurrence.WEEKLY;
1877             int dayCount = 5;
1878             int[] byday = new int[dayCount];
1879             int[] bydayNum = new int[dayCount];
1880
1881             byday[0] = EventRecurrence.MO;
1882             byday[1] = EventRecurrence.TU;
1883             byday[2] = EventRecurrence.WE;
1884             byday[3] = EventRecurrence.TH;
1885             byday[4] = EventRecurrence.FR;
1886             for (int day = 0; day < dayCount; day++) {
1887                 bydayNum[day] = 0;
1888             }
1889
1890             mEventRecurrence.byday = byday;
1891             mEventRecurrence.bydayNum = bydayNum;
1892             mEventRecurrence.bydayCount = dayCount;
1893         } else if (selection == REPEATS_WEEKLY_ON_DAY) {
1894             mEventRecurrence.freq = EventRecurrence.WEEKLY;
1895             int[] days = new int[1];
1896             int dayCount = 1;
1897             int[] dayNum = new int[dayCount];
1898
1899             days[0] = EventRecurrence.timeDay2Day(mStartTime.weekDay);
1900             // not sure why this needs to be zero, but set it for now.
1901             dayNum[0] = 0;
1902
1903             mEventRecurrence.byday = days;
1904             mEventRecurrence.bydayNum = dayNum;
1905             mEventRecurrence.bydayCount = dayCount;
1906         } else if (selection == REPEATS_MONTHLY_ON_DAY) {
1907             mEventRecurrence.freq = EventRecurrence.MONTHLY;
1908             mEventRecurrence.bydayCount = 0;
1909             mEventRecurrence.bymonthdayCount = 1;
1910             int[] bymonthday = new int[1];
1911             bymonthday[0] = mStartTime.monthDay;
1912             mEventRecurrence.bymonthday = bymonthday;
1913         } else if (selection == REPEATS_MONTHLY_ON_DAY_COUNT) {
1914             mEventRecurrence.freq = EventRecurrence.MONTHLY;
1915             mEventRecurrence.bydayCount = 1;
1916             mEventRecurrence.bymonthdayCount = 0;
1917
1918             int[] byday = new int[1];
1919             int[] bydayNum = new int[1];
1920             // Compute the week number (for example, the "2nd" Monday)
1921             int dayCount = 1 + ((mStartTime.monthDay - 1) / 7);
1922             if (dayCount == 5) {
1923                 dayCount = -1;
1924             }
1925             bydayNum[0] = dayCount;
1926             byday[0] = EventRecurrence.timeDay2Day(mStartTime.weekDay);
1927             mEventRecurrence.byday = byday;
1928             mEventRecurrence.bydayNum = bydayNum;
1929         } else if (selection == REPEATS_YEARLY) {
1930             mEventRecurrence.freq = EventRecurrence.YEARLY;
1931         }
1932
1933         // Set the week start day.
1934         mEventRecurrence.wkst = EventRecurrence.calendarDay2Day(mFirstDayOfWeek);
1935         mRrule = mEventRecurrence.toString();
1936     }
1937
1938     private ContentValues getContentValuesFromUi() {
1939         String title = mTitleTextView.getText().toString();
1940         boolean isAllDay = mAllDayCheckBox.isChecked();
1941         String location = mLocationTextView.getText().toString();
1942         String description = mDescriptionTextView.getText().toString();
1943
1944         ContentValues values = new ContentValues();
1945
1946         String timezone = null;
1947         long startMillis;
1948         long endMillis;
1949         long calendarId;
1950         if (isAllDay) {
1951             // Reset start and end time, increment the monthDay by 1, and set
1952             // the timezone to UTC, as required for all-day events.
1953             timezone = Time.TIMEZONE_UTC;
1954             mStartTime.hour = 0;
1955             mStartTime.minute = 0;
1956             mStartTime.second = 0;
1957             mStartTime.timezone = timezone;
1958             startMillis = mStartTime.normalize(true);
1959
1960             mEndTime.hour = 0;
1961             mEndTime.minute = 0;
1962             mEndTime.second = 0;
1963             mEndTime.monthDay++;
1964             mEndTime.timezone = timezone;
1965             endMillis = mEndTime.normalize(true);
1966
1967             if (mEventCursor == null) {
1968                 // This is a new event
1969                 calendarId = mCalendarsSpinner.getSelectedItemId();
1970             } else {
1971                 calendarId = mInitialValues.getAsLong(Events.CALENDAR_ID);
1972             }
1973         } else {
1974             startMillis = mStartTime.toMillis(true);
1975             endMillis = mEndTime.toMillis(true);
1976             if (mEventCursor != null) {
1977                 // This is an existing event
1978                 timezone = mEventCursor.getString(EVENT_INDEX_TIMEZONE);
1979
1980                 // The timezone might be null if we are changing an existing
1981                 // all-day event to a non-all-day event.  We need to assign
1982                 // a timezone to the non-all-day event.
1983                 if (TextUtils.isEmpty(timezone)) {
1984                     timezone = TimeZone.getDefault().getID();
1985                 }
1986                 calendarId = mInitialValues.getAsLong(Events.CALENDAR_ID);
1987             } else {
1988                 // This is a new event
1989                 calendarId = mCalendarsSpinner.getSelectedItemId();
1990
1991                 // The timezone for a new event is the currently displayed
1992                 // timezone, NOT the timezone of the containing calendar.
1993                 timezone = TimeZone.getDefault().getID();
1994             }
1995         }
1996
1997         values.put(Events.CALENDAR_ID, calendarId);
1998         values.put(Events.EVENT_TIMEZONE, timezone);
1999         values.put(Events.TITLE, title);
2000         values.put(Events.ALL_DAY, isAllDay ? 1 : 0);
2001         values.put(Events.DTSTART, startMillis);
2002         values.put(Events.DTEND, endMillis);
2003         values.put(Events.DESCRIPTION, description);
2004         values.put(Events.EVENT_LOCATION, location);
2005         values.put(Events.TRANSPARENCY, mAvailabilitySpinner.getSelectedItemPosition());
2006
2007         int visibility = mVisibilitySpinner.getSelectedItemPosition();
2008         if (visibility > 0) {
2009             // For now we the array contains the values 0, 2, and 3. We add one to match.
2010             visibility++;
2011         }
2012         values.put(Events.VISIBILITY, visibility);
2013
2014         return values;
2015     }
2016
2017     private boolean isEmpty() {
2018         String title = mTitleTextView.getText().toString();
2019         if (title.length() > 0) {
2020             return false;
2021         }
2022
2023         String location = mLocationTextView.getText().toString();
2024         if (location.length() > 0) {
2025             return false;
2026         }
2027
2028         String description = mDescriptionTextView.getText().toString();
2029         if (description.length() > 0) {
2030             return false;
2031         }
2032
2033         return true;
2034     }
2035
2036     private boolean isCustomRecurrence() {
2037
2038         if (mEventRecurrence.until != null || mEventRecurrence.interval != 0) {
2039             return true;
2040         }
2041
2042         if (mEventRecurrence.freq == 0) {
2043             return false;
2044         }
2045
2046         switch (mEventRecurrence.freq) {
2047         case EventRecurrence.DAILY:
2048             return false;
2049         case EventRecurrence.WEEKLY:
2050             if (mEventRecurrence.repeatsOnEveryWeekDay() && isWeekdayEvent()) {
2051                 return false;
2052             } else if (mEventRecurrence.bydayCount == 1) {
2053                 return false;
2054             }
2055             break;
2056         case EventRecurrence.MONTHLY:
2057             if (mEventRecurrence.repeatsMonthlyOnDayCount()) {
2058                 return false;
2059             } else if (mEventRecurrence.bydayCount == 0 && mEventRecurrence.bymonthdayCount == 1) {
2060                 return false;
2061             }
2062             break;
2063         case EventRecurrence.YEARLY:
2064             return false;
2065         }
2066
2067         return true;
2068     }
2069
2070     private boolean isWeekdayEvent() {
2071         if (mStartTime.weekDay != Time.SUNDAY && mStartTime.weekDay != Time.SATURDAY) {
2072             return true;
2073         }
2074         return false;
2075     }
2076 }