OSDN Git Service

am 9d694dfb: fix bug where the default reminders get added in onRestore(), rather...
[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
98 public class EditEvent extends Activity implements View.OnClickListener,
99         DialogInterface.OnCancelListener, DialogInterface.OnClickListener {
100     private static final String TAG = "EditEvent";
101     private static final boolean DEBUG = false;
102
103     /**
104      * This is the symbolic name for the key used to pass in the boolean
105      * for creating all-day events that is part of the extra data of the intent.
106      * This is used only for creating new events and is set to true if
107      * the default for the new event should be an all-day event.
108      */
109     public static final String EVENT_ALL_DAY = "allDay";
110
111     private static final int MAX_REMINDERS = 5;
112
113     private static final int MENU_GROUP_REMINDER = 1;
114     private static final int MENU_GROUP_SHOW_OPTIONS = 2;
115     private static final int MENU_GROUP_HIDE_OPTIONS = 3;
116
117     private static final int MENU_ADD_REMINDER = 1;
118     private static final int MENU_SHOW_EXTRA_OPTIONS = 2;
119     private static final int MENU_HIDE_EXTRA_OPTIONS = 3;
120
121     private static final String[] EVENT_PROJECTION = new String[] {
122             Events._ID,             // 0
123             Events.TITLE,           // 1
124             Events.DESCRIPTION,     // 2
125             Events.EVENT_LOCATION,  // 3
126             Events.ALL_DAY,         // 4
127             Events.HAS_ALARM,       // 5
128             Events.CALENDAR_ID,     // 6
129             Events.DTSTART,         // 7
130             Events.DURATION,        // 8
131             Events.EVENT_TIMEZONE,  // 9
132             Events.RRULE,           // 10
133             Events._SYNC_ID,        // 11
134             Events.TRANSPARENCY,    // 12
135             Events.VISIBILITY,      // 13
136             Events.OWNER_ACCOUNT,   // 14
137     };
138     private static final int EVENT_INDEX_ID = 0;
139     private static final int EVENT_INDEX_TITLE = 1;
140     private static final int EVENT_INDEX_DESCRIPTION = 2;
141     private static final int EVENT_INDEX_EVENT_LOCATION = 3;
142     private static final int EVENT_INDEX_ALL_DAY = 4;
143     private static final int EVENT_INDEX_HAS_ALARM = 5;
144     private static final int EVENT_INDEX_CALENDAR_ID = 6;
145     private static final int EVENT_INDEX_DTSTART = 7;
146     private static final int EVENT_INDEX_DURATION = 8;
147     private static final int EVENT_INDEX_TIMEZONE = 9;
148     private static final int EVENT_INDEX_RRULE = 10;
149     private static final int EVENT_INDEX_SYNC_ID = 11;
150     private static final int EVENT_INDEX_TRANSPARENCY = 12;
151     private static final int EVENT_INDEX_VISIBILITY = 13;
152     private static final int EVENT_INDEX_OWNER_ACCOUNT = 14;
153
154     private static final String[] CALENDARS_PROJECTION = new String[] {
155             Calendars._ID,           // 0
156             Calendars.DISPLAY_NAME,  // 1
157             Calendars.OWNER_ACCOUNT, // 2
158     };
159     private static final int CALENDARS_INDEX_DISPLAY_NAME = 1;
160     private static final int CALENDARS_INDEX_OWNER_ACCOUNT = 2;
161     private static final String CALENDARS_WHERE = Calendars.ACCESS_LEVEL + ">=" +
162             Calendars.CONTRIBUTOR_ACCESS + " AND " + Calendars.SYNC_EVENTS + "=1";
163
164     private static final String[] REMINDERS_PROJECTION = new String[] {
165             Reminders._ID,      // 0
166             Reminders.MINUTES,  // 1
167     };
168     private static final int REMINDERS_INDEX_MINUTES = 1;
169     private static final String REMINDERS_WHERE = Reminders.EVENT_ID + "=%d AND (" +
170             Reminders.METHOD + "=" + Reminders.METHOD_ALERT + " OR " + Reminders.METHOD + "=" +
171             Reminders.METHOD_DEFAULT + ")";
172
173     private static final String[] ATTENDEES_PROJECTION = new String[] {
174         Attendees.ATTENDEE_NAME,            // 0
175         Attendees.ATTENDEE_EMAIL,           // 1
176     };
177     private static final int ATTENDEES_INDEX_NAME = 0;
178     private static final int ATTENDEES_INDEX_EMAIL = 1;
179     private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=? AND "
180             + Attendees.ATTENDEE_RELATIONSHIP + "<>" + Attendees.RELATIONSHIP_ORGANIZER;
181
182     private static final int DOES_NOT_REPEAT = 0;
183     private static final int REPEATS_DAILY = 1;
184     private static final int REPEATS_EVERY_WEEKDAY = 2;
185     private static final int REPEATS_WEEKLY_ON_DAY = 3;
186     private static final int REPEATS_MONTHLY_ON_DAY_COUNT = 4;
187     private static final int REPEATS_MONTHLY_ON_DAY = 5;
188     private static final int REPEATS_YEARLY = 6;
189     private static final int REPEATS_CUSTOM = 7;
190
191     private static final int MODIFY_UNINITIALIZED = 0;
192     private static final int MODIFY_SELECTED = 1;
193     private static final int MODIFY_ALL = 2;
194     private static final int MODIFY_ALL_FOLLOWING = 3;
195
196     private static final int DAY_IN_SECONDS = 24 * 60 * 60;
197
198     private int mFirstDayOfWeek; // cached in onCreate
199     private Uri mUri;
200     private Cursor mEventCursor;
201     private Cursor mCalendarsCursor;
202
203     private Button mStartDateButton;
204     private Button mEndDateButton;
205     private Button mStartTimeButton;
206     private Button mEndTimeButton;
207     private Button mSaveButton;
208     private Button mDeleteButton;
209     private Button mDiscardButton;
210     private CheckBox mAllDayCheckBox;
211     private Spinner mCalendarsSpinner;
212     private Spinner mRepeatsSpinner;
213     private Spinner mAvailabilitySpinner;
214     private Spinner mVisibilitySpinner;
215     private TextView mTitleTextView;
216     private TextView mLocationTextView;
217     private TextView mDescriptionTextView;
218     private View mRemindersSeparator;
219     private LinearLayout mRemindersContainer;
220     private LinearLayout mExtraOptions;
221     private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>();
222     private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0);
223     private Rfc822Validator mEmailValidator;
224     private MultiAutoCompleteTextView mAttendeesList;
225     private EmailAddressAdapter mAddressAdapter;
226     private String mOriginalAttendees = "";
227
228     private EventRecurrence mEventRecurrence = new EventRecurrence();
229     private String mRrule;
230     private boolean mCalendarsQueryComplete;
231     private boolean mSaveAfterQueryComplete;
232     private ProgressDialog mLoadingCalendarsDialog;
233     private AlertDialog mNoCalendarsDialog;
234     private ContentValues mInitialValues;
235
236     /**
237      * If the repeating event is created on the phone and it hasn't been
238      * synced yet to the web server, then there is a bug where you can't
239      * delete or change an instance of the repeating event.  This case
240      * can be detected with mSyncId.  If mSyncId == null, then the repeating
241      * event has not been synced to the phone, in which case we won't allow
242      * the user to change one instance.
243      */
244     private String mSyncId;
245
246     private ArrayList<Integer> mRecurrenceIndexes = new ArrayList<Integer> (0);
247     private ArrayList<Integer> mReminderValues;
248     private ArrayList<String> mReminderLabels;
249
250     private Time mStartTime;
251     private Time mEndTime;
252     private int mModification = MODIFY_UNINITIALIZED;
253     private int mDefaultReminderMinutes;
254
255     private DeleteEventHelper mDeleteEventHelper;
256     private QueryHandler mQueryHandler;
257     private AccountManager mAccountManager;
258
259     /* This class is used to update the time buttons. */
260     private class TimeListener implements OnTimeSetListener {
261         private View mView;
262
263         public TimeListener(View view) {
264             mView = view;
265         }
266
267         public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
268             // Cache the member variables locally to avoid inner class overhead.
269             Time startTime = mStartTime;
270             Time endTime = mEndTime;
271
272             // Cache the start and end millis so that we limit the number
273             // of calls to normalize() and toMillis(), which are fairly
274             // expensive.
275             long startMillis;
276             long endMillis;
277             if (mView == mStartTimeButton) {
278                 // The start time was changed.
279                 int hourDuration = endTime.hour - startTime.hour;
280                 int minuteDuration = endTime.minute - startTime.minute;
281
282                 startTime.hour = hourOfDay;
283                 startTime.minute = minute;
284                 startMillis = startTime.normalize(true);
285
286                 // Also update the end time to keep the duration constant.
287                 endTime.hour = hourOfDay + hourDuration;
288                 endTime.minute = minute + minuteDuration;
289                 endMillis = endTime.normalize(true);
290             } else {
291                 // The end time was changed.
292                 startMillis = startTime.toMillis(true);
293                 endTime.hour = hourOfDay;
294                 endTime.minute = minute;
295                 endMillis = endTime.normalize(true);
296
297                 // Do not allow an event to have an end time before the start time.
298                 if (endTime.before(startTime)) {
299                     endTime.set(startTime);
300                     endMillis = startMillis;
301                 }
302             }
303
304             setDate(mEndDateButton, endMillis);
305             setTime(mStartTimeButton, startMillis);
306             setTime(mEndTimeButton, endMillis);
307         }
308     }
309
310     private class TimeClickListener implements View.OnClickListener {
311         private Time mTime;
312
313         public TimeClickListener(Time time) {
314             mTime = time;
315         }
316
317         public void onClick(View v) {
318             new TimePickerDialog(EditEvent.this, new TimeListener(v),
319                     mTime.hour, mTime.minute,
320                     DateFormat.is24HourFormat(EditEvent.this)).show();
321         }
322     }
323
324     private class DateListener implements OnDateSetListener {
325         View mView;
326
327         public DateListener(View view) {
328             mView = view;
329         }
330
331         public void onDateSet(DatePicker view, int year, int month, int monthDay) {
332             // Cache the member variables locally to avoid inner class overhead.
333             Time startTime = mStartTime;
334             Time endTime = mEndTime;
335
336             // Cache the start and end millis so that we limit the number
337             // of calls to normalize() and toMillis(), which are fairly
338             // expensive.
339             long startMillis;
340             long endMillis;
341             if (mView == mStartDateButton) {
342                 // The start date was changed.
343                 int yearDuration = endTime.year - startTime.year;
344                 int monthDuration = endTime.month - startTime.month;
345                 int monthDayDuration = endTime.monthDay - startTime.monthDay;
346
347                 startTime.year = year;
348                 startTime.month = month;
349                 startTime.monthDay = monthDay;
350                 startMillis = startTime.normalize(true);
351
352                 // Also update the end date to keep the duration constant.
353                 endTime.year = year + yearDuration;
354                 endTime.month = month + monthDuration;
355                 endTime.monthDay = monthDay + monthDayDuration;
356                 endMillis = endTime.normalize(true);
357
358                 // If the start date has changed then update the repeats.
359                 populateRepeats();
360             } else {
361                 // The end date was changed.
362                 startMillis = startTime.toMillis(true);
363                 endTime.year = year;
364                 endTime.month = month;
365                 endTime.monthDay = monthDay;
366                 endMillis = endTime.normalize(true);
367
368                 // Do not allow an event to have an end time before the start time.
369                 if (endTime.before(startTime)) {
370                     endTime.set(startTime);
371                     endMillis = startMillis;
372                 }
373             }
374
375             setDate(mStartDateButton, startMillis);
376             setDate(mEndDateButton, endMillis);
377             setTime(mEndTimeButton, endMillis); // In case end time had to be reset
378         }
379     }
380
381     private class DateClickListener implements View.OnClickListener {
382         private Time mTime;
383
384         public DateClickListener(Time time) {
385             mTime = time;
386         }
387
388         public void onClick(View v) {
389             new DatePickerDialog(EditEvent.this, new DateListener(v), mTime.year,
390                     mTime.month, mTime.monthDay).show();
391         }
392     }
393
394     static private class CalendarsAdapter extends ResourceCursorAdapter {
395         public CalendarsAdapter(Context context, Cursor c) {
396             super(context, R.layout.calendars_item, c);
397             setDropDownViewResource(R.layout.calendars_dropdown_item);
398         }
399
400         @Override
401         public void bindView(View view, Context context, Cursor cursor) {
402             TextView name = (TextView) view.findViewById(R.id.calendar_name);
403             name.setText(cursor.getString(CALENDARS_INDEX_DISPLAY_NAME));
404         }
405     }
406
407     // This is called if the user clicks on one of the buttons: "Save",
408     // "Discard", or "Delete".  This is also called if the user clicks
409     // on the "remove reminder" button.
410     public void onClick(View v) {
411         if (v == mSaveButton) {
412             if (save()) {
413                 finish();
414             }
415             return;
416         }
417
418         if (v == mDeleteButton) {
419             long begin = mStartTime.toMillis(false /* use isDst */);
420             long end = mEndTime.toMillis(false /* use isDst */);
421             int which = -1;
422             switch (mModification) {
423             case MODIFY_SELECTED:
424                 which = DeleteEventHelper.DELETE_SELECTED;
425                 break;
426             case MODIFY_ALL_FOLLOWING:
427                 which = DeleteEventHelper.DELETE_ALL_FOLLOWING;
428                 break;
429             case MODIFY_ALL:
430                 which = DeleteEventHelper.DELETE_ALL;
431                 break;
432             }
433             mDeleteEventHelper.delete(begin, end, mEventCursor, which);
434             return;
435         }
436
437         if (v == mDiscardButton) {
438             finish();
439             return;
440         }
441
442         // This must be a click on one of the "remove reminder" buttons
443         LinearLayout reminderItem = (LinearLayout) v.getParent();
444         LinearLayout parent = (LinearLayout) reminderItem.getParent();
445         parent.removeView(reminderItem);
446         mReminderItems.remove(reminderItem);
447         updateRemindersVisibility();
448     }
449
450     // This is called if the user cancels a popup dialog.  There are two
451     // dialogs: the "Loading calendars" dialog, and the "No calendars"
452     // dialog.  The "Loading calendars" dialog is shown if there is a delay
453     // in loading the calendars (needed when creating an event) and the user
454     // tries to save the event before the calendars have finished loading.
455     // The "No calendars" dialog is shown if there are no syncable calendars.
456     public void onCancel(DialogInterface dialog) {
457         if (dialog == mLoadingCalendarsDialog) {
458             mSaveAfterQueryComplete = false;
459         } else if (dialog == mNoCalendarsDialog) {
460             finish();
461         }
462     }
463
464     // This is called if the user clicks on a dialog button.
465     public void onClick(DialogInterface dialog, int which) {
466         if (dialog == mNoCalendarsDialog) {
467             finish();
468         }
469     }
470
471     private class QueryHandler extends AsyncQueryHandler {
472         public QueryHandler(ContentResolver cr) {
473             super(cr);
474         }
475
476         @Override
477         protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
478             // If the Activity is finishing, then close the cursor.
479             // Otherwise, use the new cursor in the adapter.
480             if (isFinishing()) {
481                 stopManagingCursor(cursor);
482                 cursor.close();
483             } else {
484                 mCalendarsCursor = cursor;
485                 startManagingCursor(cursor);
486
487                 // Stop the spinner
488                 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
489                         Window.PROGRESS_VISIBILITY_OFF);
490
491                 // If there are no syncable calendars, then we cannot allow
492                 // creating a new event.
493                 if (cursor.getCount() == 0) {
494                     // Cancel the "loading calendars" dialog if it exists
495                     if (mSaveAfterQueryComplete) {
496                         mLoadingCalendarsDialog.cancel();
497                     }
498
499                     // Create an error message for the user that, when clicked,
500                     // will exit this activity without saving the event.
501                     AlertDialog.Builder builder = new AlertDialog.Builder(EditEvent.this);
502                     builder.setTitle(R.string.no_syncable_calendars)
503                         .setIcon(android.R.drawable.ic_dialog_alert)
504                         .setMessage(R.string.no_calendars_found)
505                         .setPositiveButton(android.R.string.ok, EditEvent.this)
506                         .setOnCancelListener(EditEvent.this);
507                     mNoCalendarsDialog = builder.show();
508                     return;
509                 }
510
511                 int primaryCalendarPosition = findPrimaryCalendarPosition();
512
513                 // populate the calendars spinner
514                 CalendarsAdapter adapter = new CalendarsAdapter(EditEvent.this, mCalendarsCursor);
515                 mCalendarsSpinner.setAdapter(adapter);
516                 mCalendarsSpinner.setSelection(primaryCalendarPosition);
517                 mCalendarsQueryComplete = true;
518                 if (mSaveAfterQueryComplete) {
519                     mLoadingCalendarsDialog.cancel();
520                     save();
521                     finish();
522                 }
523
524                 // Find user domain and set it to the validator.
525                 // TODO: we may want to update this validator if the user actually picks
526                 // a different calendar.  maybe not.  depends on what we want for the
527                 // user experience.  this may change when we add support for multiple
528                 // accounts, anyway.
529                 if (cursor.moveToPosition(primaryCalendarPosition)) {
530                     String ownEmail = cursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
531                     if (ownEmail != null) {
532                         String domain = extractDomain(ownEmail);
533                         if (domain != null) {
534                             mEmailValidator = new Rfc822Validator(domain);
535                             mAttendeesList.setValidator(mEmailValidator);
536                         }
537                     }
538                 }
539             }
540         }
541
542         // Find the calendar position in the cursor that matches the signed-in
543         // account
544         private int findPrimaryCalendarPosition() {
545             int primaryCalendarPosition = -1;
546             try {
547                 Account[] accounts = mAccountManager.getAccountsByTypeAndFeatures(
548                         GoogleLoginServiceConstants.ACCOUNT_TYPE, new String[] {
549                             GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE
550                         }, null, null).getResult();
551                 if (accounts.length > 0) {
552                     for (int i = 0; i < accounts.length && primaryCalendarPosition == -1; ++i) {
553                         String name = accounts[i].name;
554                         if (name == null) {
555                             continue;
556                         }
557
558                         int position = 0;
559                         mCalendarsCursor.moveToPosition(-1);
560                         while (mCalendarsCursor.moveToNext()) {
561                             if (name.equals(mCalendarsCursor
562                                     .getString(CALENDARS_INDEX_OWNER_ACCOUNT))) {
563                                 primaryCalendarPosition = position;
564                                 break;
565                             }
566                             position++;
567                         }
568                     }
569                 }
570             } catch (OperationCanceledException e) {
571                 Log.w(TAG, "Ignoring unexpected exception", e);
572             } catch (IOException e) {
573                 Log.w(TAG, "Ignoring unexpected exception", e);
574             } catch (AuthenticatorException e) {
575                 Log.w(TAG, "Ignoring unexpected exception", e);
576             } finally {
577                 if (primaryCalendarPosition != -1) {
578                     return primaryCalendarPosition;
579                 } else {
580                     return 0;
581                 }
582             }
583         }
584     }
585
586     private static String extractDomain(String email) {
587         int separator = email.lastIndexOf('@');
588         if (separator != -1 && ++separator < email.length()) {
589             return email.substring(separator);
590         }
591         return null;
592     }
593
594     @Override
595     protected void onCreate(Bundle icicle) {
596         super.onCreate(icicle);
597         requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
598         setContentView(R.layout.edit_event);
599         mAccountManager = AccountManager.get(this);
600
601         boolean newEvent = false;
602
603         mFirstDayOfWeek = Calendar.getInstance().getFirstDayOfWeek();
604
605         mStartTime = new Time();
606         mEndTime = new Time();
607
608         Intent intent = getIntent();
609         mUri = intent.getData();
610
611         if (mUri != null) {
612             mEventCursor = managedQuery(mUri, EVENT_PROJECTION, null, null);
613             if (mEventCursor == null || mEventCursor.getCount() == 0) {
614                 // The cursor is empty. This can happen if the event was deleted.
615                 finish();
616                 return;
617             }
618         }
619
620         long begin = intent.getLongExtra(EVENT_BEGIN_TIME, 0);
621         long end = intent.getLongExtra(EVENT_END_TIME, 0);
622
623         String domain = "gmail.com";
624
625         boolean allDay = false;
626         if (mEventCursor != null) {
627             // The event already exists so fetch the all-day status
628             mEventCursor.moveToFirst();
629             allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
630             String rrule = mEventCursor.getString(EVENT_INDEX_RRULE);
631             String timezone = mEventCursor.getString(EVENT_INDEX_TIMEZONE);
632             long calendarId = mEventCursor.getInt(EVENT_INDEX_CALENDAR_ID);
633             String ownerAccount = mEventCursor.getString(EVENT_INDEX_OWNER_ACCOUNT);
634             if (!TextUtils.isEmpty(ownerAccount)) {
635                 String ownerDomain = extractDomain(ownerAccount);
636                 if (ownerDomain != null) {
637                     domain = ownerDomain;
638                 }
639             }
640
641             // Remember the initial values
642             mInitialValues = new ContentValues();
643             mInitialValues.put(EVENT_BEGIN_TIME, begin);
644             mInitialValues.put(EVENT_END_TIME, end);
645             mInitialValues.put(Events.ALL_DAY, allDay ? 1 : 0);
646             mInitialValues.put(Events.RRULE, rrule);
647             mInitialValues.put(Events.EVENT_TIMEZONE, timezone);
648             mInitialValues.put(Events.CALENDAR_ID, calendarId);
649         } else {
650             newEvent = true;
651             // We are creating a new event, so set the default from the
652             // intent (if specified).
653             allDay = intent.getBooleanExtra(EVENT_ALL_DAY, false);
654
655             // Start the spinner
656             getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
657                     Window.PROGRESS_VISIBILITY_ON);
658
659             // Start a query in the background to read the list of calendars
660             mQueryHandler = new QueryHandler(getContentResolver());
661             mQueryHandler.startQuery(0, null, Calendars.CONTENT_URI, CALENDARS_PROJECTION,
662                     CALENDARS_WHERE, null /* selection args */, null /* sort order */);
663         }
664
665         // If the event is all-day, read the times in UTC timezone
666         if (begin != 0) {
667             if (allDay) {
668                 String tz = mStartTime.timezone;
669                 mStartTime.timezone = Time.TIMEZONE_UTC;
670                 mStartTime.set(begin);
671                 mStartTime.timezone = tz;
672
673                 // Calling normalize to calculate isDst
674                 mStartTime.normalize(true);
675             } else {
676                 mStartTime.set(begin);
677             }
678         }
679
680         if (end != 0) {
681             if (allDay) {
682                 String tz = mStartTime.timezone;
683                 mEndTime.timezone = Time.TIMEZONE_UTC;
684                 mEndTime.set(end);
685                 mEndTime.timezone = tz;
686
687                 // Calling normalize to calculate isDst
688                 mEndTime.normalize(true);
689             } else {
690                 mEndTime.set(end);
691             }
692         }
693
694         // cache all the widgets
695         mTitleTextView = (TextView) findViewById(R.id.title);
696         mLocationTextView = (TextView) findViewById(R.id.location);
697         mDescriptionTextView = (TextView) findViewById(R.id.description);
698         mStartDateButton = (Button) findViewById(R.id.start_date);
699         mEndDateButton = (Button) findViewById(R.id.end_date);
700         mStartTimeButton = (Button) findViewById(R.id.start_time);
701         mEndTimeButton = (Button) findViewById(R.id.end_time);
702         mAllDayCheckBox = (CheckBox) findViewById(R.id.is_all_day);
703         mCalendarsSpinner = (Spinner) findViewById(R.id.calendars);
704         mRepeatsSpinner = (Spinner) findViewById(R.id.repeats);
705         mAvailabilitySpinner = (Spinner) findViewById(R.id.availability);
706         mVisibilitySpinner = (Spinner) findViewById(R.id.visibility);
707         mRemindersSeparator = findViewById(R.id.reminders_separator);
708         mRemindersContainer = (LinearLayout) findViewById(R.id.reminder_items_container);
709         mExtraOptions = (LinearLayout) findViewById(R.id.extra_options_container);
710
711         mAddressAdapter = new EmailAddressAdapter(this);
712         mEmailValidator = new Rfc822Validator(domain);
713         mAttendeesList = initMultiAutoCompleteTextView(R.id.attendees);
714
715         mAllDayCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
716             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
717                 if (isChecked) {
718                     if (mEndTime.hour == 0 && mEndTime.minute == 0) {
719                         mEndTime.monthDay--;
720                         long endMillis = mEndTime.normalize(true);
721
722                         // Do not allow an event to have an end time before the start time.
723                         if (mEndTime.before(mStartTime)) {
724                             mEndTime.set(mStartTime);
725                             endMillis = mEndTime.normalize(true);
726                         }
727                         setDate(mEndDateButton, endMillis);
728                         setTime(mEndTimeButton, endMillis);
729                     }
730
731                     mStartTimeButton.setVisibility(View.GONE);
732                     mEndTimeButton.setVisibility(View.GONE);
733                 } else {
734                     if (mEndTime.hour == 0 && mEndTime.minute == 0) {
735                         mEndTime.monthDay++;
736                         long endMillis = mEndTime.normalize(true);
737                         setDate(mEndDateButton, endMillis);
738                         setTime(mEndTimeButton, endMillis);
739                     }
740
741                     mStartTimeButton.setVisibility(View.VISIBLE);
742                     mEndTimeButton.setVisibility(View.VISIBLE);
743                 }
744             }
745         });
746
747         if (allDay) {
748             mAllDayCheckBox.setChecked(true);
749         } else {
750             mAllDayCheckBox.setChecked(false);
751         }
752
753         mSaveButton = (Button) findViewById(R.id.save);
754         mSaveButton.setOnClickListener(this);
755
756         mDeleteButton = (Button) findViewById(R.id.delete);
757         mDeleteButton.setOnClickListener(this);
758
759         mDiscardButton = (Button) findViewById(R.id.discard);
760         mDiscardButton.setOnClickListener(this);
761
762         // Initialize the reminder values array.
763         Resources r = getResources();
764         String[] strings = r.getStringArray(R.array.reminder_minutes_values);
765         int size = strings.length;
766         ArrayList<Integer> list = new ArrayList<Integer>(size);
767         for (int i = 0 ; i < size ; i++) {
768             list.add(Integer.parseInt(strings[i]));
769         }
770         mReminderValues = list;
771         String[] labels = r.getStringArray(R.array.reminder_minutes_labels);
772         mReminderLabels = new ArrayList<String>(Arrays.asList(labels));
773
774         SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
775         String durationString =
776                 prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0");
777         mDefaultReminderMinutes = Integer.parseInt(durationString);
778
779         if (newEvent && mDefaultReminderMinutes != 0) {
780             addReminder(this, this, mReminderItems, mReminderValues,
781                     mReminderLabels, mDefaultReminderMinutes);
782         }
783
784         long eventId = (mEventCursor == null) ? -1 : mEventCursor.getLong(EVENT_INDEX_ID);
785         ContentResolver cr = getContentResolver();
786
787         // Reminders cursor
788         boolean hasAlarm = (mEventCursor != null)
789                 && (mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0);
790         if (hasAlarm) {
791             Uri uri = Reminders.CONTENT_URI;
792             String where = String.format(REMINDERS_WHERE, eventId);
793             Cursor reminderCursor = cr.query(uri, REMINDERS_PROJECTION, where, null, null);
794             try {
795                 // First pass: collect all the custom reminder minutes (e.g.,
796                 // a reminder of 8 minutes) into a global list.
797                 while (reminderCursor.moveToNext()) {
798                     int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
799                     EditEvent.addMinutesToList(this, mReminderValues, mReminderLabels, minutes);
800                 }
801
802                 // Second pass: create the reminder spinners
803                 reminderCursor.moveToPosition(-1);
804                 while (reminderCursor.moveToNext()) {
805                     int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
806                     mOriginalMinutes.add(minutes);
807                     EditEvent.addReminder(this, this, mReminderItems, mReminderValues,
808                             mReminderLabels, minutes);
809                 }
810             } finally {
811                 reminderCursor.close();
812             }
813         }
814         updateRemindersVisibility();
815
816         // Setup the + Add Reminder Button
817         View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
818             public void onClick(View v) {
819                 addReminder();
820             }
821         };
822         ImageButton reminderRemoveButton = (ImageButton) findViewById(R.id.reminder_add);
823         reminderRemoveButton.setOnClickListener(addReminderOnClickListener);
824
825         mDeleteEventHelper = new DeleteEventHelper(this, true /* exit when done */);
826
827        // Attendees cursor
828         if (eventId != -1) {
829             Uri uri = Attendees.CONTENT_URI;
830             String[] whereArgs = {Long.toString(eventId)};
831             Cursor attendeeCursor = cr.query(uri, ATTENDEES_PROJECTION, ATTENDEES_WHERE, whereArgs,
832                     null);
833             try {
834                 StringBuilder b = new StringBuilder();
835                 while (attendeeCursor.moveToNext()) {
836                     String name = attendeeCursor.getString(ATTENDEES_INDEX_NAME);
837                     String email = attendeeCursor.getString(ATTENDEES_INDEX_EMAIL);
838                     if (email != null) {
839                         if (name != null && name.length() > 0 && !name.equals(email)) {
840                             b.append('"').append(name).append("\" ");
841                         }
842                         b.append('<').append(email).append(">, ");
843                     }
844                 }
845                 if (b.length() > 0) {
846                     mOriginalAttendees = b.toString();
847                     mAttendeesList.setText(mOriginalAttendees);
848                 }
849             } finally {
850                 attendeeCursor.close();
851             }
852         }
853         if (mEventCursor == null) {
854             // Allow the intent to specify the fields in the event.
855             // This will allow other apps to create events easily.
856             initFromIntent(intent);
857         }
858     }
859
860     private ArrayList<Rfc822Token> getAddressesFromList(MultiAutoCompleteTextView list) {
861         list.clearComposingText();
862         Rfc822Token[] addresses = Rfc822Tokenizer.tokenize(list.getText());
863         if (addresses == null) {
864             return new ArrayList<Rfc822Token>();
865         }
866
867         // validate the emails, out of paranoia.  they should already be
868         // validated on input, but drop any invalid emails just to be safe.
869         ArrayList<Rfc822Token> validatedAddresses = new ArrayList<Rfc822Token>(addresses.length);
870         for (Rfc822Token address : addresses) {
871             if (mEmailValidator.isValid(address.getAddress())) {
872                 validatedAddresses.add(address);
873             } else {
874                 Log.w(TAG, "Dropping invalid attendee email address: " + address);
875             }
876         }
877         return validatedAddresses;
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         if (eventIdIndex != -1 || uri != null) {
1559             Editable attendeesText = mAttendeesList.getText();
1560             // Hit the content provider only if the user has changed it
1561             if (!mOriginalAttendees.equals(attendeesText.toString())) {
1562                 // TODO we could do a diff and modify the rows only as needed
1563                 // Delete all the existing attendees for this event
1564                 b = ContentProviderOperation.newDelete(Attendees.CONTENT_URI);
1565
1566                 long eventId = -1;
1567                 if (eventIdIndex == -1) {
1568                     eventId = ContentUris.parseId(uri);
1569                     String[] args = new String[] {
1570                         Long.toString(eventId)
1571                     };
1572                     b.withSelection(ATTENDEES_WHERE, args);
1573                 } else {
1574                     // Delete all the existing reminders for this event
1575                     b.withSelection(ATTENDEES_WHERE, new String[1]);
1576                     b.withSelectionBackReference(0, eventIdIndex);
1577                 }
1578                 ops.add(b.build());
1579
1580                 if (attendeesText.length() > 0) {
1581                     ArrayList<Rfc822Token> attendees = getAddressesFromList(mAttendeesList);
1582                     // Insert the attendees
1583                     for (Rfc822Token attendee : attendees) {
1584                         values.clear();
1585                         values.put(Attendees.ATTENDEE_NAME, attendee.getName());
1586                         values.put(Attendees.ATTENDEE_EMAIL, attendee.getAddress());
1587                         values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE);
1588                         values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);
1589                         values.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_NONE);
1590
1591                         if (eventIdIndex != -1) {
1592                             b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
1593                                     .withValues(values);
1594                             b.withValueBackReference(Reminders.EVENT_ID, eventIdIndex);
1595                         } else {
1596                             values.put(Attendees.EVENT_ID, eventId);
1597                             b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
1598                                     .withValues(values);
1599                         }
1600                         ops.add(b.build());
1601                     }
1602                 }
1603             }
1604         }
1605
1606         try {
1607             // TODO Move this to background thread
1608             ContentProviderResult[] results =
1609                 getContentResolver().applyBatch(android.provider.Calendar.AUTHORITY, ops);
1610             if (DEBUG) {
1611                 for (int i = 0; i < results.length; i++) {
1612                     Log.v(TAG, "results = " + results[i].toString());
1613                 }
1614             }
1615         } catch (RemoteException e) {
1616             Log.w(TAG, "Ignoring unexpected remote exception", e);
1617         } catch (OperationApplicationException e) {
1618             Log.w(TAG, "Ignoring unexpected exception", e);
1619         }
1620
1621         return true;
1622     }
1623
1624     private boolean isFirstEventInSeries() {
1625         int dtStart = mEventCursor.getColumnIndexOrThrow(Events.DTSTART);
1626         long start = mEventCursor.getLong(dtStart);
1627         return start == mStartTime.toMillis(true);
1628     }
1629
1630     private void updatePastEvents(ArrayList<ContentProviderOperation> ops, Uri uri) {
1631         long oldStartMillis = mEventCursor.getLong(EVENT_INDEX_DTSTART);
1632         String oldDuration = mEventCursor.getString(EVENT_INDEX_DURATION);
1633         boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
1634         String oldRrule = mEventCursor.getString(EVENT_INDEX_RRULE);
1635         mEventRecurrence.parse(oldRrule);
1636
1637         Time untilTime = new Time();
1638         long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
1639         ContentValues oldValues = new ContentValues();
1640
1641         // The "until" time must be in UTC time in order for Google calendar
1642         // to display it properly.  For all-day events, the "until" time string
1643         // must include just the date field, and not the time field.  The
1644         // repeating events repeat up to and including the "until" time.
1645         untilTime.timezone = Time.TIMEZONE_UTC;
1646
1647         // Subtract one second from the old begin time to get the new
1648         // "until" time.
1649         untilTime.set(begin - 1000);  // subtract one second (1000 millis)
1650         if (allDay) {
1651             untilTime.hour = 0;
1652             untilTime.minute = 0;
1653             untilTime.second = 0;
1654             untilTime.allDay = true;
1655             untilTime.normalize(false);
1656
1657             // For all-day events, the duration must be in days, not seconds.
1658             // Otherwise, Google Calendar will (mistakenly) change this event
1659             // into a non-all-day event.
1660             int len = oldDuration.length();
1661             if (oldDuration.charAt(0) == 'P' && oldDuration.charAt(len - 1) == 'S') {
1662                 int seconds = Integer.parseInt(oldDuration.substring(1, len - 1));
1663                 int days = (seconds + DAY_IN_SECONDS - 1) / DAY_IN_SECONDS;
1664                 oldDuration = "P" + days + "D";
1665             }
1666         }
1667         mEventRecurrence.until = untilTime.format2445();
1668
1669         oldValues.put(Events.DTSTART, oldStartMillis);
1670         oldValues.put(Events.DURATION, oldDuration);
1671         oldValues.put(Events.RRULE, mEventRecurrence.toString());
1672         Builder b = ContentProviderOperation.newUpdate(uri).withValues(oldValues);
1673         ops.add(b.build());
1674     }
1675
1676     private void checkTimeDependentFields(ContentValues values) {
1677         long oldBegin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
1678         long oldEnd = mInitialValues.getAsLong(EVENT_END_TIME);
1679         boolean oldAllDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0;
1680         String oldRrule = mInitialValues.getAsString(Events.RRULE);
1681         String oldTimezone = mInitialValues.getAsString(Events.EVENT_TIMEZONE);
1682
1683         long newBegin = values.getAsLong(Events.DTSTART);
1684         long newEnd = values.getAsLong(Events.DTEND);
1685         boolean newAllDay = values.getAsInteger(Events.ALL_DAY) != 0;
1686         String newRrule = values.getAsString(Events.RRULE);
1687         String newTimezone = values.getAsString(Events.EVENT_TIMEZONE);
1688
1689         // If none of the time-dependent fields changed, then remove them.
1690         if (oldBegin == newBegin && oldEnd == newEnd && oldAllDay == newAllDay
1691                 && TextUtils.equals(oldRrule, newRrule)
1692                 && TextUtils.equals(oldTimezone, newTimezone)) {
1693             values.remove(Events.DTSTART);
1694             values.remove(Events.DTEND);
1695             values.remove(Events.DURATION);
1696             values.remove(Events.ALL_DAY);
1697             values.remove(Events.RRULE);
1698             values.remove(Events.EVENT_TIMEZONE);
1699             return;
1700         }
1701
1702         if (oldRrule == null || newRrule == null) {
1703             return;
1704         }
1705
1706         // If we are modifying all events then we need to set DTSTART to the
1707         // start time of the first event in the series, not the current
1708         // date and time.  If the start time of the event was changed
1709         // (from, say, 3pm to 4pm), then we want to add the time difference
1710         // to the start time of the first event in the series (the DTSTART
1711         // value).  If we are modifying one instance or all following instances,
1712         // then we leave the DTSTART field alone.
1713         if (mModification == MODIFY_ALL) {
1714             long oldStartMillis = mEventCursor.getLong(EVENT_INDEX_DTSTART);
1715             if (oldBegin != newBegin) {
1716                 // The user changed the start time of this event
1717                 long offset = newBegin - oldBegin;
1718                 oldStartMillis += offset;
1719             }
1720             values.put(Events.DTSTART, oldStartMillis);
1721         }
1722     }
1723
1724     static ArrayList<Integer> reminderItemsToMinutes(ArrayList<LinearLayout> reminderItems,
1725             ArrayList<Integer> reminderValues) {
1726         int len = reminderItems.size();
1727         ArrayList<Integer> reminderMinutes = new ArrayList<Integer>(len);
1728         for (int index = 0; index < len; index++) {
1729             LinearLayout layout = reminderItems.get(index);
1730             Spinner spinner = (Spinner) layout.findViewById(R.id.reminder_value);
1731             int minutes = reminderValues.get(spinner.getSelectedItemPosition());
1732             reminderMinutes.add(minutes);
1733         }
1734         return reminderMinutes;
1735     }
1736
1737     /**
1738      * Saves the reminders, if they changed.  Returns true if the database
1739      * was updated.
1740      *
1741      * @param ops the array of ContentProviderOperations
1742      * @param eventId the id of the event whose reminders are being updated
1743      * @param reminderMinutes the array of reminders set by the user
1744      * @param originalMinutes the original array of reminders
1745      * @param forceSave if true, then save the reminders even if they didn't
1746      *   change
1747      * @return true if the database was updated
1748      */
1749     static boolean saveReminders(ArrayList<ContentProviderOperation> ops, long eventId,
1750             ArrayList<Integer> reminderMinutes, ArrayList<Integer> originalMinutes,
1751             boolean forceSave) {
1752         // If the reminders have not changed, then don't update the database
1753         if (reminderMinutes.equals(originalMinutes) && !forceSave) {
1754             return false;
1755         }
1756
1757         // Delete all the existing reminders for this event
1758         String where = Reminders.EVENT_ID + "=?";
1759         String[] args = new String[] { Long.toString(eventId) };
1760         Builder b = ContentProviderOperation.newDelete(Reminders.CONTENT_URI);
1761         b.withSelection(where, args);
1762         ops.add(b.build());
1763
1764         ContentValues values = new ContentValues();
1765         int len = reminderMinutes.size();
1766
1767         // Insert the new reminders, if any
1768         for (int i = 0; i < len; i++) {
1769             int minutes = reminderMinutes.get(i);
1770
1771             values.clear();
1772             values.put(Reminders.MINUTES, minutes);
1773             values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
1774             values.put(Reminders.EVENT_ID, eventId);
1775             b = ContentProviderOperation.newInsert(Reminders.CONTENT_URI).withValues(values);
1776             ops.add(b.build());
1777         }
1778         return true;
1779     }
1780
1781     static boolean saveRemindersWithBackRef(ArrayList<ContentProviderOperation> ops,
1782             int eventIdIndex, ArrayList<Integer> reminderMinutes,
1783             ArrayList<Integer> originalMinutes, boolean forceSave) {
1784         // If the reminders have not changed, then don't update the database
1785         if (reminderMinutes.equals(originalMinutes) && !forceSave) {
1786             return false;
1787         }
1788
1789         // Delete all the existing reminders for this event
1790         Builder b = ContentProviderOperation.newDelete(Reminders.CONTENT_URI);
1791         b.withSelection(Reminders.EVENT_ID + "=?", new String[1]);
1792         b.withSelectionBackReference(0, eventIdIndex);
1793         ops.add(b.build());
1794
1795         ContentValues values = new ContentValues();
1796         int len = reminderMinutes.size();
1797
1798         // Insert the new reminders, if any
1799         for (int i = 0; i < len; i++) {
1800             int minutes = reminderMinutes.get(i);
1801
1802             values.clear();
1803             values.put(Reminders.MINUTES, minutes);
1804             values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
1805             b = ContentProviderOperation.newInsert(Reminders.CONTENT_URI).withValues(values);
1806             b.withValueBackReference(Reminders.EVENT_ID, eventIdIndex);
1807             ops.add(b.build());
1808         }
1809         return true;
1810     }
1811
1812     private void addRecurrenceRule(ContentValues values) {
1813         updateRecurrenceRule();
1814
1815         if (mRrule == null) {
1816             return;
1817         }
1818
1819         values.put(Events.RRULE, mRrule);
1820         long end = mEndTime.toMillis(true /* ignore dst */);
1821         long start = mStartTime.toMillis(true /* ignore dst */);
1822         String duration;
1823
1824         boolean isAllDay = mAllDayCheckBox.isChecked();
1825         if (isAllDay) {
1826             long days = (end - start + DateUtils.DAY_IN_MILLIS - 1) / DateUtils.DAY_IN_MILLIS;
1827             duration = "P" + days + "D";
1828         } else {
1829             long seconds = (end - start) / DateUtils.SECOND_IN_MILLIS;
1830             duration = "P" + seconds + "S";
1831         }
1832         values.put(Events.DURATION, duration);
1833     }
1834
1835     private void updateRecurrenceRule() {
1836         int position = mRepeatsSpinner.getSelectedItemPosition();
1837         int selection = mRecurrenceIndexes.get(position);
1838
1839         if (selection == DOES_NOT_REPEAT) {
1840             mRrule = null;
1841             return;
1842         } else if (selection == REPEATS_CUSTOM) {
1843             // Keep custom recurrence as before.
1844             return;
1845         } else if (selection == REPEATS_DAILY) {
1846             mEventRecurrence.freq = EventRecurrence.DAILY;
1847         } else if (selection == REPEATS_EVERY_WEEKDAY) {
1848             mEventRecurrence.freq = EventRecurrence.WEEKLY;
1849             int dayCount = 5;
1850             int[] byday = new int[dayCount];
1851             int[] bydayNum = new int[dayCount];
1852
1853             byday[0] = EventRecurrence.MO;
1854             byday[1] = EventRecurrence.TU;
1855             byday[2] = EventRecurrence.WE;
1856             byday[3] = EventRecurrence.TH;
1857             byday[4] = EventRecurrence.FR;
1858             for (int day = 0; day < dayCount; day++) {
1859                 bydayNum[day] = 0;
1860             }
1861
1862             mEventRecurrence.byday = byday;
1863             mEventRecurrence.bydayNum = bydayNum;
1864             mEventRecurrence.bydayCount = dayCount;
1865         } else if (selection == REPEATS_WEEKLY_ON_DAY) {
1866             mEventRecurrence.freq = EventRecurrence.WEEKLY;
1867             int[] days = new int[1];
1868             int dayCount = 1;
1869             int[] dayNum = new int[dayCount];
1870
1871             days[0] = EventRecurrence.timeDay2Day(mStartTime.weekDay);
1872             // not sure why this needs to be zero, but set it for now.
1873             dayNum[0] = 0;
1874
1875             mEventRecurrence.byday = days;
1876             mEventRecurrence.bydayNum = dayNum;
1877             mEventRecurrence.bydayCount = dayCount;
1878         } else if (selection == REPEATS_MONTHLY_ON_DAY) {
1879             mEventRecurrence.freq = EventRecurrence.MONTHLY;
1880             mEventRecurrence.bydayCount = 0;
1881             mEventRecurrence.bymonthdayCount = 1;
1882             int[] bymonthday = new int[1];
1883             bymonthday[0] = mStartTime.monthDay;
1884             mEventRecurrence.bymonthday = bymonthday;
1885         } else if (selection == REPEATS_MONTHLY_ON_DAY_COUNT) {
1886             mEventRecurrence.freq = EventRecurrence.MONTHLY;
1887             mEventRecurrence.bydayCount = 1;
1888             mEventRecurrence.bymonthdayCount = 0;
1889
1890             int[] byday = new int[1];
1891             int[] bydayNum = new int[1];
1892             // Compute the week number (for example, the "2nd" Monday)
1893             int dayCount = 1 + ((mStartTime.monthDay - 1) / 7);
1894             if (dayCount == 5) {
1895                 dayCount = -1;
1896             }
1897             bydayNum[0] = dayCount;
1898             byday[0] = EventRecurrence.timeDay2Day(mStartTime.weekDay);
1899             mEventRecurrence.byday = byday;
1900             mEventRecurrence.bydayNum = bydayNum;
1901         } else if (selection == REPEATS_YEARLY) {
1902             mEventRecurrence.freq = EventRecurrence.YEARLY;
1903         }
1904
1905         // Set the week start day.
1906         mEventRecurrence.wkst = EventRecurrence.calendarDay2Day(mFirstDayOfWeek);
1907         mRrule = mEventRecurrence.toString();
1908     }
1909
1910     private ContentValues getContentValuesFromUi() {
1911         String title = mTitleTextView.getText().toString();
1912         boolean isAllDay = mAllDayCheckBox.isChecked();
1913         String location = mLocationTextView.getText().toString();
1914         String description = mDescriptionTextView.getText().toString();
1915
1916         ContentValues values = new ContentValues();
1917
1918         String timezone = null;
1919         long startMillis;
1920         long endMillis;
1921         long calendarId;
1922         if (isAllDay) {
1923             // Reset start and end time, increment the monthDay by 1, and set
1924             // the timezone to UTC, as required for all-day events.
1925             timezone = Time.TIMEZONE_UTC;
1926             mStartTime.hour = 0;
1927             mStartTime.minute = 0;
1928             mStartTime.second = 0;
1929             mStartTime.timezone = timezone;
1930             startMillis = mStartTime.normalize(true);
1931
1932             mEndTime.hour = 0;
1933             mEndTime.minute = 0;
1934             mEndTime.second = 0;
1935             mEndTime.monthDay++;
1936             mEndTime.timezone = timezone;
1937             endMillis = mEndTime.normalize(true);
1938
1939             if (mEventCursor == null) {
1940                 // This is a new event
1941                 calendarId = mCalendarsSpinner.getSelectedItemId();
1942             } else {
1943                 calendarId = mInitialValues.getAsLong(Events.CALENDAR_ID);
1944             }
1945         } else {
1946             startMillis = mStartTime.toMillis(true);
1947             endMillis = mEndTime.toMillis(true);
1948             if (mEventCursor != null) {
1949                 // This is an existing event
1950                 timezone = mEventCursor.getString(EVENT_INDEX_TIMEZONE);
1951
1952                 // The timezone might be null if we are changing an existing
1953                 // all-day event to a non-all-day event.  We need to assign
1954                 // a timezone to the non-all-day event.
1955                 if (TextUtils.isEmpty(timezone)) {
1956                     timezone = TimeZone.getDefault().getID();
1957                 }
1958                 calendarId = mInitialValues.getAsLong(Events.CALENDAR_ID);
1959             } else {
1960                 // This is a new event
1961                 calendarId = mCalendarsSpinner.getSelectedItemId();
1962
1963                 // The timezone for a new event is the currently displayed
1964                 // timezone, NOT the timezone of the containing calendar.
1965                 timezone = TimeZone.getDefault().getID();
1966             }
1967         }
1968
1969         values.put(Events.CALENDAR_ID, calendarId);
1970         values.put(Events.EVENT_TIMEZONE, timezone);
1971         values.put(Events.TITLE, title);
1972         values.put(Events.ALL_DAY, isAllDay ? 1 : 0);
1973         values.put(Events.DTSTART, startMillis);
1974         values.put(Events.DTEND, endMillis);
1975         values.put(Events.DESCRIPTION, description);
1976         values.put(Events.EVENT_LOCATION, location);
1977         values.put(Events.TRANSPARENCY, mAvailabilitySpinner.getSelectedItemPosition());
1978
1979         int visibility = mVisibilitySpinner.getSelectedItemPosition();
1980         if (visibility > 0) {
1981             // For now we the array contains the values 0, 2, and 3. We add one to match.
1982             visibility++;
1983         }
1984         values.put(Events.VISIBILITY, visibility);
1985
1986         return values;
1987     }
1988
1989     private boolean isEmpty() {
1990         String title = mTitleTextView.getText().toString();
1991         if (title.length() > 0) {
1992             return false;
1993         }
1994
1995         String location = mLocationTextView.getText().toString();
1996         if (location.length() > 0) {
1997             return false;
1998         }
1999
2000         String description = mDescriptionTextView.getText().toString();
2001         if (description.length() > 0) {
2002             return false;
2003         }
2004
2005         return true;
2006     }
2007
2008     private boolean isCustomRecurrence() {
2009
2010         if (mEventRecurrence.until != null || mEventRecurrence.interval != 0) {
2011             return true;
2012         }
2013
2014         if (mEventRecurrence.freq == 0) {
2015             return false;
2016         }
2017
2018         switch (mEventRecurrence.freq) {
2019         case EventRecurrence.DAILY:
2020             return false;
2021         case EventRecurrence.WEEKLY:
2022             if (mEventRecurrence.repeatsOnEveryWeekDay() && isWeekdayEvent()) {
2023                 return false;
2024             } else if (mEventRecurrence.bydayCount == 1) {
2025                 return false;
2026             }
2027             break;
2028         case EventRecurrence.MONTHLY:
2029             if (mEventRecurrence.repeatsMonthlyOnDayCount()) {
2030                 return false;
2031             } else if (mEventRecurrence.bydayCount == 0 && mEventRecurrence.bymonthdayCount == 1) {
2032                 return false;
2033             }
2034             break;
2035         case EventRecurrence.YEARLY:
2036             return false;
2037         }
2038
2039         return true;
2040     }
2041
2042     private boolean isWeekdayEvent() {
2043         if (mStartTime.weekDay != Time.SUNDAY && mStartTime.weekDay != Time.SATURDAY) {
2044             return true;
2045         }
2046         return false;
2047     }
2048 }