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