EditEventView.java 71.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (C) 2010 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.
 */

Erik's avatar
Erik committed
17
package com.android.calendar.event;
18

Erik's avatar
Erik committed
19
import com.android.calendar.CalendarEventModel;
Erik's avatar
Erik committed
20
import com.android.calendar.CalendarEventModel.Attendee;
21
import com.android.calendar.CalendarEventModel.ReminderEntry;
Erik's avatar
Erik committed
22
import com.android.calendar.EmailAddressAdapter;
23
import com.android.calendar.EventInfoFragment;
24
import com.android.calendar.GeneralPreferences;
Erik's avatar
Erik committed
25
import com.android.calendar.R;
26
import com.android.calendar.RecipientAdapter;
Erik's avatar
Erik committed
27
import com.android.calendar.TimezoneAdapter;
28
import com.android.calendar.TimezoneAdapter.TimezoneRow;
Erik's avatar
Erik committed
29
import com.android.calendar.Utils;
Erik's avatar
Erik committed
30
import com.android.calendar.event.EditEventHelper.EditDoneRunnable;
31
import com.android.calendarcommon.EventRecurrence;
32 33
import com.android.common.Rfc822InputFilter;
import com.android.common.Rfc822Validator;
34 35 36 37
import com.android.ex.chips.AccountSpecifier;
import com.android.ex.chips.BaseRecipientAdapter;
import com.android.ex.chips.ChipsUtil;
import com.android.ex.chips.RecipientEditTextView;
38

Erik's avatar
Erik committed
39
import android.app.Activity;
40 41
import android.app.AlertDialog;
import android.app.DatePickerDialog;
42
import android.app.DatePickerDialog.OnDateSetListener;
Erik's avatar
Erik committed
43
import android.app.ProgressDialog;
44
import android.app.Service;
45 46 47 48
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
49
import android.content.Intent;
50 51 52
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
53 54
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
55
import android.graphics.drawable.Drawable;
56 57 58
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Reminders;
59
import android.provider.Settings;
60 61 62 63 64 65
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.text.util.Rfc822Tokenizer;
66
import android.util.Log;
67
import android.view.LayoutInflater;
68
import android.view.View;
69 70 71
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
Erik's avatar
Erik committed
72 73
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
74 75
import android.widget.ArrayAdapter;
import android.widget.Button;
76
import android.widget.CalendarView;
77 78 79 80 81
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.MultiAutoCompleteTextView;
82
import android.widget.RadioButton;
83
import android.widget.RadioGroup;
84 85 86 87 88 89 90 91 92
import android.widget.ResourceCursorAdapter;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
93
import java.util.Formatter;
Erik's avatar
Erik committed
94
import java.util.HashMap;
95
import java.util.Locale;
96
import java.util.TimeZone;
97 98

public class EditEventView implements View.OnClickListener, DialogInterface.OnCancelListener,
99
        DialogInterface.OnClickListener, OnItemSelectedListener {
100
    private static final String TAG = "EditEvent";
101
    private static final String GOOGLE_SECONDARY_CALENDAR = "calendar.google.com";
102
    private static final String PERIOD_SPACE = ". ";
Erik's avatar
Erik committed
103

104 105 106
    ArrayList<View> mEditOnlyList = new ArrayList<View>();
    ArrayList<View> mEditViewList = new ArrayList<View>();
    ArrayList<View> mViewOnlyList = new ArrayList<View>();
107 108 109 110 111 112
    TextView mLoadingMessage;
    ScrollView mScrollView;
    Button mStartDateButton;
    Button mEndDateButton;
    Button mStartTimeButton;
    Button mEndTimeButton;
113
    Button mTimezoneButton;
Michael Chan's avatar
Michael Chan committed
114
    View mTimezoneRow;
115 116 117 118
    TextView mStartTimeHome;
    TextView mStartDateHome;
    TextView mEndTimeHome;
    TextView mEndDateHome;
119 120 121
    CheckBox mAllDayCheckBox;
    Spinner mCalendarsSpinner;
    Spinner mRepeatsSpinner;
122 123
    Spinner mAvailabilitySpinner;
    Spinner mAccessLevelSpinner;
124
    RadioGroup mResponseRadioGroup;
125 126 127
    TextView mTitleTextView;
    TextView mLocationTextView;
    TextView mDescriptionTextView;
128
    TextView mWhenView;
129
    TextView mTimezoneTextView;
130
    TextView mTimezoneLabel;
131 132
    LinearLayout mRemindersContainer;
    MultiAutoCompleteTextView mAttendeesList;
133
    View mCalendarSelectorGroup;
134
    View mCalendarSelectorWrapper;
135
    View mCalendarStaticGroup;
Erik's avatar
Erik committed
136 137
    View mLocationGroup;
    View mDescriptionGroup;
138 139 140 141
    View mRemindersGroup;
    View mResponseGroup;
    View mOrganizerGroup;
    View mAttendeesGroup;
142 143
    View mStartHomeGroup;
    View mEndHomeGroup;
144

Erik's avatar
Erik committed
145
    private int[] mOriginalPadding = new int[4];
146
    private int[] mOriginalSpinnerPadding = new int[4];
147

148
    private boolean mIsMultipane;
149 150
    private ProgressDialog mLoadingCalendarsDialog;
    private AlertDialog mNoCalendarsDialog;
151
    private AlertDialog mTimezoneDialog;
Erik's avatar
Erik committed
152 153
    private Activity mActivity;
    private EditDoneRunnable mDone;
154 155 156
    private View mView;
    private CalendarEventModel mModel;
    private Cursor mCalendarsCursor;
157
    private AccountSpecifier mAddressAdapter;
158
    private Rfc822Validator mEmailValidator;
159
    private TimezoneAdapter mTimezoneAdapter;
160 161

    private ArrayList<Integer> mRecurrenceIndexes = new ArrayList<Integer>(0);
162 163 164 165 166 167 168 169

    /**
     * Contents of the "minutes" spinner.  This has default values from the XML file, augmented
     * with any additional values that were already associated with the event.
     */
    private ArrayList<Integer> mReminderMinuteValues;
    private ArrayList<String> mReminderMinuteLabels;

170 171 172 173 174 175 176 177
    /**
     * Contents of the "methods" spinner.  The "values" list specifies the method constant
     * (e.g. {@link Reminders#METHOD_ALERT}) associated with the labels.  Any methods that
     * aren't allowed by the Calendar will be removed.
     */
    private ArrayList<Integer> mReminderMethodValues;
    private ArrayList<String> mReminderMethodLabels;

178 179 180 181 182 183 184 185
    /**
     * Contents of the "availability" spinner. The "values" list specifies the
     * type constant (e.g. {@link Events#AVAILABILITY_BUSY}) associated with the
     * labels. Any types that aren't allowed by the Calendar will be removed.
     */
    private ArrayList<Integer> mAvailabilityValues;
    private ArrayList<String> mAvailabilityLabels;

186 187 188 189 190 191
    private int mDefaultReminderMinutes;

    private boolean mSaveAfterQueryComplete = false;

    private Time mStartTime;
    private Time mEndTime;
192
    private String mTimezone;
193
    private boolean mAllDay = false;
194 195 196 197 198
    private int mModification = EditEventHelper.MODIFY_UNINITIALIZED;

    private EventRecurrence mEventRecurrence = new EventRecurrence();

    private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0);
199
    private ArrayList<ReminderEntry> mUnsupportedReminders = new ArrayList<ReminderEntry>();
200

201 202 203
    private static StringBuilder mSB = new StringBuilder(50);
    private static Formatter mF = new Formatter(mSB, Locale.getDefault());

204 205 206 207 208 209 210 211
    /* This class is used to update the time buttons. */
    private class TimeListener implements OnTimeSetListener {
        private View mView;

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

212
        @Override
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
        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;

                // Move to the start time if the end time is before the start
                // time.
                if (endTime.before(startTime)) {
                    endTime.monthDay = startTime.monthDay + 1;
                }
            }

            endMillis = endTime.normalize(true);

            setDate(mEndDateButton, endMillis);
            setTime(mStartTimeButton, startMillis);
            setTime(mEndTimeButton, endMillis);
253
            updateHomeTime();
