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