BaseStatusBar.java revision 8afcd149970c79054a3a16377834aa0aec35eee0
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
601                ActivityOptions opts = ActivityOptions.makeThumbnailScaleDownAnimation(
602                        getStatusBarView(),
603                        first, x, y,
604                        new ActivityOptions.OnAnimationStartedListener() {
605                            public void onAnimationStarted() {
606                                Intent intent = new Intent(RecentsActivity.WINDOW_ANIMATION_START_INTENT);
607                                intent.setPackage("com.android.systemui");
608                                mContext.sendBroadcastAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
609                            }
610                        });
611                intent.putExtra(RecentsActivity.WAITING_FOR_WINDOW_ANIMATION_PARAM, true);
612                mContext.startActivityAsUser(intent, opts.toBundle(), new UserHandle(
613                        UserHandle.USER_CURRENT));
614            }
615            return;
616        } catch (ActivityNotFoundException e) {
617            Log.e(TAG, "Failed to launch RecentAppsIntent", e);
618        }
619    }
620
621    protected View.OnTouchListener mRecentsPreloadOnTouchListener = new View.OnTouchListener() {
622        // additional optimization when we have software system buttons - start loading the recent
623        // tasks on touch down
624        @Override
625        public boolean onTouch(View v, MotionEvent event) {
626            int action = event.getAction() & MotionEvent.ACTION_MASK;
627            if (action == MotionEvent.ACTION_DOWN) {
628                preloadRecentTasksList();
629            } else if (action == MotionEvent.ACTION_CANCEL) {
630                cancelPreloadingRecentTasksList();
631            } else if (action == MotionEvent.ACTION_UP) {
632                if (!v.isPressed()) {
633                    cancelPreloadingRecentTasksList();
634                }
635
636            }
637            return false;
638        }
639    };
640
641    protected void preloadRecentTasksList() {
642        if (DEBUG) Slog.d(TAG, "preloading recents");
643        Intent intent = new Intent(RecentsActivity.PRELOAD_INTENT);
644        intent.setClassName("com.android.systemui",
645                "com.android.systemui.recent.RecentsPreloadReceiver");
646        mContext.sendBroadcastAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
647
648        RecentTasksLoader.getInstance(mContext).preloadFirstTask();
649    }
650
651    protected void cancelPreloadingRecentTasksList() {
652        if (DEBUG) Slog.d(TAG, "cancel preloading recents");
653        Intent intent = new Intent(RecentsActivity.CANCEL_PRELOAD_INTENT);
654        intent.setClassName("com.android.systemui",
655                "com.android.systemui.recent.RecentsPreloadReceiver");
656        mContext.sendBroadcastAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
657
658        RecentTasksLoader.getInstance(mContext).cancelPreloadingFirstTask();
659    }
660
661    protected class H extends Handler {
662        public void handleMessage(Message m) {
663            Intent intent;
664            switch (m.what) {
665             case MSG_TOGGLE_RECENTS_PANEL:
666                 if (DEBUG) Slog.d(TAG, "toggle recents panel");
667                 toggleRecentsActivity();
668                 break;
669             case MSG_CLOSE_RECENTS_PANEL:
670                 if (DEBUG) Slog.d(TAG, "closing recents panel");
671                 intent = new Intent(RecentsActivity.CLOSE_RECENTS_INTENT);
672                 intent.setPackage("com.android.systemui");
673                 mContext.sendBroadcastAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
674                 break;
675             case MSG_PRELOAD_RECENT_APPS:
676                  preloadRecentTasksList();
677                  break;
678             case MSG_CANCEL_PRELOAD_RECENT_APPS:
679                  cancelPreloadingRecentTasksList();
680                  break;
681             case MSG_OPEN_SEARCH_PANEL:
682                 if (DEBUG) Slog.d(TAG, "opening search panel");
683                 if (mSearchPanelView != null && mSearchPanelView.isAssistantAvailable()) {
684                     mSearchPanelView.show(true, true);
685                 }
686                 break;
687             case MSG_CLOSE_SEARCH_PANEL:
688                 if (DEBUG) Slog.d(TAG, "closing search panel");
689                 if (mSearchPanelView != null && mSearchPanelView.isShowing()) {
690                     mSearchPanelView.show(false, true);
691                 }
692                 break;
693            }
694        }
695    }
696
697    public class TouchOutsideListener implements View.OnTouchListener {
698        private int mMsg;
699        private StatusBarPanel mPanel;
700
701        public TouchOutsideListener(int msg, StatusBarPanel panel) {
702            mMsg = msg;
703            mPanel = panel;
704        }
705
706        public boolean onTouch(View v, MotionEvent ev) {
707            final int action = ev.getAction();
708            if (action == MotionEvent.ACTION_OUTSIDE
709                || (action == MotionEvent.ACTION_DOWN
710                    && !mPanel.isInContentArea((int)ev.getX(), (int)ev.getY()))) {
711                mHandler.removeMessages(mMsg);
712                mHandler.sendEmptyMessage(mMsg);
713                return true;
714            }
715            return false;
716        }
717    }
718
719    protected void workAroundBadLayerDrawableOpacity(View v) {
720    }
721
722    protected  boolean inflateViews(NotificationData.Entry entry, ViewGroup parent) {
723        int minHeight =
724                mContext.getResources().getDimensionPixelSize(R.dimen.notification_min_height);
725        int maxHeight =
726                mContext.getResources().getDimensionPixelSize(R.dimen.notification_max_height);
727        StatusBarNotification sbn = entry.notification;
728        RemoteViews oneU = sbn.notification.contentView;
729        RemoteViews large = sbn.notification.bigContentView;
730        if (oneU == null) {
731            return false;
732        }
733
734        // create the row view
735        LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(
736                Context.LAYOUT_INFLATER_SERVICE);
737        View row = inflater.inflate(R.layout.status_bar_notification_row, parent, false);
738        row.setLayoutDirection(mLayoutDirection);
739
740        // for blaming (see SwipeHelper.setLongPressListener)
741        row.setTag(sbn.pkg);
742
743        workAroundBadLayerDrawableOpacity(row);
744        View vetoButton = updateNotificationVetoButton(row, sbn);
745        vetoButton.setContentDescription(mContext.getString(
746                R.string.accessibility_remove_notification));
747
748        // NB: the large icon is now handled entirely by the template
749
750        // bind the click event to the content area
751        ViewGroup content = (ViewGroup)row.findViewById(R.id.content);
752        ViewGroup adaptive = (ViewGroup)row.findViewById(R.id.adaptive);
753
754        content.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
755
756        PendingIntent contentIntent = sbn.notification.contentIntent;
757        if (contentIntent != null) {
758            final View.OnClickListener listener = new NotificationClicker(contentIntent,
759                    sbn.pkg, sbn.tag, sbn.id);
760            content.setOnClickListener(listener);
761        } else {
762            content.setOnClickListener(null);
763        }
764
765        // TODO(cwren) normalize variable names with those in updateNotification
766        View expandedOneU = null;
767        View expandedLarge = null;
768        try {
769            expandedOneU = oneU.apply(mContext, adaptive, mOnClickHandler);
770            if (large != null) {
771                expandedLarge = large.apply(mContext, adaptive, mOnClickHandler);
772            }
773        }
774        catch (RuntimeException e) {
775            final String ident = sbn.pkg + "/0x" + Integer.toHexString(sbn.id);
776            Slog.e(TAG, "couldn't inflate view for notification " + ident, e);
777            return false;
778        }
779
780        if (expandedOneU != null) {
781            SizeAdaptiveLayout.LayoutParams params =
782                    new SizeAdaptiveLayout.LayoutParams(expandedOneU.getLayoutParams());
783            params.minHeight = minHeight;
784            params.maxHeight = minHeight;
785            adaptive.addView(expandedOneU, params);
786            expandedOneU.setLayoutDirection(mLayoutDirection);
787        }
788        if (expandedLarge != null) {
789            SizeAdaptiveLayout.LayoutParams params =
790                    new SizeAdaptiveLayout.LayoutParams(expandedLarge.getLayoutParams());
791            params.minHeight = minHeight+1;
792            params.maxHeight = maxHeight;
793            adaptive.addView(expandedLarge, params);
794            expandedLarge.setLayoutDirection(mLayoutDirection);
795        }
796        row.setDrawingCacheEnabled(true);
797
798        applyLegacyRowBackground(sbn, content);
799
800        row.setTag(R.id.expandable_tag, Boolean.valueOf(large != null));
801
802        if (MULTIUSER_DEBUG) {
803            TextView debug = (TextView) row.findViewById(R.id.debug_info);
804            if (debug != null) {
805                debug.setVisibility(View.VISIBLE);
806                debug.setText("U " + entry.notification.getUserId());
807            }
808        }
809        entry.row = row;
810        entry.content = content;
811        entry.expanded = expandedOneU;
812        entry.setLargeView(expandedLarge);
813
814        return true;
815    }
816
817    public NotificationClicker makeClicker(PendingIntent intent, String pkg, String tag, int id) {
818        return new NotificationClicker(intent, pkg, tag, id);
819    }
820
821    private class NotificationClicker implements View.OnClickListener {
822        private PendingIntent mIntent;
823        private String mPkg;
824        private String mTag;
825        private int mId;
826
827        NotificationClicker(PendingIntent intent, String pkg, String tag, int id) {
828            mIntent = intent;
829            mPkg = pkg;
830            mTag = tag;
831            mId = id;
832        }
833
834        public void onClick(View v) {
835            try {
836                // The intent we are sending is for the application, which
837                // won't have permission to immediately start an activity after
838                // the user switches to home.  We know it is safe to do at this
839                // point, so make sure new activity switches are now allowed.
840                ActivityManagerNative.getDefault().resumeAppSwitches();
841                // Also, notifications can be launched from the lock screen,
842                // so dismiss the lock screen when the activity starts.
843                ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
844            } catch (RemoteException e) {
845            }
846
847            if (mIntent != null) {
848                int[] pos = new int[2];
849                v.getLocationOnScreen(pos);
850                Intent overlay = new Intent();
851                overlay.setSourceBounds(
852                        new Rect(pos[0], pos[1], pos[0]+v.getWidth(), pos[1]+v.getHeight()));
853                try {
854                    mIntent.send(mContext, 0, overlay);
855                } catch (PendingIntent.CanceledException e) {
856                    // the stack trace isn't very helpful here.  Just log the exception message.
857                    Slog.w(TAG, "Sending contentIntent failed: " + e);
858                }
859
860                KeyguardManager kgm =
861                    (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
862                if (kgm != null) kgm.exitKeyguardSecurely(null);
863            }
864
865            try {
866                mBarService.onNotificationClick(mPkg, mTag, mId);
867            } catch (RemoteException ex) {
868                // system process is dead if we're here.
869            }
870
871            // close the shade if it was open
872            animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
873            visibilityChanged(false);
874
875            // If this click was on the intruder alert, hide that instead
876//            mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
877        }
878    }
879    /**
880     * The LEDs are turned o)ff when the notification panel is shown, even just a little bit.
881     * This was added last-minute and is inconsistent with the way the rest of the notifications
882     * are handled, because the notification isn't really cancelled.  The lights are just
883     * turned off.  If any other notifications happen, the lights will turn back on.  Steve says
884     * this is what he wants. (see bug 1131461)
885     */
886    protected void visibilityChanged(boolean visible) {
887        if (mPanelSlightlyVisible != visible) {
888            mPanelSlightlyVisible = visible;
889            try {
890                mBarService.onPanelRevealed();
891            } catch (RemoteException ex) {
892                // Won't fail unless the world has ended.
893            }
894        }
895    }
896
897    /**
898     * Cancel this notification and tell the StatusBarManagerService / NotificationManagerService
899     * about the failure.
900     *
901     * WARNING: this will call back into us.  Don't hold any locks.
902     */
903    void handleNotificationError(IBinder key, StatusBarNotification n, String message) {
904        removeNotification(key);
905        try {
906            mBarService.onNotificationError(n.pkg, n.tag, n.id, n.uid, n.initialPid, message);
907        } catch (RemoteException ex) {
908            // The end is nigh.
909        }
910    }
911
912    protected StatusBarNotification removeNotificationViews(IBinder key) {
913        NotificationData.Entry entry = mNotificationData.remove(key);
914        if (entry == null) {
915            Slog.w(TAG, "removeNotification for unknown key: " + key);
916            return null;
917        }
918        // Remove the expanded view.
919        ViewGroup rowParent = (ViewGroup)entry.row.getParent();
920        if (rowParent != null) rowParent.removeView(entry.row);
921        updateExpansionStates();
922        updateNotificationIcons();
923
924        return entry.notification;
925    }
926
927    protected StatusBarIconView addNotificationViews(IBinder key,
928            StatusBarNotification notification) {
929        if (DEBUG) {
930            Slog.d(TAG, "addNotificationViews(key=" + key + ", notification=" + notification);
931        }
932        // Construct the icon.
933        final StatusBarIconView iconView = new StatusBarIconView(mContext,
934                notification.pkg + "/0x" + Integer.toHexString(notification.id),
935                notification.notification);
936        iconView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
937
938        final StatusBarIcon ic = new StatusBarIcon(notification.pkg,
939                    notification.user,
940                    notification.notification.icon,
941                    notification.notification.iconLevel,
942                    notification.notification.number,
943                    notification.notification.tickerText);
944        if (!iconView.set(ic)) {
945            handleNotificationError(key, notification, "Couldn't create icon: " + ic);
946            return null;
947        }
948        // Construct the expanded view.
949        NotificationData.Entry entry = new NotificationData.Entry(key, notification, iconView);
950        if (!inflateViews(entry, mPile)) {
951            handleNotificationError(key, notification, "Couldn't expand RemoteViews for: "
952                    + notification);
953            return null;
954        }
955
956        // Add the expanded view and icon.
957        int pos = mNotificationData.add(entry);
958        if (DEBUG) {
959            Slog.d(TAG, "addNotificationViews: added at " + pos);
960        }
961        updateExpansionStates();
962        updateNotificationIcons();
963
964        return iconView;
965    }
966
967    protected boolean expandView(NotificationData.Entry entry, boolean expand) {
968        int rowHeight =
969                mContext.getResources().getDimensionPixelSize(R.dimen.notification_row_min_height);
970        ViewGroup.LayoutParams lp = entry.row.getLayoutParams();
971        if (entry.expandable() && expand) {
972            if (DEBUG) Slog.d(TAG, "setting expanded row height to WRAP_CONTENT");
973            lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
974        } else {
975            if (DEBUG) Slog.d(TAG, "setting collapsed row height to " + rowHeight);
976            lp.height = rowHeight;
977        }
978        entry.row.setLayoutParams(lp);
979        return expand;
980    }
981
982    protected void updateExpansionStates() {
983        int N = mNotificationData.size();
984        for (int i = 0; i < N; i++) {
985            NotificationData.Entry entry = mNotificationData.get(i);
986            if (!entry.userLocked()) {
987                if (i == (N-1)) {
988                    if (DEBUG) Slog.d(TAG, "expanding top notification at " + i);
989                    expandView(entry, true);
990                } else {
991                    if (!entry.userExpanded()) {
992                        if (DEBUG) Slog.d(TAG, "collapsing notification at " + i);
993                        expandView(entry, false);
994                    } else {
995                        if (DEBUG) Slog.d(TAG, "ignoring user-modified notification at " + i);
996                    }
997                }
998            } else {
999                if (DEBUG) Slog.d(TAG, "ignoring notification being held by user at " + i);
1000            }
1001        }
1002    }
1003
1004    protected abstract void haltTicker();
1005    protected abstract void setAreThereNotifications();
1006    protected abstract void updateNotificationIcons();
1007    protected abstract void tick(IBinder key, StatusBarNotification n, boolean firstTime);
1008    protected abstract void updateExpandedViewPos(int expandedPosition);
1009    protected abstract int getExpandedViewMaxHeight();
1010    protected abstract boolean shouldDisableNavbarGestures();
1011
1012    protected boolean isTopNotification(ViewGroup parent, NotificationData.Entry entry) {
1013        return parent != null && parent.indexOfChild(entry.row) == 0;
1014    }
1015
1016    public void updateNotification(IBinder key, StatusBarNotification notification) {
1017        if (DEBUG) Slog.d(TAG, "updateNotification(" + key + " -> " + notification + ")");
1018
1019        final NotificationData.Entry oldEntry = mNotificationData.findByKey(key);
1020        if (oldEntry == null) {
1021            Slog.w(TAG, "updateNotification for unknown key: " + key);
1022            return;
1023        }
1024
1025        final StatusBarNotification oldNotification = oldEntry.notification;
1026
1027        // XXX: modify when we do something more intelligent with the two content views
1028        final RemoteViews oldContentView = oldNotification.notification.contentView;
1029        final RemoteViews contentView = notification.notification.contentView;
1030        final RemoteViews oldBigContentView = oldNotification.notification.bigContentView;
1031        final RemoteViews bigContentView = notification.notification.bigContentView;
1032
1033        if (DEBUG) {
1034            Slog.d(TAG, "old notification: when=" + oldNotification.notification.when
1035                    + " ongoing=" + oldNotification.isOngoing()
1036                    + " expanded=" + oldEntry.expanded
1037                    + " contentView=" + oldContentView
1038                    + " bigContentView=" + oldBigContentView
1039                    + " rowParent=" + oldEntry.row.getParent());
1040            Slog.d(TAG, "new notification: when=" + notification.notification.when
1041                    + " ongoing=" + oldNotification.isOngoing()
1042                    + " contentView=" + contentView
1043                    + " bigContentView=" + bigContentView);
1044        }
1045
1046        // Can we just reapply the RemoteViews in place?  If when didn't change, the order
1047        // didn't change.
1048
1049        // 1U is never null
1050        boolean contentsUnchanged = oldEntry.expanded != null
1051                && contentView.getPackage() != null
1052                && oldContentView.getPackage() != null
1053                && oldContentView.getPackage().equals(contentView.getPackage())
1054                && oldContentView.getLayoutId() == contentView.getLayoutId();
1055        // large view may be null
1056        boolean bigContentsUnchanged =
1057                (oldEntry.getLargeView() == null && bigContentView == null)
1058                || ((oldEntry.getLargeView() != null && bigContentView != null)
1059                    && bigContentView.getPackage() != null
1060                    && oldBigContentView.getPackage() != null
1061                    && oldBigContentView.getPackage().equals(bigContentView.getPackage())
1062                    && oldBigContentView.getLayoutId() == bigContentView.getLayoutId());
1063        ViewGroup rowParent = (ViewGroup) oldEntry.row.getParent();
1064        boolean orderUnchanged = notification.notification.when==oldNotification.notification.when
1065                && notification.score == oldNotification.score;
1066                // score now encompasses/supersedes isOngoing()
1067
1068        boolean updateTicker = notification.notification.tickerText != null
1069                && !TextUtils.equals(notification.notification.tickerText,
1070                        oldEntry.notification.notification.tickerText);
1071        boolean isTopAnyway = isTopNotification(rowParent, oldEntry);
1072        if (contentsUnchanged && bigContentsUnchanged && (orderUnchanged || isTopAnyway)) {
1073            if (DEBUG) Slog.d(TAG, "reusing notification for key: " + key);
1074            oldEntry.notification = notification;
1075            try {
1076                // Reapply the RemoteViews
1077                contentView.reapply(mContext, oldEntry.expanded, mOnClickHandler);
1078                if (bigContentView != null && oldEntry.getLargeView() != null) {
1079                    bigContentView.reapply(mContext, oldEntry.getLargeView(), mOnClickHandler);
1080                }
1081                // update the contentIntent
1082                final PendingIntent contentIntent = notification.notification.contentIntent;
1083                if (contentIntent != null) {
1084                    final View.OnClickListener listener = makeClicker(contentIntent,
1085                            notification.pkg, notification.tag, notification.id);
1086                    oldEntry.content.setOnClickListener(listener);
1087                } else {
1088                    oldEntry.content.setOnClickListener(null);
1089                }
1090                // Update the icon.
1091                final StatusBarIcon ic = new StatusBarIcon(notification.pkg,
1092                        notification.user,
1093                        notification.notification.icon, notification.notification.iconLevel,
1094                        notification.notification.number,
1095                        notification.notification.tickerText);
1096                if (!oldEntry.icon.set(ic)) {
1097                    handleNotificationError(key, notification, "Couldn't update icon: " + ic);
1098                    return;
1099                }
1100                updateExpansionStates();
1101            }
1102            catch (RuntimeException e) {
1103                // It failed to add cleanly.  Log, and remove the view from the panel.
1104                Slog.w(TAG, "Couldn't reapply views for package " + contentView.getPackage(), e);
1105                removeNotificationViews(key);
1106                addNotificationViews(key, notification);
1107            }
1108        } else {
1109            if (DEBUG) Slog.d(TAG, "not reusing notification for key: " + key);
1110            if (DEBUG) Slog.d(TAG, "contents was " + (contentsUnchanged ? "unchanged" : "changed"));
1111            if (DEBUG) Slog.d(TAG, "order was " + (orderUnchanged ? "unchanged" : "changed"));
1112            if (DEBUG) Slog.d(TAG, "notification is " + (isTopAnyway ? "top" : "not top"));
1113            final boolean wasExpanded = oldEntry.userExpanded();
1114            removeNotificationViews(key);
1115            addNotificationViews(key, notification);
1116            if (wasExpanded) {
1117                final NotificationData.Entry newEntry = mNotificationData.findByKey(key);
1118                expandView(newEntry, true);
1119                newEntry.setUserExpanded(true);
1120            }
1121        }
1122
1123        // Update the veto button accordingly (and as a result, whether this row is
1124        // swipe-dismissable)
1125        updateNotificationVetoButton(oldEntry.row, notification);
1126
1127        // Is this for you?
1128        boolean isForCurrentUser = notificationIsForCurrentUser(notification);
1129        if (DEBUG) Slog.d(TAG, "notification is " + (isForCurrentUser ? "" : "not ") + "for you");
1130
1131        // Restart the ticker if it's still running
1132        if (updateTicker && isForCurrentUser) {
1133            haltTicker();
1134            tick(key, notification, false);
1135        }
1136
1137        // Recalculate the position of the sliding windows and the titles.
1138        setAreThereNotifications();
1139        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1140
1141        // See if we need to update the intruder.
1142        if (ENABLE_INTRUDERS && oldNotification == mCurrentlyIntrudingNotification) {
1143            if (DEBUG) Slog.d(TAG, "updating the current intruder:" + notification);
1144            // XXX: this is a hack for Alarms. The real implementation will need to *update*
1145            // the intruder.
1146            if (notification.notification.fullScreenIntent == null) { // TODO(dsandler): consistent logic with add()
1147                if (DEBUG) Slog.d(TAG, "no longer intrudes!");
1148                mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
1149            }
1150        }
1151    }
1152
1153    // Q: What kinds of notifications should show during setup?
1154    // A: Almost none! Only things coming from the system (package is "android") that also
1155    // have special "kind" tags marking them as relevant for setup (see below).
1156    protected boolean showNotificationEvenIfUnprovisioned(StatusBarNotification sbn) {
1157        if ("android".equals(sbn.pkg)) {
1158            if (sbn.notification.kind != null) {
1159                for (String aKind : sbn.notification.kind) {
1160                    // IME switcher, created by InputMethodManagerService
1161                    if ("android.system.imeswitcher".equals(aKind)) return true;
1162                    // OTA availability & errors, created by SystemUpdateService
1163                    if ("android.system.update".equals(aKind)) return true;
1164                }
1165            }
1166        }
1167        return false;
1168    }
1169
1170    public boolean inKeyguardRestrictedInputMode() {
1171        KeyguardManager km = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
1172        return km.inKeyguardRestrictedInputMode();
1173    }
1174}
1175