254 255 256 257 258 259 260 261 262 263
        }
    }

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

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

264
        @Override
265
        public void onClick(View v) {
RoboErik's avatar
RoboErik committed
266 267 268 269
            TimePickerDialog tp = new TimePickerDialog(mActivity, new TimeListener(v), mTime.hour,
                    mTime.minute, DateFormat.is24HourFormat(mActivity));
            tp.setCanceledOnTouchOutside(true);
            tp.show();
270 271 272 273 274 275 276 277 278 279
        }
    }

    private class DateListener implements OnDateSetListener {
        View mView;

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

280
        @Override
281
        public void onDateSet(DatePicker view, int year, int month, int monthDay) {
282
            Log.d(TAG, "onDateSet: " + year +  " " + month +  " " + monthDay);
283 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 320 321 322 323 324 325 326 327 328 329 330
            // 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
331
            updateHomeTime();
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
        }
    }

    // Fills in the date and time fields
    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));
    }

352 353 354 355 356 357 358 359 360 361 362 363
    private void populateTimezone() {
        mTimezoneButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimezoneDialog();
            }
        });
        setTimezone(mTimezoneAdapter.getRowById(mTimezone));
    }

    private void showTimezoneDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
364 365
        final Context alertDialogContext = builder.getContext();
        mTimezoneAdapter = new TimezoneAdapter(alertDialogContext, mTimezone);
366 367 368 369
        builder.setTitle(R.string.timezone_label);
        builder.setSingleChoiceItems(
                mTimezoneAdapter, mTimezoneAdapter.getRowById(mTimezone), this);
        mTimezoneDialog = builder.create();
370 371 372 373 374 375 376 377

        LayoutInflater layoutInflater = (LayoutInflater) alertDialogContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final TextView timezoneFooterView = (TextView) layoutInflater.inflate(
                R.layout.timezone_footer, null);

        timezoneFooterView.setText(mActivity.getString(R.string.edit_event_show_all) + " >");
        timezoneFooterView.setOnClickListener(new View.OnClickListener() {
378 379
            @Override
            public void onClick(View v) {
380
                mTimezoneDialog.getListView().removeFooterView(timezoneFooterView);
381 382 383 384 385 386 387 388 389 390 391 392 393
                mTimezoneAdapter.showAllTimezones();
                final int row = mTimezoneAdapter.getRowById(mTimezone);
                // we need to post the selection changes to have them have
                // any effect
                mTimezoneDialog.getListView().post(new Runnable() {
                    @Override
                    public void run() {
                        mTimezoneDialog.getListView().setItemChecked(row, true);
                        mTimezoneDialog.getListView().setSelection(row);
                    }
                });
            }
        });
394
        mTimezoneDialog.getListView().addFooterView(timezoneFooterView);
RoboErik's avatar
RoboErik committed
395
        mTimezoneDialog.setCanceledOnTouchOutside(true);
396 397 398
        mTimezoneDialog.show();
    }

399 400 401 402 403 404 405 406 407 408 409
    private void populateRepeats() {
        Time time = mStartTime;
        Resources r = mActivity.getResources();

        String[] days = new String[] {
                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),
410
                DateUtils.getDayOfWeekString(Calendar.SATURDAY, DateUtils.LENGTH_MEDIUM), };
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
        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(EditEventHelper.DOES_NOT_REPEAT);

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

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

        String format = r.getString(R.string.weekly);
        repeatArray.add(String.format(format, time.format("%A")));
        recurrenceIndexes.add(EditEventHelper.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(EditEventHelper.REPEATS_MONTHLY_ON_DAY_COUNT);

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

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

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

        int position = recurrenceIndexes.indexOf(EditEventHelper.DOES_NOT_REPEAT);
464
        if (!TextUtils.isEmpty(mModel.mRrule)) {
465 466 467 468 469 470 471 472 473
            if (isCustomRecurrence) {
                position = recurrenceIndexes.indexOf(EditEventHelper.REPEATS_CUSTOM);
            } else {
                switch (mEventRecurrence.freq) {
                    case EventRecurrence.DAILY:
                        position = recurrenceIndexes.indexOf(EditEventHelper.REPEATS_DAILY);
                        break;
                    case EventRecurrence.WEEKLY:
                        if (mEventRecurrence.repeatsOnEveryWeekDay()) {
474 475
                            position = recurrenceIndexes.indexOf(
                                    EditEventHelper.REPEATS_EVERY_WEEKDAY);
476
                        } else {
477 478
                            position = recurrenceIndexes.indexOf(
                                    EditEventHelper.REPEATS_WEEKLY_ON_DAY);
479 480 481 482
                        }
                        break;
                    case EventRecurrence.MONTHLY:
                        if (mEventRecurrence.repeatsMonthlyOnDayCount()) {
483 484
                            position = recurrenceIndexes.indexOf(
                                    EditEventHelper.REPEATS_MONTHLY_ON_DAY_COUNT);
485
                        } else {
486 487
                            position = recurrenceIndexes.indexOf(
                                    EditEventHelper.REPEATS_MONTHLY_ON_DAY);
488 489 490 491 492 493 494 495
                        }
                        break;
                    case EventRecurrence.YEARLY:
                        position = recurrenceIndexes.indexOf(EditEventHelper.REPEATS_YEARLY);
                        break;
                }
            }
        }
496 497
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(mActivity,
                android.R.layout.simple_spinner_item, repeatArray);
498 499 500 501 502
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mRepeatsSpinner.setAdapter(adapter);
        mRepeatsSpinner.setSelection(position);

        // Don't allow the user to make exceptions recurring events.
503
        if (mModel.mOriginalSyncId != null) {
504 505 506 507 508 509
            mRepeatsSpinner.setEnabled(false);
        }
    }

    private boolean isCustomRecurrence() {

510
        if (mEventRecurrence.until != null
511 512
                || (mEventRecurrence.interval != 0 && mEventRecurrence.interval != 1)
                || mEventRecurrence.count != 0) {
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
            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()) {
532
                    /* this is a "3rd Tuesday of every month" sort of rule */
533 534
                    return false;
                } else if (mEventRecurrence.bydayCount == 0
535 536 537
                        && mEventRecurrence.bymonthdayCount == 1
                        && mEventRecurrence.bymonthday[0] > 0) {
                    /* this is a "22nd day of every month" sort of rule */
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
                    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;
    }

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

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

        public void onClick(View v) {
563 564 565 566 567 568 569 570 571 572 573 574 575 576
            DatePickerDialog dpd = new DatePickerDialog(
                    mActivity, new DateListener(v), mTime.year, mTime.month, mTime.monthDay);
            CalendarView cv = dpd.getDatePicker().getCalendarView();
            cv.setShowWeekNumber(Utils.getShowWeekNumber(mActivity));
            int startOfWeek = Utils.getFirstDayOfWeek(mActivity);
            // Utils returns Time days while CalendarView wants Calendar days
            if (startOfWeek == Time.SATURDAY) {
                startOfWeek = Calendar.SATURDAY;
            } else if (startOfWeek == Time.SUNDAY) {
                startOfWeek = Calendar.SUNDAY;
            } else {
                startOfWeek = Calendar.MONDAY;
            }
            cv.setFirstDayOfWeek(startOfWeek);
RoboErik's avatar
RoboErik committed
577
            dpd.setCanceledOnTouchOutside(true);
578
            dpd.show();
579 580 581 582 583 584 585 586 587 588 589 590
        }
    }

    static private class CalendarsAdapter extends ResourceCursorAdapter {
        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) {
            View colorBar = view.findViewById(R.id.color);
RoboErik's avatar
RoboErik committed
591
            int colorColumn = cursor.getColumnIndexOrThrow(Calendars.CALENDAR_COLOR);
RoboErik's avatar
RoboErik committed
592
            int nameColumn = cursor.getColumnIndexOrThrow(Calendars.CALENDAR_DISPLAY_NAME);
593 594
            int ownerColumn = cursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT);
            if (colorBar != null) {
595 596
                colorBar.setBackgroundColor(Utils.getDisplayColorFromColor(cursor
                        .getInt(colorColumn)));
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
            }

            TextView name = (TextView) view.findViewById(R.id.calendar_name);
            if (name != null) {
                String displayName = cursor.getString(nameColumn);
                name.setText(displayName);

                TextView accountName = (TextView) view.findViewById(R.id.account_name);
                if (accountName != null) {
                    accountName.setText(cursor.getString(ownerColumn));
                    accountName.setVisibility(TextView.VISIBLE);
                }
            }
        }
    }

