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