EditEvent.java 95.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.calendar;

import static android.provider.Calendar.EVENT_BEGIN_TIME;
import static android.provider.Calendar.EVENT_END_TIME;
21

22
import com.android.calendar.TimezoneAdapter.TimezoneRow;
23 24 25
import com.android.common.Rfc822InputFilter;
import com.android.common.Rfc822Validator;

26 27 28
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
29
import android.app.DatePickerDialog.OnDateSetListener;
30 31 32 33
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.AsyncQueryHandler;
34
import android.content.ContentProviderOperation;
35
import android.content.ContentProviderOperation.Builder;
36
import android.content.ContentProviderResult;
37 38 39 40 41
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
42 43
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
44
import android.content.Intent;
45
import android.content.OperationApplicationException;
46 47 48 49 50
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
51
import android.os.RemoteException;
52
import android.pim.EventRecurrence;
53
import android.provider.Calendar.Attendees;
54 55 56
import android.provider.Calendar.Calendars;
import android.provider.Calendar.Events;
import android.provider.Calendar.Reminders;
57
import android.text.Editable;
58
import android.text.InputFilter;
59 60 61 62
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
63 64
import android.text.util.Rfc822Token;
import android.text.util.Rfc822Tokenizer;
65
import android.util.Log;
66
import android.view.KeyEvent;
67 68 69 70 71
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
72
import android.widget.AdapterView;
73 74 75 76 77 78 79
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.LinearLayout;
80
import android.widget.ListView;
81
import android.widget.MultiAutoCompleteTextView;
82 83 84 85 86 87 88 89 90
import android.widget.ResourceCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
91
import java.util.Formatter;
92
import java.util.HashSet;
93
import java.util.Iterator;
94
import java.util.LinkedHashSet;
95
import java.util.Locale;
96
import java.util.TimeZone;
97 98 99

public class EditEvent extends Activity implements View.OnClickListener,
        DialogInterface.OnCancelListener, DialogInterface.OnClickListener {
100
    private static final String TAG = "EditEvent";
101 102
    private static final boolean DEBUG = false;

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    /**
     * This is the symbolic name for the key used to pass in the boolean
     * for creating all-day events that is part of the extra data of the intent.
     * This is used only for creating new events and is set to true if
     * the default for the new event should be an all-day event.
     */
    public static final String EVENT_ALL_DAY = "allDay";

    private static final int MAX_REMINDERS = 5;

    private static final int MENU_GROUP_REMINDER = 1;
    private static final int MENU_GROUP_SHOW_OPTIONS = 2;
    private static final int MENU_GROUP_HIDE_OPTIONS = 3;

    private static final int MENU_ADD_REMINDER = 1;
    private static final int MENU_SHOW_EXTRA_OPTIONS = 2;
    private static final int MENU_HIDE_EXTRA_OPTIONS = 3;

    private static final String[] EVENT_PROJECTION = new String[] {
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
            Events._ID,               // 0
            Events.TITLE,             // 1
            Events.DESCRIPTION,       // 2
            Events.EVENT_LOCATION,    // 3
            Events.ALL_DAY,           // 4
            Events.HAS_ALARM,         // 5
            Events.CALENDAR_ID,       // 6
            Events.DTSTART,           // 7
            Events.DURATION,          // 8
            Events.EVENT_TIMEZONE,    // 9
            Events.RRULE,             // 10
            Events._SYNC_ID,          // 11
            Events.TRANSPARENCY,      // 12
            Events.VISIBILITY,        // 13
            Events.OWNER_ACCOUNT,     // 14
            Events.HAS_ATTENDEE_DATA, // 15
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    };
    private static final int EVENT_INDEX_ID = 0;
    private static final int EVENT_INDEX_TITLE = 1;
    private static final int EVENT_INDEX_DESCRIPTION = 2;
    private static final int EVENT_INDEX_EVENT_LOCATION = 3;
    private static final int EVENT_INDEX_ALL_DAY = 4;
    private static final int EVENT_INDEX_HAS_ALARM = 5;
    private static final int EVENT_INDEX_CALENDAR_ID = 6;
    private static final int EVENT_INDEX_DTSTART = 7;
    private static final int EVENT_INDEX_DURATION = 8;
    private static final int EVENT_INDEX_TIMEZONE = 9;
    private static final int EVENT_INDEX_RRULE = 10;
    private static final int EVENT_INDEX_SYNC_ID = 11;
    private static final int EVENT_INDEX_TRANSPARENCY = 12;
    private static final int EVENT_INDEX_VISIBILITY = 13;
153
    private static final int EVENT_INDEX_OWNER_ACCOUNT = 14;
154
    private static final int EVENT_INDEX_HAS_ATTENDEE_DATA = 15;
155 156

    private static final String[] CALENDARS_PROJECTION = new String[] {
157 158 159
            Calendars._ID,           // 0
            Calendars.DISPLAY_NAME,  // 1
            Calendars.OWNER_ACCOUNT, // 2
160
            Calendars.COLOR,         // 3
161 162
    };
    private static final int CALENDARS_INDEX_DISPLAY_NAME = 1;
163
    private static final int CALENDARS_INDEX_OWNER_ACCOUNT = 2;
164
    private static final int CALENDARS_INDEX_COLOR = 3;
165 166 167 168 169 170 171 172 173 174 175 176
    private static final String CALENDARS_WHERE = Calendars.ACCESS_LEVEL + ">=" +
            Calendars.CONTRIBUTOR_ACCESS + " AND " + Calendars.SYNC_EVENTS + "=1";

    private static final String[] REMINDERS_PROJECTION = new String[] {
            Reminders._ID,      // 0
            Reminders.MINUTES,  // 1
    };
    private static final int REMINDERS_INDEX_MINUTES = 1;
    private static final String REMINDERS_WHERE = Reminders.EVENT_ID + "=%d AND (" +
            Reminders.METHOD + "=" + Reminders.METHOD_ALERT + " OR " + Reminders.METHOD + "=" +
            Reminders.METHOD_DEFAULT + ")";

177 178 179 180 181 182 183 184
    private static final String[] ATTENDEES_PROJECTION = new String[] {
        Attendees.ATTENDEE_NAME,            // 0
        Attendees.ATTENDEE_EMAIL,           // 1
    };
    private static final int ATTENDEES_INDEX_NAME = 0;
    private static final int ATTENDEES_INDEX_EMAIL = 1;
    private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=? AND "
            + Attendees.ATTENDEE_RELATIONSHIP + "<>" + Attendees.RELATIONSHIP_ORGANIZER;
185 186
    private static final String ATTENDEES_DELETE_PREFIX = Attendees.EVENT_ID + "=? AND " +
            Attendees.ATTENDEE_EMAIL + " IN (";
187

188 189 190 191 192 193 194 195 196 197 198 199 200
    private static final int DOES_NOT_REPEAT = 0;
    private static final int REPEATS_DAILY = 1;
    private static final int REPEATS_EVERY_WEEKDAY = 2;
    private static final int REPEATS_WEEKLY_ON_DAY = 3;
    private static final int REPEATS_MONTHLY_ON_DAY_COUNT = 4;
    private static final int REPEATS_MONTHLY_ON_DAY = 5;
    private static final int REPEATS_YEARLY = 6;
    private static final int REPEATS_CUSTOM = 7;

    private static final int MODIFY_UNINITIALIZED = 0;
    private static final int MODIFY_SELECTED = 1;
    private static final int MODIFY_ALL = 2;
    private static final int MODIFY_ALL_FOLLOWING = 3;
201

202 203 204 205 206 207 208 209 210 211 212 213 214 215
    private static final int DAY_IN_SECONDS = 24 * 60 * 60;

    private int mFirstDayOfWeek; // cached in onCreate
    private Uri mUri;
    private Cursor mEventCursor;
    private Cursor mCalendarsCursor;

    private Button mStartDateButton;
    private Button mEndDateButton;
    private Button mStartTimeButton;
    private Button mEndTimeButton;
    private Button mSaveButton;
    private Button mDeleteButton;
    private Button mDiscardButton;
216
    private Button mTimezoneButton;
217 218 219 220 221 222 223 224
    private CheckBox mAllDayCheckBox;
    private Spinner mCalendarsSpinner;
    private Spinner mRepeatsSpinner;
    private Spinner mAvailabilitySpinner;
    private Spinner mVisibilitySpinner;
    private TextView mTitleTextView;
    private TextView mLocationTextView;
    private TextView mDescriptionTextView;
225 226
    private TextView mTimezoneTextView;
    private TextView mTimezoneFooterView;
227 228 229 230
    private TextView mStartTimeHome;
    private TextView mStartDateHome;
    private TextView mEndTimeHome;
    private TextView mEndDateHome;
231 232 233 234 235
    private View mRemindersSeparator;
    private LinearLayout mRemindersContainer;
    private LinearLayout mExtraOptions;
    private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>();
    private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0);
236 237
    private Rfc822Validator mEmailValidator;
    private MultiAutoCompleteTextView mAttendeesList;
238
    private EmailAddressAdapter mAddressAdapter;
239
    private TimezoneAdapter mTimezoneAdapter;
240
    private String mOriginalAttendees = "";
241

242 243 244
    // Used to control the visibility of the Guests textview. Default to true
    private boolean mHasAttendeeData = true;

245 246 247 248 249 250
    private EventRecurrence mEventRecurrence = new EventRecurrence();
    private String mRrule;
    private boolean mCalendarsQueryComplete;
    private boolean mSaveAfterQueryComplete;
    private ProgressDialog mLoadingCalendarsDialog;
    private AlertDialog mNoCalendarsDialog;
251
    private AlertDialog mTimezoneDialog;
252
    private ContentValues mInitialValues;
Ken Shirriff's avatar
Ken Shirriff committed
253
    private String mOwnerAccount;
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

    /**
     * If the repeating event is created on the phone and it hasn't been
     * synced yet to the web server, then there is a bug where you can't
     * delete or change an instance of the repeating event.  This case
     * can be detected with mSyncId.  If mSyncId == null, then the repeating
     * event has not been synced to the phone, in which case we won't allow
     * the user to change one instance.
     */
    private String mSyncId;

    private ArrayList<Integer> mRecurrenceIndexes = new ArrayList<Integer> (0);
    private ArrayList<Integer> mReminderValues;
    private ArrayList<String> mReminderLabels;

    private Time mStartTime;
    private Time mEndTime;
271
    private String mTimezone;
272 273 274 275 276
    private int mModification = MODIFY_UNINITIALIZED;
    private int mDefaultReminderMinutes;

    private DeleteEventHelper mDeleteEventHelper;
    private QueryHandler mQueryHandler;
277

278 279 280
    private static StringBuilder mSB = new StringBuilder(50);
    private static Formatter mF = new Formatter(mSB, Locale.getDefault());

