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