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