613 614 615 616
    /**
     * Does prep steps for saving a calendar event.
     *
     * This triggers a parse of the attendees list and checks if the event is
Erik's avatar
Erik committed
617 618 619
     * ready to be saved. An event is ready to be saved so long as a model
     * exists and has a calendar it can be associated with, either because it's
     * an existing event or we've finished querying.
620
     *
Erik's avatar
Erik committed
621 622
     * @return false if there is no model or no calendar had been loaded yet,
     * true otherwise.
623 624
     */
    public boolean prepareForSave() {
Erik's avatar
Erik committed
625
        if (mModel == null || (mCalendarsCursor == null && mModel.mUri == null)) {
626 627
            return false;
        }
Erik's avatar
Erik committed
628
        return fillModelFromUI();
629 630
    }

Erik's avatar
Erik committed
631 632 633 634
    public boolean fillModelFromReadOnlyUi() {
        if (mModel == null || (mCalendarsCursor == null && mModel.mUri == null)) {
            return false;
        }
635 636
        mModel.mReminders = EventViewUtils.reminderItemsToReminders(
                    mReminderItems, mReminderMinuteValues, mReminderMethodValues);
637 638
        mModel.mReminders.addAll(mUnsupportedReminders);
        mModel.normalizeReminders();
Erik's avatar
Erik committed
639 640 641 642 643 644 645 646
        int status = EventInfoFragment.getResponseFromButtonId(
                mResponseRadioGroup.getCheckedRadioButtonId());
        if (status != Attendees.ATTENDEE_STATUS_NONE) {
            mModel.mSelfAttendeeStatus = status;
        }
        return true;
    }

647 648 649
    // 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.
650
    @Override
651
    public void onClick(View view) {
652 653

        // This must be a click on one of the "remove reminder" buttons
654
        LinearLayout reminderItem = (LinearLayout) view.getParent();
655 656 657 658
        LinearLayout parent = (LinearLayout) reminderItem.getParent();
        parent.removeView(reminderItem);
        mReminderItems.remove(reminderItem);
        updateRemindersVisibility(mReminderItems.size());
659
        EventViewUtils.updateAddReminderButton(mView, mReminderItems, mModel.mCalendarMaxReminders);
660 661 662 663
    }

    // This is called if the user cancels the "No calendars" dialog.
    // The "No calendars" dialog is shown if there are no syncable calendars.
664
    @Override
665 666 667 668 669
    public void onCancel(DialogInterface dialog) {
        if (dialog == mLoadingCalendarsDialog) {
            mLoadingCalendarsDialog = null;
            mSaveAfterQueryComplete = false;
        } else if (dialog == mNoCalendarsDialog) {
Erik's avatar
Erik committed
670 671
            mDone.setDoneCode(Utils.DONE_REVERT);
            mDone.run();
672 673 674 675 676
            return;
        }
    }

    // This is called if the user clicks on a dialog button.
677
    @Override
678 679
    public void onClick(DialogInterface dialog, int which) {
        if (dialog == mNoCalendarsDialog) {
Erik's avatar
Erik committed
680 681
            mDone.setDoneCode(Utils.DONE_REVERT);
            mDone.run();
682 683 684 685
            if (which == DialogInterface.BUTTON_POSITIVE) {
                Intent nextIntent = new Intent(Settings.ACTION_ADD_ACCOUNT);
                final String[] array = {"com.android.calendar"};
                nextIntent.putExtra(Settings.EXTRA_AUTHORITIES, array);
686
                nextIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
687 688
                mActivity.startActivity(nextIntent);
            }
689 690 691
        } else if (dialog == mTimezoneDialog) {
            if (which >= 0 && which < mTimezoneAdapter.getCount()) {
                setTimezone(which);
692
                updateHomeTime();
693 694
                dialog.dismiss();
            }
695 696 697 698
        }
    }

    // Goes through the UI elements and updates the model as necessary
699
    private boolean fillModelFromUI() {
700 701 702
        if (mModel == null) {
            return false;
        }
703 704
        mModel.mReminders = EventViewUtils.reminderItemsToReminders(mReminderItems,
                mReminderMinuteValues, mReminderMethodValues);
705 706
        mModel.mReminders.addAll(mUnsupportedReminders);
        mModel.normalizeReminders();
707
        mModel.mHasAlarm = mReminderItems.size() > 0;
708
        mModel.mTitle = mTitleTextView.getText().toString();
709
        mModel.mAllDay = mAllDayCheckBox.isChecked();
710 711
        mModel.mLocation = mLocationTextView.getText().toString();
        mModel.mDescription = mDescriptionTextView.getText().toString();
712 713 714 715 716 717
        if (TextUtils.isEmpty(mModel.mLocation)) {
            mModel.mLocation = null;
        }
        if (TextUtils.isEmpty(mModel.mDescription)) {
            mModel.mDescription = null;
        }
718 719 720 721 722

        int status = EventInfoFragment.getResponseFromButtonId(mResponseRadioGroup
                .getCheckedRadioButtonId());
        if (status != Attendees.ATTENDEE_STATUS_NONE) {
            mModel.mSelfAttendeeStatus = status;
Erik's avatar
Erik committed
723 724
        }

725
        if (mAttendeesList != null) {
726 727
            mEmailValidator.setRemoveInvalid(true);
            mAttendeesList.performValidation();
728
            mModel.mAttendeesList.clear();
729
            mModel.addAttendees(mAttendeesList.getText().toString(), mEmailValidator);
730
            mEmailValidator.setRemoveInvalid(false);
731 732 733 734 735 736 737
        }

        // If this was a new event we need to fill in the Calendar information
        if (mModel.mUri == null) {
            mModel.mCalendarId = mCalendarsSpinner.getSelectedItemId();
            int calendarCursorPosition = mCalendarsSpinner.getSelectedItemPosition();
            if (mCalendarsCursor.moveToPosition(calendarCursorPosition)) {
738 739 740 741
                String defaultCalendar = mCalendarsCursor.getString(
                        EditEventHelper.CALENDARS_INDEX_OWNER_ACCOUNT);
                Utils.setSharedPreference(
                        mActivity, GeneralPreferences.KEY_DEFAULT_CALENDAR, defaultCalendar);
742 743 744 745 746 747 748 749 750
                mModel.mOwnerAccount = defaultCalendar;
                mModel.mOrganizer = defaultCalendar;
                mModel.mCalendarId = mCalendarsCursor.getLong(EditEventHelper.CALENDARS_INDEX_ID);
            }
        }

        if (mModel.mAllDay) {
            // Reset start and end time, increment the monthDay by 1, and set
            // the timezone to UTC, as required for all-day events.
751
            mTimezone = Time.TIMEZONE_UTC;
752 753 754
            mStartTime.hour = 0;
            mStartTime.minute = 0;
            mStartTime.second = 0;
755
            mStartTime.timezone = mTimezone;
756 757 758 759 760
            mModel.mStart = mStartTime.normalize(true);

            mEndTime.hour = 0;
            mEndTime.minute = 0;
            mEndTime.second = 0;
761
            mEndTime.timezone = mTimezone;
762 763 764 765 766 767 768 769 770 771
            // When a user see the event duration as "X - Y" (e.g. Oct. 28 - Oct. 29), end time
            // should be Y + 1 (Oct.30).
            final long normalizedEndTimeMillis =
                    mEndTime.normalize(true) + DateUtils.DAY_IN_MILLIS;
            if (normalizedEndTimeMillis < mModel.mStart) {
                // mEnd should be midnight of the next day of mStart.
                mModel.mEnd = mModel.mStart + DateUtils.DAY_IN_MILLIS;
            } else {
                mModel.mEnd = normalizedEndTimeMillis;
            }
772
        } else {
773 774
            mStartTime.timezone = mTimezone;
            mEndTime.timezone = mTimezone;
775 776 777
            mModel.mStart = mStartTime.toMillis(true);
            mModel.mEnd = mEndTime.toMillis(true);
        }
778
        mModel.mTimezone = mTimezone;
779
        mModel.mAccessLevel = mAccessLevelSpinner.getSelectedItemPosition();
780 781 782
        // TODO set correct availability value
        mModel.mAvailability = mAvailabilityValues.get(mAvailabilitySpinner
                .getSelectedItemPosition());
783 784 785 786 787 788 789

        int selection;
        // If we're making an exception we don't want it to be a repeating
        // event.
        if (mModification == EditEventHelper.MODIFY_SELECTED) {
            selection = EditEventHelper.DOES_NOT_REPEAT;
        } else {
790
            int position = mRepeatsSpinner.getSelectedItemPosition();
791 792 793
            selection = mRecurrenceIndexes.get(position);
        }

794 795
        EditEventHelper.updateRecurrenceRule(
                selection, mModel, Utils.getFirstDayOfWeek(mActivity) + 1);
796

797 798 799 800
        // Save the timezone so we can display it as a standard option next time
        if (!mModel.mAllDay) {
            mTimezoneAdapter.saveRecentTimezone(mTimezone);
        }
801 802 803
        return true;
    }

