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