281 282 283
    // This is here in case we need to update tz info later
    private Runnable mUpdateTZ = null;

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    /* This class is used to update the time buttons. */
    private class TimeListener implements OnTimeSetListener {
        private View mView;

        public TimeListener(View view) {
            mView = view;
        }

        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            // Cache the member variables locally to avoid inner class overhead.
            Time startTime = mStartTime;
            Time endTime = mEndTime;

            // Cache the start and end millis so that we limit the number
            // of calls to normalize() and toMillis(), which are fairly
            // expensive.
            long startMillis;
            long endMillis;
            if (mView == mStartTimeButton) {
                // The start time was changed.
                int hourDuration = endTime.hour - startTime.hour;
                int minuteDuration = endTime.minute - startTime.minute;

                startTime.hour = hourOfDay;
                startTime.minute = minute;
                startMillis = startTime.normalize(true);

                // Also update the end time to keep the duration constant.
                endTime.hour = hourOfDay + hourDuration;
                endTime.minute = minute + minuteDuration;
            } else {
                // The end time was changed.
                startMillis = startTime.toMillis(true);
                endTime.hour = hourOfDay;
                endTime.minute = minute;

320
                // Move to the next day if the end time is before the start time.
321
                if (endTime.before(startTime)) {
322
                    endTime.monthDay = startTime.monthDay + 1;
323 324 325
                }
            }

326 327
            endMillis = endTime.normalize(true);

328 329 330
            setDate(mEndDateButton, endMillis);
            setTime(mStartTimeButton, startMillis);
            setTime(mEndTimeButton, endMillis);
331
            updateHomeTime();
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
        }
    }

    private class TimeClickListener implements View.OnClickListener {
        private Time mTime;

        public TimeClickListener(Time time) {
            mTime = time;
        }

        public void onClick(View v) {
            new TimePickerDialog(EditEvent.this, new TimeListener(v),
                    mTime.hour, mTime.minute,
                    DateFormat.is24HourFormat(EditEvent.this)).show();
        }
    }

    private class DateListener implements OnDateSetListener {
        View mView;

        public DateListener(View view) {
            mView = view;
        }

        public void onDateSet(DatePicker view, int year, int month, int monthDay) {
            // Cache the member variables locally to avoid inner class overhead.
            Time startTime = mStartTime;
            Time endTime = mEndTime;

            // Cache the start and end millis so that we limit the number
            // of calls to normalize() and toMillis(), which are fairly
            // expensive.
            long startMillis;
            long endMillis;
            if (mView == mStartDateButton) {
                // The start date was changed.
                int yearDuration = endTime.year - startTime.year;
                int monthDuration = endTime.month - startTime.month;
                int monthDayDuration = endTime.monthDay - startTime.monthDay;

                startTime.year = year;
                startTime.month = month;
                startTime.monthDay = monthDay;
                startMillis = startTime.normalize(true);

                // Also update the end date to keep the duration constant.
                endTime.year = year + yearDuration;
                endTime.month = month + monthDuration;
                endTime.monthDay = monthDay + monthDayDuration;
                endMillis = endTime.normalize(true);

                // If the start date has changed then update the repeats.
                populateRepeats();
            } else {
                // The end date was changed.
                startMillis = startTime.toMillis(true);
                endTime.year = year;
                endTime.month = month;
                endTime.monthDay = monthDay;
                endMillis = endTime.normalize(true);

                // Do not allow an event to have an end time before the start time.
                if (endTime.before(startTime)) {
                    endTime.set(startTime);
                    endMillis = startMillis;
                }
            }

            setDate(mStartDateButton, startMillis);
            setDate(mEndDateButton, endMillis);
            setTime(mEndTimeButton, endMillis); // In case end time had to be reset
403
            updateHomeTime();
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
        }
    }

    private class DateClickListener implements View.OnClickListener {
        private Time mTime;

        public DateClickListener(Time time) {
            mTime = time;
        }

        public void onClick(View v) {
            new DatePickerDialog(EditEvent.this, new DateListener(v), mTime.year,
                    mTime.month, mTime.monthDay).show();
        }
    }

Michael Chan's avatar
Michael Chan committed
420
    static private class CalendarsAdapter extends ResourceCursorAdapter {
421 422 423 424 425 426 427
        public CalendarsAdapter(Context context, Cursor c) {
            super(context, R.layout.calendars_item, c);
            setDropDownViewResource(R.layout.calendars_dropdown_item);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
428 429 430 431 432 433
            View colorBar = view.findViewById(R.id.color);
            if (colorBar != null) {
                colorBar.setBackgroundDrawable(
                        Utils.getColorChip(cursor.getInt(CALENDARS_INDEX_COLOR)));
            }

434
            TextView name = (TextView) view.findViewById(R.id.calendar_name);
435 436 437 438 439 440 441
            if (name != null) {
                String displayName = cursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
                name.setText(displayName);
                name.setTextColor(0xFF000000);

                TextView accountName = (TextView) view.findViewById(R.id.account_name);
                if(accountName != null) {
442
                    Resources res = context.getResources();
443 444
                    accountName.setText(cursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT));
                    accountName.setVisibility(TextView.VISIBLE);
445
                    accountName.setTextColor(res.getColor(R.color.calendar_owner_text_color));
446 447
                }
            }
448 449 450 451 452 453 454 455 456 457 458 459 460
        }
    }

    // This is called if the user clicks on one of the buttons: "Save",
    // "Discard", or "Delete".  This is also called if the user clicks
    // on the "remove reminder" button.
    public void onClick(View v) {
        if (v == mSaveButton) {
            if (save()) {
                finish();
            }
            return;
        }
461

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
        if (v == mDeleteButton) {
            long begin = mStartTime.toMillis(false /* use isDst */);
            long end = mEndTime.toMillis(false /* use isDst */);
            int which = -1;
            switch (mModification) {
            case MODIFY_SELECTED:
                which = DeleteEventHelper.DELETE_SELECTED;
                break;
            case MODIFY_ALL_FOLLOWING:
                which = DeleteEventHelper.DELETE_ALL_FOLLOWING;
                break;
            case MODIFY_ALL:
                which = DeleteEventHelper.DELETE_ALL;
                break;
            }
            mDeleteEventHelper.delete(begin, end, mEventCursor, which);
            return;
        }
480

481 482 483 484
        if (v == mDiscardButton) {
            finish();
            return;
        }
485

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
        // This must be a click on one of the "remove reminder" buttons
        LinearLayout reminderItem = (LinearLayout) v.getParent();
        LinearLayout parent = (LinearLayout) reminderItem.getParent();
        parent.removeView(reminderItem);
        mReminderItems.remove(reminderItem);
        updateRemindersVisibility();
    }

    // This is called if the user cancels a popup dialog.  There are two
    // dialogs: the "Loading calendars" dialog, and the "No calendars"
    // dialog.  The "Loading calendars" dialog is shown if there is a delay
    // in loading the calendars (needed when creating an event) and the user
    // tries to save the event before the calendars have finished loading.
    // The "No calendars" dialog is shown if there are no syncable calendars.
    public void onCancel(DialogInterface dialog) {
        if (dialog == mLoadingCalendarsDialog) {
            mSaveAfterQueryComplete = false;
        } else if (dialog == mNoCalendarsDialog) {
            finish();
        }
    }

    // This is called if the user clicks on a dialog button.
    public void onClick(DialogInterface dialog, int which) {
        if (dialog == mNoCalendarsDialog) {
            finish();
512 513 514
        } else if (dialog == mTimezoneDialog) {
            if (which >= 0 && which < mTimezoneAdapter.getCount()) {
                setTimezone(which);
515
                updateHomeTime();
516 517
                dialog.dismiss();
            }
518 519
        }
    }
520

521 522 523 524 525 526 527
    private class QueryHandler extends AsyncQueryHandler {
        public QueryHandler(ContentResolver cr) {
            super(cr);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
Erik's avatar
Erik committed
528 529 530 531 532
            // If the query didn't return a cursor for some reason return
            if (cursor == null) {
                return;
            }

533 534 535 536 537 538 539 540
            // If the Activity is finishing, then close the cursor.
            // Otherwise, use the new cursor in the adapter.
            if (isFinishing()) {
                stopManagingCursor(cursor);
                cursor.close();
            } else {
                mCalendarsCursor = cursor;
                startManagingCursor(cursor);
541

542 543 544 545 546 547 548 549 550 551 552
                // Stop the spinner
                getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
                        Window.PROGRESS_VISIBILITY_OFF);

                // If there are no syncable calendars, then we cannot allow
                // creating a new event.
                if (cursor.getCount() == 0) {
                    // Cancel the "loading calendars" dialog if it exists
                    if (mSaveAfterQueryComplete) {
                        mLoadingCalendarsDialog.cancel();
                    }
553

554 555 556 557 558 559 560 561 562 563 564 565
                    // Create an error message for the user that, when clicked,
                    // will exit this activity without saving the event.
                    AlertDialog.Builder builder = new AlertDialog.Builder(EditEvent.this);
                    builder.setTitle(R.string.no_syncable_calendars)
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setMessage(R.string.no_calendars_found)
                        .setPositiveButton(android.R.string.ok, EditEvent.this)
                        .setOnCancelListener(EditEvent.this);
                    mNoCalendarsDialog = builder.show();
                    return;
                }

566
                int defaultCalendarPosition = findDefaultCalendarPosition(mCalendarsCursor);
567

568 569 570
                // populate the calendars spinner
                CalendarsAdapter adapter = new CalendarsAdapter(EditEvent.this, mCalendarsCursor);
                mCalendarsSpinner.setAdapter(adapter);
571
                mCalendarsSpinner.setSelection(defaultCalendarPosition);
572 573 574 575 576 577
                mCalendarsQueryComplete = true;
                if (mSaveAfterQueryComplete) {
                    mLoadingCalendarsDialog.cancel();
                    save();
                    finish();
                }
578

579 580 581 582 583
                // Find user domain and set it to the validator.
                // TODO: we may want to update this validator if the user actually picks
                // a different calendar.  maybe not.  depends on what we want for the
                // user experience.  this may change when we add support for multiple
                // accounts, anyway.
584
                if (mHasAttendeeData && cursor.moveToPosition(defaultCalendarPosition)) {
585 586
                    String ownEmail = cursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
                    if (ownEmail != null) {
587 588 589 590
                        String domain = extractDomain(ownEmail);
                        if (domain != null) {
                            mEmailValidator = new Rfc822Validator(domain);
                            mAttendeesList.setValidator(mEmailValidator);
591 592 593 594 595 596
                        }
                    }
                }
            }
        }

597 598 599 600 601
        // Find the calendar position in the cursor that matches calendar in preference
        private int findDefaultCalendarPosition(Cursor calendarsCursor) {
            if (calendarsCursor.getCount() <= 0) {
                return -1;
            }
602

603 604 605 606 607 608 609 610 611 612 613 614 615
            String defaultCalendar = Utils.getSharedPreference(EditEvent.this,
                    CalendarPreferenceActivity.KEY_DEFAULT_CALENDAR, null);

            if (defaultCalendar == null) {
                return 0;
            }

            int position = 0;
            calendarsCursor.moveToPosition(-1);
            while(calendarsCursor.moveToNext()) {
                if (defaultCalendar.equals(mCalendarsCursor
                        .getString(CALENDARS_INDEX_OWNER_ACCOUNT))) {
                    return position;
616
                }
617
                position++;
618
            }
619
            return 0;
620 621 622
        }
    }

623 624 625 626 627 628 629 630
    private static String extractDomain(String email) {
        int separator = email.lastIndexOf('@');
        if (separator != -1 && ++separator < email.length()) {
            return email.substring(separator);
        }
        return null;
    }

631 632 633 634 635 636
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.edit_event);

637 638
        boolean newEvent = false;