Erik's avatar
Erik committed
804
    public EditEventView(Activity activity, View view, EditDoneRunnable done) {
805 806 807

        mActivity = activity;
        mView = view;
Erik's avatar
Erik committed
808
        mDone = done;
809 810 811 812 813 814

        // cache top level view elements
        mLoadingMessage = (TextView) view.findViewById(R.id.loading_message);
        mScrollView = (ScrollView) view.findViewById(R.id.scroll_view);

        // cache all the widgets
815
        mCalendarsSpinner = (Spinner) view.findViewById(R.id.calendars_spinner);
816 817 818
        mTitleTextView = (TextView) view.findViewById(R.id.title);
        mLocationTextView = (TextView) view.findViewById(R.id.location);
        mDescriptionTextView = (TextView) view.findViewById(R.id.description);
819
        mTimezoneLabel = (TextView) view.findViewById(R.id.timezone_label);
820 821
        mStartDateButton = (Button) view.findViewById(R.id.start_date);
        mEndDateButton = (Button) view.findViewById(R.id.end_date);
822 823
        mWhenView = (TextView) mView.findViewById(R.id.when);
        mTimezoneTextView = (TextView) mView.findViewById(R.id.timezone_textView);
824 825
        mStartTimeButton = (Button) view.findViewById(R.id.start_time);
        mEndTimeButton = (Button) view.findViewById(R.id.end_time);
826
        mTimezoneButton = (Button) view.findViewById(R.id.timezone_button);
Michael Chan's avatar
Michael Chan committed
827
        mTimezoneRow = view.findViewById(R.id.timezone_button_row);
828 829 830 831
        mStartTimeHome = (TextView) view.findViewById(R.id.start_time_home_tz);
        mStartDateHome = (TextView) view.findViewById(R.id.start_date_home_tz);
        mEndTimeHome = (TextView) view.findViewById(R.id.end_time_home_tz);
        mEndDateHome = (TextView) view.findViewById(R.id.end_date_home_tz);
832 833
        mAllDayCheckBox = (CheckBox) view.findViewById(R.id.is_all_day);
        mRepeatsSpinner = (Spinner) view.findViewById(R.id.repeats);
834 835
        mAvailabilitySpinner = (Spinner) view.findViewById(R.id.availability);
        mAccessLevelSpinner = (Spinner) view.findViewById(R.id.visibility);
836
        mCalendarSelectorGroup = view.findViewById(R.id.calendar_selector_group);
837
        mCalendarSelectorWrapper = view.findViewById(R.id.calendar_selector_wrapper);
838 839 840 841
        mCalendarStaticGroup = view.findViewById(R.id.calendar_group);
        mRemindersGroup = view.findViewById(R.id.reminders_row);
        mResponseGroup = view.findViewById(R.id.response_row);
        mOrganizerGroup = view.findViewById(R.id.organizer_row);
842
        mAttendeesGroup = view.findViewById(R.id.add_attendees_row);
Erik's avatar
Erik committed
843 844
        mLocationGroup = view.findViewById(R.id.where_row);
        mDescriptionGroup = view.findViewById(R.id.description_row);
845 846
        mStartHomeGroup = view.findViewById(R.id.from_row_home_tz);
        mEndHomeGroup = view.findViewById(R.id.to_row_home_tz);
847
        mAttendeesList = (MultiAutoCompleteTextView) view.findViewById(R.id.attendees);
848

Erik's avatar
Erik committed
849 850 851 852
        mTitleTextView.setTag(mTitleTextView.getBackground());
        mLocationTextView.setTag(mLocationTextView.getBackground());
        mDescriptionTextView.setTag(mDescriptionTextView.getBackground());
        mRepeatsSpinner.setTag(mRepeatsSpinner.getBackground());
853
        mAttendeesList.setTag(mAttendeesList.getBackground());
Erik's avatar
Erik committed
854 855 856 857
        mOriginalPadding[0] = mLocationTextView.getPaddingLeft();
        mOriginalPadding[1] = mLocationTextView.getPaddingTop();
        mOriginalPadding[2] = mLocationTextView.getPaddingRight();
        mOriginalPadding[3] = mLocationTextView.getPaddingBottom();
858 859 860 861
        mOriginalSpinnerPadding[0] = mRepeatsSpinner.getPaddingLeft();
        mOriginalSpinnerPadding[1] = mRepeatsSpinner.getPaddingTop();
        mOriginalSpinnerPadding[2] = mRepeatsSpinner.getPaddingRight();
        mOriginalSpinnerPadding[3] = mRepeatsSpinner.getPaddingBottom();
862 863 864
        mEditViewList.add(mTitleTextView);
        mEditViewList.add(mLocationTextView);
        mEditViewList.add(mDescriptionTextView);
865
        mEditViewList.add(mAttendeesList);
866 867 868 869 870 871 872 873 874

        mViewOnlyList.add(view.findViewById(R.id.when_row));
        mViewOnlyList.add(view.findViewById(R.id.timezone_textview_row));

        mEditOnlyList.add(view.findViewById(R.id.all_day_row));
        mEditOnlyList.add(view.findViewById(R.id.availability_row));
        mEditOnlyList.add(view.findViewById(R.id.visibility_row));
        mEditOnlyList.add(view.findViewById(R.id.from_row));
        mEditOnlyList.add(view.findViewById(R.id.to_row));
Michael Chan's avatar
Michael Chan committed
875
        mEditOnlyList.add(mTimezoneRow);
876 877
        mEditOnlyList.add(mStartHomeGroup);
        mEditOnlyList.add(mEndHomeGroup);
878

879
        mResponseRadioGroup = (RadioGroup) view.findViewById(R.id.response_value);
880 881
        mRemindersContainer = (LinearLayout) view.findViewById(R.id.reminder_items_container);

882
        mTimezone = Utils.getTimeZone(activity, null);
883
        mIsMultipane = activity.getResources().getBoolean(R.bool.tablet_config);
884 885
        mStartTime = new Time(mTimezone);
        mEndTime = new Time(mTimezone);
886
        mTimezoneAdapter = new TimezoneAdapter(mActivity, mTimezone);
887 888
        mEmailValidator = new Rfc822Validator(null);
        initMultiAutoCompleteTextView((RecipientEditTextView) mAttendeesList);
889 890 891 892 893

        // Display loading screen
        setModel(null);
    }

