TabletStatusBar.java revision e40451a89dc91dfd636af7cb32a23b4a4cc93fdc
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.tablet;
18
19import java.io.FileDescriptor;
20import java.io.PrintWriter;
21import java.util.ArrayList;
22
23import android.animation.LayoutTransition;
24import android.animation.ObjectAnimator;
25import android.app.ActivityManagerNative;
26import android.app.PendingIntent;
27import android.app.Notification;
28import android.app.StatusBarManager;
29import android.content.Context;
30import android.content.Intent;
31import android.content.res.Configuration;
32import android.content.res.Resources;
33import android.inputmethodservice.InputMethodService;
34import android.graphics.PixelFormat;
35import android.graphics.Rect;
36import android.graphics.drawable.LayerDrawable;
37import android.os.Handler;
38import android.os.IBinder;
39import android.os.Message;
40import android.os.RemoteException;
41import android.os.ServiceManager;
42import android.text.TextUtils;
43import android.util.Slog;
44import android.view.Gravity;
45import android.view.IWindowManager;
46import android.view.KeyEvent;
47import android.view.LayoutInflater;
48import android.view.MotionEvent;
49import android.view.VelocityTracker;
50import android.view.View;
51import android.view.ViewConfiguration;
52import android.view.ViewGroup;
53import android.view.WindowManager;
54import android.view.WindowManagerImpl;
55import android.widget.ImageView;
56import android.widget.LinearLayout;
57import android.widget.RemoteViews;
58import android.widget.ScrollView;
59import android.widget.TextView;
60
61import com.android.internal.statusbar.StatusBarIcon;
62import com.android.internal.statusbar.StatusBarNotification;
63
64import com.android.systemui.R;
65import com.android.systemui.statusbar.*;
66import com.android.systemui.statusbar.policy.BatteryController;
67import com.android.systemui.statusbar.policy.BluetoothController;
68import com.android.systemui.statusbar.policy.LocationController;
69import com.android.systemui.statusbar.policy.NetworkController;
70import com.android.systemui.recent.RecentApplicationsActivity;
71
72public class TabletStatusBar extends StatusBar implements
73        HeightReceiver.OnBarHeightChangedListener,
74        InputMethodsPanel.OnHardKeyboardEnabledChangeListener {
75    public static final boolean DEBUG = false;
76    public static final String TAG = "TabletStatusBar";
77
78    public static final int MAX_NOTIFICATION_ICONS = 5;
79    // IME switcher icon is big and occupy width of two icons
80    public static final int MAX_NOTIFICATION_ICONS_IME_BUTTON_VISIBLE = MAX_NOTIFICATION_ICONS - 1;
81
82    public static final int MSG_OPEN_NOTIFICATION_PANEL = 1000;
83    public static final int MSG_CLOSE_NOTIFICATION_PANEL = 1001;
84    public static final int MSG_OPEN_NOTIFICATION_PEEK = 1002;
85    public static final int MSG_CLOSE_NOTIFICATION_PEEK = 1003;
86    public static final int MSG_OPEN_RECENTS_PANEL = 1020;
87    public static final int MSG_CLOSE_RECENTS_PANEL = 1021;
88    public static final int MSG_SHOW_CHROME = 1030;
89    public static final int MSG_HIDE_CHROME = 1031;
90    public static final int MSG_OPEN_INPUT_METHODS_PANEL = 1040;
91    public static final int MSG_CLOSE_INPUT_METHODS_PANEL = 1041;
92    public static final int MSG_STOP_TICKER = 2000;
93
94    // Fitts' Law assistance for LatinIME; TODO: replace with a more general approach
95    private static final boolean FAKE_SPACE_BAR = true;
96
97    // The height of the bar, as definied by the build.  It may be taller if we're plugged
98    // into hdmi.
99    int mNaturalBarHeight = -1;
100    int mIconSize = -1;
101    int mIconHPadding = -1;
102
103    H mHandler = new H();
104
105    IWindowManager mWindowManager;
106
107    // tracking all current notifications
108    private NotificationData mNotns = new NotificationData();
109
110    TabletStatusBarView mStatusBarView;
111    View mNotificationArea;
112    View mNotificationTrigger;
113    NotificationIconArea mNotificationIconArea;
114    View mNavigationArea;
115
116    ImageView mBackButton;
117    View mHomeButton;
118    View mMenuButton;
119    View mRecentButton;
120
121    ViewGroup mNotificationAndImeArea;
122    InputMethodButton mInputMethodSwitchButton;
123
124    NotificationPanel mNotificationPanel;
125    NotificationPeekPanel mNotificationPeekWindow;
126    ViewGroup mNotificationPeekRow;
127    int mNotificationPeekIndex;
128    IBinder mNotificationPeekKey;
129    LayoutTransition mNotificationPeekScrubLeft, mNotificationPeekScrubRight;
130
131    int mNotificationPeekTapDuration;
132    int mNotificationFlingVelocity;
133
134    ViewGroup mPile;
135
136    HeightReceiver mHeightReceiver;
137    BatteryController mBatteryController;
138    BluetoothController mBluetoothController;
139    LocationController mLocationController;
140    NetworkController mNetworkController;
141
142    View mBarContents;
143
144    // hide system chrome ("lights out") support
145    View mShadow;
146
147    NotificationIconArea.IconLayout mIconLayout;
148
149    TabletTicker mTicker;
150
151    View mFakeSpaceBar;
152    KeyEvent mSpaceBarKeyEvent = null;
153
154    // for disabling the status bar
155    int mDisabled = 0;
156
157    boolean mNotificationsOn = true;
158    private RecentAppsPanel mRecentsPanel;
159    private InputMethodsPanel mInputMethodsPanel;
160
161    public Context getContext() { return mContext; }
162
163    protected void addPanelWindows() {
164        final Context context = mContext;
165
166        // Notification Panel
167        mNotificationPanel = (NotificationPanel)View.inflate(context,
168                R.layout.status_bar_notification_panel, null);
169        mNotificationPanel.show(false, false);
170        mNotificationPanel.setOnTouchListener(
171                new TouchOutsideListener(MSG_CLOSE_NOTIFICATION_PANEL, mNotificationPanel));
172
173        // the battery and network icons
174        mBatteryController.addIconView((ImageView)mNotificationPanel.findViewById(R.id.battery));
175        mBatteryController.addLabelView(
176                (TextView)mNotificationPanel.findViewById(R.id.battery_text));
177        mBluetoothController.addIconView(
178                (ImageView)mNotificationPanel.findViewById(R.id.bluetooth));
179        mNetworkController.addCombinedSignalIconView(
180                (ImageView)mNotificationPanel.findViewById(R.id.network_signal));
181        mNetworkController.addDataTypeIconView(
182                (ImageView)mNotificationPanel.findViewById(R.id.network_type));
183        mNetworkController.addDataDirectionOverlayIconView(
184                (ImageView)mNotificationPanel.findViewById(R.id.network_direction));
185        mNetworkController.addLabelView(
186                (TextView)mNotificationPanel.findViewById(R.id.network_text));
187        mNetworkController.addLabelView(
188                (TextView)mBarContents.findViewById(R.id.network_text));
189
190        mStatusBarView.setIgnoreChildren(0, mNotificationTrigger, mNotificationPanel);
191
192        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
193                512, // ViewGroup.LayoutParams.MATCH_PARENT,
194                ViewGroup.LayoutParams.MATCH_PARENT,
195                WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL,
196                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
197                    | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
198                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH
199                    | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
200                PixelFormat.TRANSLUCENT);
201        lp.gravity = Gravity.BOTTOM | Gravity.RIGHT;
202        lp.setTitle("NotificationPanel");
203        lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED
204                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
205        lp.windowAnimations = com.android.internal.R.style.Animation; // == no animation
206//        lp.windowAnimations = com.android.internal.R.style.Animation_ZoomButtons; // simple fade
207
208        WindowManagerImpl.getDefault().addView(mNotificationPanel, lp);
209
210        // Notification preview window
211        mNotificationPeekWindow = (NotificationPeekPanel) View.inflate(context,
212                R.layout.status_bar_notification_peek, null);
213        mNotificationPeekRow = (ViewGroup) mNotificationPeekWindow.findViewById(R.id.content);
214        mNotificationPeekWindow.setVisibility(View.GONE);
215        mNotificationPeekWindow.setOnTouchListener(
216                new TouchOutsideListener(MSG_CLOSE_NOTIFICATION_PEEK, mNotificationPeekWindow));
217        mNotificationPeekScrubRight = new LayoutTransition();
218        mNotificationPeekScrubRight.setAnimator(LayoutTransition.APPEARING,
219                ObjectAnimator.ofInt(null, "left", -512, 0));
220        mNotificationPeekScrubRight.setAnimator(LayoutTransition.DISAPPEARING,
221                ObjectAnimator.ofInt(null, "left", -512, 0));
222        mNotificationPeekScrubRight.setDuration(500);
223
224        mNotificationPeekScrubLeft = new LayoutTransition();
225        mNotificationPeekScrubLeft.setAnimator(LayoutTransition.APPEARING,
226                ObjectAnimator.ofInt(null, "left", 512, 0));
227        mNotificationPeekScrubLeft.setAnimator(LayoutTransition.DISAPPEARING,
228                ObjectAnimator.ofInt(null, "left", 512, 0));
229        mNotificationPeekScrubLeft.setDuration(500);
230
231        // XXX: setIgnoreChildren?
232        lp = new WindowManager.LayoutParams(
233                512, // ViewGroup.LayoutParams.WRAP_CONTENT,
234                ViewGroup.LayoutParams.WRAP_CONTENT,
235                WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL,
236                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
237                    | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
238                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
239                PixelFormat.TRANSLUCENT);
240        lp.gravity = Gravity.BOTTOM | Gravity.RIGHT;
241        lp.setTitle("NotificationPeekWindow");
242        lp.windowAnimations = com.android.internal.R.style.Animation_Toast;
243
244        WindowManagerImpl.getDefault().addView(mNotificationPeekWindow, lp);
245
246        // Recents Panel
247        mRecentsPanel = (RecentAppsPanel) View.inflate(context,
248                R.layout.status_bar_recent_panel, null);
249        mRecentsPanel.setVisibility(View.GONE);
250        mRecentsPanel.setOnTouchListener(new TouchOutsideListener(MSG_CLOSE_RECENTS_PANEL,
251                mRecentsPanel));
252        mStatusBarView.setIgnoreChildren(2, mRecentButton, mRecentsPanel);
253
254        lp = new WindowManager.LayoutParams(
255                ViewGroup.LayoutParams.WRAP_CONTENT,
256                ViewGroup.LayoutParams.WRAP_CONTENT,
257                WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL,
258                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
259                    | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
260                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH
261                    | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
262                PixelFormat.TRANSLUCENT);
263        lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
264        lp.setTitle("RecentsPanel");
265        lp.windowAnimations = R.style.Animation_RecentPanel;
266
267        WindowManagerImpl.getDefault().addView(mRecentsPanel, lp);
268        mRecentsPanel.setBar(this);
269
270        // Input methods Panel
271        mInputMethodsPanel = (InputMethodsPanel) View.inflate(context,
272                R.layout.status_bar_input_methods_panel, null);
273        mInputMethodsPanel.setHardKeyboardEnabledChangeListener(this);
274        mInputMethodsPanel.setOnTouchListener(new TouchOutsideListener(
275                MSG_CLOSE_INPUT_METHODS_PANEL, mInputMethodsPanel));
276        mInputMethodsPanel.setImeSwitchButton(mInputMethodSwitchButton);
277        mStatusBarView.setIgnoreChildren(3, mInputMethodSwitchButton, mInputMethodsPanel);
278        lp = new WindowManager.LayoutParams(
279                ViewGroup.LayoutParams.WRAP_CONTENT,
280                ViewGroup.LayoutParams.WRAP_CONTENT,
281                WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL,
282                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
283                    | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
284                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH
285                    | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
286                PixelFormat.TRANSLUCENT);
287        lp.gravity = Gravity.BOTTOM | Gravity.RIGHT;
288        lp.setTitle("InputMethodsPanel");
289        lp.windowAnimations = R.style.Animation_RecentPanel;
290
291        WindowManagerImpl.getDefault().addView(mInputMethodsPanel, lp);
292    }
293
294    @Override
295    public void start() {
296        super.start(); // will add the main bar view
297    }
298
299    @Override
300    protected void onConfigurationChanged(Configuration newConfig) {
301        loadDimens();
302    }
303
304    protected void loadDimens() {
305        final Resources res = mContext.getResources();
306
307        mNaturalBarHeight = res.getDimensionPixelSize(
308                com.android.internal.R.dimen.status_bar_height);
309
310        int newIconSize = res.getDimensionPixelSize(
311            com.android.internal.R.dimen.status_bar_icon_size);
312        int newIconHPadding = res.getDimensionPixelSize(
313            R.dimen.status_bar_icon_padding);
314
315        if (newIconHPadding != mIconHPadding || newIconSize != mIconSize) {
316//            Slog.d(TAG, "size=" + newIconSize + " padding=" + newIconHPadding);
317            mIconHPadding = newIconHPadding;
318            mIconSize = newIconSize;
319            reloadAllNotificationIcons(); // reload the tray
320        }
321    }
322
323    protected View makeStatusBarView() {
324        final Context context = mContext;
325
326        mWindowManager = IWindowManager.Stub.asInterface(
327                ServiceManager.getService(Context.WINDOW_SERVICE));
328
329        // This guy will listen for HDMI plugged broadcasts so we can resize the
330        // status bar as appropriate.
331        mHeightReceiver = new HeightReceiver(mContext);
332        mHeightReceiver.registerReceiver();
333        loadDimens();
334
335        final TabletStatusBarView sb = (TabletStatusBarView)View.inflate(
336                context, R.layout.status_bar, null);
337        mStatusBarView = sb;
338
339        sb.setHandler(mHandler);
340
341        mBarContents = sb.findViewById(R.id.bar_contents);
342
343        // the whole right-hand side of the bar
344        mNotificationArea = sb.findViewById(R.id.notificationArea);
345
346        // the button to open the notification area
347        mNotificationTrigger = sb.findViewById(R.id.notificationTrigger);
348        mNotificationTrigger.setOnClickListener(mOnClickListener);
349
350        // the more notifications icon
351        mNotificationIconArea = (NotificationIconArea)sb.findViewById(R.id.notificationIcons);
352
353        // where the icons go
354        mIconLayout = (NotificationIconArea.IconLayout) sb.findViewById(R.id.icons);
355        mIconLayout.setOnTouchListener(new NotificationIconTouchListener());
356
357        ViewConfiguration vc = ViewConfiguration.get(context);
358        mNotificationPeekTapDuration = vc.getTapTimeout();
359        mNotificationFlingVelocity = 300; // px/s
360
361        mTicker = new TabletTicker(this);
362
363        // The icons
364        mLocationController = new LocationController(mContext); // will post a notification
365
366        mBatteryController = new BatteryController(mContext);
367        mBatteryController.addIconView((ImageView)sb.findViewById(R.id.battery));
368        mBluetoothController = new BluetoothController(mContext);
369        mBluetoothController.addIconView((ImageView)sb.findViewById(R.id.bluetooth));
370        mNetworkController = new NetworkController(mContext);
371        mNetworkController.addCombinedSignalIconView(
372                (ImageView)sb.findViewById(R.id.network_signal));
373        mNetworkController.addDataTypeIconView(
374                (ImageView)sb.findViewById(R.id.network_type));
375        mNetworkController.addDataDirectionOverlayIconView(
376                (ImageView)sb.findViewById(R.id.network_direction));
377
378        // The navigation buttons
379        mBackButton = (ImageView)sb.findViewById(R.id.back);
380        mNavigationArea = sb.findViewById(R.id.navigationArea);
381        mHomeButton = mNavigationArea.findViewById(R.id.home);
382        mMenuButton = mNavigationArea.findViewById(R.id.menu);
383        mRecentButton = mNavigationArea.findViewById(R.id.recent_apps);
384        mRecentButton.setOnClickListener(mOnClickListener);
385
386        // The bar contents buttons
387        mNotificationAndImeArea = (ViewGroup)sb.findViewById(R.id.notificationAndImeArea);
388        mInputMethodSwitchButton = (InputMethodButton) sb.findViewById(R.id.imeSwitchButton);
389        // Overwrite the lister
390        mInputMethodSwitchButton.setOnClickListener(mOnClickListener);
391
392        // for redirecting errant bar taps to the IME
393        mFakeSpaceBar = sb.findViewById(R.id.fake_space_bar);
394
395        // "shadows" of the status bar features, for lights-out mode
396        mShadow = sb.findViewById(R.id.bar_shadow);
397        mShadow.setOnTouchListener(
398            new View.OnTouchListener() {
399                public boolean onTouch(View v, MotionEvent ev) {
400                    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
401                        // even though setting the systemUI visibility below will turn these views
402                        // on, we need them to come up faster so that they can catch this motion
403                        // event
404                        mShadow.setVisibility(View.GONE);
405                        mBarContents.setVisibility(View.VISIBLE);
406
407                        try {
408                            mBarService.setSystemUiVisibility(View.STATUS_BAR_VISIBLE);
409                        } catch (RemoteException ex) {
410                            // system process dead
411                        }
412                    }
413                    return false;
414                }
415            });
416
417        // tuning parameters
418        final int LIGHTS_GOING_OUT_SYSBAR_DURATION = 600;
419        final int LIGHTS_GOING_OUT_SHADOW_DURATION = 1000;
420        final int LIGHTS_GOING_OUT_SHADOW_DELAY    = 500;
421
422        final int LIGHTS_COMING_UP_SYSBAR_DURATION = 200;
423//        final int LIGHTS_COMING_UP_SYSBAR_DELAY    = 50;
424        final int LIGHTS_COMING_UP_SHADOW_DURATION = 0;
425
426        LayoutTransition xition = new LayoutTransition();
427        xition.setAnimator(LayoutTransition.APPEARING,
428               ObjectAnimator.ofFloat(null, "alpha", 0.5f, 1f));
429        xition.setDuration(LayoutTransition.APPEARING, LIGHTS_COMING_UP_SYSBAR_DURATION);
430        xition.setStartDelay(LayoutTransition.APPEARING, 0);
431        xition.setAnimator(LayoutTransition.DISAPPEARING,
432               ObjectAnimator.ofFloat(null, "alpha", 1f, 0f));
433        xition.setDuration(LayoutTransition.DISAPPEARING, LIGHTS_GOING_OUT_SYSBAR_DURATION);
434        xition.setStartDelay(LayoutTransition.DISAPPEARING, 0);
435        ((ViewGroup)sb.findViewById(R.id.bar_contents_holder)).setLayoutTransition(xition);
436
437        xition = new LayoutTransition();
438        xition.setAnimator(LayoutTransition.APPEARING,
439               ObjectAnimator.ofFloat(null, "alpha", 0f, 1f));
440        xition.setDuration(LayoutTransition.APPEARING, LIGHTS_GOING_OUT_SHADOW_DURATION);
441        xition.setStartDelay(LayoutTransition.APPEARING, LIGHTS_GOING_OUT_SHADOW_DELAY);
442        xition.setAnimator(LayoutTransition.DISAPPEARING,
443               ObjectAnimator.ofFloat(null, "alpha", 1f, 0f));
444        xition.setDuration(LayoutTransition.DISAPPEARING, LIGHTS_COMING_UP_SHADOW_DURATION);
445        xition.setStartDelay(LayoutTransition.DISAPPEARING, 0);
446        ((ViewGroup)sb.findViewById(R.id.bar_shadow_holder)).setLayoutTransition(xition);
447
448        // set the initial view visibility
449        setAreThereNotifications();
450
451        // Add the windows
452        addPanelWindows();
453
454        mPile = (ViewGroup)mNotificationPanel.findViewById(R.id.content);
455        mPile.removeAllViews();
456
457        ScrollView scroller = (ScrollView)mPile.getParent();
458        scroller.setFillViewport(true);
459
460        mHeightReceiver.addOnBarHeightChangedListener(this);
461
462        return sb;
463    }
464
465    public int getStatusBarHeight() {
466        return mHeightReceiver.getHeight();
467    }
468
469    protected int getStatusBarGravity() {
470        return Gravity.BOTTOM | Gravity.FILL_HORIZONTAL;
471    }
472
473    public void onBarHeightChanged(int height) {
474        final WindowManager.LayoutParams lp
475                = (WindowManager.LayoutParams)mStatusBarView.getLayoutParams();
476        if (lp == null) {
477            // haven't been added yet
478            return;
479        }
480        if (lp.height != height) {
481            lp.height = height;
482            final WindowManager wm = WindowManagerImpl.getDefault();
483            wm.updateViewLayout(mStatusBarView, lp);
484        }
485    }
486
487    private class H extends Handler {
488        public void handleMessage(Message m) {
489            switch (m.what) {
490                case MSG_OPEN_NOTIFICATION_PEEK:
491                    if (DEBUG) Slog.d(TAG, "opening notification peek window; arg=" + m.arg1);
492                    if (m.arg1 >= 0) {
493                        final int N = mNotns.size();
494                        if (mNotificationPeekIndex >= 0 && mNotificationPeekIndex < N) {
495                            NotificationData.Entry entry = mNotns.get(N-1-mNotificationPeekIndex);
496                            entry.icon.setBackgroundColor(0);
497                            mNotificationPeekIndex = -1;
498                            mNotificationPeekKey = null;
499                        }
500
501                        final int peekIndex = m.arg1;
502                        if (peekIndex < N) {
503                            //Slog.d(TAG, "loading peek: " + peekIndex);
504                            NotificationData.Entry entry = mNotns.get(N-1-peekIndex);
505                            NotificationData.Entry copy = new NotificationData.Entry(
506                                    entry.key,
507                                    entry.notification,
508                                    entry.icon);
509                            inflateViews(copy, mNotificationPeekRow);
510
511                            entry.icon.setBackgroundColor(0x20FFFFFF);
512
513//                          mNotificationPeekRow.setLayoutTransition(
514//                              peekIndex < mNotificationPeekIndex
515//                                  ? mNotificationPeekScrubLeft
516//                                  : mNotificationPeekScrubRight);
517
518                            mNotificationPeekRow.removeAllViews();
519                            mNotificationPeekRow.addView(copy.row);
520
521                            mNotificationPeekWindow.setVisibility(View.VISIBLE);
522                            mNotificationPanel.show(false, true);
523
524                            mNotificationPeekIndex = peekIndex;
525                            mNotificationPeekKey = entry.key;
526                        }
527                    }
528                    break;
529                case MSG_CLOSE_NOTIFICATION_PEEK:
530                    if (DEBUG) Slog.d(TAG, "closing notification peek window");
531                    mNotificationPeekWindow.setVisibility(View.GONE);
532                    mNotificationPeekRow.removeAllViews();
533                    final int N = mNotns.size();
534                    if (mNotificationPeekIndex >= 0 && mNotificationPeekIndex < N) {
535                        NotificationData.Entry entry = mNotns.get(N-1-mNotificationPeekIndex);
536                        entry.icon.setBackgroundColor(0);
537                    }
538
539                    mNotificationPeekIndex = -1;
540                    mNotificationPeekKey = null;
541                    break;
542                case MSG_OPEN_NOTIFICATION_PANEL:
543                    if (DEBUG) Slog.d(TAG, "opening notifications panel");
544                    if (!mNotificationPanel.isShowing()) {
545                        mNotificationPeekWindow.setVisibility(View.GONE);
546                        mNotificationPanel.show(true, true);
547                        mNotificationArea.setVisibility(View.GONE);
548                        mTicker.halt();
549                    }
550                    break;
551                case MSG_CLOSE_NOTIFICATION_PANEL:
552                    if (DEBUG) Slog.d(TAG, "closing notifications panel");
553                    if (mNotificationPanel.isShowing()) {
554                        mNotificationPanel.show(false, true);
555                        mNotificationArea.setVisibility(View.VISIBLE);
556                    }
557                    break;
558                case MSG_OPEN_RECENTS_PANEL:
559                    if (DEBUG) Slog.d(TAG, "opening recents panel");
560                    if (mRecentsPanel != null) {
561                        mRecentsPanel.setVisibility(View.VISIBLE);
562                        mRecentsPanel.show(true, true);
563                    }
564                    break;
565                case MSG_CLOSE_RECENTS_PANEL:
566                    if (DEBUG) Slog.d(TAG, "closing recents panel");
567                    if (mRecentsPanel != null && mRecentsPanel.isShowing()) {
568                        mRecentsPanel.show(false, true);
569                    }
570                    break;
571                case MSG_OPEN_INPUT_METHODS_PANEL:
572                    if (DEBUG) Slog.d(TAG, "opening input methods panel");
573                    if (mInputMethodsPanel != null) mInputMethodsPanel.openPanel();
574                    break;
575                case MSG_CLOSE_INPUT_METHODS_PANEL:
576                    if (DEBUG) Slog.d(TAG, "closing input methods panel");
577                    if (mInputMethodsPanel != null) mInputMethodsPanel.closePanel(false);
578                    break;
579                case MSG_SHOW_CHROME:
580                    if (DEBUG) Slog.d(TAG, "hiding shadows (lights on)");
581                    mBarContents.setVisibility(View.VISIBLE);
582                    mShadow.setVisibility(View.GONE);
583                    notifyLightsChanged(true);
584                    break;
585                case MSG_HIDE_CHROME:
586                    if (DEBUG) Slog.d(TAG, "showing shadows (lights out)");
587                    animateCollapse();
588                    mBarContents.setVisibility(View.GONE);
589                    mShadow.setVisibility(View.VISIBLE);
590                    notifyLightsChanged(false);
591                    break;
592                case MSG_STOP_TICKER:
593                    mTicker.halt();
594                    break;
595            }
596        }
597    }
598
599    private void notifyLightsChanged(boolean shown) {
600        try {
601            Slog.d(TAG, "lights " + (shown?"on":"out"));
602            mWindowManager.statusBarVisibilityChanged(
603                    shown ? View.STATUS_BAR_VISIBLE : View.STATUS_BAR_HIDDEN);
604        } catch (RemoteException ex) {
605        }
606    }
607
608    public void addIcon(String slot, int index, int viewIndex, StatusBarIcon icon) {
609        if (DEBUG) Slog.d(TAG, "addIcon(" + slot + ") -> " + icon);
610    }
611
612    public void updateIcon(String slot, int index, int viewIndex,
613            StatusBarIcon old, StatusBarIcon icon) {
614        if (DEBUG) Slog.d(TAG, "updateIcon(" + slot + ") -> " + icon);
615    }
616
617    public void removeIcon(String slot, int index, int viewIndex) {
618        if (DEBUG) Slog.d(TAG, "removeIcon(" + slot + ")");
619    }
620
621    public void addNotification(IBinder key, StatusBarNotification notification) {
622        if (DEBUG) Slog.d(TAG, "addNotification(" + key + " -> " + notification + ")");
623        addNotificationViews(key, notification);
624
625        final boolean immersive = isImmersive();
626        if (false && immersive) {
627            // TODO: immersive mode popups for tablet
628        } else if (notification.notification.fullScreenIntent != null) {
629            // not immersive & a full-screen alert should be shown
630            Slog.w(TAG, "Notification has fullScreenIntent and activity is not immersive;"
631                    + " sending fullScreenIntent");
632            try {
633                notification.notification.fullScreenIntent.send();
634            } catch (PendingIntent.CanceledException e) {
635            }
636        } else {
637            tick(key, notification, true);
638        }
639
640        setAreThereNotifications();
641    }
642
643    public void updateNotification(IBinder key, StatusBarNotification notification) {
644        if (DEBUG) Slog.d(TAG, "updateNotification(" + key + " -> " + notification + ") // TODO");
645
646        final NotificationData.Entry oldEntry = mNotns.findByKey(key);
647        if (oldEntry == null) {
648            Slog.w(TAG, "updateNotification for unknown key: " + key);
649            return;
650        }
651
652        final StatusBarNotification oldNotification = oldEntry.notification;
653        final RemoteViews oldContentView = oldNotification.notification.contentView;
654
655        final RemoteViews contentView = notification.notification.contentView;
656
657        if (DEBUG) {
658            Slog.d(TAG, "old notification: when=" + oldNotification.notification.when
659                    + " ongoing=" + oldNotification.isOngoing()
660                    + " expanded=" + oldEntry.expanded
661                    + " contentView=" + oldContentView);
662            Slog.d(TAG, "new notification: when=" + notification.notification.when
663                    + " ongoing=" + oldNotification.isOngoing()
664                    + " contentView=" + contentView);
665        }
666
667        // Can we just reapply the RemoteViews in place?  If when didn't change, the order
668        // didn't change.
669        boolean contentsUnchanged = oldEntry.expanded != null
670                && contentView != null && oldContentView != null
671                && contentView.getPackage() != null
672                && oldContentView.getPackage() != null
673                && oldContentView.getPackage().equals(contentView.getPackage())
674                && oldContentView.getLayoutId() == contentView.getLayoutId();
675        ViewGroup rowParent = (ViewGroup) oldEntry.row.getParent();
676        boolean orderUnchanged = notification.notification.when==oldNotification.notification.when
677                && notification.priority == oldNotification.priority;
678                // priority now encompasses isOngoing()
679        boolean isLastAnyway = rowParent.indexOfChild(oldEntry.row) == rowParent.getChildCount()-1;
680        if (contentsUnchanged && (orderUnchanged || isLastAnyway)) {
681            if (DEBUG) Slog.d(TAG, "reusing notification for key: " + key);
682            oldEntry.notification = notification;
683            try {
684                // Reapply the RemoteViews
685                contentView.reapply(mContext, oldEntry.content);
686                // update the contentIntent
687                final PendingIntent contentIntent = notification.notification.contentIntent;
688                if (contentIntent != null) {
689                    oldEntry.content.setOnClickListener(new NotificationClicker(contentIntent,
690                                notification.pkg, notification.tag, notification.id));
691                } else {
692                    oldEntry.content.setOnClickListener(null);
693                }
694                // Update the icon.
695                final StatusBarIcon ic = new StatusBarIcon(notification.pkg,
696                        notification.notification.icon, notification.notification.iconLevel,
697                        notification.notification.number);
698                if (!oldEntry.icon.set(ic)) {
699                    handleNotificationError(key, notification, "Couldn't update icon: " + ic);
700                    return;
701                }
702                // Update the large icon
703                if (notification.notification.largeIcon != null) {
704                    oldEntry.largeIcon.setImageBitmap(notification.notification.largeIcon);
705                } else {
706                    oldEntry.largeIcon.getLayoutParams().width = 0;
707                    oldEntry.largeIcon.setVisibility(View.INVISIBLE);
708                }
709
710                if (key == mNotificationPeekKey) {
711                    // must update the peek window
712                    Message peekMsg = mHandler.obtainMessage(MSG_OPEN_NOTIFICATION_PEEK);
713                    peekMsg.arg1 = mNotificationPeekIndex;
714                    mHandler.removeMessages(MSG_OPEN_NOTIFICATION_PEEK);
715                    mHandler.sendMessage(peekMsg);
716                }
717            }
718            catch (RuntimeException e) {
719                // It failed to add cleanly.  Log, and remove the view from the panel.
720                Slog.w(TAG, "Couldn't reapply views for package " + contentView.getPackage(), e);
721                removeNotificationViews(key);
722                addNotificationViews(key, notification);
723            }
724        } else {
725            if (DEBUG) Slog.d(TAG, "not reusing notification for key: " + key);
726            removeNotificationViews(key);
727            addNotificationViews(key, notification);
728        }
729        // fullScreenIntent doesn't happen on updates.  You need to clear & repost a new
730        // notification.
731        final boolean immersive = isImmersive();
732        if (false && immersive) {
733            // TODO: immersive mode
734        } else {
735            tick(key, notification, false);
736        }
737
738        setAreThereNotifications();
739    }
740
741    public void removeNotification(IBinder key) {
742        if (DEBUG) Slog.d(TAG, "removeNotification(" + key + ") // TODO");
743        removeNotificationViews(key);
744        mTicker.remove(key);
745        setAreThereNotifications();
746    }
747
748    public void showClock(boolean show) {
749        View clock = mBarContents.findViewById(R.id.clock);
750        View network_text = mBarContents.findViewById(R.id.network_text);
751        if (clock != null) {
752            clock.setVisibility(show ? View.VISIBLE : View.GONE);
753        }
754        if (network_text != null) {
755            network_text.setVisibility((!show) ? View.VISIBLE : View.GONE);
756        }
757    }
758
759    public void disable(int state) {
760        int old = mDisabled;
761        int diff = state ^ old;
762        mDisabled = state;
763
764        // act accordingly
765        if ((diff & StatusBarManager.DISABLE_CLOCK) != 0) {
766            boolean show = (state & StatusBarManager.DISABLE_CLOCK) == 0;
767            Slog.i(TAG, "DISABLE_CLOCK: " + (show ? "no" : "yes"));
768            showClock(show);
769        }
770        if ((diff & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) {
771            boolean show = (state & StatusBarManager.DISABLE_SYSTEM_INFO) == 0;
772            Slog.i(TAG, "DISABLE_SYSTEM_INFO: " + (show ? "no" : "yes"));
773            mNotificationTrigger.setVisibility(show ? View.VISIBLE : View.GONE);
774        }
775        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
776            if ((state & StatusBarManager.DISABLE_EXPAND) != 0) {
777                Slog.i(TAG, "DISABLE_EXPAND: yes");
778                animateCollapse();
779            }
780        }
781        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
782            if ((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
783                Slog.i(TAG, "DISABLE_NOTIFICATION_ICONS: yes");
784                // synchronize with current shadow state
785                mNotificationIconArea.setVisibility(View.GONE);
786                mTicker.halt();
787            } else {
788                Slog.i(TAG, "DISABLE_NOTIFICATION_ICONS: no");
789                // synchronize with current shadow state
790                mNotificationIconArea.setVisibility(View.VISIBLE);
791            }
792        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
793            if ((state & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
794                mTicker.halt();
795            }
796        }
797        if ((diff & StatusBarManager.DISABLE_NAVIGATION) != 0) {
798            if ((state & StatusBarManager.DISABLE_NAVIGATION) != 0) {
799                Slog.i(TAG, "DISABLE_NAVIGATION: yes");
800                mNavigationArea.setVisibility(View.GONE);
801                mInputMethodSwitchButton.setScreenLocked(true);
802            } else {
803                Slog.i(TAG, "DISABLE_NAVIGATION: no");
804                mNavigationArea.setVisibility(View.VISIBLE);
805                mInputMethodSwitchButton.setScreenLocked(false);
806            }
807        }
808        if ((diff & StatusBarManager.DISABLE_BACK) != 0) {
809            if ((state & StatusBarManager.DISABLE_BACK) != 0) {
810                Slog.i(TAG, "DISABLE_BACK: yes");
811                mBackButton.setVisibility(View.INVISIBLE);
812                mInputMethodSwitchButton.setScreenLocked(true);
813            } else {
814                Slog.i(TAG, "DISABLE_BACK: no");
815                mBackButton.setVisibility(View.VISIBLE);
816                mInputMethodSwitchButton.setScreenLocked(false);
817            }
818        }
819
820    }
821
822    private boolean hasTicker(Notification n) {
823        return n.tickerView != null || !TextUtils.isEmpty(n.tickerText);
824    }
825
826    private void tick(IBinder key, StatusBarNotification n, boolean firstTime) {
827        // Don't show the ticker when the windowshade is open.
828        if (mNotificationPanel.isShowing()) {
829            return;
830        }
831        // If they asked for FLAG_ONLY_ALERT_ONCE, then only show this notification
832        // if it's a new notification.
833        if (!firstTime && (n.notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0) {
834            return;
835        }
836        // Show the ticker if one is requested. Also don't do this
837        // until status bar window is attached to the window manager,
838        // because...  well, what's the point otherwise?  And trying to
839        // run a ticker without being attached will crash!
840        if (hasTicker(n.notification) && mStatusBarView.getWindowToken() != null) {
841            if (0 == (mDisabled & (StatusBarManager.DISABLE_NOTIFICATION_ICONS
842                            | StatusBarManager.DISABLE_NOTIFICATION_TICKER))) {
843                mTicker.add(key, n);
844                mNotificationAndImeArea.setVisibility(View.GONE);
845            }
846        }
847    }
848
849    // called by TabletTicker when it's done with all queued ticks
850    public void doneTicking() {
851        mNotificationAndImeArea.setVisibility(View.VISIBLE);
852    }
853
854    public void animateExpand() {
855        mHandler.removeMessages(MSG_OPEN_NOTIFICATION_PANEL);
856        mHandler.sendEmptyMessage(MSG_OPEN_NOTIFICATION_PANEL);
857    }
858
859    public void animateCollapse() {
860        mHandler.removeMessages(MSG_CLOSE_NOTIFICATION_PANEL);
861        mHandler.sendEmptyMessage(MSG_CLOSE_NOTIFICATION_PANEL);
862        mHandler.removeMessages(MSG_CLOSE_RECENTS_PANEL);
863        mHandler.sendEmptyMessage(MSG_CLOSE_RECENTS_PANEL);
864        mHandler.removeMessages(MSG_CLOSE_INPUT_METHODS_PANEL);
865        mHandler.sendEmptyMessage(MSG_CLOSE_INPUT_METHODS_PANEL);
866    }
867
868    // called by StatusBar
869    @Override
870    public void setLightsOn(boolean on) {
871        // Policy note: if the frontmost activity needs the menu key, we assume it is a legacy app
872        // that can't handle lights-out mode.
873        if (mMenuButton.getVisibility() == View.VISIBLE) {
874            on = true;
875        }
876        mHandler.removeMessages(MSG_HIDE_CHROME);
877        mHandler.removeMessages(MSG_SHOW_CHROME);
878        mHandler.sendEmptyMessage(on ? MSG_SHOW_CHROME : MSG_HIDE_CHROME);
879    }
880
881    public void setMenuKeyVisible(boolean visible) {
882        if (DEBUG) {
883            Slog.d(TAG, (visible?"showing":"hiding") + " the MENU button");
884        }
885        mMenuButton.setVisibility(visible ? View.VISIBLE : View.GONE);
886
887        // See above re: lights-out policy for legacy apps.
888        if (visible) setLightsOn(true);
889    }
890
891    public void setImeWindowStatus(IBinder token, int vis, int backDisposition) {
892        mInputMethodSwitchButton.setImeWindowStatus(token,
893                (vis & InputMethodService.IME_ACTIVE) != 0);
894        updateNotificationIcons();
895        mInputMethodsPanel.setImeToken(token);
896        int res;
897        switch (backDisposition) {
898            case InputMethodService.BACK_DISPOSITION_WILL_NOT_DISMISS:
899                res = R.drawable.ic_sysbar_back;
900                break;
901            case InputMethodService.BACK_DISPOSITION_WILL_DISMISS:
902                res = R.drawable.ic_sysbar_back_ime;
903                break;
904            case InputMethodService.BACK_DISPOSITION_DEFAULT:
905            default:
906                if ((vis & InputMethodService.IME_VISIBLE) != 0) {
907                    res = R.drawable.ic_sysbar_back_ime;
908                } else {
909                    res = R.drawable.ic_sysbar_back;
910                }
911                break;
912        }
913        mBackButton.setImageResource(res);
914        if (FAKE_SPACE_BAR) {
915            mFakeSpaceBar.setVisibility(((vis & InputMethodService.IME_VISIBLE) != 0)
916                    ? View.VISIBLE : View.GONE);
917        }
918    }
919
920    @Override
921    public void setHardKeyboardStatus(boolean available, boolean enabled) {
922        if (DEBUG) {
923            Slog.d(TAG, "Set hard keyboard status: available=" + available
924                    + ", enabled=" + enabled);
925        }
926        mInputMethodSwitchButton.setHardKeyboardStatus(available);
927        updateNotificationIcons();
928        mInputMethodsPanel.setHardKeyboardStatus(available, enabled);
929    }
930
931    @Override
932    public void onHardKeyboardEnabledChange(boolean enabled) {
933        try {
934            mBarService.setHardKeyboardEnabled(enabled);
935        } catch (RemoteException ex) {
936        }
937    }
938
939    private boolean isImmersive() {
940        try {
941            return ActivityManagerNative.getDefault().isTopActivityImmersive();
942            //Slog.d(TAG, "Top activity is " + (immersive?"immersive":"not immersive"));
943        } catch (RemoteException ex) {
944            // the end is nigh
945            return false;
946        }
947    }
948
949    private void setAreThereNotifications() {
950        final boolean hasClearable = mNotns.hasClearableItems();
951    }
952
953    /**
954     * Cancel this notification and tell the status bar service about the failure. Hold no locks.
955     */
956    void handleNotificationError(IBinder key, StatusBarNotification n, String message) {
957        removeNotification(key);
958        try {
959            mBarService.onNotificationError(n.pkg, n.tag, n.id, n.uid, n.initialPid, message);
960        } catch (RemoteException ex) {
961            // The end is nigh.
962        }
963    }
964
965    private void sendKey(KeyEvent key) {
966        try {
967            if (DEBUG) Slog.d(TAG, "injecting key event: " + key);
968            mWindowManager.injectInputEventNoWait(key);
969        } catch (RemoteException ex) {
970        }
971    }
972
973    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
974        public void onClick(View v) {
975            if (v == mNotificationTrigger) {
976                onClickNotificationTrigger();
977            } else if (v == mRecentButton) {
978                onClickRecentButton();
979            } else if (v == mInputMethodSwitchButton) {
980                onClickInputMethodSwitchButton();
981            }
982        }
983    };
984
985    public void onClickNotificationTrigger() {
986        if (DEBUG) Slog.d(TAG, "clicked notification icons; disabled=" + mDisabled);
987        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) == 0) {
988            if (!mNotificationsOn) {
989                mNotificationsOn = true;
990                mIconLayout.setVisibility(View.VISIBLE); // TODO: animation
991            } else {
992                int msg = !mNotificationPanel.isShowing()
993                    ? MSG_OPEN_NOTIFICATION_PANEL
994                    : MSG_CLOSE_NOTIFICATION_PANEL;
995                mHandler.removeMessages(msg);
996                mHandler.sendEmptyMessage(msg);
997            }
998        }
999    }
1000
1001    public void onClickRecentButton() {
1002        if (DEBUG) Slog.d(TAG, "clicked recent apps; disabled=" + mDisabled);
1003        if (mRecentsPanel == null) {
1004            Intent intent = new Intent();
1005            intent.setClass(mContext, RecentApplicationsActivity.class);
1006            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1007                    | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1008            mContext.startActivity(intent);
1009        } else {
1010            if ((mDisabled & StatusBarManager.DISABLE_EXPAND) == 0) {
1011                int msg = (mRecentsPanel.getVisibility() == View.GONE)
1012                    ? MSG_OPEN_RECENTS_PANEL
1013                    : MSG_CLOSE_RECENTS_PANEL;
1014                mHandler.removeMessages(msg);
1015                mHandler.sendEmptyMessage(msg);
1016            }
1017        }
1018    }
1019
1020    public void onClickInputMethodSwitchButton() {
1021        if (DEBUG) Slog.d(TAG, "clicked input methods panel; disabled=" + mDisabled);
1022        int msg = (mInputMethodsPanel.getVisibility() == View.GONE) ?
1023                MSG_OPEN_INPUT_METHODS_PANEL : MSG_CLOSE_INPUT_METHODS_PANEL;
1024        mHandler.removeMessages(msg);
1025        mHandler.sendEmptyMessage(msg);
1026    }
1027
1028    public NotificationClicker makeClicker(PendingIntent intent, String pkg, String tag, int id) {
1029        return new NotificationClicker(intent, pkg, tag, id);
1030    }
1031
1032    private class NotificationClicker implements View.OnClickListener {
1033        private PendingIntent mIntent;
1034        private String mPkg;
1035        private String mTag;
1036        private int mId;
1037
1038        NotificationClicker(PendingIntent intent, String pkg, String tag, int id) {
1039            mIntent = intent;
1040            mPkg = pkg;
1041            mTag = tag;
1042            mId = id;
1043        }
1044
1045        public void onClick(View v) {
1046            try {
1047                // The intent we are sending is for the application, which
1048                // won't have permission to immediately start an activity after
1049                // the user switches to home.  We know it is safe to do at this
1050                // point, so make sure new activity switches are now allowed.
1051                ActivityManagerNative.getDefault().resumeAppSwitches();
1052            } catch (RemoteException e) {
1053            }
1054
1055            if (mIntent != null) {
1056                int[] pos = new int[2];
1057                v.getLocationOnScreen(pos);
1058                Intent overlay = new Intent();
1059                overlay.setSourceBounds(
1060                        new Rect(pos[0], pos[1], pos[0]+v.getWidth(), pos[1]+v.getHeight()));
1061                try {
1062                    mIntent.send(mContext, 0, overlay);
1063                } catch (PendingIntent.CanceledException e) {
1064                    // the stack trace isn't very helpful here.  Just log the exception message.
1065                    Slog.w(TAG, "Sending contentIntent failed: " + e);
1066                }
1067            }
1068
1069            try {
1070                mBarService.onNotificationClick(mPkg, mTag, mId);
1071            } catch (RemoteException ex) {
1072                // system process is dead if we're here.
1073            }
1074
1075            // close the shade if it was open
1076            animateCollapse();
1077
1078            // If this click was on the intruder alert, hide that instead
1079//            mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
1080        }
1081    }
1082
1083    StatusBarNotification removeNotificationViews(IBinder key) {
1084        NotificationData.Entry entry = mNotns.remove(key);
1085        if (entry == null) {
1086            Slog.w(TAG, "removeNotification for unknown key: " + key);
1087            return null;
1088        }
1089        // Remove the expanded view.
1090        ViewGroup rowParent = (ViewGroup)entry.row.getParent();
1091        if (rowParent != null) rowParent.removeView(entry.row);
1092
1093        if (key == mNotificationPeekKey) {
1094            // must close the peek as well, since it's gone
1095            mHandler.sendEmptyMessage(MSG_CLOSE_NOTIFICATION_PEEK);
1096        }
1097        // Remove the icon.
1098//        ViewGroup iconParent = (ViewGroup)entry.icon.getParent();
1099//        if (iconParent != null) iconParent.removeView(entry.icon);
1100        updateNotificationIcons();
1101
1102        return entry.notification;
1103    }
1104
1105    private class NotificationIconTouchListener implements View.OnTouchListener {
1106        VelocityTracker mVT;
1107
1108        public NotificationIconTouchListener() {
1109        }
1110
1111        public boolean onTouch(View v, MotionEvent event) {
1112            boolean peeking = mNotificationPeekWindow.getVisibility() != View.GONE;
1113            boolean panelShowing = mNotificationPanel.isShowing();
1114            if (panelShowing) return false;
1115
1116            switch (event.getAction()) {
1117                case MotionEvent.ACTION_DOWN:
1118                    mVT = VelocityTracker.obtain();
1119
1120                    // fall through
1121                case MotionEvent.ACTION_OUTSIDE:
1122                case MotionEvent.ACTION_MOVE:
1123                    // peek and switch icons if necessary
1124                    int numIcons = mIconLayout.getChildCount();
1125                    int peekIndex = (int)((float)event.getX() * numIcons / mIconLayout.getWidth());
1126                    if (peekIndex > numIcons - 1) peekIndex = numIcons - 1;
1127                    else if (peekIndex < 0) peekIndex = 0;
1128
1129                    if (!peeking || mNotificationPeekIndex != peekIndex) {
1130                        if (DEBUG) Slog.d(TAG, "will peek at notification #" + peekIndex);
1131                        Message peekMsg = mHandler.obtainMessage(MSG_OPEN_NOTIFICATION_PEEK);
1132                        peekMsg.arg1 = peekIndex;
1133
1134                        mHandler.removeMessages(MSG_OPEN_NOTIFICATION_PEEK);
1135
1136                        // no delay if we're scrubbing left-right
1137                        mHandler.sendMessage(peekMsg);
1138                    }
1139
1140                    // check for fling
1141                    if (mVT != null) {
1142                        mVT.addMovement(event);
1143                        mVT.computeCurrentVelocity(1000);
1144                        // require a little more oomph once we're already in peekaboo mode
1145                        if (!panelShowing && (
1146                               (peeking && mVT.getYVelocity() < -mNotificationFlingVelocity*3)
1147                            || (mVT.getYVelocity() < -mNotificationFlingVelocity))) {
1148                            mHandler.removeMessages(MSG_OPEN_NOTIFICATION_PEEK);
1149                            mHandler.removeMessages(MSG_OPEN_NOTIFICATION_PANEL);
1150                            mHandler.sendEmptyMessage(MSG_CLOSE_NOTIFICATION_PEEK);
1151                            mHandler.sendEmptyMessage(MSG_OPEN_NOTIFICATION_PANEL);
1152                        }
1153                    }
1154                    return true;
1155                case MotionEvent.ACTION_UP:
1156                case MotionEvent.ACTION_CANCEL:
1157                    mHandler.removeMessages(MSG_OPEN_NOTIFICATION_PEEK);
1158                    if (peeking) {
1159                        mHandler.sendEmptyMessageDelayed(MSG_CLOSE_NOTIFICATION_PEEK, 5000);
1160                    }
1161                    mVT.recycle();
1162                    mVT = null;
1163                    return true;
1164            }
1165            return false;
1166        }
1167    }
1168
1169    StatusBarIconView addNotificationViews(IBinder key, StatusBarNotification notification) {
1170        if (DEBUG) {
1171            Slog.d(TAG, "addNotificationViews(key=" + key + ", notification=" + notification);
1172        }
1173        // Construct the icon.
1174        final StatusBarIconView iconView = new StatusBarIconView(mContext,
1175                notification.pkg + "/0x" + Integer.toHexString(notification.id));
1176        iconView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
1177
1178        final StatusBarIcon ic = new StatusBarIcon(notification.pkg,
1179                    notification.notification.icon,
1180                    notification.notification.iconLevel,
1181                    notification.notification.number);
1182        if (!iconView.set(ic)) {
1183            handleNotificationError(key, notification, "Couldn't attach StatusBarIcon: " + ic);
1184            return null;
1185        }
1186        // Construct the expanded view.
1187        NotificationData.Entry entry = new NotificationData.Entry(key, notification, iconView);
1188        if (!inflateViews(entry, mPile)) {
1189            handleNotificationError(key, notification, "Couldn't expand RemoteViews for: "
1190                    + notification);
1191            return null;
1192        }
1193
1194        // Add the icon.
1195        int pos = mNotns.add(entry);
1196        if (DEBUG) {
1197            Slog.d(TAG, "addNotificationViews: added at " + pos);
1198        }
1199        updateNotificationIcons();
1200
1201        return iconView;
1202    }
1203
1204    private void reloadAllNotificationIcons() {
1205        if (mIconLayout == null) return;
1206        mIconLayout.removeAllViews();
1207        updateNotificationIcons();
1208    }
1209
1210    private void updateNotificationIcons() {
1211        // XXX: need to implement a new limited linear layout class
1212        // to avoid removing & readding everything
1213
1214        if (mIconLayout == null) return;
1215
1216        final LinearLayout.LayoutParams params
1217            = new LinearLayout.LayoutParams(mIconSize + 2*mIconHPadding, mNaturalBarHeight);
1218
1219        int N = mNotns.size();
1220
1221        if (DEBUG) {
1222            Slog.d(TAG, "refreshing icons: " + N + " notifications, mIconLayout=" + mIconLayout);
1223        }
1224
1225        ArrayList<View> toShow = new ArrayList<View>();
1226
1227        // When IME button is visible, the number of notification icons should be decremented
1228        // to fit the upper limit.
1229        final int maxNotificationIconsCount =
1230                (mInputMethodSwitchButton.getVisibility() != View.GONE) ?
1231                        MAX_NOTIFICATION_ICONS_IME_BUTTON_VISIBLE : MAX_NOTIFICATION_ICONS;
1232        for (int i=0; i< maxNotificationIconsCount; i++) {
1233            if (i>=N) break;
1234            toShow.add(mNotns.get(N-i-1).icon);
1235        }
1236
1237        ArrayList<View> toRemove = new ArrayList<View>();
1238        for (int i=0; i<mIconLayout.getChildCount(); i++) {
1239            View child = mIconLayout.getChildAt(i);
1240            if (!toShow.contains(child)) {
1241                toRemove.add(child);
1242            }
1243        }
1244
1245        for (View remove : toRemove) {
1246            mIconLayout.removeView(remove);
1247        }
1248
1249        for (int i=0; i<toShow.size(); i++) {
1250            View v = toShow.get(i);
1251            v.setPadding(mIconHPadding, 0, mIconHPadding, 0);
1252            if (v.getParent() == null) {
1253                mIconLayout.addView(v, i, params);
1254            }
1255        }
1256
1257        loadNotificationPanel();
1258    }
1259
1260    private void loadNotificationPanel() {
1261        int N = mNotns.size();
1262
1263        ArrayList<View> toShow = new ArrayList<View>();
1264
1265        for (int i=0; i<N; i++) {
1266            View row = mNotns.get(N-i-1).row;
1267            toShow.add(row);
1268        }
1269
1270        ArrayList<View> toRemove = new ArrayList<View>();
1271        for (int i=0; i<mPile.getChildCount(); i++) {
1272            View child = mPile.getChildAt(i);
1273            if (!toShow.contains(child)) {
1274                toRemove.add(child);
1275            }
1276        }
1277
1278        for (View remove : toRemove) {
1279            mPile.removeView(remove);
1280        }
1281
1282        for (int i=0; i<toShow.size(); i++) {
1283            View v = toShow.get(i);
1284            if (v.getParent() == null) {
1285                mPile.addView(v, N-1-i); // the notification panel has newest at the bottom
1286            }
1287        }
1288
1289        mNotificationPanel.setNotificationCount(N);
1290    }
1291
1292    void workAroundBadLayerDrawableOpacity(View v) {
1293        LayerDrawable d = (LayerDrawable)v.getBackground();
1294        if (d == null) return;
1295        v.setBackgroundDrawable(null);
1296        d.setOpacity(PixelFormat.TRANSLUCENT);
1297        v.setBackgroundDrawable(d);
1298    }
1299
1300    private boolean inflateViews(NotificationData.Entry entry, ViewGroup parent) {
1301        StatusBarNotification sbn = entry.notification;
1302        RemoteViews remoteViews = sbn.notification.contentView;
1303        if (remoteViews == null) {
1304            return false;
1305        }
1306
1307        // create the row view
1308        LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(
1309                Context.LAYOUT_INFLATER_SERVICE);
1310        View row = inflater.inflate(R.layout.status_bar_notification_row, parent, false);
1311        workAroundBadLayerDrawableOpacity(row);
1312        View vetoButton = row.findViewById(R.id.veto);
1313        if (entry.notification.isClearable()) {
1314            final String _pkg = sbn.pkg;
1315            final String _tag = sbn.tag;
1316            final int _id = sbn.id;
1317            vetoButton.setOnClickListener(new View.OnClickListener() {
1318                    public void onClick(View v) {
1319                        try {
1320                            mBarService.onNotificationClear(_pkg, _tag, _id);
1321                        } catch (RemoteException ex) {
1322                            // system process is dead if we're here.
1323                        }
1324                    }
1325                });
1326        } else {
1327            if ((sbn.notification.flags & Notification.FLAG_ONGOING_EVENT) == 0) {
1328                vetoButton.setVisibility(View.INVISIBLE);
1329            } else {
1330                vetoButton.setVisibility(View.GONE);
1331            }
1332        }
1333
1334        // the large icon
1335        ImageView largeIcon = (ImageView)row.findViewById(R.id.large_icon);
1336        if (sbn.notification.largeIcon != null) {
1337            largeIcon.setImageBitmap(sbn.notification.largeIcon);
1338        } else {
1339            largeIcon.getLayoutParams().width = 0;
1340            largeIcon.setVisibility(View.INVISIBLE);
1341        }
1342
1343        // bind the click event to the content area
1344        ViewGroup content = (ViewGroup)row.findViewById(R.id.content);
1345        // XXX: update to allow controls within notification views
1346        content.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
1347//        content.setOnFocusChangeListener(mFocusChangeListener);
1348        PendingIntent contentIntent = sbn.notification.contentIntent;
1349        if (contentIntent != null) {
1350            content.setOnClickListener(new NotificationClicker(contentIntent,
1351                        sbn.pkg, sbn.tag, sbn.id));
1352        } else {
1353            content.setOnClickListener(null);
1354        }
1355
1356        View expanded = null;
1357        Exception exception = null;
1358        try {
1359            expanded = remoteViews.apply(mContext, content);
1360        }
1361        catch (RuntimeException e) {
1362            exception = e;
1363        }
1364        if (expanded == null) {
1365            final String ident = sbn.pkg + "/0x" + Integer.toHexString(sbn.id);
1366            Slog.e(TAG, "couldn't inflate view for notification " + ident, exception);
1367            return false;
1368        } else {
1369            content.addView(expanded);
1370            row.setDrawingCacheEnabled(true);
1371        }
1372
1373        entry.row = row;
1374        entry.content = content;
1375        entry.expanded = expanded;
1376        entry.largeIcon = largeIcon;
1377
1378        return true;
1379    }
1380
1381/*
1382    public class ShadowController {
1383        boolean mShowShadows;
1384        Map<View, View> mShadowsForElements = new IdentityHashMap<View, View>(7);
1385        Map<View, View> mElementsForShadows = new IdentityHashMap<View, View>(7);
1386        LayoutTransition mElementTransition, mShadowTransition;
1387
1388        View mTouchTarget;
1389
1390        ShadowController(boolean showShadows) {
1391            mShowShadows = showShadows;
1392            mTouchTarget = null;
1393
1394            mElementTransition = new LayoutTransition();
1395//            AnimatorSet s = new AnimatorSet();
1396//            s.play(ObjectAnimator.ofInt(null, "top", 48, 0))
1397//                .with(ObjectAnimator.ofFloat(null, "scaleY", 0.5f, 1f))
1398//                .with(ObjectAnimator.ofFloat(null, "alpha", 0.5f, 1f))
1399//                ;
1400            mElementTransition.setAnimator(LayoutTransition.APPEARING, //s);
1401                   ObjectAnimator.ofInt(null, "top", 48, 0));
1402            mElementTransition.setDuration(LayoutTransition.APPEARING, 100);
1403            mElementTransition.setStartDelay(LayoutTransition.APPEARING, 0);
1404
1405//            s = new AnimatorSet();
1406//            s.play(ObjectAnimator.ofInt(null, "top", 0, 48))
1407//                .with(ObjectAnimator.ofFloat(null, "scaleY", 1f, 0.5f))
1408//                .with(ObjectAnimator.ofFloat(null, "alpha", 1f, 0.5f))
1409//                ;
1410            mElementTransition.setAnimator(LayoutTransition.DISAPPEARING, //s);
1411                    ObjectAnimator.ofInt(null, "top", 0, 48));
1412            mElementTransition.setDuration(LayoutTransition.DISAPPEARING, 400);
1413
1414            mShadowTransition = new LayoutTransition();
1415            mShadowTransition.setAnimator(LayoutTransition.APPEARING,
1416                    ObjectAnimator.ofFloat(null, "alpha", 0f, 1f));
1417            mShadowTransition.setDuration(LayoutTransition.APPEARING, 200);
1418            mShadowTransition.setStartDelay(LayoutTransition.APPEARING, 100);
1419            mShadowTransition.setAnimator(LayoutTransition.DISAPPEARING,
1420                    ObjectAnimator.ofFloat(null, "alpha", 1f, 0f));
1421            mShadowTransition.setDuration(LayoutTransition.DISAPPEARING, 100);
1422
1423            ViewGroup bar = (ViewGroup) TabletStatusBar.this.mBarContents;
1424            bar.setLayoutTransition(mElementTransition);
1425            ViewGroup nav = (ViewGroup) TabletStatusBar.this.mNavigationArea;
1426            nav.setLayoutTransition(mElementTransition);
1427            ViewGroup shadowGroup = (ViewGroup) bar.findViewById(R.id.shadows);
1428            shadowGroup.setLayoutTransition(mShadowTransition);
1429        }
1430
1431        public void add(View element, View shadow) {
1432            shadow.setOnTouchListener(makeTouchListener());
1433            mShadowsForElements.put(element, shadow);
1434            mElementsForShadows.put(shadow, element);
1435        }
1436
1437        public boolean getShadowState() {
1438            return mShowShadows;
1439        }
1440
1441        public View.OnTouchListener makeTouchListener() {
1442            return new View.OnTouchListener() {
1443                public boolean onTouch(View v, MotionEvent ev) {
1444                    final int action = ev.getAction();
1445
1446                    if (DEBUG) Slog.d(TAG, "ShadowController: v=" + v + ", ev=" + ev);
1447
1448                    // currently redirecting events?
1449                    if (mTouchTarget == null) {
1450                        mTouchTarget = mElementsForShadows.get(v);
1451                    }
1452
1453                    if (mTouchTarget != null && mTouchTarget.getVisibility() != View.GONE) {
1454                        boolean last = false;
1455                        switch (action) {
1456                            case MotionEvent.ACTION_CANCEL:
1457                            case MotionEvent.ACTION_UP:
1458                                mHandler.removeMessages(MSG_RESTORE_SHADOWS);
1459                                if (mShowShadows) {
1460                                    mHandler.sendEmptyMessageDelayed(MSG_RESTORE_SHADOWS,
1461                                            v == mNotificationShadow ? 5000 : 500);
1462                                }
1463                                last = true;
1464                                break;
1465                            case MotionEvent.ACTION_DOWN:
1466                                mHandler.removeMessages(MSG_RESTORE_SHADOWS);
1467                                setElementShadow(mTouchTarget, false);
1468                                break;
1469                        }
1470                        mTouchTarget.dispatchTouchEvent(ev);
1471                        if (last) mTouchTarget = null;
1472                        return true;
1473                    }
1474
1475                    return false;
1476                }
1477            };
1478        }
1479
1480        public void refresh() {
1481            for (View element : mShadowsForElements.keySet()) {
1482                setElementShadow(element, mShowShadows);
1483            }
1484        }
1485
1486        public void showAllShadows() {
1487            mShowShadows = true;
1488            refresh();
1489        }
1490
1491        public void hideAllShadows() {
1492            mShowShadows = false;
1493            refresh();
1494        }
1495
1496        // Use View.INVISIBLE for things hidden due to shadowing, and View.GONE for things that are
1497        // disabled (and should not be shadowed or re-shown)
1498        public void setElementShadow(View button, boolean shade) {
1499            View shadow = mShadowsForElements.get(button);
1500            if (shadow != null) {
1501                if (button.getVisibility() != View.GONE) {
1502                    shadow.setVisibility(shade ? View.VISIBLE : View.INVISIBLE);
1503                    button.setVisibility(shade ? View.INVISIBLE : View.VISIBLE);
1504                }
1505            }
1506        }
1507
1508        // Hide both element and shadow, using default layout animations.
1509        public void hideElement(View button) {
1510            Slog.d(TAG, "hiding: " + button);
1511            View shadow = mShadowsForElements.get(button);
1512            if (shadow != null) {
1513                shadow.setVisibility(View.GONE);
1514            }
1515            button.setVisibility(View.GONE);
1516        }
1517
1518        // Honoring the current shadow state.
1519        public void showElement(View button) {
1520            Slog.d(TAG, "showing: " + button);
1521            View shadow = mShadowsForElements.get(button);
1522            if (shadow != null) {
1523                shadow.setVisibility(mShowShadows ? View.VISIBLE : View.INVISIBLE);
1524            }
1525            button.setVisibility(mShowShadows ? View.INVISIBLE : View.VISIBLE);
1526        }
1527    }
1528    */
1529
1530    public class TouchOutsideListener implements View.OnTouchListener {
1531        private int mMsg;
1532        private StatusBarPanel mPanel;
1533
1534        public TouchOutsideListener(int msg, StatusBarPanel panel) {
1535            mMsg = msg;
1536            mPanel = panel;
1537        }
1538
1539        public boolean onTouch(View v, MotionEvent ev) {
1540            final int action = ev.getAction();
1541            if (action == MotionEvent.ACTION_OUTSIDE
1542                    || (action == MotionEvent.ACTION_DOWN
1543                        && !mPanel.isInContentArea((int)ev.getX(), (int)ev.getY()))) {
1544                mHandler.removeMessages(mMsg);
1545                mHandler.sendEmptyMessage(mMsg);
1546                return true;
1547            }
1548            return false;
1549        }
1550    }
1551
1552    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1553        pw.print("mDisabled=0x");
1554        pw.println(Integer.toHexString(mDisabled));
1555        pw.println("mNetworkController:");
1556        mNetworkController.dump(fd, pw, args);
1557    }
1558}
1559
1560
1561