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