639 640 641 642
        mFirstDayOfWeek = Calendar.getInstance().getFirstDayOfWeek();

        mStartTime = new Time();
        mEndTime = new Time();
643
        mTimezone = Utils.getTimeZone(this, mUpdateTZ);
644 645 646 647 648

        Intent intent = getIntent();
        mUri = intent.getData();

        if (mUri != null) {
649
            mEventCursor = managedQuery(mUri, EVENT_PROJECTION, null, null, null);
650 651 652 653 654 655 656 657 658 659
            if (mEventCursor == null || mEventCursor.getCount() == 0) {
                // The cursor is empty. This can happen if the event was deleted.
                finish();
                return;
            }
        }

        long begin = intent.getLongExtra(EVENT_BEGIN_TIME, 0);
        long end = intent.getLongExtra(EVENT_END_TIME, 0);

660
        String domain = getResources().getString(R.string.google_email_domain);
661

662 663 664 665
        boolean allDay = false;
        if (mEventCursor != null) {
            // The event already exists so fetch the all-day status
            mEventCursor.moveToFirst();
666
            mHasAttendeeData = mEventCursor.getInt(EVENT_INDEX_HAS_ATTENDEE_DATA) != 0;
667 668
            allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
            String rrule = mEventCursor.getString(EVENT_INDEX_RRULE);
669 670 671 672 673
            if (!allDay) {
                // only load the event timezone for non-all-day events
                // otherwise it defaults to device default
                mTimezone = mEventCursor.getString(EVENT_INDEX_TIMEZONE);
            }
674
            long calendarId = mEventCursor.getInt(EVENT_INDEX_CALENDAR_ID);
Ken Shirriff's avatar
Ken Shirriff committed
675 676 677
            mOwnerAccount = mEventCursor.getString(EVENT_INDEX_OWNER_ACCOUNT);
            if (!TextUtils.isEmpty(mOwnerAccount)) {
                String ownerDomain = extractDomain(mOwnerAccount);
678 679 680 681
                if (ownerDomain != null) {
                    domain = ownerDomain;
                }
            }
682

683 684 685 686 687 688
            // Remember the initial values
            mInitialValues = new ContentValues();
            mInitialValues.put(EVENT_BEGIN_TIME, begin);
            mInitialValues.put(EVENT_END_TIME, end);
            mInitialValues.put(Events.ALL_DAY, allDay ? 1 : 0);
            mInitialValues.put(Events.RRULE, rrule);
689
            mInitialValues.put(Events.EVENT_TIMEZONE, mTimezone);
690 691
            mInitialValues.put(Events.CALENDAR_ID, calendarId);
        } else {
692
            newEvent = true;
693 694 695
            // We are creating a new event, so set the default from the
            // intent (if specified).
            allDay = intent.getBooleanExtra(EVENT_ALL_DAY, false);
696

697 698 699 700 701 702 703 704 705 706
            // Start the spinner
            getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
                    Window.PROGRESS_VISIBILITY_ON);

            // Start a query in the background to read the list of calendars
            mQueryHandler = new QueryHandler(getContentResolver());
            mQueryHandler.startQuery(0, null, Calendars.CONTENT_URI, CALENDARS_PROJECTION,
                    CALENDARS_WHERE, null /* selection args */, null /* sort order */);
        }

707 708
        mTimezoneAdapter = new TimezoneAdapter(this, mTimezone);

709 710 711 712 713
        // If the event is all-day, read the times in UTC timezone
        if (begin != 0) {
            if (allDay) {
                mStartTime.timezone = Time.TIMEZONE_UTC;
                mStartTime.set(begin);
714
                mStartTime.timezone = mTimezone;
715 716 717 718

                // Calling normalize to calculate isDst
                mStartTime.normalize(true);
            } else {
719
                mStartTime.timezone = mTimezone;
720 721 722 723 724 725 726 727
                mStartTime.set(begin);
            }
        }

        if (end != 0) {
            if (allDay) {
                mEndTime.timezone = Time.TIMEZONE_UTC;
                mEndTime.set(end);
728
                mEndTime.timezone = mTimezone;
729 730 731 732

                // Calling normalize to calculate isDst
                mEndTime.normalize(true);
            } else {
733
                mEndTime.timezone = mTimezone;
734 735 736 737
                mEndTime.set(end);
            }
        }

738 739
        LayoutInflater inflater = getLayoutInflater();

740 741 742 743
        // cache all the widgets
        mTitleTextView = (TextView) findViewById(R.id.title);
        mLocationTextView = (TextView) findViewById(R.id.location);
        mDescriptionTextView = (TextView) findViewById(R.id.description);
744 745
        mTimezoneTextView = (TextView) findViewById(R.id.timezone_label);
        mTimezoneFooterView = (TextView) inflater.inflate(R.layout.timezone_footer, null);
746 747 748 749
        mStartDateButton = (Button) findViewById(R.id.start_date);
        mEndDateButton = (Button) findViewById(R.id.end_date);
        mStartTimeButton = (Button) findViewById(R.id.start_time);
        mEndTimeButton = (Button) findViewById(R.id.end_time);
750 751 752 753
        mStartTimeHome = (TextView) findViewById(R.id.start_time_home);
        mStartDateHome = (TextView) findViewById(R.id.start_date_home);
        mEndTimeHome = (TextView) findViewById(R.id.end_time_home);
        mEndDateHome = (TextView) findViewById(R.id.end_date_home);
754
        mAllDayCheckBox = (CheckBox) findViewById(R.id.is_all_day);
755
        mTimezoneButton = (Button) findViewById(R.id.timezone);
756 757 758 759 760
        mCalendarsSpinner = (Spinner) findViewById(R.id.calendars);
        mRepeatsSpinner = (Spinner) findViewById(R.id.repeats);
        mAvailabilitySpinner = (Spinner) findViewById(R.id.availability);
        mVisibilitySpinner = (Spinner) findViewById(R.id.visibility);
        mRemindersSeparator = findViewById(R.id.reminders_separator);
761
        mRemindersContainer = (LinearLayout) findViewById(R.id.reminder_items_container);
762 763
        mExtraOptions = (LinearLayout) findViewById(R.id.extra_options_container);

764 765 766 767 768 769 770
        if (mHasAttendeeData) {
            mAddressAdapter = new EmailAddressAdapter(this);
            mEmailValidator = new Rfc822Validator(domain);
            mAttendeesList = initMultiAutoCompleteTextView(R.id.attendees);
        } else {
            findViewById(R.id.attendees_group).setVisibility(View.GONE);
        }
771

772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
        mAllDayCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (mEndTime.hour == 0 && mEndTime.minute == 0) {
                        mEndTime.monthDay--;
                        long endMillis = mEndTime.normalize(true);

                        // Do not allow an event to have an end time before the start time.
                        if (mEndTime.before(mStartTime)) {
                            mEndTime.set(mStartTime);
                            endMillis = mEndTime.normalize(true);
                        }
                        setDate(mEndDateButton, endMillis);
                        setTime(mEndTimeButton, endMillis);
                    }

                    mStartTimeButton.setVisibility(View.GONE);
                    mEndTimeButton.setVisibility(View.GONE);
790 791
                    mTimezoneButton.setVisibility(View.GONE);
                    mTimezoneTextView.setVisibility(View.GONE);
792 793 794 795 796 797 798 799 800 801
                } else {
                    if (mEndTime.hour == 0 && mEndTime.minute == 0) {
                        mEndTime.monthDay++;
                        long endMillis = mEndTime.normalize(true);
                        setDate(mEndDateButton, endMillis);
                        setTime(mEndTimeButton, endMillis);
                    }

                    mStartTimeButton.setVisibility(View.VISIBLE);
                    mEndTimeButton.setVisibility(View.VISIBLE);
802 803
                    mTimezoneButton.setVisibility(View.VISIBLE);
                    mTimezoneTextView.setVisibility(View.VISIBLE);
804
                }
805
                updateHomeTime();
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
            }
        });

        if (allDay) {
            mAllDayCheckBox.setChecked(true);
        } else {
            mAllDayCheckBox.setChecked(false);
        }

        mSaveButton = (Button) findViewById(R.id.save);
        mSaveButton.setOnClickListener(this);

        mDeleteButton = (Button) findViewById(R.id.delete);
        mDeleteButton.setOnClickListener(this);

        mDiscardButton = (Button) findViewById(R.id.discard);
        mDiscardButton.setOnClickListener(this);

        // Initialize the reminder values array.
        Resources r = getResources();
        String[] strings = r.getStringArray(R.array.reminder_minutes_values);
        int size = strings.length;
        ArrayList<Integer> list = new ArrayList<Integer>(size);
        for (int i = 0 ; i < size ; i++) {
            list.add(Integer.parseInt(strings[i]));
        }
        mReminderValues = list;
        String[] labels = r.getStringArray(R.array.reminder_minutes_labels);
        mReminderLabels = new ArrayList<String>(Arrays.asList(labels));

836
        SharedPreferences prefs = CalendarPreferenceActivity.getSharedPreferences(this);
837 838 839 840
        String durationString =
                prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0");
        mDefaultReminderMinutes = Integer.parseInt(durationString);

841 842 843 844 845
        if (newEvent && mDefaultReminderMinutes != 0) {
            addReminder(this, this, mReminderItems, mReminderValues,
                    mReminderLabels, mDefaultReminderMinutes);
        }

846 847 848
        long eventId = (mEventCursor == null) ? -1 : mEventCursor.getLong(EVENT_INDEX_ID);
        ContentResolver cr = getContentResolver();

849 850 851 852 853 854 855 856 857 858 859 860 861 862
        // Reminders cursor
        boolean hasAlarm = (mEventCursor != null)
                && (mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0);
        if (hasAlarm) {
            Uri uri = Reminders.CONTENT_URI;
            String where = String.format(REMINDERS_WHERE, eventId);
            Cursor reminderCursor = cr.query(uri, REMINDERS_PROJECTION, where, null, null);
            try {
                // First pass: collect all the custom reminder minutes (e.g.,
                // a reminder of 8 minutes) into a global list.
                while (reminderCursor.moveToNext()) {
                    int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
                    EditEvent.addMinutesToList(this, mReminderValues, mReminderLabels, minutes);
                }
863

864 865 866 867 868 869 870 871 872 873 874 875 876 877
                // Second pass: create the reminder spinners
                reminderCursor.moveToPosition(-1);
                while (reminderCursor.moveToNext()) {
                    int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
                    mOriginalMinutes.add(minutes);
                    EditEvent.addReminder(this, this, mReminderItems, mReminderValues,
                            mReminderLabels, minutes);
                }
            } finally {
                reminderCursor.close();
            }
        }
        updateRemindersVisibility();

878 879 880 881 882
        // Setup the + Add Reminder Button
        View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
            public void onClick(View v) {
                addReminder();
            }
883
        };
884 885 886
        ImageButton reminderRemoveButton = (ImageButton) findViewById(R.id.reminder_add);
        reminderRemoveButton.setOnClickListener(addReminderOnClickListener);

887 888
        mDeleteEventHelper = new DeleteEventHelper(this, true /* exit when done */);

889
       // Attendees cursor