894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918

    /**
     * Loads an integer array asset into a list.
     */
    private static ArrayList<Integer> loadIntegerArray(Resources r, int resNum) {
        int[] vals = r.getIntArray(resNum);
        int size = vals.length;
        ArrayList<Integer> list = new ArrayList<Integer>(size);

        for (int i = 0; i < size; i++) {
            list.add(vals[i]);
        }

        return list;
    }

    /**
     * Loads a String array asset into a list.
     */
    private static ArrayList<String> loadStringArray(Resources r, int resNum) {
        String[] labels = r.getStringArray(resNum);
        ArrayList<String> list = new ArrayList<String>(Arrays.asList(labels));
        return list;
    }

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
    private void prepareAvailability() {
        Resources r = mActivity.getResources();

        mAvailabilityValues = loadIntegerArray(r, R.array.availability_values);
        mAvailabilityLabels = loadStringArray(r, R.array.availability);

        if (mModel.mCalendarAllowedAvailability != null) {
            EventViewUtils.reduceMethodList(mAvailabilityValues, mAvailabilityLabels,
                    mModel.mCalendarAllowedAvailability);
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(mActivity,
                android.R.layout.simple_spinner_item, mAvailabilityLabels);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mAvailabilitySpinner.setAdapter(adapter);
    }

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
    /**
     * Prepares the reminder UI elements.
     * <p>
     * (Re-)loads the minutes / methods lists from the XML assets, adds/removes items as
     * needed for the current set of reminders and calendar properties, and then creates UI
     * elements.
     */
    private void prepareReminders() {
        CalendarEventModel model = mModel;
        Resources r = mActivity.getResources();

        // Load the labels and corresponding numeric values for the minutes and methods lists
        // from the assets.  If we're switching calendars, we need to clear and re-populate the
        // lists (which may have elements added and removed based on calendar properties).  This
        // is mostly relevant for "methods", since we shouldn't have any "minutes" values in a
        // new event that aren't in the default set.
        mReminderMinuteValues = loadIntegerArray(r, R.array.reminder_minutes_values);
        mReminderMinuteLabels = loadStringArray(r, R.array.reminder_minutes_labels);
        mReminderMethodValues = loadIntegerArray(r, R.array.reminder_methods_values);
        mReminderMethodLabels = loadStringArray(r, R.array.reminder_methods_labels);

        // Remove any reminder methods that aren't allowed for this calendar.  If this is
        // a new event, mCalendarAllowedReminders may not be set the first time we're called.
        if (mModel.mCalendarAllowedReminders != null) {
            EventViewUtils.reduceMethodList(mReminderMethodValues, mReminderMethodLabels,
                    mModel.mCalendarAllowedReminders);
        }

        int numReminders = 0;
        if (model.mHasAlarm) {
            ArrayList<ReminderEntry> reminders = model.mReminders;
            numReminders = reminders.size();
            // Insert any minute values that aren't represented in the minutes list.
            for (ReminderEntry re : reminders) {
970 971 972 973
                if (mReminderMethodValues.contains(re.getMethod())) {
                    EventViewUtils.addMinutesToList(mActivity, mReminderMinuteValues,
                            mReminderMinuteLabels, re.getMinutes());
                }
974 975 976 977 978
            }

            // Create a UI element for each reminder.  We display all of the reminders we get
            // from the provider, even if the count exceeds the calendar maximum.  (Also, for
            // a new event, we won't have a maxReminders value available.)
979
            mUnsupportedReminders.clear();
980
            for (ReminderEntry re : reminders) {
981 982
                if (mReminderMethodValues.contains(re.getMethod())
                        || re.getMethod() == Reminders.METHOD_DEFAULT) {
983 984
                    EventViewUtils.addReminder(mActivity, mScrollView, this, mReminderItems,
                            mReminderMinuteValues, mReminderMinuteLabels, mReminderMethodValues,
985
                            mReminderMethodLabels, re, Integer.MAX_VALUE, null);
986 987 988 989
                } else {
                    // TODO figure out a way to display unsupported reminders
                    mUnsupportedReminders.add(re);
                }
990 991 992 993
            }
        }

        updateRemindersVisibility(numReminders);
994
        EventViewUtils.updateAddReminderButton(mView, mReminderItems, mModel.mCalendarMaxReminders);
995 996
    }

997 998 999 1000 1001 1002 1003 1004 1005 1006
    /**
     * Fill in the view with the contents of the given event model. This allows
     * an edit view to be initialized before the event has been loaded. Passing
     * in null for the model will display a loading screen. A non-null model
     * will fill in the view's fields with the data contained in the model.
     *
     * @param model The event model to pull the data from
     */
    public void setModel(CalendarEventModel model) {
        mModel = model;
1007 1008

        // Need to close the autocomplete adapter to prevent leaking cursors.
1009 1010
        if (mAddressAdapter != null && mAddressAdapter instanceof EmailAddressAdapter) {
            ((EmailAddressAdapter)mAddressAdapter).close();
1011 1012 1013
            mAddressAdapter = null;
        }

1014 1015 1016 1017 1018 1019 1020
        if (model == null) {
            // Display loading screen
            mLoadingMessage.setVisibility(View.VISIBLE);
            mScrollView.setVisibility(View.GONE);
            return;
        }

1021 1022
        boolean canRespond = EditEventHelper.canRespond(model);

1023 1024
        long begin = model.mStart;
        long end = model.mEnd;
1025
        mTimezone = model.mTimezone; // this will be UTC for all day events
1026 1027 1028

        // Set up the starting times
        if (begin > 0) {
1029
            mStartTime.timezone = mTimezone;
1030 1031 1032 1033
            mStartTime.set(begin);
            mStartTime.normalize(true);
        }
        if (end > 0) {
1034
            mEndTime.timezone = mTimezone;
1035 1036 1037 1038
            mEndTime.set(end);
            mEndTime.normalize(true);
        }
        String rrule = model.mRrule;
1039
        if (!TextUtils.isEmpty(rrule)) {
1040 1041 1042 1043 1044
            mEventRecurrence.parse(rrule);
        }

        // If the user is allowed to change the attendees set up the view and
        // validator
1045
        if (!model.mHasAttendeeData) {
1046
            mAttendeesGroup.setVisibility(View.GONE);
1047 1048
        }

1049
        mAllDayCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
1050
            @Override
1051
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
1052
                setAllDayViewsVisibility(isChecked);
1053 1054
            }
        });
1055

1056
        boolean prevAllDay = mAllDayCheckBox.isChecked();
1057
        mAllDay = false; // default to false. Let setAllDayViewsVisibility update it as needed
1058 1059
        if (model.mAllDay) {
            mAllDayCheckBox.setChecked(true);
1060 1061 1062 1063 1064 1065
            // put things back in local time for all day events
            mTimezone = TimeZone.getDefault().getID();
            mStartTime.timezone = mTimezone;
            mStartTime.normalize(true);
            mEndTime.timezone = mTimezone;
            mEndTime.normalize(true);
1066 1067 1068
        } else {
            mAllDayCheckBox.setChecked(false);
        }
1069 1070 1071 1072 1073
        // On a rotation we need to update the views but onCheckedChanged
        // doesn't get called
        if (prevAllDay == mAllDayCheckBox.isChecked()) {
            setAllDayViewsVisibility(prevAllDay);
        }
1074

1075 1076 1077 1078 1079
        mTimezoneAdapter = new TimezoneAdapter(mActivity, mTimezone);
        if (mTimezoneDialog != null) {
            mTimezoneDialog.getListView().setAdapter(mTimezoneAdapter);
        }

1080
        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(mActivity);
1081 1082 1083
        String defaultReminderString = prefs.getString(
                GeneralPreferences.KEY_DEFAULT_REMINDER, GeneralPreferences.NO_REMINDER_STRING);
        mDefaultReminderMinutes = Integer.parseInt(defaultReminderString);
1084

1085
        prepareReminders();
1086
        prepareAvailability();
1087

Michael Chan's avatar
Michael Chan committed
1088
        View reminderAddButton = mView.findViewById(R.id.reminder_add);
1089
        View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
1090
            @Override
1091 1092 1093 1094
            public void onClick(View v) {
                addReminder();
            }
        };
1095
        reminderAddButton.setOnClickListener(addReminderOnClickListener);
1096

Michael Chan's avatar
Michael Chan committed
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
        if (!mIsMultipane) {
            mView.findViewById(R.id.is_all_day_label).setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mAllDayCheckBox.setChecked(!mAllDayCheckBox.isChecked());
                        }
                    });
        }

1107 1108 1109 1110
        if (model.mTitle != null) {
            mTitleTextView.setTextKeepState(model.mTitle);
        }

