PhoneStatusBar.java revision 6f983a7906ce98a1a8e3f5e805da8c933f53fc3d
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 (disableNavigation && disableBack) {
1129            mNavigationBarView.setEnabled(false);
1130        } else {
1131            mNavigationBarView.getBackButton().setEnabled(!disableBack);
1132            mNavigationBarView.getHomeButton().setEnabled(!disableNavigation);
1133            mNavigationBarView.getRecentsButton().setEnabled(!disableNavigation);
1134
1135            if (disableNavigation) {
1136                // close recents if it's visible
1137                mHandler.removeMessages(MSG_CLOSE_RECENTS_PANEL);
1138                mHandler.sendEmptyMessage(MSG_CLOSE_RECENTS_PANEL);
1139            }
1140
1141            mNavigationBarView.setEnabled(true);
1142        }
1143    }
1144
1145    /**
1146     * All changes to the status bar and notifications funnel through here and are batched.
1147     */
1148    private class H extends Handler {
1149        public void handleMessage(Message m) {
1150            switch (m.what) {
1151                case MSG_ANIMATE:
1152                    doAnimation();
1153                    break;
1154                case MSG_ANIMATE_REVEAL:
1155                    doRevealAnimation();
1156                    break;
1157                case MSG_SHOW_INTRUDER:
1158                    setIntruderAlertVisibility(true);
1159                    break;
1160                case MSG_HIDE_INTRUDER:
1161                    setIntruderAlertVisibility(false);
1162                    break;
1163                case MSG_OPEN_RECENTS_PANEL:
1164                    if (DEBUG) Slog.d(TAG, "opening recents panel");
1165                    if (mRecentsPanel != null) {
1166                        disable(StatusBarManager.DISABLE_BACK);
1167                        mRecentsPanel.setVisibility(View.VISIBLE);
1168                        mRecentsPanel.show(true, true);
1169                    }
1170                    break;
1171                case MSG_CLOSE_RECENTS_PANEL:
1172                    if (DEBUG) Slog.d(TAG, "closing recents panel");
1173                    if (mRecentsPanel != null && mRecentsPanel.isShowing()) {
1174                        disable(StatusBarManager.DISABLE_NONE);
1175                        mRecentsPanel.show(false, true);
1176                    }
1177                    break;
1178            }
1179        }
1180    }
1181
1182    View.OnFocusChangeListener mFocusChangeListener = new View.OnFocusChangeListener() {
1183        public void onFocusChange(View v, boolean hasFocus) {
1184            // Because 'v' is a ViewGroup, all its children will be (un)selected
1185            // too, which allows marqueeing to work.
1186            v.setSelected(hasFocus);
1187        }
1188    };
1189
1190    private void makeExpandedVisible() {
1191        if (SPEW) Slog.d(TAG, "Make expanded visible: expanded visible=" + mExpandedVisible);
1192        if (mExpandedVisible) {
1193            return;
1194        }
1195        mExpandedVisible = true;
1196        visibilityChanged(true);
1197
1198        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1199        mExpandedParams.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1200        mExpandedParams.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
1201        if (DEBUG) {
1202            Slog.d(TAG, "makeExpandedVisible: expanded params = " + mExpandedParams);
1203        }
1204        mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1205        mExpandedView.requestFocus(View.FOCUS_FORWARD);
1206        mTrackingView.setVisibility(View.VISIBLE);
1207    }
1208
1209    public void animateExpand() {
1210        if (SPEW) Slog.d(TAG, "Animate expand: expanded=" + mExpanded);
1211        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1212            return ;
1213        }
1214        if (mExpanded) {
1215            return;
1216        }
1217
1218        prepareTracking(0, true);
1219        performFling(0, mSelfExpandVelocityPx, true);
1220    }
1221
1222    public void animateCollapse() {
1223        animateCollapse(false);
1224    }
1225
1226    public void animateCollapse(boolean excludeRecents) {
1227        if (SPEW) {
1228            Slog.d(TAG, "animateCollapse(): mExpanded=" + mExpanded
1229                    + " mExpandedVisible=" + mExpandedVisible
1230                    + " mExpanded=" + mExpanded
1231                    + " mAnimating=" + mAnimating
1232                    + " mAnimY=" + mAnimY
1233                    + " mAnimVel=" + mAnimVel);
1234        }
1235
1236        if (!excludeRecents) {
1237            mHandler.removeMessages(MSG_CLOSE_RECENTS_PANEL);
1238            mHandler.sendEmptyMessage(MSG_CLOSE_RECENTS_PANEL);
1239        }
1240
1241        if (!mExpandedVisible) {
1242            return;
1243        }
1244
1245        int y;
1246        if (mAnimating) {
1247            y = (int)mAnimY;
1248        } else {
1249            y = mDisplayMetrics.heightPixels-1;
1250        }
1251        // Let the fling think that we're open so it goes in the right direction
1252        // and doesn't try to re-open the windowshade.
1253        mExpanded = true;
1254        prepareTracking(y, false);
1255        performFling(y, -mSelfCollapseVelocityPx, true);
1256    }
1257
1258    void performExpand() {
1259        if (SPEW) Slog.d(TAG, "performExpand: mExpanded=" + mExpanded);
1260        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1261            return ;
1262        }
1263        if (mExpanded) {
1264            return;
1265        }
1266
1267        mExpanded = true;
1268        makeExpandedVisible();
1269        updateExpandedViewPos(EXPANDED_FULL_OPEN);
1270
1271        if (false) postStartTracing();
1272    }
1273
1274    void performCollapse() {
1275        if (SPEW) Slog.d(TAG, "performCollapse: mExpanded=" + mExpanded
1276                + " mExpandedVisible=" + mExpandedVisible);
1277
1278        if (!mExpandedVisible) {
1279            return;
1280        }
1281        mExpandedVisible = false;
1282        visibilityChanged(false);
1283        mExpandedParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1284        mExpandedParams.flags &= ~WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
1285        mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1286        mTrackingView.setVisibility(View.GONE);
1287
1288        if ((mDisabled & StatusBarManager.DISABLE_NOTIFICATION_ICONS) == 0) {
1289            setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
1290        }
1291
1292        if (!mExpanded) {
1293            return;
1294        }
1295        mExpanded = false;
1296    }
1297
1298    void doAnimation() {
1299        if (mAnimating) {
1300            if (SPEW) Slog.d(TAG, "doAnimation");
1301            if (SPEW) Slog.d(TAG, "doAnimation before mAnimY=" + mAnimY);
1302            incrementAnim();
1303            if (SPEW) Slog.d(TAG, "doAnimation after  mAnimY=" + mAnimY);
1304            if (mAnimY >= mDisplayMetrics.heightPixels-1) {
1305                if (SPEW) Slog.d(TAG, "Animation completed to expanded state.");
1306                mAnimating = false;
1307                updateExpandedViewPos(EXPANDED_FULL_OPEN);
1308                performExpand();
1309            }
1310            else if (mAnimY < mStatusBarView.getHeight()) {
1311                if (SPEW) Slog.d(TAG, "Animation completed to collapsed state.");
1312                mAnimating = false;
1313                updateExpandedViewPos(0);
1314                performCollapse();
1315            }
1316            else {
1317                updateExpandedViewPos((int)mAnimY);
1318                mCurAnimationTime += ANIM_FRAME_DURATION;
1319                mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), mCurAnimationTime);
1320            }
1321        }
1322    }
1323
1324    void stopTracking() {
1325        mTracking = false;
1326        mVelocityTracker.recycle();
1327        mVelocityTracker = null;
1328    }
1329
1330    void incrementAnim() {
1331        long now = SystemClock.uptimeMillis();
1332        float t = ((float)(now - mAnimLastTime)) / 1000;            // ms -> s
1333        final float y = mAnimY;
1334        final float v = mAnimVel;                                   // px/s
1335        final float a = mAnimAccel;                                 // px/s/s
1336        mAnimY = y + (v*t) + (0.5f*a*t*t);                          // px
1337        mAnimVel = v + (a*t);                                       // px/s
1338        mAnimLastTime = now;                                        // ms
1339        //Slog.d(TAG, "y=" + y + " v=" + v + " a=" + a + " t=" + t + " mAnimY=" + mAnimY
1340        //        + " mAnimAccel=" + mAnimAccel);
1341    }
1342
1343    void doRevealAnimation() {
1344        final int h = mCloseView.getHeight() + mStatusBarView.getHeight();
1345        if (mAnimatingReveal && mAnimating && mAnimY < h) {
1346            incrementAnim();
1347            if (mAnimY >= h) {
1348                mAnimY = h;
1349                updateExpandedViewPos((int)mAnimY);
1350            } else {
1351                updateExpandedViewPos((int)mAnimY);
1352                mCurAnimationTime += ANIM_FRAME_DURATION;
1353                mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE_REVEAL),
1354                        mCurAnimationTime);
1355            }
1356        }
1357    }
1358
1359    void prepareTracking(int y, boolean opening) {
1360        if (CHATTY) {
1361            Slog.d(TAG, "panel: beginning to track the user's touch, y=" + y + " opening=" + opening);
1362        }
1363
1364        // there are some race conditions that cause this to be inaccurate; let's recalculate it any
1365        // time we're about to drag the panel
1366        updateExpandedSize();
1367
1368        mTracking = true;
1369        mVelocityTracker = VelocityTracker.obtain();
1370        if (opening) {
1371            mAnimAccel = mExpandAccelPx;
1372            mAnimVel = mFlingExpandMinVelocityPx;
1373            mAnimY = mStatusBarView.getHeight();
1374            updateExpandedViewPos((int)mAnimY);
1375            mAnimating = true;
1376            mAnimatingReveal = true;
1377            mHandler.removeMessages(MSG_ANIMATE);
1378            mHandler.removeMessages(MSG_ANIMATE_REVEAL);
1379            long now = SystemClock.uptimeMillis();
1380            mAnimLastTime = now;
1381            mCurAnimationTime = now + ANIM_FRAME_DURATION;
1382            mAnimating = true;
1383            mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE_REVEAL),
1384                    mCurAnimationTime);
1385            makeExpandedVisible();
1386        } else {
1387            // it's open, close it?
1388            if (mAnimating) {
1389                mAnimating = false;
1390                mHandler.removeMessages(MSG_ANIMATE);
1391            }
1392            updateExpandedViewPos(y + mViewDelta);
1393        }
1394    }
1395
1396    void performFling(int y, float vel, boolean always) {
1397        if (CHATTY) {
1398            Slog.d(TAG, "panel: will fling, y=" + y + " vel=" + vel);
1399        }
1400
1401        mAnimatingReveal = false;
1402
1403        mAnimY = y;
1404        mAnimVel = vel;
1405
1406        //Slog.d(TAG, "starting with mAnimY=" + mAnimY + " mAnimVel=" + mAnimVel);
1407
1408        if (mExpanded) {
1409            if (!always && (
1410                    vel > mFlingCollapseMinVelocityPx
1411                    || (y > (mDisplayMetrics.heightPixels*(1f-mCollapseMinDisplayFraction)) &&
1412                        vel > -mFlingExpandMinVelocityPx))) {
1413                // We are expanded, but they didn't move sufficiently to cause
1414                // us to retract.  Animate back to the expanded position.
1415                mAnimAccel = mExpandAccelPx;
1416                if (vel < 0) {
1417                    mAnimVel = 0;
1418                }
1419            }
1420            else {
1421                // We are expanded and are now going to animate away.
1422                mAnimAccel = -mCollapseAccelPx;
1423                if (vel > 0) {
1424                    mAnimVel = 0;
1425                }
1426            }
1427        } else {
1428            if (always || (
1429                    vel > mFlingExpandMinVelocityPx
1430                    || (y > (mDisplayMetrics.heightPixels*(1f-mExpandMinDisplayFraction)) &&
1431                        vel > -mFlingCollapseMinVelocityPx))) {
1432                // We are collapsed, and they moved enough to allow us to
1433                // expand.  Animate in the notifications.
1434                mAnimAccel = mExpandAccelPx;
1435                if (vel < 0) {
1436                    mAnimVel = 0;
1437                }
1438            }
1439            else {
1440                // We are collapsed, but they didn't move sufficiently to cause
1441                // us to retract.  Animate back to the collapsed position.
1442                mAnimAccel = -mCollapseAccelPx;
1443                if (vel > 0) {
1444                    mAnimVel = 0;
1445                }
1446            }
1447        }
1448        //Slog.d(TAG, "mAnimY=" + mAnimY + " mAnimVel=" + mAnimVel
1449        //        + " mAnimAccel=" + mAnimAccel);
1450
1451        long now = SystemClock.uptimeMillis();
1452        mAnimLastTime = now;
1453        mCurAnimationTime = now + ANIM_FRAME_DURATION;
1454        mAnimating = true;
1455        mHandler.removeMessages(MSG_ANIMATE);
1456        mHandler.removeMessages(MSG_ANIMATE_REVEAL);
1457        mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), mCurAnimationTime);
1458        stopTracking();
1459    }
1460
1461    boolean interceptTouchEvent(MotionEvent event) {
1462        if (SPEW) {
1463            Slog.d(TAG, "Touch: rawY=" + event.getRawY() + " event=" + event + " mDisabled="
1464                + mDisabled);
1465        } else if (CHATTY) {
1466            if (event.getAction() == MotionEvent.ACTION_DOWN) {
1467                Slog.d(TAG, String.format(
1468                            "panel: ACTION_DOWN at (%f, %f) mDisabled=0x%08x",
1469                            event.getRawX(), event.getRawY(), mDisabled));
1470            }
1471        }
1472
1473        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1474            return false;
1475        }
1476
1477        final int statusBarSize = mStatusBarView.getHeight();
1478        final int hitSize = statusBarSize*2;
1479        if (event.getAction() == MotionEvent.ACTION_DOWN) {
1480            final int y = (int)event.getRawY();
1481
1482            if (!mExpanded) {
1483                mViewDelta = statusBarSize - y;
1484            } else {
1485                mTrackingView.getLocationOnScreen(mAbsPos);
1486                mViewDelta = mAbsPos[1] + mTrackingView.getHeight() - y;
1487            }
1488            if ((!mExpanded && y < hitSize) ||
1489                    (mExpanded && y > (mDisplayMetrics.heightPixels-hitSize))) {
1490
1491                // We drop events at the edge of the screen to make the windowshade come
1492                // down by accident less, especially when pushing open a device with a keyboard
1493                // that rotates (like g1 and droid)
1494                int x = (int)event.getRawX();
1495                final int edgeBorder = mEdgeBorder;
1496                if (x >= edgeBorder && x < mDisplayMetrics.widthPixels - edgeBorder) {
1497                    prepareTracking(y, !mExpanded);// opening if we're not already fully visible
1498                    mVelocityTracker.addMovement(event);
1499                }
1500            }
1501        } else if (mTracking) {
1502            mVelocityTracker.addMovement(event);
1503            final int minY = statusBarSize + mCloseView.getHeight();
1504            if (event.getAction() == MotionEvent.ACTION_MOVE) {
1505                int y = (int)event.getRawY();
1506                if (mAnimatingReveal && y < minY) {
1507                    // nothing
1508                } else  {
1509                    mAnimatingReveal = false;
1510                    updateExpandedViewPos(y + mViewDelta);
1511                }
1512            } else if (event.getAction() == MotionEvent.ACTION_UP) {
1513                mVelocityTracker.computeCurrentVelocity(1000);
1514
1515                float yVel = mVelocityTracker.getYVelocity();
1516                boolean negative = yVel < 0;
1517
1518                float xVel = mVelocityTracker.getXVelocity();
1519                if (xVel < 0) {
1520                    xVel = -xVel;
1521                }
1522                if (xVel > mFlingGestureMaxXVelocityPx) {
1523                    xVel = mFlingGestureMaxXVelocityPx; // limit how much we care about the x axis
1524                }
1525
1526                float vel = (float)Math.hypot(yVel, xVel);
1527                if (negative) {
1528                    vel = -vel;
1529                }
1530
1531                if (CHATTY) {
1532                    Slog.d(TAG, String.format("gesture: vraw=(%f,%f) vnorm=(%f,%f) vlinear=%f",
1533                        mVelocityTracker.getXVelocity(),
1534                        mVelocityTracker.getYVelocity(),
1535                        xVel, yVel,
1536                        vel));
1537                }
1538
1539                performFling((int)event.getRawY(), vel, false);
1540            }
1541
1542        }
1543        return false;
1544    }
1545
1546    @Override // CommandQueue
1547    public void setSystemUiVisibility(int vis) {
1548        final int old = mSystemUiVisibility;
1549        final int diff = vis ^ old;
1550
1551        if (diff != 0) {
1552            mSystemUiVisibility = vis;
1553
1554            if (0 != (diff & View.SYSTEM_UI_FLAG_LOW_PROFILE)) {
1555                final boolean lightsOut = (0 != (vis & View.SYSTEM_UI_FLAG_LOW_PROFILE));
1556                if (lightsOut) {
1557                    animateCollapse();
1558                }
1559                if (mNavigationBarView != null) {
1560                    mNavigationBarView.setLowProfile(lightsOut);
1561                }
1562            }
1563
1564            notifyUiVisibilityChanged();
1565        }
1566    }
1567
1568    public void setLightsOn(boolean on) {
1569        Log.v(TAG, "setLightsOn(" + on + ")");
1570        if (on) {
1571            setSystemUiVisibility(mSystemUiVisibility & ~View.SYSTEM_UI_FLAG_LOW_PROFILE);
1572        } else {
1573            setSystemUiVisibility(mSystemUiVisibility | View.SYSTEM_UI_FLAG_LOW_PROFILE);
1574        }
1575    }
1576
1577    private void notifyUiVisibilityChanged() {
1578        try {
1579            mWindowManager.statusBarVisibilityChanged(mSystemUiVisibility);
1580        } catch (RemoteException ex) {
1581        }
1582    }
1583
1584    public void topAppWindowChanged(boolean showMenu) {
1585        if (DEBUG) {
1586            Slog.d(TAG, (showMenu?"showing":"hiding") + " the MENU button");
1587        }
1588        if (mNavigationBarView != null) {
1589            mNavigationBarView.getMenuButton().setVisibility(showMenu
1590                ? View.VISIBLE : View.INVISIBLE);
1591        }
1592
1593        // See above re: lights-out policy for legacy apps.
1594        if (showMenu) setLightsOn(true);
1595    }
1596
1597    // Not supported
1598    public void setImeWindowStatus(IBinder token, int vis, int backDisposition) { }
1599    @Override
1600    public void setHardKeyboardStatus(boolean available, boolean enabled) { }
1601
1602    public NotificationClicker makeClicker(PendingIntent intent, String pkg, String tag, int id) {
1603        return new NotificationClicker(intent, pkg, tag, id);
1604    }
1605
1606    private class NotificationClicker implements View.OnClickListener {
1607        private PendingIntent mIntent;
1608        private String mPkg;
1609        private String mTag;
1610        private int mId;
1611
1612        NotificationClicker(PendingIntent intent, String pkg, String tag, int id) {
1613            mIntent = intent;
1614            mPkg = pkg;
1615            mTag = tag;
1616            mId = id;
1617        }
1618
1619        public void onClick(View v) {
1620            try {
1621                // The intent we are sending is for the application, which
1622                // won't have permission to immediately start an activity after
1623                // the user switches to home.  We know it is safe to do at this
1624                // point, so make sure new activity switches are now allowed.
1625                ActivityManagerNative.getDefault().resumeAppSwitches();
1626            } catch (RemoteException e) {
1627            }
1628
1629            if (mIntent != null) {
1630                int[] pos = new int[2];
1631                v.getLocationOnScreen(pos);
1632                Intent overlay = new Intent();
1633                overlay.setSourceBounds(
1634                        new Rect(pos[0], pos[1], pos[0]+v.getWidth(), pos[1]+v.getHeight()));
1635                try {
1636                    mIntent.send(mContext, 0, overlay);
1637                } catch (PendingIntent.CanceledException e) {
1638                    // the stack trace isn't very helpful here.  Just log the exception message.
1639                    Slog.w(TAG, "Sending contentIntent failed: " + e);
1640                }
1641            }
1642
1643            try {
1644                mBarService.onNotificationClick(mPkg, mTag, mId);
1645            } catch (RemoteException ex) {
1646                // system process is dead if we're here.
1647            }
1648
1649            // close the shade if it was open
1650            animateCollapse();
1651
1652            // If this click was on the intruder alert, hide that instead
1653            mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
1654        }
1655    }
1656
1657    private void tick(StatusBarNotification n) {
1658        // Show the ticker if one is requested. Also don't do this
1659        // until status bar window is attached to the window manager,
1660        // because...  well, what's the point otherwise?  And trying to
1661        // run a ticker without being attached will crash!
1662        if (n.notification.tickerText != null && mStatusBarView.getWindowToken() != null) {
1663            if (0 == (mDisabled & (StatusBarManager.DISABLE_NOTIFICATION_ICONS
1664                            | StatusBarManager.DISABLE_NOTIFICATION_TICKER))) {
1665                mTicker.addEntry(n);
1666            }
1667        }
1668    }
1669
1670    /**
1671     * Cancel this notification and tell the StatusBarManagerService / NotificationManagerService
1672     * about the failure.
1673     *
1674     * WARNING: this will call back into us.  Don't hold any locks.
1675     */
1676    void handleNotificationError(IBinder key, StatusBarNotification n, String message) {
1677        removeNotification(key);
1678        try {
1679            mBarService.onNotificationError(n.pkg, n.tag, n.id, n.uid, n.initialPid, message);
1680        } catch (RemoteException ex) {
1681            // The end is nigh.
1682        }
1683    }
1684
1685    private class MyTicker extends Ticker {
1686        MyTicker(Context context, View sb) {
1687            super(context, sb);
1688        }
1689
1690        @Override
1691        public void tickerStarting() {
1692            mTicking = true;
1693            mIcons.setVisibility(View.GONE);
1694            mTickerView.setVisibility(View.VISIBLE);
1695            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_up_in, null));
1696            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_up_out, null));
1697        }
1698
1699        @Override
1700        public void tickerDone() {
1701            mIcons.setVisibility(View.VISIBLE);
1702            mTickerView.setVisibility(View.GONE);
1703            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_down_in, null));
1704            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_down_out,
1705                        mTickingDoneListener));
1706        }
1707
1708        public void tickerHalting() {
1709            mIcons.setVisibility(View.VISIBLE);
1710            mTickerView.setVisibility(View.GONE);
1711            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
1712            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.fade_out,
1713                        mTickingDoneListener));
1714        }
1715    }
1716
1717    Animation.AnimationListener mTickingDoneListener = new Animation.AnimationListener() {;
1718        public void onAnimationEnd(Animation animation) {
1719            mTicking = false;
1720        }
1721        public void onAnimationRepeat(Animation animation) {
1722        }
1723        public void onAnimationStart(Animation animation) {
1724        }
1725    };
1726
1727    private Animation loadAnim(int id, Animation.AnimationListener listener) {
1728        Animation anim = AnimationUtils.loadAnimation(mContext, id);
1729        if (listener != null) {
1730            anim.setAnimationListener(listener);
1731        }
1732        return anim;
1733    }
1734
1735    public String viewInfo(View v) {
1736        return "(" + v.getLeft() + "," + v.getTop() + ")(" + v.getRight() + "," + v.getBottom()
1737                + " " + v.getWidth() + "x" + v.getHeight() + ")";
1738    }
1739
1740    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1741        synchronized (mQueueLock) {
1742            pw.println("Current Status Bar state:");
1743            pw.println("  mExpanded=" + mExpanded
1744                    + ", mExpandedVisible=" + mExpandedVisible);
1745            pw.println("  mTicking=" + mTicking);
1746            pw.println("  mTracking=" + mTracking);
1747            pw.println("  mAnimating=" + mAnimating
1748                    + ", mAnimY=" + mAnimY + ", mAnimVel=" + mAnimVel
1749                    + ", mAnimAccel=" + mAnimAccel);
1750            pw.println("  mCurAnimationTime=" + mCurAnimationTime
1751                    + " mAnimLastTime=" + mAnimLastTime);
1752            pw.println("  mAnimatingReveal=" + mAnimatingReveal
1753                    + " mViewDelta=" + mViewDelta);
1754            pw.println("  mDisplayMetrics=" + mDisplayMetrics);
1755            pw.println("  mExpandedParams: " + mExpandedParams);
1756            pw.println("  mExpandedView: " + viewInfo(mExpandedView));
1757            pw.println("  mExpandedDialog: " + mExpandedDialog);
1758            pw.println("  mTrackingParams: " + mTrackingParams);
1759            pw.println("  mTrackingView: " + viewInfo(mTrackingView));
1760            pw.println("  mPile: " + viewInfo(mPile));
1761            pw.println("  mNoNotificationsTitle: " + viewInfo(mNoNotificationsTitle));
1762            pw.println("  mCloseView: " + viewInfo(mCloseView));
1763            pw.println("  mTickerView: " + viewInfo(mTickerView));
1764            pw.println("  mScrollView: " + viewInfo(mScrollView)
1765                    + " scroll " + mScrollView.getScrollX() + "," + mScrollView.getScrollY());
1766        }
1767
1768        if (DUMPTRUCK) {
1769            synchronized (mNotificationData) {
1770                int N = mNotificationData.size();
1771                pw.println("  notification icons: " + N);
1772                for (int i=0; i<N; i++) {
1773                    NotificationData.Entry e = mNotificationData.get(i);
1774                    pw.println("    [" + i + "] key=" + e.key + " icon=" + e.icon);
1775                    StatusBarNotification n = e.notification;
1776                    pw.println("         pkg=" + n.pkg + " id=" + n.id + " priority=" + n.priority);
1777                    pw.println("         notification=" + n.notification);
1778                    pw.println("         tickerText=\"" + n.notification.tickerText + "\"");
1779                }
1780            }
1781
1782            int N = mStatusIcons.getChildCount();
1783            pw.println("  system icons: " + N);
1784            for (int i=0; i<N; i++) {
1785                StatusBarIconView ic = (StatusBarIconView) mStatusIcons.getChildAt(i);
1786                pw.println("    [" + i + "] icon=" + ic);
1787            }
1788
1789            pw.println("see the logcat for a dump of the views we have created.");
1790            // must happen on ui thread
1791            mHandler.post(new Runnable() {
1792                    public void run() {
1793                        mStatusBarView.getLocationOnScreen(mAbsPos);
1794                        Slog.d(TAG, "mStatusBarView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1795                                + ") " + mStatusBarView.getWidth() + "x"
1796                                + mStatusBarView.getHeight());
1797                        mStatusBarView.debug();
1798
1799                        mExpandedView.getLocationOnScreen(mAbsPos);
1800                        Slog.d(TAG, "mExpandedView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1801                                + ") " + mExpandedView.getWidth() + "x"
1802                                + mExpandedView.getHeight());
1803                        mExpandedView.debug();
1804
1805                        mTrackingView.getLocationOnScreen(mAbsPos);
1806                        Slog.d(TAG, "mTrackingView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1807                                + ") " + mTrackingView.getWidth() + "x"
1808                                + mTrackingView.getHeight());
1809                        mTrackingView.debug();
1810                    }
1811                });
1812        }
1813    }
1814
1815    void onBarViewAttached() {
1816        WindowManager.LayoutParams lp;
1817        int pixelFormat;
1818        Drawable bg;
1819
1820        /// ---------- Tracking View --------------
1821        pixelFormat = PixelFormat.RGBX_8888;
1822        bg = mTrackingView.getBackground();
1823        if (bg != null) {
1824            pixelFormat = bg.getOpacity();
1825        }
1826
1827        lp = new WindowManager.LayoutParams(
1828                ViewGroup.LayoutParams.MATCH_PARENT,
1829                ViewGroup.LayoutParams.MATCH_PARENT,
1830                WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL,
1831                0
1832                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1833                | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
1834                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
1835                pixelFormat);
1836//        lp.token = mStatusBarView.getWindowToken();
1837        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
1838        lp.setTitle("TrackingView");
1839        lp.y = mTrackingPosition;
1840        mTrackingParams = lp;
1841
1842        WindowManagerImpl.getDefault().addView(mTrackingView, lp);
1843    }
1844
1845    void onTrackingViewAttached() {
1846        WindowManager.LayoutParams lp;
1847        int pixelFormat;
1848
1849        /// ---------- Expanded View --------------
1850        pixelFormat = PixelFormat.TRANSLUCENT;
1851
1852        lp = mExpandedDialog.getWindow().getAttributes();
1853        lp.x = 0;
1854        mTrackingPosition = lp.y = mDisplayMetrics.heightPixels; // sufficiently large negative
1855        lp.type = WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL;
1856        lp.flags = 0
1857                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1858                | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
1859                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
1860                | WindowManager.LayoutParams.FLAG_DITHER
1861                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1862        lp.format = pixelFormat;
1863        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
1864        lp.setTitle("StatusBarExpanded");
1865        mExpandedParams = lp;
1866        updateExpandedSize();
1867        mExpandedDialog.getWindow().setFormat(pixelFormat);
1868
1869        mExpandedDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
1870        mExpandedDialog.setContentView(mExpandedView,
1871                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1872                                           ViewGroup.LayoutParams.MATCH_PARENT));
1873        mExpandedDialog.getWindow().setBackgroundDrawable(null);
1874        mExpandedDialog.show();
1875    }
1876
1877    void setNotificationIconVisibility(boolean visible, int anim) {
1878        int old = mNotificationIcons.getVisibility();
1879        int v = visible ? View.VISIBLE : View.INVISIBLE;
1880        if (old != v) {
1881            mNotificationIcons.setVisibility(v);
1882            mNotificationIcons.startAnimation(loadAnim(anim, null));
1883        }
1884    }
1885
1886    void updateExpandedInvisiblePosition() {
1887        if (mTrackingView != null) {
1888            mTrackingPosition = -mDisplayMetrics.heightPixels;
1889            if (mTrackingParams != null) {
1890                mTrackingParams.y = mTrackingPosition;
1891                WindowManagerImpl.getDefault().updateViewLayout(mTrackingView, mTrackingParams);
1892            }
1893        }
1894        if (mExpandedParams != null) {
1895            mExpandedParams.y = -mDisplayMetrics.heightPixels;
1896            mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1897        }
1898    }
1899
1900    void updateExpandedViewPos(int expandedPosition) {
1901        if (SPEW) {
1902            Slog.d(TAG, "updateExpandedViewPos before expandedPosition=" + expandedPosition
1903                    + " mTrackingParams.y=" + ((mTrackingParams == null) ? "?" : mTrackingParams.y)
1904                    + " mTrackingPosition=" + mTrackingPosition);
1905        }
1906
1907        int h = mStatusBarView.getHeight();
1908        int disph = mDisplayMetrics.heightPixels;
1909
1910        // If the expanded view is not visible, make sure they're still off screen.
1911        // Maybe the view was resized.
1912        if (!mExpandedVisible) {
1913            updateExpandedInvisiblePosition();
1914            return;
1915        }
1916
1917        // tracking view...
1918        int pos;
1919        if (expandedPosition == EXPANDED_FULL_OPEN) {
1920            pos = h;
1921        }
1922        else if (expandedPosition == EXPANDED_LEAVE_ALONE) {
1923            pos = mTrackingPosition;
1924        }
1925        else {
1926            if (expandedPosition <= disph) {
1927                pos = expandedPosition;
1928            } else {
1929                pos = disph;
1930            }
1931            pos -= disph-h;
1932        }
1933        mTrackingPosition = mTrackingParams.y = pos;
1934        mTrackingParams.height = disph-h;
1935        WindowManagerImpl.getDefault().updateViewLayout(mTrackingView, mTrackingParams);
1936
1937        if (mExpandedParams != null) {
1938            if (mCloseView.getWindowVisibility() == View.VISIBLE) {
1939                mCloseView.getLocationInWindow(mPositionTmp);
1940                final int closePos = mPositionTmp[1];
1941
1942                mExpandedContents.getLocationInWindow(mPositionTmp);
1943                final int contentsBottom = mPositionTmp[1] + mExpandedContents.getHeight();
1944
1945                mExpandedParams.y = pos + mTrackingView.getHeight()
1946                        - (mTrackingParams.height-closePos) - contentsBottom;
1947
1948                if (SPEW) {
1949                    Slog.d(PhoneStatusBar.TAG,
1950                            "pos=" + pos +
1951                            " trackingHeight=" + mTrackingView.getHeight() +
1952                            " (trackingParams.height - closePos)=" +
1953                                (mTrackingParams.height - closePos) +
1954                            " contentsBottom=" + contentsBottom);
1955                }
1956
1957            } else {
1958                // If the tracking view is not yet visible, then we can't have
1959                // a good value of the close view location.  We need to wait for
1960                // it to be visible to do a layout.
1961                mExpandedParams.y = -mDisplayMetrics.heightPixels;
1962            }
1963            int max = h;
1964            if (mExpandedParams.y > max) {
1965                mExpandedParams.y = max;
1966            }
1967            int min = mTrackingPosition;
1968            if (mExpandedParams.y < min) {
1969                mExpandedParams.y = min;
1970            }
1971
1972            boolean visible = (mTrackingPosition + mTrackingView.getHeight()) > h;
1973            if (!visible) {
1974                // if the contents aren't visible, move the expanded view way off screen
1975                // because the window itself extends below the content view.
1976                mExpandedParams.y = -disph;
1977            }
1978            mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1979
1980            // As long as this isn't just a repositioning that's not supposed to affect
1981            // the user's perception of what's showing, call to say that the visibility
1982            // has changed. (Otherwise, someone else will call to do that).
1983            if (expandedPosition != EXPANDED_LEAVE_ALONE) {
1984                if (SPEW) Slog.d(TAG, "updateExpandedViewPos visibilityChanged(" + visible + ")");
1985                visibilityChanged(visible);
1986            }
1987        }
1988
1989        if (SPEW) {
1990            Slog.d(TAG, "updateExpandedViewPos after  expandedPosition=" + expandedPosition
1991                    + " mTrackingParams.y=" + mTrackingParams.y
1992                    + " mTrackingPosition=" + mTrackingPosition
1993                    + " mExpandedParams.y=" + mExpandedParams.y
1994                    + " mExpandedParams.height=" + mExpandedParams.height);
1995        }
1996    }
1997
1998    int getExpandedHeight(int disph) {
1999        if (DEBUG) {
2000            Slog.d(TAG, "getExpandedHeight(" + disph + "): sbView="
2001                    + mStatusBarView.getHeight() + " closeView=" + mCloseView.getHeight());
2002        }
2003        return disph - mStatusBarView.getHeight() - mCloseView.getHeight();
2004    }
2005
2006    void updateDisplaySize() {
2007        mDisplay.getMetrics(mDisplayMetrics);
2008        if (DEBUG) {
2009            Slog.d(TAG, "updateDisplaySize: " + mDisplayMetrics);
2010        }
2011        updateExpandedSize();
2012    }
2013
2014    void updateExpandedSize() {
2015        if (DEBUG) {
2016            Slog.d(TAG, "updateExpandedSize()");
2017        }
2018        if (mExpandedDialog != null && mExpandedParams != null && mDisplayMetrics != null) {
2019            mExpandedParams.width = mDisplayMetrics.widthPixels;
2020            mExpandedParams.height = getExpandedHeight(mDisplayMetrics.heightPixels);
2021            if (!mExpandedVisible) {
2022                updateExpandedInvisiblePosition();
2023            } else {
2024                mExpandedDialog.getWindow().setAttributes(mExpandedParams);
2025            }
2026            if (DEBUG) {
2027                Slog.d(TAG, "updateExpandedSize: height=" + mExpandedParams.height + " " +
2028                    (mExpandedVisible ? "VISIBLE":"INVISIBLE"));
2029            }
2030        }
2031    }
2032
2033    // The user is not allowed to get stuck without navigation UI. Upon the slightest user
2034    // interaction we bring the navigation back.
2035    public void userActivity() {
2036        if (mNavigationBarView != null) {
2037            mNavigationBarView.setHidden(false);
2038        }
2039    }
2040
2041    public void toggleRecentApps() {
2042        int msg = (mRecentsPanel.getVisibility() == View.GONE)
2043                ? MSG_OPEN_RECENTS_PANEL : MSG_CLOSE_RECENTS_PANEL;
2044        mHandler.removeMessages(msg);
2045        mHandler.sendEmptyMessage(msg);
2046    }
2047
2048    /**
2049     * The LEDs are turned o)ff when the notification panel is shown, even just a little bit.
2050     * This was added last-minute and is inconsistent with the way the rest of the notifications
2051     * are handled, because the notification isn't really cancelled.  The lights are just
2052     * turned off.  If any other notifications happen, the lights will turn back on.  Steve says
2053     * this is what he wants. (see bug 1131461)
2054     */
2055    void visibilityChanged(boolean visible) {
2056        if (mPanelSlightlyVisible != visible) {
2057            mPanelSlightlyVisible = visible;
2058            try {
2059                mBarService.onPanelRevealed();
2060            } catch (RemoteException ex) {
2061                // Won't fail unless the world has ended.
2062            }
2063        }
2064    }
2065
2066    void performDisableActions(int net) {
2067        int old = mDisabled;
2068        int diff = net ^ old;
2069        mDisabled = net;
2070
2071        // act accordingly
2072        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
2073            if ((net & StatusBarManager.DISABLE_EXPAND) != 0) {
2074                Slog.d(TAG, "DISABLE_EXPAND: yes");
2075                animateCollapse();
2076            }
2077        }
2078        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
2079            if ((net & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
2080                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: yes");
2081                if (mTicking) {
2082                    mNotificationIcons.setVisibility(View.INVISIBLE);
2083                    mTicker.halt();
2084                } else {
2085                    setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
2086                }
2087            } else {
2088                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: no");
2089                if (!mExpandedVisible) {
2090                    setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
2091                }
2092            }
2093        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
2094            if (mTicking && (net & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
2095                mTicker.halt();
2096            }
2097        }
2098    }
2099
2100    private View.OnClickListener mClearButtonListener = new View.OnClickListener() {
2101        public void onClick(View v) {
2102            try {
2103                mBarService.onClearAllNotifications();
2104            } catch (RemoteException ex) {
2105                // system process is dead if we're here.
2106            }
2107            animateCollapse();
2108        }
2109    };
2110
2111    private View.OnClickListener mSettingsButtonListener = new View.OnClickListener() {
2112        public void onClick(View v) {
2113            v.getContext().startActivity(new Intent(Settings.ACTION_SETTINGS)
2114                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
2115            animateCollapse();
2116        }
2117    };
2118
2119    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
2120        public void onReceive(Context context, Intent intent) {
2121            String action = intent.getAction();
2122            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
2123                    || Intent.ACTION_SCREEN_OFF.equals(action)) {
2124                boolean excludeRecents = false;
2125                if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
2126                    String reason = intent.getStringExtra("reason");
2127                    if (reason != null) {
2128                        excludeRecents = reason.equals("recentapps");
2129                    }
2130                }
2131                animateCollapse(excludeRecents);
2132            }
2133            else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
2134                repositionNavigationBar();
2135                updateResources();
2136            }
2137        }
2138    };
2139
2140    private void setIntruderAlertVisibility(boolean vis) {
2141        mIntruderAlertView.setVisibility(vis ? View.VISIBLE : View.GONE);
2142    }
2143
2144    /**
2145     * Reload some of our resources when the configuration changes.
2146     *
2147     * We don't reload everything when the configuration changes -- we probably
2148     * should, but getting that smooth is tough.  Someday we'll fix that.  In the
2149     * meantime, just update the things that we know change.
2150     */
2151    void updateResources() {
2152        final Context context = mContext;
2153        final Resources res = context.getResources();
2154
2155        if (mClearButton instanceof TextView) {
2156            ((TextView)mClearButton).setText(context.getText(R.string.status_bar_clear_all_button));
2157        }
2158        mNoNotificationsTitle.setText(context.getText(R.string.status_bar_no_notifications_title));
2159
2160        loadDimens();
2161    }
2162
2163    protected void loadDimens() {
2164        final Resources res = mContext.getResources();
2165
2166        mNaturalBarHeight = res.getDimensionPixelSize(
2167                com.android.internal.R.dimen.status_bar_height);
2168
2169        int newIconSize = res.getDimensionPixelSize(
2170            com.android.internal.R.dimen.status_bar_icon_size);
2171        int newIconHPadding = res.getDimensionPixelSize(
2172            R.dimen.status_bar_icon_padding);
2173
2174        if (newIconHPadding != mIconHPadding || newIconSize != mIconSize) {
2175//            Slog.d(TAG, "size=" + newIconSize + " padding=" + newIconHPadding);
2176            mIconHPadding = newIconHPadding;
2177            mIconSize = newIconSize;
2178            //reloadAllNotificationIcons(); // reload the tray
2179        }
2180
2181        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
2182
2183        mSelfExpandVelocityPx = res.getDimension(R.dimen.self_expand_velocity);
2184        mSelfCollapseVelocityPx = res.getDimension(R.dimen.self_collapse_velocity);
2185        mFlingExpandMinVelocityPx = res.getDimension(R.dimen.fling_expand_min_velocity);
2186        mFlingCollapseMinVelocityPx = res.getDimension(R.dimen.fling_collapse_min_velocity);
2187
2188        mCollapseMinDisplayFraction = res.getFraction(R.dimen.collapse_min_display_fraction, 1, 1);
2189        mExpandMinDisplayFraction = res.getFraction(R.dimen.expand_min_display_fraction, 1, 1);
2190
2191        mExpandAccelPx = res.getDimension(R.dimen.expand_accel);
2192        mCollapseAccelPx = res.getDimension(R.dimen.collapse_accel);
2193
2194        mFlingGestureMaxXVelocityPx = res.getDimension(R.dimen.fling_gesture_max_x_velocity);
2195
2196        if (false) Slog.v(TAG, "updateResources");
2197    }
2198
2199    //
2200    // tracing
2201    //
2202
2203    void postStartTracing() {
2204        mHandler.postDelayed(mStartTracing, 3000);
2205    }
2206
2207    void vibrate() {
2208        android.os.Vibrator vib = (android.os.Vibrator)mContext.getSystemService(
2209                Context.VIBRATOR_SERVICE);
2210        vib.vibrate(250);
2211    }
2212
2213    Runnable mStartTracing = new Runnable() {
2214        public void run() {
2215            vibrate();
2216            SystemClock.sleep(250);
2217            Slog.d(TAG, "startTracing");
2218            android.os.Debug.startMethodTracing("/data/statusbar-traces/trace");
2219            mHandler.postDelayed(mStopTracing, 10000);
2220        }
2221    };
2222
2223    Runnable mStopTracing = new Runnable() {
2224        public void run() {
2225            android.os.Debug.stopMethodTracing();
2226            Slog.d(TAG, "stopTracing");
2227            vibrate();
2228        }
2229    };
2230
2231    public class TouchOutsideListener implements View.OnTouchListener {
2232        private int mMsg;
2233        private RecentsPanelView mPanel;
2234
2235        public TouchOutsideListener(int msg, RecentsPanelView panel) {
2236            mMsg = msg;
2237            mPanel = panel;
2238        }
2239
2240        public boolean onTouch(View v, MotionEvent ev) {
2241            final int action = ev.getAction();
2242            if (action == MotionEvent.ACTION_OUTSIDE
2243                || (action == MotionEvent.ACTION_DOWN
2244                    && !mPanel.isInContentArea((int)ev.getX(), (int)ev.getY()))) {
2245                mHandler.removeMessages(mMsg);
2246                mHandler.sendEmptyMessage(mMsg);
2247                return true;
2248            }
2249            return false;
2250        }
2251    }
2252}
2253
2254