890
        if (mHasAttendeeData && eventId != -1) {
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
            Uri uri = Attendees.CONTENT_URI;
            String[] whereArgs = {Long.toString(eventId)};
            Cursor attendeeCursor = cr.query(uri, ATTENDEES_PROJECTION, ATTENDEES_WHERE, whereArgs,
                    null);
            try {
                StringBuilder b = new StringBuilder();
                while (attendeeCursor.moveToNext()) {
                    String name = attendeeCursor.getString(ATTENDEES_INDEX_NAME);
                    String email = attendeeCursor.getString(ATTENDEES_INDEX_EMAIL);
                    if (email != null) {
                        if (name != null && name.length() > 0 && !name.equals(email)) {
                            b.append('"').append(name).append("\" ");
                        }
                        b.append('<').append(email).append(">, ");
                    }
                }
                if (b.length() > 0) {
                    mOriginalAttendees = b.toString();
                    mAttendeesList.setText(mOriginalAttendees);
                }
            } finally {
                attendeeCursor.close();
            }
        }
915 916 917 918 919 920
        if (mEventCursor == null) {
            // Allow the intent to specify the fields in the event.
            // This will allow other apps to create events easily.
            initFromIntent(intent);
        }
    }
921

922
    private LinkedHashSet<Rfc822Token> getAddressesFromList(MultiAutoCompleteTextView list) {
923
        list.clearComposingText();
924 925
        LinkedHashSet<Rfc822Token> addresses = new LinkedHashSet<Rfc822Token>();
        Rfc822Tokenizer.tokenize(list.getText(), addresses);
926 927 928

        // validate the emails, out of paranoia.  they should already be
        // validated on input, but drop any invalid emails just to be safe.
929 930 931
        Iterator<Rfc822Token> addressIterator = addresses.iterator();
        while (addressIterator.hasNext()) {
            Rfc822Token address = addressIterator.next();
932
            if (!mEmailValidator.isValid(address.getAddress())) {
933
                Log.w(TAG, "Dropping invalid attendee email address: " + address);
934
                addressIterator.remove();
935 936
            }
        }
937
        return addresses;
938 939 940
    }

    // From com.google.android.gm.ComposeActivity
941
    private MultiAutoCompleteTextView initMultiAutoCompleteTextView(int res) {
942 943 944
        MultiAutoCompleteTextView list = (MultiAutoCompleteTextView) findViewById(res);
        list.setAdapter(mAddressAdapter);
        list.setTokenizer(new Rfc822Tokenizer());
945
        list.setValidator(mEmailValidator);
946 947 948 949 950 951 952 953 954 955 956 957 958 959

        // NOTE: assumes no other filters are set
        list.setFilters(sRecipientFilters);

        return list;
    }

    /**
     * From com.google.android.gm.ComposeActivity
     * Implements special address cleanup rules:
     * The first space key entry following an "@" symbol that is followed by any combination
     * of letters and symbols, including one+ dots and zero commas, should insert an extra
     * comma (followed by the space).
     */
960
    private static InputFilter[] sRecipientFilters = new InputFilter[] { new Rfc822InputFilter() };
961

962 963 964 965 966
    private void initFromIntent(Intent intent) {
        String title = intent.getStringExtra(Events.TITLE);
        if (title != null) {
            mTitleTextView.setText(title);
        }
967

968 969 970 971
        String location = intent.getStringExtra(Events.EVENT_LOCATION);
        if (location != null) {
            mLocationTextView.setText(location);
        }
972

973 974 975 976
        String description = intent.getStringExtra(Events.DESCRIPTION);
        if (description != null) {
            mDescriptionTextView.setText(description);
        }
977

978 979 980 981
        int availability = intent.getIntExtra(Events.TRANSPARENCY, -1);
        if (availability != -1) {
            mAvailabilitySpinner.setSelection(availability);
        }
982

983 984 985 986
        int visibility = intent.getIntExtra(Events.VISIBILITY, -1);
        if (visibility != -1) {
            mVisibilitySpinner.setSelection(visibility);
        }
987

988
        String rrule = intent.getStringExtra(Events.RRULE);
989
        if (!TextUtils.isEmpty(rrule)) {
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
            mRrule = rrule;
            mEventRecurrence.parse(rrule);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mUri != null) {
            if (mEventCursor == null || mEventCursor.getCount() == 0) {
                // The cursor is empty. This can happen if the event was deleted.
                finish();
                return;
            }
        }
1006

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
        if (mEventCursor != null) {
            Cursor cursor = mEventCursor;
            cursor.moveToFirst();

            mRrule = cursor.getString(EVENT_INDEX_RRULE);
            String title = cursor.getString(EVENT_INDEX_TITLE);
            String description = cursor.getString(EVENT_INDEX_DESCRIPTION);
            String location = cursor.getString(EVENT_INDEX_EVENT_LOCATION);
            int availability = cursor.getInt(EVENT_INDEX_TRANSPARENCY);
            int visibility = cursor.getInt(EVENT_INDEX_VISIBILITY);
            if (visibility > 0) {
                // For now we the array contains the values 0, 2, and 3. We subtract one to match.
                visibility--;
            }

            if (!TextUtils.isEmpty(mRrule) && mModification == MODIFY_UNINITIALIZED) {
                // If this event has not been synced, then don't allow deleting
                // or changing a single instance.
                mSyncId = cursor.getString(EVENT_INDEX_SYNC_ID);
                mEventRecurrence.parse(mRrule);

                // If we haven't synced this repeating event yet, then don't
                // allow the user to change just one instance.
                int itemIndex = 0;
                CharSequence[] items;
                if (mSyncId == null) {
Erik's avatar
Erik committed
1033 1034 1035 1036 1037 1038
                    if(isFirstEventInSeries()) {
                        // Still display the option so the user knows all events are changing
                        items = new CharSequence[1];
                    } else {
                        items = new CharSequence[2];
                    }
1039
                } else {
Erik's avatar
Erik committed
1040 1041 1042 1043 1044
                    if(isFirstEventInSeries()) {
                        items = new CharSequence[2];
                    } else {
                        items = new CharSequence[3];
                    }
1045 1046 1047
                    items[itemIndex++] = getText(R.string.modify_event);
                }
                items[itemIndex++] = getText(R.string.modify_all);
Erik's avatar
Erik committed
1048 1049 1050 1051 1052 1053 1054

                // Do one more check to make sure this remains at the end of the list
                if(!isFirstEventInSeries()) {
                    // TODO Find out why modify all following causes a dup of the first event if
                    // it's operating on the first event.
                    items[itemIndex++] = getText(R.string.modify_all_following);
                }
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074

                // Display the modification dialog.
                new AlertDialog.Builder(this)
                        .setOnCancelListener(new OnCancelListener() {
                            public void onCancel(DialogInterface dialog) {
                                finish();
                            }
                        })
                        .setTitle(R.string.edit_event_label)
                        .setItems(items, new OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    mModification =
                                            (mSyncId == null) ? MODIFY_ALL : MODIFY_SELECTED;
                                } else if (which == 1) {
                                    mModification =
                                        (mSyncId == null) ? MODIFY_ALL_FOLLOWING : MODIFY_ALL;
                                } else if (which == 2) {
                                    mModification = MODIFY_ALL_FOLLOWING;
                                }
1075

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
                                // If we are modifying all the events in a
                                // series then disable and ignore the date.
                                if (mModification == MODIFY_ALL) {
                                    mStartDateButton.setEnabled(false);
                                    mEndDateButton.setEnabled(false);
                                } else if (mModification == MODIFY_SELECTED) {
                                    mRepeatsSpinner.setEnabled(false);
                                }
                            }
                        })
                        .show();
            }

            mTitleTextView.setText(title);
            mLocationTextView.setText(location);
            mDescriptionTextView.setText(description);
            mAvailabilitySpinner.setSelection(availability);
            mVisibilitySpinner.setSelection(visibility);

            // This is an existing event so hide the calendar spinner
            // since we can't change the calendar.
1097 1098
            View calendarGroup = findViewById(R.id.calendar_group);
            calendarGroup.setVisibility(View.GONE);
1099 1100 1101 1102 1103 1104 1105 1106
        } else {
            // New event
            if (Time.isEpoch(mStartTime) && Time.isEpoch(mEndTime)) {
                mStartTime.setToNow();

                // Round the time to the nearest half hour.
                mStartTime.second = 0;
                int minute = mStartTime.minute;
1107 1108 1109
                if (minute == 0) {
                    // We are already on a half hour increment
                } else if (minute > 0 && minute <= 30) {
1110 1111 1112 1113 1114 1115 1116 1117
                    mStartTime.minute = 30;
                } else {
                    mStartTime.minute = 0;
                    mStartTime.hour += 1;
                }

                long startMillis = mStartTime.normalize(true /* ignore isDst */);
                mEndTime.set(startMillis + DateUtils.HOUR_IN_MILLIS);
1118 1119 1120 1121 1122 1123 1124 1125
            }

            // Hide delete button
            mDeleteButton.setVisibility(View.GONE);
        }

        updateRemindersVisibility();
        populateWhen();
1126
        populateTimezone();
1127
        updateHomeTime();
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
        populateRepeats();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem item;
        item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0,
                R.string.add_new_reminder);
        item.setIcon(R.drawable.ic_menu_reminder);
        item.setAlphabeticShortcut('r');

        item = menu.add(MENU_GROUP_SHOW_OPTIONS, MENU_SHOW_EXTRA_OPTIONS, 0,
                R.string.edit_event_show_extra_options);
        item.setIcon(R.drawable.ic_menu_show_list);
        item = menu.add(MENU_GROUP_HIDE_OPTIONS, MENU_HIDE_EXTRA_OPTIONS, 0,
                R.string.edit_event_hide_extra_options);
        item.setIcon(R.drawable.ic_menu_show_list);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (mReminderItems.size() < MAX_REMINDERS) {
            menu.setGroupVisible(MENU_GROUP_REMINDER, true);
            menu.setGroupEnabled(MENU_GROUP_REMINDER, true);
        } else {
            menu.setGroupVisible(MENU_GROUP_REMINDER, false);
            menu.setGroupEnabled(MENU_GROUP_REMINDER, false);
        }

        if (mExtraOptions.getVisibility() == View.VISIBLE) {
            menu.setGroupVisible(MENU_GROUP_SHOW_OPTIONS, false);
            menu.setGroupVisible(MENU_GROUP_HIDE_OPTIONS, true);
        } else {
            menu.setGroupVisible(MENU_GROUP_SHOW_OPTIONS, true);
            menu.setGroupVisible(MENU_GROUP_HIDE_OPTIONS, false);
        }

        return super.onPrepareOptionsMenu(menu);
    }

1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    private void addReminder() {
        // TODO: when adding a new reminder, make it different from the
        // last one in the list (if any).
        if (mDefaultReminderMinutes == 0) {
            addReminder(this, this, mReminderItems, mReminderValues,
                    mReminderLabels, 10 /* minutes */);
        } else {
            addReminder(this, this, mReminderItems, mReminderValues,
                    mReminderLabels, mDefaultReminderMinutes);
        }
        updateRemindersVisibility();
    }

