AllInOneActivity.java revision 2aeb8d988aa4b65d3402374832613ab977e009dc
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.calendar;
18
19import static android.provider.CalendarContract.EXTRA_EVENT_BEGIN_TIME;
20import static android.provider.CalendarContract.EXTRA_EVENT_END_TIME;
21import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS;
22import static com.android.calendar.CalendarController.EVENT_ATTENDEE_RESPONSE;
23
24import com.android.calendar.CalendarController.EventHandler;
25import com.android.calendar.CalendarController.EventInfo;
26import com.android.calendar.CalendarController.EventType;
27import com.android.calendar.CalendarController.ViewType;
28import com.android.calendar.agenda.AgendaFragment;
29import com.android.calendar.month.MonthByWeekFragment;
30import com.android.calendar.selectcalendars.SelectSyncedCalendarsMultiAccountActivity;
31import com.android.calendar.selectcalendars.SelectVisibleCalendarsFragment;
32
33import android.animation.Animator;
34import android.animation.Animator.AnimatorListener;
35import android.animation.ObjectAnimator;
36import android.app.ActionBar;
37import android.app.ActionBar.Tab;
38import android.app.Activity;
39import android.app.Fragment;
40import android.app.FragmentManager;
41import android.app.FragmentTransaction;
42import android.content.ContentResolver;
43import android.content.ContentUris;
44import android.content.Intent;
45import android.content.SharedPreferences;
46import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
47import android.content.res.Resources;
48import android.database.ContentObserver;
49import android.net.Uri;
50import android.os.Bundle;
51import android.os.Handler;
52import android.provider.CalendarContract;
53import android.provider.CalendarContract.Events;
54import android.text.TextUtils;
55import android.text.format.DateFormat;
56import android.text.format.DateUtils;
57import android.text.format.Time;
58import android.util.Log;
59import android.view.Menu;
60import android.view.MenuItem;
61import android.view.View;
62import android.view.accessibility.AccessibilityEvent;
63import android.widget.RelativeLayout;
64import android.widget.RelativeLayout.LayoutParams;
65import android.widget.SearchView;
66import android.widget.SearchView.OnCloseListener;
67import android.widget.SpinnerAdapter;
68import android.widget.TextView;
69
70import java.util.List;
71import java.util.Locale;
72import java.util.TimeZone;
73
74public class AllInOneActivity extends Activity implements EventHandler,
75        OnSharedPreferenceChangeListener, SearchView.OnQueryTextListener, ActionBar.TabListener,
76        ActionBar.OnNavigationListener, OnCloseListener {
77    private static final String TAG = "AllInOneActivity";
78    private static final boolean DEBUG = false;
79    private static final String EVENT_INFO_FRAGMENT_TAG = "EventInfoFragment";
80    private static final String BUNDLE_KEY_RESTORE_TIME = "key_restore_time";
81    private static final String BUNDLE_KEY_EVENT_ID = "key_event_id";
82    private static final String BUNDLE_KEY_RESTORE_VIEW = "key_restore_view";
83    private static final int HANDLER_KEY = 0;
84    private static final long CONTROLS_ANIMATE_DURATION = 400;
85    private static int CONTROLS_ANIMATE_WIDTH = 280;
86    private static float mScale = 0;
87
88    // Indices of buttons for the drop down menu (tabs replacement)
89    // Must match the strings in the array buttons_list in arrays.xml and the
90    // OnNavigationListener
91    private static final int BUTTON_DAY_INDEX = 0;
92    private static final int BUTTON_WEEK_INDEX = 1;
93    private static final int BUTTON_MONTH_INDEX = 2;
94    private static final int BUTTON_AGENDA_INDEX = 3;
95
96    private static CalendarController mController;
97    private static boolean mIsMultipane;
98    private static boolean mIsTabletConfig;
99    private static boolean mShowAgendaWithMonth;
100    private static boolean mShowEventDetailsWithAgenda;
101    private boolean mOnSaveInstanceStateCalled = false;
102    private ContentResolver mContentResolver;
103    private int mPreviousView;
104    private int mCurrentView;
105    private boolean mPaused = true;
106    private boolean mUpdateOnResume = false;
107    private boolean mHideControls = false;
108    private boolean mShowSideViews = true;
109    private TextView mHomeTime;
110    private TextView mDateRange;
111    private View mMiniMonth;
112    private View mCalendarsList;
113    private View mMiniMonthContainer;
114    private View mSecondaryPane;
115    private String mTimeZone;
116    private boolean mShowCalendarControls;
117    private boolean mShowEventInfoFullScreen;
118
119    private long mViewEventId = -1;
120    private long mIntentEventStartMillis = -1;
121    private long mIntentEventEndMillis = -1;
122    private int mIntentAttendeeResponse = CalendarController.ATTENDEE_NO_RESPONSE;
123
124    // Action bar and Navigation bar (left side of Action bar)
125    private ActionBar mActionBar;
126    private ActionBar.Tab mDayTab;
127    private ActionBar.Tab mWeekTab;
128    private ActionBar.Tab mMonthTab;
129    private ActionBar.Tab mAgendaTab;
130    private SearchView mSearchView;
131    private MenuItem mSearchMenu;
132    private MenuItem mControlsMenu;
133    private Menu mOptionsMenu;
134    private CalendarViewAdapter mActionBarMenuSpinnerAdapter;
135
136    private String mHideString;
137    private String mShowString;
138
139    // Params for animating the controls on the right
140    private LayoutParams mControlsParams = new LayoutParams(CONTROLS_ANIMATE_WIDTH, 0);
141
142    private AnimatorListener mSlideAnimationDoneListener = new AnimatorListener() {
143
144        @Override
145        public void onAnimationCancel(Animator animation) {
146        }
147
148        @Override
149        public void onAnimationEnd(android.animation.Animator animation) {
150            int visibility = mShowSideViews ? View.VISIBLE : View.GONE;
151            mMiniMonth.setVisibility(visibility);
152            mCalendarsList.setVisibility(visibility);
153            mMiniMonthContainer.setVisibility(visibility);
154        }
155
156        @Override
157        public void onAnimationRepeat(android.animation.Animator animation) {
158        }
159
160        @Override
161        public void onAnimationStart(android.animation.Animator animation) {
162        }
163    };
164
165    private Runnable mHomeTimeUpdater = new Runnable() {
166        @Override
167        public void run() {
168            updateHomeClock();
169        }
170    };
171
172    // Create an observer so that we can update the views whenever a
173    // Calendar event changes.
174    private ContentObserver mObserver = new ContentObserver(new Handler()) {
175        @Override
176        public boolean deliverSelfNotifications() {
177            return true;
178        }
179
180        @Override
181        public void onChange(boolean selfChange) {
182            eventsChanged();
183        }
184    };
185
186    @Override
187    protected void onNewIntent(Intent intent) {
188        String action = intent.getAction();
189        if (Intent.ACTION_VIEW.equals(action)) {
190            parseViewAction(intent);
191        }
192    }
193
194    @Override
195    protected void onCreate(Bundle icicle) {
196        if (Utils.getSharedPreference(this, OtherPreferences.KEY_OTHER_1, false)) {
197            setTheme(R.style.CalendarTheme_WithActionBarWallpaper);
198        }
199        super.onCreate(icicle);
200
201        // This needs to be created before setContentView
202        mController = CalendarController.getInstance(this);
203        // Get time from intent or icicle
204        long timeMillis = -1;
205        int viewType = -1;
206        final Intent intent = getIntent();
207        if (icicle != null) {
208            timeMillis = icicle.getLong(BUNDLE_KEY_RESTORE_TIME);
209            viewType = icicle.getInt(BUNDLE_KEY_RESTORE_VIEW, -1);
210        } else {
211            String action = intent.getAction();
212            if (Intent.ACTION_VIEW.equals(action)) {
213                // Open EventInfo later
214                timeMillis = parseViewAction(intent);
215            }
216
217            if (timeMillis == -1) {
218                timeMillis = Utils.timeFromIntentInMillis(intent);
219            }
220        }
221
222        if (viewType == -1) {
223            viewType = Utils.getViewTypeFromIntentAndSharedPref(this);
224        }
225        mTimeZone = Utils.getTimeZone(this, mHomeTimeUpdater);
226        Time t = new Time(mTimeZone);
227        t.set(timeMillis);
228
229        if (icicle != null && intent != null) {
230            Log.d(TAG, "both, icicle:" + icicle.toString() + "  intent:" + intent.toString());
231        } else {
232            Log.d(TAG, "not both, icicle:" + icicle + " intent:" + intent);
233        }
234
235        Resources res = getResources();
236        if (mScale == 0) {
237            mScale = res.getDisplayMetrics().density;
238            CONTROLS_ANIMATE_WIDTH *= mScale;
239        }
240        mHideString = res.getString(R.string.hide_controls);
241        mShowString = res.getString(R.string.show_controls);
242        mControlsParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
243
244        mIsMultipane = Utils.isMultiPaneConfiguration(this);
245        mIsTabletConfig = Utils.getConfigBool(this, R.bool.tablet_config);
246        mShowAgendaWithMonth = Utils.getConfigBool(this, R.bool.show_agenda_with_month);
247        mShowCalendarControls = Utils.getConfigBool(this, R.bool.show_calendar_controls);
248        mShowEventDetailsWithAgenda =
249            Utils.getConfigBool(this, R.bool.show_event_details_with_agenda);
250        mShowEventInfoFullScreen =
251            Utils.getConfigBool(this, R.bool.show_event_info_full_screen);
252
253        Utils.setAllowWeekForDetailView(mIsMultipane);
254
255        // setContentView must be called before configureActionBar
256        setContentView(R.layout.all_in_one);
257
258        if (mIsTabletConfig) {
259            mDateRange = (TextView) findViewById(R.id.date_bar);
260        } else {
261            mDateRange = (TextView) getLayoutInflater().inflate(R.layout.date_range_title, null);
262        }
263
264        // configureActionBar auto-selects the first tab you add, so we need to
265        // call it before we set up our own fragments to make sure it doesn't
266        // overwrite us
267        configureActionBar(viewType);
268
269        // Must be the first to register because this activity can modify the
270        // list of event handlers in it's handle method. This affects who the
271        // rest of the handlers the controller dispatches to are.
272        mController.registerEventHandler(HANDLER_KEY, this);
273
274        mHomeTime = (TextView) findViewById(R.id.home_time);
275        mMiniMonth = findViewById(R.id.mini_month);
276        mCalendarsList = findViewById(R.id.calendar_list);
277        mMiniMonthContainer = findViewById(R.id.mini_month_container);
278        mSecondaryPane = findViewById(R.id.secondary_pane);
279
280        initFragments(timeMillis, viewType, icicle);
281
282        // Listen for changes that would require this to be refreshed
283        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(this);
284        prefs.registerOnSharedPreferenceChangeListener(this);
285
286        mContentResolver = getContentResolver();
287    }
288
289    private long parseViewAction(final Intent intent) {
290        long timeMillis = -1;
291        Uri data = intent.getData();
292        if (data != null && data.isHierarchical()) {
293            List<String> path = data.getPathSegments();
294            if (path.size() == 2 && path.get(0).equals("events")) {
295                try {
296                    mViewEventId = Long.valueOf(data.getLastPathSegment());
297                    if (mViewEventId != -1) {
298                        mIntentEventStartMillis = intent.getLongExtra(EXTRA_EVENT_BEGIN_TIME, 0);
299                        mIntentEventEndMillis = intent.getLongExtra(EXTRA_EVENT_END_TIME, 0);
300                        mIntentAttendeeResponse = intent.getIntExtra(
301                                ATTENDEE_STATUS, CalendarController.ATTENDEE_NO_RESPONSE);
302                        timeMillis = mIntentEventStartMillis;
303                    }
304                } catch (NumberFormatException e) {
305                    // Ignore if mViewEventId can't be parsed
306                }
307            }
308        }
309        return timeMillis;
310    }
311
312    private void configureActionBar(int viewType) {
313        if (mIsTabletConfig) {
314            createTabs();
315        } else {
316            createButtonsSpinner(viewType);
317            mActionBar.setCustomView(mDateRange);
318        }
319        if (mIsMultipane) {
320            mActionBar.setDisplayOptions(
321                    ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
322        } else {
323            mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
324        }
325    }
326
327    private void createTabs() {
328        mActionBar = getActionBar();
329        if (mActionBar == null) {
330            Log.w(TAG, "ActionBar is null.");
331        } else {
332            mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
333            mDayTab = mActionBar.newTab();
334            mDayTab.setText(getString(R.string.day_view));
335            mDayTab.setTabListener(this);
336            mActionBar.addTab(mDayTab);
337            mWeekTab = mActionBar.newTab();
338            mWeekTab.setText(getString(R.string.week_view));
339            mWeekTab.setTabListener(this);
340            mActionBar.addTab(mWeekTab);
341            mMonthTab = mActionBar.newTab();
342            mMonthTab.setText(getString(R.string.month_view));
343            mMonthTab.setTabListener(this);
344            mActionBar.addTab(mMonthTab);
345            mAgendaTab = mActionBar.newTab();
346            mAgendaTab.setText(getString(R.string.agenda_view));
347            mAgendaTab.setTabListener(this);
348            mActionBar.addTab(mAgendaTab);
349        }
350    }
351
352    private void createButtonsSpinner(int viewType) {
353        mActionBarMenuSpinnerAdapter = new CalendarViewAdapter (this, viewType);
354        mActionBar = getActionBar();
355        mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
356        mActionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_HOME|ActionBar.DISPLAY_USE_LOGO|
357                ActionBar.DISPLAY_SHOW_TITLE);
358        mActionBar.setListNavigationCallbacks(mActionBarMenuSpinnerAdapter, this);
359        switch (viewType) {
360            case ViewType.AGENDA:
361                mActionBar.setSelectedNavigationItem(BUTTON_AGENDA_INDEX);
362                break;
363            case ViewType.DAY:
364                mActionBar.setSelectedNavigationItem(BUTTON_DAY_INDEX);
365                break;
366            case ViewType.WEEK:
367                mActionBar.setSelectedNavigationItem(BUTTON_WEEK_INDEX);
368                break;
369            case ViewType.MONTH:
370                mActionBar.setSelectedNavigationItem(BUTTON_MONTH_INDEX);
371                break;
372            default:
373                mActionBar.setSelectedNavigationItem(BUTTON_DAY_INDEX);
374                break;
375       }
376    }
377    // Clear buttons used in the agenda view
378    private void clearOptionsMenu() {
379        if (mOptionsMenu == null) {
380            return;
381        }
382        MenuItem cancelItem = mOptionsMenu.findItem(R.id.action_cancel);
383        MenuItem deleteItem = mOptionsMenu.findItem(R.id.action_delete);
384        MenuItem editItem = mOptionsMenu.findItem(R.id.action_edit);
385        if (cancelItem != null) {
386            cancelItem.setVisible(false);
387        }
388        if (deleteItem != null) {
389            deleteItem.setVisible(false);
390        }
391        if (editItem != null) {
392            editItem.setVisible(false);
393        }
394    }
395
396    @Override
397    protected void onResume() {
398        super.onResume();
399        mContentResolver.registerContentObserver(CalendarContract.Events.CONTENT_URI,
400                true, mObserver);
401        if (mUpdateOnResume) {
402            initFragments(mController.getTime(), mController.getViewType(), null);
403            mUpdateOnResume = false;
404        }
405        updateHomeClock();
406        // Make sure the drop-down menu will get its date updated at midnight
407        if (mActionBarMenuSpinnerAdapter != null) {
408            mActionBarMenuSpinnerAdapter.setMidnightHandler();
409        }
410
411        if (mControlsMenu != null) {
412            mControlsMenu.setTitle(mHideControls ? mShowString : mHideString);
413        }
414        mPaused = false;
415        mOnSaveInstanceStateCalled = false;
416
417        if (mViewEventId != -1 && mIntentEventStartMillis != -1 && mIntentEventEndMillis != -1) {
418            long currentMillis = System.currentTimeMillis();
419            long selectedTime = -1;
420            if (currentMillis > mIntentEventStartMillis && currentMillis < mIntentEventEndMillis) {
421                selectedTime = currentMillis;
422            }
423            mController.sendEventRelatedEventWithResponse(this, EventType.VIEW_EVENT, mViewEventId,
424                    mIntentEventStartMillis, mIntentEventEndMillis, -1, -1,
425                    mIntentAttendeeResponse, selectedTime);
426            mViewEventId = -1;
427            mIntentEventStartMillis = -1;
428            mIntentEventEndMillis = -1;
429        }
430    }
431
432    @Override
433    protected void onPause() {
434        super.onPause();
435        mPaused = true;
436        mHomeTime.removeCallbacks(mHomeTimeUpdater);
437        if (mActionBarMenuSpinnerAdapter != null) {
438            mActionBarMenuSpinnerAdapter.resetMidnightHandler();
439        }
440        mContentResolver.unregisterContentObserver(mObserver);
441        if (isFinishing()) {
442            // Stop listening for changes that would require this to be refreshed
443            SharedPreferences prefs = GeneralPreferences.getSharedPreferences(this);
444            prefs.unregisterOnSharedPreferenceChangeListener(this);
445        }
446        // FRAG_TODO save highlighted days of the week;
447        if (mController.getViewType() != ViewType.EDIT) {
448            Utils.setDefaultView(this, mController.getViewType());
449        }
450    }
451
452    @Override
453    protected void onUserLeaveHint() {
454        mController.sendEvent(this, EventType.USER_HOME, null, null, -1, ViewType.CURRENT);
455        super.onUserLeaveHint();
456    }
457
458    @Override
459    public void onSaveInstanceState(Bundle outState) {
460        mOnSaveInstanceStateCalled = true;
461        super.onSaveInstanceState(outState);
462
463        outState.putLong(BUNDLE_KEY_RESTORE_TIME, mController.getTime());
464        if (mCurrentView == ViewType.EDIT) {
465            outState.putInt(BUNDLE_KEY_RESTORE_VIEW, mCurrentView);
466            outState.putLong(BUNDLE_KEY_EVENT_ID, mController.getEventId());
467        }
468    }
469
470    @Override
471    protected void onDestroy() {
472        super.onDestroy();
473
474        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(this);
475        prefs.unregisterOnSharedPreferenceChangeListener(this);
476        CalendarController.removeInstance(this);
477    }
478
479    private void initFragments(long timeMillis, int viewType, Bundle icicle) {
480        FragmentTransaction ft = getFragmentManager().beginTransaction();
481
482        if (mShowCalendarControls) {
483            Fragment miniMonthFrag = new MonthByWeekFragment(timeMillis, true);
484            ft.replace(R.id.mini_month, miniMonthFrag);
485            mController.registerEventHandler(R.id.mini_month, (EventHandler) miniMonthFrag);
486
487            Fragment selectCalendarsFrag = new SelectVisibleCalendarsFragment();
488            ft.replace(R.id.calendar_list, selectCalendarsFrag);
489            mController.registerEventHandler(
490                    R.id.calendar_list, (EventHandler) selectCalendarsFrag);
491        }
492        if (!mShowCalendarControls || viewType == ViewType.EDIT) {
493            mMiniMonth.setVisibility(View.GONE);
494            mCalendarsList.setVisibility(View.GONE);
495        }
496
497        EventInfo info = null;
498        if (viewType == ViewType.EDIT) {
499            mPreviousView = GeneralPreferences.getSharedPreferences(this).getInt(
500                    GeneralPreferences.KEY_START_VIEW, GeneralPreferences.DEFAULT_START_VIEW);
501
502            long eventId = -1;
503            Intent intent = getIntent();
504            Uri data = intent.getData();
505            if (data != null) {
506                try {
507                    eventId = Long.parseLong(data.getLastPathSegment());
508                } catch (NumberFormatException e) {
509                    if (DEBUG) {
510                        Log.d(TAG, "Create new event");
511                    }
512                }
513            } else if (icicle != null && icicle.containsKey(BUNDLE_KEY_EVENT_ID)) {
514                eventId = icicle.getLong(BUNDLE_KEY_EVENT_ID);
515            }
516
517            long begin = intent.getLongExtra(EXTRA_EVENT_BEGIN_TIME, -1);
518            long end = intent.getLongExtra(EXTRA_EVENT_END_TIME, -1);
519            info = new EventInfo();
520            if (end != -1) {
521                info.endTime = new Time();
522                info.endTime.set(end);
523            }
524            if (begin != -1) {
525                info.startTime = new Time();
526                info.startTime.set(begin);
527            }
528            info.id = eventId;
529            // We set the viewtype so if the user presses back when they are
530            // done editing the controller knows we were in the Edit Event
531            // screen. Likewise for eventId
532            mController.setViewType(viewType);
533            mController.setEventId(eventId);
534        } else {
535            mPreviousView = viewType;
536        }
537
538        setMainPane(ft, R.id.main_pane, viewType, timeMillis, true);
539        ft.commit(); // this needs to be after setMainPane()
540
541        Time t = new Time(mTimeZone);
542        t.set(timeMillis);
543        if (viewType != ViewType.EDIT) {
544            mController.sendEvent(this, EventType.GO_TO, t, null, -1, viewType);
545        }
546    }
547
548    @Override
549    public void onBackPressed() {
550        if (mCurrentView == ViewType.EDIT || mCurrentView == ViewType.DETAIL) {
551            mController.sendEvent(this, EventType.GO_TO, null, null, -1, mPreviousView);
552        } else {
553            super.onBackPressed();
554        }
555    }
556
557    @Override
558    public boolean onCreateOptionsMenu(Menu menu) {
559        super.onCreateOptionsMenu(menu);
560        mOptionsMenu = menu;
561        getMenuInflater().inflate(R.menu.all_in_one_title_bar, menu);
562
563        mSearchMenu = menu.findItem(R.id.action_search);
564        mSearchView = (SearchView) mSearchMenu.getActionView();
565        if (mSearchView != null) {
566            mSearchView.setIconifiedByDefault(true);
567            mSearchView.setOnQueryTextListener(this);
568            mSearchView.setSubmitButtonEnabled(true);
569            mSearchView.setOnCloseListener(this);
570        }
571
572        // Hide the "show/hide controls" button if this is a phone
573        // or the view type is "Month" or "Agenda".
574
575        mControlsMenu = menu.findItem(R.id.action_hide_controls);
576        if (!mShowCalendarControls) {
577            if (mControlsMenu != null) {
578                mControlsMenu.setVisible(false);
579                mControlsMenu.setEnabled(false);
580            }
581        } else if (mControlsMenu != null && mController != null
582                    && (mController.getViewType() == ViewType.MONTH ||
583                        mController.getViewType() == ViewType.AGENDA)) {
584            mControlsMenu.setVisible(false);
585            mControlsMenu.setEnabled(false);
586        } else if (mControlsMenu != null){
587            mControlsMenu.setTitle(mHideControls ? mShowString : mHideString);
588        }
589        return true;
590    }
591
592    @Override
593    public boolean onOptionsItemSelected(MenuItem item) {
594        Time t = null;
595        int viewType = ViewType.CURRENT;
596        switch (item.getItemId()) {
597            case R.id.action_refresh:
598                mController.refreshCalendars();
599                return true;
600            case R.id.action_today:
601                viewType = ViewType.CURRENT;
602                t = new Time(mTimeZone);
603                t.setToNow();
604                break;
605            case R.id.action_create_event:
606                t = new Time();
607                t.set(mController.getTime());
608                if (t.minute >= 30) {
609                    t.hour++;
610                    t.minute = 0;
611                } else {
612                    t.minute = 30;
613                }
614                mController.sendEventRelatedEvent(
615                        this, EventType.CREATE_EVENT, -1, t.toMillis(true), 0, 0, 0, -1);
616                return true;
617            case R.id.action_select_visible_calendars:
618                mController.sendEvent(this, EventType.LAUNCH_SELECT_VISIBLE_CALENDARS, null, null,
619                        0, 0);
620                return true;
621            case R.id.action_settings:
622                mController.sendEvent(this, EventType.LAUNCH_SETTINGS, null, null, 0, 0);
623                return true;
624            case R.id.action_hide_controls:
625                mHideControls = !mHideControls;
626                item.setTitle(mHideControls ? mShowString : mHideString);
627                final ObjectAnimator slideAnimation = ObjectAnimator.ofInt(this, "controlsOffset",
628                        mHideControls ? 0 : CONTROLS_ANIMATE_WIDTH,
629                        mHideControls ? CONTROLS_ANIMATE_WIDTH : 0);
630                slideAnimation.setDuration(CONTROLS_ANIMATE_DURATION);
631                ObjectAnimator.setFrameDelay(0);
632                slideAnimation.start();
633                return true;
634            case R.id.action_search:
635                if (!mIsMultipane && mSearchView != null) {
636                    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
637                    mSearchView.setActivated(true);
638                    mSearchView.setIconified(false);
639                }
640            default:
641                return false;
642        }
643        mController.sendEvent(this, EventType.GO_TO, t, null, -1, viewType);
644        return true;
645    }
646
647    /**
648     * Sets the offset of the controls on the right for animating them off/on
649     * screen. ProGuard strips this if it's not in proguard.flags
650     *
651     * @param controlsOffset The current offset in pixels
652     */
653    public void setControlsOffset(int controlsOffset) {
654        mMiniMonth.setTranslationX(controlsOffset);
655        mCalendarsList.setTranslationX(controlsOffset);
656        mHomeTime.setTranslationX(controlsOffset);
657        mControlsParams.width = Math.max(0, CONTROLS_ANIMATE_WIDTH - controlsOffset);
658        mMiniMonthContainer.setLayoutParams(mControlsParams);
659    }
660
661    @Override
662    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
663        if (key.equals(GeneralPreferences.KEY_WEEK_START_DAY)) {
664            if (mPaused) {
665                mUpdateOnResume = true;
666            } else {
667                initFragments(mController.getTime(), mController.getViewType(), null);
668            }
669        }
670    }
671
672    private void setMainPane(
673            FragmentTransaction ft, int viewId, int viewType, long timeMillis, boolean force) {
674        if (mOnSaveInstanceStateCalled) {
675            return;
676        }
677        if (!force && mCurrentView == viewType) {
678            return;
679        }
680
681        // Remove this when transition to and from month view looks fine.
682        boolean doTransition = viewType != ViewType.MONTH && mCurrentView != ViewType.MONTH;
683        FragmentManager fragmentManager = getFragmentManager();
684        // Check if our previous view was an Agenda view
685        // TODO remove this if framework ever supports nested fragments
686        if (mCurrentView == ViewType.AGENDA) {
687            // If it was, we need to do some cleanup on it to prevent the
688            // edit/delete buttons from coming back on a rotation.
689            Fragment oldFrag = fragmentManager.findFragmentById(viewId);
690            if (oldFrag instanceof AgendaFragment) {
691                ((AgendaFragment) oldFrag).removeFragments(fragmentManager);
692            }
693        }
694
695        if (viewType != mCurrentView) {
696            // The rules for this previous view are different than the
697            // controller's and are used for intercepting the back button.
698            if (mCurrentView != ViewType.EDIT && mCurrentView > 0) {
699                mPreviousView = mCurrentView;
700            }
701            mCurrentView = viewType;
702        }
703        // Create new fragment
704        Fragment frag = null;
705        Fragment secFrag = null;
706        switch (viewType) {
707            case ViewType.AGENDA:
708                if (mActionBar != null && (mActionBar.getSelectedTab() != mAgendaTab)) {
709                    mActionBar.selectTab(mAgendaTab);
710                }
711                if (mActionBarMenuSpinnerAdapter != null) {
712                    mActionBar.setSelectedNavigationItem(CalendarViewAdapter.AGENDA_BUTTON_INDEX);
713                }
714                frag = new AgendaFragment(timeMillis, false);
715                break;
716            case ViewType.DAY:
717                if (mActionBar != null && (mActionBar.getSelectedTab() != mDayTab)) {
718                    mActionBar.selectTab(mDayTab);
719                }
720                if (mActionBarMenuSpinnerAdapter != null) {
721                    mActionBar.setSelectedNavigationItem(CalendarViewAdapter.DAY_BUTTON_INDEX);
722                }
723                frag = new DayFragment(timeMillis, 1);
724                break;
725            case ViewType.WEEK:
726                if (mActionBar != null && (mActionBar.getSelectedTab() != mWeekTab)) {
727                    mActionBar.selectTab(mWeekTab);
728                }
729                if (mActionBarMenuSpinnerAdapter != null) {
730                    mActionBar.setSelectedNavigationItem(CalendarViewAdapter.WEEK_BUTTON_INDEX);
731                }
732                frag = new DayFragment(timeMillis, 7);
733                break;
734            case ViewType.MONTH:
735                if (mActionBar != null && (mActionBar.getSelectedTab() != mMonthTab)) {
736                    mActionBar.selectTab(mMonthTab);
737                }
738                if (mActionBarMenuSpinnerAdapter != null) {
739                    mActionBar.setSelectedNavigationItem(CalendarViewAdapter.MONTH_BUTTON_INDEX);
740                }
741                frag = new MonthByWeekFragment(timeMillis, false);
742                if (mShowAgendaWithMonth) {
743                    secFrag = new AgendaFragment(timeMillis, false);
744                }
745                break;
746            default:
747                throw new IllegalArgumentException(
748                        "Must be Agenda, Day, Week, or Month ViewType, not " + viewType);
749        }
750
751        // Update the current view so that the menu can update its look according to the
752        // current view.
753        if (!mIsTabletConfig && mActionBarMenuSpinnerAdapter != null) {
754            mActionBarMenuSpinnerAdapter.setMainView(viewType);
755        }
756
757
758        // Show date only on tablet configurations in views different than Agenda
759        if (!mIsTabletConfig) {
760            mDateRange.setVisibility(View.GONE);
761        } else if (viewType != ViewType.AGENDA) {
762            mDateRange.setVisibility(View.VISIBLE);
763        } else {
764            mDateRange.setVisibility(View.GONE);
765        }
766
767        // Clear unnecessary buttons from the option menu when switching from the agenda view
768        if (viewType != ViewType.AGENDA) {
769            clearOptionsMenu();
770        }
771
772        boolean doCommit = false;
773        if (ft == null) {
774            doCommit = true;
775            ft = fragmentManager.beginTransaction();
776        }
777
778        if (doTransition) {
779            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
780        }
781
782        ft.replace(viewId, frag);
783        if (mShowAgendaWithMonth) {
784
785            // Show/hide secondary fragment
786
787            if (secFrag != null) {
788                ft.replace(R.id.secondary_pane, secFrag);
789                mSecondaryPane.setVisibility(View.VISIBLE);
790            } else {
791                mSecondaryPane.setVisibility(View.GONE);
792                Fragment f = fragmentManager.findFragmentById(R.id.secondary_pane);
793                if (f != null) {
794                    ft.remove(f);
795                }
796                mController.deregisterEventHandler(R.id.secondary_pane);
797            }
798        }
799        if (DEBUG) {
800            Log.d(TAG, "Adding handler with viewId " + viewId + " and type " + viewType);
801        }
802        // If the key is already registered this will replace it
803        mController.registerEventHandler(viewId, (EventHandler) frag);
804        if (secFrag != null) {
805            mController.registerEventHandler(viewId, (EventHandler) secFrag);
806        }
807
808        if (doCommit) {
809            Log.d(TAG, "setMainPane AllInOne=" + this + " finishing:" + this.isFinishing());
810            ft.commit();
811        }
812    }
813
814    private void setTitleInActionBar(EventInfo event) {
815        if (event.eventType != EventType.UPDATE_TITLE || mActionBar == null) {
816            return;
817        }
818
819        final long start = event.startTime.toMillis(false /* use isDst */);
820        final long end;
821        if (event.endTime != null) {
822            end = event.endTime.toMillis(false /* use isDst */);
823        } else {
824            end = start;
825        }
826
827        final String msg = Utils.formatDateRange(this, start, end, (int) event.extraLong);
828        CharSequence oldDate = mDateRange.getText();
829        mDateRange.setText(msg);
830        if (!TextUtils.equals(oldDate, msg)) {
831            mDateRange.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
832        }
833    }
834
835    private void updateHomeClock() {
836        mTimeZone = Utils.getTimeZone(this, mHomeTimeUpdater);
837        if (mIsMultipane && (mCurrentView == ViewType.DAY || mCurrentView == ViewType.WEEK)
838                && !TextUtils.equals(mTimeZone, Time.getCurrentTimezone())) {
839            Time time = new Time(mTimeZone);
840            time.setToNow();
841            long millis = time.toMillis(true);
842            boolean isDST = time.isDst != 0;
843            int flags = DateUtils.FORMAT_SHOW_TIME;
844            if (DateFormat.is24HourFormat(this)) {
845                flags |= DateUtils.FORMAT_24HOUR;
846            }
847            // Formats the time as
848            String timeString = (new StringBuilder(
849                    Utils.formatDateRange(this, millis, millis, flags))).append(" ").append(
850                    TimeZone.getTimeZone(mTimeZone).getDisplayName(
851                            isDST, TimeZone.SHORT, Locale.getDefault())).toString();
852            mHomeTime.setText(timeString);
853            mHomeTime.setVisibility(View.VISIBLE);
854            // Update when the minute changes
855            mHomeTime.postDelayed(
856                    mHomeTimeUpdater,
857                    DateUtils.MINUTE_IN_MILLIS - (millis % DateUtils.MINUTE_IN_MILLIS));
858        } else {
859            mHomeTime.setVisibility(View.INVISIBLE);
860        }
861    }
862
863    @Override
864    public long getSupportedEventTypes() {
865        return EventType.GO_TO | EventType.VIEW_EVENT | EventType.UPDATE_TITLE;
866    }
867
868    @Override
869    public void handleEvent(EventInfo event) {
870        Log.d(TAG, "handleEvent AllInOne=" + this);
871        if (event.eventType == EventType.GO_TO) {
872            setMainPane(
873                    null, R.id.main_pane, event.viewType, event.startTime.toMillis(false), false);
874            if (mSearchView != null) {
875                mSearchView.clearFocus();
876            }
877
878            if (mShowCalendarControls) {
879                if (event.viewType == ViewType.MONTH || event.viewType == ViewType.AGENDA) {
880                    // hide minimonth and calendar frag
881                    mShowSideViews = false;
882                    if (mControlsMenu != null) {
883                        mControlsMenu.setVisible(false);
884                        mControlsMenu.setEnabled(false);
885
886                        if (!mHideControls) {
887                            final ObjectAnimator slideAnimation = ObjectAnimator.ofInt(this,
888                                    "controlsOffset", 0, CONTROLS_ANIMATE_WIDTH);
889                            slideAnimation.addListener(mSlideAnimationDoneListener);
890                            slideAnimation.setDuration(220);
891                            ObjectAnimator.setFrameDelay(0);
892                            slideAnimation.start();
893                        }
894                    } else {
895                        mMiniMonth.setVisibility(View.GONE);
896                        mCalendarsList.setVisibility(View.GONE);
897                        mMiniMonthContainer.setVisibility(View.GONE);
898                    }
899                } else {
900                    // show minimonth and calendar frag
901                    mShowSideViews = true;
902                    mMiniMonth.setVisibility(View.VISIBLE);
903                    mCalendarsList.setVisibility(View.VISIBLE);
904                    mMiniMonthContainer.setVisibility(View.VISIBLE);
905                    if (mControlsMenu != null) {
906                        mControlsMenu.setVisible(true);
907                        mControlsMenu.setEnabled(true);
908                        if (!mHideControls &&
909                                (mController.getPreviousViewType() == ViewType.MONTH ||
910                                 mController.getPreviousViewType() == ViewType.AGENDA)) {
911                            final ObjectAnimator slideAnimation = ObjectAnimator.ofInt(this,
912                                    "controlsOffset", CONTROLS_ANIMATE_WIDTH, 0);
913                            slideAnimation.setDuration(220);
914                            ObjectAnimator.setFrameDelay(0);
915                            slideAnimation.start();
916                        }
917                    }
918                }
919            }
920        } else if (event.eventType == EventType.VIEW_EVENT) {
921
922            // If in Agenda view and "show_event_details_with_agenda" is "true",
923            // do not create the event info fragment here, it will be created by the Agenda
924            // fragment
925
926            if (mCurrentView == ViewType.AGENDA && mShowEventDetailsWithAgenda) {
927                if (event.selectedTime != null) {
928                    mController.sendEvent(this, EventType.GO_TO, event.selectedTime,
929                        event.selectedTime, event.id, ViewType.AGENDA);
930                }
931            } else {
932                if (mShowEventInfoFullScreen) {
933                    // start event info as activity
934                    Intent intent = new Intent(Intent.ACTION_VIEW);
935                    Uri eventUri = ContentUris.withAppendedId(Events.CONTENT_URI, event.id);
936                    intent.setData(eventUri);
937                    intent.setClassName(this, EventInfoActivity.class.getName());
938                    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT |
939                            Intent.FLAG_ACTIVITY_SINGLE_TOP);
940                    intent.putExtra(EXTRA_EVENT_BEGIN_TIME, event.startTime.toMillis(false));
941                    intent.putExtra(EXTRA_EVENT_END_TIME, event.endTime.toMillis(false));
942                    intent.putExtra(EVENT_ATTENDEE_RESPONSE, (int)event.extraLong);
943                    startActivity(intent);
944                } else {
945                    // start event info as a dialog
946                    EventInfoFragment fragment = new EventInfoFragment(this,
947                            event.id, event.startTime.toMillis(false),
948                            event.endTime.toMillis(false), (int) event.extraLong, true);
949                    // TODO Fix the temp hack below: && mCurrentView !=
950                    // ViewType.AGENDA
951                    if (event.selectedTime != null && mCurrentView != ViewType.AGENDA) {
952                        mController.sendEvent(this, EventType.GO_TO, event.selectedTime,
953                                event.selectedTime, -1, ViewType.DETAIL);
954                    }
955                    fragment.setDialogParams(event.x, event.y);
956                    FragmentManager fm = getFragmentManager();
957                    FragmentTransaction ft = fm.beginTransaction();
958                    // if we have an old popup close it
959                    Fragment fOld = fm.findFragmentByTag(EVENT_INFO_FRAGMENT_TAG);
960                    if (fOld != null && fOld.isAdded()) {
961                        ft.remove(fOld);
962                    }
963                    ft.add(fragment, EVENT_INFO_FRAGMENT_TAG);
964                    ft.commit();
965                }
966            }
967        } else if (event.eventType == EventType.UPDATE_TITLE) {
968            setTitleInActionBar(event);
969            if (!mIsTabletConfig) {
970                mActionBarMenuSpinnerAdapter.setTime(event.startTime.toMillis(false));
971            }
972        }
973        updateHomeClock();
974    }
975
976    // Needs to be in proguard whitelist
977    // Specified as listener via android:onClick in a layout xml
978    public void handleSelectSyncedCalendarsClicked(View v) {
979        mController.sendEvent(this, EventType.LAUNCH_SETTINGS, null, null, null, 0, 0,
980                CalendarController.EXTRA_GOTO_TIME, null,
981                null);
982    }
983
984    @Override
985    public void eventsChanged() {
986        mController.sendEvent(this, EventType.EVENTS_CHANGED, null, null, -1, ViewType.CURRENT);
987    }
988
989    @Override
990    public boolean onQueryTextChange(String newText) {
991        return false;
992    }
993
994    @Override
995    public boolean onQueryTextSubmit(String query) {
996        if ("TARDIS".equalsIgnoreCase(query)) {
997            Utils.tardis();
998        }
999        mSearchView.clearFocus();
1000        mController.sendEvent(this, EventType.SEARCH, null, null, -1, ViewType.CURRENT, -1, query,
1001                getComponentName());
1002        return false;
1003    }
1004
1005    @Override
1006    public void onTabSelected(Tab tab, FragmentTransaction ft) {
1007        Log.w(TAG, "TabSelected AllInOne=" + this + " finishing:" + this.isFinishing());
1008        if (tab == mDayTab && mCurrentView != ViewType.DAY) {
1009            mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.DAY);
1010        } else if (tab == mWeekTab && mCurrentView != ViewType.WEEK) {
1011            mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.WEEK);
1012        } else if (tab == mMonthTab && mCurrentView != ViewType.MONTH) {
1013            mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.MONTH);
1014        } else if (tab == mAgendaTab && mCurrentView != ViewType.AGENDA) {
1015            mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.AGENDA);
1016        } else {
1017            Log.w(TAG, "TabSelected event from unknown tab: "
1018                    + (tab == null ? "null" : tab.getText()));
1019            Log.w(TAG, "CurrentView:" + mCurrentView + " Tab:" + tab.toString() + " Day:" + mDayTab
1020                    + " Week:" + mWeekTab + " Month:" + mMonthTab + " Agenda:" + mAgendaTab);
1021        }
1022    }
1023
1024    @Override
1025    public void onTabReselected(Tab tab, FragmentTransaction ft) {
1026    }
1027
1028    @Override
1029    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
1030    }
1031
1032
1033    @Override
1034    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
1035        switch (itemPosition) {
1036            case CalendarViewAdapter.DAY_BUTTON_INDEX:
1037                if (mCurrentView != ViewType.DAY) {
1038                    mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.DAY);
1039                }
1040                break;
1041            case CalendarViewAdapter.WEEK_BUTTON_INDEX:
1042                if (mCurrentView != ViewType.WEEK) {
1043                    mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.WEEK);
1044                }
1045                break;
1046            case CalendarViewAdapter.MONTH_BUTTON_INDEX:
1047                if (mCurrentView != ViewType.MONTH) {
1048                    mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.MONTH);
1049                }
1050                break;
1051            case CalendarViewAdapter.AGENDA_BUTTON_INDEX:
1052                if (mCurrentView != ViewType.AGENDA) {
1053                    mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.AGENDA);
1054                }
1055                break;
1056            default:
1057                Log.w(TAG, "ItemSelected event from unknown button: " + itemPosition);
1058                Log.w(TAG, "CurrentView:" + mCurrentView + " Button:" + itemPosition +
1059                        " Day:" + mDayTab + " Week:" + mWeekTab + " Month:" + mMonthTab +
1060                        " Agenda:" + mAgendaTab);
1061                break;
1062        }
1063        return false;
1064    }
1065
1066    /*
1067     * Handles the search view being closed.
1068     */
1069    @Override
1070    public boolean onClose() {
1071        if (!mIsMultipane) {
1072            mSearchMenu.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1073            invalidateOptionsMenu();
1074        }
1075        return false;
1076    }
1077}
1078