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