1111 1112 1113 1114
        if (model.mIsOrganizer || TextUtils.isEmpty(model.mOrganizer)
                || model.mOrganizer.endsWith(GOOGLE_SECONDARY_CALENDAR)) {
            mView.findViewById(R.id.organizer_label).setVisibility(View.GONE);
            mView.findViewById(R.id.organizer).setVisibility(View.GONE);
1115
            mOrganizerGroup.setVisibility(View.GONE);
1116 1117 1118
        } else {
            ((TextView) mView.findViewById(R.id.organizer)).setText(model.mOrganizerDisplayName);
        }
1119 1120 1121 1122 1123 1124 1125 1126 1127

        if (model.mLocation != null) {
            mLocationTextView.setTextKeepState(model.mLocation);
        }

        if (model.mDescription != null) {
            mDescriptionTextView.setTextKeepState(model.mDescription);
        }

1128 1129 1130 1131
        int availIndex = mAvailabilityValues.indexOf(model.mAvailability);
        if (availIndex != -1) {
            mAvailabilitySpinner.setSelection(availIndex);
        }
1132
        mAccessLevelSpinner.setSelection(model.mAccessLevel);
1133

1134
        View responseLabel = mView.findViewById(R.id.response_label);
1135
        if (canRespond) {
1136 1137 1138 1139
            int buttonToCheck = EventInfoFragment
                    .findButtonIdForResponse(model.mSelfAttendeeStatus);
            mResponseRadioGroup.check(buttonToCheck); // -1 clear all radio buttons
            mResponseRadioGroup.setVisibility(View.VISIBLE);
1140 1141 1142
            responseLabel.setVisibility(View.VISIBLE);
        } else {
            responseLabel.setVisibility(View.GONE);
1143
            mResponseRadioGroup.setVisibility(View.GONE);
1144
            mResponseGroup.setVisibility(View.GONE);
1145
        }
1146

1147
        int displayColor = Utils.getDisplayColorFromColor(model.mCalendarColor);
1148 1149 1150
        if (model.mUri != null) {
            // This is an existing event so hide the calendar spinner
            // since we can't change the calendar.
1151 1152 1153 1154
            View calendarGroup = mView.findViewById(R.id.calendar_selector_group);
            calendarGroup.setVisibility(View.GONE);
            TextView tv = (TextView) mView.findViewById(R.id.calendar_textview);
            tv.setText(model.mCalendarDisplayName);
RoboErik's avatar
RoboErik committed
1155 1156 1157 1158
            tv = (TextView) mView.findViewById(R.id.calendar_textview_secondary);
            if (tv != null) {
                tv.setText(model.mOwnerAccount);
            }
1159 1160 1161 1162 1163
            if (mIsMultipane) {
                mView.findViewById(R.id.calendar_textview).setBackgroundColor(displayColor);
            } else {
                mView.findViewById(R.id.calendar_group).setBackgroundColor(displayColor);
            }
1164
        } else {
1165 1166 1167 1168
            View calendarGroup = mView.findViewById(R.id.calendar_group);
            calendarGroup.setVisibility(View.GONE);
        }

1169
        populateTimezone();
1170
        populateWhen();
1171
        populateRepeats();
Erik's avatar
Erik committed
1172
        updateAttendees(model.mAttendeesList);
1173

1174
        updateView();
1175 1176
        mScrollView.setVisibility(View.VISIBLE);
        mLoadingMessage.setVisibility(View.GONE);
1177 1178 1179 1180
        sendAccessibilityEvent();
    }

    private void sendAccessibilityEvent() {
1181 1182
        AccessibilityManager am =
            (AccessibilityManager) mActivity.getSystemService(Service.ACCESSIBILITY_SERVICE);
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
        if (!am.isEnabled() || mModel == null) {
            return;
        }
        StringBuilder b = new StringBuilder();
        addFieldsRecursive(b, mView);
        CharSequence msg = b.toString();

        AccessibilityEvent event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_FOCUSED);
        event.setClassName(getClass().getName());
        event.setPackageName(mActivity.getPackageName());
        event.getText().add(msg);
        event.setAddedCount(msg.length());

        am.sendAccessibilityEvent(event);
    }

    private void addFieldsRecursive(StringBuilder b, View v) {
        if (v == null || v.getVisibility() != View.VISIBLE) {
            return;
        }
        if (v instanceof TextView) {
            CharSequence tv = ((TextView) v).getText();
            if (!TextUtils.isEmpty(tv.toString().trim())) {
                b.append(tv + PERIOD_SPACE);
            }
        } else if (v instanceof RadioGroup) {
            RadioGroup rg = (RadioGroup) v;
            int id = rg.getCheckedRadioButtonId();
            if (id != View.NO_ID) {
                b.append(((RadioButton) (v.findViewById(id))).getText() + PERIOD_SPACE);
            }
        } else if (v instanceof Spinner) {
            Spinner s = (Spinner) v;
            if (s.getSelectedItem() instanceof String) {
                String str = ((String) (s.getSelectedItem())).trim();
                if (!TextUtils.isEmpty(str)) {
                    b.append(str + PERIOD_SPACE);
                }
            }
        } else if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            int children = vg.getChildCount();
            for (int i = 0; i < children; i++) {
                addFieldsRecursive(b, vg.getChildAt(i));
            }
        }
1229 1230
    }

1231
    /**
1232
     * Creates a single line string for the time/duration
1233
     */
1234 1235 1236
    protected void setWhenString() {
        String when;
        int flags = DateUtils.FORMAT_SHOW_DATE;
1237
        String tz = mTimezone;
1238
        if (mModel.mAllDay) {
1239 1240
            flags |= DateUtils.FORMAT_SHOW_WEEKDAY;
            tz = Time.TIMEZONE_UTC;
1241
        } else {
1242 1243 1244
            flags |= DateUtils.FORMAT_SHOW_TIME;
            if (DateFormat.is24HourFormat(mActivity)) {
                flags |= DateUtils.FORMAT_24HOUR;
1245 1246
            }
        }
1247 1248
        long startMillis = mStartTime.normalize(true);
        long endMillis = mEndTime.normalize(true);
1249
        mSB.setLength(0);
1250 1251
        when = DateUtils
                .formatDateRange(mActivity, mF, startMillis, endMillis, flags, tz).toString();
1252
        mWhenView.setText(when);
1253 1254
    }

1255 1256 1257 1258 1259 1260 1261 1262
    /**
     * Configures the Calendars spinner.  This is only done for new events, because only new
     * events allow you to select a calendar while editing an event.
     * <p>
     * We tuck a reference to a Cursor with calendar database data into the spinner, so that
     * we can easily extract calendar-specific values when the value changes (the spinner's
     * onItemSelected callback is configured).
     */
1263
    public void setCalendarsCursor(Cursor cursor, boolean userVisible) {
1264 1265 1266 1267 1268 1269 1270 1271
        // If there are no syncable calendars, then we cannot allow
        // creating a new event.
        mCalendarsCursor = cursor;
        if (cursor == null || cursor.getCount() == 0) {
            // Cancel the "loading calendars" dialog if it exists
            if (mSaveAfterQueryComplete) {
                mLoadingCalendarsDialog.cancel();
            }
1272 1273 1274
            if (!userVisible) {
                return;
            }
1275 1276 1277
            // Create an error message for the user that, when clicked,
            // will exit this activity without saving the event.
            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
1278 1279
            builder.setTitle(R.string.no_syncable_calendars).setIconAttribute(
                    android.R.attr.alertDialogIcon).setMessage(R.string.no_calendars_found)
1280
                    .setPositiveButton(R.string.add_account, this)
1281
                    .setNegativeButton(android.R.string.no, this).setOnCancelListener(this);
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
            mNoCalendarsDialog = builder.show();
            return;
        }

        int defaultCalendarPosition = findDefaultCalendarPosition(cursor);

        // populate the calendars spinner
        CalendarsAdapter adapter = new CalendarsAdapter(mActivity, cursor);
        mCalendarsSpinner.setAdapter(adapter);
        mCalendarsSpinner.setSelection(defaultCalendarPosition);
Erik's avatar
Erik committed
1292 1293
        mCalendarsSpinner.setOnItemSelectedListener(this);

1294 1295
        if (mSaveAfterQueryComplete) {
            mLoadingCalendarsDialog.cancel();
1296 1297 1298
            if (prepareForSave() && fillModelFromUI()) {
                int exit = userVisible ? Utils.DONE_EXIT : 0;
                mDone.setDoneCode(Utils.DONE_SAVE | exit);
Erik's avatar
Erik committed
1299
                mDone.run();
1300 1301
            } else if (userVisible) {
                mDone.setDoneCode(Utils.DONE_EXIT);
Erik's avatar
Erik committed
1302
                mDone.run();
1303 1304
            } else if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "SetCalendarsCursor:Save failed and unable to exit view");
1305 1306 1307 1308 1309
            }
            return;
        }
    }

