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