PhoneStatusBar.java revision 7f3cf9586ef51d6a870d941e56a0f12471cbbad2
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.systemui.statusbar.phone;
18
19import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
21import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.app.ActivityManager;
24import android.app.ActivityManagerNative;
25import android.app.Dialog;
26import android.app.KeyguardManager;
27import android.app.Notification;
28import android.app.PendingIntent;
29import android.app.StatusBarManager;
30import android.content.BroadcastReceiver;
31import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.res.Configuration;
35import android.content.res.Resources;
36import android.graphics.Canvas;
37import android.graphics.ColorFilter;
38import android.graphics.PixelFormat;
39import android.graphics.PorterDuff;
40import android.graphics.Rect;
41import android.graphics.drawable.Drawable;
42import android.graphics.drawable.NinePatchDrawable;
43import android.inputmethodservice.InputMethodService;
44import android.os.IBinder;
45import android.os.Message;
46import android.os.RemoteException;
47import android.os.ServiceManager;
48import android.os.SystemClock;
49import android.os.UserHandle;
50import android.provider.Settings;
51import android.service.dreams.IDreamManager;
52import android.util.DisplayMetrics;
53import android.util.Log;
54import android.util.Slog;
55import android.view.Display;
56import android.view.Gravity;
57import android.view.IWindowManager;
58import android.view.KeyEvent;
59import android.view.MotionEvent;
60import android.view.VelocityTracker;
61import android.view.View;
62import android.view.ViewGroup;
63import android.view.WindowManagerGlobal;
64import android.view.ViewGroup.LayoutParams;
65import android.view.WindowManager;
66import android.view.animation.AccelerateInterpolator;
67import android.view.animation.Animation;
68import android.view.animation.AnimationUtils;
69import android.view.animation.DecelerateInterpolator;
70import android.widget.FrameLayout;
71import android.widget.ImageView;
72import android.widget.LinearLayout;
73import android.widget.ScrollView;
74import android.widget.TextView;
75
76import com.android.internal.statusbar.StatusBarIcon;
77import com.android.internal.statusbar.StatusBarNotification;
78import com.android.systemui.R;
79import com.android.systemui.recent.RecentTasksLoader;
80import com.android.systemui.statusbar.BaseStatusBar;
81import com.android.systemui.statusbar.CommandQueue;
82import com.android.systemui.statusbar.GestureRecorder;
83import com.android.systemui.statusbar.NotificationData;
84import com.android.systemui.statusbar.NotificationData.Entry;
85import com.android.systemui.statusbar.RotationToggle;
86import com.android.systemui.statusbar.SignalClusterView;
87import com.android.systemui.statusbar.StatusBarIconView;
88import com.android.systemui.statusbar.policy.BatteryController;
89import com.android.systemui.statusbar.policy.DateView;
90import com.android.systemui.statusbar.policy.IntruderAlertView;
91import com.android.systemui.statusbar.policy.LocationController;
92import com.android.systemui.statusbar.policy.NetworkController;
93import com.android.systemui.statusbar.policy.NotificationRowLayout;
94import com.android.systemui.statusbar.policy.OnSizeChangedListener;
95
96import java.io.FileDescriptor;
97import java.io.PrintWriter;
98import java.util.ArrayList;
99
100public class PhoneStatusBar extends BaseStatusBar {
101    static final String TAG = "PhoneStatusBar";
102    public static final boolean DEBUG = false;
103    public static final boolean SPEW = DEBUG;
104    public static final boolean DUMPTRUCK = true; // extra dumpsys info
105
106    // additional instrumentation for testing purposes; intended to be left on during development
107    public static final boolean CHATTY = DEBUG;
108
109    public static final String ACTION_STATUSBAR_START
110            = "com.android.internal.policy.statusbar.START";
111
112    private static final boolean SHOW_CARRIER_LABEL = false; // XXX: doesn't work with rubberband panels right now
113
114    private static final int MSG_OPEN_NOTIFICATION_PANEL = 1000;
115    private static final int MSG_CLOSE_NOTIFICATION_PANEL = 1001;
116    // 1020-1030 reserved for BaseStatusBar
117
118    // will likely move to a resource or other tunable param at some point
119    private static final int INTRUDER_ALERT_DECAY_MS = 0; // disabled, was 10000;
120
121    private static final boolean CLOSE_PANEL_WHEN_EMPTIED = true;
122
123    private static final int NOTIFICATION_PRIORITY_MULTIPLIER = 10; // see NotificationManagerService
124    private static final int HIDE_ICONS_BELOW_SCORE = Notification.PRIORITY_LOW * NOTIFICATION_PRIORITY_MULTIPLIER;
125
126    // fling gesture tuning parameters, scaled to display density
127    private float mSelfExpandVelocityPx; // classic value: 2000px/s
128    private float mSelfCollapseVelocityPx; // classic value: 2000px/s (will be negated to collapse "up")
129    private float mFlingExpandMinVelocityPx; // classic value: 200px/s
130    private float mFlingCollapseMinVelocityPx; // classic value: 200px/s
131    private float mCollapseMinDisplayFraction; // classic value: 0.08 (25px/min(320px,480px) on G1)
132    private float mExpandMinDisplayFraction; // classic value: 0.5 (drag open halfway to expand)
133    private float mFlingGestureMaxXVelocityPx; // classic value: 150px/s
134
135    private float mExpandAccelPx; // classic value: 2000px/s/s
136    private float mCollapseAccelPx; // classic value: 2000px/s/s (will be negated to collapse "up")
137
138    private float mFlingGestureMaxOutputVelocityPx; // how fast can it really go? (should be a little
139                                                    // faster than mSelfCollapseVelocityPx)
140
141    PhoneStatusBarPolicy mIconPolicy;
142
143    // These are no longer handled by the policy, because we need custom strategies for them
144    BatteryController mBatteryController;
145    LocationController mLocationController;
146    NetworkController mNetworkController;
147
148    int mNaturalBarHeight = -1;
149    int mIconSize = -1;
150    int mIconHPadding = -1;
151    Display mDisplay;
152
153    IDreamManager mDreamManager;
154
155    StatusBarWindowView mStatusBarWindow;
156    PhoneStatusBarView mStatusBarView;
157
158    int mPixelFormat;
159    Object mQueueLock = new Object();
160
161    // icons
162    LinearLayout mIcons;
163    IconMerger mNotificationIcons;
164    View mMoreIcon;
165    LinearLayout mStatusIcons;
166
167    // expanded notifications
168    PanelView mNotificationPanel; // the sliding/resizing panel within the notification window
169    ScrollView mScrollView;
170    View mExpandedContents;
171    final Rect mNotificationPanelBackgroundPadding = new Rect();
172    int mNotificationPanelGravity;
173    int mNotificationPanelMarginBottomPx, mNotificationPanelMarginPx;
174    int mNotificationPanelMinHeight;
175    boolean mNotificationPanelIsFullScreenWidth;
176    TextView mNotificationPanelDebugText;
177
178    // settings
179    PanelView mSettingsPanel;
180    int mSettingsPanelGravity;
181
182    // top bar
183    View mClearButton;
184    View mSettingsButton;
185    RotationToggle mRotationButton;
186
187    // carrier/wifi label
188    private TextView mCarrierLabel;
189    private boolean mCarrierLabelVisible = false;
190    private int mCarrierLabelHeight;
191    private TextView mEmergencyCallLabel;
192
193    // position
194    int[] mPositionTmp = new int[2];
195    boolean mExpandedVisible;
196
197    // the date view
198    DateView mDateView;
199
200    // for immersive activities
201    private IntruderAlertView mIntruderAlertView;
202
203    // on-screen navigation buttons
204    private NavigationBarView mNavigationBarView = null;
205
206    // the tracker view
207    int mTrackingPosition; // the position of the top of the tracking view.
208
209    // ticker
210    private Ticker mTicker;
211    private View mTickerView;
212    private boolean mTicking;
213
214    // Tracking finger for opening/closing.
215    int mEdgeBorder; // corresponds to R.dimen.status_bar_edge_ignore
216    boolean mTracking;
217    VelocityTracker mVelocityTracker;
218
219    boolean mAnimating;
220    boolean mClosing; // only valid when mAnimating; indicates the initial acceleration
221    float mAnimY;
222    float mAnimVel;
223    float mAnimAccel;
224    long mAnimLastTimeNanos;
225    boolean mAnimatingReveal = false;
226    int mViewDelta;
227    float mFlingVelocity;
228    int mFlingY;
229    int[] mAbsPos = new int[2];
230    Runnable mPostCollapseCleanup = null;
231
232    private AnimatorSet mLightsOutAnimation;
233    private AnimatorSet mLightsOnAnimation;
234
235    // for disabling the status bar
236    int mDisabled = 0;
237
238    // tracking calls to View.setSystemUiVisibility()
239    int mSystemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE;
240
241    DisplayMetrics mDisplayMetrics = new DisplayMetrics();
242
243    // XXX: gesture research
244    private GestureRecorder mGestureRec = new GestureRecorder("/sdcard/statusbar_gestures.dat");
245
246    private int mNavigationIconHints = 0;
247    private final Animator.AnimatorListener mMakeIconsInvisible = new AnimatorListenerAdapter() {
248        @Override
249        public void onAnimationEnd(Animator animation) {
250            // double-check to avoid races
251            if (mIcons.getAlpha() == 0) {
252                Slog.d(TAG, "makeIconsInvisible");
253                mIcons.setVisibility(View.INVISIBLE);
254            }
255        }
256    };
257
258    @Override
259    public void start() {
260        mDisplay = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
261                .getDefaultDisplay();
262
263        mDreamManager = IDreamManager.Stub.asInterface(
264                ServiceManager.checkService("dreams"));
265
266        super.start(); // calls createAndAddWindows()
267
268        addNavigationBar();
269
270        if (ENABLE_INTRUDERS) addIntruderView();
271
272        // Lastly, call to the icon policy to install/update all the icons.
273        mIconPolicy = new PhoneStatusBarPolicy(mContext);
274    }
275
276    // ================================================================================
277    // Constructing the view
278    // ================================================================================
279    protected PhoneStatusBarView makeStatusBarView() {
280        final Context context = mContext;
281
282        Resources res = context.getResources();
283
284        updateDisplaySize(); // populates mDisplayMetrics
285        loadDimens();
286
287        mIconSize = res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_icon_size);
288
289        mStatusBarWindow = (StatusBarWindowView) View.inflate(context,
290                R.layout.super_status_bar, null);
291        if (DEBUG) {
292            mStatusBarWindow.setBackgroundColor(0x6000FF80);
293        }
294        mStatusBarWindow.mService = this;
295        mStatusBarWindow.setOnTouchListener(new View.OnTouchListener() {
296            @Override
297            public boolean onTouch(View v, MotionEvent event) {
298                if (event.getAction() == MotionEvent.ACTION_DOWN) {
299                    if (mExpandedVisible && !mAnimating) {
300                        animateCollapse();
301                    }
302                }
303                return mStatusBarWindow.onTouchEvent(event);
304            }});
305
306        mStatusBarView = (PhoneStatusBarView) mStatusBarWindow.findViewById(R.id.status_bar);
307        mStatusBarView.setBar(this);
308
309        PanelHolder holder = (PanelHolder) mStatusBarWindow.findViewById(R.id.panel_holder);
310        mStatusBarView.setPanelHolder(holder);
311
312        mNotificationPanel = (PanelView) mStatusBarWindow.findViewById(R.id.notification_panel);
313        // don't allow clicks on the panel to pass through to the background where they will cause the panel to close
314        View.OnTouchListener clickStopper = new View.OnTouchListener() {
315            @Override
316            public boolean onTouch(View v, MotionEvent event) {
317                return true;
318            }
319        };
320        mNotificationPanel.setOnTouchListener(clickStopper);
321        mNotificationPanelIsFullScreenWidth =
322            (mNotificationPanel.getLayoutParams().width == ViewGroup.LayoutParams.MATCH_PARENT);
323        mNotificationPanel.setSystemUiVisibility(
324                  View.STATUS_BAR_DISABLE_NOTIFICATION_TICKER
325                | (mNotificationPanelIsFullScreenWidth ? 0 : View.STATUS_BAR_DISABLE_SYSTEM_INFO));
326
327        // quick settings (WIP)
328        mSettingsPanel = (PanelView) mStatusBarWindow.findViewById(R.id.settings_panel);
329        mSettingsPanel.setOnTouchListener(clickStopper);
330
331        if (!ActivityManager.isHighEndGfx()) {
332            mStatusBarWindow.setBackground(null);
333            mNotificationPanel.setBackground(new FastColorDrawable(context.getResources().getColor(
334                    R.color.notification_panel_solid_background)));
335            mSettingsPanel.setBackground(new FastColorDrawable(context.getResources().getColor(
336                    R.color.notification_panel_solid_background)));
337        }
338        if (ENABLE_INTRUDERS) {
339            mIntruderAlertView = (IntruderAlertView) View.inflate(context, R.layout.intruder_alert, null);
340            mIntruderAlertView.setVisibility(View.GONE);
341            mIntruderAlertView.setBar(this);
342        }
343        if (MULTIUSER_DEBUG) {
344            mNotificationPanelDebugText = (TextView) mNotificationPanel.findViewById(R.id.header_debug_info);
345            mNotificationPanelDebugText.setVisibility(View.VISIBLE);
346        }
347
348        updateShowSearchHoldoff();
349
350        try {
351            boolean showNav = mWindowManagerService.hasNavigationBar();
352            if (DEBUG) Slog.v(TAG, "hasNavigationBar=" + showNav);
353            if (showNav) {
354                mNavigationBarView =
355                    (NavigationBarView) View.inflate(context, R.layout.navigation_bar, null);
356
357                mNavigationBarView.setDisabledFlags(mDisabled);
358                mNavigationBarView.setBar(this);
359            }
360        } catch (RemoteException ex) {
361            // no window manager? good luck with that
362        }
363
364        // figure out which pixel-format to use for the status bar.
365        mPixelFormat = PixelFormat.OPAQUE;
366        mStatusIcons = (LinearLayout)mStatusBarView.findViewById(R.id.statusIcons);
367        mNotificationIcons = (IconMerger)mStatusBarView.findViewById(R.id.notificationIcons);
368        mNotificationIcons.setOverflowIndicator(mMoreIcon);
369        mIcons = (LinearLayout)mStatusBarView.findViewById(R.id.icons);
370        mTickerView = mStatusBarView.findViewById(R.id.ticker);
371
372        mPile = (NotificationRowLayout)mStatusBarWindow.findViewById(R.id.latestItems);
373        mPile.setLayoutTransitionsEnabled(false);
374        mPile.setLongPressListener(getNotificationLongClicker());
375        mExpandedContents = mPile; // was: expanded.findViewById(R.id.notificationLinearLayout);
376
377        mClearButton = mStatusBarWindow.findViewById(R.id.clear_all_button);
378        mClearButton.setOnClickListener(mClearButtonListener);
379        mClearButton.setAlpha(0f);
380        mClearButton.setVisibility(View.INVISIBLE);
381        mClearButton.setEnabled(false);
382        mDateView = (DateView)mStatusBarWindow.findViewById(R.id.date);
383        mSettingsButton = mStatusBarWindow.findViewById(R.id.settings_button);
384        mSettingsButton.setOnClickListener(mSettingsButtonListener);
385        mRotationButton = (RotationToggle) mStatusBarWindow.findViewById(R.id.rotation_lock_button);
386
387        mScrollView = (ScrollView)mStatusBarWindow.findViewById(R.id.scroll);
388        mScrollView.setVerticalScrollBarEnabled(false); // less drawing during pulldowns
389
390        mTicker = new MyTicker(context, mStatusBarView);
391
392        TickerView tickerView = (TickerView)mStatusBarView.findViewById(R.id.tickerText);
393        tickerView.mTicker = mTicker;
394
395        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
396
397        // set the inital view visibility
398        setAreThereNotifications();
399
400        // Other icons
401        mLocationController = new LocationController(mContext); // will post a notification
402        mBatteryController = new BatteryController(mContext);
403        mBatteryController.addIconView((ImageView)mStatusBarView.findViewById(R.id.battery));
404        mNetworkController = new NetworkController(mContext);
405        final SignalClusterView signalCluster =
406                (SignalClusterView)mStatusBarView.findViewById(R.id.signal_cluster);
407
408        mNetworkController.addSignalCluster(signalCluster);
409        signalCluster.setNetworkController(mNetworkController);
410
411        mEmergencyCallLabel = (TextView)mStatusBarWindow.findViewById(R.id.emergency_calls_only);
412        if (mEmergencyCallLabel != null) {
413            mNetworkController.addEmergencyLabelView(mEmergencyCallLabel);
414            mEmergencyCallLabel.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
415                @Override
416                public void onLayoutChange(View v, int left, int top, int right, int bottom,
417                        int oldLeft, int oldTop, int oldRight, int oldBottom) {
418                    updateCarrierLabelVisibility(false);
419                }});
420        }
421
422        if (SHOW_CARRIER_LABEL) {
423            mCarrierLabel = (TextView)mStatusBarWindow.findViewById(R.id.carrier_label);
424            mCarrierLabel.setVisibility(mCarrierLabelVisible ? View.VISIBLE : View.INVISIBLE);
425
426            // for mobile devices, we always show mobile connection info here (SPN/PLMN)
427            // for other devices, we show whatever network is connected
428            if (mNetworkController.hasMobileDataFeature()) {
429                mNetworkController.addMobileLabelView(mCarrierLabel);
430            } else {
431                mNetworkController.addCombinedLabelView(mCarrierLabel);
432            }
433
434            // set up the dynamic hide/show of the label
435            mPile.setOnSizeChangedListener(new OnSizeChangedListener() {
436                @Override
437                public void onSizeChanged(View view, int w, int h, int oldw, int oldh) {
438                    updateCarrierLabelVisibility(false);
439                }
440            });
441        }
442
443//        final ImageView wimaxRSSI =
444//                (ImageView)sb.findViewById(R.id.wimax_signal);
445//        if (wimaxRSSI != null) {
446//            mNetworkController.addWimaxIconView(wimaxRSSI);
447//        }
448
449        // receive broadcasts
450        IntentFilter filter = new IntentFilter();
451        filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
452        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
453        filter.addAction(Intent.ACTION_SCREEN_OFF);
454        filter.addAction(Intent.ACTION_SCREEN_ON);
455        context.registerReceiver(mBroadcastReceiver, filter);
456
457        return mStatusBarView;
458    }
459
460    @Override
461    protected View getStatusBarView() {
462        return mStatusBarView;
463    }
464
465    @Override
466    protected WindowManager.LayoutParams getRecentsLayoutParams(LayoutParams layoutParams) {
467        boolean opaque = false;
468        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
469                layoutParams.width,
470                layoutParams.height,
471                WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL,
472                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
473                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
474                | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
475                (opaque ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT));
476        if (ActivityManager.isHighEndGfx()) {
477            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
478        } else {
479            lp.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
480            lp.dimAmount = 0.75f;
481        }
482        lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
483        lp.setTitle("RecentsPanel");
484        lp.windowAnimations = com.android.internal.R.style.Animation_RecentApplications;
485        lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED
486        | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
487        return lp;
488    }
489
490    @Override
491    protected WindowManager.LayoutParams getSearchLayoutParams(LayoutParams layoutParams) {
492        boolean opaque = false;
493        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
494                LayoutParams.MATCH_PARENT,
495                LayoutParams.MATCH_PARENT,
496                WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL,
497                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
498                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
499                | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
500                (opaque ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT));
501        if (ActivityManager.isHighEndGfx()) {
502            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
503        }
504        lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
505        lp.setTitle("SearchPanel");
506        // TODO: Define custom animation for Search panel
507        lp.windowAnimations = com.android.internal.R.style.Animation_RecentApplications;
508        lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED
509        | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
510        return lp;
511    }
512
513    /*
514    protected void updateRecentsPanel() {
515        super.updateRecentsPanel(R.layout.status_bar_recent_panel);
516        // Make .03 alpha the minimum so you always see the item a bit-- slightly below
517        // .03, the item disappears entirely (as if alpha = 0) and that discontinuity looks
518        // a bit jarring
519        mRecentsPanel.setMinSwipeAlpha(0.03f);
520        if (mNavigationBarView != null) {
521            mNavigationBarView.getRecentsButton().setOnTouchListener(mRecentsPanel);
522        }
523    }
524    */
525
526    @Override
527    protected void updateSearchPanel() {
528        super.updateSearchPanel();
529        mSearchPanelView.setStatusBarView(mNavigationBarView);
530        mNavigationBarView.setDelegateView(mSearchPanelView);
531    }
532
533    @Override
534    public void showSearchPanel() {
535        super.showSearchPanel();
536        WindowManager.LayoutParams lp =
537            (android.view.WindowManager.LayoutParams) mNavigationBarView.getLayoutParams();
538        lp.flags &= ~WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
539        mWindowManager.updateViewLayout(mNavigationBarView, lp);
540    }
541
542    @Override
543    public void hideSearchPanel() {
544        super.hideSearchPanel();
545        WindowManager.LayoutParams lp =
546            (android.view.WindowManager.LayoutParams) mNavigationBarView.getLayoutParams();
547        lp.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
548        mWindowManager.updateViewLayout(mNavigationBarView, lp);
549    }
550
551    protected int getStatusBarGravity() {
552        return Gravity.TOP | Gravity.FILL_HORIZONTAL;
553    }
554
555    public int getStatusBarHeight() {
556        if (mNaturalBarHeight < 0) {
557            final Resources res = mContext.getResources();
558            mNaturalBarHeight =
559                    res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
560        }
561        return mNaturalBarHeight;
562    }
563
564    private View.OnClickListener mRecentsClickListener = new View.OnClickListener() {
565        public void onClick(View v) {
566            toggleRecentApps();
567        }
568    };
569
570    private int mShowSearchHoldoff = 0;
571    private Runnable mShowSearchPanel = new Runnable() {
572        public void run() {
573            showSearchPanel();
574            awakenDreams();
575        }
576    };
577
578    View.OnTouchListener mHomeSearchActionListener = new View.OnTouchListener() {
579        public boolean onTouch(View v, MotionEvent event) {
580            switch(event.getAction()) {
581            case MotionEvent.ACTION_DOWN:
582                if (!shouldDisableNavbarGestures() && !inKeyguardRestrictedInputMode()) {
583                    mHandler.removeCallbacks(mShowSearchPanel);
584                    mHandler.postDelayed(mShowSearchPanel, mShowSearchHoldoff);
585                }
586            break;
587
588            case MotionEvent.ACTION_UP:
589            case MotionEvent.ACTION_CANCEL:
590                mHandler.removeCallbacks(mShowSearchPanel);
591                awakenDreams();
592            break;
593        }
594        return false;
595        }
596    };
597
598    private void awakenDreams() {
599        if (mDreamManager != null) {
600            try {
601                mDreamManager.awaken();
602            } catch (RemoteException e) {
603                // fine, stay asleep then
604            }
605        }
606    }
607
608    private void prepareNavigationBarView() {
609        mNavigationBarView.reorient();
610
611        mNavigationBarView.getRecentsButton().setOnClickListener(mRecentsClickListener);
612        mNavigationBarView.getRecentsButton().setOnTouchListener(getRecentTasksLoader());
613        mNavigationBarView.getHomeButton().setOnTouchListener(mHomeSearchActionListener);
614        updateSearchPanel();
615    }
616
617    // For small-screen devices (read: phones) that lack hardware navigation buttons
618    private void addNavigationBar() {
619        if (DEBUG) Slog.v(TAG, "addNavigationBar: about to add " + mNavigationBarView);
620        if (mNavigationBarView == null) return;
621
622        prepareNavigationBarView();
623
624        mWindowManager.addView(mNavigationBarView, getNavigationBarLayoutParams());
625    }
626
627    private void repositionNavigationBar() {
628        if (mNavigationBarView == null) return;
629
630        prepareNavigationBarView();
631
632        mWindowManager.updateViewLayout(mNavigationBarView, getNavigationBarLayoutParams());
633    }
634
635    private WindowManager.LayoutParams getNavigationBarLayoutParams() {
636        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
637                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
638                WindowManager.LayoutParams.TYPE_NAVIGATION_BAR,
639                    0
640                    | WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
641                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
642                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
643                    | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
644                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
645                PixelFormat.OPAQUE);
646        // this will allow the navbar to run in an overlay on devices that support this
647        if (ActivityManager.isHighEndGfx()) {
648            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
649        }
650
651        lp.setTitle("NavigationBar");
652        lp.windowAnimations = 0;
653        return lp;
654    }
655
656    private void addIntruderView() {
657        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
658                ViewGroup.LayoutParams.MATCH_PARENT,
659                ViewGroup.LayoutParams.WRAP_CONTENT,
660                WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL, // above the status bar!
661                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
662                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
663                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
664                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
665                    | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
666                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
667                PixelFormat.TRANSLUCENT);
668        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
669        //lp.y += height * 1.5; // FIXME
670        lp.setTitle("IntruderAlert");
671        lp.packageName = mContext.getPackageName();
672        lp.windowAnimations = R.style.Animation_StatusBar_IntruderAlert;
673
674        mWindowManager.addView(mIntruderAlertView, lp);
675    }
676
677    public void addIcon(String slot, int index, int viewIndex, StatusBarIcon icon) {
678        if (SPEW) Slog.d(TAG, "addIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex
679                + " icon=" + icon);
680        StatusBarIconView view = new StatusBarIconView(mContext, slot, null);
681        view.set(icon);
682        mStatusIcons.addView(view, viewIndex, new LinearLayout.LayoutParams(mIconSize, mIconSize));
683    }
684
685    public void updateIcon(String slot, int index, int viewIndex,
686            StatusBarIcon old, StatusBarIcon icon) {
687        if (SPEW) Slog.d(TAG, "updateIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex
688                + " old=" + old + " icon=" + icon);
689        StatusBarIconView view = (StatusBarIconView)mStatusIcons.getChildAt(viewIndex);
690        view.set(icon);
691    }
692
693    public void removeIcon(String slot, int index, int viewIndex) {
694        if (SPEW) Slog.d(TAG, "removeIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex);
695        mStatusIcons.removeViewAt(viewIndex);
696    }
697
698    public void addNotification(IBinder key, StatusBarNotification notification) {
699        /* if (DEBUG) */ Slog.d(TAG, "addNotification score=" + notification.score);
700        StatusBarIconView iconView = addNotificationViews(key, notification);
701        if (iconView == null) return;
702
703        boolean immersive = false;
704        try {
705            immersive = ActivityManagerNative.getDefault().isTopActivityImmersive();
706            if (DEBUG) {
707                Slog.d(TAG, "Top activity is " + (immersive?"immersive":"not immersive"));
708            }
709        } catch (RemoteException ex) {
710        }
711
712        /*
713         * DISABLED due to missing API
714        if (ENABLE_INTRUDERS && (
715                   // TODO(dsandler): Only if the screen is on
716                notification.notification.intruderView != null)) {
717            Slog.d(TAG, "Presenting high-priority notification");
718            // special new transient ticker mode
719            // 1. Populate mIntruderAlertView
720
721            if (notification.notification.intruderView == null) {
722                Slog.e(TAG, notification.notification.toString() + " wanted to intrude but intruderView was null");
723                return;
724            }
725
726            // bind the click event to the content area
727            PendingIntent contentIntent = notification.notification.contentIntent;
728            final View.OnClickListener listener = (contentIntent != null)
729                    ? new NotificationClicker(contentIntent,
730                            notification.pkg, notification.tag, notification.id)
731                    : null;
732
733            mIntruderAlertView.applyIntruderContent(notification.notification.intruderView, listener);
734
735            mCurrentlyIntrudingNotification = notification;
736
737            // 2. Animate mIntruderAlertView in
738            mHandler.sendEmptyMessage(MSG_SHOW_INTRUDER);
739
740            // 3. Set alarm to age the notification off (TODO)
741            mHandler.removeMessages(MSG_HIDE_INTRUDER);
742            if (INTRUDER_ALERT_DECAY_MS > 0) {
743                mHandler.sendEmptyMessageDelayed(MSG_HIDE_INTRUDER, INTRUDER_ALERT_DECAY_MS);
744            }
745        } else
746         */
747
748        if (notification.notification.fullScreenIntent != null) {
749            // not immersive & a full-screen alert should be shown
750            Slog.d(TAG, "Notification has fullScreenIntent; sending fullScreenIntent");
751            try {
752                notification.notification.fullScreenIntent.send();
753            } catch (PendingIntent.CanceledException e) {
754            }
755        } else {
756            // usual case: status bar visible & not immersive
757
758            // show the ticker if there isn't an intruder too
759            if (mCurrentlyIntrudingNotification == null) {
760                tick(null, notification, true);
761            }
762        }
763
764        // Recalculate the position of the sliding windows and the titles.
765        setAreThereNotifications();
766        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
767    }
768
769    public void removeNotification(IBinder key) {
770        StatusBarNotification old = removeNotificationViews(key);
771        if (SPEW) Slog.d(TAG, "removeNotification key=" + key + " old=" + old);
772
773        if (old != null) {
774            // Cancel the ticker if it's still running
775            mTicker.removeEntry(old);
776
777            // Recalculate the position of the sliding windows and the titles.
778            updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
779
780            if (ENABLE_INTRUDERS && old == mCurrentlyIntrudingNotification) {
781                mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
782            }
783
784            if (CLOSE_PANEL_WHEN_EMPTIED && mNotificationData.size() == 0 && !mAnimating) {
785                animateCollapse();
786            }
787        }
788
789        setAreThereNotifications();
790    }
791
792    private void updateShowSearchHoldoff() {
793        mShowSearchHoldoff = mContext.getResources().getInteger(
794            R.integer.config_show_search_delay);
795    }
796
797    private void loadNotificationShade() {
798        if (mPile == null) return;
799
800        int N = mNotificationData.size();
801
802        ArrayList<View> toShow = new ArrayList<View>();
803
804        final boolean provisioned = isDeviceProvisioned();
805        // If the device hasn't been through Setup, we only show system notifications
806        for (int i=0; i<N; i++) {
807            Entry ent = mNotificationData.get(N-i-1);
808            if (!(provisioned || showNotificationEvenIfUnprovisioned(ent.notification))) continue;
809            if (!notificationIsForCurrentUser(ent.notification)) continue;
810            toShow.add(ent.row);
811        }
812
813        ArrayList<View> toRemove = new ArrayList<View>();
814        for (int i=0; i<mPile.getChildCount(); i++) {
815            View child = mPile.getChildAt(i);
816            if (!toShow.contains(child)) {
817                toRemove.add(child);
818            }
819        }
820
821        for (View remove : toRemove) {
822            mPile.removeView(remove);
823        }
824
825        for (int i=0; i<toShow.size(); i++) {
826            View v = toShow.get(i);
827            if (v.getParent() == null) {
828                mPile.addView(v, i);
829            }
830        }
831
832        mSettingsButton.setEnabled(isDeviceProvisioned());
833    }
834
835    @Override
836    protected void updateNotificationIcons() {
837        if (mNotificationIcons == null) return;
838
839        loadNotificationShade();
840
841        final LinearLayout.LayoutParams params
842            = new LinearLayout.LayoutParams(mIconSize + 2*mIconHPadding, mNaturalBarHeight);
843
844        int N = mNotificationData.size();
845
846        if (DEBUG) {
847            Slog.d(TAG, "refreshing icons: " + N + " notifications, mNotificationIcons=" + mNotificationIcons);
848        }
849
850        ArrayList<View> toShow = new ArrayList<View>();
851
852        final boolean provisioned = isDeviceProvisioned();
853        // If the device hasn't been through Setup, we only show system notifications
854        for (int i=0; i<N; i++) {
855            Entry ent = mNotificationData.get(N-i-1);
856            if (!((provisioned && ent.notification.score >= HIDE_ICONS_BELOW_SCORE)
857                    || showNotificationEvenIfUnprovisioned(ent.notification))) continue;
858            if (!notificationIsForCurrentUser(ent.notification)) continue;
859            toShow.add(ent.icon);
860        }
861
862        ArrayList<View> toRemove = new ArrayList<View>();
863        for (int i=0; i<mNotificationIcons.getChildCount(); i++) {
864            View child = mNotificationIcons.getChildAt(i);
865            if (!toShow.contains(child)) {
866                toRemove.add(child);
867            }
868        }
869
870        for (View remove : toRemove) {
871            mNotificationIcons.removeView(remove);
872        }
873
874        for (int i=0; i<toShow.size(); i++) {
875            View v = toShow.get(i);
876            if (v.getParent() == null) {
877                mNotificationIcons.addView(v, i, params);
878            }
879        }
880    }
881
882    protected void updateCarrierLabelVisibility(boolean force) {
883        if (!SHOW_CARRIER_LABEL) return;
884        // The idea here is to only show the carrier label when there is enough room to see it,
885        // i.e. when there aren't enough notifications to fill the panel.
886        if (DEBUG) {
887            Slog.d(TAG, String.format("pileh=%d scrollh=%d carrierh=%d",
888                    mPile.getHeight(), mScrollView.getHeight(), mCarrierLabelHeight));
889        }
890
891        final boolean emergencyCallsShownElsewhere = mEmergencyCallLabel != null;
892        final boolean makeVisible =
893            !(emergencyCallsShownElsewhere && mNetworkController.isEmergencyOnly())
894            && mPile.getHeight() < (mScrollView.getHeight() - mCarrierLabelHeight);
895
896        if (force || mCarrierLabelVisible != makeVisible) {
897            mCarrierLabelVisible = makeVisible;
898            if (DEBUG) {
899                Slog.d(TAG, "making carrier label " + (makeVisible?"visible":"invisible"));
900            }
901            mCarrierLabel.animate().cancel();
902            if (makeVisible) {
903                mCarrierLabel.setVisibility(View.VISIBLE);
904            }
905            mCarrierLabel.animate()
906                .alpha(makeVisible ? 1f : 0f)
907                //.setStartDelay(makeVisible ? 500 : 0)
908                //.setDuration(makeVisible ? 750 : 100)
909                .setDuration(150)
910                .setListener(makeVisible ? null : new AnimatorListenerAdapter() {
911                    @Override
912                    public void onAnimationEnd(Animator animation) {
913                        if (!mCarrierLabelVisible) { // race
914                            mCarrierLabel.setVisibility(View.INVISIBLE);
915                            mCarrierLabel.setAlpha(0f);
916                        }
917                    }
918                })
919                .start();
920        }
921    }
922
923    @Override
924    protected void setAreThereNotifications() {
925        final boolean any = mNotificationData.size() > 0;
926
927        final boolean clearable = any && mNotificationData.hasClearableItems();
928
929        if (DEBUG) {
930            Slog.d(TAG, "setAreThereNotifications: N=" + mNotificationData.size()
931                    + " any=" + any + " clearable=" + clearable);
932        }
933
934        if (mClearButton.isShown()) {
935            if (clearable != (mClearButton.getAlpha() == 1.0f)) {
936                ObjectAnimator clearAnimation = ObjectAnimator.ofFloat(
937                        mClearButton, "alpha", clearable ? 1.0f : 0.0f).setDuration(250);
938                clearAnimation.addListener(new AnimatorListenerAdapter() {
939                    @Override
940                    public void onAnimationEnd(Animator animation) {
941                        if (mClearButton.getAlpha() <= 0.0f) {
942                            mClearButton.setVisibility(View.INVISIBLE);
943                        }
944                    }
945
946                    @Override
947                    public void onAnimationStart(Animator animation) {
948                        if (mClearButton.getAlpha() <= 0.0f) {
949                            mClearButton.setVisibility(View.VISIBLE);
950                        }
951                    }
952                });
953                clearAnimation.start();
954            }
955        } else {
956            mClearButton.setAlpha(clearable ? 1.0f : 0.0f);
957            mClearButton.setVisibility(clearable ? View.VISIBLE : View.INVISIBLE);
958        }
959        mClearButton.setEnabled(clearable);
960
961        final View nlo = mStatusBarView.findViewById(R.id.notification_lights_out);
962        final boolean showDot = (any&&!areLightsOn());
963        if (showDot != (nlo.getAlpha() == 1.0f)) {
964            if (showDot) {
965                nlo.setAlpha(0f);
966                nlo.setVisibility(View.VISIBLE);
967            }
968            nlo.animate()
969                .alpha(showDot?1:0)
970                .setDuration(showDot?750:250)
971                .setInterpolator(new AccelerateInterpolator(2.0f))
972                .setListener(showDot ? null : new AnimatorListenerAdapter() {
973                    @Override
974                    public void onAnimationEnd(Animator _a) {
975                        nlo.setVisibility(View.GONE);
976                    }
977                })
978                .start();
979        }
980
981        updateCarrierLabelVisibility(false);
982    }
983
984    public void showClock(boolean show) {
985        if (mStatusBarView == null) return;
986        View clock = mStatusBarView.findViewById(R.id.clock);
987        if (clock != null) {
988            clock.setVisibility(show ? View.VISIBLE : View.GONE);
989        }
990    }
991
992    /**
993     * State is one or more of the DISABLE constants from StatusBarManager.
994     */
995    public void disable(int state) {
996        final int old = mDisabled;
997        final int diff = state ^ old;
998        mDisabled = state;
999
1000        if (DEBUG) {
1001            Slog.d(TAG, String.format("disable: 0x%08x -> 0x%08x (diff: 0x%08x)",
1002                old, state, diff));
1003        }
1004
1005        StringBuilder flagdbg = new StringBuilder();
1006        flagdbg.append("disable: < ");
1007        flagdbg.append(((state & StatusBarManager.DISABLE_EXPAND) != 0) ? "EXPAND" : "expand");
1008        flagdbg.append(((diff  & StatusBarManager.DISABLE_EXPAND) != 0) ? "* " : " ");
1009        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) ? "ICONS" : "icons");
1010        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) ? "* " : " ");
1011        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) ? "ALERTS" : "alerts");
1012        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) ? "* " : " ");
1013        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) ? "TICKER" : "ticker");
1014        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) ? "* " : " ");
1015        flagdbg.append(((state & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) ? "SYSTEM_INFO" : "system_info");
1016        flagdbg.append(((diff  & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) ? "* " : " ");
1017        flagdbg.append(((state & StatusBarManager.DISABLE_BACK) != 0) ? "BACK" : "back");
1018        flagdbg.append(((diff  & StatusBarManager.DISABLE_BACK) != 0) ? "* " : " ");
1019        flagdbg.append(((state & StatusBarManager.DISABLE_HOME) != 0) ? "HOME" : "home");
1020        flagdbg.append(((diff  & StatusBarManager.DISABLE_HOME) != 0) ? "* " : " ");
1021        flagdbg.append(((state & StatusBarManager.DISABLE_RECENT) != 0) ? "RECENT" : "recent");
1022        flagdbg.append(((diff  & StatusBarManager.DISABLE_RECENT) != 0) ? "* " : " ");
1023        flagdbg.append(((state & StatusBarManager.DISABLE_CLOCK) != 0) ? "CLOCK" : "clock");
1024        flagdbg.append(((diff  & StatusBarManager.DISABLE_CLOCK) != 0) ? "* " : " ");
1025        flagdbg.append(">");
1026        Slog.d(TAG, flagdbg.toString());
1027
1028        if ((diff & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) {
1029            mIcons.animate().cancel();
1030            if ((state & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) {
1031                if (mTicking) {
1032                    mTicker.halt();
1033                }
1034                mIcons.animate()
1035                    .alpha(0f)
1036                    .translationY(mNaturalBarHeight*0.5f)
1037                    //.setStartDelay(100)
1038                    .setDuration(175)
1039                    .setInterpolator(new DecelerateInterpolator(1.5f))
1040                    .setListener(mMakeIconsInvisible)
1041                    .start();
1042            } else {
1043                mIcons.setVisibility(View.VISIBLE);
1044                mIcons.animate()
1045                    .alpha(1f)
1046                    .translationY(0)
1047                    .setStartDelay(0)
1048                    .setInterpolator(new DecelerateInterpolator(1.5f))
1049                    .setDuration(175)
1050                    .start();
1051            }
1052        }
1053
1054        if ((diff & StatusBarManager.DISABLE_CLOCK) != 0) {
1055            boolean show = (state & StatusBarManager.DISABLE_CLOCK) == 0;
1056            showClock(show);
1057        }
1058        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
1059            if ((state & StatusBarManager.DISABLE_EXPAND) != 0) {
1060                animateCollapse();
1061            }
1062        }
1063
1064        if ((diff & (StatusBarManager.DISABLE_HOME
1065                        | StatusBarManager.DISABLE_RECENT
1066                        | StatusBarManager.DISABLE_BACK)) != 0) {
1067            // the nav bar will take care of these
1068            if (mNavigationBarView != null) mNavigationBarView.setDisabledFlags(state);
1069
1070            if ((state & StatusBarManager.DISABLE_RECENT) != 0) {
1071                // close recents if it's visible
1072                mHandler.removeMessages(MSG_CLOSE_RECENTS_PANEL);
1073                mHandler.sendEmptyMessage(MSG_CLOSE_RECENTS_PANEL);
1074            }
1075        }
1076
1077        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1078            if ((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1079                if (mTicking) {
1080                    mTicker.halt();
1081                } else {
1082                    setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
1083                }
1084            } else {
1085                if (!mExpandedVisible) {
1086                    setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
1087                }
1088            }
1089        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1090            if (mTicking && (state & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1091                mTicker.halt();
1092            }
1093        }
1094    }
1095
1096    @Override
1097    protected BaseStatusBar.H createHandler() {
1098        return new PhoneStatusBar.H();
1099    }
1100
1101    /**
1102     * All changes to the status bar and notifications funnel through here and are batched.
1103     */
1104    private class H extends BaseStatusBar.H {
1105        public void handleMessage(Message m) {
1106            super.handleMessage(m);
1107            switch (m.what) {
1108                case MSG_OPEN_NOTIFICATION_PANEL:
1109                    animateExpand();
1110                    break;
1111                case MSG_CLOSE_NOTIFICATION_PANEL:
1112                    animateCollapse();
1113                    break;
1114                case MSG_SHOW_INTRUDER:
1115                    setIntruderAlertVisibility(true);
1116                    break;
1117                case MSG_HIDE_INTRUDER:
1118                    setIntruderAlertVisibility(false);
1119                    mCurrentlyIntrudingNotification = null;
1120                    break;
1121            }
1122        }
1123    }
1124
1125    View.OnFocusChangeListener mFocusChangeListener = new View.OnFocusChangeListener() {
1126        public void onFocusChange(View v, boolean hasFocus) {
1127            // Because 'v' is a ViewGroup, all its children will be (un)selected
1128            // too, which allows marqueeing to work.
1129            v.setSelected(hasFocus);
1130        }
1131    };
1132
1133    void makeExpandedVisible(boolean revealAfterDraw) {
1134        if (SPEW) Slog.d(TAG, "Make expanded visible: expanded visible=" + mExpandedVisible);
1135        if (mExpandedVisible) {
1136            return;
1137        }
1138
1139        mExpandedVisible = true;
1140        mPile.setLayoutTransitionsEnabled(true);
1141        if (mNavigationBarView != null)
1142            mNavigationBarView.setSlippery(true);
1143
1144        updateCarrierLabelVisibility(true);
1145
1146        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1147
1148        // Expand the window to encompass the full screen in anticipation of the drag.
1149        // This is only possible to do atomically because the status bar is at the top of the screen!
1150        WindowManager.LayoutParams lp = (WindowManager.LayoutParams) mStatusBarWindow.getLayoutParams();
1151        lp.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1152        lp.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
1153        lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
1154        mWindowManager.updateViewLayout(mStatusBarWindow, lp);
1155
1156        // Updating the window layout will force an expensive traversal/redraw.
1157        // Kick off the reveal animation after this is complete to avoid animation latency.
1158        if (revealAfterDraw) {
1159//            mHandler.post(mStartRevealAnimation);
1160        }
1161
1162        visibilityChanged(true);
1163    }
1164
1165    public void animateCollapse() {
1166        animateCollapse(CommandQueue.FLAG_EXCLUDE_NONE);
1167    }
1168
1169    public void animateCollapse(int flags) {
1170        if (SPEW) {
1171            Slog.d(TAG, "animateCollapse(): "
1172                    + " mExpandedVisible=" + mExpandedVisible
1173                    + " mAnimating=" + mAnimating
1174                    + " mAnimatingReveal=" + mAnimatingReveal
1175                    + " mAnimY=" + mAnimY
1176                    + " mAnimVel=" + mAnimVel
1177                    + " flags=" + flags);
1178        }
1179
1180        if ((flags & CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL) == 0) {
1181            mHandler.removeMessages(MSG_CLOSE_RECENTS_PANEL);
1182            mHandler.sendEmptyMessage(MSG_CLOSE_RECENTS_PANEL);
1183        }
1184
1185        if ((flags & CommandQueue.FLAG_EXCLUDE_SEARCH_PANEL) == 0) {
1186            mHandler.removeMessages(MSG_CLOSE_SEARCH_PANEL);
1187            mHandler.sendEmptyMessage(MSG_CLOSE_SEARCH_PANEL);
1188        }
1189
1190        mStatusBarView.collapseAllPanels(true);
1191    }
1192
1193    @Override
1194    public void animateExpand() {
1195        if (SPEW) Slog.d(TAG, "animateExpand: mExpandedVisible=" + mExpandedVisible);
1196        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1197            return ;
1198        }
1199
1200        mNotificationPanel.expand();
1201
1202        if (false) postStartTracing();
1203    }
1204
1205    void makeExpandedInvisible() {
1206        if (SPEW) Slog.d(TAG, "makeExpandedInvisible: mExpandedVisible=" + mExpandedVisible
1207                + " mExpandedVisible=" + mExpandedVisible);
1208
1209        if (!mExpandedVisible) {
1210            return;
1211        }
1212
1213        // Ensure the panel is fully collapsed (just in case; bug 6765842)
1214        mStatusBarView.collapseAllPanels(/*animate=*/ false);
1215
1216        mExpandedVisible = false;
1217        mPile.setLayoutTransitionsEnabled(false);
1218        if (mNavigationBarView != null)
1219            mNavigationBarView.setSlippery(false);
1220        visibilityChanged(false);
1221
1222        // Shrink the window to the size of the status bar only
1223        WindowManager.LayoutParams lp = (WindowManager.LayoutParams) mStatusBarWindow.getLayoutParams();
1224        lp.height = getStatusBarHeight();
1225        lp.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1226        lp.flags &= ~WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
1227        mWindowManager.updateViewLayout(mStatusBarWindow, lp);
1228
1229        if ((mDisabled & StatusBarManager.DISABLE_NOTIFICATION_ICONS) == 0) {
1230            setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
1231        }
1232
1233        // Close any "App info" popups that might have snuck on-screen
1234        dismissPopups();
1235
1236        if (mPostCollapseCleanup != null) {
1237            mPostCollapseCleanup.run();
1238            mPostCollapseCleanup = null;
1239        }
1240    }
1241
1242    /**
1243     * Enables or disables layers on the children of the notifications pile.
1244     *
1245     * When layers are enabled, this method attempts to enable layers for the minimal
1246     * number of children. Only children visible when the notification area is fully
1247     * expanded will receive a layer. The technique used in this method might cause
1248     * more children than necessary to get a layer (at most one extra child with the
1249     * current UI.)
1250     *
1251     * @param layerType {@link View#LAYER_TYPE_NONE} or {@link View#LAYER_TYPE_HARDWARE}
1252     */
1253    private void setPileLayers(int layerType) {
1254        final int count = mPile.getChildCount();
1255
1256        switch (layerType) {
1257            case View.LAYER_TYPE_NONE:
1258                for (int i = 0; i < count; i++) {
1259                    mPile.getChildAt(i).setLayerType(layerType, null);
1260                }
1261                break;
1262            case View.LAYER_TYPE_HARDWARE:
1263                final int[] location = new int[2];
1264                mNotificationPanel.getLocationInWindow(location);
1265
1266                final int left = location[0];
1267                final int top = location[1];
1268                final int right = left + mNotificationPanel.getWidth();
1269                final int bottom = top + getExpandedViewMaxHeight();
1270
1271                final Rect childBounds = new Rect();
1272
1273                for (int i = 0; i < count; i++) {
1274                    final View view = mPile.getChildAt(i);
1275                    view.getLocationInWindow(location);
1276
1277                    childBounds.set(location[0], location[1],
1278                            location[0] + view.getWidth(), location[1] + view.getHeight());
1279
1280                    if (childBounds.intersects(left, top, right, bottom)) {
1281                        view.setLayerType(layerType, null);
1282                    }
1283                }
1284
1285                break;
1286        }
1287    }
1288
1289    boolean interceptTouchEvent(MotionEvent event) {
1290        if (SPEW) {
1291            Slog.d(TAG, "Touch: rawY=" + event.getRawY() + " event=" + event + " mDisabled="
1292                + mDisabled + " mTracking=" + mTracking);
1293        } else if (CHATTY) {
1294            if (event.getAction() != MotionEvent.ACTION_MOVE) {
1295                Slog.d(TAG, String.format(
1296                            "panel: %s at (%f, %f) mDisabled=0x%08x",
1297                            MotionEvent.actionToString(event.getAction()),
1298                            event.getRawX(), event.getRawY(), mDisabled));
1299            }
1300        }
1301
1302        mGestureRec.add(event);
1303
1304        return false;
1305    }
1306
1307    public GestureRecorder getGestureRecorder() {
1308        return mGestureRec;
1309    }
1310
1311    @Override // CommandQueue
1312    public void setNavigationIconHints(int hints) {
1313        if (hints == mNavigationIconHints) return;
1314
1315        mNavigationIconHints = hints;
1316
1317        if (mNavigationBarView != null) {
1318            mNavigationBarView.setNavigationIconHints(hints);
1319        }
1320    }
1321
1322    @Override // CommandQueue
1323    public void setSystemUiVisibility(int vis, int mask) {
1324        final int oldVal = mSystemUiVisibility;
1325        final int newVal = (oldVal&~mask) | (vis&mask);
1326        final int diff = newVal ^ oldVal;
1327
1328        if (diff != 0) {
1329            mSystemUiVisibility = newVal;
1330
1331            if (0 != (diff & View.SYSTEM_UI_FLAG_LOW_PROFILE)) {
1332                final boolean lightsOut = (0 != (vis & View.SYSTEM_UI_FLAG_LOW_PROFILE));
1333                if (lightsOut) {
1334                    animateCollapse();
1335                    if (mTicking) {
1336                        mTicker.halt();
1337                    }
1338                }
1339
1340                if (mNavigationBarView != null) {
1341                    mNavigationBarView.setLowProfile(lightsOut);
1342                }
1343
1344                setStatusBarLowProfile(lightsOut);
1345            }
1346
1347            notifyUiVisibilityChanged();
1348        }
1349    }
1350
1351    private void setStatusBarLowProfile(boolean lightsOut) {
1352        if (mLightsOutAnimation == null) {
1353            final View notifications = mStatusBarView.findViewById(R.id.notification_icon_area);
1354            final View systemIcons = mStatusBarView.findViewById(R.id.statusIcons);
1355            final View signal = mStatusBarView.findViewById(R.id.signal_cluster);
1356            final View battery = mStatusBarView.findViewById(R.id.battery);
1357            final View clock = mStatusBarView.findViewById(R.id.clock);
1358
1359            mLightsOutAnimation = new AnimatorSet();
1360            mLightsOutAnimation.playTogether(
1361                    ObjectAnimator.ofFloat(notifications, View.ALPHA, 0),
1362                    ObjectAnimator.ofFloat(systemIcons, View.ALPHA, 0),
1363                    ObjectAnimator.ofFloat(signal, View.ALPHA, 0),
1364                    ObjectAnimator.ofFloat(battery, View.ALPHA, 0.5f),
1365                    ObjectAnimator.ofFloat(clock, View.ALPHA, 0.5f)
1366                );
1367            mLightsOutAnimation.setDuration(750);
1368
1369            mLightsOnAnimation = new AnimatorSet();
1370            mLightsOnAnimation.playTogether(
1371                    ObjectAnimator.ofFloat(notifications, View.ALPHA, 1),
1372                    ObjectAnimator.ofFloat(systemIcons, View.ALPHA, 1),
1373                    ObjectAnimator.ofFloat(signal, View.ALPHA, 1),
1374                    ObjectAnimator.ofFloat(battery, View.ALPHA, 1),
1375                    ObjectAnimator.ofFloat(clock, View.ALPHA, 1)
1376                );
1377            mLightsOnAnimation.setDuration(250);
1378        }
1379
1380        mLightsOutAnimation.cancel();
1381        mLightsOnAnimation.cancel();
1382
1383        final Animator a = lightsOut ? mLightsOutAnimation : mLightsOnAnimation;
1384        a.start();
1385
1386        setAreThereNotifications();
1387    }
1388
1389    private boolean areLightsOn() {
1390        return 0 == (mSystemUiVisibility & View.SYSTEM_UI_FLAG_LOW_PROFILE);
1391    }
1392
1393    public void setLightsOn(boolean on) {
1394        Log.v(TAG, "setLightsOn(" + on + ")");
1395        if (on) {
1396            setSystemUiVisibility(0, View.SYSTEM_UI_FLAG_LOW_PROFILE);
1397        } else {
1398            setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE, View.SYSTEM_UI_FLAG_LOW_PROFILE);
1399        }
1400    }
1401
1402    private void notifyUiVisibilityChanged() {
1403        try {
1404            mWindowManagerService.statusBarVisibilityChanged(mSystemUiVisibility);
1405        } catch (RemoteException ex) {
1406        }
1407    }
1408
1409    public void topAppWindowChanged(boolean showMenu) {
1410        if (DEBUG) {
1411            Slog.d(TAG, (showMenu?"showing":"hiding") + " the MENU button");
1412        }
1413        if (mNavigationBarView != null) {
1414            mNavigationBarView.setMenuVisibility(showMenu);
1415        }
1416
1417        // See above re: lights-out policy for legacy apps.
1418        if (showMenu) setLightsOn(true);
1419    }
1420
1421    @Override
1422    public void setImeWindowStatus(IBinder token, int vis, int backDisposition) {
1423        boolean altBack = (backDisposition == InputMethodService.BACK_DISPOSITION_WILL_DISMISS)
1424            || ((vis & InputMethodService.IME_VISIBLE) != 0);
1425
1426        mCommandQueue.setNavigationIconHints(
1427                altBack ? (mNavigationIconHints | StatusBarManager.NAVIGATION_HINT_BACK_ALT)
1428                        : (mNavigationIconHints & ~StatusBarManager.NAVIGATION_HINT_BACK_ALT));
1429    }
1430
1431    @Override
1432    public void setHardKeyboardStatus(boolean available, boolean enabled) { }
1433
1434    @Override
1435    protected void tick(IBinder key, StatusBarNotification n, boolean firstTime) {
1436        // no ticking in lights-out mode
1437        if (!areLightsOn()) return;
1438
1439        // no ticking in Setup
1440        if (!isDeviceProvisioned()) return;
1441
1442        // Show the ticker if one is requested. Also don't do this
1443        // until status bar window is attached to the window manager,
1444        // because...  well, what's the point otherwise?  And trying to
1445        // run a ticker without being attached will crash!
1446        if (n.notification.tickerText != null && mStatusBarWindow.getWindowToken() != null) {
1447            if (0 == (mDisabled & (StatusBarManager.DISABLE_NOTIFICATION_ICONS
1448                            | StatusBarManager.DISABLE_NOTIFICATION_TICKER))) {
1449                mTicker.addEntry(n);
1450            }
1451        }
1452    }
1453
1454    private class MyTicker extends Ticker {
1455        MyTicker(Context context, View sb) {
1456            super(context, sb);
1457        }
1458
1459        @Override
1460        public void tickerStarting() {
1461            mTicking = true;
1462            mIcons.setVisibility(View.GONE);
1463            mTickerView.setVisibility(View.VISIBLE);
1464            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_up_in, null));
1465            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_up_out, null));
1466        }
1467
1468        @Override
1469        public void tickerDone() {
1470            mIcons.setVisibility(View.VISIBLE);
1471            mTickerView.setVisibility(View.GONE);
1472            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_down_in, null));
1473            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_down_out,
1474                        mTickingDoneListener));
1475        }
1476
1477        public void tickerHalting() {
1478            mIcons.setVisibility(View.VISIBLE);
1479            mTickerView.setVisibility(View.GONE);
1480            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
1481            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.fade_out,
1482                        mTickingDoneListener));
1483        }
1484    }
1485
1486    Animation.AnimationListener mTickingDoneListener = new Animation.AnimationListener() {;
1487        public void onAnimationEnd(Animation animation) {
1488            mTicking = false;
1489        }
1490        public void onAnimationRepeat(Animation animation) {
1491        }
1492        public void onAnimationStart(Animation animation) {
1493        }
1494    };
1495
1496    private Animation loadAnim(int id, Animation.AnimationListener listener) {
1497        Animation anim = AnimationUtils.loadAnimation(mContext, id);
1498        if (listener != null) {
1499            anim.setAnimationListener(listener);
1500        }
1501        return anim;
1502    }
1503
1504    public static String viewInfo(View v) {
1505        return "[(" + v.getLeft() + "," + v.getTop() + ")(" + v.getRight() + "," + v.getBottom()
1506                + ") " + v.getWidth() + "x" + v.getHeight() + "]";
1507    }
1508
1509    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1510        synchronized (mQueueLock) {
1511            pw.println("Current Status Bar state:");
1512            pw.println("  mExpandedVisible=" + mExpandedVisible
1513                    + ", mTrackingPosition=" + mTrackingPosition);
1514            pw.println("  mTicking=" + mTicking);
1515            pw.println("  mTracking=" + mTracking);
1516            pw.println("  mNotificationPanel=" +
1517                    ((mNotificationPanel == null)
1518                            ? "null"
1519                            : (mNotificationPanel + " params=" + mNotificationPanel.getLayoutParams().debug(""))));
1520            pw.println("  mAnimating=" + mAnimating
1521                    + ", mAnimY=" + mAnimY + ", mAnimVel=" + mAnimVel
1522                    + ", mAnimAccel=" + mAnimAccel);
1523            pw.println("  mAnimLastTimeNanos=" + mAnimLastTimeNanos);
1524            pw.println("  mAnimatingReveal=" + mAnimatingReveal
1525                    + " mViewDelta=" + mViewDelta);
1526            pw.println("  mDisplayMetrics=" + mDisplayMetrics);
1527            pw.println("  mPile: " + viewInfo(mPile));
1528            pw.println("  mTickerView: " + viewInfo(mTickerView));
1529            pw.println("  mScrollView: " + viewInfo(mScrollView)
1530                    + " scroll " + mScrollView.getScrollX() + "," + mScrollView.getScrollY());
1531        }
1532
1533        pw.print("  mNavigationBarView=");
1534        if (mNavigationBarView == null) {
1535            pw.println("null");
1536        } else {
1537            mNavigationBarView.dump(fd, pw, args);
1538        }
1539
1540        if (DUMPTRUCK) {
1541            synchronized (mNotificationData) {
1542                int N = mNotificationData.size();
1543                pw.println("  notification icons: " + N);
1544                for (int i=0; i<N; i++) {
1545                    NotificationData.Entry e = mNotificationData.get(i);
1546                    pw.println("    [" + i + "] key=" + e.key + " icon=" + e.icon);
1547                    StatusBarNotification n = e.notification;
1548                    pw.println("         pkg=" + n.pkg + " id=" + n.id + " score=" + n.score);
1549                    pw.println("         notification=" + n.notification);
1550                    pw.println("         tickerText=\"" + n.notification.tickerText + "\"");
1551                }
1552            }
1553
1554            int N = mStatusIcons.getChildCount();
1555            pw.println("  system icons: " + N);
1556            for (int i=0; i<N; i++) {
1557                StatusBarIconView ic = (StatusBarIconView) mStatusIcons.getChildAt(i);
1558                pw.println("    [" + i + "] icon=" + ic);
1559            }
1560
1561            if (false) {
1562                pw.println("see the logcat for a dump of the views we have created.");
1563                // must happen on ui thread
1564                mHandler.post(new Runnable() {
1565                        public void run() {
1566                            mStatusBarView.getLocationOnScreen(mAbsPos);
1567                            Slog.d(TAG, "mStatusBarView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1568                                    + ") " + mStatusBarView.getWidth() + "x"
1569                                    + getStatusBarHeight());
1570                            mStatusBarView.debug();
1571                        }
1572                    });
1573            }
1574        }
1575
1576        pw.print("  status bar gestures: ");
1577        mGestureRec.dump(fd, pw, args);
1578
1579        mNetworkController.dump(fd, pw, args);
1580    }
1581
1582    @Override
1583    public void createAndAddWindows() {
1584        addStatusBarWindow();
1585    }
1586
1587    private void addStatusBarWindow() {
1588        // Put up the view
1589        final int height = getStatusBarHeight();
1590
1591        // Now that the status bar window encompasses the sliding panel and its
1592        // translucent backdrop, the entire thing is made TRANSLUCENT and is
1593        // hardware-accelerated.
1594        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
1595                ViewGroup.LayoutParams.MATCH_PARENT,
1596                height,
1597                WindowManager.LayoutParams.TYPE_STATUS_BAR,
1598                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1599                    | WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
1600                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
1601                PixelFormat.TRANSLUCENT);
1602
1603        lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
1604
1605        lp.gravity = getStatusBarGravity();
1606        lp.setTitle("StatusBar");
1607        lp.packageName = mContext.getPackageName();
1608
1609        makeStatusBarView();
1610        mWindowManager.addView(mStatusBarWindow, lp);
1611    }
1612
1613    void setNotificationIconVisibility(boolean visible, int anim) {
1614        int old = mNotificationIcons.getVisibility();
1615        int v = visible ? View.VISIBLE : View.INVISIBLE;
1616        if (old != v) {
1617            mNotificationIcons.setVisibility(v);
1618            mNotificationIcons.startAnimation(loadAnim(anim, null));
1619        }
1620    }
1621
1622    void updateExpandedInvisiblePosition() {
1623        mTrackingPosition = -mDisplayMetrics.heightPixels;
1624    }
1625
1626    static final float saturate(float a) {
1627        return a < 0f ? 0f : (a > 1f ? 1f : a);
1628    }
1629
1630    @Override
1631    protected int getExpandedViewMaxHeight() {
1632        return mDisplayMetrics.heightPixels - mNotificationPanelMarginBottomPx;
1633    }
1634
1635    @Override
1636    public void updateExpandedViewPos(int thingy) {
1637        // TODO
1638        if (DEBUG) Slog.v(TAG, "updateExpandedViewPos");
1639        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mNotificationPanel.getLayoutParams();
1640        lp.gravity = mNotificationPanelGravity;
1641        lp.leftMargin = mNotificationPanelMarginPx;
1642        mNotificationPanel.setLayoutParams(lp);
1643        lp = (FrameLayout.LayoutParams) mSettingsPanel.getLayoutParams();
1644        lp.gravity = mSettingsPanelGravity;
1645        lp.rightMargin = mNotificationPanelMarginPx;
1646        mSettingsPanel.setLayoutParams(lp);
1647    }
1648
1649    // called by makeStatusbar and also by PhoneStatusBarView
1650    void updateDisplaySize() {
1651        mDisplay.getMetrics(mDisplayMetrics);
1652        mGestureRec.tag("display",
1653                String.format("%dx%d", mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels));
1654    }
1655
1656    void performDisableActions(int net) {
1657        int old = mDisabled;
1658        int diff = net ^ old;
1659        mDisabled = net;
1660
1661        // act accordingly
1662        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
1663            if ((net & StatusBarManager.DISABLE_EXPAND) != 0) {
1664                Slog.d(TAG, "DISABLE_EXPAND: yes");
1665                animateCollapse();
1666            }
1667        }
1668        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1669            if ((net & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1670                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: yes");
1671                if (mTicking) {
1672                    mNotificationIcons.setVisibility(View.INVISIBLE);
1673                    mTicker.halt();
1674                } else {
1675                    setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
1676                }
1677            } else {
1678                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: no");
1679                if (!mExpandedVisible) {
1680                    setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
1681                }
1682            }
1683        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1684            if (mTicking && (net & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1685                mTicker.halt();
1686            }
1687        }
1688    }
1689
1690    private View.OnClickListener mClearButtonListener = new View.OnClickListener() {
1691        public void onClick(View v) {
1692            synchronized (mNotificationData) {
1693                // animate-swipe all dismissable notifications, then animate the shade closed
1694                int numChildren = mPile.getChildCount();
1695
1696                int scrollTop = mScrollView.getScrollY();
1697                int scrollBottom = scrollTop + mScrollView.getHeight();
1698                final ArrayList<View> snapshot = new ArrayList<View>(numChildren);
1699                for (int i=0; i<numChildren; i++) {
1700                    final View child = mPile.getChildAt(i);
1701                    if (mPile.canChildBeDismissed(child) && child.getBottom() > scrollTop &&
1702                            child.getTop() < scrollBottom) {
1703                        snapshot.add(child);
1704                    }
1705                }
1706                if (snapshot.isEmpty()) {
1707                    animateCollapse(CommandQueue.FLAG_EXCLUDE_NONE);
1708                    return;
1709                }
1710                new Thread(new Runnable() {
1711                    @Override
1712                    public void run() {
1713                        // Decrease the delay for every row we animate to give the sense of
1714                        // accelerating the swipes
1715                        final int ROW_DELAY_DECREMENT = 10;
1716                        int currentDelay = 140;
1717                        int totalDelay = 0;
1718
1719                        // Set the shade-animating state to avoid doing other work during
1720                        // all of these animations. In particular, avoid layout and
1721                        // redrawing when collapsing the shade.
1722                        mPile.setViewRemoval(false);
1723
1724                        mPostCollapseCleanup = new Runnable() {
1725                            @Override
1726                            public void run() {
1727                                if (DEBUG) {
1728                                    Slog.v(TAG, "running post-collapse cleanup");
1729                                }
1730                                try {
1731                                    mPile.setViewRemoval(true);
1732                                    mBarService.onClearAllNotifications();
1733                                } catch (Exception ex) { }
1734                            }
1735                        };
1736
1737                        View sampleView = snapshot.get(0);
1738                        int width = sampleView.getWidth();
1739                        final int velocity = width * 8; // 1000/8 = 125 ms duration
1740                        for (final View _v : snapshot) {
1741                            mHandler.postDelayed(new Runnable() {
1742                                @Override
1743                                public void run() {
1744                                    mPile.dismissRowAnimated(_v, velocity);
1745                                }
1746                            }, totalDelay);
1747                            currentDelay = Math.max(50, currentDelay - ROW_DELAY_DECREMENT);
1748                            totalDelay += currentDelay;
1749                        }
1750                        // Delay the collapse animation until after all swipe animations have
1751                        // finished. Provide some buffer because there may be some extra delay
1752                        // before actually starting each swipe animation. Ideally, we'd
1753                        // synchronize the end of those animations with the start of the collaps
1754                        // exactly.
1755                        mHandler.postDelayed(new Runnable() {
1756                            @Override
1757                            public void run() {
1758                                animateCollapse(CommandQueue.FLAG_EXCLUDE_NONE);
1759                            }
1760                        }, totalDelay + 225);
1761                    }
1762                }).start();
1763            }
1764        }
1765    };
1766
1767    private View.OnClickListener mSettingsButtonListener = new View.OnClickListener() {
1768        public void onClick(View v) {
1769            // We take this as a good indicator that Setup is running and we shouldn't
1770            // allow you to go somewhere else
1771            if (!isDeviceProvisioned()) return;
1772            try {
1773                // Dismiss the lock screen when Settings starts.
1774                ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
1775            } catch (RemoteException e) {
1776            }
1777            v.getContext().startActivityAsUser(new Intent(Settings.ACTION_SETTINGS)
1778                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
1779                    new UserHandle(UserHandle.USER_CURRENT));
1780            animateCollapse();
1781        }
1782    };
1783
1784    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1785        public void onReceive(Context context, Intent intent) {
1786            Slog.v(TAG, "onReceive: " + intent);
1787            String action = intent.getAction();
1788            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
1789                int flags = CommandQueue.FLAG_EXCLUDE_NONE;
1790                if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
1791                    String reason = intent.getStringExtra("reason");
1792                    if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
1793                        flags |= CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL;
1794                    }
1795                }
1796                animateCollapse(flags);
1797            }
1798            else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
1799                // no waiting!
1800                makeExpandedInvisible();
1801            }
1802            else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1803                if (DEBUG) {
1804                    Slog.v(TAG, "configuration changed: " + mContext.getResources().getConfiguration());
1805                }
1806                updateResources();
1807                repositionNavigationBar();
1808                updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1809                updateShowSearchHoldoff();
1810            }
1811            else if (Intent.ACTION_SCREEN_ON.equals(action)) {
1812                // work around problem where mDisplay.getRotation() is not stable while screen is off (bug 7086018)
1813                repositionNavigationBar();
1814            }
1815        }
1816    };
1817
1818    @Override
1819    public void userSwitched(int newUserId) {
1820        if (MULTIUSER_DEBUG) mNotificationPanelDebugText.setText("USER " + newUserId);
1821        animateCollapse();
1822        updateNotificationIcons();
1823    }
1824
1825    private void setIntruderAlertVisibility(boolean vis) {
1826        if (!ENABLE_INTRUDERS) return;
1827        if (DEBUG) {
1828            Slog.v(TAG, (vis ? "showing" : "hiding") + " intruder alert window");
1829        }
1830        mIntruderAlertView.setVisibility(vis ? View.VISIBLE : View.GONE);
1831    }
1832
1833    public void dismissIntruder() {
1834        if (mCurrentlyIntrudingNotification == null) return;
1835
1836        try {
1837            mBarService.onNotificationClear(
1838                    mCurrentlyIntrudingNotification.pkg,
1839                    mCurrentlyIntrudingNotification.tag,
1840                    mCurrentlyIntrudingNotification.id);
1841        } catch (android.os.RemoteException ex) {
1842            // oh well
1843        }
1844    }
1845
1846    /**
1847     * Reload some of our resources when the configuration changes.
1848     *
1849     * We don't reload everything when the configuration changes -- we probably
1850     * should, but getting that smooth is tough.  Someday we'll fix that.  In the
1851     * meantime, just update the things that we know change.
1852     */
1853    void updateResources() {
1854        final Context context = mContext;
1855        final Resources res = context.getResources();
1856
1857        if (mClearButton instanceof TextView) {
1858            ((TextView)mClearButton).setText(context.getText(R.string.status_bar_clear_all_button));
1859        }
1860        loadDimens();
1861    }
1862
1863    protected void loadDimens() {
1864        final Resources res = mContext.getResources();
1865
1866        mNaturalBarHeight = res.getDimensionPixelSize(
1867                com.android.internal.R.dimen.status_bar_height);
1868
1869        int newIconSize = res.getDimensionPixelSize(
1870            com.android.internal.R.dimen.status_bar_icon_size);
1871        int newIconHPadding = res.getDimensionPixelSize(
1872            R.dimen.status_bar_icon_padding);
1873
1874        if (newIconHPadding != mIconHPadding || newIconSize != mIconSize) {
1875//            Slog.d(TAG, "size=" + newIconSize + " padding=" + newIconHPadding);
1876            mIconHPadding = newIconHPadding;
1877            mIconSize = newIconSize;
1878            //reloadAllNotificationIcons(); // reload the tray
1879        }
1880
1881        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
1882
1883        mSelfExpandVelocityPx = res.getDimension(R.dimen.self_expand_velocity);
1884        mSelfCollapseVelocityPx = res.getDimension(R.dimen.self_collapse_velocity);
1885        mFlingExpandMinVelocityPx = res.getDimension(R.dimen.fling_expand_min_velocity);
1886        mFlingCollapseMinVelocityPx = res.getDimension(R.dimen.fling_collapse_min_velocity);
1887
1888        mCollapseMinDisplayFraction = res.getFraction(R.dimen.collapse_min_display_fraction, 1, 1);
1889        mExpandMinDisplayFraction = res.getFraction(R.dimen.expand_min_display_fraction, 1, 1);
1890
1891        mExpandAccelPx = res.getDimension(R.dimen.expand_accel);
1892        mCollapseAccelPx = res.getDimension(R.dimen.collapse_accel);
1893
1894        mFlingGestureMaxXVelocityPx = res.getDimension(R.dimen.fling_gesture_max_x_velocity);
1895
1896        mFlingGestureMaxOutputVelocityPx = res.getDimension(R.dimen.fling_gesture_max_output_velocity);
1897
1898        mNotificationPanelMarginBottomPx
1899            = (int) res.getDimension(R.dimen.notification_panel_margin_bottom);
1900        mNotificationPanelMarginPx
1901            = (int) res.getDimension(R.dimen.notification_panel_margin_left);
1902        mNotificationPanelGravity = res.getInteger(R.integer.notification_panel_layout_gravity);
1903        if (mNotificationPanelGravity <= 0) {
1904            mNotificationPanelGravity = Gravity.LEFT | Gravity.TOP;
1905        }
1906        mSettingsPanelGravity = res.getInteger(R.integer.settings_panel_layout_gravity);
1907        if (mSettingsPanelGravity <= 0) {
1908            mSettingsPanelGravity = Gravity.RIGHT | Gravity.TOP;
1909        }
1910        getNinePatchPadding(res.getDrawable(R.drawable.notification_panel_bg), mNotificationPanelBackgroundPadding);
1911        final int notificationPanelDecorationHeight =
1912              res.getDimensionPixelSize(R.dimen.notification_panel_padding_top)
1913            + res.getDimensionPixelSize(R.dimen.notification_panel_header_height)
1914            + mNotificationPanelBackgroundPadding.top
1915            + mNotificationPanelBackgroundPadding.bottom;
1916        mNotificationPanelMinHeight =
1917              notificationPanelDecorationHeight
1918            + res.getDimensionPixelSize(R.dimen.close_handle_underlap);
1919
1920        mCarrierLabelHeight = res.getDimensionPixelSize(R.dimen.carrier_label_height);
1921
1922        if (false) Slog.v(TAG, "updateResources");
1923    }
1924
1925    private static void getNinePatchPadding(Drawable d, Rect outPadding) {
1926        if (d instanceof NinePatchDrawable) {
1927            NinePatchDrawable ninePatch = (NinePatchDrawable) d;
1928            ninePatch.getPadding(outPadding);
1929        }
1930    }
1931
1932    //
1933    // tracing
1934    //
1935
1936    void postStartTracing() {
1937        mHandler.postDelayed(mStartTracing, 3000);
1938    }
1939
1940    void vibrate() {
1941        android.os.Vibrator vib = (android.os.Vibrator)mContext.getSystemService(
1942                Context.VIBRATOR_SERVICE);
1943        vib.vibrate(250);
1944    }
1945
1946    Runnable mStartTracing = new Runnable() {
1947        public void run() {
1948            vibrate();
1949            SystemClock.sleep(250);
1950            Slog.d(TAG, "startTracing");
1951            android.os.Debug.startMethodTracing("/data/statusbar-traces/trace");
1952            mHandler.postDelayed(mStopTracing, 10000);
1953        }
1954    };
1955
1956    Runnable mStopTracing = new Runnable() {
1957        public void run() {
1958            android.os.Debug.stopMethodTracing();
1959            Slog.d(TAG, "stopTracing");
1960            vibrate();
1961        }
1962    };
1963
1964    @Override
1965    protected void haltTicker() {
1966        mTicker.halt();
1967    }
1968
1969    @Override
1970    protected boolean shouldDisableNavbarGestures() {
1971        return mExpandedVisible || (mDisabled & StatusBarManager.DISABLE_HOME) != 0;
1972    }
1973
1974    private static class FastColorDrawable extends Drawable {
1975        private final int mColor;
1976
1977        public FastColorDrawable(int color) {
1978            mColor = 0xff000000 | color;
1979        }
1980
1981        @Override
1982        public void draw(Canvas canvas) {
1983            canvas.drawColor(mColor, PorterDuff.Mode.SRC);
1984        }
1985
1986        @Override
1987        public void setAlpha(int alpha) {
1988        }
1989
1990        @Override
1991        public void setColorFilter(ColorFilter cf) {
1992        }
1993
1994        @Override
1995        public int getOpacity() {
1996            return PixelFormat.OPAQUE;
1997        }
1998
1999        @Override
2000        public void setBounds(int left, int top, int right, int bottom) {
2001        }
2002
2003        @Override
2004        public void setBounds(Rect bounds) {
2005        }
2006    }
2007}
2008