1183 1184 1185 1186
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_ADD_REMINDER:
1187
            addReminder();
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
            return true;
        case MENU_SHOW_EXTRA_OPTIONS:
            mExtraOptions.setVisibility(View.VISIBLE);
            return true;
        case MENU_HIDE_EXTRA_OPTIONS:
            mExtraOptions.setVisibility(View.GONE);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
    public void onBackPressed() {
        // If we are creating a new event, do not create it if the
        // title, location and description are all empty, in order to
        // prevent accidental "no subject" event creations.
        if (mUri != null || !isEmpty()) {
            if (!save()) {
                // We cannot exit this activity because the calendars
                // are still loading.
                return;
            }
1210
        }
1211
        finish();
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
    }

    private void populateWhen() {
        long startMillis = mStartTime.toMillis(false /* use isDst */);
        long endMillis = mEndTime.toMillis(false /* use isDst */);
        setDate(mStartDateButton, startMillis);
        setDate(mEndDateButton, endMillis);

        setTime(mStartTimeButton, startMillis);
        setTime(mEndTimeButton, endMillis);

        mStartDateButton.setOnClickListener(new DateClickListener(mStartTime));
        mEndDateButton.setOnClickListener(new DateClickListener(mEndTime));

        mStartTimeButton.setOnClickListener(new TimeClickListener(mStartTime));
        mEndTimeButton.setOnClickListener(new TimeClickListener(mEndTime));
    }

1230 1231 1232 1233
    private void populateTimezone() {
        mTimezoneButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
1234
                showTimezoneDialog();
1235 1236 1237 1238 1239
            }
        });
        setTimezone(mTimezoneAdapter.getRowById(mTimezone));
    }

1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
    /**
     * Checks if the start and end times for this event should be
     * displayed in the Calendar app's time zone as well and
     * formats and displays them.
     */
    private void updateHomeTime() {
        String tz = Utils.getTimeZone(this, mUpdateTZ);
        if (!mAllDayCheckBox.isChecked() && !TextUtils.equals(tz, mTimezone)) {
            int flags = DateUtils.FORMAT_SHOW_TIME;
            boolean is24Format = DateFormat.is24HourFormat(this);
            if (is24Format) {
                flags |= DateUtils.FORMAT_24HOUR;
            }
            long millisStart = mStartTime.toMillis(false);
            long millisEnd = mEndTime.toMillis(false);

            boolean isDSTStart = mStartTime.isDst != 0;
            boolean isDSTEnd = mEndTime.isDst != 0;

            // First update the start date and times
            String tzDisplay = TimeZone.getTimeZone(tz).getDisplayName(isDSTStart,
                    TimeZone.SHORT, Locale.getDefault());
            StringBuilder time = new StringBuilder();

            mSB.setLength(0);
            time.append(DateUtils.formatDateRange(this, mF, millisStart, millisStart, flags, tz))
                    .append(" ").append(tzDisplay);
            mStartTimeHome.setText(time.toString());

            flags = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE |
                    DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY;
            mSB.setLength(0);
            mStartDateHome.setText(DateUtils.formatDateRange(this, mF, millisStart, millisStart,
                    flags, tz).toString());

            // Make any adjustments needed for the end times
            if (isDSTEnd != isDSTStart) {
                tzDisplay = TimeZone.getTimeZone(tz).getDisplayName(isDSTEnd,
                        TimeZone.SHORT, Locale.getDefault());
            }
            flags = DateUtils.FORMAT_SHOW_TIME;
            if (is24Format) {
                flags |= DateUtils.FORMAT_24HOUR;
            }

            // Then update the end times
            time.setLength(0);
            mSB.setLength(0);
            time.append(DateUtils.formatDateRange(this, mF, millisEnd, millisEnd, flags, tz))
                    .append(" ").append(tzDisplay);
            mEndTimeHome.setText(time.toString());

            flags = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE |
            DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY;
            mSB.setLength(0);
            mEndDateHome.setText(DateUtils.formatDateRange(this, mF, millisEnd, millisEnd,
                    flags, tz).toString());

            mStartTimeHome.setVisibility(View.VISIBLE);
            mStartDateHome.setVisibility(View.VISIBLE);
            mEndTimeHome.setVisibility(View.VISIBLE);
            mEndDateHome.setVisibility(View.VISIBLE);
        } else {
            mStartTimeHome.setVisibility(View.GONE);
            mStartDateHome.setVisibility(View.GONE);
            mEndTimeHome.setVisibility(View.GONE);
            mEndDateHome.setVisibility(View.GONE);
        }
    }

1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
    /**
     * Removes "Show all timezone" footer and adds all timezones to the dialog.
     */
    private void showAllTimezone(ListView listView) {
        final ListView lv = listView;  // For making this variable available from Runnable.
        lv.removeFooterView(mTimezoneFooterView);
        mTimezoneAdapter.showAllTimezones();
        final int row = mTimezoneAdapter.getRowById(mTimezone);
        // we need to post the selection changes to have them have any effect.
        lv.post(new Runnable() {
            @Override
            public void run() {
                lv.setItemChecked(row, true);
                lv.setSelection(row);
            }
        });
    }

1328 1329
    private void showTimezoneDialog() {
        mTimezoneAdapter = new TimezoneAdapter(this, mTimezone);
1330 1331 1332 1333 1334
        final int row = mTimezoneAdapter.getRowById(mTimezone);
        mTimezoneDialog = new AlertDialog.Builder(this)
                .setTitle(R.string.timezone_label)
                .setSingleChoiceItems(mTimezoneAdapter, row, this)
                .create();
1335 1336 1337 1338
        final ListView lv = mTimezoneDialog.getListView();
        mTimezoneFooterView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
1339
                showAllTimezone(lv);
1340 1341 1342
            }
        });
        lv.addFooterView(mTimezoneFooterView);
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
        mTimezoneDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER &&
                        lv.getSelectedView() == mTimezoneFooterView) {
                    showAllTimezone(lv);
                    return true;
                } else {
                    return false;
                }
            }
        });
1355 1356 1357
        mTimezoneDialog.show();
    }

1358 1359 1360 1361 1362
    private void populateRepeats() {
        Time time = mStartTime;
        Resources r = getResources();
        int resource = android.R.layout.simple_spinner_item;

1363
        String[] days = new String[] {
1364 1365 1366 1367 1368 1369 1370
            DateUtils.getDayOfWeekString(Calendar.SUNDAY, DateUtils.LENGTH_MEDIUM),
            DateUtils.getDayOfWeekString(Calendar.MONDAY, DateUtils.LENGTH_MEDIUM),
            DateUtils.getDayOfWeekString(Calendar.TUESDAY, DateUtils.LENGTH_MEDIUM),
            DateUtils.getDayOfWeekString(Calendar.WEDNESDAY, DateUtils.LENGTH_MEDIUM),
            DateUtils.getDayOfWeekString(Calendar.THURSDAY, DateUtils.LENGTH_MEDIUM),
            DateUtils.getDayOfWeekString(Calendar.FRIDAY, DateUtils.LENGTH_MEDIUM),
            DateUtils.getDayOfWeekString(Calendar.SATURDAY, DateUtils.LENGTH_MEDIUM),
1371
        };
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
        String[] ordinals = r.getStringArray(R.array.ordinal_labels);

        // Only display "Custom" in the spinner if the device does not support the
        // recurrence functionality of the event. Only display every weekday if
        // the event starts on a weekday.
        boolean isCustomRecurrence = isCustomRecurrence();
        boolean isWeekdayEvent = isWeekdayEvent();

        ArrayList<String> repeatArray = new ArrayList<String>(0);
        ArrayList<Integer> recurrenceIndexes = new ArrayList<Integer>(0);

        repeatArray.add(r.getString(R.string.does_not_repeat));
        recurrenceIndexes.add(DOES_NOT_REPEAT);

        repeatArray.add(r.getString(R.string.daily));
        recurrenceIndexes.add(REPEATS_DAILY);

        if (isWeekdayEvent) {
            repeatArray.add(r.getString(R.string.every_weekday));
            recurrenceIndexes.add(REPEATS_EVERY_WEEKDAY);
        }

        String format = r.getString(R.string.weekly);
        repeatArray.add(String.format(format, time.format("%A")));
        recurrenceIndexes.add(REPEATS_WEEKLY_ON_DAY);

        // Calculate whether this is the 1st, 2nd, 3rd, 4th, or last appearance of the given day.
        int dayNumber = (time.monthDay - 1) / 7;
        format = r.getString(R.string.monthly_on_day_count);
        repeatArray.add(String.format(format, ordinals[dayNumber], days[time.weekDay]));
        recurrenceIndexes.add(REPEATS_MONTHLY_ON_DAY_COUNT);

        format = r.getString(R.string.monthly_on_day);
        repeatArray.add(String.format(format, time.monthDay));
        recurrenceIndexes.add(REPEATS_MONTHLY_ON_DAY);

        long when = time.toMillis(false);
        format = r.getString(R.string.yearly);
        int flags = 0;
        if (DateFormat.is24HourFormat(this)) {
            flags |= DateUtils.FORMAT_24HOUR;
        }
        repeatArray.add(String.format(format, DateUtils.formatDateTime(this, when, flags)));
        recurrenceIndexes.add(REPEATS_YEARLY);

        if (isCustomRecurrence) {
            repeatArray.add(r.getString(R.string.custom));
            recurrenceIndexes.add(REPEATS_CUSTOM);
        }
        mRecurrenceIndexes = recurrenceIndexes;

        int position = recurrenceIndexes.indexOf(DOES_NOT_REPEAT);
1424
        if (!TextUtils.isEmpty(mRrule)) {
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
            if (isCustomRecurrence) {
                position = recurrenceIndexes.indexOf(REPEATS_CUSTOM);
            } else {
                switch (mEventRecurrence.freq) {
                    case EventRecurrence.DAILY:
                        position = recurrenceIndexes.indexOf(REPEATS_DAILY);
                        break;
                    case EventRecurrence.WEEKLY:
                        if (mEventRecurrence.repeatsOnEveryWeekDay()) {
                            position = recurrenceIndexes.indexOf(REPEATS_EVERY_WEEKDAY);
                        } else {
                            position = recurrenceIndexes.indexOf(REPEATS_WEEKLY_ON_DAY);
                        }
                        break;
                    case EventRecurrence.MONTHLY:
                        if (mEventRecurrence.repeatsMonthlyOnDayCount()) {
                            position = recurrenceIndexes.indexOf(REPEATS_MONTHLY_ON_DAY_COUNT);
                        } else {
                            position = recurrenceIndexes.indexOf(REPEATS_MONTHLY_ON_DAY);
                        }
                        break;
                    case EventRecurrence.YEARLY:
                        position = recurrenceIndexes.indexOf(REPEATS_YEARLY);
                        break;
                }
            }
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, resource, repeatArray);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mRepeatsSpinner.setAdapter(adapter);
        mRepeatsSpinner.setSelection(position);
    }

    // Adds a reminder to the displayed list of reminders.
    // Returns true if successfully added reminder, false if no reminders can
    // be added.
    static boolean addReminder(Activity activity, View.OnClickListener listener,
            ArrayList<LinearLayout> items, ArrayList<Integer> values,
            ArrayList<String> labels, int minutes) {

        if (items.size() >= MAX_REMINDERS) {
            return false;
        }

        LayoutInflater inflater = activity.getLayoutInflater();
        LinearLayout parent = (LinearLayout) activity.findViewById(R.id.reminder_items_container);
        LinearLayout reminderItem = (LinearLayout) inflater.inflate(R.layout.edit_reminder_item, null);
        parent.addView(reminderItem);
1473

1474 1475 1476 1477 1478 1479 1480
        Spinner spinner = (Spinner) reminderItem.findViewById(R.id.reminder_value);
        Resources res = activity.getResources();
        spinner.setPrompt(res.getString(R.string.reminders_label));
        int resource = android.R.layout.simple_spinner_item;
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, resource, labels);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
1481

