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