BaseStatusBar.java revision 12cdec9b940b8488e2a4e98c89ba0a359c082669
1
2/*
3 * Copyright (C) 2010 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.systemui.statusbar;
19
20import android.content.res.Configuration;
21import com.android.internal.statusbar.IStatusBarService;
22import com.android.internal.statusbar.StatusBarIcon;
23import com.android.internal.statusbar.StatusBarIconList;
24import com.android.internal.statusbar.StatusBarNotification;
25import com.android.internal.widget.SizeAdaptiveLayout;
26import com.android.systemui.R;
27import com.android.systemui.SearchPanelView;
28import com.android.systemui.SystemUI;
29import com.android.systemui.recent.RecentTasksLoader;
30import com.android.systemui.recent.RecentsActivity;
31import com.android.systemui.recent.TaskDescription;
32import com.android.systemui.statusbar.policy.NotificationRowLayout;
33import com.android.systemui.statusbar.tablet.StatusBarPanel;
34
35import android.app.ActivityManager;
36import android.app.ActivityManagerNative;
37import android.app.ActivityOptions;
38import android.app.KeyguardManager;
39import android.app.PendingIntent;
40import android.app.TaskStackBuilder;
41import android.content.ActivityNotFoundException;
42import android.content.BroadcastReceiver;
43import android.content.Context;
44import android.content.Intent;
45import android.content.IntentFilter;
46import android.content.pm.ApplicationInfo;
47import android.content.pm.PackageManager.NameNotFoundException;
48import android.content.res.Resources;
49import android.database.ContentObserver;
50import android.graphics.Bitmap;
51import android.graphics.Paint;
52import android.graphics.Rect;
53import android.net.Uri;
54import android.os.Build;
55import android.os.Handler;
56import android.os.IBinder;
57import android.os.Message;
58import android.os.RemoteException;
59import android.os.ServiceManager;
60import android.os.UserHandle;
61import android.provider.Settings;
62import android.text.TextUtils;
63import android.util.DisplayMetrics;
64import android.util.Log;
65import android.util.Slog;
66import android.view.Display;
67import android.view.IWindowManager;
68import android.view.LayoutInflater;
69import android.view.MenuItem;
70import android.view.MotionEvent;
71import android.view.View;
72import android.view.ViewGroup;
73import android.view.ViewGroup.LayoutParams;
74import android.view.WindowManager;
75import android.view.WindowManagerGlobal;
76import android.widget.ImageView;
77import android.widget.LinearLayout;
78import android.widget.PopupMenu;
79import android.widget.RemoteViews;
80import android.widget.TextView;
81
82import java.util.ArrayList;
83import java.util.Locale;
84
85public abstract class BaseStatusBar extends SystemUI implements
86        CommandQueue.Callbacks {
87    public static final String TAG = "StatusBar";
88    public static final boolean DEBUG = false;
89    public static final boolean MULTIUSER_DEBUG = false;
90
91    protected static final int MSG_TOGGLE_RECENTS_PANEL = 1020;
92    protected static final int MSG_CLOSE_RECENTS_PANEL = 1021;
93    protected static final int MSG_PRELOAD_RECENT_APPS = 1022;
94    protected static final int MSG_CANCEL_PRELOAD_RECENT_APPS = 1023;
95    protected static final int MSG_OPEN_SEARCH_PANEL = 1024;
96    protected static final int MSG_CLOSE_SEARCH_PANEL = 1025;
97    protected static final int MSG_SHOW_INTRUDER = 1026;
98    protected static final int MSG_HIDE_INTRUDER = 1027;
99
100    protected static final boolean ENABLE_INTRUDERS = false;
101
102    // Should match the value in PhoneWindowManager
103    public static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
104
105    public static final int EXPANDED_LEAVE_ALONE = -10000;
106    public static final int EXPANDED_FULL_OPEN = -10001;
107
108    protected CommandQueue mCommandQueue;
109    protected IStatusBarService mBarService;
110    protected H mHandler = createHandler();
111
112    // all notifications
113    protected NotificationData mNotificationData = new NotificationData();
114    protected NotificationRowLayout mPile;
115
116    protected StatusBarNotification mCurrentlyIntrudingNotification;
117
118    // used to notify status bar for suppressing notification LED
119    protected boolean mPanelSlightlyVisible;
120
121    // Search panel
122    protected SearchPanelView mSearchPanelView;
123
124    protected PopupMenu mNotificationBlamePopup;
125
126    protected int mCurrentUserId = 0;
127
128    protected int mLayoutDirection;
129    private Locale mLocale;
130
131    // UI-specific methods
132
133    /**
134     * Create all windows necessary for the status bar (including navigation, overlay panels, etc)
135     * and add them to the window manager.
136     */
137    protected abstract void createAndAddWindows();
138
139    protected WindowManager mWindowManager;
140    protected IWindowManager mWindowManagerService;
141    protected abstract void refreshLayout(int layoutDirection);
142
143    protected Display mDisplay;
144
145    private boolean mDeviceProvisioned = false;
146
147    public IStatusBarService getStatusBarService() {
148        return mBarService;
149    }
150
151    public boolean isDeviceProvisioned() {
152        return mDeviceProvisioned;
153    }
154
155    private ContentObserver mProvisioningObserver = new ContentObserver(new Handler()) {
156        @Override
157        public void onChange(boolean selfChange) {
158            final boolean provisioned = 0 != Settings.Global.getInt(
159                    mContext.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0);
160            if (provisioned != mDeviceProvisioned) {
161                mDeviceProvisioned = provisioned;
162                updateNotificationIcons();
163            }
164        }
165    };
166
167    private RemoteViews.OnClickHandler mOnClickHandler = new RemoteViews.OnClickHandler() {
168        @Override
169        public boolean onClickHandler(View view, PendingIntent pendingIntent, Intent fillInIntent) {
170            if (DEBUG) {
171                Slog.v(TAG, "Notification click handler invoked for intent: " + pendingIntent);
172            }
173            final boolean isActivity = pendingIntent.isActivity();
174            if (isActivity) {
175                try {
176                    // The intent we are sending is for the application, which
177                    // won't have permission to immediately start an activity after
178                    // the user switches to home.  We know it is safe to do at this
179                    // point, so make sure new activity switches are now allowed.
180                    ActivityManagerNative.getDefault().resumeAppSwitches();
181                    // Also, notifications can be launched from the lock screen,
182                    // so dismiss the lock screen when the activity starts.
183                    ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
184                } catch (RemoteException e) {
185                }
186            }
187
188            boolean handled = super.onClickHandler(view, pendingIntent, fillInIntent);
189
190            if (isActivity && handled) {
191                // close the shade if it was open
192                animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
193                visibilityChanged(false);
194            }
195            return handled;
196        }
197    };
198
199    public void start() {
200        mWindowManager = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
201        mWindowManagerService = WindowManagerGlobal.getWindowManagerService();
202        mDisplay = mWindowManager.getDefaultDisplay();
203
204        mProvisioningObserver.onChange(false); // set up
205        mContext.getContentResolver().registerContentObserver(
206                Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), true,
207                mProvisioningObserver);
208
209        mBarService = IStatusBarService.Stub.asInterface(
210                ServiceManager.getService(Context.STATUS_BAR_SERVICE));
211
212        mLocale = mContext.getResources().getConfiguration().locale;
213        mLayoutDirection = TextUtils.getLayoutDirectionFromLocale(mLocale);
214
215        // Connect in to the status bar manager service
216        StatusBarIconList iconList = new StatusBarIconList();
217        ArrayList<IBinder> notificationKeys = new ArrayList<IBinder>();
218        ArrayList<StatusBarNotification> notifications = new ArrayList<StatusBarNotification>();
219        mCommandQueue = new CommandQueue(this, iconList);
220
221        int[] switches = new int[7];
222        ArrayList<IBinder> binders = new ArrayList<IBinder>();
223        try {
224            mBarService.registerStatusBar(mCommandQueue, iconList, notificationKeys, notifications,
225                    switches, binders);
226        } catch (RemoteException ex) {
227            // If the system process isn't there we're doomed anyway.
228        }
229
230        createAndAddWindows();
231
232        disable(switches[0]);
233        setSystemUiVisibility(switches[1], 0xffffffff);
234        topAppWindowChanged(switches[2] != 0);
235        // StatusBarManagerService has a back up of IME token and it's restored here.
236        setImeWindowStatus(binders.get(0), switches[3], switches[4]);
237        setHardKeyboardStatus(switches[5] != 0, switches[6] != 0);
238
239        // Set up the initial icon state
240        int N = iconList.size();
241        int viewIndex = 0;
242        for (int i=0; i<N; i++) {
243            StatusBarIcon icon = iconList.getIcon(i);
244            if (icon != null) {
245                addIcon(iconList.getSlot(i), i, viewIndex, icon);
246                viewIndex++;
247            }
248        }
249
250        // Set up the initial notification state
251        N = notificationKeys.size();
252        if (N == notifications.size()) {
253            for (int i=0; i<N; i++) {
254                addNotification(notificationKeys.get(i), notifications.get(i));
255            }
256        } else {
257            Log.wtf(TAG, "Notification list length mismatch: keys=" + N
258                    + " notifications=" + notifications.size());
259        }
260
261        if (DEBUG) {
262            Slog.d(TAG, String.format(
263                    "init: icons=%d disabled=0x%08x lights=0x%08x menu=0x%08x imeButton=0x%08x",
264                   iconList.size(),
265                   switches[0],
266                   switches[1],
267                   switches[2],
268                   switches[3]
269                   ));
270        }
271
272        mCurrentUserId = ActivityManager.getCurrentUser();
273
274        IntentFilter filter = new IntentFilter();
275        filter.addAction(Intent.ACTION_USER_SWITCHED);
276        mContext.registerReceiver(new BroadcastReceiver() {
277            @Override
278            public void onReceive(Context context, Intent intent) {
279                String action = intent.getAction();
280                if (Intent.ACTION_USER_SWITCHED.equals(action)) {
281                    mCurrentUserId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
282                    if (true) Slog.v(TAG, "userId " + mCurrentUserId + " is in the house");
283                    userSwitched(mCurrentUserId);
284                }
285            }}, filter);
286
287        mLocale = mContext.getResources().getConfiguration().locale;
288    }
289
290    public void userSwitched(int newUserId) {
291        // should be overridden
292    }
293
294    public boolean notificationIsForCurrentUser(StatusBarNotification n) {
295        final int thisUserId = mCurrentUserId;
296        final int notificationUserId = n.getUserId();
297        if (DEBUG && MULTIUSER_DEBUG) {
298            Slog.v(TAG, String.format("%s: current userid: %d, notification userid: %d",
299                    n, thisUserId, notificationUserId));
300        }
301        return notificationUserId == UserHandle.USER_ALL
302                || thisUserId == notificationUserId;
303    }
304
305    @Override
306    protected void onConfigurationChanged(Configuration newConfig) {
307        final Locale newLocale = mContext.getResources().getConfiguration().locale;
308        if (! newLocale.equals(mLocale)) {
309            mLocale = newLocale;
310            mLayoutDirection = TextUtils.getLayoutDirectionFromLocale(mLocale);
311            refreshLayout(mLayoutDirection);
312        }
313    }
314
315    protected View updateNotificationVetoButton(View row, StatusBarNotification n) {
316        View vetoButton = row.findViewById(R.id.veto);
317        if (n.isClearable()) {
318            final String _pkg = n.pkg;
319            final String _tag = n.tag;
320            final int _id = n.id;
321            vetoButton.setOnClickListener(new View.OnClickListener() {
322                    public void onClick(View v) {
323                        // Accessibility feedback
324                        v.announceForAccessibility(
325                                mContext.getString(R.string.accessibility_notification_dismissed));
326                        try {
327                            mBarService.onNotificationClear(_pkg, _tag, _id);
328
329                        } catch (RemoteException ex) {
330                            // system process is dead if we're here.
331                        }
332                    }
333                });
334            vetoButton.setVisibility(View.VISIBLE);
335        } else {
336            vetoButton.setVisibility(View.GONE);
337        }
338        vetoButton.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
339        return vetoButton;
340    }
341
342
343    protected void applyLegacyRowBackground(StatusBarNotification sbn, View content) {
344        if (sbn.notification.contentView.getLayoutId() !=
345                com.android.internal.R.layout.notification_template_base) {
346            int version = 0;
347            try {
348                ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(sbn.pkg, 0);
349                version = info.targetSdkVersion;
350            } catch (NameNotFoundException ex) {
351                Slog.e(TAG, "Failed looking up ApplicationInfo for " + sbn.pkg, ex);
352            }
353            if (version > 0 && version < Build.VERSION_CODES.GINGERBREAD) {
354                content.setBackgroundResource(R.drawable.notification_row_legacy_bg);
355            } else {
356                content.setBackgroundResource(com.android.internal.R.drawable.notification_bg);
357            }
358        }
359    }
360
361    private void startApplicationDetailsActivity(String packageName) {
362        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
363                Uri.fromParts("package", packageName, null));
364        intent.setComponent(intent.resolveActivity(mContext.getPackageManager()));
365        TaskStackBuilder.create(mContext).addNextIntentWithParentStack(intent).startActivities(
366                null, UserHandle.CURRENT);
367    }
368
369    protected View.OnLongClickListener getNotificationLongClicker() {
370        return new View.OnLongClickListener() {
371            @Override
372            public boolean onLongClick(View v) {
373                final String packageNameF = (String) v.getTag();
374                if (packageNameF == null) return false;
375                if (v.getWindowToken() == null) return false;
376                mNotificationBlamePopup = new PopupMenu(mContext, v);
377                mNotificationBlamePopup.getMenuInflater().inflate(
378                        R.menu.notification_popup_menu,
379                        mNotificationBlamePopup.getMenu());
380                mNotificationBlamePopup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
381                    public boolean onMenuItemClick(MenuItem item) {
382                        if (item.getItemId() == R.id.notification_inspect_item) {
383                            startApplicationDetailsActivity(packageNameF);
384                            animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
385                        } else {
386                            return false;
387                        }
388                        return true;
389                    }
390                });
391                mNotificationBlamePopup.show();
392
393                return true;
394            }
395        };
396    }
397
398    public void dismissPopups() {
399        if (mNotificationBlamePopup != null) {
400            mNotificationBlamePopup.dismiss();
401            mNotificationBlamePopup = null;
402        }
403    }
404
405    public void dismissIntruder() {
406        // pass
407    }
408
409    @Override
410    public void toggleRecentApps() {
411        int msg = MSG_TOGGLE_RECENTS_PANEL;
412        mHandler.removeMessages(msg);
413        mHandler.sendEmptyMessage(msg);
414    }
415
416    @Override
417    public void preloadRecentApps() {
418        int msg = MSG_PRELOAD_RECENT_APPS;
419        mHandler.removeMessages(msg);
420        mHandler.sendEmptyMessage(msg);
421    }
422
423    @Override
424    public void cancelPreloadRecentApps() {
425        int msg = MSG_CANCEL_PRELOAD_RECENT_APPS;
426        mHandler.removeMessages(msg);
427        mHandler.sendEmptyMessage(msg);
428    }
429
430    @Override
431    public void showSearchPanel() {
432        int msg = MSG_OPEN_SEARCH_PANEL;
433        mHandler.removeMessages(msg);
434        mHandler.sendEmptyMessage(msg);
435    }
436
437    @Override
438    public void hideSearchPanel() {
439        int msg = MSG_CLOSE_SEARCH_PANEL;
440        mHandler.removeMessages(msg);
441        mHandler.sendEmptyMessage(msg);
442    }
443
444    protected abstract WindowManager.LayoutParams getRecentsLayoutParams(
445            LayoutParams layoutParams);
446
447    protected abstract WindowManager.LayoutParams getSearchLayoutParams(
448            LayoutParams layoutParams);
449
450    protected void updateSearchPanel() {
451        // Search Panel
452        boolean visible = false;
453        if (mSearchPanelView != null) {
454            visible = mSearchPanelView.isShowing();
455            mWindowManager.removeView(mSearchPanelView);
456        }
457
458        // Provide SearchPanel with a temporary parent to allow layout params to work.
459        LinearLayout tmpRoot = new LinearLayout(mContext);
460        mSearchPanelView = (SearchPanelView) LayoutInflater.from(mContext).inflate(
461                 R.layout.status_bar_search_panel, tmpRoot, false);
462        mSearchPanelView.setOnTouchListener(
463                 new TouchOutsideListener(MSG_CLOSE_SEARCH_PANEL, mSearchPanelView));
464        mSearchPanelView.setVisibility(View.GONE);
465        mSearchPanelView.setLayoutDirection(mLayoutDirection);
466
467        WindowManager.LayoutParams lp = getSearchLayoutParams(mSearchPanelView.getLayoutParams());
468
469        mWindowManager.addView(mSearchPanelView, lp);
470        mSearchPanelView.setBar(this);
471        if (visible) {
472            mSearchPanelView.show(true, false);
473        }
474    }
475
476    protected H createHandler() {
477         return new H();
478    }
479
480    static void sendCloseSystemWindows(Context context, String reason) {
481        if (ActivityManagerNative.isSystemReady()) {
482            try {
483                ActivityManagerNative.getDefault().closeSystemDialogs(reason);
484            } catch (RemoteException e) {
485            }
486        }
487    }
488
489    protected abstract View getStatusBarView();
490
491    protected void toggleRecentsActivity() {
492        try {
493
494            TaskDescription firstTask = RecentTasksLoader.getInstance(mContext).getFirstTask();
495
496            Intent intent = new Intent(RecentsActivity.TOGGLE_RECENTS_INTENT);
497            intent.setClassName("com.android.systemui",
498                    "com.android.systemui.recent.RecentsActivity");
499            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
500                    | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
501
502            if (firstTask == null) {
503                if (RecentsActivity.forceOpaqueBackground(mContext)) {
504                    ActivityOptions opts = ActivityOptions.makeCustomAnimation(mContext,
505                            R.anim.recents_launch_from_launcher_enter,
506                            R.anim.recents_launch_from_launcher_exit);
507                    mContext.startActivityAsUser(intent, opts.toBundle(), new UserHandle(
508                            UserHandle.USER_CURRENT));
509                } else {
510                    // The correct window animation will be applied via the activity's style
511                    mContext.startActivityAsUser(intent, new UserHandle(
512                            UserHandle.USER_CURRENT));
513                }
514
515            } else {
516                Bitmap first = firstTask.getThumbnail();
517                final Resources res = mContext.getResources();
518
519                float thumbWidth = res
520                        .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_width);
521                float thumbHeight = res
522                        .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_height);
523                if (first == null) {
524                    throw new RuntimeException("Recents thumbnail is null");
525                }
526                if (first.getWidth() != thumbWidth || first.getHeight() != thumbHeight) {
527                    first = Bitmap.createScaledBitmap(first, (int) thumbWidth, (int) thumbHeight,
528                            true);
529                    if (first == null) {
530                        throw new RuntimeException("Recents thumbnail is null");
531                    }
532                }
533
534
535                DisplayMetrics dm = new DisplayMetrics();
536                mDisplay.getMetrics(dm);
537                // calculate it here, but consider moving it elsewhere
538                // first, determine which orientation you're in.
539                // todo: move the system_bar layouts to sw600dp ?
540                final Configuration config = res.getConfiguration();
541                int x, y;
542
543                if (config.orientation == Configuration.ORIENTATION_PORTRAIT) {
544                    float appLabelLeftMargin = res
545                            .getDimensionPixelSize(R.dimen.status_bar_recents_app_label_left_margin);
546                    float appLabelWidth = res
547                            .getDimensionPixelSize(R.dimen.status_bar_recents_app_label_width);
548                    float thumbLeftMargin = res
549                            .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_left_margin);
550                    float thumbBgPadding = res
551                            .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_bg_padding);
552
553                    float width = appLabelLeftMargin +
554                            +appLabelWidth
555                            + thumbLeftMargin
556                            + thumbWidth
557                            + 2 * thumbBgPadding;
558
559                    x = (int) ((dm.widthPixels - width) / 2f + appLabelLeftMargin + appLabelWidth
560                            + thumbBgPadding + thumbLeftMargin);
561                    y = (int) (dm.heightPixels
562                            - res.getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_height) - thumbBgPadding);
563                } else { // if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
564                    float thumbTopMargin = res
565                            .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_top_margin);
566                    float thumbBgPadding = res
567                            .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_bg_padding);
568                    float textPadding = res
569                            .getDimensionPixelSize(R.dimen.status_bar_recents_text_description_padding);
570                    float labelTextSize = res
571                            .getDimensionPixelSize(R.dimen.status_bar_recents_app_label_text_size);
572                    Paint p = new Paint();
573                    p.setTextSize(labelTextSize);
574                    float labelTextHeight = p.getFontMetricsInt().bottom
575                            - p.getFontMetricsInt().top;
576                    float descriptionTextSize = res
577                            .getDimensionPixelSize(R.dimen.status_bar_recents_app_description_text_size);
578                    p.setTextSize(descriptionTextSize);
579                    float descriptionTextHeight = p.getFontMetricsInt().bottom
580                            - p.getFontMetricsInt().top;
581
582                    float statusBarHeight = res
583                            .getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
584                    float recentsItemTopPadding = statusBarHeight;
585
586                    float height = thumbTopMargin
587                            + thumbHeight
588                            + 2 * thumbBgPadding + textPadding + labelTextHeight
589                            + recentsItemTopPadding + textPadding + descriptionTextHeight;
590                    float recentsItemRightPadding = res
591                            .getDimensionPixelSize(R.dimen.status_bar_recents_item_padding);
592                    float recentsScrollViewRightPadding = res
593                            .getDimensionPixelSize(R.dimen.status_bar_recents_right_glow_margin);
594                    x = (int) (dm.widthPixels - res
595                            .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_width)
596                            - thumbBgPadding - recentsItemRightPadding - recentsScrollViewRightPadding);
597                    y = (int) ((dm.heightPixels - statusBarHeight - height) / 2f + thumbTopMargin
598                            + recentsItemTopPadding + thumbBgPadding + statusBarHeight);
599                }
600                if (mLayoutDirection == View.LAYOUT_DIRECTION_RTL) {
601                    x = dm.widthPixels - x - res
602                            .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_width);
603                }
604
605                ActivityOptions opts = ActivityOptions.makeThumbnailScaleDownAnimation(
606                        getStatusBarView(),
607                        first, x, y,
608                        new ActivityOptions.OnAnimationStartedListener() {
609                            public void onAnimationStarted() {
610                                Intent intent = new Intent(RecentsActivity.WINDOW_ANIMATION_START_INTENT);
611                                intent.setPackage("com.android.systemui");
612                                mContext.sendBroadcastAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
613                            }
614                        });
615                intent.putExtra(RecentsActivity.WAITING_FOR_WINDOW_ANIMATION_PARAM, true);
616                mContext.startActivityAsUser(intent, opts.toBundle(), new UserHandle(
617                        UserHandle.USER_CURRENT));
618            }
619            return;
620        } catch (ActivityNotFoundException e) {
621            Log.e(TAG, "Failed to launch RecentAppsIntent", e);
622        }
623    }
624
625    protected View.OnTouchListener mRecentsPreloadOnTouchListener = new View.OnTouchListener() {
626        // additional optimization when we have software system buttons - start loading the recent
627        // tasks on touch down
628        @Override
629        public boolean onTouch(View v, MotionEvent event) {
630            int action = event.getAction() & MotionEvent.ACTION_MASK;
631            if (action == MotionEvent.ACTION_DOWN) {
632                preloadRecentTasksList();
633            } else if (action == MotionEvent.ACTION_CANCEL) {
634                cancelPreloadingRecentTasksList();
635            } else if (action == MotionEvent.ACTION_UP) {
636                if (!v.isPressed()) {
637                    cancelPreloadingRecentTasksList();
638                }
639
640            }
641            return false;
642        }
643    };
644
645    protected void preloadRecentTasksList() {
646        if (DEBUG) Slog.d(TAG, "preloading recents");
647        Intent intent = new Intent(RecentsActivity.PRELOAD_INTENT);
648        intent.setClassName("com.android.systemui",
649                "com.android.systemui.recent.RecentsPreloadReceiver");
650        mContext.sendBroadcastAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
651
652        RecentTasksLoader.getInstance(mContext).preloadFirstTask();
653    }
654
655    protected void cancelPreloadingRecentTasksList() {
656        if (DEBUG) Slog.d(TAG, "cancel preloading recents");
657        Intent intent = new Intent(RecentsActivity.CANCEL_PRELOAD_INTENT);
658        intent.setClassName("com.android.systemui",
659                "com.android.systemui.recent.RecentsPreloadReceiver");
660        mContext.sendBroadcastAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
661
662        RecentTasksLoader.getInstance(mContext).cancelPreloadingFirstTask();
663    }
664
665    protected class H extends Handler {
666        public void handleMessage(Message m) {
667            Intent intent;
668            switch (m.what) {
669             case MSG_TOGGLE_RECENTS_PANEL:
670                 if (DEBUG) Slog.d(TAG, "toggle recents panel");
671                 toggleRecentsActivity();
672                 break;
673             case MSG_CLOSE_RECENTS_PANEL:
674                 if (DEBUG) Slog.d(TAG, "closing recents panel");
675                 intent = new Intent(RecentsActivity.CLOSE_RECENTS_INTENT);
676                 intent.setPackage("com.android.systemui");
677                 mContext.sendBroadcastAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
678                 break;
679             case MSG_PRELOAD_RECENT_APPS:
680                  preloadRecentTasksList();
681                  break;
682             case MSG_CANCEL_PRELOAD_RECENT_APPS:
683                  cancelPreloadingRecentTasksList();
684                  break;
685             case MSG_OPEN_SEARCH_PANEL:
686                 if (DEBUG) Slog.d(TAG, "opening search panel");
687                 if (mSearchPanelView != null && mSearchPanelView.isAssistantAvailable()) {
688                     mSearchPanelView.show(true, true);
689                 }
690                 break;
691             case MSG_CLOSE_SEARCH_PANEL:
692                 if (DEBUG) Slog.d(TAG, "closing search panel");
693                 if (mSearchPanelView != null && mSearchPanelView.isShowing()) {
694                     mSearchPanelView.show(false, true);
695                 }
696                 break;
697            }
698        }
699    }
700
701    public class TouchOutsideListener implements View.OnTouchListener {
702        private int mMsg;
703        private StatusBarPanel mPanel;
704
705        public TouchOutsideListener(int msg, StatusBarPanel panel) {
706            mMsg = msg;
707            mPanel = panel;
708        }
709
710        public boolean onTouch(View v, MotionEvent ev) {
711            final int action = ev.getAction();
712            if (action == MotionEvent.ACTION_OUTSIDE
713                || (action == MotionEvent.ACTION_DOWN
714                    && !mPanel.isInContentArea((int)ev.getX(), (int)ev.getY()))) {
715                mHandler.removeMessages(mMsg);
716                mHandler.sendEmptyMessage(mMsg);
717                return true;
718            }
719            return false;
720        }
721    }
722
723    protected void workAroundBadLayerDrawableOpacity(View v) {
724    }
725
726    protected  boolean inflateViews(NotificationData.Entry entry, ViewGroup parent) {
727        int minHeight =
728                mContext.getResources().getDimensionPixelSize(R.dimen.notification_min_height);
729        int maxHeight =
730                mContext.getResources().getDimensionPixelSize(R.dimen.notification_max_height);
731        StatusBarNotification sbn = entry.notification;
732        RemoteViews oneU = sbn.notification.contentView;
733        RemoteViews large = sbn.notification.bigContentView;
734        if (oneU == null) {
735            return false;
736        }
737
738        // create the row view
739        LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(
740                Context.LAYOUT_INFLATER_SERVICE);
741        View row = inflater.inflate(R.layout.status_bar_notification_row, parent, false);
742        row.setLayoutDirection(mLayoutDirection);
743
744        // for blaming (see SwipeHelper.setLongPressListener)
745        row.setTag(sbn.pkg);
746
747        workAroundBadLayerDrawableOpacity(row);
748        View vetoButton = updateNotificationVetoButton(row, sbn);
749        vetoButton.setContentDescription(mContext.getString(
750                R.string.accessibility_remove_notification));
751
752        // NB: the large icon is now handled entirely by the template
753
754        // bind the click event to the content area
755        ViewGroup content = (ViewGroup)row.findViewById(R.id.content);
756        ViewGroup adaptive = (ViewGroup)row.findViewById(R.id.adaptive);
757
758        content.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
759
760        PendingIntent contentIntent = sbn.notification.contentIntent;
761        if (contentIntent != null) {
762            final View.OnClickListener listener = new NotificationClicker(contentIntent,
763                    sbn.pkg, sbn.tag, sbn.id);
764            content.setOnClickListener(listener);
765        } else {
766            content.setOnClickListener(null);
767        }
768
769        // TODO(cwren) normalize variable names with those in updateNotification
770        View expandedOneU = null;
771        View expandedLarge = null;
772        try {
773            expandedOneU = oneU.apply(mContext, adaptive, mOnClickHandler);
774            if (large != null) {
775                expandedLarge = large.apply(mContext, adaptive, mOnClickHandler);
776            }
777        }
778        catch (RuntimeException e) {
779            final String ident = sbn.pkg + "/0x" + Integer.toHexString(sbn.id);
780            Slog.e(TAG, "couldn't inflate view for notification " + ident, e);
781            return false;
782        }
783
784        if (expandedOneU != null) {
785            SizeAdaptiveLayout.LayoutParams params =
786                    new SizeAdaptiveLayout.LayoutParams(expandedOneU.getLayoutParams());
787            params.minHeight = minHeight;
788            params.maxHeight = minHeight;
789            adaptive.addView(expandedOneU, params);
790            expandedOneU.setLayoutDirection(mLayoutDirection);
791        }
792        if (expandedLarge != null) {
793            SizeAdaptiveLayout.LayoutParams params =
794                    new SizeAdaptiveLayout.LayoutParams(expandedLarge.getLayoutParams());
795            params.minHeight = minHeight+1;
796            params.maxHeight = maxHeight;
797            adaptive.addView(expandedLarge, params);
798            expandedLarge.setLayoutDirection(mLayoutDirection);
799        }
800        row.setDrawingCacheEnabled(true);
801
802        applyLegacyRowBackground(sbn, content);
803
804        row.setTag(R.id.expandable_tag, Boolean.valueOf(large != null));
805
806        if (MULTIUSER_DEBUG) {
807            TextView debug = (TextView) row.findViewById(R.id.debug_info);
808            if (debug != null) {
809                debug.setVisibility(View.VISIBLE);
810                debug.setText("U " + entry.notification.getUserId());
811            }
812        }
813        entry.row = row;
814        entry.content = content;
815        entry.expanded = expandedOneU;
816        entry.setLargeView(expandedLarge);
817
818        return true;
819    }
820
821    public NotificationClicker makeClicker(PendingIntent intent, String pkg, String tag, int id) {
822        return new NotificationClicker(intent, pkg, tag, id);
823    }
824
825    private class NotificationClicker implements View.OnClickListener {
826        private PendingIntent mIntent;
827        private String mPkg;
828        private String mTag;
829        private int mId;
830
831        NotificationClicker(PendingIntent intent, String pkg, String tag, int id) {
832            mIntent = intent;
833            mPkg = pkg;
834            mTag = tag;
835            mId = id;
836        }
837
838        public void onClick(View v) {
839            try {
840                // The intent we are sending is for the application, which
841                // won't have permission to immediately start an activity after
842                // the user switches to home.  We know it is safe to do at this
843                // point, so make sure new activity switches are now allowed.
844                ActivityManagerNative.getDefault().resumeAppSwitches();
845                // Also, notifications can be launched from the lock screen,
846                // so dismiss the lock screen when the activity starts.
847                ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
848            } catch (RemoteException e) {
849            }
850
851            if (mIntent != null) {
852                int[] pos = new int[2];
853                v.getLocationOnScreen(pos);
854                Intent overlay = new Intent();
855                overlay.setSourceBounds(
856                        new Rect(pos[0], pos[1], pos[0]+v.getWidth(), pos[1]+v.getHeight()));
857                try {
858                    mIntent.send(mContext, 0, overlay);
859                } catch (PendingIntent.CanceledException e) {
860                    // the stack trace isn't very helpful here.  Just log the exception message.
861                    Slog.w(TAG, "Sending contentIntent failed: " + e);
862                }
863
864                KeyguardManager kgm =
865                    (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
866                if (kgm != null) kgm.exitKeyguardSecurely(null);
867            }
868
869            try {
870                mBarService.onNotificationClick(mPkg, mTag, mId);
871            } catch (RemoteException ex) {
872                // system process is dead if we're here.
873            }
874
875            // close the shade if it was open
876            animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
877            visibilityChanged(false);
878
879            // If this click was on the intruder alert, hide that instead
880//            mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
881        }
882    }
883    /**
884     * The LEDs are turned o)ff when the notification panel is shown, even just a little bit.
885     * This was added last-minute and is inconsistent with the way the rest of the notifications
886     * are handled, because the notification isn't really cancelled.  The lights are just
887     * turned off.  If any other notifications happen, the lights will turn back on.  Steve says
888     * this is what he wants. (see bug 1131461)
889     */
890    protected void visibilityChanged(boolean visible) {
891        if (mPanelSlightlyVisible != visible) {
892            mPanelSlightlyVisible = visible;
893            try {
894                mBarService.onPanelRevealed();
895            } catch (RemoteException ex) {
896                // Won't fail unless the world has ended.
897            }
898        }
899    }
900
901    /**
902     * Cancel this notification and tell the StatusBarManagerService / NotificationManagerService
903     * about the failure.
904     *
905     * WARNING: this will call back into us.  Don't hold any locks.
906     */
907    void handleNotificationError(IBinder key, StatusBarNotification n, String message) {
908        removeNotification(key);
909        try {
910            mBarService.onNotificationError(n.pkg, n.tag, n.id, n.uid, n.initialPid, message);
911        } catch (RemoteException ex) {
912            // The end is nigh.
913        }
914    }
915
916    protected StatusBarNotification removeNotificationViews(IBinder key) {
917        NotificationData.Entry entry = mNotificationData.remove(key);
918        if (entry == null) {
919            Slog.w(TAG, "removeNotification for unknown key: " + key);
920            return null;
921        }
922        // Remove the expanded view.
923        ViewGroup rowParent = (ViewGroup)entry.row.getParent();
924        if (rowParent != null) rowParent.removeView(entry.row);
925        updateExpansionStates();
926        updateNotificationIcons();
927
928        return entry.notification;
929    }
930
931    protected StatusBarIconView addNotificationViews(IBinder key,
932            StatusBarNotification notification) {
933        if (DEBUG) {
934            Slog.d(TAG, "addNotificationViews(key=" + key + ", notification=" + notification);
935        }
936        // Construct the icon.
937        final StatusBarIconView iconView = new StatusBarIconView(mContext,
938                notification.pkg + "/0x" + Integer.toHexString(notification.id),
939                notification.notification);
940        iconView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
941
942        final StatusBarIcon ic = new StatusBarIcon(notification.pkg,
943                    notification.user,
944                    notification.notification.icon,
945                    notification.notification.iconLevel,
946                    notification.notification.number,
947                    notification.notification.tickerText);
948        if (!iconView.set(ic)) {
949            handleNotificationError(key, notification, "Couldn't create icon: " + ic);
950            return null;
951        }
952        // Construct the expanded view.
953        NotificationData.Entry entry = new NotificationData.Entry(key, notification, iconView);
954        if (!inflateViews(entry, mPile)) {
955            handleNotificationError(key, notification, "Couldn't expand RemoteViews for: "
956                    + notification);
957            return null;
958        }
959
960        // Add the expanded view and icon.
961        int pos = mNotificationData.add(entry);
962        if (DEBUG) {
963            Slog.d(TAG, "addNotificationViews: added at " + pos);
964        }
965        updateExpansionStates();
966        updateNotificationIcons();
967
968        return iconView;
969    }
970
971    protected boolean expandView(NotificationData.Entry entry, boolean expand) {
972        int rowHeight =
973                mContext.getResources().getDimensionPixelSize(R.dimen.notification_row_min_height);
974        ViewGroup.LayoutParams lp = entry.row.getLayoutParams();
975        if (entry.expandable() && expand) {
976            if (DEBUG) Slog.d(TAG, "setting expanded row height to WRAP_CONTENT");
977            lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
978        } else {
979            if (DEBUG) Slog.d(TAG, "setting collapsed row height to " + rowHeight);
980            lp.height = rowHeight;
981        }
982        entry.row.setLayoutParams(lp);
983        return expand;
984    }
985
986    protected void updateExpansionStates() {
987        int N = mNotificationData.size();
988        for (int i = 0; i < N; i++) {
989            NotificationData.Entry entry = mNotificationData.get(i);
990            if (!entry.userLocked()) {
991                if (i == (N-1)) {
992                    if (DEBUG) Slog.d(TAG, "expanding top notification at " + i);
993                    expandView(entry, true);
994                } else {
995                    if (!entry.userExpanded()) {
996                        if (DEBUG) Slog.d(TAG, "collapsing notification at " + i);
997                        expandView(entry, false);
998                    } else {
999                        if (DEBUG) Slog.d(TAG, "ignoring user-modified notification at " + i);
1000                    }
1001                }
1002            } else {
1003                if (DEBUG) Slog.d(TAG, "ignoring notification being held by user at " + i);
1004            }
1005        }
1006    }
1007
1008    protected abstract void haltTicker();
1009    protected abstract void setAreThereNotifications();
1010    protected abstract void updateNotificationIcons();
1011    protected abstract void tick(IBinder key, StatusBarNotification n, boolean firstTime);
1012    protected abstract void updateExpandedViewPos(int expandedPosition);
1013    protected abstract int getExpandedViewMaxHeight();
1014    protected abstract boolean shouldDisableNavbarGestures();
1015
1016    protected boolean isTopNotification(ViewGroup parent, NotificationData.Entry entry) {
1017        return parent != null && parent.indexOfChild(entry.row) == 0;
1018    }
1019
1020    public void updateNotification(IBinder key, StatusBarNotification notification) {
1021        if (DEBUG) Slog.d(TAG, "updateNotification(" + key + " -> " + notification + ")");
1022
1023        final NotificationData.Entry oldEntry = mNotificationData.findByKey(key);
1024        if (oldEntry == null) {
1025            Slog.w(TAG, "updateNotification for unknown key: " + key);
1026            return;
1027        }
1028
1029        final StatusBarNotification oldNotification = oldEntry.notification;
1030
1031        // XXX: modify when we do something more intelligent with the two content views
1032        final RemoteViews oldContentView = oldNotification.notification.contentView;
1033        final RemoteViews contentView = notification.notification.contentView;
1034        final RemoteViews oldBigContentView = oldNotification.notification.bigContentView;
1035        final RemoteViews bigContentView = notification.notification.bigContentView;
1036
1037        if (DEBUG) {
1038            Slog.d(TAG, "old notification: when=" + oldNotification.notification.when
1039                    + " ongoing=" + oldNotification.isOngoing()
1040                    + " expanded=" + oldEntry.expanded
1041                    + " contentView=" + oldContentView
1042                    + " bigContentView=" + oldBigContentView
1043                    + " rowParent=" + oldEntry.row.getParent());
1044            Slog.d(TAG, "new notification: when=" + notification.notification.when
1045                    + " ongoing=" + oldNotification.isOngoing()
1046                    + " contentView=" + contentView
1047                    + " bigContentView=" + bigContentView);
1048        }
1049
1050        // Can we just reapply the RemoteViews in place?  If when didn't change, the order
1051        // didn't change.
1052
1053        // 1U is never null
1054        boolean contentsUnchanged = oldEntry.expanded != null
1055                && contentView.getPackage() != null
1056                && oldContentView.getPackage() != null
1057                && oldContentView.getPackage().equals(contentView.getPackage())
1058                && oldContentView.getLayoutId() == contentView.getLayoutId();
1059        // large view may be null
1060        boolean bigContentsUnchanged =
1061                (oldEntry.getLargeView() == null && bigContentView == null)
1062                || ((oldEntry.getLargeView() != null && bigContentView != null)
1063                    && bigContentView.getPackage() != null
1064                    && oldBigContentView.getPackage() != null
1065                    && oldBigContentView.getPackage().equals(bigContentView.getPackage())
1066                    && oldBigContentView.getLayoutId() == bigContentView.getLayoutId());
1067        ViewGroup rowParent = (ViewGroup) oldEntry.row.getParent();
1068        boolean orderUnchanged = notification.notification.when==oldNotification.notification.when
1069                && notification.score == oldNotification.score;
1070                // score now encompasses/supersedes isOngoing()
1071
1072        boolean updateTicker = notification.notification.tickerText != null
1073                && !TextUtils.equals(notification.notification.tickerText,
1074                        oldEntry.notification.notification.tickerText);
1075        boolean isTopAnyway = isTopNotification(rowParent, oldEntry);
1076        if (contentsUnchanged && bigContentsUnchanged && (orderUnchanged || isTopAnyway)) {
1077            if (DEBUG) Slog.d(TAG, "reusing notification for key: " + key);
1078            oldEntry.notification = notification;
1079            try {
1080                // Reapply the RemoteViews
1081                contentView.reapply(mContext, oldEntry.expanded, mOnClickHandler);
1082                if (bigContentView != null && oldEntry.getLargeView() != null) {
1083                    bigContentView.reapply(mContext, oldEntry.getLargeView(), mOnClickHandler);
1084                }
1085                // update the contentIntent
1086                final PendingIntent contentIntent = notification.notification.contentIntent;
1087                if (contentIntent != null) {
1088                    final View.OnClickListener listener = makeClicker(contentIntent,
1089                            notification.pkg, notification.tag, notification.id);
1090                    oldEntry.content.setOnClickListener(listener);
1091                } else {
1092                    oldEntry.content.setOnClickListener(null);
1093                }
1094                // Update the icon.
1095                final StatusBarIcon ic = new StatusBarIcon(notification.pkg,
1096                        notification.user,
1097                        notification.notification.icon, notification.notification.iconLevel,
1098                        notification.notification.number,
1099                        notification.notification.tickerText);
1100                if (!oldEntry.icon.set(ic)) {
1101                    handleNotificationError(key, notification, "Couldn't update icon: " + ic);
1102                    return;
1103                }
1104                updateExpansionStates();
1105            }
1106            catch (RuntimeException e) {
1107                // It failed to add cleanly.  Log, and remove the view from the panel.
1108                Slog.w(TAG, "Couldn't reapply views for package " + contentView.getPackage(), e);
1109                removeNotificationViews(key);
1110                addNotificationViews(key, notification);
1111            }
1112        } else {
1113            if (DEBUG) Slog.d(TAG, "not reusing notification for key: " + key);
1114            if (DEBUG) Slog.d(TAG, "contents was " + (contentsUnchanged ? "unchanged" : "changed"));
1115            if (DEBUG) Slog.d(TAG, "order was " + (orderUnchanged ? "unchanged" : "changed"));
1116            if (DEBUG) Slog.d(TAG, "notification is " + (isTopAnyway ? "top" : "not top"));
1117            final boolean wasExpanded = oldEntry.userExpanded();
1118            removeNotificationViews(key);
1119            addNotificationViews(key, notification);
1120            if (wasExpanded) {
1121                final NotificationData.Entry newEntry = mNotificationData.findByKey(key);
1122                expandView(newEntry, true);
1123                newEntry.setUserExpanded(true);
1124            }
1125        }
1126
1127        // Update the veto button accordingly (and as a result, whether this row is
1128        // swipe-dismissable)
1129        updateNotificationVetoButton(oldEntry.row, notification);
1130
1131        // Is this for you?
1132        boolean isForCurrentUser = notificationIsForCurrentUser(notification);
1133        if (DEBUG) Slog.d(TAG, "notification is " + (isForCurrentUser ? "" : "not ") + "for you");
1134
1135        // Restart the ticker if it's still running
1136        if (updateTicker && isForCurrentUser) {
1137            haltTicker();
1138            tick(key, notification, false);
1139        }
1140
1141        // Recalculate the position of the sliding windows and the titles.
1142        setAreThereNotifications();
1143        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1144
1145        // See if we need to update the intruder.
1146        if (ENABLE_INTRUDERS && oldNotification == mCurrentlyIntrudingNotification) {
1147            if (DEBUG) Slog.d(TAG, "updating the current intruder:" + notification);
1148            // XXX: this is a hack for Alarms. The real implementation will need to *update*
1149            // the intruder.
1150            if (notification.notification.fullScreenIntent == null) { // TODO(dsandler): consistent logic with add()
1151                if (DEBUG) Slog.d(TAG, "no longer intrudes!");
1152                mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
1153            }
1154        }
1155    }
1156
1157    // Q: What kinds of notifications should show during setup?
1158    // A: Almost none! Only things coming from the system (package is "android") that also
1159    // have special "kind" tags marking them as relevant for setup (see below).
1160    protected boolean showNotificationEvenIfUnprovisioned(StatusBarNotification sbn) {
1161        if ("android".equals(sbn.pkg)) {
1162            if (sbn.notification.kind != null) {
1163                for (String aKind : sbn.notification.kind) {
1164                    // IME switcher, created by InputMethodManagerService
1165                    if ("android.system.imeswitcher".equals(aKind)) return true;
1166                    // OTA availability & errors, created by SystemUpdateService
1167                    if ("android.system.update".equals(aKind)) return true;
1168                }
1169            }
1170        }
1171        return false;
1172    }
1173
1174    public boolean inKeyguardRestrictedInputMode() {
1175        KeyguardManager km = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
1176        return km.inKeyguardRestrictedInputMode();
1177    }
1178}
1179