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