1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
    /**
     * Updates the view based on {@link #mModification} and {@link #mModel}
     */
    public void updateView() {
        if (mModel == null) {
            return;
        }
        if (EditEventHelper.canModifyEvent(mModel)) {
            setViewStates(mModification);
        } else {
            setViewStates(Utils.MODIFY_UNINITIALIZED);
        }
    }

    private void setViewStates(int mode) {
        // Extra canModify check just in case
        if (mode == Utils.MODIFY_UNINITIALIZED || !EditEventHelper.canModifyEvent(mModel)) {
            setWhenString();

            for (View v : mViewOnlyList) {
                v.setVisibility(View.VISIBLE);
            }
            for (View v : mEditOnlyList) {
                v.setVisibility(View.GONE);
            }
            for (View v : mEditViewList) {
                v.setEnabled(false);
Erik's avatar
Erik committed
1337
                v.setBackgroundDrawable(null);
1338 1339 1340
            }
            mCalendarSelectorGroup.setVisibility(View.GONE);
            mCalendarStaticGroup.setVisibility(View.VISIBLE);
1341
            mRepeatsSpinner.setEnabled(false);
Erik's avatar
Erik committed
1342
            mRepeatsSpinner.setBackgroundDrawable(null);
1343
            setAllDayViewsVisibility(mAllDayCheckBox.isChecked());
1344 1345 1346 1347 1348
            if (EditEventHelper.canAddReminders(mModel)) {
                mRemindersGroup.setVisibility(View.VISIBLE);
            } else {
                mRemindersGroup.setVisibility(View.GONE);
            }
Erik's avatar
Erik committed
1349 1350 1351 1352 1353 1354
            if (TextUtils.isEmpty(mLocationTextView.getText())) {
                mLocationGroup.setVisibility(View.GONE);
            }
            if (TextUtils.isEmpty(mDescriptionTextView.getText())) {
                mDescriptionGroup.setVisibility(View.GONE);
            }
1355 1356 1357 1358 1359 1360 1361 1362 1363
        } else {
            for (View v : mViewOnlyList) {
                v.setVisibility(View.GONE);
            }
            for (View v : mEditOnlyList) {
                v.setVisibility(View.VISIBLE);
            }
            for (View v : mEditViewList) {
                v.setEnabled(true);
Erik's avatar
Erik committed
1364 1365
                if (v.getTag() != null) {
                    v.setBackgroundDrawable((Drawable) v.getTag());
RoboErik's avatar
RoboErik committed
1366 1367
                    v.setPadding(mOriginalPadding[0], mOriginalPadding[1], mOriginalPadding[2],
                            mOriginalPadding[3]);
Erik's avatar
Erik committed
1368
                }
1369 1370 1371 1372 1373 1374 1375 1376
            }
            if (mModel.mUri == null) {
                mCalendarSelectorGroup.setVisibility(View.VISIBLE);
                mCalendarStaticGroup.setVisibility(View.GONE);
            } else {
                mCalendarSelectorGroup.setVisibility(View.GONE);
                mCalendarStaticGroup.setVisibility(View.VISIBLE);
            }
Erik's avatar
Erik committed
1377
            mRepeatsSpinner.setBackgroundDrawable((Drawable) mRepeatsSpinner.getTag());
1378 1379
            mRepeatsSpinner.setPadding(mOriginalSpinnerPadding[0], mOriginalSpinnerPadding[1],
                    mOriginalSpinnerPadding[2], mOriginalSpinnerPadding[3]);
1380
            if (mModel.mOriginalSyncId == null) {
1381 1382 1383 1384 1385 1386
                mRepeatsSpinner.setEnabled(true);
            } else {
                mRepeatsSpinner.setEnabled(false);
            }
            mRemindersGroup.setVisibility(View.VISIBLE);

Erik's avatar
Erik committed
1387 1388
            mLocationGroup.setVisibility(View.VISIBLE);
            mDescriptionGroup.setVisibility(View.VISIBLE);
1389 1390 1391
        }
    }

1392 1393 1394
    public void setModification(int modifyWhich) {
        mModification = modifyWhich;
        updateView();
1395
        updateHomeTime();
1396 1397
    }

1398 1399 1400 1401 1402 1403 1404
    // Find the calendar position in the cursor that matches calendar in
    // preference
    private int findDefaultCalendarPosition(Cursor calendarsCursor) {
        if (calendarsCursor.getCount() <= 0) {
            return -1;
        }

1405 1406
        String defaultCalendar = Utils.getSharedPreference(
                mActivity, GeneralPreferences.KEY_DEFAULT_CALENDAR, null);
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422

        if (defaultCalendar == null) {
            return 0;
        }
        int calendarsOwnerColumn = calendarsCursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT);
        int position = 0;
        calendarsCursor.moveToPosition(-1);
        while (calendarsCursor.moveToNext()) {
            if (defaultCalendar.equals(calendarsCursor.getString(calendarsOwnerColumn))) {
                return position;
            }
            position++;
        }
        return 0;
    }

1423
    private void updateAttendees(HashMap<String, Attendee> attendeesList) {
1424 1425 1426 1427 1428 1429 1430
        if (attendeesList == null || attendeesList.isEmpty()) {
            return;
        }
        mAttendeesList.setText(null);
        for (Attendee attendee : attendeesList.values()) {
            mAttendeesList.append(attendee.mEmail);
        }
Erik's avatar
Erik committed
1431
    }
1432

1433 1434 1435 1436 1437 1438 1439 1440
    private void updateRemindersVisibility(int numReminders) {
        if (numReminders == 0) {
            mRemindersContainer.setVisibility(View.GONE);
        } else {
            mRemindersContainer.setVisibility(View.VISIBLE);
        }
    }

1441 1442 1443 1444
    /**
     * Add a new reminder when the user hits the "add reminder" button.  We use the default
     * reminder time and method.
     */
1445
    private void addReminder() {
1446 1447
        // TODO: when adding a new reminder, make it different from the
        // last one in the list (if any).
1448
        if (mDefaultReminderMinutes == GeneralPreferences.NO_REMINDER) {
Erik's avatar
Erik committed
1449
            EventViewUtils.addReminder(mActivity, mScrollView, this, mReminderItems,
1450
                    mReminderMinuteValues, mReminderMinuteLabels,
1451 1452
                    mReminderMethodValues, mReminderMethodLabels,
                    ReminderEntry.valueOf(GeneralPreferences.REMINDER_DEFAULT_TIME),
1453
                    mModel.mCalendarMaxReminders, null);
1454
        } else {
Erik's avatar
Erik committed
1455
            EventViewUtils.addReminder(mActivity, mScrollView, this, mReminderItems,
1456
                    mReminderMinuteValues, mReminderMinuteLabels,
1457 1458
                    mReminderMethodValues, mReminderMethodLabels,
                    ReminderEntry.valueOf(mDefaultReminderMinutes),
1459
                    mModel.mCalendarMaxReminders, null);
1460 1461
        }
        updateRemindersVisibility(mReminderItems.size());
1462
        EventViewUtils.updateAddReminderButton(mView, mReminderItems, mModel.mCalendarMaxReminders);
1463 1464 1465
    }

    // From com.google.android.gm.ComposeActivity
