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