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