1466
    private MultiAutoCompleteTextView initMultiAutoCompleteTextView(RecipientEditTextView list) {
1467 1468 1469
        if (ChipsUtil.supportsChipsUi()) {
            mAddressAdapter = new RecipientAdapter(mActivity);
            list.setAdapter((BaseRecipientAdapter) mAddressAdapter);
1470
            list.setOnFocusListShrinkRecipients(false);
1471 1472 1473 1474
        } else {
            mAddressAdapter = new EmailAddressAdapter(mActivity);
            list.setAdapter((EmailAddressAdapter)mAddressAdapter);
        }
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
        list.setTokenizer(new Rfc822Tokenizer());
        list.setValidator(mEmailValidator);

        // 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).
     */
1490
    private static InputFilter[] sRecipientFilters = new InputFilter[] { new Rfc822InputFilter() };
1491 1492 1493 1494 1495

    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;
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511

        // Unfortunately, DateUtils doesn't support a timezone other than the
        // default timezone provided by the system, so we have this ugly hack
        // here to trick it into formatting our time correctly. In order to
        // prevent all sorts of craziness, we synchronize on the TimeZone class
        // to prevent other threads from reading an incorrect timezone from
        // calls to TimeZone#getDefault()
        // TODO fix this if/when DateUtils allows for passing in a timezone
        String dateString;
        synchronized (TimeZone.class) {
            TimeZone.setDefault(TimeZone.getTimeZone(mTimezone));
            dateString = DateUtils.formatDateTime(mActivity, millis, flags);
            // setting the default back to null restores the correct behavior
            TimeZone.setDefault(null);
        }
        view.setText(dateString);
1512 1513 1514 1515 1516 1517 1518
    }

    private void setTime(TextView view, long millis) {
        int flags = DateUtils.FORMAT_SHOW_TIME;
        if (DateFormat.is24HourFormat(mActivity)) {
            flags |= DateUtils.FORMAT_24HOUR;
        }
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540

        // Unfortunately, DateUtils doesn't support a timezone other than the
        // default timezone provided by the system, so we have this ugly hack
        // here to trick it into formatting our time correctly. In order to
        // prevent all sorts of craziness, we synchronize on the TimeZone class
        // to prevent other threads from reading an incorrect timezone from
        // calls to TimeZone#getDefault()
        // TODO fix this if/when DateUtils allows for passing in a timezone
        String timeString;
        synchronized (TimeZone.class) {
            TimeZone.setDefault(TimeZone.getTimeZone(mTimezone));
            timeString = DateUtils.formatDateTime(mActivity, millis, flags);
            TimeZone.setDefault(null);
        }
        view.setText(timeString);
    }

    private void setTimezone(int i) {
        if (i < 0 || i >= mTimezoneAdapter.getCount()) {
            return; // do nothing
        }
        TimezoneRow timezone = mTimezoneAdapter.getItem(i);
1541
        mTimezoneTextView.setText(timezone.toString());
1542 1543
        mTimezoneButton.setText(timezone.toString());
        mTimezone = timezone.mId;
1544 1545 1546 1547
        mStartTime.timezone = mTimezone;
        mStartTime.normalize(true);
        mEndTime.timezone = mTimezone;
        mEndTime.normalize(true);
1548
        mTimezoneAdapter.setCurrentTimezone(mTimezone);
1549
    }
1550

1551 1552 1553 1554 1555 1556
    /**
     * @param isChecked
     */
    protected void setAllDayViewsVisibility(boolean isChecked) {
        if (isChecked) {
            if (mEndTime.hour == 0 && mEndTime.minute == 0) {
1557 1558 1559 1560
                if (mAllDay != isChecked) {
                    mEndTime.monthDay--;
                }

1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
                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);
Michael Chan's avatar
Michael Chan committed
1576
            mTimezoneRow.setVisibility(View.GONE);
1577 1578
        } else {
            if (mEndTime.hour == 0 && mEndTime.minute == 0) {
1579 1580 1581 1582
                if (mAllDay != isChecked) {
                    mEndTime.monthDay++;
                }

1583 1584 1585 1586 1587 1588
                long endMillis = mEndTime.normalize(true);
                setDate(mEndDateButton, endMillis);
                setTime(mEndTimeButton, endMillis);
            }
            mStartTimeButton.setVisibility(View.VISIBLE);
            mEndTimeButton.setVisibility(View.VISIBLE);
Michael Chan's avatar
Michael Chan committed
1589
            mTimezoneRow.setVisibility(View.VISIBLE);
1590
        }
1591
        mAllDay = isChecked;
1592
        updateHomeTime();
1593
    }
Erik's avatar
Erik committed
1594 1595 1596

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
1597
        // This is only used for the Calendar spinner in new events, and only fires when the
1598
        // calendar selection changes or on screen rotation
Erik's avatar
Erik committed
1599
        Cursor c = (Cursor) parent.getItemAtPosition(position);
1600 1601 1602 1603
        if (c == null) {
            // TODO: can this happen? should we drop this check?
            Log.w(TAG, "Cursor not set on calendar item");
            return;
Erik's avatar
Erik committed
1604
        }
1605 1606

        int colorColumn = c.getColumnIndexOrThrow(Calendars.CALENDAR_COLOR);
1607 1608
        int color = c.getInt(colorColumn);
        int displayColor = Utils.getDisplayColorFromColor(color);
1609

1610
        if (mIsMultipane) {
1611
            mCalendarSelectorWrapper.setBackgroundColor(displayColor);
1612 1613 1614
        } else {
            mCalendarSelectorGroup.setBackgroundColor(displayColor);
        }
1615

1616 1617 1618 1619 1620 1621 1622 1623
        // Do nothing if the selection didn't change so that reminders will not get lost
        int idColumn = c.getColumnIndexOrThrow(Calendars._ID);
        long calendarId = c.getLong(idColumn);
        if (calendarId == mModel.mCalendarId) {
            return;
        }
        mModel.mCalendarId = calendarId;
        mModel.mCalendarColor = color;
1624 1625 1626 1627 1628
        // Update the max/allowed reminders with the new calendar properties.
        int maxRemindersColumn = c.getColumnIndexOrThrow(Calendars.MAX_REMINDERS);
        mModel.mCalendarMaxReminders = c.getInt(maxRemindersColumn);
        int allowedRemindersColumn = c.getColumnIndexOrThrow(Calendars.ALLOWED_REMINDERS);
        mModel.mCalendarAllowedReminders = c.getString(allowedRemindersColumn);
1629 1630 1631 1632
        int allowedAttendeeTypesColumn = c.getColumnIndexOrThrow(Calendars.ALLOWED_ATTENDEE_TYPES);
        mModel.mCalendarAllowedAttendeeTypes = c.getString(allowedAttendeeTypesColumn);
        int allowedAvailabilityColumn = c.getColumnIndexOrThrow(Calendars.ALLOWED_AVAILABILITY);
        mModel.mCalendarAllowedAvailability = c.getString(allowedAvailabilityColumn);
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646

        // Discard the current reminders and replace them with the model's default reminder set.
        // We could attempt to save & restore the reminders that have been added, but that's
        // probably more trouble than it's worth.
        mModel.mReminders.clear();
        mModel.mReminders.addAll(mModel.mDefaultReminders);
        mModel.mHasAlarm = mModel.mReminders.size() != 0;

        // Update the UI elements.
        mReminderItems.clear();
        LinearLayout reminderLayout =
            (LinearLayout) mScrollView.findViewById(R.id.reminder_items_container);
        reminderLayout.removeAllViews();
        prepareReminders();
1647
        prepareAvailability();
Erik's avatar
Erik committed
1648 1649
    }

1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
    /**
     * 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(mActivity, null);
        if (!mAllDayCheckBox.isChecked() && !TextUtils.equals(tz, mTimezone)
                && mModification != EditEventHelper.MODIFY_UNINITIALIZED) {
            int flags = DateUtils.FORMAT_SHOW_TIME;
            boolean is24Format = DateFormat.is24HourFormat(mActivity);
            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(mActivity, 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(
                            mActivity, 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(
                    mActivity, 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(
                            mActivity, mF, millisEnd, millisEnd, flags, tz).toString());

            mStartHomeGroup.setVisibility(View.VISIBLE);
            mEndHomeGroup.setVisibility(View.VISIBLE);
        } else {
            mStartHomeGroup.setVisibility(View.GONE);
            mEndHomeGroup.setVisibility(View.GONE);
        }
    }

Erik's avatar
Erik committed
1718 1719 1720
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
1721
}