1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
        ImageButton reminderRemoveButton;
        reminderRemoveButton = (ImageButton) reminderItem.findViewById(R.id.reminder_remove);
        reminderRemoveButton.setOnClickListener(listener);

        int index = findMinutesInReminderList(values, minutes);
        spinner.setSelection(index);
        items.add(reminderItem);

        return true;
    }
1492

1493 1494 1495 1496 1497 1498
    static void addMinutesToList(Context context, ArrayList<Integer> values,
            ArrayList<String> labels, int minutes) {
        int index = values.indexOf(minutes);
        if (index != -1) {
            return;
        }
1499

1500 1501
        // The requested "minutes" does not exist in the list, so insert it
        // into the list.
1502

1503 1504 1505 1506 1507 1508 1509 1510 1511
        String label = constructReminderLabel(context, minutes, false);
        int len = values.size();
        for (int i = 0; i < len; i++) {
            if (minutes < values.get(i)) {
                values.add(i, minutes);
                labels.add(i, label);
                return;
            }
        }
1512

1513 1514 1515
        values.add(minutes);
        labels.add(len, label);
    }
1516

1517 1518
    /**
     * Finds the index of the given "minutes" in the "values" list.
1519
     *
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
     * @param values the list of minutes corresponding to the spinner choices
     * @param minutes the minutes to search for in the values list
     * @return the index of "minutes" in the "values" list
     */
    private static int findMinutesInReminderList(ArrayList<Integer> values, int minutes) {
        int index = values.indexOf(minutes);
        if (index == -1) {
            // This should never happen.
            Log.e("Cal", "Cannot find minutes (" + minutes + ") in list");
            return 0;
        }
        return index;
    }
1533

1534 1535 1536 1537 1538 1539 1540
    // Constructs a label given an arbitrary number of minutes.  For example,
    // if the given minutes is 63, then this returns the string "63 minutes".
    // As another example, if the given minutes is 120, then this returns
    // "2 hours".
    static String constructReminderLabel(Context context, int minutes, boolean abbrev) {
        Resources resources = context.getResources();
        int value, resId;
1541

1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
        if (minutes % 60 != 0) {
            value = minutes;
            if (abbrev) {
                resId = R.plurals.Nmins;
            } else {
                resId = R.plurals.Nminutes;
            }
        } else if (minutes % (24 * 60) != 0) {
            value = minutes / 60;
            resId = R.plurals.Nhours;
        } else {
            value = minutes / ( 24 * 60);
            resId = R.plurals.Ndays;
        }

        String format = resources.getQuantityString(resId, value);
        return String.format(format, value);
    }

    private void updateRemindersVisibility() {
        if (mReminderItems.size() == 0) {
            mRemindersSeparator.setVisibility(View.GONE);
            mRemindersContainer.setVisibility(View.GONE);
        } else {
            mRemindersSeparator.setVisibility(View.VISIBLE);
            mRemindersContainer.setVisibility(View.VISIBLE);
        }
    }

    private void setDate(TextView view, long millis) {
        int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
                DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_MONTH |
                DateUtils.FORMAT_ABBREV_WEEKDAY;
1575

1576 1577 1578
        mSB.setLength(0);
        String dateString = DateUtils.formatDateRange(this, mF, millis, millis, flags, mTimezone)
                .toString();
1579
        view.setText(dateString);
1580 1581 1582 1583 1584 1585 1586
    }

    private void setTime(TextView view, long millis) {
        int flags = DateUtils.FORMAT_SHOW_TIME;
        if (DateFormat.is24HourFormat(this)) {
            flags |= DateUtils.FORMAT_24HOUR;
        }
1587 1588 1589
        mSB.setLength(0);
        String timeString = DateUtils.formatDateRange(this, mF, millis, millis, flags, mTimezone)
                .toString();
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
        view.setText(timeString);
    }

    private void setTimezone(int i) {
        if (i < 0 || i > mTimezoneAdapter.getCount()) {
            return; // do nothing
        }
        TimezoneRow timezone = mTimezoneAdapter.getItem(i);
        mTimezoneButton.setText(timezone.toString());
        mTimezone = timezone.mId;
        mTimezoneAdapter.setCurrentTimezone(mTimezone);
1601
        mStartTime.timezone = mTimezone;
1602
        mStartTime.normalize(true);
1603
        mEndTime.timezone = mTimezone;
1604
        mEndTime.normalize(true);
1605 1606 1607 1608
    }

    // Saves the event.  Returns true if it is okay to exit this activity.
    private boolean save() {
1609
        boolean forceSaveReminders = false;
1610

1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
        // If we are creating a new event, then make sure we wait until the
        // query to fetch the list of calendars has finished.
        if (mEventCursor == null) {
            if (!mCalendarsQueryComplete) {
                // Wait for the calendars query to finish.
                if (mLoadingCalendarsDialog == null) {
                    // Create the progress dialog
                    mLoadingCalendarsDialog = ProgressDialog.show(this,
                            getText(R.string.loading_calendars_title),
                            getText(R.string.loading_calendars_message),
                            true, true, this);
                    mSaveAfterQueryComplete = true;
                }
                return false;
            }

1627 1628 1629 1630 1631 1632
            // Avoid creating a new event if the calendars cursor is empty or we clicked through
            // too quickly and no calendar was selected (blame the monkey)
            if (mCalendarsCursor == null || mCalendarsCursor.getCount() == 0 ||
                    mCalendarsSpinner.getSelectedItemId() == AdapterView.INVALID_ROW_ID) {
                Log.w("Cal", "The calendars table does not contain any calendars"
                        + " or no calendar was selected."
1633 1634 1635 1636 1637 1638 1639 1640
                        + " New event was not created.");
                return true;
            }
            Toast.makeText(this, R.string.creating_event, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show();
        }

1641 1642 1643
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        int eventIdIndex = -1;

1644 1645 1646
        ContentValues values = getContentValuesFromUi();
        Uri uri = mUri;

1647
        // save the timezone as a recent one
1648 1649 1650
        if (!mAllDayCheckBox.isChecked()) {
            mTimezoneAdapter.saveRecentTimezone(mTimezone);
        }
1651

1652 1653 1654 1655 1656 1657
        // Update the "hasAlarm" field for the event
        ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems,
                mReminderValues);
        int len = reminderMinutes.size();
        values.put(Events.HAS_ALARM, (len > 0) ? 1 : 0);

1658 1659 1660
        // For recurring events, we must make sure that we use duration rather
        // than dtend.
        if (uri == null) {
1661 1662
            // Add hasAttendeeData for a new event
            values.put(Events.HAS_ATTENDEE_DATA, 1);
1663 1664
            // Create new event with new contents
            addRecurrenceRule(values);
1665
            if (!TextUtils.isEmpty(mRrule)) {
1666 1667
                values.remove(Events.DTEND);
            }
1668 1669 1670
            eventIdIndex = ops.size();
            Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values);
            ops.add(b.build());
1671
            forceSaveReminders = true;
1672

1673
        } else if (TextUtils.isEmpty(mRrule)) {
1674 1675 1676
            // Modify contents of a non-repeating event
            addRecurrenceRule(values);
            checkTimeDependentFields(values);
1677 1678
            ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());

1679
        } else if (TextUtils.isEmpty(mInitialValues.getAsString(Events.RRULE))) {
1680 1681 1682 1683
            // This event was changed from a non-repeating event to a
            // repeating event.
            addRecurrenceRule(values);
            values.remove(Events.DTEND);
1684
            ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695

        } else if (mModification == MODIFY_SELECTED) {
            // Modify contents of the current instance of repeating event

            // Create a recurrence exception
            long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
            values.put(Events.ORIGINAL_EVENT, mEventCursor.getString(EVENT_INDEX_SYNC_ID));
            values.put(Events.ORIGINAL_INSTANCE_TIME, begin);
            boolean allDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0;
            values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0);

1696 1697 1698
            eventIdIndex = ops.size();
            Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values);
            ops.add(b.build());
1699
            forceSaveReminders = true;
1700 1701 1702 1703 1704

        } else if (mModification == MODIFY_ALL_FOLLOWING) {
            // Modify this instance and all future instances of repeating event
            addRecurrenceRule(values);

1705
            if (TextUtils.isEmpty(mRrule)) {
1706 1707 1708 1709 1710
                // We've changed a recurring event to a non-recurring event.
                // If the event we are editing is the first in the series,
                // then delete the whole series.  Otherwise, update the series
                // to end at the new start time.
                if (isFirstEventInSeries()) {
1711
                    ops.add(ContentProviderOperation.newDelete(uri).build());
1712 1713 1714
                } else {
                    // Update the current repeating event to end at the new
                    // start time.
1715
                    updatePastEvents(ops, uri);
1716
                }
1717 1718 1719
                eventIdIndex = ops.size();
                ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values)
                        .build());
1720 1721 1722 1723
            } else {
                if (isFirstEventInSeries()) {
                    checkTimeDependentFields(values);
                    values.remove(Events.DTEND);
1724 1725
                    Builder b = ContentProviderOperation.newUpdate(uri).withValues(values);
                    ops.add(b.build());
1726 1727 1728
                } else {
                    // Update the current repeating event to end at the new
                    // start time.
1729
                    updatePastEvents(ops, uri);
1730 1731 1732

                    // Create a new event with the user-modified fields
                    values.remove(Events.DTEND);
1733 1734 1735
                    eventIdIndex = ops.size();
                    ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(
                            values).build());
1736 1737
                }
            }
1738
            forceSaveReminders = true;
1739 1740

        } else if (mModification == MODIFY_ALL) {
1741

1742 1743
            // Modify all instances of repeating event
            addRecurrenceRule(values);
1744

1745
            if (TextUtils.isEmpty(mRrule)) {
1746 1747 1748
                // We've changed a recurring event to a non-recurring event.
                // Delete the whole series and replace it with a new
                // non-recurring event.
1749 1750 1751 1752 1753
                ops.add(ContentProviderOperation.newDelete(uri).build());

                eventIdIndex = ops.size();
                ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values)
                        .build());
1754
                forceSaveReminders = true;
1755 1756 1757
            } else {
                checkTimeDependentFields(values);
                values.remove(Events.DTEND);
1758
                ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
1759 1760 1761
            }
        }

1762 1763 1764 1765
        // New Event or New Exception to an existing event
        boolean newEvent = (eventIdIndex != -1);

        if (newEvent) {
1766 1767 1768
            saveRemindersWithBackRef(ops, eventIdIndex, reminderMinutes, mOriginalMinutes,
                    forceSaveReminders);
        } else if (uri != null) {
1769
            long eventId = ContentUris.parseId(uri);
1770
            saveReminders(ops, eventId, reminderMinutes, mOriginalMinutes,
1771
                    forceSaveReminders);
1772
        }
1773

1774 1775 1776
        Builder b;

        // New event/instance - Set Organizer's response as yes
