NavigationBarFragment.java revision 08a2028228c73d83f37c23eb63d03c2e775d1594
1/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5 * except in compliance with the License. You may obtain a copy of the License at
6 *
7 *      http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the
10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
11 * KIND, either express or implied. See the License for the specific language governing
12 * permissions and limitations under the License.
13 */
14
15package com.android.systemui.statusbar.phone;
16
17import static android.app.StatusBarManager.NAVIGATION_HINT_BACK_ALT;
18import static android.app.StatusBarManager.NAVIGATION_HINT_IME_SHOWN;
19import static android.app.StatusBarManager.WINDOW_STATE_SHOWING;
20import static android.app.StatusBarManager.windowStateToString;
21
22import static com.android.internal.view.RotationPolicy.NATURAL_ROTATION;
23
24import static com.android.systemui.shared.system.NavigationBarCompat.InteractionType;
25import static com.android.systemui.statusbar.phone.BarTransitions.MODE_SEMI_TRANSPARENT;
26import static com.android.systemui.statusbar.phone.StatusBar.DEBUG_WINDOW_STATE;
27import static com.android.systemui.statusbar.phone.StatusBar.dumpBarTransitions;
28import static com.android.systemui.OverviewProxyService.OverviewProxyListener;
29
30import android.accessibilityservice.AccessibilityServiceInfo;
31import android.animation.Animator;
32import android.animation.AnimatorListenerAdapter;
33import android.animation.ObjectAnimator;
34import android.annotation.IdRes;
35import android.annotation.Nullable;
36import android.app.ActivityManager;
37import android.app.ActivityManagerNative;
38import android.app.Fragment;
39import android.app.IActivityManager;
40import android.app.StatusBarManager;
41import android.content.BroadcastReceiver;
42import android.content.ContentResolver;
43import android.content.Context;
44import android.content.Intent;
45import android.content.IntentFilter;
46import android.content.res.Configuration;
47import android.database.ContentObserver;
48import android.graphics.PixelFormat;
49import android.graphics.Rect;
50import android.graphics.drawable.AnimatedVectorDrawable;
51import android.inputmethodservice.InputMethodService;
52import android.os.Binder;
53import android.os.Bundle;
54import android.os.Handler;
55import android.os.IBinder;
56import android.os.Message;
57import android.os.RemoteException;
58import android.os.UserHandle;
59import android.provider.Settings;
60import android.support.annotation.VisibleForTesting;
61import android.telecom.TelecomManager;
62import android.text.TextUtils;
63import android.util.Log;
64import android.view.IRotationWatcher.Stub;
65import android.view.KeyEvent;
66import android.view.LayoutInflater;
67import android.view.MotionEvent;
68import android.view.Surface;
69import android.view.View;
70import android.view.ViewGroup;
71import android.view.WindowManager;
72import android.view.WindowManager.LayoutParams;
73import android.view.WindowManagerGlobal;
74import android.view.accessibility.AccessibilityEvent;
75import android.view.accessibility.AccessibilityManager;
76import android.view.accessibility.AccessibilityManager.AccessibilityServicesStateChangeListener;
77
78import com.android.internal.logging.MetricsLogger;
79import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
80import com.android.internal.util.LatencyTracker;
81import com.android.systemui.Dependency;
82import com.android.systemui.Interpolators;
83import com.android.systemui.OverviewProxyService;
84import com.android.systemui.R;
85import com.android.systemui.SysUiServiceProvider;
86import com.android.systemui.assist.AssistManager;
87import com.android.systemui.fragments.FragmentHostManager;
88import com.android.systemui.fragments.FragmentHostManager.FragmentListener;
89import com.android.systemui.recents.Recents;
90import com.android.systemui.recents.misc.SysUiTaskStackChangeListener;
91import com.android.systemui.shared.system.ActivityManagerWrapper;
92import com.android.systemui.stackdivider.Divider;
93import com.android.systemui.statusbar.CommandQueue;
94import com.android.systemui.statusbar.CommandQueue.Callbacks;
95import com.android.systemui.statusbar.policy.AccessibilityManagerWrapper;
96import com.android.systemui.statusbar.policy.KeyButtonDrawable;
97import com.android.systemui.statusbar.policy.KeyButtonView;
98import com.android.systemui.statusbar.policy.RotationLockController;
99import com.android.systemui.statusbar.stack.StackStateAnimator;
100
101import java.io.FileDescriptor;
102import java.io.PrintWriter;
103import java.util.List;
104import java.util.Locale;
105import java.util.Optional;
106
107/**
108 * Fragment containing the NavigationBarFragment. Contains logic for what happens
109 * on clicks and view states of the nav bar.
110 */
111public class NavigationBarFragment extends Fragment implements Callbacks {
112
113    public static final String TAG = "NavigationBar";
114    private static final boolean DEBUG = false;
115    private static final boolean DEBUG_ROTATION = true;
116    private static final String EXTRA_DISABLE_STATE = "disabled_state";
117    private static final String EXTRA_DISABLE2_STATE = "disabled2_state";
118
119    private final static int BUTTON_FADE_IN_OUT_DURATION_MS = 100;
120    private final static int NAVBAR_HIDDEN_PENDING_ICON_TIMEOUT_MS = 20000;
121
122    private static final int NUM_ACCEPTED_ROTATION_SUGGESTIONS_FOR_INTRODUCTION = 3;
123
124    /** Allow some time inbetween the long press for back and recents. */
125    private static final int LOCK_TO_APP_GESTURE_TOLERENCE = 200;
126
127    protected NavigationBarView mNavigationBarView = null;
128    protected AssistManager mAssistManager;
129
130    private int mNavigationBarWindowState = WINDOW_STATE_SHOWING;
131
132    private int mNavigationIconHints = 0;
133    private int mNavigationBarMode;
134    private boolean mAccessibilityFeedbackEnabled;
135    private AccessibilityManager mAccessibilityManager;
136    private MagnificationContentObserver mMagnificationObserver;
137    private ContentResolver mContentResolver;
138    private final MetricsLogger mMetricsLogger = Dependency.get(MetricsLogger.class);
139
140    private int mDisabledFlags1;
141    private int mDisabledFlags2;
142    private StatusBar mStatusBar;
143    private Recents mRecents;
144    private Divider mDivider;
145    private WindowManager mWindowManager;
146    private CommandQueue mCommandQueue;
147    private long mLastLockToAppLongPress;
148
149    private Locale mLocale;
150    private int mLayoutDirection;
151
152    private int mSystemUiVisibility;
153    private LightBarController mLightBarController;
154
155    private OverviewProxyService mOverviewProxyService;
156
157    public boolean mHomeBlockedThisTouch;
158
159    private int mLastRotationSuggestion;
160    private boolean mPendingRotationSuggestion;
161    private boolean mHoveringRotationSuggestion;
162    private RotationLockController mRotationLockController;
163    private TaskStackListenerImpl mTaskStackListener;
164
165    private final Runnable mRemoveRotationProposal = () -> setRotateSuggestionButtonState(false);
166    private final Runnable mCancelPendingRotationProposal =
167            () -> mPendingRotationSuggestion = false;
168    private Animator mRotateHideAnimator;
169    private ViewRippler mViewRippler = new ViewRippler();
170
171    private final OverviewProxyListener mOverviewProxyListener = new OverviewProxyListener() {
172        @Override
173        public void onConnectionChanged(boolean isConnected) {
174            mNavigationBarView.updateStates();
175            updateScreenPinningGestures();
176        }
177
178        @Override
179        public void onQuickStepStarted() {
180            // Use navbar dragging as a signal to hide the rotate button
181            setRotateSuggestionButtonState(false);
182        }
183
184        @Override
185        public void onInteractionFlagsChanged(@InteractionType int flags) {
186            mNavigationBarView.updateStates();
187            updateScreenPinningGestures();
188        }
189    };
190
191    // ----- Fragment Lifecycle Callbacks -----
192
193    @Override
194    public void onCreate(@Nullable Bundle savedInstanceState) {
195        super.onCreate(savedInstanceState);
196        mCommandQueue = SysUiServiceProvider.getComponent(getContext(), CommandQueue.class);
197        mCommandQueue.addCallbacks(this);
198        mStatusBar = SysUiServiceProvider.getComponent(getContext(), StatusBar.class);
199        mRecents = SysUiServiceProvider.getComponent(getContext(), Recents.class);
200        mDivider = SysUiServiceProvider.getComponent(getContext(), Divider.class);
201        mWindowManager = getContext().getSystemService(WindowManager.class);
202        mAccessibilityManager = getContext().getSystemService(AccessibilityManager.class);
203        Dependency.get(AccessibilityManagerWrapper.class).addCallback(
204                mAccessibilityListener);
205        mContentResolver = getContext().getContentResolver();
206        mMagnificationObserver = new MagnificationContentObserver(
207                getContext().getMainThreadHandler());
208        mContentResolver.registerContentObserver(Settings.Secure.getUriFor(
209                Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED), false,
210                mMagnificationObserver, UserHandle.USER_ALL);
211
212        if (savedInstanceState != null) {
213            mDisabledFlags1 = savedInstanceState.getInt(EXTRA_DISABLE_STATE, 0);
214            mDisabledFlags2 = savedInstanceState.getInt(EXTRA_DISABLE2_STATE, 0);
215        }
216        mAssistManager = Dependency.get(AssistManager.class);
217        mOverviewProxyService = Dependency.get(OverviewProxyService.class);
218
219        try {
220            WindowManagerGlobal.getWindowManagerService()
221                    .watchRotation(mRotationWatcher, getContext().getDisplay().getDisplayId());
222        } catch (RemoteException e) {
223            throw e.rethrowFromSystemServer();
224        }
225
226        mRotationLockController = Dependency.get(RotationLockController.class);
227
228        // Reset user rotation pref to match that of the WindowManager if starting in locked mode
229        // This will automatically happen when switching from auto-rotate to locked mode
230        if (mRotationLockController.isRotationLocked()) {
231            final int winRotation = mWindowManager.getDefaultDisplay().getRotation();
232            mRotationLockController.setRotationLockedAtAngle(true, winRotation);
233        }
234
235        // Register the task stack listener
236        mTaskStackListener = new TaskStackListenerImpl();
237        ActivityManagerWrapper.getInstance().registerTaskStackListener(mTaskStackListener);
238    }
239
240    @Override
241    public void onDestroy() {
242        super.onDestroy();
243        mCommandQueue.removeCallbacks(this);
244        Dependency.get(AccessibilityManagerWrapper.class).removeCallback(
245                mAccessibilityListener);
246        mContentResolver.unregisterContentObserver(mMagnificationObserver);
247        try {
248            WindowManagerGlobal.getWindowManagerService()
249                    .removeRotationWatcher(mRotationWatcher);
250        } catch (RemoteException e) {
251            throw e.rethrowFromSystemServer();
252        }
253
254        // Unregister the task stack listener
255        ActivityManagerWrapper.getInstance().unregisterTaskStackListener(mTaskStackListener);
256    }
257
258    @Override
259    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
260            Bundle savedInstanceState) {
261        return inflater.inflate(R.layout.navigation_bar, container, false);
262    }
263
264    @Override
265    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
266        super.onViewCreated(view, savedInstanceState);
267        mNavigationBarView = (NavigationBarView) view;
268
269        mNavigationBarView.setDisabledFlags(mDisabledFlags1);
270        mNavigationBarView.setComponents(mRecents, mDivider, mStatusBar.getPanel());
271        mNavigationBarView.setOnVerticalChangedListener(this::onVerticalChanged);
272        mNavigationBarView.setOnTouchListener(this::onNavigationTouch);
273        if (savedInstanceState != null) {
274            mNavigationBarView.getLightTransitionsController().restoreState(savedInstanceState);
275        }
276
277        prepareNavigationBarView();
278        checkNavBarModes();
279
280        setDisabled2Flags(mDisabledFlags2);
281
282        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
283        filter.addAction(Intent.ACTION_SCREEN_ON);
284        getContext().registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, filter, null, null);
285        notifyNavigationBarScreenOn();
286        mOverviewProxyService.addCallback(mOverviewProxyListener);
287    }
288
289    @Override
290    public void onDestroyView() {
291        super.onDestroyView();
292        mNavigationBarView.getLightTransitionsController().destroy(getContext());
293        mOverviewProxyService.removeCallback(mOverviewProxyListener);
294        getContext().unregisterReceiver(mBroadcastReceiver);
295    }
296
297    @Override
298    public void onSaveInstanceState(Bundle outState) {
299        super.onSaveInstanceState(outState);
300        outState.putInt(EXTRA_DISABLE_STATE, mDisabledFlags1);
301        outState.putInt(EXTRA_DISABLE2_STATE, mDisabledFlags2);
302        if (mNavigationBarView != null) {
303            mNavigationBarView.getLightTransitionsController().saveState(outState);
304        }
305    }
306
307    @Override
308    public void onConfigurationChanged(Configuration newConfig) {
309        super.onConfigurationChanged(newConfig);
310        final Locale locale = getContext().getResources().getConfiguration().locale;
311        final int ld = TextUtils.getLayoutDirectionFromLocale(locale);
312        if (!locale.equals(mLocale) || ld != mLayoutDirection) {
313            if (DEBUG) {
314                Log.v(TAG, String.format(
315                        "config changed locale/LD: %s (%d) -> %s (%d)", mLocale, mLayoutDirection,
316                        locale, ld));
317            }
318            mLocale = locale;
319            mLayoutDirection = ld;
320            refreshLayout(ld);
321        }
322        repositionNavigationBar();
323    }
324
325    @Override
326    public void dump(String prefix, FileDescriptor fd, PrintWriter pw, String[] args) {
327        if (mNavigationBarView != null) {
328            pw.print("  mNavigationBarWindowState=");
329            pw.println(windowStateToString(mNavigationBarWindowState));
330            pw.print("  mNavigationBarMode=");
331            pw.println(BarTransitions.modeToString(mNavigationBarMode));
332            dumpBarTransitions(pw, "mNavigationBarView", mNavigationBarView.getBarTransitions());
333        }
334
335        pw.print("  mNavigationBarView=");
336        if (mNavigationBarView == null) {
337            pw.println("null");
338        } else {
339            mNavigationBarView.dump(fd, pw, args);
340        }
341    }
342
343    // ----- CommandQueue Callbacks -----
344
345    @Override
346    public void setImeWindowStatus(IBinder token, int vis, int backDisposition,
347            boolean showImeSwitcher) {
348        boolean imeShown = (vis & InputMethodService.IME_VISIBLE) != 0;
349        int hints = mNavigationIconHints;
350        switch (backDisposition) {
351            case InputMethodService.BACK_DISPOSITION_DEFAULT:
352            case InputMethodService.BACK_DISPOSITION_WILL_NOT_DISMISS:
353            case InputMethodService.BACK_DISPOSITION_WILL_DISMISS:
354                if (imeShown) {
355                    hints |= NAVIGATION_HINT_BACK_ALT;
356                } else {
357                    hints &= ~NAVIGATION_HINT_BACK_ALT;
358                }
359                break;
360            case InputMethodService.BACK_DISPOSITION_ADJUST_NOTHING:
361                hints &= ~NAVIGATION_HINT_BACK_ALT;
362                break;
363        }
364        if (showImeSwitcher) {
365            hints |= NAVIGATION_HINT_IME_SHOWN;
366        } else {
367            hints &= ~NAVIGATION_HINT_IME_SHOWN;
368        }
369        if (hints == mNavigationIconHints) return;
370
371        mNavigationIconHints = hints;
372
373        if (mNavigationBarView != null) {
374            mNavigationBarView.setNavigationIconHints(hints);
375        }
376        mStatusBar.checkBarModes();
377    }
378
379    @Override
380    public void topAppWindowChanged(boolean showMenu) {
381        if (mNavigationBarView != null) {
382            mNavigationBarView.setMenuVisibility(showMenu);
383        }
384    }
385
386    @Override
387    public void setWindowState(int window, int state) {
388        if (mNavigationBarView != null
389                && window == StatusBarManager.WINDOW_NAVIGATION_BAR
390                && mNavigationBarWindowState != state) {
391            mNavigationBarWindowState = state;
392            if (DEBUG_WINDOW_STATE) Log.d(TAG, "Navigation bar " + windowStateToString(state));
393
394            // If the navbar is visible, show the rotate button if there's a pending suggestion
395            if (state == WINDOW_STATE_SHOWING && mPendingRotationSuggestion) {
396                showAndLogRotationSuggestion();
397            }
398        }
399    }
400
401    @Override
402    public void onRotationProposal(final int rotation, boolean isValid) {
403        final int winRotation = mWindowManager.getDefaultDisplay().getRotation();
404        final boolean rotateSuggestionsDisabled = hasDisable2RotateSuggestionFlag(mDisabledFlags2);
405        if (DEBUG_ROTATION) {
406            Log.v(TAG, "onRotationProposal proposedRotation=" + Surface.rotationToString(rotation)
407                    + ", winRotation=" + Surface.rotationToString(winRotation)
408                    + ", isValid=" + isValid + ", mNavBarWindowState="
409                    + StatusBarManager.windowStateToString(mNavigationBarWindowState)
410                    + ", rotateSuggestionsDisabled=" + rotateSuggestionsDisabled
411                    + ", isRotateButtonVisible=" + (mNavigationBarView == null ? "null" :
412                        mNavigationBarView.isRotateButtonVisible()));
413        }
414
415        // Respect the disabled flag, no need for action as flag change callback will handle hiding
416        if (rotateSuggestionsDisabled) return;
417
418        // This method will be called on rotation suggestion changes even if the proposed rotation
419        // is not valid for the top app. Use invalid rotation choices as a signal to remove the
420        // rotate button if shown.
421        if (!isValid) {
422            setRotateSuggestionButtonState(false);
423            return;
424        }
425
426        // If window rotation matches suggested rotation, remove any current suggestions
427        if (rotation == winRotation) {
428            getView().removeCallbacks(mRemoveRotationProposal);
429            setRotateSuggestionButtonState(false);
430            return;
431        }
432
433        // Prepare to show the navbar icon by updating the icon style to change anim params
434        mLastRotationSuggestion = rotation; // Remember rotation for click
435        if (mNavigationBarView != null) {
436            final boolean rotationCCW = isRotationAnimationCCW(winRotation, rotation);
437            int style;
438            if (winRotation == Surface.ROTATION_0 || winRotation == Surface.ROTATION_180) {
439                style = rotationCCW ? R.style.RotateButtonCCWStart90 :
440                        R.style.RotateButtonCWStart90;
441            } else { // 90 or 270
442                style = rotationCCW ? R.style.RotateButtonCCWStart0 :
443                        R.style.RotateButtonCWStart0;
444            }
445            mNavigationBarView.updateRotateSuggestionButtonStyle(style, true);
446        }
447
448        if (mNavigationBarWindowState != WINDOW_STATE_SHOWING) {
449            // If the navbar isn't shown, flag the rotate icon to be shown should the navbar become
450            // visible given some time limit.
451            mPendingRotationSuggestion = true;
452            getView().removeCallbacks(mCancelPendingRotationProposal);
453            getView().postDelayed(mCancelPendingRotationProposal,
454                    NAVBAR_HIDDEN_PENDING_ICON_TIMEOUT_MS);
455
456        } else { // The navbar is visible so show the icon right away
457            showAndLogRotationSuggestion();
458        }
459    }
460
461    private void onRotationSuggestionsDisabled() {
462        // Immediately hide the rotate button and clear any planned removal
463        setRotateSuggestionButtonState(false, true);
464
465        // This method can be called before view setup is done, ensure getView isn't null
466        final View v = getView();
467        if (v != null) v.removeCallbacks(mRemoveRotationProposal);
468    }
469
470    private void showAndLogRotationSuggestion() {
471        setRotateSuggestionButtonState(true);
472        rescheduleRotationTimeout(false);
473        mMetricsLogger.visible(MetricsEvent.ROTATION_SUGGESTION_SHOWN);
474    }
475
476    private boolean isRotationAnimationCCW(int from, int to) {
477        // All 180deg WM rotation animations are CCW, match that
478        if (from == Surface.ROTATION_0 && to == Surface.ROTATION_90) return false;
479        if (from == Surface.ROTATION_0 && to == Surface.ROTATION_180) return true; //180d so CCW
480        if (from == Surface.ROTATION_0 && to == Surface.ROTATION_270) return true;
481        if (from == Surface.ROTATION_90 && to == Surface.ROTATION_0) return true;
482        if (from == Surface.ROTATION_90 && to == Surface.ROTATION_180) return false;
483        if (from == Surface.ROTATION_90 && to == Surface.ROTATION_270) return true; //180d so CCW
484        if (from == Surface.ROTATION_180 && to == Surface.ROTATION_0) return true; //180d so CCW
485        if (from == Surface.ROTATION_180 && to == Surface.ROTATION_90) return true;
486        if (from == Surface.ROTATION_180 && to == Surface.ROTATION_270) return false;
487        if (from == Surface.ROTATION_270 && to == Surface.ROTATION_0) return false;
488        if (from == Surface.ROTATION_270 && to == Surface.ROTATION_90) return true; //180d so CCW
489        if (from == Surface.ROTATION_270 && to == Surface.ROTATION_180) return true;
490        return false; // Default
491    }
492
493    public void setRotateSuggestionButtonState(final boolean visible) {
494        setRotateSuggestionButtonState(visible, false);
495    }
496
497    public void setRotateSuggestionButtonState(final boolean visible, final boolean force) {
498        if (mNavigationBarView == null) return;
499
500        // At any point the the button can become invisible because an a11y service became active.
501        // Similarly, a call to make the button visible may be rejected because an a11y service is
502        // active. Must account for this.
503
504        ButtonDispatcher rotBtn = mNavigationBarView.getRotateSuggestionButton();
505        final boolean currentlyVisible = mNavigationBarView.isRotateButtonVisible();
506
507        // Rerun a show animation to indicate change but don't rerun a hide animation
508        if (!visible && !currentlyVisible) return;
509
510        View view = rotBtn.getCurrentView();
511        if (view == null) return;
512
513        KeyButtonDrawable kbd = rotBtn.getImageDrawable();
514        if (kbd == null) return;
515
516        // The KBD and AVD is recreated every new valid suggestion because of style changes.
517        AnimatedVectorDrawable animIcon = null;
518        if (kbd.getDrawable(0) instanceof AnimatedVectorDrawable) {
519            animIcon = (AnimatedVectorDrawable) kbd.getDrawable(0);
520        }
521
522        // Clear any pending suggestion flag as it has either been nullified or is being shown
523        mPendingRotationSuggestion = false;
524        getView().removeCallbacks(mCancelPendingRotationProposal);
525
526        // Handle the visibility change and animation
527        if (visible) { // Appear and change (cannot force)
528            // Stop and clear any currently running hide animations
529            if (mRotateHideAnimator != null && mRotateHideAnimator.isRunning()) {
530                mRotateHideAnimator.cancel();
531            }
532            mRotateHideAnimator = null;
533
534            // Reset the alpha if any has changed due to hide animation
535            view.setAlpha(1f);
536
537            // Run the rotate icon's animation if it has one
538            if (animIcon != null) {
539                animIcon.reset();
540                animIcon.start();
541            }
542
543            if (!isRotateSuggestionIntroduced()) mViewRippler.start(view);
544
545            // Set visibility, may fail if a11y service is active.
546            // If invisible, call will stop animation.
547            mNavigationBarView.setRotateButtonVisibility(true);
548
549        } else { // Hide
550
551            mViewRippler.stop(); // Prevent any pending ripples, force hide or not
552
553            if (force) {
554                // If a hide animator is running stop it and make invisible
555                if (mRotateHideAnimator != null && mRotateHideAnimator.isRunning()) {
556                    mRotateHideAnimator.pause();
557                }
558                mNavigationBarView.setRotateButtonVisibility(false);
559                return;
560            }
561
562            // Don't start any new hide animations if one is running
563            if (mRotateHideAnimator != null && mRotateHideAnimator.isRunning()) return;
564
565            ObjectAnimator fadeOut = ObjectAnimator.ofFloat(view, "alpha",
566                    0f);
567            fadeOut.setDuration(BUTTON_FADE_IN_OUT_DURATION_MS);
568            fadeOut.setInterpolator(Interpolators.LINEAR);
569            fadeOut.addListener(new AnimatorListenerAdapter() {
570                @Override
571                public void onAnimationEnd(Animator animation) {
572                    mNavigationBarView.setRotateButtonVisibility(false);
573                }
574            });
575
576            mRotateHideAnimator = fadeOut;
577            fadeOut.start();
578        }
579    }
580
581    private void rescheduleRotationTimeout(final boolean reasonHover) {
582        // May be called due to a new rotation proposal or a change in hover state
583        if (reasonHover) {
584            // Don't reschedule if a hide animator is running
585            if (mRotateHideAnimator != null && mRotateHideAnimator.isRunning()) return;
586            // Don't reschedule if not visible
587            if (!mNavigationBarView.isRotateButtonVisible()) return;
588        }
589
590        getView().removeCallbacks(mRemoveRotationProposal); // Stop any pending removal
591        getView().postDelayed(mRemoveRotationProposal,
592                computeRotationProposalTimeout()); // Schedule timeout
593    }
594
595    private int computeRotationProposalTimeout() {
596        if (mAccessibilityFeedbackEnabled) return 20000;
597        if (mHoveringRotationSuggestion) return 16000;
598        return 6000;
599    }
600
601    private boolean isRotateSuggestionIntroduced() {
602        ContentResolver cr = getContext().getContentResolver();
603        return Settings.Secure.getInt(cr, Settings.Secure.NUM_ROTATION_SUGGESTIONS_ACCEPTED, 0)
604                >= NUM_ACCEPTED_ROTATION_SUGGESTIONS_FOR_INTRODUCTION;
605    }
606
607    private void incrementNumAcceptedRotationSuggestionsIfNeeded() {
608        // Get the number of accepted suggestions
609        ContentResolver cr = getContext().getContentResolver();
610        final int numSuggestions = Settings.Secure.getInt(cr,
611                Settings.Secure.NUM_ROTATION_SUGGESTIONS_ACCEPTED, 0);
612
613        // Increment the number of accepted suggestions only if it would change intro mode
614        if (numSuggestions < NUM_ACCEPTED_ROTATION_SUGGESTIONS_FOR_INTRODUCTION) {
615            Settings.Secure.putInt(cr, Settings.Secure.NUM_ROTATION_SUGGESTIONS_ACCEPTED,
616                    numSuggestions + 1);
617        }
618    }
619
620    // Injected from StatusBar at creation.
621    public void setCurrentSysuiVisibility(int systemUiVisibility) {
622        mSystemUiVisibility = systemUiVisibility;
623        mNavigationBarMode = mStatusBar.computeBarMode(0, mSystemUiVisibility,
624                View.NAVIGATION_BAR_TRANSIENT, View.NAVIGATION_BAR_TRANSLUCENT,
625                View.NAVIGATION_BAR_TRANSPARENT);
626        checkNavBarModes();
627        mStatusBar.touchAutoHide();
628        mLightBarController.onNavigationVisibilityChanged(mSystemUiVisibility, 0 /* mask */,
629                true /* nbModeChanged */, mNavigationBarMode);
630    }
631
632    @Override
633    public void setSystemUiVisibility(int vis, int fullscreenStackVis, int dockedStackVis,
634            int mask, Rect fullscreenStackBounds, Rect dockedStackBounds) {
635        final int oldVal = mSystemUiVisibility;
636        final int newVal = (oldVal & ~mask) | (vis & mask);
637        final int diff = newVal ^ oldVal;
638        boolean nbModeChanged = false;
639        if (diff != 0) {
640            mSystemUiVisibility = newVal;
641
642            // update navigation bar mode
643            final int nbMode = getView() == null
644                    ? -1 : mStatusBar.computeBarMode(oldVal, newVal,
645                    View.NAVIGATION_BAR_TRANSIENT, View.NAVIGATION_BAR_TRANSLUCENT,
646                    View.NAVIGATION_BAR_TRANSPARENT);
647            nbModeChanged = nbMode != -1;
648            if (nbModeChanged) {
649                if (mNavigationBarMode != nbMode) {
650                    mNavigationBarMode = nbMode;
651                    checkNavBarModes();
652                }
653                mStatusBar.touchAutoHide();
654            }
655        }
656
657        mLightBarController.onNavigationVisibilityChanged(vis, mask, nbModeChanged,
658                mNavigationBarMode);
659    }
660
661    @Override
662    public void disable(int state1, int state2, boolean animate) {
663        // Navigation bar flags are in both state1 and state2.
664        final int masked = state1 & (StatusBarManager.DISABLE_HOME
665                | StatusBarManager.DISABLE_RECENT
666                | StatusBarManager.DISABLE_BACK
667                | StatusBarManager.DISABLE_SEARCH);
668        if (masked != mDisabledFlags1) {
669            mDisabledFlags1 = masked;
670            if (mNavigationBarView != null) mNavigationBarView.setDisabledFlags(state1);
671            updateScreenPinningGestures();
672        }
673
674        final int masked2 = state2 & (StatusBarManager.DISABLE2_ROTATE_SUGGESTIONS);
675        if (masked2 != mDisabledFlags2) {
676            mDisabledFlags2 = masked2;
677            setDisabled2Flags(masked2);
678        }
679    }
680
681    private void setDisabled2Flags(int state2) {
682        // Method only called on change of disable2 flags
683        final boolean rotateSuggestionsDisabled = hasDisable2RotateSuggestionFlag(state2);
684        if (rotateSuggestionsDisabled) onRotationSuggestionsDisabled();
685    }
686
687    private boolean hasDisable2RotateSuggestionFlag(int disable2Flags) {
688        return (disable2Flags & StatusBarManager.DISABLE2_ROTATE_SUGGESTIONS) != 0;
689    }
690
691    // ----- Internal stuffz -----
692
693    private void refreshLayout(int layoutDirection) {
694        if (mNavigationBarView != null) {
695            mNavigationBarView.setLayoutDirection(layoutDirection);
696        }
697    }
698
699    private boolean shouldDisableNavbarGestures() {
700        return !mStatusBar.isDeviceProvisioned()
701                || (mDisabledFlags1 & StatusBarManager.DISABLE_SEARCH) != 0;
702    }
703
704    private void repositionNavigationBar() {
705        if (mNavigationBarView == null || !mNavigationBarView.isAttachedToWindow()) return;
706
707        prepareNavigationBarView();
708
709        mWindowManager.updateViewLayout((View) mNavigationBarView.getParent(),
710                ((View) mNavigationBarView.getParent()).getLayoutParams());
711    }
712
713    private void updateScreenPinningGestures() {
714        if (mNavigationBarView == null) {
715            return;
716        }
717
718        // Change the cancel pin gesture to home and back if recents button is invisible
719        boolean recentsVisible = mNavigationBarView.isRecentsButtonVisible();
720        ButtonDispatcher backButton = mNavigationBarView.getBackButton();
721        if (recentsVisible) {
722            backButton.setOnLongClickListener(this::onLongPressBackRecents);
723        } else {
724            backButton.setOnLongClickListener(this::onLongPressBackHome);
725        }
726    }
727
728    private void notifyNavigationBarScreenOn() {
729        mNavigationBarView.updateNavButtonIcons();
730    }
731
732    private void prepareNavigationBarView() {
733        mNavigationBarView.reorient();
734
735        ButtonDispatcher recentsButton = mNavigationBarView.getRecentsButton();
736        recentsButton.setOnClickListener(this::onRecentsClick);
737        recentsButton.setOnTouchListener(this::onRecentsTouch);
738        recentsButton.setLongClickable(true);
739        recentsButton.setOnLongClickListener(this::onLongPressBackRecents);
740
741        ButtonDispatcher backButton = mNavigationBarView.getBackButton();
742        backButton.setLongClickable(true);
743
744        ButtonDispatcher homeButton = mNavigationBarView.getHomeButton();
745        homeButton.setOnTouchListener(this::onHomeTouch);
746        homeButton.setOnLongClickListener(this::onHomeLongClick);
747
748        ButtonDispatcher accessibilityButton = mNavigationBarView.getAccessibilityButton();
749        accessibilityButton.setOnClickListener(this::onAccessibilityClick);
750        accessibilityButton.setOnLongClickListener(this::onAccessibilityLongClick);
751        updateAccessibilityServicesState(mAccessibilityManager);
752
753        ButtonDispatcher rotateSuggestionButton = mNavigationBarView.getRotateSuggestionButton();
754        rotateSuggestionButton.setOnClickListener(this::onRotateSuggestionClick);
755        rotateSuggestionButton.setOnHoverListener(this::onRotateSuggestionHover);
756        updateScreenPinningGestures();
757    }
758
759    private boolean onHomeTouch(View v, MotionEvent event) {
760        if (mHomeBlockedThisTouch && event.getActionMasked() != MotionEvent.ACTION_DOWN) {
761            return true;
762        }
763        // If an incoming call is ringing, HOME is totally disabled.
764        // (The user is already on the InCallUI at this point,
765        // and his ONLY options are to answer or reject the call.)
766        switch (event.getAction()) {
767            case MotionEvent.ACTION_DOWN:
768                mHomeBlockedThisTouch = false;
769                TelecomManager telecomManager =
770                        getContext().getSystemService(TelecomManager.class);
771                if (telecomManager != null && telecomManager.isRinging()) {
772                    if (mStatusBar.isKeyguardShowing()) {
773                        Log.i(TAG, "Ignoring HOME; there's a ringing incoming call. " +
774                                "No heads up");
775                        mHomeBlockedThisTouch = true;
776                        return true;
777                    }
778                }
779                break;
780            case MotionEvent.ACTION_UP:
781            case MotionEvent.ACTION_CANCEL:
782                mStatusBar.awakenDreams();
783                break;
784        }
785        return false;
786    }
787
788    private void onVerticalChanged(boolean isVertical) {
789        mStatusBar.setQsScrimEnabled(!isVertical);
790    }
791
792    private boolean onNavigationTouch(View v, MotionEvent event) {
793        mStatusBar.checkUserAutohide(event);
794        return false;
795    }
796
797    @VisibleForTesting
798    boolean onHomeLongClick(View v) {
799        if (!mNavigationBarView.isRecentsButtonVisible()
800                && ActivityManagerWrapper.getInstance().isScreenPinningActive()) {
801            return onLongPressBackHome(v);
802        }
803        if (shouldDisableNavbarGestures()) {
804            return false;
805        }
806        mNavigationBarView.onNavigationButtonLongPress(v);
807        mMetricsLogger.action(MetricsEvent.ACTION_ASSIST_LONG_PRESS);
808        mAssistManager.startAssist(new Bundle() /* args */);
809        mStatusBar.awakenDreams();
810
811        if (mNavigationBarView != null) {
812            mNavigationBarView.abortCurrentGesture();
813        }
814        return true;
815    }
816
817    // additional optimization when we have software system buttons - start loading the recent
818    // tasks on touch down
819    private boolean onRecentsTouch(View v, MotionEvent event) {
820        int action = event.getAction() & MotionEvent.ACTION_MASK;
821        if (action == MotionEvent.ACTION_DOWN) {
822            mCommandQueue.preloadRecentApps();
823        } else if (action == MotionEvent.ACTION_CANCEL) {
824            mCommandQueue.cancelPreloadRecentApps();
825        } else if (action == MotionEvent.ACTION_UP) {
826            if (!v.isPressed()) {
827                mCommandQueue.cancelPreloadRecentApps();
828            }
829        }
830        return false;
831    }
832
833    private void onRecentsClick(View v) {
834        if (LatencyTracker.isEnabled(getContext())) {
835            LatencyTracker.getInstance(getContext()).onActionStart(
836                    LatencyTracker.ACTION_TOGGLE_RECENTS);
837        }
838        mStatusBar.awakenDreams();
839        mCommandQueue.toggleRecentApps();
840    }
841
842    private boolean onLongPressBackHome(View v) {
843        mNavigationBarView.onNavigationButtonLongPress(v);
844        return onLongPressNavigationButtons(v, R.id.back, R.id.home);
845    }
846
847    private boolean onLongPressBackRecents(View v) {
848        mNavigationBarView.onNavigationButtonLongPress(v);
849        return onLongPressNavigationButtons(v, R.id.back, R.id.recent_apps);
850    }
851
852    /**
853     * This handles long-press of both back and recents/home. Back is the common button with
854     * combination of recents if it is visible or home if recents is invisible.
855     * They are handled together to capture them both being long-pressed
856     * at the same time to exit screen pinning (lock task).
857     *
858     * When accessibility mode is on, only a long-press from recents/home
859     * is required to exit.
860     *
861     * In all other circumstances we try to pass through long-press events
862     * for Back, so that apps can still use it.  Which can be from two things.
863     * 1) Not currently in screen pinning (lock task).
864     * 2) Back is long-pressed without recents/home.
865     */
866    private boolean onLongPressNavigationButtons(View v, @IdRes int btnId1, @IdRes int btnId2) {
867        try {
868            boolean sendBackLongPress = false;
869            IActivityManager activityManager = ActivityManagerNative.getDefault();
870            boolean touchExplorationEnabled = mAccessibilityManager.isTouchExplorationEnabled();
871            boolean inLockTaskMode = activityManager.isInLockTaskMode();
872            if (inLockTaskMode && !touchExplorationEnabled) {
873                long time = System.currentTimeMillis();
874
875                // If we recently long-pressed the other button then they were
876                // long-pressed 'together'
877                if ((time - mLastLockToAppLongPress) < LOCK_TO_APP_GESTURE_TOLERENCE) {
878                    activityManager.stopSystemLockTaskMode();
879                    // When exiting refresh disabled flags.
880                    mNavigationBarView.updateNavButtonIcons();
881                    return true;
882                } else if (v.getId() == btnId1) {
883                    ButtonDispatcher button = btnId2 == R.id.recent_apps
884                            ? mNavigationBarView.getRecentsButton()
885                            : mNavigationBarView.getHomeButton();
886                    if (!button.getCurrentView().isPressed()) {
887                        // If we aren't pressing recents/home right now then they presses
888                        // won't be together, so send the standard long-press action.
889                        sendBackLongPress = true;
890                    }
891                }
892                mLastLockToAppLongPress = time;
893            } else {
894                // If this is back still need to handle sending the long-press event.
895                if (v.getId() == btnId1) {
896                    sendBackLongPress = true;
897                } else if (touchExplorationEnabled && inLockTaskMode) {
898                    // When in accessibility mode a long press that is recents/home (not back)
899                    // should stop lock task.
900                    activityManager.stopSystemLockTaskMode();
901                    // When exiting refresh disabled flags.
902                    mNavigationBarView.updateNavButtonIcons();
903                    return true;
904                } else if (v.getId() == btnId2) {
905                    return btnId2 == R.id.recent_apps
906                            ? onLongPressRecents()
907                            : onHomeLongClick(mNavigationBarView.getHomeButton().getCurrentView());
908                }
909            }
910            if (sendBackLongPress) {
911                KeyButtonView keyButtonView = (KeyButtonView) v;
912                keyButtonView.sendEvent(KeyEvent.ACTION_DOWN, KeyEvent.FLAG_LONG_PRESS);
913                keyButtonView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
914                return true;
915            }
916        } catch (RemoteException e) {
917            Log.d(TAG, "Unable to reach activity manager", e);
918        }
919        return false;
920    }
921
922    private boolean onLongPressRecents() {
923        if (mRecents == null || !ActivityManager.supportsMultiWindow(getContext())
924                || !mDivider.getView().getSnapAlgorithm().isSplitScreenFeasible()
925                || Recents.getConfiguration().isLowRamDevice
926                // If we are connected to the overview service, then disable the recents button
927                || mOverviewProxyService.getProxy() != null) {
928            return false;
929        }
930
931        return mStatusBar.toggleSplitScreenMode(MetricsEvent.ACTION_WINDOW_DOCK_LONGPRESS,
932                MetricsEvent.ACTION_WINDOW_UNDOCK_LONGPRESS);
933    }
934
935    private void onAccessibilityClick(View v) {
936        mAccessibilityManager.notifyAccessibilityButtonClicked();
937    }
938
939    private boolean onAccessibilityLongClick(View v) {
940        Intent intent = new Intent(AccessibilityManager.ACTION_CHOOSE_ACCESSIBILITY_BUTTON);
941        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
942        v.getContext().startActivityAsUser(intent, UserHandle.CURRENT);
943        return true;
944    }
945
946    private void updateAccessibilityServicesState(AccessibilityManager accessibilityManager) {
947        int requestingServices = 0;
948        try {
949            if (Settings.Secure.getIntForUser(mContentResolver,
950                    Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED,
951                    UserHandle.USER_CURRENT) == 1) {
952                requestingServices++;
953            }
954        } catch (Settings.SettingNotFoundException e) {
955        }
956
957        boolean feedbackEnabled = false;
958        // AccessibilityManagerService resolves services for the current user since the local
959        // AccessibilityManager is created from a Context with the INTERACT_ACROSS_USERS permission
960        final List<AccessibilityServiceInfo> services =
961                accessibilityManager.getEnabledAccessibilityServiceList(
962                        AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
963        for (int i = services.size() - 1; i >= 0; --i) {
964            AccessibilityServiceInfo info = services.get(i);
965            if ((info.flags & AccessibilityServiceInfo.FLAG_REQUEST_ACCESSIBILITY_BUTTON) != 0) {
966                requestingServices++;
967            }
968
969            if (info.feedbackType != 0 && info.feedbackType !=
970                    AccessibilityServiceInfo.FEEDBACK_GENERIC) {
971                feedbackEnabled = true;
972            }
973        }
974
975        mAccessibilityFeedbackEnabled = feedbackEnabled;
976
977        final boolean showAccessibilityButton = requestingServices >= 1;
978        final boolean targetSelection = requestingServices >= 2;
979        mNavigationBarView.setAccessibilityButtonState(showAccessibilityButton, targetSelection);
980    }
981
982    private void onRotateSuggestionClick(View v) {
983        mMetricsLogger.action(MetricsEvent.ACTION_ROTATION_SUGGESTION_ACCEPTED);
984        incrementNumAcceptedRotationSuggestionsIfNeeded();
985        mRotationLockController.setRotationLockedAtAngle(true, mLastRotationSuggestion);
986    }
987
988    private boolean onRotateSuggestionHover(View v, MotionEvent event) {
989        final int action = event.getActionMasked();
990        mHoveringRotationSuggestion = (action == MotionEvent.ACTION_HOVER_ENTER)
991                || (action == MotionEvent.ACTION_HOVER_MOVE);
992        rescheduleRotationTimeout(true);
993        return false; // Must return false so a11y hover events are dispatched correctly.
994    }
995
996    // ----- Methods that StatusBar talks to (should be minimized) -----
997
998    public void setLightBarController(LightBarController lightBarController) {
999        mLightBarController = lightBarController;
1000        mLightBarController.setNavigationBar(mNavigationBarView.getLightTransitionsController());
1001    }
1002
1003    public boolean isSemiTransparent() {
1004        return mNavigationBarMode == MODE_SEMI_TRANSPARENT;
1005    }
1006
1007    public void disableAnimationsDuringHide(long delay) {
1008        mNavigationBarView.setLayoutTransitionsEnabled(false);
1009        mNavigationBarView.postDelayed(() -> mNavigationBarView.setLayoutTransitionsEnabled(true),
1010                delay + StackStateAnimator.ANIMATION_DURATION_GO_TO_FULL_SHADE);
1011    }
1012
1013    public BarTransitions getBarTransitions() {
1014        return mNavigationBarView.getBarTransitions();
1015    }
1016
1017    public void checkNavBarModes() {
1018        mStatusBar.checkBarMode(mNavigationBarMode,
1019                mNavigationBarWindowState, mNavigationBarView.getBarTransitions());
1020    }
1021
1022    public void finishBarAnimations() {
1023        mNavigationBarView.getBarTransitions().finishAnimations();
1024    }
1025
1026    private final AccessibilityServicesStateChangeListener mAccessibilityListener =
1027            this::updateAccessibilityServicesState;
1028
1029    private class MagnificationContentObserver extends ContentObserver {
1030
1031        public MagnificationContentObserver(Handler handler) {
1032            super(handler);
1033        }
1034
1035        @Override
1036        public void onChange(boolean selfChange) {
1037            NavigationBarFragment.this.updateAccessibilityServicesState(mAccessibilityManager);
1038        }
1039    }
1040
1041    private final Stub mRotationWatcher = new Stub() {
1042        @Override
1043        public void onRotationChanged(final int rotation) throws RemoteException {
1044            // We need this to be scheduled as early as possible to beat the redrawing of
1045            // window in response to the orientation change.
1046            Handler h = getView().getHandler();
1047            Message msg = Message.obtain(h, () -> {
1048
1049                // If the screen rotation changes while locked, potentially update lock to flow with
1050                // new screen rotation and hide any showing suggestions.
1051                if (mRotationLockController.isRotationLocked()) {
1052                    if (shouldOverrideUserLockPrefs(rotation)) {
1053                        mRotationLockController.setRotationLockedAtAngle(true, rotation);
1054                    }
1055                    setRotateSuggestionButtonState(false, true);
1056                }
1057
1058                if (mNavigationBarView != null
1059                        && mNavigationBarView.needsReorient(rotation)) {
1060                    repositionNavigationBar();
1061                }
1062            });
1063            msg.setAsynchronous(true);
1064            h.sendMessageAtFrontOfQueue(msg);
1065        }
1066
1067        private boolean shouldOverrideUserLockPrefs(final int rotation) {
1068            // Only override user prefs when returning to the natural rotation (normally portrait).
1069            // Don't let apps that force landscape or 180 alter user lock.
1070            return rotation == NATURAL_ROTATION;
1071        }
1072    };
1073
1074    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1075        @Override
1076        public void onReceive(Context context, Intent intent) {
1077            String action = intent.getAction();
1078            if (Intent.ACTION_SCREEN_OFF.equals(action)
1079                    || Intent.ACTION_SCREEN_ON.equals(action)) {
1080                notifyNavigationBarScreenOn();
1081            }
1082        }
1083    };
1084
1085    class TaskStackListenerImpl extends SysUiTaskStackChangeListener {
1086        // Invalidate any rotation suggestion on task change or activity orientation change
1087        // Note: all callbacks happen on main thread
1088
1089        @Override
1090        public void onTaskStackChanged() {
1091            setRotateSuggestionButtonState(false);
1092        }
1093
1094        @Override
1095        public void onTaskRemoved(int taskId) {
1096            setRotateSuggestionButtonState(false);
1097        }
1098
1099        @Override
1100        public void onTaskMovedToFront(int taskId) {
1101            setRotateSuggestionButtonState(false);
1102        }
1103
1104        @Override
1105        public void onActivityRequestedOrientationChanged(int taskId, int requestedOrientation) {
1106            // Only hide the icon if the top task changes its requestedOrientation
1107            // Launcher can alter its requestedOrientation while it's not on top, don't hide on this
1108            Optional.ofNullable(ActivityManagerWrapper.getInstance())
1109                    .map(ActivityManagerWrapper::getRunningTask)
1110                    .ifPresent(a -> {
1111                        if (a.id == taskId) setRotateSuggestionButtonState(false);
1112                    });
1113        }
1114    }
1115
1116    private class ViewRippler {
1117        private static final int RIPPLE_OFFSET_MS = 50;
1118        private static final int RIPPLE_INTERVAL_MS = 2000;
1119        private View mRoot;
1120
1121        public void start(View root) {
1122            stop(); // Stop any pending ripple animations
1123
1124            mRoot = root;
1125
1126            // Schedule pending ripples, offset the 1st to avoid problems with visibility change
1127            mRoot.postOnAnimationDelayed(mRipple, RIPPLE_OFFSET_MS);
1128            mRoot.postOnAnimationDelayed(mRipple, RIPPLE_INTERVAL_MS);
1129            mRoot.postOnAnimationDelayed(mRipple, 2*RIPPLE_INTERVAL_MS);
1130        }
1131
1132        public void stop() {
1133            if (mRoot != null) mRoot.removeCallbacks(mRipple);
1134        }
1135
1136        private final Runnable mRipple = new Runnable() {
1137            @Override
1138            public void run() { // Cause the ripple to fire via false presses
1139                mRoot.setPressed(true);
1140                mRoot.setPressed(false);
1141            }
1142        };
1143    }
1144
1145    public static View create(Context context, FragmentListener listener) {
1146        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
1147                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
1148                WindowManager.LayoutParams.TYPE_NAVIGATION_BAR,
1149                WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
1150                        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1151                        | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
1152                        | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
1153                        | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH
1154                        | WindowManager.LayoutParams.FLAG_SLIPPERY,
1155                PixelFormat.TRANSLUCENT);
1156        lp.token = new Binder();
1157        lp.setTitle("NavigationBar");
1158        lp.accessibilityTitle = context.getString(R.string.nav_bar);
1159        lp.windowAnimations = 0;
1160
1161        View navigationBarView = LayoutInflater.from(context).inflate(
1162                R.layout.navigation_bar_window, null);
1163
1164        if (DEBUG) Log.v(TAG, "addNavigationBar: about to add " + navigationBarView);
1165        if (navigationBarView == null) return null;
1166
1167        context.getSystemService(WindowManager.class).addView(navigationBarView, lp);
1168        FragmentHostManager fragmentHost = FragmentHostManager.get(navigationBarView);
1169        NavigationBarFragment fragment = new NavigationBarFragment();
1170        fragmentHost.getFragmentManager().beginTransaction()
1171                .replace(R.id.navigation_bar_frame, fragment, TAG)
1172                .commit();
1173        fragmentHost.addTagListener(TAG, listener);
1174        return navigationBarView;
1175    }
1176}
1177