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