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