summaryrefslogtreecommitdiffstats
path: root/src/com/android/wallpaper/livepicker/LiveWallpaperPreview.java
blob: f5bfce99b175c215d417318837cd71b64ef24a2f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.wallpaper.livepicker;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.WallpaperInfo;
import android.app.WallpaperManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.res.Resources.NotFoundException;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.service.wallpaper.IWallpaperConnection;
import android.service.wallpaper.IWallpaperEngine;
import android.service.wallpaper.IWallpaperService;
import android.service.wallpaper.WallpaperService;
import android.service.wallpaper.WallpaperSettingsActivity;
import android.support.design.widget.BottomSheetBehavior;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toolbar;

import java.io.IOException;

public class LiveWallpaperPreview extends Activity {
    static final String EXTRA_LIVE_WALLPAPER_INFO = "android.live_wallpaper.info";

    private static final String LOG_TAG = "LiveWallpaperPreview";

    private static final boolean SHOW_DUMMY_DATA = false;

    private WallpaperManager mWallpaperManager;
    private WallpaperConnection mWallpaperConnection;

    private String mSettings;
    private String mPackageName;
    private Intent mWallpaperIntent;

    private TextView mAttributionTitle;
    private TextView mAttributionSubtitle1;
    private TextView mAttributionSubtitle2;
    private Button mAttributionExploreButton;
    private ImageButton mPreviewPaneArrow;
    private View mBottomSheet;
    private View mSpacer;
    private View mLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    protected void init() {
        Bundle extras = getIntent().getExtras();
        WallpaperInfo info = extras.getParcelable(EXTRA_LIVE_WALLPAPER_INFO);
        if (info == null) {
            setResult(RESULT_CANCELED);
            finish();
        }
        initUI(info);
    }

    protected void initUI(WallpaperInfo info) {
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        setContentView(R.layout.live_wallpaper_preview);
        mAttributionTitle = (TextView) findViewById(R.id.preview_attribution_pane_title);
        mAttributionSubtitle1 = (TextView) findViewById(R.id.preview_attribution_pane_subtitle1);
        mAttributionSubtitle2 = (TextView) findViewById(R.id.preview_attribution_pane_subtitle2);
        mAttributionExploreButton = (Button) findViewById(
                R.id.preview_attribution_pane_explore_button);
        mPreviewPaneArrow = (ImageButton) findViewById(R.id.preview_attribution_pane_arrow);
        mBottomSheet = findViewById(R.id.bottom_sheet);
        mSpacer = findViewById(R.id.spacer);
        mLoading = findViewById(R.id.loading);

        mSettings = info.getSettingsActivity();
        mPackageName = info.getPackageName();
        mWallpaperIntent = new Intent(WallpaperService.SERVICE_INTERFACE)
                .setClassName(info.getPackageName(), info.getServiceName());

        setActionBar((Toolbar) findViewById(R.id.toolbar));
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setDisplayShowTitleEnabled(false);

        mWallpaperManager = WallpaperManager.getInstance(this);
        mWallpaperConnection = new WallpaperConnection(mWallpaperIntent);

        populateAttributionPane(info);
    }

