1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
19import com.android.internal.R;
20import com.android.internal.app.WindowDecorActionBar;
21import com.android.internal.policy.PhoneWindow;
22
23import android.annotation.CallSuper;
24import android.annotation.DrawableRes;
25import android.annotation.IdRes;
26import android.annotation.LayoutRes;
27import android.annotation.NonNull;
28import android.annotation.Nullable;
29import android.annotation.StringRes;
30import android.annotation.StyleRes;
31import android.content.ComponentName;
32import android.content.Context;
33import android.content.ContextWrapper;
34import android.content.DialogInterface;
35import android.content.res.Configuration;
36import android.content.pm.ApplicationInfo;
37import android.content.res.ResourceId;
38import android.graphics.drawable.Drawable;
39import android.net.Uri;
40import android.os.Bundle;
41import android.os.Handler;
42import android.os.Looper;
43import android.os.Message;
44import android.util.Log;
45import android.util.TypedValue;
46import android.view.ActionMode;
47import android.view.ContextMenu;
48import android.view.ContextMenu.ContextMenuInfo;
49import android.view.ContextThemeWrapper;
50import android.view.Gravity;
51import android.view.KeyEvent;
52import android.view.LayoutInflater;
53import android.view.Menu;
54import android.view.MenuItem;
55import android.view.MotionEvent;
56import android.view.SearchEvent;
57import android.view.View;
58import android.view.View.OnCreateContextMenuListener;
59import android.view.ViewGroup;
60import android.view.ViewGroup.LayoutParams;
61import android.view.Window;
62import android.view.WindowManager;
63import android.view.accessibility.AccessibilityEvent;
64
65import java.lang.ref.WeakReference;
66
67/**
68 * Base class for Dialogs.
69 *
70 * <p>Note: Activities provide a facility to manage the creation, saving and
71 * restoring of dialogs. See {@link Activity#onCreateDialog(int)},
72 * {@link Activity#onPrepareDialog(int, Dialog)},
73 * {@link Activity#showDialog(int)}, and {@link Activity#dismissDialog(int)}. If
74 * these methods are used, {@link #getOwnerActivity()} will return the Activity
75 * that managed this dialog.
76 *
77 * <p>Often you will want to have a Dialog display on top of the current
78 * input method, because there is no reason for it to accept text.  You can
79 * do this by setting the {@link WindowManager.LayoutParams#FLAG_ALT_FOCUSABLE_IM
80 * WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM} window flag (assuming
81 * your Dialog takes input focus, as it the default) with the following code:
82 *
83 * <pre>
84 * getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
85 *         WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);</pre>
86 *
87 * <div class="special reference">
88 * <h3>Developer Guides</h3>
89 * <p>For more information about creating dialogs, read the
90 * <a href="{@docRoot}guide/topics/ui/dialogs.html">Dialogs</a> developer guide.</p>
91 * </div>
92 */
93public class Dialog implements DialogInterface, Window.Callback,
94        KeyEvent.Callback, OnCreateContextMenuListener, Window.OnWindowDismissedCallback {
95    private static final String TAG = "Dialog";
96    private Activity mOwnerActivity;
97
98    private final WindowManager mWindowManager;
99
100    final Context mContext;
101    final Window mWindow;
102
103    View mDecor;
104
105    private ActionBar mActionBar;
106    /**
107     * This field should be made private, so it is hidden from the SDK.
108     * {@hide}
109     */
110    protected boolean mCancelable = true;
111
112    private String mCancelAndDismissTaken;
113    private Message mCancelMessage;
114    private Message mDismissMessage;
115    private Message mShowMessage;
116
117    private OnKeyListener mOnKeyListener;
118
119    private boolean mCreated = false;
120    private boolean mShowing = false;
121    private boolean mCanceled = false;
122
123    private final Handler mHandler = new Handler();
124
125    private static final int DISMISS = 0x43;
126    private static final int CANCEL = 0x44;
127    private static final int SHOW = 0x45;
128
129    private final Handler mListenersHandler;
130
131    private SearchEvent mSearchEvent;
132
133    private ActionMode mActionMode;
134
135    private int mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
136
137    private final Runnable mDismissAction = this::dismissDialog;
138
139    /**
140     * Creates a dialog window that uses the default dialog theme.
141     * <p>
142     * The supplied {@code context} is used to obtain the window manager and
143     * base theme used to present the dialog.
144     *
145     * @param context the context in which the dialog should run
146     * @see android.R.styleable#Theme_dialogTheme
147     */
148    public Dialog(@NonNull Context context) {
149        this(context, 0, true);
150    }
151
152    /**
153     * Creates a dialog window that uses a custom dialog style.
154     * <p>
155     * The supplied {@code context} is used to obtain the window manager and
156     * base theme used to present the dialog.
157     * <p>
158     * The supplied {@code theme} is applied on top of the context's theme. See
159     * <a href="{@docRoot}guide/topics/resources/available-resources.html#stylesandthemes">
160     * Style and Theme Resources</a> for more information about defining and
161     * using styles.
162     *
163     * @param context the context in which the dialog should run
164     * @param themeResId a style resource describing the theme to use for the
165     *              window, or {@code 0} to use the default dialog theme
166     */
167    public Dialog(@NonNull Context context, @StyleRes int themeResId) {
168        this(context, themeResId, true);
169    }
170
171    Dialog(@NonNull Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
172        if (createContextThemeWrapper) {
173            if (themeResId == ResourceId.ID_NULL) {
174                final TypedValue outValue = new TypedValue();
175                context.getTheme().resolveAttribute(R.attr.dialogTheme, outValue, true);
176                themeResId = outValue.resourceId;
177            }
178            mContext = new ContextThemeWrapper(context, themeResId);
179        } else {
180            mContext = context;
181        }
182
183        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
184
185        final Window w = new PhoneWindow(mContext);
186        mWindow = w;
187        w.setCallback(this);
188        w.setOnWindowDismissedCallback(this);
189        w.setOnWindowSwipeDismissedCallback(() -> {
190            if (mCancelable) {
191                cancel();
192            }
193        });
194        w.setWindowManager(mWindowManager, null, null);
195        w.setGravity(Gravity.CENTER);
196
197        mListenersHandler = new ListenersHandler(this);
198    }
199
200    /**
201     * @deprecated
202     * @hide
203     */
204    @Deprecated
205    protected Dialog(@NonNull Context context, boolean cancelable,
206            @Nullable Message cancelCallback) {
207        this(context);
208        mCancelable = cancelable;
209        updateWindowForCancelable();
210        mCancelMessage = cancelCallback;
211    }
212
213    protected Dialog(@NonNull Context context, boolean cancelable,
214            @Nullable OnCancelListener cancelListener) {
215        this(context);
216        mCancelable = cancelable;
217        updateWindowForCancelable();
218        setOnCancelListener(cancelListener);
219    }
220
221    /**
222     * Retrieve the Context this Dialog is running in.
223     *
224     * @return Context The Context used by the Dialog.
225     */
226    public final @NonNull Context getContext() {
227        return mContext;
228    }
229
230    /**
231     * Retrieve the {@link ActionBar} attached to this dialog, if present.
232     *
233     * @return The ActionBar attached to the dialog or null if no ActionBar is present.
234     */
235    public @Nullable ActionBar getActionBar() {
236        return mActionBar;
237    }
238
239    /**
240     * Sets the Activity that owns this dialog. An example use: This Dialog will
241     * use the suggested volume control stream of the Activity.
242     *
243     * @param activity The Activity that owns this dialog.
244     */
245    public final void setOwnerActivity(@NonNull Activity activity) {
246        mOwnerActivity = activity;
247
248        getWindow().setVolumeControlStream(mOwnerActivity.getVolumeControlStream());
249    }
250
251    /**
252     * Returns the Activity that owns this Dialog. For example, if
253     * {@link Activity#showDialog(int)} is used to show this Dialog, that
254     * Activity will be the owner (by default). Depending on how this dialog was
255     * created, this may return null.
256     *
257     * @return The Activity that owns this Dialog.
258     */
259    public final @Nullable Activity getOwnerActivity() {
260        return mOwnerActivity;
261    }
262
263    /**
264     * @return Whether the dialog is currently showing.
265     */
266    public boolean isShowing() {
267        return mShowing;
268    }
269
270    /**
271     * Forces immediate creation of the dialog.
272     * <p>
273     * Note that you should not override this method to perform dialog creation.
274     * Rather, override {@link #onCreate(Bundle)}.
275     */
276    public void create() {
277        if (!mCreated) {
278            dispatchOnCreate(null);
279        }
280    }
281
282    /**
283     * Start the dialog and display it on screen.  The window is placed in the
284     * application layer and opaque.  Note that you should not override this
285     * method to do initialization when the dialog is shown, instead implement
286     * that in {@link #onStart}.
287     */
288    public void show() {
289        if (mShowing) {
290            if (mDecor != null) {
291                if (mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
292                    mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR);
293                }
294                mDecor.setVisibility(View.VISIBLE);
295            }
296            return;
297        }
298
299        mCanceled = false;
300
301        if (!mCreated) {
302            dispatchOnCreate(null);
303        } else {
304            // Fill the DecorView in on any configuration changes that
305            // may have occured while it was removed from the WindowManager.
306            final Configuration config = mContext.getResources().getConfiguration();
307            mWindow.getDecorView().dispatchConfigurationChanged(config);
308        }
309
310        onStart();
311        mDecor = mWindow.getDecorView();
312
313        if (mActionBar == null && mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
314            final ApplicationInfo info = mContext.getApplicationInfo();
315            mWindow.setDefaultIcon(info.icon);
316            mWindow.setDefaultLogo(info.logo);
317            mActionBar = new WindowDecorActionBar(this);
318        }
319
320        WindowManager.LayoutParams l = mWindow.getAttributes();
321        if ((l.softInputMode
322                & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) == 0) {
323            WindowManager.LayoutParams nl = new WindowManager.LayoutParams();
324            nl.copyFrom(l);
325            nl.softInputMode |=
326                    WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
327            l = nl;
328        }
329
330        mWindowManager.addView(mDecor, l);
331        mShowing = true;
332
333        sendShowMessage();
334    }
335
336    /**
337     * Hide the dialog, but do not dismiss it.
338     */
339    public void hide() {
340        if (mDecor != null) {
341            mDecor.setVisibility(View.GONE);
342        }
343    }
344
345    /**
346     * Dismiss this dialog, removing it from the screen. This method can be
347     * invoked safely from any thread.  Note that you should not override this
348     * method to do cleanup when the dialog is dismissed, instead implement
349     * that in {@link #onStop}.
350     */
351    @Override
352    public void dismiss() {
353        if (Looper.myLooper() == mHandler.getLooper()) {
354            dismissDialog();
355        } else {
356            mHandler.post(mDismissAction);
357        }
358    }
359
360    void dismissDialog() {
361        if (mDecor == null || !mShowing) {
362            return;
363        }
364
365        if (mWindow.isDestroyed()) {
366            Log.e(TAG, "Tried to dismissDialog() but the Dialog's window was already destroyed!");
367            return;
368        }
369
370        try {
371            mWindowManager.removeViewImmediate(mDecor);
372        } finally {
373            if (mActionMode != null) {
374                mActionMode.finish();
375            }
376            mDecor = null;
377            mWindow.closeAllPanels();
378            onStop();
379            mShowing = false;
380
381            sendDismissMessage();
382        }
383    }
384
385    private void sendDismissMessage() {
386        if (mDismissMessage != null) {
387            // Obtain a new message so this dialog can be re-used
388            Message.obtain(mDismissMessage).sendToTarget();
389        }
390    }
391
392    private void sendShowMessage() {
393        if (mShowMessage != null) {
394            // Obtain a new message so this dialog can be re-used
395            Message.obtain(mShowMessage).sendToTarget();
396        }
397    }
398
399    // internal method to make sure mCreated is set properly without requiring
400    // users to call through to super in onCreate
401    void dispatchOnCreate(Bundle savedInstanceState) {
402        if (!mCreated) {
403            onCreate(savedInstanceState);
404            mCreated = true;
405        }
406    }
407
408    /**
409     * Similar to {@link Activity#onCreate}, you should initialize your dialog
410     * in this method, including calling {@link #setContentView}.
411     * @param savedInstanceState If this dialog is being reinitialized after a
412     *     the hosting activity was previously shut down, holds the result from
413     *     the most recent call to {@link #onSaveInstanceState}, or null if this
414     *     is the first time.
415     */
416    protected void onCreate(Bundle savedInstanceState) {
417    }
418
419    /**
420     * Called when the dialog is starting.
421     */
422    protected void onStart() {
423        if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
424    }
425
426    /**
427     * Called to tell you that you're stopping.
428     */
429    protected void onStop() {
430        if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
431    }
432
433    private static final String DIALOG_SHOWING_TAG = "android:dialogShowing";
434    private static final String DIALOG_HIERARCHY_TAG = "android:dialogHierarchy";
435
436    /**
437     * Saves the state of the dialog into a bundle.
438     *
439     * The default implementation saves the state of its view hierarchy, so you'll
440     * likely want to call through to super if you override this to save additional
441     * state.
442     * @return A bundle with the state of the dialog.
443     */
444    public @NonNull Bundle onSaveInstanceState() {
445        Bundle bundle = new Bundle();
446        bundle.putBoolean(DIALOG_SHOWING_TAG, mShowing);
447        if (mCreated) {
448            bundle.putBundle(DIALOG_HIERARCHY_TAG, mWindow.saveHierarchyState());
449        }
450        return bundle;
451    }
452
453    /**
454     * Restore the state of the dialog from a previously saved bundle.
455     *
456     * The default implementation restores the state of the dialog's view
457     * hierarchy that was saved in the default implementation of {@link #onSaveInstanceState()},
458     * so be sure to call through to super when overriding unless you want to
459     * do all restoring of state yourself.
460     * @param savedInstanceState The state of the dialog previously saved by
461     *     {@link #onSaveInstanceState()}.
462     */
463    public void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
464        final Bundle dialogHierarchyState = savedInstanceState.getBundle(DIALOG_HIERARCHY_TAG);
465        if (dialogHierarchyState == null) {
466            // dialog has never been shown, or onCreated, nothing to restore.
467            return;
468        }
469        dispatchOnCreate(savedInstanceState);
470        mWindow.restoreHierarchyState(dialogHierarchyState);
471        if (savedInstanceState.getBoolean(DIALOG_SHOWING_TAG)) {
472            show();
473        }
474    }
475
476    /**
477     * Retrieve the current Window for the activity.  This can be used to
478     * directly access parts of the Window API that are not available
479     * through Activity/Screen.
480     *
481     * @return Window The current window, or null if the activity is not
482     *         visual.
483     */
484    public @Nullable Window getWindow() {
485        return mWindow;
486    }
487
488    /**
489     * Call {@link android.view.Window#getCurrentFocus} on the
490     * Window if this Activity to return the currently focused view.
491     *
492     * @return View The current View with focus or null.
493     *
494     * @see #getWindow
495     * @see android.view.Window#getCurrentFocus
496     */
497    public @Nullable View getCurrentFocus() {
498        return mWindow != null ? mWindow.getCurrentFocus() : null;
499    }
500
501    /**
502     * Finds the first descendant view with the given ID or {@code null} if the
503     * ID is invalid (< 0), there is no matching view in the hierarchy, or the
504     * dialog has not yet been fully created (for example, via {@link #show()}
505     * or {@link #create()}).
506     * <p>
507     * <strong>Note:</strong> In most cases -- depending on compiler support --
508     * the resulting view is automatically cast to the target class type. If
509     * the target class type is unconstrained, an explicit cast may be
510     * necessary.
511     *
512     * @param id the ID to search for
513     * @return a view with given ID if found, or {@code null} otherwise
514     * @see View#findViewById(int)
515     */
516    @Nullable
517    public <T extends View> T findViewById(@IdRes int id) {
518        return mWindow.findViewById(id);
519    }
520
521    /**
522     * Set the screen content from a layout resource.  The resource will be
523     * inflated, adding all top-level views to the screen.
524     *
525     * @param layoutResID Resource ID to be inflated.
526     */
527    public void setContentView(@LayoutRes int layoutResID) {
528        mWindow.setContentView(layoutResID);
529    }
530
531    /**
532     * Set the screen content to an explicit view.  This view is placed
533     * directly into the screen's view hierarchy.  It can itself be a complex
534     * view hierarchy.
535     *
536     * @param view The desired content to display.
537     */
538    public void setContentView(@NonNull View view) {
539        mWindow.setContentView(view);
540    }
541
542    /**
543     * Set the screen content to an explicit view.  This view is placed
544     * directly into the screen's view hierarchy.  It can itself be a complex
545     * view hierarchy.
546     *
547     * @param view The desired content to display.
548     * @param params Layout parameters for the view.
549     */
550    public void setContentView(@NonNull View view, @Nullable ViewGroup.LayoutParams params) {
551        mWindow.setContentView(view, params);
552    }
553
554    /**
555     * Add an additional content view to the screen.  Added after any existing
556     * ones in the screen -- existing views are NOT removed.
557     *
558     * @param view The desired content to display.
559     * @param params Layout parameters for the view.
560     */
561    public void addContentView(@NonNull View view, @Nullable ViewGroup.LayoutParams params) {
562        mWindow.addContentView(view, params);
563    }
564
565    /**
566     * Set the title text for this dialog's window.
567     *
568     * @param title The new text to display in the title.
569     */
570    public void setTitle(@Nullable CharSequence title) {
571        mWindow.setTitle(title);
572        mWindow.getAttributes().setTitle(title);
573    }
574
575    /**
576     * Set the title text for this dialog's window. The text is retrieved
577     * from the resources with the supplied identifier.
578     *
579     * @param titleId the title's text resource identifier
580     */
581    public void setTitle(@StringRes int titleId) {
582        setTitle(mContext.getText(titleId));
583    }
584
585    /**
586     * A key was pressed down.
587     *
588     * <p>If the focused view didn't want this event, this method is called.
589     *
590     * <p>The default implementation consumed the KEYCODE_BACK to later
591     * handle it in {@link #onKeyUp}.
592     *
593     * @see #onKeyUp
594     * @see android.view.KeyEvent
595     */
596    @Override
597    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
598        if (keyCode == KeyEvent.KEYCODE_BACK) {
599            event.startTracking();
600            return true;
601        }
602
603        return false;
604    }
605
606    /**
607     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
608     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
609     * the event).
610     */
611    @Override
612    public boolean onKeyLongPress(int keyCode, @NonNull KeyEvent event) {
613        return false;
614    }
615
616    /**
617     * A key was released.
618     *
619     * <p>The default implementation handles KEYCODE_BACK to close the
620     * dialog.
621     *
622     * @see #onKeyDown
623     * @see KeyEvent
624     */
625    @Override
626    public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
627        if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
628                && !event.isCanceled()) {
629            onBackPressed();
630            return true;
631        }
632        return false;
633    }
634
635    /**
636     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
637     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
638     * the event).
639     */
640    @Override
641    public boolean onKeyMultiple(int keyCode, int repeatCount, @NonNull KeyEvent event) {
642        return false;
643    }
644
645    /**
646     * Called when the dialog has detected the user's press of the back
647     * key.  The default implementation simply cancels the dialog (only if
648     * it is cancelable), but you can override this to do whatever you want.
649     */
650    public void onBackPressed() {
651        if (mCancelable) {
652            cancel();
653        }
654    }
655
656    /**
657     * Called when a key shortcut event is not handled by any of the views in the Dialog.
658     * Override this method to implement global key shortcuts for the Dialog.
659     * Key shortcuts can also be implemented by setting the
660     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
661     *
662     * @param keyCode The value in event.getKeyCode().
663     * @param event Description of the key event.
664     * @return True if the key shortcut was handled.
665     */
666    public boolean onKeyShortcut(int keyCode, @NonNull KeyEvent event) {
667        return false;
668    }
669
670    /**
671     * Called when a touch screen event was not handled by any of the views
672     * under it. This is most useful to process touch events that happen outside
673     * of your window bounds, where there is no view to receive it.
674     *
675     * @param event The touch screen event being processed.
676     * @return Return true if you have consumed the event, false if you haven't.
677     *         The default implementation will cancel the dialog when a touch
678     *         happens outside of the window bounds.
679     */
680    public boolean onTouchEvent(@NonNull MotionEvent event) {
681        if (mCancelable && mShowing && mWindow.shouldCloseOnTouch(mContext, event)) {
682            cancel();
683            return true;
684        }
685
686        return false;
687    }
688
689    /**
690     * Called when the trackball was moved and not handled by any of the
691     * views inside of the activity.  So, for example, if the trackball moves
692     * while focus is on a button, you will receive a call here because
693     * buttons do not normally do anything with trackball events.  The call
694     * here happens <em>before</em> trackball movements are converted to
695     * DPAD key events, which then get sent back to the view hierarchy, and
696     * will be processed at the point for things like focus navigation.
697     *
698     * @param event The trackball event being processed.
699     *
700     * @return Return true if you have consumed the event, false if you haven't.
701     * The default implementation always returns false.
702     */
703    public boolean onTrackballEvent(@NonNull MotionEvent event) {
704        return false;
705    }
706
707    /**
708     * Called when a generic motion event was not handled by any of the
709     * views inside of the dialog.
710     * <p>
711     * Generic motion events describe joystick movements, mouse hovers, track pad
712     * touches, scroll wheel movements and other input events.  The
713     * {@link MotionEvent#getSource() source} of the motion event specifies
714     * the class of input that was received.  Implementations of this method
715     * must examine the bits in the source before processing the event.
716     * The following code example shows how this is done.
717     * </p><p>
718     * Generic motion events with source class
719     * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
720     * are delivered to the view under the pointer.  All other generic motion events are
721     * delivered to the focused view.
722     * </p><p>
723     * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
724     * handle this event.
725     * </p>
726     *
727     * @param event The generic motion event being processed.
728     *
729     * @return Return true if you have consumed the event, false if you haven't.
730     * The default implementation always returns false.
731     */
732    public boolean onGenericMotionEvent(@NonNull MotionEvent event) {
733        return false;
734    }
735
736    @Override
737    public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
738        if (mDecor != null) {
739            mWindowManager.updateViewLayout(mDecor, params);
740        }
741    }
742
743    @Override
744    public void onContentChanged() {
745    }
746
747    @Override
748    public void onWindowFocusChanged(boolean hasFocus) {
749    }
750
751    @Override
752    public void onAttachedToWindow() {
753    }
754
755    @Override
756    public void onDetachedFromWindow() {
757    }
758
759    /** @hide */
760    @Override
761    public void onWindowDismissed(boolean finishTask, boolean suppressWindowTransition) {
762        dismiss();
763    }
764
765    /**
766     * Called to process key events.  You can override this to intercept all
767     * key events before they are dispatched to the window.  Be sure to call
768     * this implementation for key events that should be handled normally.
769     *
770     * @param event The key event.
771     *
772     * @return boolean Return true if this event was consumed.
773     */
774    @Override
775    public boolean dispatchKeyEvent(@NonNull KeyEvent event) {
776        if ((mOnKeyListener != null) && (mOnKeyListener.onKey(this, event.getKeyCode(), event))) {
777            return true;
778        }
779        if (mWindow.superDispatchKeyEvent(event)) {
780            return true;
781        }
782        return event.dispatch(this, mDecor != null
783                ? mDecor.getKeyDispatcherState() : null, this);
784    }
785
786    /**
787     * Called to process a key shortcut event.
788     * You can override this to intercept all key shortcut events before they are
789     * dispatched to the window.  Be sure to call this implementation for key shortcut
790     * events that should be handled normally.
791     *
792     * @param event The key shortcut event.
793     * @return True if this event was consumed.
794     */
795    @Override
796    public boolean dispatchKeyShortcutEvent(@NonNull KeyEvent event) {
797        if (mWindow.superDispatchKeyShortcutEvent(event)) {
798            return true;
799        }
800        return onKeyShortcut(event.getKeyCode(), event);
801    }
802
803    /**
804     * Called to process touch screen events.  You can override this to
805     * intercept all touch screen events before they are dispatched to the
806     * window.  Be sure to call this implementation for touch screen events
807     * that should be handled normally.
808     *
809     * @param ev The touch screen event.
810     *
811     * @return boolean Return true if this event was consumed.
812     */
813    @Override
814    public boolean dispatchTouchEvent(@NonNull MotionEvent ev) {
815        if (mWindow.superDispatchTouchEvent(ev)) {
816            return true;
817        }
818        return onTouchEvent(ev);
819    }
820
821    /**
822     * Called to process trackball events.  You can override this to
823     * intercept all trackball events before they are dispatched to the
824     * window.  Be sure to call this implementation for trackball events
825     * that should be handled normally.
826     *
827     * @param ev The trackball event.
828     *
829     * @return boolean Return true if this event was consumed.
830     */
831    @Override
832    public boolean dispatchTrackballEvent(@NonNull MotionEvent ev) {
833        if (mWindow.superDispatchTrackballEvent(ev)) {
834            return true;
835        }
836        return onTrackballEvent(ev);
837    }
838
839    /**
840     * Called to process generic motion events.  You can override this to
841     * intercept all generic motion events before they are dispatched to the
842     * window.  Be sure to call this implementation for generic motion events
843     * that should be handled normally.
844     *
845     * @param ev The generic motion event.
846     *
847     * @return boolean Return true if this event was consumed.
848     */
849    @Override
850    public boolean dispatchGenericMotionEvent(@NonNull MotionEvent ev) {
851        if (mWindow.superDispatchGenericMotionEvent(ev)) {
852            return true;
853        }
854        return onGenericMotionEvent(ev);
855    }
856
857    @Override
858    public boolean dispatchPopulateAccessibilityEvent(@NonNull AccessibilityEvent event) {
859        event.setClassName(getClass().getName());
860        event.setPackageName(mContext.getPackageName());
861
862        LayoutParams params = getWindow().getAttributes();
863        boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
864            (params.height == LayoutParams.MATCH_PARENT);
865        event.setFullScreen(isFullScreen);
866
867        return false;
868    }
869
870    /**
871     * @see Activity#onCreatePanelView(int)
872     */
873    @Override
874    public View onCreatePanelView(int featureId) {
875        return null;
876    }
877
878    /**
879     * @see Activity#onCreatePanelMenu(int, Menu)
880     */
881    @Override
882    public boolean onCreatePanelMenu(int featureId, @NonNull Menu menu) {
883        if (featureId == Window.FEATURE_OPTIONS_PANEL) {
884            return onCreateOptionsMenu(menu);
885        }
886
887        return false;
888    }
889
890    /**
891     * @see Activity#onPreparePanel(int, View, Menu)
892     */
893    @Override
894    public boolean onPreparePanel(int featureId, View view, Menu menu) {
895        if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
896            return onPrepareOptionsMenu(menu) && menu.hasVisibleItems();
897        }
898        return true;
899    }
900
901    /**
902     * @see Activity#onMenuOpened(int, Menu)
903     */
904    @Override
905    public boolean onMenuOpened(int featureId, Menu menu) {
906        if (featureId == Window.FEATURE_ACTION_BAR) {
907            mActionBar.dispatchMenuVisibilityChanged(true);
908        }
909        return true;
910    }
911
912    /**
913     * @see Activity#onMenuItemSelected(int, MenuItem)
914     */
915    @Override
916    public boolean onMenuItemSelected(int featureId, MenuItem item) {
917        return false;
918    }
919
920    /**
921     * @see Activity#onPanelClosed(int, Menu)
922     */
923    @Override
924    public void onPanelClosed(int featureId, Menu menu) {
925        if (featureId == Window.FEATURE_ACTION_BAR) {
926            mActionBar.dispatchMenuVisibilityChanged(false);
927        }
928    }
929
930    /**
931     * It is usually safe to proxy this call to the owner activity's
932     * {@link Activity#onCreateOptionsMenu(Menu)} if the client desires the same
933     * menu for this Dialog.
934     *
935     * @see Activity#onCreateOptionsMenu(Menu)
936     * @see #getOwnerActivity()
937     */
938    public boolean onCreateOptionsMenu(@NonNull Menu menu) {
939        return true;
940    }
941
942    /**
943     * It is usually safe to proxy this call to the owner activity's
944     * {@link Activity#onPrepareOptionsMenu(Menu)} if the client desires the
945     * same menu for this Dialog.
946     *
947     * @see Activity#onPrepareOptionsMenu(Menu)
948     * @see #getOwnerActivity()
949     */
950    public boolean onPrepareOptionsMenu(@NonNull Menu menu) {
951        return true;
952    }
953
954    /**
955     * @see Activity#onOptionsItemSelected(MenuItem)
956     */
957    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
958        return false;
959    }
960
961    /**
962     * @see Activity#onOptionsMenuClosed(Menu)
963     */
964    public void onOptionsMenuClosed(@NonNull Menu menu) {
965    }
966
967    /**
968     * @see Activity#openOptionsMenu()
969     */
970    public void openOptionsMenu() {
971        if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL)) {
972            mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
973        }
974    }
975
976    /**
977     * @see Activity#closeOptionsMenu()
978     */
979    public void closeOptionsMenu() {
980        if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL)) {
981            mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
982        }
983    }
984
985    /**
986     * @see Activity#invalidateOptionsMenu()
987     */
988    public void invalidateOptionsMenu() {
989        if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL)) {
990            mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
991        }
992    }
993
994    /**
995     * @see Activity#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)
996     */
997    @Override
998    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
999    }
1000
1001    /**
1002     * @see Activity#registerForContextMenu(View)
1003     */
1004    public void registerForContextMenu(@NonNull View view) {
1005        view.setOnCreateContextMenuListener(this);
1006    }
1007
1008    /**
1009     * @see Activity#unregisterForContextMenu(View)
1010     */
1011    public void unregisterForContextMenu(@NonNull View view) {
1012        view.setOnCreateContextMenuListener(null);
1013    }
1014
1015    /**
1016     * @see Activity#openContextMenu(View)
1017     */
1018    public void openContextMenu(@NonNull View view) {
1019        view.showContextMenu();
1020    }
1021
1022    /**
1023     * @see Activity#onContextItemSelected(MenuItem)
1024     */
1025    public boolean onContextItemSelected(@NonNull MenuItem item) {
1026        return false;
1027    }
1028
1029    /**
1030     * @see Activity#onContextMenuClosed(Menu)
1031     */
1032    public void onContextMenuClosed(@NonNull Menu menu) {
1033    }
1034
1035    /**
1036     * This hook is called when the user signals the desire to start a search.
1037     */
1038    @Override
1039    public boolean onSearchRequested(@NonNull SearchEvent searchEvent) {
1040        mSearchEvent = searchEvent;
1041        return onSearchRequested();
1042    }
1043
1044    /**
1045     * This hook is called when the user signals the desire to start a search.
1046     */
1047    @Override
1048    public boolean onSearchRequested() {
1049        final SearchManager searchManager = (SearchManager) mContext
1050                .getSystemService(Context.SEARCH_SERVICE);
1051
1052        // associate search with owner activity
1053        final ComponentName appName = getAssociatedActivity();
1054        if (appName != null && searchManager.getSearchableInfo(appName) != null) {
1055            searchManager.startSearch(null, false, appName, null, false);
1056            dismiss();
1057            return true;
1058        } else {
1059            return false;
1060        }
1061    }
1062
1063    /**
1064     * During the onSearchRequested() callbacks, this function will return the
1065     * {@link SearchEvent} that triggered the callback, if it exists.
1066     *
1067     * @return SearchEvent The SearchEvent that triggered the {@link
1068     *                    #onSearchRequested} callback.
1069     */
1070    public final @Nullable SearchEvent getSearchEvent() {
1071        return mSearchEvent;
1072    }
1073
1074    @Override
1075    public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
1076        if (mActionBar != null && mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) {
1077            return mActionBar.startActionMode(callback);
1078        }
1079        return null;
1080    }
1081
1082    @Override
1083    public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
1084        try {
1085            mActionModeTypeStarting = type;
1086            return onWindowStartingActionMode(callback);
1087        } finally {
1088            mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
1089        }
1090    }
1091
1092    /**
1093     * {@inheritDoc}
1094     *
1095     * Note that if you override this method you should always call through
1096     * to the superclass implementation by calling super.onActionModeStarted(mode).
1097     */
1098    @Override
1099    @CallSuper
1100    public void onActionModeStarted(ActionMode mode) {
1101        mActionMode = mode;
1102    }
1103
1104    /**
1105     * {@inheritDoc}
1106     *
1107     * Note that if you override this method you should always call through
1108     * to the superclass implementation by calling super.onActionModeFinished(mode).
1109     */
1110    @Override
1111    @CallSuper
1112    public void onActionModeFinished(ActionMode mode) {
1113        if (mode == mActionMode) {
1114            mActionMode = null;
1115        }
1116    }
1117
1118    /**
1119     * @return The activity associated with this dialog, or null if there is no associated activity.
1120     */
1121    private ComponentName getAssociatedActivity() {
1122        Activity activity = mOwnerActivity;
1123        Context context = getContext();
1124        while (activity == null && context != null) {
1125            if (context instanceof Activity) {
1126                activity = (Activity) context;  // found it!
1127            } else {
1128                context = (context instanceof ContextWrapper) ?
1129                        ((ContextWrapper) context).getBaseContext() : // unwrap one level
1130                        null;                                         // done
1131            }
1132        }
1133        return activity == null ? null : activity.getComponentName();
1134    }
1135
1136
1137    /**
1138     * Request that key events come to this dialog. Use this if your
1139     * dialog has no views with focus, but the dialog still wants
1140     * a chance to process key events.
1141     *
1142     * @param get true if the dialog should receive key events, false otherwise
1143     * @see android.view.Window#takeKeyEvents
1144     */
1145    public void takeKeyEvents(boolean get) {
1146        mWindow.takeKeyEvents(get);
1147    }
1148
1149    /**
1150     * Enable extended window features.  This is a convenience for calling
1151     * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
1152     *
1153     * @param featureId The desired feature as defined in
1154     *                  {@link android.view.Window}.
1155     * @return Returns true if the requested feature is supported and now
1156     *         enabled.
1157     *
1158     * @see android.view.Window#requestFeature
1159     */
1160    public final boolean requestWindowFeature(int featureId) {
1161        return getWindow().requestFeature(featureId);
1162    }
1163
1164    /**
1165     * Convenience for calling
1166     * {@link android.view.Window#setFeatureDrawableResource}.
1167     */
1168    public final void setFeatureDrawableResource(int featureId, @DrawableRes int resId) {
1169        getWindow().setFeatureDrawableResource(featureId, resId);
1170    }
1171
1172    /**
1173     * Convenience for calling
1174     * {@link android.view.Window#setFeatureDrawableUri}.
1175     */
1176    public final void setFeatureDrawableUri(int featureId, @Nullable Uri uri) {
1177        getWindow().setFeatureDrawableUri(featureId, uri);
1178    }
1179
1180    /**
1181     * Convenience for calling
1182     * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
1183     */
1184    public final void setFeatureDrawable(int featureId, @Nullable Drawable drawable) {
1185        getWindow().setFeatureDrawable(featureId, drawable);
1186    }
1187
1188    /**
1189     * Convenience for calling
1190     * {@link android.view.Window#setFeatureDrawableAlpha}.
1191     */
1192    public final void setFeatureDrawableAlpha(int featureId, int alpha) {
1193        getWindow().setFeatureDrawableAlpha(featureId, alpha);
1194    }
1195
1196    public @NonNull LayoutInflater getLayoutInflater() {
1197        return getWindow().getLayoutInflater();
1198    }
1199
1200    /**
1201     * Sets whether this dialog is cancelable with the
1202     * {@link KeyEvent#KEYCODE_BACK BACK} key.
1203     */
1204    public void setCancelable(boolean flag) {
1205        mCancelable = flag;
1206        updateWindowForCancelable();
1207    }
1208
1209    /**
1210     * Sets whether this dialog is canceled when touched outside the window's
1211     * bounds. If setting to true, the dialog is set to be cancelable if not
1212     * already set.
1213     *
1214     * @param cancel Whether the dialog should be canceled when touched outside
1215     *            the window.
1216     */
1217    public void setCanceledOnTouchOutside(boolean cancel) {
1218        if (cancel && !mCancelable) {
1219            mCancelable = true;
1220            updateWindowForCancelable();
1221        }
1222
1223        mWindow.setCloseOnTouchOutside(cancel);
1224    }
1225
1226    /**
1227     * Cancel the dialog.  This is essentially the same as calling {@link #dismiss()}, but it will
1228     * also call your {@link DialogInterface.OnCancelListener} (if registered).
1229     */
1230    @Override
1231    public void cancel() {
1232        if (!mCanceled && mCancelMessage != null) {
1233            mCanceled = true;
1234            // Obtain a new message so this dialog can be re-used
1235            Message.obtain(mCancelMessage).sendToTarget();
1236        }
1237        dismiss();
1238    }
1239
1240    /**
1241     * Set a listener to be invoked when the dialog is canceled.
1242     *
1243     * <p>This will only be invoked when the dialog is canceled.
1244     * Cancel events alone will not capture all ways that
1245     * the dialog might be dismissed. If the creator needs
1246     * to know when a dialog is dismissed in general, use
1247     * {@link #setOnDismissListener}.</p>
1248     *
1249     * @param listener The {@link DialogInterface.OnCancelListener} to use.
1250     */
1251    public void setOnCancelListener(@Nullable OnCancelListener listener) {
1252        if (mCancelAndDismissTaken != null) {
1253            throw new IllegalStateException(
1254                    "OnCancelListener is already taken by "
1255                    + mCancelAndDismissTaken + " and can not be replaced.");
1256        }
1257        if (listener != null) {
1258            mCancelMessage = mListenersHandler.obtainMessage(CANCEL, listener);
1259        } else {
1260            mCancelMessage = null;
1261        }
1262    }
1263
1264    /**
1265     * Set a message to be sent when the dialog is canceled.
1266     * @param msg The msg to send when the dialog is canceled.
1267     * @see #setOnCancelListener(android.content.DialogInterface.OnCancelListener)
1268     */
1269    public void setCancelMessage(@Nullable Message msg) {
1270        mCancelMessage = msg;
1271    }
1272
1273    /**
1274     * Set a listener to be invoked when the dialog is dismissed.
1275     * @param listener The {@link DialogInterface.OnDismissListener} to use.
1276     */
1277    public void setOnDismissListener(@Nullable OnDismissListener listener) {
1278        if (mCancelAndDismissTaken != null) {
1279            throw new IllegalStateException(
1280                    "OnDismissListener is already taken by "
1281                    + mCancelAndDismissTaken + " and can not be replaced.");
1282        }
1283        if (listener != null) {
1284            mDismissMessage = mListenersHandler.obtainMessage(DISMISS, listener);
1285        } else {
1286            mDismissMessage = null;
1287        }
1288    }
1289
1290    /**
1291     * Sets a listener to be invoked when the dialog is shown.
1292     * @param listener The {@link DialogInterface.OnShowListener} to use.
1293     */
1294    public void setOnShowListener(@Nullable OnShowListener listener) {
1295        if (listener != null) {
1296            mShowMessage = mListenersHandler.obtainMessage(SHOW, listener);
1297        } else {
1298            mShowMessage = null;
1299        }
1300    }
1301
1302    /**
1303     * Set a message to be sent when the dialog is dismissed.
1304     * @param msg The msg to send when the dialog is dismissed.
1305     */
1306    public void setDismissMessage(@Nullable Message msg) {
1307        mDismissMessage = msg;
1308    }
1309
1310    /** @hide */
1311    public boolean takeCancelAndDismissListeners(@Nullable String msg,
1312            @Nullable OnCancelListener cancel, @Nullable OnDismissListener dismiss) {
1313        if (mCancelAndDismissTaken != null) {
1314            mCancelAndDismissTaken = null;
1315        } else if (mCancelMessage != null || mDismissMessage != null) {
1316            return false;
1317        }
1318
1319        setOnCancelListener(cancel);
1320        setOnDismissListener(dismiss);
1321        mCancelAndDismissTaken = msg;
1322
1323        return true;
1324    }
1325
1326    /**
1327     * By default, this will use the owner Activity's suggested stream type.
1328     *
1329     * @see Activity#setVolumeControlStream(int)
1330     * @see #setOwnerActivity(Activity)
1331     */
1332    public final void setVolumeControlStream(int streamType) {
1333        getWindow().setVolumeControlStream(streamType);
1334    }
1335
1336    /**
1337     * @see Activity#getVolumeControlStream()
1338     */
1339    public final int getVolumeControlStream() {
1340        return getWindow().getVolumeControlStream();
1341    }
1342
1343    /**
1344     * Sets the callback that will be called if a key is dispatched to the dialog.
1345     */
1346    public void setOnKeyListener(@Nullable OnKeyListener onKeyListener) {
1347        mOnKeyListener = onKeyListener;
1348    }
1349
1350    private static final class ListenersHandler extends Handler {
1351        private final WeakReference<DialogInterface> mDialog;
1352
1353        public ListenersHandler(Dialog dialog) {
1354            mDialog = new WeakReference<>(dialog);
1355        }
1356
1357        @Override
1358        public void handleMessage(Message msg) {
1359            switch (msg.what) {
1360                case DISMISS:
1361                    ((OnDismissListener) msg.obj).onDismiss(mDialog.get());
1362                    break;
1363                case CANCEL:
1364                    ((OnCancelListener) msg.obj).onCancel(mDialog.get());
1365                    break;
1366                case SHOW:
1367                    ((OnShowListener) msg.obj).onShow(mDialog.get());
1368                    break;
1369            }
1370        }
1371    }
1372
1373    private void updateWindowForCancelable() {
1374        mWindow.setCloseOnSwipeEnabled(mCancelable);
1375    }
1376}
1377