blob: 3d638dd9e211e112e35a25b26efc24e47bf87287 [file] [log] [blame]
Beth Thibodeau7b6c1782020-03-05 11:43:51 -05001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.systemui.media;
18
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050019import android.app.PendingIntent;
20import android.content.ComponentName;
21import android.content.Context;
22import android.content.Intent;
Beth Thibodeau23a33ab2020-04-07 20:51:57 -040023import android.content.SharedPreferences;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050024import android.content.pm.PackageManager;
25import android.content.pm.ResolveInfo;
26import android.content.res.ColorStateList;
Selim Cinekc5436712020-04-27 15:15:44 -070027import android.graphics.Bitmap;
28import android.graphics.Canvas;
29import android.graphics.Rect;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050030import android.graphics.drawable.Drawable;
31import android.graphics.drawable.GradientDrawable;
Selim Cinekc5436712020-04-27 15:15:44 -070032import android.graphics.drawable.Icon;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050033import android.graphics.drawable.RippleDrawable;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050034import android.media.session.MediaController;
Robert Snoebergerc981dc92020-04-27 15:00:50 -040035import android.media.session.MediaController.PlaybackInfo;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050036import android.media.session.MediaSession;
37import android.media.session.PlaybackState;
Beth Thibodeau23a33ab2020-04-07 20:51:57 -040038import android.service.media.MediaBrowserService;
Selim Cinek3df592e2020-04-28 13:51:43 -070039import android.util.DisplayMetrics;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050040import android.util.Log;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050041import android.view.LayoutInflater;
42import android.view.View;
43import android.view.ViewGroup;
44import android.widget.ImageButton;
45import android.widget.ImageView;
46import android.widget.LinearLayout;
Selim Cinek5dbef2d2020-05-07 17:44:38 -070047import android.widget.SeekBar;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050048import android.widget.TextView;
49
Robert Snoeberger9a7409b2020-04-09 18:12:27 -040050import androidx.annotation.Nullable;
Selim Cinekf0f74952020-04-21 11:45:16 -070051import androidx.constraintlayout.motion.widget.Key;
52import androidx.constraintlayout.motion.widget.KeyAttributes;
53import androidx.constraintlayout.motion.widget.KeyFrames;
Selim Cinekd8357922020-04-10 15:06:53 -070054import androidx.constraintlayout.motion.widget.MotionLayout;
Selim Cinek5dbef2d2020-05-07 17:44:38 -070055import androidx.constraintlayout.widget.ConstraintSet;
Selim Cinekc5436712020-04-27 15:15:44 -070056import androidx.core.graphics.drawable.RoundedBitmapDrawable;
57import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050058
Selim Cinekc5436712020-04-27 15:15:44 -070059import com.android.settingslib.Utils;
Robert Snoeberger9a7409b2020-04-09 18:12:27 -040060import com.android.settingslib.media.LocalMediaManager;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050061import com.android.settingslib.media.MediaDevice;
62import com.android.settingslib.media.MediaOutputSliceConstants;
63import com.android.settingslib.widget.AdaptiveIcon;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050064import com.android.systemui.R;
65import com.android.systemui.plugins.ActivityStarter;
Beth Thibodeau23a33ab2020-04-07 20:51:57 -040066import com.android.systemui.qs.QSMediaBrowser;
Robert Snoeberger3cc22222020-03-25 15:36:31 -040067import com.android.systemui.util.Assert;
Selim Cinek5dbef2d2020-05-07 17:44:38 -070068import com.android.systemui.util.concurrency.DelayableExecutor;
69
70import org.jetbrains.annotations.NotNull;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050071
Selim Cinekf0f74952020-04-21 11:45:16 -070072import java.util.ArrayList;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050073import java.util.List;
74import java.util.concurrent.Executor;
75
76/**
Selim Cinekd8357922020-04-10 15:06:53 -070077 * A view controller used for Media Playback.
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050078 */
Robert Snoeberger3cc22222020-03-25 15:36:31 -040079public class MediaControlPanel {
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050080 private static final String TAG = "MediaControlPanel";
Robert Snoeberger9a7409b2020-04-09 18:12:27 -040081 @Nullable private final LocalMediaManager mLocalMediaManager;
Selim Cinek5dbef2d2020-05-07 17:44:38 -070082
83 // Button IDs for QS controls
84 static final int[] ACTION_IDS = {
85 R.id.action0,
86 R.id.action1,
87 R.id.action2,
88 R.id.action3,
89 R.id.action4
90 };
91
92 private final SeekBarViewModel mSeekBarViewModel;
93 private final SeekBarObserver mSeekBarObserver;
Beth Thibodeaua51c3142020-03-17 17:27:04 -040094 private final Executor mForegroundExecutor;
Beth Thibodeau23a33ab2020-04-07 20:51:57 -040095 protected final Executor mBackgroundExecutor;
Beth Thibodeaue561c002020-04-23 17:33:00 -040096 private final ActivityStarter mActivityStarter;
Selim Cinek3df592e2020-04-28 13:51:43 -070097 private final LayoutAnimationHelper mLayoutAnimationHelper;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -050098
99 private Context mContext;
Selim Cinekf0f74952020-04-21 11:45:16 -0700100 private MotionLayout mMediaNotifView;
101 private final View mBackground;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500102 private View mSeamless;
103 private MediaSession.Token mToken;
104 private MediaController mController;
105 private int mForegroundColor;
106 private int mBackgroundColor;
Robert Snoeberger9a7409b2020-04-09 18:12:27 -0400107 private MediaDevice mDevice;
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400108 protected ComponentName mServiceComponent;
Robert Snoeberger3cc22222020-03-25 15:36:31 -0400109 private boolean mIsRegistered = false;
Selim Cinekf0f74952020-04-21 11:45:16 -0700110 private final List<KeyFrames> mKeyFrames;
Beth Thibodeaua3d90982020-04-13 23:42:48 -0400111 private String mKey;
Selim Cinekc5436712020-04-27 15:15:44 -0700112 private int mAlbumArtSize;
113 private int mAlbumArtRadius;
Selim Cinek3df592e2020-04-28 13:51:43 -0700114 private int mViewWidth;
Selim Cinek54809622020-04-30 19:04:44 -0700115 private MediaMeasurementInput mLastMeasureInput;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500116
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400117 public static final String MEDIA_PREFERENCES = "media_control_prefs";
118 public static final String MEDIA_PREFERENCE_KEY = "browser_components";
119 private SharedPreferences mSharedPrefs;
120 private boolean mCheckedForResumption = false;
Robert Snoebergerc981dc92020-04-27 15:00:50 -0400121 private boolean mIsRemotePlayback;
Beth Thibodeauee42e8c2020-04-30 01:09:29 -0400122 private QSMediaBrowser mQSMediaBrowser;
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400123
Robert Snoeberger3cc22222020-03-25 15:36:31 -0400124 private final MediaController.Callback mSessionCallback = new MediaController.Callback() {
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500125 @Override
126 public void onSessionDestroyed() {
127 Log.d(TAG, "session destroyed");
128 mController.unregisterCallback(mSessionCallback);
129 clearControls();
Robert Snoeberger3cc22222020-03-25 15:36:31 -0400130 makeInactive();
131 }
Robert Snoeberger3cc22222020-03-25 15:36:31 -0400132 @Override
Robert Snoeberger445d4412020-04-15 00:03:13 -0400133 public void onPlaybackStateChanged(PlaybackState state) {
134 final int s = state != null ? state.getState() : PlaybackState.STATE_NONE;
Beth Thibodeaud664de22020-04-28 16:29:36 -0400135 if (s == PlaybackState.STATE_NONE) {
Robert Snoeberger445d4412020-04-15 00:03:13 -0400136 Log.d(TAG, "playback state change will trigger resumption, state=" + state);
Robert Snoeberger3cc22222020-03-25 15:36:31 -0400137 clearControls();
138 makeInactive();
139 }
140 }
141 };
142
Robert Snoeberger9a7409b2020-04-09 18:12:27 -0400143 private final LocalMediaManager.DeviceCallback mDeviceCallback =
144 new LocalMediaManager.DeviceCallback() {
145 @Override
146 public void onDeviceListUpdate(List<MediaDevice> devices) {
147 if (mLocalMediaManager == null) {
148 return;
149 }
150 MediaDevice currentDevice = mLocalMediaManager.getCurrentConnectedDevice();
151 // Check because this can be called several times while changing devices
152 if (mDevice == null || !mDevice.equals(currentDevice)) {
153 mDevice = currentDevice;
154 updateDevice(mDevice);
155 }
156 }
157
158 @Override
159 public void onSelectedDeviceStateChanged(MediaDevice device, int state) {
160 if (mDevice == null || !mDevice.equals(device)) {
161 mDevice = device;
162 updateDevice(mDevice);
163 }
164 }
165 };
166
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500167 /**
168 * Initialize a new control panel
169 * @param context
170 * @param parent
Robert Snoeberger9a7409b2020-04-09 18:12:27 -0400171 * @param routeManager Manager used to listen for device change events.
Beth Thibodeaua51c3142020-03-17 17:27:04 -0400172 * @param foregroundExecutor foreground executor
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500173 * @param backgroundExecutor background executor, used for processing artwork
Beth Thibodeaue561c002020-04-23 17:33:00 -0400174 * @param activityStarter activity starter
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500175 */
Robert Snoeberger445d4412020-04-15 00:03:13 -0400176 public MediaControlPanel(Context context, ViewGroup parent,
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700177 @Nullable LocalMediaManager routeManager, Executor foregroundExecutor,
178 DelayableExecutor backgroundExecutor, ActivityStarter activityStarter) {
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500179 mContext = context;
180 LayoutInflater inflater = LayoutInflater.from(mContext);
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700181 mMediaNotifView = (MotionLayout) inflater.inflate(R.layout.qs_media_panel, parent, false);
Selim Cinekf0f74952020-04-21 11:45:16 -0700182 mBackground = mMediaNotifView.findViewById(R.id.media_background);
Selim Cinek3df592e2020-04-28 13:51:43 -0700183 mLayoutAnimationHelper = new LayoutAnimationHelper(mMediaNotifView);
Selim Cinekf0f74952020-04-21 11:45:16 -0700184 mKeyFrames = mMediaNotifView.getDefinedTransitions().get(0).getKeyFrameList();
Robert Snoeberger9a7409b2020-04-09 18:12:27 -0400185 mLocalMediaManager = routeManager;
Beth Thibodeaua51c3142020-03-17 17:27:04 -0400186 mForegroundExecutor = foregroundExecutor;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500187 mBackgroundExecutor = backgroundExecutor;
Beth Thibodeaue561c002020-04-23 17:33:00 -0400188 mActivityStarter = activityStarter;
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700189 mSeekBarViewModel = new SeekBarViewModel(backgroundExecutor);
190 mSeekBarObserver = new SeekBarObserver(getView());
Selim Cinek098baf42020-04-27 19:02:06 -0700191 // TODO: we should pause this whenever the screen is off / panel is collapsed etc.
192 mSeekBarViewModel.getProgress().observeForever(mSeekBarObserver);
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700193 SeekBar bar = getView().findViewById(R.id.media_progress_bar);
194 bar.setOnSeekBarChangeListener(mSeekBarViewModel.getSeekBarListener());
195 bar.setOnTouchListener(mSeekBarViewModel.getSeekBarTouchListener());
Selim Cinekc5436712020-04-27 15:15:44 -0700196 loadDimens();
197 }
198
Selim Cinek098baf42020-04-27 19:02:06 -0700199 public void onDestroy() {
200 mSeekBarViewModel.getProgress().removeObserver(mSeekBarObserver);
201 makeInactive();
202 }
203
Selim Cinekc5436712020-04-27 15:15:44 -0700204 private void loadDimens() {
205 mAlbumArtRadius = mContext.getResources().getDimensionPixelSize(
206 Utils.getThemeAttr(mContext, android.R.attr.dialogCornerRadius));
207 mAlbumArtSize = mContext.getResources().getDimensionPixelSize(R.dimen.qs_media_album_size);
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500208 }
209
210 /**
211 * Get the view used to display media controls
212 * @return the view
213 */
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700214 public MotionLayout getView() {
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500215 return mMediaNotifView;
216 }
217
218 /**
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700219 * Sets the listening state of the player.
220 *
221 * Should be set to true when the QS panel is open. Otherwise, false. This is a signal to avoid
222 * unnecessary work when the QS panel is closed.
223 *
224 * @param listening True when player should be active. Otherwise, false.
225 */
226 public void setListening(boolean listening) {
227 mSeekBarViewModel.setListening(listening);
228 }
229
230 /**
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500231 * Get the context
232 * @return context
233 */
234 public Context getContext() {
235 return mContext;
236 }
237
238 /**
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700239 * Bind this view based on the data given
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500240 */
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700241 public void bind(@NotNull MediaData data) {
Selim Cinekf0f74952020-04-21 11:45:16 -0700242 MediaSession.Token token = data.getToken();
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700243 mForegroundColor = data.getForegroundColor();
244 mBackgroundColor = data.getBackgroundColor();
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400245 if (mToken == null || !mToken.equals(token)) {
Beth Thibodeauee42e8c2020-04-30 01:09:29 -0400246 if (mQSMediaBrowser != null) {
247 Log.d(TAG, "Disconnecting old media browser");
248 mQSMediaBrowser.disconnect();
249 mQSMediaBrowser = null;
250 }
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400251 mToken = token;
252 mServiceComponent = null;
253 mCheckedForResumption = false;
254 }
255
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500256 mController = new MediaController(mContext, mToken);
257
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400258 // Try to find a browser service component for this app
259 // TODO also check for a media button receiver intended for restarting (b/154127084)
260 // Only check if we haven't tried yet or the session token changed
Robert Snoeberger44299172020-04-24 22:22:21 -0400261 final String pkgName = mController.getPackageName();
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400262 if (mServiceComponent == null && !mCheckedForResumption) {
263 Log.d(TAG, "Checking for service component");
264 PackageManager pm = mContext.getPackageManager();
265 Intent resumeIntent = new Intent(MediaBrowserService.SERVICE_INTERFACE);
266 List<ResolveInfo> resumeInfo = pm.queryIntentServices(resumeIntent, 0);
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700267 // TODO: look into this resumption
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400268 if (resumeInfo != null) {
269 for (ResolveInfo inf : resumeInfo) {
270 if (inf.serviceInfo.packageName.equals(mController.getPackageName())) {
271 mBackgroundExecutor.execute(() ->
272 tryUpdateResumptionList(inf.getComponentInfo().getComponentName()));
273 break;
274 }
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500275 }
276 }
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400277 mCheckedForResumption = true;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500278 }
279
280 mController.registerCallback(mSessionCallback);
281
Selim Cinekf0f74952020-04-21 11:45:16 -0700282 mMediaNotifView.requireViewById(R.id.media_background).setBackgroundTintList(
283 ColorStateList.valueOf(mBackgroundColor));
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500284
285 // Click action
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700286 PendingIntent clickIntent = data.getClickIntent();
287 if (clickIntent != null) {
Beth Thibodeaua51c3142020-03-17 17:27:04 -0400288 mMediaNotifView.setOnClickListener(v -> {
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700289 mActivityStarter.postStartActivityDismissingKeyguard(clickIntent);
Beth Thibodeaua51c3142020-03-17 17:27:04 -0400290 });
291 }
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500292
Selim Cinekf0f74952020-04-21 11:45:16 -0700293 ImageView albumView = mMediaNotifView.findViewById(R.id.album_art);
Selim Cinekc5436712020-04-27 15:15:44 -0700294 // TODO: migrate this to a view with rounded corners instead of baking the rounding
295 // into the bitmap
296 Drawable artwork = createRoundedBitmap(data.getArtwork());
297 albumView.setImageDrawable(artwork);
Selim Cinekf0f74952020-04-21 11:45:16 -0700298
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500299 // App icon
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700300 ImageView appIcon = mMediaNotifView.requireViewById(R.id.icon);
301 // TODO: look at iconDrawable
302 Drawable iconDrawable = data.getAppIcon();
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500303 iconDrawable.setTint(mForegroundColor);
304 appIcon.setImageDrawable(iconDrawable);
305
Selim Cinekf0f74952020-04-21 11:45:16 -0700306 // Song name
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700307 TextView titleText = mMediaNotifView.requireViewById(R.id.header_title);
308 titleText.setText(data.getSong());
Selim Cinekf0f74952020-04-21 11:45:16 -0700309 titleText.setTextColor(data.getForegroundColor());
310
311 // App title
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700312 TextView appName = mMediaNotifView.requireViewById(R.id.app_name);
313 appName.setText(data.getApp());
314 appName.setTextColor(mForegroundColor);
Selim Cinekf0f74952020-04-21 11:45:16 -0700315
316 // Artist name
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700317 TextView artistText = mMediaNotifView.requireViewById(R.id.header_artist);
318 artistText.setText(data.getArtist());
319 artistText.setTextColor(mForegroundColor);
Selim Cinekf0f74952020-04-21 11:45:16 -0700320
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500321 // Transfer chip
322 mSeamless = mMediaNotifView.findViewById(R.id.media_seamless);
Robert Snoeberger44299172020-04-24 22:22:21 -0400323 if (mSeamless != null) {
324 if (mLocalMediaManager != null) {
325 mSeamless.setVisibility(View.VISIBLE);
326 updateDevice(mLocalMediaManager.getCurrentConnectedDevice());
327 mSeamless.setOnClickListener(v -> {
328 final Intent intent = new Intent()
329 .setAction(MediaOutputSliceConstants.ACTION_MEDIA_OUTPUT)
330 .putExtra(MediaOutputSliceConstants.EXTRA_PACKAGE_NAME,
331 mController.getPackageName())
332 .putExtra(MediaOutputSliceConstants.KEY_MEDIA_SESSION_TOKEN, mToken);
333 mActivityStarter.startActivity(intent, false, true /* dismissShade */,
334 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
335 });
336 } else {
337 Log.d(TAG, "LocalMediaManager is null. Not binding output chip for pkg=" + pkgName);
338 }
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500339 }
Robert Snoebergerc981dc92020-04-27 15:00:50 -0400340 PlaybackInfo playbackInfo = mController.getPlaybackInfo();
341 if (playbackInfo != null) {
342 mIsRemotePlayback = playbackInfo.getPlaybackType() == PlaybackInfo.PLAYBACK_TYPE_REMOTE;
343 } else {
344 Log.d(TAG, "PlaybackInfo was null. Defaulting to local playback.");
345 mIsRemotePlayback = false;
346 }
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500347
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700348 ConstraintSet expandedSet = mMediaNotifView.getConstraintSet(R.id.expanded);
349 ConstraintSet collapsedSet = mMediaNotifView.getConstraintSet(R.id.collapsed);
350 List<Integer> actionsWhenCollapsed = data.getActionsToShowInCompact();
351 // Media controls
352 int i = 0;
353 List<MediaAction> actionIcons = data.getActions();
354 for (; i < actionIcons.size() && i < ACTION_IDS.length; i++) {
Selim Cinekf0f74952020-04-21 11:45:16 -0700355 int actionId = ACTION_IDS[i];
356 final ImageButton button = mMediaNotifView.findViewById(actionId);
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700357 MediaAction mediaAction = actionIcons.get(i);
358 button.setImageDrawable(mediaAction.getDrawable());
359 button.setContentDescription(mediaAction.getContentDescription());
360 button.setImageTintList(ColorStateList.valueOf(mForegroundColor));
361 PendingIntent actionIntent = mediaAction.getIntent();
362
Selim Cinekf0f74952020-04-21 11:45:16 -0700363 if (mBackground.getBackground() instanceof IlluminationDrawable) {
364 ((IlluminationDrawable) mBackground.getBackground())
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700365 .setupTouch(button, mMediaNotifView);
366 }
367
368 button.setOnClickListener(v -> {
369 if (actionIntent != null) {
370 try {
371 actionIntent.send();
372 } catch (PendingIntent.CanceledException e) {
373 e.printStackTrace();
374 }
375 }
376 });
377 boolean visibleInCompat = actionsWhenCollapsed.contains(i);
Selim Cinekf0f74952020-04-21 11:45:16 -0700378 updateKeyFrameVisibility(actionId, visibleInCompat);
379 collapsedSet.setVisibility(actionId,
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700380 visibleInCompat ? ConstraintSet.VISIBLE : ConstraintSet.GONE);
Selim Cinekf0f74952020-04-21 11:45:16 -0700381 expandedSet.setVisibility(actionId, ConstraintSet.VISIBLE);
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700382 }
383
384 // Hide any unused buttons
385 for (; i < ACTION_IDS.length; i++) {
386 expandedSet.setVisibility(ACTION_IDS[i], ConstraintSet.GONE);
387 collapsedSet.setVisibility(ACTION_IDS[i], ConstraintSet.GONE);
388 }
389
390 // Seek Bar
391 final MediaController controller = new MediaController(getContext(), data.getToken());
392 mBackgroundExecutor.execute(
393 () -> mSeekBarViewModel.updateController(controller, data.getForegroundColor()));
394
395 // Set up long press menu
396 // TODO: b/156036025 bring back media guts
397
Robert Snoeberger3cc22222020-03-25 15:36:31 -0400398 makeActive();
Selim Cinekf0f74952020-04-21 11:45:16 -0700399 }
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400400
Selim Cinekc5436712020-04-27 15:15:44 -0700401 private Drawable createRoundedBitmap(Icon icon) {
402 if (icon == null) {
403 return null;
404 }
405 // Let's scale down the View, such that the content always nicely fills the view.
406 // ThumbnailUtils actually scales it down such that it may not be filled for odd aspect
407 // ratios
408 Drawable drawable = icon.loadDrawable(mContext);
409 float aspectRatio = drawable.getIntrinsicHeight() / (float) drawable.getIntrinsicWidth();
410 Rect bounds;
411 if (aspectRatio > 1.0f) {
412 bounds = new Rect(0, 0, mAlbumArtSize, (int) (mAlbumArtSize * aspectRatio));
413 } else {
414 bounds = new Rect(0, 0, (int) (mAlbumArtSize / aspectRatio), mAlbumArtSize);
415 }
416 if (bounds.width() > mAlbumArtSize || bounds.height() > mAlbumArtSize) {
417 float offsetX = (bounds.width() - mAlbumArtSize) / 2.0f;
418 float offsetY = (bounds.height() - mAlbumArtSize) / 2.0f;
419 bounds.offset((int) -offsetX,(int) -offsetY);
420 }
421 drawable.setBounds(bounds);
422 Bitmap scaled = Bitmap.createBitmap(mAlbumArtSize, mAlbumArtSize,
423 Bitmap.Config.ARGB_8888);
424 Canvas canvas = new Canvas(scaled);
425 drawable.draw(canvas);
426 RoundedBitmapDrawable artwork = RoundedBitmapDrawableFactory.create(
427 mContext.getResources(), scaled);
428 artwork.setCornerRadius(mAlbumArtRadius);
429 return artwork;
430 }
431
Selim Cinekf0f74952020-04-21 11:45:16 -0700432 /**
433 * Updates the keyframe visibility such that only views that are not visible actually go
434 * through a transition and fade in.
435 *
436 * @param actionId the id to change
437 * @param visible is the view visible
438 */
439 private void updateKeyFrameVisibility(int actionId, boolean visible) {
440 for (int i = 0; i < mKeyFrames.size(); i++) {
441 KeyFrames keyframe = mKeyFrames.get(i);
442 ArrayList<Key> viewKeyFrames = keyframe.getKeyFramesForView(actionId);
443 for (int j = 0; j < viewKeyFrames.size(); j++) {
444 Key key = viewKeyFrames.get(j);
445 if (key instanceof KeyAttributes) {
446 KeyAttributes attributes = (KeyAttributes) key;
447 attributes.setValue("alpha", visible ? 1.0f : 0.0f);
448 }
Beth Thibodeau4b5ec832020-04-30 19:43:37 -0400449 }
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400450 }
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500451 }
452
453 /**
454 * Return the token for the current media session
455 * @return the token
456 */
457 public MediaSession.Token getMediaSessionToken() {
458 return mToken;
459 }
460
461 /**
462 * Get the current media controller
463 * @return the controller
464 */
465 public MediaController getController() {
466 return mController;
467 }
468
469 /**
470 * Get the name of the package associated with the current media controller
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400471 * @return the package name, or null if no controller
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500472 */
473 public String getMediaPlayerPackage() {
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400474 if (mController == null) {
475 return null;
476 }
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500477 return mController.getPackageName();
478 }
479
480 /**
Beth Thibodeaua3d90982020-04-13 23:42:48 -0400481 * Return the original notification's key
482 * @return The notification key
483 */
484 public String getKey() {
485 return mKey;
486 }
487
488 /**
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500489 * Check whether this player has an attached media session.
490 * @return whether there is a controller with a current media session.
491 */
492 public boolean hasMediaSession() {
493 return mController != null && mController.getPlaybackState() != null;
494 }
495
496 /**
497 * Check whether the media controlled by this player is currently playing
498 * @return whether it is playing, or false if no controller information
499 */
500 public boolean isPlaying() {
501 return isPlaying(mController);
502 }
503
504 /**
505 * Check whether the given controller is currently playing
506 * @param controller media controller to check
507 * @return whether it is playing, or false if no controller information
508 */
509 protected boolean isPlaying(MediaController controller) {
510 if (controller == null) {
511 return false;
512 }
513
514 PlaybackState state = controller.getPlaybackState();
515 if (state == null) {
516 return false;
517 }
518
519 return (state.getState() == PlaybackState.STATE_PLAYING);
520 }
521
522 /**
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500523 * Update the current device information
524 * @param device device information to display
525 */
Robert Snoeberger9a7409b2020-04-09 18:12:27 -0400526 private void updateDevice(MediaDevice device) {
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500527 if (mSeamless == null) {
528 return;
529 }
Beth Thibodeaua51c3142020-03-17 17:27:04 -0400530 mForegroundExecutor.execute(() -> {
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500531 updateChipInternal(device);
532 });
533 }
534
535 private void updateChipInternal(MediaDevice device) {
536 ColorStateList fgTintList = ColorStateList.valueOf(mForegroundColor);
537
538 // Update the outline color
539 LinearLayout viewLayout = (LinearLayout) mSeamless;
540 RippleDrawable bkgDrawable = (RippleDrawable) viewLayout.getBackground();
541 GradientDrawable rect = (GradientDrawable) bkgDrawable.getDrawable(0);
542 rect.setStroke(2, mForegroundColor);
543 rect.setColor(mBackgroundColor);
544
545 ImageView iconView = mSeamless.findViewById(R.id.media_seamless_image);
546 TextView deviceName = mSeamless.findViewById(R.id.media_seamless_text);
547 deviceName.setTextColor(fgTintList);
548
Robert Snoebergerc981dc92020-04-27 15:00:50 -0400549 if (mIsRemotePlayback) {
550 mSeamless.setEnabled(false);
551 mSeamless.setAlpha(0.38f);
552 iconView.setImageResource(R.drawable.ic_hardware_speaker);
553 iconView.setVisibility(View.VISIBLE);
554 iconView.setImageTintList(fgTintList);
555 deviceName.setText(R.string.media_seamless_remote_device);
556 } else if (device != null) {
557 mSeamless.setEnabled(true);
558 mSeamless.setAlpha(1f);
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500559 Drawable icon = device.getIcon();
560 iconView.setVisibility(View.VISIBLE);
561 iconView.setImageTintList(fgTintList);
562
563 if (icon instanceof AdaptiveIcon) {
564 AdaptiveIcon aIcon = (AdaptiveIcon) icon;
565 aIcon.setBackgroundColor(mBackgroundColor);
566 iconView.setImageDrawable(aIcon);
567 } else {
568 iconView.setImageDrawable(icon);
569 }
570 deviceName.setText(device.getName());
571 } else {
572 // Reset to default
Robert Snoeberger44299172020-04-24 22:22:21 -0400573 Log.d(TAG, "device is null. Not binding output chip.");
Robert Snoebergerc981dc92020-04-27 15:00:50 -0400574 mSeamless.setEnabled(true);
575 mSeamless.setAlpha(1f);
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500576 iconView.setVisibility(View.GONE);
577 deviceName.setText(com.android.internal.R.string.ext_media_seamless_action);
578 }
579 }
580
581 /**
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400582 * Puts controls into a resumption state if possible, or calls removePlayer if no component was
583 * found that could resume playback
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500584 */
585 public void clearControls() {
Robert Snoeberger445d4412020-04-15 00:03:13 -0400586 Log.d(TAG, "clearControls to resumption state package=" + getMediaPlayerPackage());
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400587 if (mServiceComponent == null) {
588 // If we don't have a way to resume, just remove the player altogether
589 Log.d(TAG, "Removing unresumable controls");
590 removePlayer();
591 return;
592 }
593 resetButtons();
594 }
595
596 /**
597 * Hide the media buttons and show only a restart button
598 */
599 protected void resetButtons() {
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500600 // Hide all the old buttons
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700601
602 ConstraintSet expandedSet = mMediaNotifView.getConstraintSet(R.id.expanded);
603 ConstraintSet collapsedSet = mMediaNotifView.getConstraintSet(R.id.collapsed);
604 for (int i = 1; i < ACTION_IDS.length; i++) {
605 expandedSet.setVisibility(ACTION_IDS[i], ConstraintSet.GONE);
606 collapsedSet.setVisibility(ACTION_IDS[i], ConstraintSet.GONE);
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500607 }
608
609 // Add a restart button
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700610 ImageButton btn = mMediaNotifView.findViewById(ACTION_IDS[0]);
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500611 btn.setOnClickListener(v -> {
612 Log.d(TAG, "Attempting to restart session");
Beth Thibodeauee42e8c2020-04-30 01:09:29 -0400613 if (mQSMediaBrowser != null) {
614 mQSMediaBrowser.disconnect();
615 }
616 mQSMediaBrowser = new QSMediaBrowser(mContext, new QSMediaBrowser.Callback(){
617 @Override
618 public void onConnected() {
619 Log.d(TAG, "Successfully restarted");
620 }
621 @Override
622 public void onError() {
623 Log.e(TAG, "Error restarting");
624 mQSMediaBrowser.disconnect();
625 mQSMediaBrowser = null;
626 }
627 }, mServiceComponent);
628 mQSMediaBrowser.restart();
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500629 });
630 btn.setImageDrawable(mContext.getResources().getDrawable(R.drawable.lb_ic_play));
631 btn.setImageTintList(ColorStateList.valueOf(mForegroundColor));
Selim Cinek5dbef2d2020-05-07 17:44:38 -0700632 expandedSet.setVisibility(ACTION_IDS[0], ConstraintSet.VISIBLE);
633 collapsedSet.setVisibility(ACTION_IDS[0], ConstraintSet.VISIBLE);
634
635 mSeekBarViewModel.clearController();
636 // TODO: fix guts
637 // View guts = mMediaNotifView.findViewById(R.id.media_guts);
638 View options = mMediaNotifView.findViewById(R.id.qs_media_controls_options);
639
640 mMediaNotifView.setOnLongClickListener(v -> {
641 // Replace player view with close/cancel view
642// guts.setVisibility(View.GONE);
643 options.setVisibility(View.VISIBLE);
644 return true; // consumed click
645 });
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500646 }
647
Robert Snoeberger3cc22222020-03-25 15:36:31 -0400648 private void makeActive() {
649 Assert.isMainThread();
650 if (!mIsRegistered) {
Robert Snoeberger9a7409b2020-04-09 18:12:27 -0400651 if (mLocalMediaManager != null) {
652 mLocalMediaManager.registerCallback(mDeviceCallback);
653 mLocalMediaManager.startScan();
654 }
Robert Snoeberger3cc22222020-03-25 15:36:31 -0400655 mIsRegistered = true;
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500656 }
657 }
Robert Snoeberger3cc22222020-03-25 15:36:31 -0400658
659 private void makeInactive() {
660 Assert.isMainThread();
661 if (mIsRegistered) {
Robert Snoeberger9a7409b2020-04-09 18:12:27 -0400662 if (mLocalMediaManager != null) {
663 mLocalMediaManager.stopScan();
664 mLocalMediaManager.unregisterCallback(mDeviceCallback);
665 }
Robert Snoeberger3cc22222020-03-25 15:36:31 -0400666 mIsRegistered = false;
667 }
668 }
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400669 /**
670 * Verify that we can connect to the given component with a MediaBrowser, and if so, add that
671 * component to the list of resumption components
672 */
673 private void tryUpdateResumptionList(ComponentName componentName) {
674 Log.d(TAG, "Testing if we can connect to " + componentName);
Beth Thibodeauee42e8c2020-04-30 01:09:29 -0400675 if (mQSMediaBrowser != null) {
676 mQSMediaBrowser.disconnect();
677 }
678 mQSMediaBrowser = new QSMediaBrowser(mContext,
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400679 new QSMediaBrowser.Callback() {
680 @Override
681 public void onConnected() {
682 Log.d(TAG, "yes we can resume with " + componentName);
683 mServiceComponent = componentName;
684 updateResumptionList(componentName);
Beth Thibodeauee42e8c2020-04-30 01:09:29 -0400685 mQSMediaBrowser.disconnect();
686 mQSMediaBrowser = null;
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400687 }
688
689 @Override
690 public void onError() {
691 Log.d(TAG, "Cannot resume with " + componentName);
692 mServiceComponent = null;
Beth Thibodeau89f5c762020-04-21 13:09:55 -0400693 if (!hasMediaSession()) {
694 // If it's not active and we can't resume, remove
695 removePlayer();
696 }
Beth Thibodeauee42e8c2020-04-30 01:09:29 -0400697 mQSMediaBrowser.disconnect();
698 mQSMediaBrowser = null;
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400699 }
700 },
701 componentName);
Beth Thibodeauee42e8c2020-04-30 01:09:29 -0400702 mQSMediaBrowser.testConnection();
Beth Thibodeau23a33ab2020-04-07 20:51:57 -0400703 }
704
705 /**
706 * Add the component to the saved list of media browser services, checking for duplicates and
707 * removing older components that exceed the maximum limit
708 * @param componentName
709 */
710 private synchronized void updateResumptionList(ComponentName componentName) {
711 // Add to front of saved list
712 if (mSharedPrefs == null) {
713 mSharedPrefs = mContext.getSharedPreferences(MEDIA_PREFERENCES, 0);
714 }
715 String componentString = componentName.flattenToString();
716 String listString = mSharedPrefs.getString(MEDIA_PREFERENCE_KEY, null);
717 if (listString == null) {
718 listString = componentString;
719 } else {
720 String[] components = listString.split(QSMediaBrowser.DELIMITER);
721 StringBuilder updated = new StringBuilder(componentString);
722 int nBrowsers = 1;
723 for (int i = 0; i < components.length
724 && nBrowsers < QSMediaBrowser.MAX_RESUMPTION_CONTROLS; i++) {
725 if (componentString.equals(components[i])) {
726 continue;
727 }
728 updated.append(QSMediaBrowser.DELIMITER).append(components[i]);
729 nBrowsers++;
730 }
731 listString = updated.toString();
732 }
733 mSharedPrefs.edit().putString(MEDIA_PREFERENCE_KEY, listString).apply();
734 }
735
736 /**
737 * Called when a player can't be resumed to give it an opportunity to hide or remove itself
738 */
739 protected void removePlayer() { }
Selim Cinek3df592e2020-04-28 13:51:43 -0700740
Selim Cinek54809622020-04-30 19:04:44 -0700741 public void remeasure(@Nullable MediaMeasurementInput input, boolean animate, long duration,
Selim Cinek3df592e2020-04-28 13:51:43 -0700742 long startDelay) {
743 // Let's remeasure if our width changed. Our height is dependent on the expansion, so we
744 // won't animate if it changed
Selim Cinek54809622020-04-30 19:04:44 -0700745 if (input != null && !input.sameAs(mLastMeasureInput)) {
746 mLastMeasureInput = input;
Selim Cinek3df592e2020-04-28 13:51:43 -0700747 if (animate) {
748 mLayoutAnimationHelper.animatePendingSizeChange(duration, startDelay);
749 }
Selim Cinek54809622020-04-30 19:04:44 -0700750 remeasureInternal(input);
751 mMediaNotifView.layout(0, 0, mMediaNotifView.getMeasuredWidth(),
752 mMediaNotifView.getMeasuredHeight());
Selim Cinek3df592e2020-04-28 13:51:43 -0700753 }
754 }
755
Selim Cinek54809622020-04-30 19:04:44 -0700756 public MediaMeasurementInput getLastMeasureInput() {
757 return mLastMeasureInput;
758 }
759
760 private void remeasureInternal(MediaMeasurementInput input) {
Selim Cinek3df592e2020-04-28 13:51:43 -0700761 ConstraintSet expandedSet = mMediaNotifView.getConstraintSet(R.id.expanded);
762 ConstraintSet collapsedSet = mMediaNotifView.getConstraintSet(R.id.collapsed);
Selim Cinek54809622020-04-30 19:04:44 -0700763 int width = input.getWidth();
764 collapsedSet.setGuidelineBegin(R.id.view_width, width);
765 expandedSet.setGuidelineBegin(R.id.view_width, width);
766 mMediaNotifView.measure(input.getWidthMeasureSpec(), input.getHeightMeasureSpec());
Selim Cinek3df592e2020-04-28 13:51:43 -0700767 }
Beth Thibodeau7b6c1782020-03-05 11:43:51 -0500768}