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