1777
        if (mHasAttendeeData && newEvent) {
1778 1779
            values.clear();
            int calendarCursorPosition = mCalendarsSpinner.getSelectedItemPosition();
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790

            // Save the default calendar for new events
            if (mCalendarsCursor != null) {
                if (mCalendarsCursor.moveToPosition(calendarCursorPosition)) {
                    String defaultCalendar = mCalendarsCursor
                            .getString(CALENDARS_INDEX_OWNER_ACCOUNT);
                    Utils.setSharedPreference(this,
                            CalendarPreferenceActivity.KEY_DEFAULT_CALENDAR, defaultCalendar);
                }
            }

Ken Shirriff's avatar
Ken Shirriff committed
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
            String ownerEmail = mOwnerAccount;
            // Just in case mOwnerAccount is null, try to get owner from mCalendarsCursor
            if (ownerEmail == null && mCalendarsCursor != null &&
                    mCalendarsCursor.moveToPosition(calendarCursorPosition)) {
                ownerEmail = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
            }
            if (ownerEmail != null) {
                values.put(Attendees.ATTENDEE_EMAIL, ownerEmail);
                values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER);
                values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);
1801 1802 1803 1804 1805 1806 1807
                int initialStatus = Attendees.ATTENDEE_STATUS_ACCEPTED;

                // Don't accept for secondary calendars
                if (ownerEmail.endsWith("calendar.google.com")) {
                    initialStatus = Attendees.ATTENDEE_STATUS_NONE;
                }
                values.put(Attendees.ATTENDEE_STATUS, initialStatus);
Ken Shirriff's avatar
Ken Shirriff committed
1808 1809 1810 1811 1812

                b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
                        .withValues(values);
                b.withValueBackReference(Reminders.EVENT_ID, eventIdIndex);
                ops.add(b.build());
1813 1814 1815
            }
        }

1816 1817
        // TODO: is this the right test?  this currently checks if this is
        // a new event or an existing event.  or is this a paranoia check?
1818
        if (mHasAttendeeData && (newEvent || uri != null)) {
1819
            Editable attendeesText = mAttendeesList.getText();
1820 1821
            // Hit the content provider only if this is a new event or the user has changed it
            if (newEvent || !mOriginalAttendees.equals(attendeesText.toString())) {
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
                // figure out which attendees need to be added and which ones
                // need to be deleted.  use a linked hash set, so we maintain
                // order (but also remove duplicates).
                LinkedHashSet<Rfc822Token> newAttendees = getAddressesFromList(mAttendeesList);

                // the eventId is only used if eventIdIndex is -1.
                // TODO: clean up this code.
                long eventId = uri != null ? ContentUris.parseId(uri) : -1;

                // only compute deltas if this is an existing event.
                // new events (being inserted into the Events table) won't
                // have any existing attendees.
1834
                if (!newEvent) {
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
                    HashSet<Rfc822Token> removedAttendees = new HashSet<Rfc822Token>();
                    HashSet<Rfc822Token> originalAttendees = new HashSet<Rfc822Token>();
                    Rfc822Tokenizer.tokenize(mOriginalAttendees, originalAttendees);
                    for (Rfc822Token originalAttendee : originalAttendees) {
                        if (newAttendees.contains(originalAttendee)) {
                            // existing attendee.  remove from new attendees set.
                            newAttendees.remove(originalAttendee);
                        } else {
                            // no longer in attendees.  mark as removed.
                            removedAttendees.add(originalAttendee);
                        }
                    }

                    // delete removed attendees
                    b = ContentProviderOperation.newDelete(Attendees.CONTENT_URI);

                    String[] args = new String[removedAttendees.size() + 1];
                    args[0] = Long.toString(eventId);
                    int i = 1;
                    StringBuilder deleteWhere = new StringBuilder(ATTENDEES_DELETE_PREFIX);
                    for (Rfc822Token removedAttendee : removedAttendees) {
                        if (i > 1) {
                            deleteWhere.append(",");
                        }
                        deleteWhere.append("?");
                        args[i++] = removedAttendee.getAddress();
                    }
                    deleteWhere.append(")");
                    b.withSelection(deleteWhere.toString(), args);
                    ops.add(b.build());
1865 1866
                }

1867 1868 1869
                if (newAttendees.size() > 0) {
                    // Insert the new attendees
                    for (Rfc822Token attendee : newAttendees) {
1870 1871 1872 1873 1874 1875 1876
                        values.clear();
                        values.put(Attendees.ATTENDEE_NAME, attendee.getName());
                        values.put(Attendees.ATTENDEE_EMAIL, attendee.getAddress());
                        values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE);
                        values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);
                        values.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_NONE);

1877
                        if (newEvent) {
1878 1879
                            b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
                                    .withValues(values);
1880
                            b.withValueBackReference(Attendees.EVENT_ID, eventIdIndex);
1881 1882 1883 1884 1885 1886
                        } else {
                            values.put(Attendees.EVENT_ID, eventId);
                            b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
                                    .withValues(values);
                        }
                        ops.add(b.build());
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
                    }
                }
            }
        }

        try {
            // TODO Move this to background thread
            ContentProviderResult[] results =
                getContentResolver().applyBatch(android.provider.Calendar.AUTHORITY, ops);
            if (DEBUG) {
1897 1898 1899
                for (int i = 0; i < results.length; i++) {
                    Log.v(TAG, "results = " + results[i].toString());
                }
1900 1901
            }
        } catch (RemoteException e) {
1902
            Log.w(TAG, "Ignoring unexpected remote exception", e);
1903
        } catch (OperationApplicationException e) {
1904
            Log.w(TAG, "Ignoring unexpected exception", e);
1905 1906
        }

1907 1908 1909 1910 1911 1912 1913 1914 1915
        return true;
    }

    private boolean isFirstEventInSeries() {
        int dtStart = mEventCursor.getColumnIndexOrThrow(Events.DTSTART);
        long start = mEventCursor.getLong(dtStart);
        return start == mStartTime.toMillis(true);
    }

1916
    private void updatePastEvents(ArrayList<ContentProviderOperation> ops, Uri uri) {
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
        long oldStartMillis = mEventCursor.getLong(EVENT_INDEX_DTSTART);
        String oldDuration = mEventCursor.getString(EVENT_INDEX_DURATION);
        boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
        String oldRrule = mEventCursor.getString(EVENT_INDEX_RRULE);
        mEventRecurrence.parse(oldRrule);

        Time untilTime = new Time();
        long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
        ContentValues oldValues = new ContentValues();

        // The "until" time must be in UTC time in order for Google calendar
        // to display it properly.  For all-day events, the "until" time string
        // must include just the date field, and not the time field.  The
        // repeating events repeat up to and including the "until" time.
        untilTime.timezone = Time.TIMEZONE_UTC;
1932

1933 1934
        // Subtract one second from the old begin time to get the new
        // "until" time.
1935
        untilTime.set(begin - 1000);  // subtract one second (1000 millis)
1936 1937 1938 1939 1940 1941
        if (allDay) {
            untilTime.hour = 0;
            untilTime.minute = 0;
            untilTime.second = 0;
            untilTime.allDay = true;
            untilTime.normalize(false);
1942

1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
            // For all-day events, the duration must be in days, not seconds.
            // Otherwise, Google Calendar will (mistakenly) change this event
            // into a non-all-day event.
            int len = oldDuration.length();
            if (oldDuration.charAt(0) == 'P' && oldDuration.charAt(len - 1) == 'S') {
                int seconds = Integer.parseInt(oldDuration.substring(1, len - 1));
                int days = (seconds + DAY_IN_SECONDS - 1) / DAY_IN_SECONDS;
                oldDuration = "P" + days + "D";
            }
        }
        mEventRecurrence.until = untilTime.format2445();

        oldValues.put(Events.DTSTART, oldStartMillis);
        oldValues.put(Events.DURATION, oldDuration);
        oldValues.put(Events.RRULE, mEventRecurrence.toString());
1958 1959
        Builder b = ContentProviderOperation.newUpdate(uri).withValues(oldValues);
        ops.add(b.build());
1960 1961 1962 1963 1964 1965 1966 1967
    }

    private void checkTimeDependentFields(ContentValues values) {
        long oldBegin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
        long oldEnd = mInitialValues.getAsLong(EVENT_END_TIME);
        boolean oldAllDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0;
        String oldRrule = mInitialValues.getAsString(Events.RRULE);
        String oldTimezone = mInitialValues.getAsString(Events.EVENT_TIMEZONE);
1968

1969 1970 1971 1972 1973
        long newBegin = values.getAsLong(Events.DTSTART);
        long newEnd = values.getAsLong(Events.DTEND);
        boolean newAllDay = values.getAsInteger(Events.ALL_DAY) != 0;
        String newRrule = values.getAsString(Events.RRULE);
        String newTimezone = values.getAsString(Events.EVENT_TIMEZONE);
1974

1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
        // If none of the time-dependent fields changed, then remove them.
        if (oldBegin == newBegin && oldEnd == newEnd && oldAllDay == newAllDay
                && TextUtils.equals(oldRrule, newRrule)
                && TextUtils.equals(oldTimezone, newTimezone)) {
            values.remove(Events.DTSTART);
            values.remove(Events.DTEND);
            values.remove(Events.DURATION);
            values.remove(Events.ALL_DAY);
            values.remove(Events.RRULE);
            values.remove(Events.EVENT_TIMEZONE);
            return;
        }

1988
        if (TextUtils.isEmpty(oldRrule) || TextUtils.isEmpty(newRrule)) {
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
            return;
        }

        // If we are modifying all events then we need to set DTSTART to the
        // start time of the first event in the series, not the current
        // date and time.  If the start time of the event was changed
        // (from, say, 3pm to 4pm), then we want to add the time difference
        // to the start time of the first event in the series (the DTSTART
        // value).  If we are modifying one instance or all following instances,
        // then we leave the DTSTART field alone.
        if (mModification == MODIFY_ALL) {
            long oldStartMillis = mEventCursor.getLong(EVENT_INDEX_DTSTART);
            if (oldBegin != newBegin) {
                // The user changed the start time of this event
                long offset = newBegin - oldBegin;
                oldStartMillis += offset;
            }
            values.put(Events.DTSTART, oldStartMillis);
        }
    }
2009

2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
    static ArrayList<Integer> reminderItemsToMinutes(ArrayList<LinearLayout> reminderItems,
            ArrayList<Integer> reminderValues) {
        int len = reminderItems.size();
        ArrayList<Integer> reminderMinutes = new ArrayList<Integer>(len);
        for (int index = 0; index < len; index++) {
            LinearLayout layout = reminderItems.get(index);
            Spinner spinner = (Spinner) layout.findViewById(R.id.reminder_value);
            int minutes = reminderValues.get(spinner.getSelectedItemPosition());
            reminderMinutes.add(minutes);
        }
        return reminderMinutes;
    }

    /**
     * Saves the reminders, if they changed.  Returns true if the database
     * was updated.
2026 2027
     *
     * @param ops the array of ContentProviderOperations
2028 2029 2030
     * @param eventId the id of the event whose reminders are being updated
     * @param reminderMinutes the array of reminders set by the user
     * @param originalMinutes the original array of reminders
2031 2032
     * @param forceSave if true, then save the reminders even if they didn't
     *   change
2033 2034
     * @return true if the database was updated
     */
