summaryrefslogtreecommitdiffstats
path: root/src/org/lineageos/eleven/widgets/PlayPauseProgressButton.java
blob: 8b8788fed0ee6992c3e747b562fe82d6715b60c0 (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
/*
* Copyright (c) 2013, The Linux Foundation. All rights reserved.
* Copyright (C) 2015 The CyanogenMod 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.cyanogenmod.eleven.widgets;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import com.cyanogenmod.eleven.R;
import com.cyanogenmod.eleven.utils.MusicUtils;

/**
 * This class handles the playpause button as well as the circular progress bar
 * it self-updates the progress bar but the containing activity/fragment
 * needs to add code to pause/resume this button to prevent unnecessary
 * updates while the activity/fragment is not visible
 */
public class PlayPauseProgressButton extends FrameLayout {
    private static String TAG = PlayPauseProgressButton.class.getSimpleName();
    private static boolean DEBUG = false;
    private static final int REVOLUTION_IN_DEGREES = 360;
    private static final int HALF_REVOLUTION_IN_DEGREES = REVOLUTION_IN_DEGREES / 2;

    private ProgressBar mProgressBar;
    private PlayPauseButton mPlayPauseButton;
    private Runnable mUpdateProgress;
    private boolean mPaused;

    private final int mSmallDistance;
    private float mDragPercentage = 0.0f;
    private boolean mDragEnabled = false;
    private boolean mDragging = false;
    private float mDownAngle;
    private float mDragAngle;
    private float mDownX;
    private float mDownY;
    private int mWidth;
    private long mCurrentSongDuration;
    private long mCurrentSongProgress;

    public PlayPauseProgressButton(Context context, AttributeSet attrs) {
        super(context, attrs);

        // set enabled to false as default so that calling enableAndShow will execute
        setEnabled(false);

        // set paused to false since we shouldn't be typically created while not visible
        mPaused = false;

        mSmallDistance = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        mPlayPauseButton = (PlayPauseButton)findViewById(R.id.action_button_play);
        mProgressBar = (ProgressBar)findViewById(R.id.circularProgressBar);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // Make the play pause button size dependent on the container size
        int horizontalPadding = getMeasuredWidth() / 4;
        int verticalPadding = getMeasuredHeight() / 4;
        mPlayPauseButton.setPadding(
                horizontalPadding, horizontalPadding,
                verticalPadding, verticalPadding);

        // rotate the progress bar 90 degrees counter clockwise so that the
        // starting position is at the top
        mProgressBar.setPivotX(mProgressBar.getMeasuredWidth() / 2);
        mProgressBar.setPivotY(mProgressBar.getMeasuredHeight() / 2);
        mProgressBar.setRotation(-90);
    }

    /**
     * Enable and shows the container
     */
    public void enableAndShow() {
        // enable
        setEnabled(true);

        // make our view visible
        setVisibility(VISIBLE);
    }

    /**
     * Disables and sets the visibility to gone for the container
     */
    public void disableAndHide() {
        // disable
        setEnabled(false);

        // hide our view
        setVisibility(GONE);
    }

    /**
     * Sets whether the user can drag the progress in a circular motion to seek the track
     */
    public void setDragEnabled(boolean enabled) {
        mDragEnabled = enabled;
    }

    /**
     * @return true if the user is actively dragging to seek
     */
    public boolean isDragging() {
        return mDragEnabled && mDragging;
    }

    /**
     * @return how far the user has dragged in the track in ms
     */
    public long getDragProgressInMs() {
        return (long)(mDragPercentage * mCurrentSongDuration);
    }

    @Override
    public void setEnabled(boolean enabled) {
        // if the enabled state isn't changed, quit
        if (enabled == isEnabled()) return;

        super.setEnabled(enabled);

        // signal our state has changed
        onStateChanged();
    }

    /**
     * Pauses the progress bar periodic update logic
     */
    public void pause() {
        if (!mPaused) {
            mPaused = true;

            // signal our state has changed
            onStateChanged();
        }
    }

    /**
     * Resumes the progress bar periodic update logic
     */
    public void resume() {
        if (mPaused) {
            mPaused = false;

            // signal our state has changed
            onStateChanged();
        }
    }

    /**
     * @return play pause button
     */
    public PlayPauseButton getPlayPauseButton() {
        return mPlayPauseButton;
    }

    /**
     * Signaled if the state has changed (either the enabled or paused flag)
     * When the state changes, we either kick off the updates or remove them based on those flags
     */
    private void onStateChanged() {
        // if we are enabled and not paused
        if (isEnabled() && !mPaused) {
            // update the state of the progress bar and play/pause button
            updateState();

            // kick off update states
            postUpdate();
        } else {
            // otherwise remove our update
            removeUpdate();
        }
    }

    /**
     * Updates the state of the progress bar and the play pause button
     */
    private void updateState() {
        mCurrentSongDuration = MusicUtils.duration();
        mCurrentSongProgress = MusicUtils.position();

        int progress = 0;
        if (isDragging()) {
            progress = (int) (mDragPercentage * mProgressBar.getMax());
        } else if (mCurrentSongDuration > 0) {
            progress = (int) (mProgressBar.getMax() * mCurrentSongProgress / mCurrentSongDuration);
        }

        mProgressBar.setProgress(progress);
        mPlayPauseButton.updateState();
    }

    /**
     * Creates and posts the update runnable to the handler
     */
    private void postUpdate() {
        if (mUpdateProgress == null) {
            mUpdateProgress = new Runnable() {
                @Override
                public void run() {
                    updateState();
                    postDelayed(mUpdateProgress, isDragging() ? MusicUtils.UPDATE_FREQUENCY_FAST_MS
                            : MusicUtils.UPDATE_FREQUENCY_MS);
                }
            };
        }

        // remove any existing callbacks
        removeCallbacks(mUpdateProgress);

        // post ourselves as a delayed
        post(mUpdateProgress);
    }

    /**
     * Removes the runnable from the handler
     */
    private void removeUpdate() {
        if (mUpdateProgress != null) {
            removeCallbacks(mUpdateProgress);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldW, int oldH) {
        mWidth = Math.min(w, h);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (!mDragEnabled) {
            return false;
        }

        return onTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();

        if (!mDragEnabled || mCurrentSongDuration <= 0) {
            return false;
        }

        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                mDownX = event.getX();
                mDownY = event.getY();
                mDownAngle = angle(mDownX, mDownY);
                mDragAngle = REVOLUTION_IN_DEGREES
                        * (mCurrentSongProgress / (float) mCurrentSongDuration);
                mDragPercentage = mDragAngle / REVOLUTION_IN_DEGREES;
                mDragging = false;
                break;
            case MotionEvent.ACTION_MOVE:
                // if the user has moved a certain distance
                if (Math.sqrt(Math.pow(event.getX() - mDownX, 2)
                        + Math.pow(event.getY() - mDownY, 2)) < mSmallDistance) {
                    return false;
                }

                // if we weren't previously dragging, immediately kick off an update to reflect
                // the change faster
                if (!mDragging) {
                    postUpdate();
                }

                mDragging = true;
                getParent().requestDisallowInterceptTouchEvent(true);

                // calculate the amount of angle we've moved
                final float deltaAngle = getDelta(x, y);
                mDragAngle = cropAngle(mDragAngle + deltaAngle);
                mDragPercentage = mDragAngle / REVOLUTION_IN_DEGREES;

                if (DEBUG) {
                    Log.d(TAG, "Delta Angle: " + deltaAngle + ", Target Angle: " + mDownAngle);
                }

                return true;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                // if we were dragging, seek to where we dragged to
                if (mDragging) {
                    MusicUtils.seek((long)(mDragPercentage * mCurrentSongDuration));
                }
                mDragging = false;
            default:
                break;
        }
        return mDragging;
    }

    /**
     * Crops the angle between 0 and 360 - if the angle is < 0, it will return 0, if it is more than
     * 360 it will return 360
     */
    private static float cropAngle(float angle) {
        return Math.min(REVOLUTION_IN_DEGREES, Math.max(0.0f, angle));
    }

    /**
     * Wraps the angle between -180 and 180. This assumes that the passed in
     * angle is >= -360 and <= 360
     */
    private static float wrapHalfRevolution(float angle) {
        if (angle < -HALF_REVOLUTION_IN_DEGREES) {
            return angle + REVOLUTION_IN_DEGREES;
        } else if (angle > HALF_REVOLUTION_IN_DEGREES) {
            return angle - REVOLUTION_IN_DEGREES;
        }

        return angle;
    }

    /**
     * Gets the change in angle from the down angle and updates the down angle to the current angle
     */
    private float getDelta(float x, float y) {
        float angle = angle(x, y);
        float deltaAngle = wrapHalfRevolution(angle - mDownAngle);
        mDownAngle = angle;
        return deltaAngle;
    }

    /**
     * Calculates the angle at the point passed in based on the center of the button
     */
    private float angle(float x, float y) {
        float center = mWidth / 2.0f;
        x -= center;
        y -= center;

        if (x == 0.0f) {
            if (y > 0.0f) {
                return 180.0f;
            } else {
                return 0.0f;
            }
        }

        float angle = (float) (Math.atan(y / x) / Math.PI * 180.0);
        if (x > 0.0f) {
            angle += 90;
        } else {
            angle += 270;
        }
        return angle;
    }
}