summaryrefslogtreecommitdiff
path: root/src/com/android/messaging/ui/VideoThumbnailView.java
blob: 966336e4a9b471c727781cfda0724cb8d69669dc (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
/*
 * Copyright (C) 2015 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.messaging.ui;

import android.content.Context;
import android.content.res.TypedArray;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView.ScaleType;
import android.widget.VideoView;

import com.android.messaging.R;
import com.android.messaging.datamodel.data.MessagePartData;
import com.android.messaging.datamodel.media.ImageRequest;
import com.android.messaging.datamodel.media.MessagePartVideoThumbnailRequestDescriptor;
import com.android.messaging.datamodel.media.VideoThumbnailRequest;
import com.android.messaging.util.Assert;

/**
 * View that encapsulates a video preview (either as a thumbnail image, or video player), and the
 * a play button to overlay it.  Ensures that the video preview maintains the aspect ratio of the
 * original video while trying to respect minimum width/height and constraining to the available
 * bounds
 */
public class VideoThumbnailView extends FrameLayout {
    /**
     * When in this mode the VideoThumbnailView is a lightweight AsyncImageView with an ImageButton
     * to play the video.  Clicking play will launch a full screen player
     */
    private static final int MODE_IMAGE_THUMBNAIL = 0;

    /**
     * When in this mode the VideoThumbnailVideo will include a VideoView, and the play button will
     * play the video inline.  When in this mode, the loop and playOnLoad attributes can be applied
     * to auto-play or loop the video.
     */
    private static final int MODE_PLAYABLE_VIDEO = 1;

    private final int mMode;
    private final boolean mPlayOnLoad;
    private final boolean mAllowCrop;
    private final VideoView mVideoView;
    private final ImageButton mPlayButton;
    private final AsyncImageView mThumbnailImage;
    private int mVideoWidth;
    private int mVideoHeight;
    private Uri mVideoSource;
    private boolean mAnimating;
    private boolean mVideoLoaded;

    public VideoThumbnailView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        final TypedArray typedAttributes =
                context.obtainStyledAttributes(attrs, R.styleable.VideoThumbnailView);

        final LayoutInflater inflater = LayoutInflater.from(context);
        inflater.inflate(R.layout.video_thumbnail_view, this, true);

        mPlayOnLoad = typedAttributes.getBoolean(R.styleable.VideoThumbnailView_playOnLoad, false);
        final boolean loop =
                typedAttributes.getBoolean(R.styleable.VideoThumbnailView_loop, false);
        mMode = typedAttributes.getInt(R.styleable.VideoThumbnailView_mode, MODE_IMAGE_THUMBNAIL);
        mAllowCrop = typedAttributes.getBoolean(R.styleable.VideoThumbnailView_allowCrop, false);

        mVideoWidth = ImageRequest.UNSPECIFIED_SIZE;
        mVideoHeight = ImageRequest.UNSPECIFIED_SIZE;

        if (mMode == MODE_PLAYABLE_VIDEO) {
            mVideoView = new VideoView(context);
            // Video view tries to request focus on start which pulls focus from the user's intended
            // focus when we add this control.  Remove focusability to prevent this.  The play
            // button can still be focused
            mVideoView.setFocusable(false);
            mVideoView.setFocusableInTouchMode(false);
            mVideoView.clearFocus();
            addView(mVideoView, 0, new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(final MediaPlayer mediaPlayer) {
                    mVideoLoaded = true;
                    mVideoWidth = mediaPlayer.getVideoWidth();
                    mVideoHeight = mediaPlayer.getVideoHeight();
                    mediaPlayer.setLooping(loop);
                    trySwitchToVideo();
                }
            });
            mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(final MediaPlayer mediaPlayer) {
                    mPlayButton.setVisibility(View.VISIBLE);
                }
            });
            mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(final MediaPlayer mediaPlayer, final int i, final int i2) {
                    return true;
                }
            });
        } else {
            mVideoView = null;
        }

        mPlayButton = (ImageButton) findViewById(R.id.video_thumbnail_play_button);
        if (loop) {
            mPlayButton.setVisibility(View.GONE);
        } else {
            mPlayButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(final View view) {
                    if (mVideoSource == null) {
                        return;
                    }

                    if (mMode == MODE_PLAYABLE_VIDEO) {
                        mVideoView.seekTo(0);
                        start();
                    } else {
                        UIIntents.get().launchFullScreenVideoViewer(getContext(), mVideoSource);
                    }
                }
            });
            mPlayButton.setOnLongClickListener(new OnLongClickListener() {
                @Override
                public boolean onLongClick(final View view) {
                    // Button prevents long click from propagating up, do it manually
                    VideoThumbnailView.this.performLongClick();
                    return true;
                }
            });
        }

        mThumbnailImage = (AsyncImageView) findViewById(R.id.video_thumbnail_image);
        if (mAllowCrop) {
            mThumbnailImage.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
            mThumbnailImage.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
            mThumbnailImage.setScaleType(ScaleType.CENTER_CROP);
        } else {
            // This is the default setting in the layout, so No-op.
        }
        final int maxHeight = typedAttributes.getDimensionPixelSize(
                R.styleable.VideoThumbnailView_android_maxHeight, ImageRequest.UNSPECIFIED_SIZE);
        if (maxHeight != ImageRequest.UNSPECIFIED_SIZE) {
            mThumbnailImage.setMaxHeight(maxHeight);
            mThumbnailImage.setAdjustViewBounds(true);
        }

        typedAttributes.recycle();
    }

    @Override
    protected void onAnimationStart() {
        super.onAnimationStart();
        mAnimating = true;
    }

    @Override
    protected void onAnimationEnd() {
        super.onAnimationEnd();
        mAnimating = false;
        trySwitchToVideo();
    }

    private void trySwitchToVideo() {
        if (mAnimating) {
            // Don't start video or hide image until after animation completes
            return;
        }

        if (!mVideoLoaded) {
            // Video hasn't loaded, nothing more to do
            return;
        }

        if (mPlayOnLoad) {
            start();
        } else {
            mVideoView.seekTo(0);
        }
    }

    private boolean hasVideoSize() {
        return mVideoWidth != ImageRequest.UNSPECIFIED_SIZE &&
                mVideoHeight != ImageRequest.UNSPECIFIED_SIZE;
    }

    public void start() {
        Assert.equals(MODE_PLAYABLE_VIDEO, mMode);
        mPlayButton.setVisibility(View.GONE);
        mThumbnailImage.setVisibility(View.GONE);
        mVideoView.start();
    }

    // TODO: The check could be added to MessagePartData itself so that all users of MessagePartData
    // get the right behavior, instead of requiring all the users to do similar checks.
    private static boolean shouldUseGenericVideoIcon(final boolean incomingMessage) {
        return incomingMessage && !VideoThumbnailRequest.shouldShowIncomingVideoThumbnails();
    }

    public void setSource(final MessagePartData part, final boolean incomingMessage) {
        if (part == null) {
            clearSource();
        } else {
            mVideoSource = part.getContentUri();
            if (shouldUseGenericVideoIcon(incomingMessage)) {
                mThumbnailImage.setImageResource(R.drawable.generic_video_icon);
                mVideoWidth = ImageRequest.UNSPECIFIED_SIZE;
                mVideoHeight = ImageRequest.UNSPECIFIED_SIZE;
            } else {
                mThumbnailImage.setImageResourceId(
                        new MessagePartVideoThumbnailRequestDescriptor(part));
                if (mVideoView != null) {
                    mVideoView.setVideoURI(mVideoSource);
                }
                mVideoWidth = part.getWidth();
                mVideoHeight = part.getHeight();
            }
        }
    }

    public void setSource(final Uri videoSource, final boolean incomingMessage) {
        if (videoSource == null) {
            clearSource();
        } else {
            mVideoSource = videoSource;
            if (shouldUseGenericVideoIcon(incomingMessage)) {
                mThumbnailImage.setImageResource(R.drawable.generic_video_icon);
                mVideoWidth = ImageRequest.UNSPECIFIED_SIZE;
                mVideoHeight = ImageRequest.UNSPECIFIED_SIZE;
            } else {
                mThumbnailImage.setImageResourceId(
                        new MessagePartVideoThumbnailRequestDescriptor(videoSource));
                if (mVideoView != null) {
                    mVideoView.setVideoURI(videoSource);
                }
            }
        }
    }

    private void clearSource() {
        mVideoSource = null;
        mThumbnailImage.setImageResourceId(null);
        mVideoWidth = ImageRequest.UNSPECIFIED_SIZE;
        mVideoHeight = ImageRequest.UNSPECIFIED_SIZE;
        if (mVideoView != null) {
            mVideoView.setVideoURI(null);
        }
    }

    @Override
    public void setMinimumWidth(final int minWidth) {
        super.setMinimumWidth(minWidth);
        if (mVideoView != null) {
            mVideoView.setMinimumWidth(minWidth);
        }
    }

    @Override
    public void setMinimumHeight(final int minHeight) {
        super.setMinimumHeight(minHeight);
        if (mVideoView != null) {
            mVideoView.setMinimumHeight(minHeight);
        }
    }

    public void setColorFilter(int color) {
        mThumbnailImage.setColorFilter(color);
        mPlayButton.setColorFilter(color);
    }

    public void clearColorFilter() {
        mThumbnailImage.clearColorFilter();
        mPlayButton.clearColorFilter();
    }

    @Override
    protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
        if (mAllowCrop) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
        int desiredWidth = 1;
        int desiredHeight = 1;
        if (mVideoView != null) {
            mVideoView.measure(widthMeasureSpec, heightMeasureSpec);
        }
        mThumbnailImage.measure(widthMeasureSpec, heightMeasureSpec);
        if (hasVideoSize()) {
            desiredWidth = mVideoWidth;
            desiredHeight = mVideoHeight;
        } else {
            desiredWidth = mThumbnailImage.getMeasuredWidth();
            desiredHeight = mThumbnailImage.getMeasuredHeight();
        }

        final int minimumWidth = getMinimumWidth();
        final int minimumHeight = getMinimumHeight();

        // Constrain the scale to fit within the supplied size
        final float maxScale = Math.max(
                MeasureSpec.getSize(widthMeasureSpec) / (float) desiredWidth,
                MeasureSpec.getSize(heightMeasureSpec) / (float) desiredHeight);

        // Scale up to reach minimum width/height
        final float widthScale = Math.max(1, minimumWidth / (float) desiredWidth);
        final float heightScale = Math.max(1, minimumHeight / (float) desiredHeight);
        final float scale = Math.min(maxScale, Math.max(widthScale, heightScale));
        desiredWidth = (int) (desiredWidth * scale);
        desiredHeight = (int) (desiredHeight * scale);

        setMeasuredDimension(desiredWidth, desiredHeight);
    }

    @Override
    protected void onLayout(final boolean changed, final int left, final int top, final int right,
            final int bottom) {
        final int count = getChildCount();
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            child.layout(0, 0, right - left, bottom - top);
        }
    }
}