    private void populateAttributionPane(WallpaperInfo info) {
        if (!info.getShowMetadataInPreview() && !SHOW_DUMMY_DATA) {
            mBottomSheet.setVisibility(View.GONE);
            return;
        }
        final BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(mBottomSheet);

        OnClickListener onClickListener = new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                } else if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                }
            }
        };
        mAttributionTitle.setOnClickListener(onClickListener);
        mPreviewPaneArrow.setOnClickListener(onClickListener);

        bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                    mPreviewPaneArrow.setImageResource(R.drawable.ic_keyboard_arrow_up_white_24dp);
                    mPreviewPaneArrow.setContentDescription(
                            getResources().getString(R.string.expand_attribution_panel));
                } else if (newState == BottomSheetBehavior.STATE_EXPANDED) {
                    mPreviewPaneArrow.setImageResource(
                            R.drawable.ic_keyboard_arrow_down_white_24dp);
                    mPreviewPaneArrow.setContentDescription(
                            getResources().getString(R.string.collapse_attribution_panel));
                }
            }

            @Override
            public void onSlide(View bottomSheet, float slideOffset) {
                float alpha;
                if (slideOffset >= 0) {
                    alpha = slideOffset;
                } else {
                    alpha = 1f - slideOffset;
                }
                mAttributionTitle.setAlpha(slideOffset);
                mAttributionSubtitle1.setAlpha(slideOffset);
                mAttributionSubtitle2.setAlpha(slideOffset);
                mAttributionExploreButton.setAlpha(slideOffset);
            }
        });

        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        mPreviewPaneArrow.setImageResource(R.drawable.ic_keyboard_arrow_down_white_24dp);

        if (SHOW_DUMMY_DATA) {
            mAttributionTitle.setText("Diorama, Yosemite");
            mAttributionSubtitle1.setText("Live Earth Collection - Android Earth");
            mAttributionSubtitle2.setText("Lorem ipsum dolor sit amet, consectetur adipiscing elit."
                    + " Sed imperdiet et mauris molestie laoreet. Proin volutpat elit nec magna"
                    + " tempus, ac aliquet lectus volutpat.");
            mAttributionExploreButton.setText("Explore");
        } else {
            PackageManager pm = getPackageManager();

            CharSequence title = info.loadLabel(pm);
            if (!TextUtils.isEmpty(title)) {
                mAttributionTitle.setText(title);
            } else {
                mAttributionTitle.setVisibility(View.GONE);
            }

            try {
                CharSequence author = info.loadAuthor(pm);
                if (TextUtils.isEmpty(author)) {
                    throw new NotFoundException();
                }
                mAttributionSubtitle1.setText(author);
            } catch (NotFoundException e) {
                mAttributionSubtitle1.setVisibility(View.GONE);
            }

            try {
                CharSequence description = info.loadDescription(pm);
                if (TextUtils.isEmpty(description)) {
                    throw new NotFoundException();
                }
                mAttributionSubtitle2.setText(description);
            } catch (NotFoundException e) {
                mAttributionSubtitle2.setVisibility(View.GONE);
            }

            try {
                Uri contextUri = info.loadContextUri(pm);
                CharSequence contextDescription = info.loadContextDescription(pm);
                if (contextUri == null) {
                    throw new NotFoundException();
                }
                mAttributionExploreButton.setText(contextDescription);
                mAttributionExploreButton.setOnClickListener(v -> {
                    Intent intent = new Intent(Intent.ACTION_VIEW, contextUri);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        Log.e(LOG_TAG, "Couldn't find activity for context link.", e);
                    }
                });
            } catch (NotFoundException e) {
                mAttributionExploreButton.setVisibility(View.GONE);
                mSpacer.setVisibility(View.VISIBLE);
            }
        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_preview, menu);
        menu.findItem(R.id.configure).setVisible(mSettings != null);
        menu.findItem(R.id.set_wallpaper).getActionView().setOnClickListener(
                this::setLiveWallpaper);
        return super.onCreateOptionsMenu(menu);
    }

    public void setLiveWallpaper(final View v) {
        if (mWallpaperManager.getWallpaperId(WallpaperManager.FLAG_LOCK) < 0) {
            // The lock screen does not have a wallpaper, so no need to prompt; can only set both.
            try {
                setLiveWallpaper(v.getRootView().getWindowToken());
                setResult(RESULT_OK);
            } catch (RuntimeException e) {
                Log.w(LOG_TAG, "Failure setting wallpaper", e);
            }
            finish();
        } else {
            // Otherwise, prompt to either set on home or both home and lock screen.
            Context themedContext = new ContextThemeWrapper(this, android.R.style.Theme_DeviceDefault_Settings);
            new AlertDialog.Builder(themedContext)
                    .setTitle(R.string.set_live_wallpaper)
                    .setAdapter(new WallpaperTargetAdapter(themedContext), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                setLiveWallpaper(v.getRootView().getWindowToken());
                                if (which == 1) {
                                    // "Home screen and lock screen"; clear the lock screen so it
                                    // shows through to the live wallpaper on home.
                                    mWallpaperManager.clear(WallpaperManager.FLAG_LOCK);
                                }
                                setResult(RESULT_OK);
                            } catch (RuntimeException|IOException e) {
                                Log.w(LOG_TAG, "Failure setting wallpaper", e);
                            }
                            finish();
                        }
                    })
                    .show();
        }
    }

    private void setLiveWallpaper(IBinder windowToken) {
        mWallpaperManager.setWallpaperComponent(mWallpaperIntent.getComponent());
        mWallpaperManager.setWallpaperOffsetSteps(0.5f, 0.0f);
        mWallpaperManager.setWallpaperOffsets(windowToken, 0.5f, 0.0f);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.configure) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(mPackageName, mSettings));
            intent.putExtra(WallpaperSettingsActivity.EXTRA_PREVIEW_MODE, true);
            startActivity(intent);
            return true;
        } else if (id == R.id.set_wallpaper) {
            setLiveWallpaper(getWindow().getDecorView());
            return true;
        } else if (id == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mWallpaperConnection != null && mWallpaperConnection.mEngine != null) {
            try {
                mWallpaperConnection.mEngine.setVisibility(true);
            } catch (RemoteException e) {
                // Ignore
            }
        }
    }
    
    @Override
    public void onPause() {
        super.onPause();
        if (mWallpaperConnection != null && mWallpaperConnection.mEngine != null) {
            try {
                mWallpaperConnection.mEngine.setVisibility(false);
            } catch (RemoteException e) {
                // Ignore
            }
        }
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();

        getWindow().getDecorView().post(new Runnable() {
            public void run() {
                if (!mWallpaperConnection.connect()) {
                    mWallpaperConnection = null;
                }
            }
        });
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        
        if (mWallpaperConnection != null) {
            mWallpaperConnection.disconnect();
        }
        mWallpaperConnection = null;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mWallpaperConnection != null && mWallpaperConnection.mEngine != null) {
            MotionEvent dup = MotionEvent.obtainNoHistory(ev);
            try {
                mWallpaperConnection.mEngine.dispatchPointer(dup);
            } catch (RemoteException e) {
            }
        }
        
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        boolean handled = getWindow().superDispatchTouchEvent(ev);
        if (!handled) {
            handled = onTouchEvent(ev);
        }

        if (!handled && mWallpaperConnection != null && mWallpaperConnection.mEngine != null) {
            int action = ev.getActionMasked();
            try {
                if (action == MotionEvent.ACTION_UP) {
                    mWallpaperConnection.mEngine.dispatchWallpaperCommand(
                            WallpaperManager.COMMAND_TAP,
                            (int) ev.getX(), (int) ev.getY(), 0, null);
                } else if (action == MotionEvent.ACTION_POINTER_UP) {
                    int pointerIndex = ev.getActionIndex();
                    mWallpaperConnection.mEngine.dispatchWallpaperCommand(
                            WallpaperManager.COMMAND_SECONDARY_TAP,
                            (int) ev.getX(pointerIndex), (int) ev.getY(pointerIndex), 0, null);
                }
            } catch (RemoteException e) {
            }
        }
        return handled;
    }
    
    class WallpaperConnection extends IWallpaperConnection.Stub implements ServiceConnection {
        final Intent mIntent;
        IWallpaperService mService;
        IWallpaperEngine mEngine;
        boolean mConnected;

        WallpaperConnection(Intent intent) {
            mIntent = intent;
        }

        public boolean connect() {
            synchronized (this) {
                if (!bindService(mIntent, this, Context.BIND_AUTO_CREATE)) {
                    return false;
                }

                mConnected = true;
                return true;
            }
        }

        public void disconnect() {
            synchronized (this) {
                mConnected = false;
                if (mEngine != null) {
                    try {
                        mEngine.destroy();
                    } catch (RemoteException e) {
                        // Ignore
                    }
                    mEngine = null;
                }
                unbindService(this);
                mService = null;
            }
        }
        
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (mWallpaperConnection == this) {
                mService = IWallpaperService.Stub.asInterface(service);
                try {
                    final View root = getWindow().getDecorView();
                    mService.attach(this, root.getWindowToken(),
                            LayoutParams.TYPE_APPLICATION_MEDIA,
                            true, root.getWidth(), root.getHeight(),
                            new Rect(0, 0, 0, 0));
                } catch (RemoteException e) {
                    Log.w(LOG_TAG, "Failed attaching wallpaper; clearing", e);
                }
            }
        }

        public void onServiceDisconnected(ComponentName name) {
            mService = null;
            mEngine = null;
            if (mWallpaperConnection == this) {
                Log.w(LOG_TAG, "Wallpaper service gone: " + name);
            }
        }
        
        public void attachEngine(IWallpaperEngine engine) {
            synchronized (this) {
                if (mConnected) {
                    mEngine = engine;
                    try {
                        engine.setVisibility(true);
                    } catch (RemoteException e) {
                        // Ignore
                    }
                } else {
                    try {
                        engine.destroy();
                    } catch (RemoteException e) {
                        // Ignore
                    }
                }
            }
        }
        
        public ParcelFileDescriptor setWallpaper(String name) {
            return null;
        }

        @Override
        public void engineShown(IWallpaperEngine engine) throws RemoteException {
            mLoading.post(() -> {
                mLoading.animate()
                        .alpha(0f)
                        .setDuration(220)
                        .setInterpolator(AnimationUtils.loadInterpolator(LiveWallpaperPreview.this,
                                android.R.interpolator.fast_out_linear_in))
                        .withEndAction(() -> mLoading.setVisibility(View.INVISIBLE));
            });
        }
    }

    private static class WallpaperTargetAdapter extends ArrayAdapter<CharSequence> {

        public WallpaperTargetAdapter(Context context) {
            super(context, R.layout.wallpaper_target_dialog_item,
                    context.getResources().getTextArray(R.array.which_wallpaper_options));
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView tv = (TextView) super.getView(position, convertView, parent);
            tv.setCompoundDrawablesRelativeWithIntrinsicBounds(
                    position == 0 ? R.drawable.ic_home : R.drawable.ic_device, 0, 0, 0);
            return tv;
        }
    }
}