2035
    static boolean saveReminders(ArrayList<ContentProviderOperation> ops, long eventId,
2036 2037
            ArrayList<Integer> reminderMinutes, ArrayList<Integer> originalMinutes,
            boolean forceSave) {
2038
        // If the reminders have not changed, then don't update the database
2039
        if (reminderMinutes.equals(originalMinutes) && !forceSave) {
2040 2041 2042
            return false;
        }

2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
        // Delete all the existing reminders for this event
        String where = Reminders.EVENT_ID + "=?";
        String[] args = new String[] { Long.toString(eventId) };
        Builder b = ContentProviderOperation.newDelete(Reminders.CONTENT_URI);
        b.withSelection(where, args);
        ops.add(b.build());

        ContentValues values = new ContentValues();
        int len = reminderMinutes.size();

        // Insert the new reminders, if any
        for (int i = 0; i < len; i++) {
            int minutes = reminderMinutes.get(i);

            values.clear();
            values.put(Reminders.MINUTES, minutes);
            values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
            values.put(Reminders.EVENT_ID, eventId);
            b = ContentProviderOperation.newInsert(Reminders.CONTENT_URI).withValues(values);
            ops.add(b.build());
        }
2064 2065
        return true;
    }
2066

2067 2068 2069 2070 2071 2072
    static boolean saveRemindersWithBackRef(ArrayList<ContentProviderOperation> ops,
            int eventIdIndex, ArrayList<Integer> reminderMinutes,
            ArrayList<Integer> originalMinutes, boolean forceSave) {
        // If the reminders have not changed, then don't update the database
        if (reminderMinutes.equals(originalMinutes) && !forceSave) {
            return false;
2073
        }
2074

2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
        // Delete all the existing reminders for this event
        Builder b = ContentProviderOperation.newDelete(Reminders.CONTENT_URI);
        b.withSelection(Reminders.EVENT_ID + "=?", new String[1]);
        b.withSelectionBackReference(0, eventIdIndex);
        ops.add(b.build());

        ContentValues values = new ContentValues();
        int len = reminderMinutes.size();

        // Insert the new reminders, if any
        for (int i = 0; i < len; i++) {
            int minutes = reminderMinutes.get(i);

            values.clear();
            values.put(Reminders.MINUTES, minutes);
            values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
            b = ContentProviderOperation.newInsert(Reminders.CONTENT_URI).withValues(values);
            b.withValueBackReference(Reminders.EVENT_ID, eventIdIndex);
            ops.add(b.build());
        }
2095 2096 2097 2098 2099 2100
        return true;
    }

    private void addRecurrenceRule(ContentValues values) {
        updateRecurrenceRule();

2101
        if (TextUtils.isEmpty(mRrule)) {
2102 2103
            return;
        }
2104

2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
        values.put(Events.RRULE, mRrule);
        long end = mEndTime.toMillis(true /* ignore dst */);
        long start = mStartTime.toMillis(true /* ignore dst */);
        String duration;

        boolean isAllDay = mAllDayCheckBox.isChecked();
        if (isAllDay) {
            long days = (end - start + DateUtils.DAY_IN_MILLIS - 1) / DateUtils.DAY_IN_MILLIS;
            duration = "P" + days + "D";
        } else {
            long seconds = (end - start) / DateUtils.SECOND_IN_MILLIS;
            duration = "P" + seconds + "S";
        }
        values.put(Events.DURATION, duration);
    }

2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
    private void clearRecurrence() {
        mEventRecurrence.byday = null;
        mEventRecurrence.bydayNum = null;
        mEventRecurrence.bydayCount = 0;
        mEventRecurrence.bymonth = null;
        mEventRecurrence.bymonthCount = 0;
        mEventRecurrence.bymonthday = null;
        mEventRecurrence.bymonthdayCount = 0;
    }

2131 2132 2133
    private void updateRecurrenceRule() {
        int position = mRepeatsSpinner.getSelectedItemPosition();
        int selection = mRecurrenceIndexes.get(position);
2134 2135
        // Make sure we don't have any leftover data from the previous setting
        clearRecurrence();
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208

        if (selection == DOES_NOT_REPEAT) {
            mRrule = null;
            return;
        } else if (selection == REPEATS_CUSTOM) {
            // Keep custom recurrence as before.
            return;
        } else if (selection == REPEATS_DAILY) {
            mEventRecurrence.freq = EventRecurrence.DAILY;
        } else if (selection == REPEATS_EVERY_WEEKDAY) {
            mEventRecurrence.freq = EventRecurrence.WEEKLY;
            int dayCount = 5;
            int[] byday = new int[dayCount];
            int[] bydayNum = new int[dayCount];

            byday[0] = EventRecurrence.MO;
            byday[1] = EventRecurrence.TU;
            byday[2] = EventRecurrence.WE;
            byday[3] = EventRecurrence.TH;
            byday[4] = EventRecurrence.FR;
            for (int day = 0; day < dayCount; day++) {
                bydayNum[day] = 0;
            }

            mEventRecurrence.byday = byday;
            mEventRecurrence.bydayNum = bydayNum;
            mEventRecurrence.bydayCount = dayCount;
        } else if (selection == REPEATS_WEEKLY_ON_DAY) {
            mEventRecurrence.freq = EventRecurrence.WEEKLY;
            int[] days = new int[1];
            int dayCount = 1;
            int[] dayNum = new int[dayCount];

            days[0] = EventRecurrence.timeDay2Day(mStartTime.weekDay);
            // not sure why this needs to be zero, but set it for now.
            dayNum[0] = 0;

            mEventRecurrence.byday = days;
            mEventRecurrence.bydayNum = dayNum;
            mEventRecurrence.bydayCount = dayCount;
        } else if (selection == REPEATS_MONTHLY_ON_DAY) {
            mEventRecurrence.freq = EventRecurrence.MONTHLY;
            mEventRecurrence.bydayCount = 0;
            mEventRecurrence.bymonthdayCount = 1;
            int[] bymonthday = new int[1];
            bymonthday[0] = mStartTime.monthDay;
            mEventRecurrence.bymonthday = bymonthday;
        } else if (selection == REPEATS_MONTHLY_ON_DAY_COUNT) {
            mEventRecurrence.freq = EventRecurrence.MONTHLY;
            mEventRecurrence.bydayCount = 1;
            mEventRecurrence.bymonthdayCount = 0;

            int[] byday = new int[1];
            int[] bydayNum = new int[1];
            // Compute the week number (for example, the "2nd" Monday)
            int dayCount = 1 + ((mStartTime.monthDay - 1) / 7);
            if (dayCount == 5) {
                dayCount = -1;
            }
            bydayNum[0] = dayCount;
            byday[0] = EventRecurrence.timeDay2Day(mStartTime.weekDay);
            mEventRecurrence.byday = byday;
            mEventRecurrence.bydayNum = bydayNum;
        } else if (selection == REPEATS_YEARLY) {
            mEventRecurrence.freq = EventRecurrence.YEARLY;
        }

        // Set the week start day.
        mEventRecurrence.wkst = EventRecurrence.calendarDay2Day(mFirstDayOfWeek);
        mRrule = mEventRecurrence.toString();
    }

    private ContentValues getContentValuesFromUi() {
2209
        String title = mTitleTextView.getText().toString().trim();
2210
        boolean isAllDay = mAllDayCheckBox.isChecked();
2211 2212
        String location = mLocationTextView.getText().toString().trim();
        String description = mDescriptionTextView.getText().toString().trim();
2213 2214 2215 2216 2217 2218 2219 2220 2221

        ContentValues values = new ContentValues();

        long startMillis;
        long endMillis;
        long calendarId;
        if (isAllDay) {
            // Reset start and end time, increment the monthDay by 1, and set
            // the timezone to UTC, as required for all-day events.
2222
            mTimezone = Time.TIMEZONE_UTC;
2223 2224 2225
            mStartTime.hour = 0;
            mStartTime.minute = 0;
            mStartTime.second = 0;
2226
            mStartTime.timezone = mTimezone;
2227 2228 2229 2230 2231 2232
            startMillis = mStartTime.normalize(true);

            mEndTime.hour = 0;
            mEndTime.minute = 0;
            mEndTime.second = 0;
            mEndTime.monthDay++;
2233
            mEndTime.timezone = mTimezone;
2234
            endMillis = mEndTime.normalize(true);
2235

2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
            if (mEventCursor == null) {
                // This is a new event
                calendarId = mCalendarsSpinner.getSelectedItemId();
            } else {
                calendarId = mInitialValues.getAsLong(Events.CALENDAR_ID);
            }
        } else {
            if (mEventCursor != null) {
                calendarId = mInitialValues.getAsLong(Events.CALENDAR_ID);
            } else {
                // This is a new event
                calendarId = mCalendarsSpinner.getSelectedItemId();
            }
2249 2250 2251 2252 2253
            // mTimezone is set automatically in onClick
            mStartTime.timezone = mTimezone;
            mEndTime.timezone = mTimezone;
            startMillis = mStartTime.toMillis(true);
            endMillis = mEndTime.toMillis(true);
2254 2255 2256
        }

        values.put(Events.CALENDAR_ID, calendarId);
2257
        values.put(Events.EVENT_TIMEZONE, mTimezone);
2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
        values.put(Events.TITLE, title);
        values.put(Events.ALL_DAY, isAllDay ? 1 : 0);
        values.put(Events.DTSTART, startMillis);
        values.put(Events.DTEND, endMillis);
        values.put(Events.DESCRIPTION, description);
        values.put(Events.EVENT_LOCATION, location);
        values.put(Events.TRANSPARENCY, mAvailabilitySpinner.getSelectedItemPosition());

        int visibility = mVisibilitySpinner.getSelectedItemPosition();
        if (visibility > 0) {
            // For now we the array contains the values 0, 2, and 3. We add one to match.
            visibility++;
        }
        values.put(Events.VISIBILITY, visibility);

        return values;
    }

    private boolean isEmpty() {
2277
        String title = mTitleTextView.getText().toString().trim();
2278 2279 2280 2281
        if (title.length() > 0) {
            return false;
        }

2282
        String location = mLocationTextView.getText().toString().trim();
2283 2284 2285 2286
        if (location.length() > 0) {
            return false;
        }

2287
        String description = mDescriptionTextView.getText().toString().trim();
2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
        if (description.length() > 0) {
            return false;
        }

        return true;
    }

    private boolean isCustomRecurrence() {

        if (mEventRecurrence.until != null || mEventRecurrence.interval != 0) {
            return true;
        }

        if (mEventRecurrence.freq == 0) {
            return false;
        }

        switch (mEventRecurrence.freq) {
        case EventRecurrence.DAILY:
            return false;
        case EventRecurrence.WEEKLY:
            if (mEventRecurrence.repeatsOnEveryWeekDay() && isWeekdayEvent()) {
                return false;
            } else if (mEventRecurrence.bydayCount == 1) {
                return false;
            }
            break;
        case EventRecurrence.MONTHLY:
            if (mEventRecurrence.repeatsMonthlyOnDayCount()) {
                return false;
            } else if (mEventRecurrence.bydayCount == 0 && mEventRecurrence.bymonthdayCount == 1) {
                return false;
            }
            break;
        case EventRecurrence.YEARLY:
            return false;
        }

        return true;
    }

    private boolean isWeekdayEvent() {
        if (mStartTime.weekDay != Time.SUNDAY && mStartTime.weekDay != Time.SATURDAY) {
            return true;
        }
        return false;
    }
}