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