AllInOneActivity.java revision 96a0b5436f79157e8175b3b761fd5ccfe26a7f62
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.Calendar.EVENT_BEGIN_TIME;
20import static android.provider.Calendar.EVENT_END_TIME;
21import static android.provider.Calendar.AttendeesColumns.ATTENDEE_STATUS;
22
23import com.android.calendar.CalendarController.EventHandler;
24import com.android.calendar.CalendarController.EventInfo;
25import com.android.calendar.CalendarController.EventType;
26import com.android.calendar.CalendarController.ViewType;
27import com.android.calendar.agenda.AgendaFragment;
28import com.android.calendar.month.MonthByWeekFragment;
29import com.android.calendar.selectcalendars.SelectCalendarsFragment;
30
31import android.animation.Animator;
32import android.animation.Animator.AnimatorListener;
33import android.animation.ObjectAnimator;
34import android.app.ActionBar;
35import android.app.ActionBar.Tab;
36import android.app.Activity;
37import android.app.Fragment;
38import android.app.FragmentManager;
39import android.app.FragmentTransaction;
40import android.content.ContentResolver;
41import android.content.Intent;
42import android.content.SharedPreferences;
43import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
44import android.content.res.Configuration;
45import android.content.res.Resources;
46import android.database.ContentObserver;
47import android.net.Uri;
48import android.os.Bundle;
49import android.os.Handler;
50import android.provider.Calendar;
51import android.text.TextUtils;
52import android.text.format.DateFormat;
53import android.text.format.DateUtils;
54import android.text.format.Time;
55import android.util.Log;
56import android.view.Menu;
57import android.view.MenuItem;
58import android.view.View;
59import android.view.accessibility.AccessibilityEvent;
60import android.widget.RelativeLayout;
61import android.widget.RelativeLayout.LayoutParams;
62import android.widget.SearchView;
63import android.widget.TextView;
64
65import java.util.List;
66import java.util.Locale;
67import java.util.TimeZone;
68
69public class AllInOneActivity extends Activity implements EventHandler,
70        OnSharedPreferenceChangeListener, SearchView.OnQueryTextListener,
71        ActionBar.TabListener {
72    private static final String TAG = "AllInOneActivity";
73    private static final boolean DEBUG = false;
74    private static final String EVENT_INFO_FRAGMENT_TAG = "EventInfoFragment";
75    private static final String BUNDLE_KEY_RESTORE_TIME = "key_restore_time";
76    private static final String BUNDLE_KEY_EVENT_ID = "key_event_id";
77    private static final String BUNDLE_KEY_RESTORE_VIEW = "key_restore_view";
78    private static final int HANDLER_KEY = 0;
79    private static final long CONTROLS_ANIMATE_DURATION = 400;
80    private static int CONTROLS_ANIMATE_WIDTH = 267;
81    private static float mScale = 0;
82
83    private static CalendarController mController;
84    private static boolean mIsMultipane;
85    private boolean mOnSaveInstanceStateCalled = false;
86    private ContentResolver mContentResolver;
87    private int mPreviousView;
88    private int mCurrentView;
89    private boolean mPaused = true;
90    private boolean mUpdateOnResume = false;
91    private boolean mHideControls = false;
92    private boolean mShowSideViews = true;
93    private TextView mHomeTime;
94    private TextView mDateRange;
95    private View mMiniMonth;
96    private View mCalendarsList;
97    private View mMiniMonthContainer;
98    private View mSecondaryPane;
99    private String mTimeZone;
100
101    private long mViewEventId = -1;
102    private long mIntentEventStartMillis = -1;
103    private long mIntentEventEndMillis = -1;
104    private int mIntentAttendeeResponse = CalendarController.ATTENDEE_NO_RESPONSE;
105
106    // Action bar and Navigation bar (left side of Action bar)
107    private ActionBar mActionBar;
108    private ActionBar.Tab mDayTab;
109    private ActionBar.Tab mWeekTab;
110    private ActionBar.Tab mMonthTab;
111    private ActionBar.Tab mAgendaTab;
112    private SearchView mSearchView;
113    private MenuItem mControlsMenu;
114
115    private String mHideString;
116    private String mShowString;
117
118    // Params for animating the controls on the right
119    private LayoutParams mControlsParams = new LayoutParams(CONTROLS_ANIMATE_WIDTH, 0);
120
121    private AnimatorListener mSlideAnimationDoneListener = new AnimatorListener() {
122
123        @Override
124        public void onAnimationCancel(Animator animation) {
125        }
126
127        @Override
128        public void onAnimationEnd(android.animation.Animator animation) {
129            int visibility = mShowSideViews ? View.VISIBLE : View.GONE;
130            mMiniMonth.setVisibility(visibility);
131            mCalendarsList.setVisibility(visibility);
132            mMiniMonthContainer.setVisibility(visibility);
133        }
134
135        @Override
136        public void onAnimationRepeat(android.animation.Animator animation) {
137        }
138
139        @Override
140        public void onAnimationStart(android.animation.Animator animation) {
141        }
142    };
143
144    private Runnable mHomeTimeUpdater = new Runnable() {
145        @Override
146        public void run() {
147            updateHomeClock();
148        }
149    };
150
151    // Create an observer so that we can update the views whenever a
152    // Calendar event changes.
153    private ContentObserver mObserver = new ContentObserver(new Handler()) {
154        @Override
155        public boolean deliverSelfNotifications() {
156            return true;
157        }
158
159        @Override
160        public void onChange(boolean selfChange) {
161            eventsChanged();
162        }
163    };
164
165    @Override
166    protected void onNewIntent(Intent intent) {
167        String action = intent.getAction();
168        if (Intent.ACTION_VIEW.equals(action)) {
169            parseViewAction(intent);
170        }
171    }
172
173    @Override
174    protected void onCreate(Bundle icicle) {
175        if (Utils.getSharedPreference(this, OtherPreferences.KEY_OTHER_1, false)) {
176            setTheme(R.style.CalendarTheme_WithActionBarWallpaper);
177        }
178        super.onCreate(icicle);
179
180        // This needs to be created before setContentView
181        mController = CalendarController.getInstance(this);
182        // Get time from intent or icicle
183        long timeMillis = -1;
184        int viewType = -1;
185        final Intent intent = getIntent();
186        if (icicle != null) {
187            timeMillis = icicle.getLong(BUNDLE_KEY_RESTORE_TIME);
188            viewType = icicle.getInt(BUNDLE_KEY_RESTORE_VIEW, -1);
189        } else {
190            String action = intent.getAction();
191            if (Intent.ACTION_VIEW.equals(action)) {
192                // Open EventInfo later
193                timeMillis = parseViewAction(intent);
194            }
195
196            if (timeMillis == -1) {
197                timeMillis = Utils.timeFromIntentInMillis(intent);
198            }
199        }
200
201        if (viewType == -1) {
202            viewType = Utils.getViewTypeFromIntentAndSharedPref(this);
203        }
204        mTimeZone = Utils.getTimeZone(this, mHomeTimeUpdater);
205        Time t = new Time(mTimeZone);
206        t.set(timeMillis);
207
208        if (icicle != null && intent != null) {
209            Log.d(TAG, "both, icicle:" + icicle.toString() + "  intent:" + intent.toString());
210        } else {
211            Log.d(TAG, "not both, icicle:" + icicle + " intent:" + intent);
212        }
213
214        Resources res = getResources();
215        if (mScale == 0) {
216            mScale = res.getDisplayMetrics().density;
217            CONTROLS_ANIMATE_WIDTH *= mScale;
218        }
219        mHideString = res.getString(R.string.hide_controls);
220        mShowString = res.getString(R.string.show_controls);
221        mControlsParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
222
223        mIsMultipane = Utils.isMultiPaneConfiguration(this);
224
225        Utils.setAllowWeekForDetailView(mIsMultipane);
226
227        mDateRange = (TextView) getLayoutInflater().inflate(R.layout.date_range_title, null);
228
229        // setContentView must be called before configureActionBar
230        setContentView(R.layout.all_in_one);
231        // configureActionBar auto-selects the first tab you add, so we need to
232        // call it before we set up our own fragments to make sure it doesn't
233        // overwrite us
234        configureActionBar();
235
236        // Must be the first to register because this activity can modify the
237        // list of event handlers in it's handle method. This affects who the
238        // rest of the handlers the controller dispatches to are.
239        mController.registerEventHandler(HANDLER_KEY, this);
240
241        mHomeTime = (TextView) findViewById(R.id.home_time);
242        mMiniMonth = findViewById(R.id.mini_month);
243        mCalendarsList = findViewById(R.id.calendar_list);
244        mMiniMonthContainer = findViewById(R.id.mini_month_container);
245        mSecondaryPane = findViewById(R.id.secondary_pane);
246
247        initFragments(timeMillis, viewType, icicle);
248
249        // Listen for changes that would require this to be refreshed
250        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(this);
251        prefs.registerOnSharedPreferenceChangeListener(this);
252
253        mContentResolver = getContentResolver();
254    }
255
256    private long parseViewAction(final Intent intent) {
257        long timeMillis = -1;
258        Uri data = intent.getData();
259        if (data != null && data.isHierarchical()) {
260            List<String> path = data.getPathSegments();
261            if (path.size() == 2 && path.get(0).equals("events")) {
262                try {
263                    mViewEventId = Long.valueOf(data.getLastPathSegment());
264                    if (mViewEventId != -1) {
265                        mIntentEventStartMillis = intent.getLongExtra(EVENT_BEGIN_TIME, 0);
266                        mIntentEventEndMillis = intent.getLongExtra(EVENT_END_TIME, 0);
267                        mIntentAttendeeResponse = intent.getIntExtra(
268                                ATTENDEE_STATUS, CalendarController.ATTENDEE_NO_RESPONSE);
269                        timeMillis = mIntentEventStartMillis;
270                    }
271                } catch (NumberFormatException e) {
272                    // Ignore if mViewEventId can't be parsed
273                }
274            }
275        }
276        return timeMillis;
277    }
278
279    private void configureActionBar() {
280        mActionBar = getActionBar();
281        mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
282        if (mActionBar == null) {
283            Log.w(TAG, "ActionBar is null.");
284        } else {
285            mDayTab = mActionBar.newTab();
286            mDayTab.setText(getString(R.string.day_view));
287            mDayTab.setTabListener(this);
288            mActionBar.addTab(mDayTab);
289            mWeekTab = mActionBar.newTab();
290            mWeekTab.setText(getString(R.string.week_view));
291            mWeekTab.setTabListener(this);
292            mActionBar.addTab(mWeekTab);
293            mMonthTab = mActionBar.newTab();
294            mMonthTab.setText(getString(R.string.month_view));
295            mMonthTab.setTabListener(this);
296            mActionBar.addTab(mMonthTab);
297            mAgendaTab = mActionBar.newTab();
298            mAgendaTab.setText(getString(R.string.agenda_view));
299            mAgendaTab.setTabListener(this);
300            mActionBar.addTab(mAgendaTab);
301            mActionBar.setCustomView(mDateRange);
302            if (mIsMultipane) {
303                mActionBar.setDisplayOptions(
304                        ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
305            } else {
306                mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
307            }
308        }
309    }
310
311    @Override
312    protected void onResume() {
313        super.onResume();
314        mContentResolver.registerContentObserver(Calendar.Events.CONTENT_URI, true, mObserver);
315        if (mUpdateOnResume) {
316            initFragments(mController.getTime(), mController.getViewType(), null);
317            mUpdateOnResume = false;
318        }
319        updateHomeClock();
320        if (mControlsMenu != null) {
321            mControlsMenu.setTitle(mHideControls ? mShowString : mHideString);
322        }
323        mPaused = false;
324        mOnSaveInstanceStateCalled = false;
325
326        if (mViewEventId != -1 && mIntentEventStartMillis != -1 && mIntentEventEndMillis != -1) {
327            long currentMillis = System.currentTimeMillis();
328            long selectedTime = -1;
329            if (currentMillis > mIntentEventStartMillis && currentMillis < mIntentEventEndMillis) {
330                selectedTime = currentMillis;
331            }
332            mController.sendEventRelatedEventWithResponse(this, EventType.VIEW_EVENT, mViewEventId,
333                    mIntentEventStartMillis, mIntentEventEndMillis, -1, -1,
334                    mIntentAttendeeResponse, selectedTime);
335            mViewEventId = -1;
336            mIntentEventStartMillis = -1;
337            mIntentEventEndMillis = -1;
338        }
339    }
340
341    @Override
342    protected void onPause() {
343        super.onPause();
344        mPaused = true;
345        mHomeTime.removeCallbacks(mHomeTimeUpdater);
346        mContentResolver.unregisterContentObserver(mObserver);
347        if (isFinishing()) {
348            // Stop listening for changes that would require this to be refreshed
349            SharedPreferences prefs = GeneralPreferences.getSharedPreferences(this);
350            prefs.unregisterOnSharedPreferenceChangeListener(this);
351        }
352        // FRAG_TODO save highlighted days of the week;
353        if (mController.getViewType() != ViewType.EDIT) {
354            Utils.setDefaultView(this, mController.getViewType());
355        }
356    }
357
358    @Override
359    protected void onUserLeaveHint() {
360        mController.sendEvent(this, EventType.USER_HOME, null, null, -1, ViewType.CURRENT);
361        super.onUserLeaveHint();
362    }
363
364    @Override
365    public void onSaveInstanceState(Bundle outState) {
366        mOnSaveInstanceStateCalled = true;
367        super.onSaveInstanceState(outState);
368
369        outState.putLong(BUNDLE_KEY_RESTORE_TIME, mController.getTime());
370        if (mCurrentView == ViewType.EDIT) {
371            outState.putInt(BUNDLE_KEY_RESTORE_VIEW, mCurrentView);
372            outState.putLong(BUNDLE_KEY_EVENT_ID, mController.getEventId());
373        }
374    }
375
376    @Override
377    protected void onDestroy() {
378        super.onDestroy();
379
380        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(this);
381        prefs.unregisterOnSharedPreferenceChangeListener(this);
382        CalendarController.removeInstance(this);
383    }
384
385    private void initFragments(long timeMillis, int viewType, Bundle icicle) {
386        FragmentTransaction ft = getFragmentManager().beginTransaction();
387
388        if (mIsMultipane) {
389            Fragment miniMonthFrag = new MonthByWeekFragment(timeMillis, true);
390            ft.replace(R.id.mini_month, miniMonthFrag);
391            mController.registerEventHandler(R.id.mini_month, (EventHandler) miniMonthFrag);
392
393            Fragment selectCalendarsFrag = new SelectCalendarsFragment();
394            ft.replace(R.id.calendar_list, selectCalendarsFrag);
395            mController.registerEventHandler(
396                    R.id.calendar_list, (EventHandler) selectCalendarsFrag);
397        }
398        if (!mIsMultipane || viewType == ViewType.EDIT) {
399            mMiniMonth.setVisibility(View.GONE);
400            mCalendarsList.setVisibility(View.GONE);
401        }
402
403        EventInfo info = null;
404        if (viewType == ViewType.EDIT) {
405            mPreviousView = GeneralPreferences.getSharedPreferences(this).getInt(
406                    GeneralPreferences.KEY_START_VIEW, GeneralPreferences.DEFAULT_START_VIEW);
407
408            long eventId = -1;
409            Intent intent = getIntent();
410            Uri data = intent.getData();
411            if (data != null) {
412                try {
413                    eventId = Long.parseLong(data.getLastPathSegment());
414                } catch (NumberFormatException e) {
415                    if (DEBUG) {
416                        Log.d(TAG, "Create new event");
417                    }
418                }
419            } else if (icicle != null && icicle.containsKey(BUNDLE_KEY_EVENT_ID)) {
420                eventId = icicle.getLong(BUNDLE_KEY_EVENT_ID);
421            }
422
423            long begin = intent.getLongExtra(EVENT_BEGIN_TIME, -1);
424            long end = intent.getLongExtra(EVENT_END_TIME, -1);
425            info = new EventInfo();
426            if (end != -1) {
427                info.endTime = new Time();
428                info.endTime.set(end);
429            }
430            if (begin != -1) {
431                info.startTime = new Time();
432                info.startTime.set(begin);
433            }
434            info.id = eventId;
435            // We set the viewtype so if the user presses back when they are
436            // done editing the controller knows we were in the Edit Event
437            // screen. Likewise for eventId
438            mController.setViewType(viewType);
439            mController.setEventId(eventId);
440        } else {
441            mPreviousView = viewType;
442        }
443
444        setMainPane(ft, R.id.main_pane, viewType, timeMillis, true);
445        if (!mIsMultipane && viewType == ViewType.MONTH) {
446            setAgendaPane(ft, R.id.secondary_pane, timeMillis);
447            mSecondaryPane.setVisibility(View.VISIBLE);
448        } else if (mSecondaryPane != null) {
449            mSecondaryPane.setVisibility(View.GONE);
450        }
451
452        ft.commit(); // this needs to be after setMainPane()
453
454        Time t = new Time(mTimeZone);
455        t.set(timeMillis);
456        if (viewType != ViewType.EDIT) {
457            mController.sendEvent(this, EventType.GO_TO, t, null, -1, viewType);
458        }
459    }
460
461    @Override
462    public void onBackPressed() {
463        if (mCurrentView == ViewType.EDIT || mCurrentView == ViewType.DETAIL) {
464            mController.sendEvent(this, EventType.GO_TO, null, null, -1, mPreviousView);
465        } else {
466            super.onBackPressed();
467        }
468    }
469
470    @Override
471    public boolean onCreateOptionsMenu(Menu menu) {
472        super.onCreateOptionsMenu(menu);
473
474        getMenuInflater().inflate(R.menu.all_in_one_title_bar, menu);
475
476        mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
477        if (mSearchView != null) {
478            mSearchView.setIconifiedByDefault(true);
479            mSearchView.setOnQueryTextListener(this);
480            mSearchView.setSubmitButtonEnabled(true);
481            if (!mIsMultipane)
482                mSearchView.setVisibility(View.GONE);
483        }
484
485        // Hide the "show/hide controls" button if this is a phone
486        // or the view type is "Month".
487
488        mControlsMenu = menu.findItem(R.id.action_hide_controls);
489        if (!mIsMultipane) {
490            if (mControlsMenu != null) {
491                mControlsMenu.setVisible(false);
492                mControlsMenu.setEnabled(false);
493            }
494        } else if (mControlsMenu != null && mController != null
495                    && mController.getViewType() == ViewType.MONTH) {
496            mControlsMenu.setVisible(false);
497            mControlsMenu.setEnabled(false);
498        }
499        return true;
500    }
501
502    @Override
503    public boolean onOptionsItemSelected(MenuItem item) {
504        Time t = null;
505        int viewType = ViewType.CURRENT;
506        switch (item.getItemId()) {
507            case R.id.action_refresh:
508                mController.refreshCalendars();
509                return true;
510            case R.id.action_today:
511                viewType = ViewType.CURRENT;
512                t = new Time(mTimeZone);
513                t.setToNow();
514                break;
515            case R.id.action_create_event:
516                t = new Time();
517                t.set(mController.getTime());
518                if (t.minute >= 30) {
519                    t.hour++;
520                    t.minute = 0;
521                } else {
522                    t.minute = 30;
523                }
524                mController.sendEventRelatedEvent(
525                        this, EventType.CREATE_EVENT, -1, t.toMillis(true), 0, 0, 0, -1);
526                return true;
527            case R.id.action_settings:
528                mController.sendEvent(this, EventType.LAUNCH_SETTINGS, null, null, 0, 0);
529                return true;
530            case R.id.action_hide_controls:
531                mHideControls = !mHideControls;
532                item.setTitle(mHideControls ? mShowString : mHideString);
533                final ObjectAnimator slideAnimation = ObjectAnimator.ofInt(this, "controlsOffset",
534                        mHideControls ? 0 : CONTROLS_ANIMATE_WIDTH,
535                        mHideControls ? CONTROLS_ANIMATE_WIDTH : 0);
536                slideAnimation.setDuration(CONTROLS_ANIMATE_DURATION);
537                ObjectAnimator.setFrameDelay(0);
538                slideAnimation.start();
539                return true;
540            default:
541                return false;
542        }
543        mController.sendEvent(this, EventType.GO_TO, t, null, -1, viewType);
544        return true;
545    }
546
547    /**
548     * Sets the offset of the controls on the right for animating them off/on
549     * screen. ProGuard strips this if it's not in proguard.flags
550     *
551     * @param controlsOffset The current offset in pixels
552     */
553    public void setControlsOffset(int controlsOffset) {
554        mMiniMonth.setTranslationX(controlsOffset);
555        mCalendarsList.setTranslationX(controlsOffset);
556        mHomeTime.setTranslationX(controlsOffset);
557        mControlsParams.width = Math.max(0, CONTROLS_ANIMATE_WIDTH - controlsOffset);
558        mMiniMonthContainer.setLayoutParams(mControlsParams);
559    }
560
561    @Override
562    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
563        if (key.equals(GeneralPreferences.KEY_WEEK_START_DAY)) {
564            if (mPaused) {
565                mUpdateOnResume = true;
566            } else {
567                initFragments(mController.getTime(), mController.getViewType(), null);
568            }
569        }
570    }
571
572    private void setAgendaPane(FragmentTransaction ft, int viewId, long timeMillis) {
573        boolean doCommit = false;
574        Fragment frag = new AgendaFragment(timeMillis);
575        if (ft == null) {
576            doCommit = true;
577            ft = getFragmentManager().beginTransaction();
578        }
579        ft.replace(viewId, frag);
580        if (doCommit) {
581            ft.commit();
582        }
583    }
584
585    private void setMainPane(
586            FragmentTransaction ft, int viewId, int viewType, long timeMillis, boolean force) {
587        if (mOnSaveInstanceStateCalled) {
588            return;
589        }
590        if (!force && mCurrentView == viewType) {
591            return;
592        }
593
594        // Remove this when transition to and from month view looks fine.
595        boolean doTransition = viewType != ViewType.MONTH && mCurrentView != ViewType.MONTH;
596
597        if (viewType != mCurrentView) {
598            // The rules for this previous view are different than the
599            // controller's and are used for intercepting the back button.
600            if (mCurrentView != ViewType.EDIT && mCurrentView > 0) {
601                mPreviousView = mCurrentView;
602            }
603            mCurrentView = viewType;
604        }
605        // Create new fragment
606        Fragment frag;
607        switch (viewType) {
608            case ViewType.AGENDA:
609                if (mActionBar != null && (mActionBar.getSelectedTab() != mAgendaTab)) {
610                    mActionBar.selectTab(mAgendaTab);
611                }
612                frag = new AgendaFragment(timeMillis);
613                break;
614            case ViewType.DAY:
615                if (mActionBar != null && (mActionBar.getSelectedTab() != mDayTab)) {
616                    mActionBar.selectTab(mDayTab);
617                }
618                frag = new DayFragment(timeMillis, 1);
619                break;
620            case ViewType.WEEK:
621                if (mActionBar != null && (mActionBar.getSelectedTab() != mWeekTab)) {
622                    mActionBar.selectTab(mWeekTab);
623                }
624                frag = new DayFragment(timeMillis, 7);
625                break;
626            case ViewType.MONTH:
627                if (mActionBar != null && (mActionBar.getSelectedTab() != mMonthTab)) {
628                    mActionBar.selectTab(mMonthTab);
629                }
630                frag = new MonthByWeekFragment(timeMillis, false);
631                break;
632            default:
633                throw new IllegalArgumentException(
634                        "Must be Agenda, Day, Week, or Month ViewType, not " + viewType);
635        }
636
637        boolean doCommit = false;
638        if (ft == null) {
639            doCommit = true;
640            ft = getFragmentManager().beginTransaction();
641        }
642
643        if (doTransition) {
644            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
645        }
646
647        ft.replace(viewId, frag);
648
649        if (DEBUG) {
650            Log.d(TAG, "Adding handler with viewId " + viewId + " and type " + viewType);
651        }
652        // If the key is already registered this will replace it
653        mController.registerEventHandler(viewId, (EventHandler) frag);
654
655        if (doCommit) {
656            Log.d(TAG, "setMainPane AllInOne=" + this + " finishing:" + this.isFinishing());
657            ft.commit();
658        }
659    }
660
661    private void setTitleInActionBar(EventInfo event) {
662        if (event.eventType != EventType.UPDATE_TITLE || mActionBar == null) {
663            return;
664        }
665
666        final long start = event.startTime.toMillis(false /* use isDst */);
667        final long end;
668        if (event.endTime != null) {
669            end = event.endTime.toMillis(false /* use isDst */);
670        } else {
671            end = start;
672        }
673
674        final String msg = Utils.formatDateRange(this, start, end, (int) event.extraLong);
675        CharSequence oldDate = mDateRange.getText();
676        mDateRange.setText(msg);
677        if (!TextUtils.equals(oldDate, msg)) {
678            mDateRange.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
679        }
680    }
681
682    private void updateHomeClock() {
683        mTimeZone = Utils.getTimeZone(this, mHomeTimeUpdater);
684        if (mIsMultipane && (mCurrentView == ViewType.DAY || mCurrentView == ViewType.WEEK)
685                && !TextUtils.equals(mTimeZone, Time.getCurrentTimezone())) {
686            Time time = new Time(mTimeZone);
687            time.setToNow();
688            long millis = time.toMillis(true);
689            boolean isDST = time.isDst != 0;
690            int flags = DateUtils.FORMAT_SHOW_TIME;
691            if (DateFormat.is24HourFormat(this)) {
692                flags |= DateUtils.FORMAT_24HOUR;
693            }
694            // Formats the time as
695            String timeString = (new StringBuilder(
696                    Utils.formatDateRange(this, millis, millis, flags))).append(" ").append(
697                    TimeZone.getTimeZone(mTimeZone).getDisplayName(
698                            isDST, TimeZone.SHORT, Locale.getDefault())).toString();
699            mHomeTime.setText(timeString);
700            mHomeTime.setVisibility(View.VISIBLE);
701            // Update when the minute changes
702            mHomeTime.postDelayed(
703                    mHomeTimeUpdater,
704                    DateUtils.MINUTE_IN_MILLIS - (millis % DateUtils.MINUTE_IN_MILLIS));
705        } else {
706            mHomeTime.setVisibility(View.GONE);
707        }
708    }
709
710    @Override
711    public long getSupportedEventTypes() {
712        return EventType.GO_TO | EventType.VIEW_EVENT | EventType.UPDATE_TITLE;
713    }
714
715    @Override
716    public void handleEvent(EventInfo event) {
717        Log.d(TAG, "handleEvent AllInOne=" + this);
718        if (event.eventType == EventType.GO_TO) {
719            setMainPane(
720                    null, R.id.main_pane, event.viewType, event.startTime.toMillis(false), false);
721            if (mSearchView != null) {
722                mSearchView.clearFocus();
723            }
724            if (!mIsMultipane) {
725
726                // show agenda view below main pane
727
728                if (event.viewType == ViewType.MONTH) {
729                    setAgendaPane(null, R.id.secondary_pane, event.startTime.toMillis(false));
730                    mSecondaryPane.setVisibility(View.VISIBLE);
731                } else {
732                    mSecondaryPane.setVisibility(View.GONE);
733                }
734                return;
735            }
736            if (event.viewType == ViewType.MONTH) {
737                // hide minimonth and calendar frag
738                mShowSideViews = false;
739                if (mControlsMenu != null) {
740                    mControlsMenu.setVisible(false);
741                    mControlsMenu.setEnabled(false);
742
743                    if (!mHideControls) {
744                        final ObjectAnimator slideAnimation = ObjectAnimator.ofInt(this,
745                                "controlsOffset", 0, CONTROLS_ANIMATE_WIDTH);
746                        slideAnimation.addListener(mSlideAnimationDoneListener);
747                        slideAnimation.setDuration(220);
748                        ObjectAnimator.setFrameDelay(0);
749                        slideAnimation.start();
750                    }
751                } else {
752                    mMiniMonth.setVisibility(View.GONE);
753                    mCalendarsList.setVisibility(View.GONE);
754                    mMiniMonthContainer.setVisibility(View.GONE);
755                }
756            } else {
757                // show minimonth and calendar frag
758                mShowSideViews = true;
759                mMiniMonth.setVisibility(View.VISIBLE);
760                mCalendarsList.setVisibility(View.VISIBLE);
761                mMiniMonthContainer.setVisibility(View.VISIBLE);
762                if (mControlsMenu != null) {
763                    mControlsMenu.setVisible(true);
764                    mControlsMenu.setEnabled(true);
765                    if (!mHideControls && mController.getPreviousViewType() == ViewType.MONTH) {
766                        final ObjectAnimator slideAnimation = ObjectAnimator.ofInt(this,
767                                "controlsOffset", CONTROLS_ANIMATE_WIDTH, 0);
768                        slideAnimation.setDuration(220);
769                        ObjectAnimator.setFrameDelay(0);
770                        slideAnimation.start();
771                    }
772                }
773            }
774        } else if (event.eventType == EventType.VIEW_EVENT) {
775            EventInfoFragment fragment = new EventInfoFragment(this,
776                    event.id, event.startTime.toMillis(false), event.endTime.toMillis(false),
777                    (int) event.extraLong);
778            if (event.selectedTime != null) {
779                mController.sendEvent(this, EventType.GO_TO, event.selectedTime, event.selectedTime,
780                        -1, ViewType.DETAIL);
781            }
782            fragment.setDialogParams(event.x, event.y, !mIsMultipane);
783            FragmentManager fm = getFragmentManager();
784            FragmentTransaction ft = fm.beginTransaction();
785            // if we have an old popup close it
786            Fragment fOld = fm.findFragmentByTag(EVENT_INFO_FRAGMENT_TAG);
787            if (fOld != null && fOld.isAdded()) {
788                ft.remove(fOld);
789            }
790            ft.add(fragment, EVENT_INFO_FRAGMENT_TAG);
791            ft.commit();
792        } else if (event.eventType == EventType.UPDATE_TITLE) {
793            setTitleInActionBar(event);
794        }
795        updateHomeClock();
796    }
797
798    @Override
799    public void eventsChanged() {
800        mController.sendEvent(this, EventType.EVENTS_CHANGED, null, null, -1, ViewType.CURRENT);
801    }
802
803    @Override
804    public boolean onQueryTextChange(String newText) {
805        return false;
806    }
807
808    @Override
809    public boolean onQueryTextSubmit(String query) {
810        if (TextUtils.equals(query, "TARDIS")) {
811            Utils.tardis();
812        }
813        mSearchView.clearFocus();
814        mController.sendEvent(this, EventType.SEARCH, null, null, -1, ViewType.CURRENT, -1, query,
815                getComponentName());
816        return false;
817    }
818
819    @Override
820    public void onTabSelected(Tab tab, FragmentTransaction ft) {
821        Log.w(TAG, "TabSelected AllInOne=" + this + " finishing:" + this.isFinishing());
822        if (tab == mDayTab && mCurrentView != ViewType.DAY) {
823            mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.DAY);
824        } else if (tab == mWeekTab && mCurrentView != ViewType.WEEK) {
825            mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.WEEK);
826        } else if (tab == mMonthTab && mCurrentView != ViewType.MONTH) {
827            mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.MONTH);
828        } else if (tab == mAgendaTab && mCurrentView != ViewType.AGENDA) {
829            mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.AGENDA);
830        } else {
831            Log.w(TAG, "TabSelected event from unknown tab: "
832                    + (tab == null ? "null" : tab.getText()));
833            Log.w(TAG, "CurrentView:" + mCurrentView + " Tab:" + tab.toString() + " Day:" + mDayTab
834                    + " Week:" + mWeekTab + " Month:" + mMonthTab + " Agenda:" + mAgendaTab);
835        }
836    }
837
838    @Override
839    public void onTabReselected(Tab tab, FragmentTransaction ft) {
840    }
841
842    @Override
843    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
844    }
845}
846