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