Merge remote-tracking branch 'upstream/develop' into
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / preview / PreviewMediaFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17 package com.owncloud.android.ui.preview;
18
19 import android.accounts.Account;
20 import android.app.Activity;
21 import android.app.AlertDialog;
22 import android.content.ComponentName;
23 import android.content.Context;
24 import android.content.DialogInterface;
25 import android.content.Intent;
26 import android.content.ServiceConnection;
27 import android.content.res.Configuration;
28 import android.media.MediaPlayer;
29 import android.media.MediaPlayer.OnCompletionListener;
30 import android.media.MediaPlayer.OnErrorListener;
31 import android.media.MediaPlayer.OnPreparedListener;
32 import android.net.Uri;
33 import android.os.Build;
34 import android.os.Bundle;
35 import android.os.IBinder;
36 import android.view.LayoutInflater;
37 import android.view.MotionEvent;
38 import android.view.View;
39 import android.view.View.OnTouchListener;
40 import android.view.ViewGroup;
41 import android.widget.ImageView;
42 import android.widget.Toast;
43 import android.widget.VideoView;
44
45 import com.actionbarsherlock.view.Menu;
46 import com.actionbarsherlock.view.MenuInflater;
47 import com.actionbarsherlock.view.MenuItem;
48 import com.owncloud.android.R;
49 import com.owncloud.android.datamodel.OCFile;
50 import com.owncloud.android.files.FileMenuFilter;
51 import com.owncloud.android.lib.common.utils.Log_OC;
52 import com.owncloud.android.media.MediaControlView;
53 import com.owncloud.android.media.MediaService;
54 import com.owncloud.android.media.MediaServiceBinder;
55 import com.owncloud.android.ui.activity.FileActivity;
56 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
57 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
58 import com.owncloud.android.ui.fragment.FileFragment;
59
60
61 /**
62 * This fragment shows a preview of a downloaded media file (audio or video).
63 *
64 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
65 *
66 * By now, if the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
67 *
68 * @author David A. Velasco
69 */
70 public class PreviewMediaFragment extends FileFragment implements
71 OnTouchListener {
72
73 public static final String EXTRA_FILE = "FILE";
74 public static final String EXTRA_ACCOUNT = "ACCOUNT";
75 private static final String EXTRA_PLAY_POSITION = "PLAY_POSITION";
76 private static final String EXTRA_PLAYING = "PLAYING";
77
78 private View mView;
79 private Account mAccount;
80 private ImageView mImagePreview;
81 private VideoView mVideoPreview;
82 private int mSavedPlaybackPosition;
83
84 private MediaServiceBinder mMediaServiceBinder = null;
85 private MediaControlView mMediaController = null;
86 private MediaServiceConnection mMediaServiceConnection = null;
87 private VideoHelper mVideoHelper;
88 private boolean mAutoplay;
89 public boolean mPrepared;
90
91 private static final String TAG = PreviewMediaFragment.class.getSimpleName();
92
93
94 /**
95 * Creates a fragment to preview a file.
96 *
97 * When 'fileToDetail' or 'ocAccount' are null
98 *
99 * @param fileToDetail An {@link OCFile} to preview in the fragment
100 * @param ocAccount An ownCloud account; needed to start downloads
101 */
102 public PreviewMediaFragment(
103 OCFile fileToDetail,
104 Account ocAccount,
105 int startPlaybackPosition,
106 boolean autoplay) {
107
108 super(fileToDetail);
109 mAccount = ocAccount;
110 mSavedPlaybackPosition = startPlaybackPosition;
111 mAutoplay = autoplay;
112 }
113
114
115 /**
116 * Creates an empty fragment for previews.
117 *
118 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically
119 * (for instance, when the device is turned a aside).
120 *
121 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful
122 * construction
123 */
124 public PreviewMediaFragment() {
125 super();
126 mAccount = null;
127 mSavedPlaybackPosition = 0;
128 mAutoplay = true;
129 }
130
131
132 /**
133 * {@inheritDoc}
134 */
135 @Override
136 public void onCreate(Bundle savedInstanceState) {
137 super.onCreate(savedInstanceState);
138 setHasOptionsMenu(true);
139 }
140
141
142 /**
143 * {@inheritDoc}
144 */
145 @Override
146 public View onCreateView(LayoutInflater inflater, ViewGroup container,
147 Bundle savedInstanceState) {
148 super.onCreateView(inflater, container, savedInstanceState);
149 Log_OC.e(TAG, "onCreateView");
150
151
152 mView = inflater.inflate(R.layout.file_preview, container, false);
153
154 mImagePreview = (ImageView)mView.findViewById(R.id.image_preview);
155 mVideoPreview = (VideoView)mView.findViewById(R.id.video_preview);
156 mVideoPreview.setOnTouchListener(this);
157
158 mMediaController = (MediaControlView)mView.findViewById(R.id.media_controller);
159
160 return mView;
161 }
162
163
164 /**
165 * {@inheritDoc}
166 */
167 @Override
168 public void onActivityCreated(Bundle savedInstanceState) {
169 super.onActivityCreated(savedInstanceState);
170 Log_OC.e(TAG, "onActivityCreated");
171
172 OCFile file = getFile();
173 if (savedInstanceState == null) {
174 if (file == null) {
175 throw new IllegalStateException("Instanced with a NULL OCFile");
176 }
177 if (mAccount == null) {
178 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
179 }
180 if (!file.isDown()) {
181 throw new IllegalStateException("There is no local file to preview");
182 }
183
184 } else {
185 file = (OCFile)savedInstanceState.getParcelable(PreviewMediaFragment.EXTRA_FILE);
186 setFile(file);
187 mAccount = savedInstanceState.getParcelable(PreviewMediaFragment.EXTRA_ACCOUNT);
188 mSavedPlaybackPosition =
189 savedInstanceState.getInt(PreviewMediaFragment.EXTRA_PLAY_POSITION);
190 mAutoplay = savedInstanceState.getBoolean(PreviewMediaFragment.EXTRA_PLAYING);
191
192 }
193 if (file != null && file.isDown()) {
194 if (file.isVideo()) {
195 mVideoPreview.setVisibility(View.VISIBLE);
196 mImagePreview.setVisibility(View.GONE);
197 prepareVideo();
198
199 } else {
200 mVideoPreview.setVisibility(View.GONE);
201 mImagePreview.setVisibility(View.VISIBLE);
202 }
203 }
204
205 }
206
207
208 /**
209 * {@inheritDoc}
210 */
211 @Override
212 public void onSaveInstanceState(Bundle outState) {
213 super.onSaveInstanceState(outState);
214 Log_OC.e(TAG, "onSaveInstanceState");
215
216 outState.putParcelable(PreviewMediaFragment.EXTRA_FILE, getFile());
217 outState.putParcelable(PreviewMediaFragment.EXTRA_ACCOUNT, mAccount);
218
219 if (getFile().isVideo()) {
220 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
221 mAutoplay = mVideoPreview.isPlaying();
222 outState.putInt(PreviewMediaFragment.EXTRA_PLAY_POSITION , mSavedPlaybackPosition);
223 outState.putBoolean(PreviewMediaFragment.EXTRA_PLAYING , mAutoplay);
224 } else {
225 outState.putInt(
226 PreviewMediaFragment.EXTRA_PLAY_POSITION ,
227 mMediaServiceBinder.getCurrentPosition());
228 outState.putBoolean(
229 PreviewMediaFragment.EXTRA_PLAYING , mMediaServiceBinder.isPlaying());
230 }
231 }
232
233
234 @Override
235 public void onStart() {
236 super.onStart();
237 Log_OC.e(TAG, "onStart");
238
239 OCFile file = getFile();
240 if (file != null && file.isDown()) {
241 if (file.isAudio()) {
242 bindMediaService();
243
244 } else if (file.isVideo()) {
245 stopAudio();
246 playVideo();
247 }
248 }
249 }
250
251
252 private void stopAudio() {
253 Intent i = new Intent(getSherlockActivity(), MediaService.class);
254 i.setAction(MediaService.ACTION_STOP_ALL);
255 getSherlockActivity().startService(i);
256 }
257
258
259 /**
260 * {@inheritDoc}
261 */
262 @Override
263 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
264 super.onCreateOptionsMenu(menu, inflater);
265 inflater.inflate(R.menu.file_actions_menu, menu);
266 }
267
268
269 /**
270 * {@inheritDoc}
271 */
272 @Override
273 public void onPrepareOptionsMenu(Menu menu) {
274 super.onPrepareOptionsMenu(menu);
275
276 if (mContainerActivity.getStorageManager() != null) {
277 FileMenuFilter mf = new FileMenuFilter(
278 getFile(),
279 mContainerActivity.getStorageManager().getAccount(),
280 mContainerActivity,
281 getSherlockActivity()
282 );
283 mf.filter(menu);
284 }
285
286 // additional restriction for this fragment
287 // TODO allow renaming in PreviewImageFragment
288 MenuItem item = menu.findItem(R.id.action_rename_file);
289 if (item != null) {
290 item.setVisible(false);
291 item.setEnabled(false);
292 }
293
294 // additional restriction for this fragment
295 item = menu.findItem(R.id.action_move);
296 if (item != null) {
297 item.setVisible(false);
298 item.setEnabled(false);
299 }
300 }
301
302
303 /**
304 * {@inheritDoc}
305 */
306 @Override
307 public boolean onOptionsItemSelected(MenuItem item) {
308 switch (item.getItemId()) {
309 case R.id.action_share_file: {
310 stopPreview(false);
311 mContainerActivity.getFileOperationsHelper().shareFileWithLink(getFile());
312 return true;
313 }
314 case R.id.action_unshare_file: {
315 stopPreview(false);
316 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(getFile());
317 return true;
318 }
319 case R.id.action_open_file_with: {
320 openFile();
321 return true;
322 }
323 case R.id.action_remove_file: {
324 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(getFile());
325 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
326 return true;
327 }
328 case R.id.action_see_details: {
329 seeDetails();
330 return true;
331 }
332 case R.id.action_send_file: {
333 sendFile();
334 return true;
335 }
336 case R.id.action_sync_file: {
337 mContainerActivity.getFileOperationsHelper().syncFile(getFile());
338 return true;
339 }
340
341 default:
342 return false;
343 }
344 }
345
346
347
348 /**
349 * Update the file of the fragment with file value
350 * @param file
351 */
352 public void updateFile(OCFile file){
353 setFile(file);
354 }
355
356 private void sendFile() {
357 stopPreview(false);
358 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(getFile());
359
360 }
361
362 private void seeDetails() {
363 stopPreview(false);
364 mContainerActivity.showDetails(getFile());
365 }
366
367
368 private void prepareVideo() {
369 // create helper to get more control on the playback
370 mVideoHelper = new VideoHelper();
371 mVideoPreview.setOnPreparedListener(mVideoHelper);
372 mVideoPreview.setOnCompletionListener(mVideoHelper);
373 mVideoPreview.setOnErrorListener(mVideoHelper);
374 }
375
376 @SuppressWarnings("static-access")
377 private void playVideo() {
378 // create and prepare control panel for the user
379 mMediaController.setMediaPlayer(mVideoPreview);
380
381 // load the video file in the video player ;
382 // when done, VideoHelper#onPrepared() will be called
383 Uri uri = Uri.parse(getFile().getStoragePath());
384 mVideoPreview.setVideoPath(uri.encode(getFile().getStoragePath()));
385 }
386
387
388 private class VideoHelper implements OnCompletionListener, OnPreparedListener, OnErrorListener {
389
390 /**
391 * Called when the file is ready to be played.
392 *
393 * Just starts the playback.
394 *
395 * @param mp {@link MediaPlayer} instance performing the playback.
396 */
397 @Override
398 public void onPrepared(MediaPlayer vp) {
399 Log_OC.e(TAG, "onPrepared");
400 mVideoPreview.seekTo(mSavedPlaybackPosition);
401 if (mAutoplay) {
402 mVideoPreview.start();
403 }
404 mMediaController.setEnabled(true);
405 mMediaController.updatePausePlay();
406 mPrepared = true;
407 }
408
409
410 /**
411 * Called when the file is finished playing.
412 *
413 * Finishes the activity.
414 *
415 * @param mp {@link MediaPlayer} instance performing the playback.
416 */
417 @Override
418 public void onCompletion(MediaPlayer mp) {
419 Log_OC.e(TAG, "completed");
420 if (mp != null) {
421 mVideoPreview.seekTo(0);
422 // next lines are necessary to work around undesired video loops
423 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.GINGERBREAD) {
424 mVideoPreview.pause();
425
426 } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.GINGERBREAD_MR1) {
427 // mVideePreview.pause() is not enough
428
429 mMediaController.setEnabled(false);
430 mVideoPreview.stopPlayback();
431 mAutoplay = false;
432 mSavedPlaybackPosition = 0;
433 mVideoPreview.setVideoPath(getFile().getStoragePath());
434 }
435 } // else : called from onError()
436 mMediaController.updatePausePlay();
437 }
438
439
440 /**
441 * Called when an error in playback occurs.
442 *
443 * @param mp {@link MediaPlayer} instance performing the playback.
444 * @param what Type of error
445 * @param extra Extra code specific to the error
446 */
447 @Override
448 public boolean onError(MediaPlayer mp, int what, int extra) {
449 if (mVideoPreview.getWindowToken() != null) {
450 String message = MediaService.getMessageForMediaError(
451 getSherlockActivity(), what, extra);
452 new AlertDialog.Builder(getSherlockActivity())
453 .setMessage(message)
454 .setPositiveButton(android.R.string.VideoView_error_button,
455 new DialogInterface.OnClickListener() {
456 public void onClick(DialogInterface dialog, int whichButton) {
457 dialog.dismiss();
458 VideoHelper.this.onCompletion(null);
459 }
460 })
461 .setCancelable(false)
462 .show();
463 }
464 return true;
465 }
466
467 }
468
469
470 @Override
471 public void onPause() {
472 Log_OC.e(TAG, "onPause");
473 super.onPause();
474 }
475
476 @Override
477 public void onResume() {
478 super.onResume();
479 Log_OC.e(TAG, "onResume");
480 }
481
482 @Override
483 public void onDestroy() {
484 Log_OC.e(TAG, "onDestroy");
485 super.onDestroy();
486 }
487
488 @Override
489 public void onStop() {
490 Log_OC.e(TAG, "onStop");
491
492 mPrepared = false;
493 if (mMediaServiceConnection != null) {
494 Log_OC.d(TAG, "Unbinding from MediaService ...");
495 if (mMediaServiceBinder != null && mMediaController != null) {
496 mMediaServiceBinder.unregisterMediaController(mMediaController);
497 }
498 getSherlockActivity().unbindService(mMediaServiceConnection);
499 mMediaServiceConnection = null;
500 mMediaServiceBinder = null;
501 }
502
503 super.onStop();
504 }
505
506 @Override
507 public boolean onTouch(View v, MotionEvent event) {
508 if (event.getAction() == MotionEvent.ACTION_DOWN && v == mVideoPreview) {
509 startFullScreenVideo();
510 return true;
511 }
512 return false;
513 }
514
515
516 private void startFullScreenVideo() {
517 Intent i = new Intent(getSherlockActivity(), PreviewVideoActivity.class);
518 i.putExtra(FileActivity.EXTRA_ACCOUNT, mAccount);
519 i.putExtra(FileActivity.EXTRA_FILE, getFile());
520 i.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, mVideoPreview.isPlaying());
521 mVideoPreview.pause();
522 i.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, mVideoPreview.getCurrentPosition());
523 startActivityForResult(i, 0);
524 }
525
526 @Override
527 public void onConfigurationChanged (Configuration newConfig) {
528 Log_OC.e(TAG, "onConfigurationChanged " + this);
529 }
530
531 @Override
532 public void onActivityResult (int requestCode, int resultCode, Intent data) {
533 Log_OC.e(TAG, "onActivityResult " + this);
534 super.onActivityResult(requestCode, resultCode, data);
535 if (resultCode == Activity.RESULT_OK) {
536 mSavedPlaybackPosition = data.getExtras().getInt(
537 PreviewVideoActivity.EXTRA_START_POSITION);
538 mAutoplay = data.getExtras().getBoolean(PreviewVideoActivity.EXTRA_AUTOPLAY);
539 }
540 }
541
542
543 private void playAudio() {
544 OCFile file = getFile();
545 if (!mMediaServiceBinder.isPlaying(file)) {
546 Log_OC.d(TAG, "starting playback of " + file.getStoragePath());
547 mMediaServiceBinder.start(mAccount, file, mAutoplay, mSavedPlaybackPosition);
548
549 } else {
550 if (!mMediaServiceBinder.isPlaying() && mAutoplay) {
551 mMediaServiceBinder.start();
552 mMediaController.updatePausePlay();
553 }
554 }
555 }
556
557
558 private void bindMediaService() {
559 Log_OC.d(TAG, "Binding to MediaService...");
560 if (mMediaServiceConnection == null) {
561 mMediaServiceConnection = new MediaServiceConnection();
562 }
563 getSherlockActivity().bindService( new Intent(getSherlockActivity(),
564 MediaService.class),
565 mMediaServiceConnection,
566 Context.BIND_AUTO_CREATE);
567 // follow the flow in MediaServiceConnection#onServiceConnected(...)
568 }
569
570 /** Defines callbacks for service binding, passed to bindService() */
571 private class MediaServiceConnection implements ServiceConnection {
572
573 @Override
574 public void onServiceConnected(ComponentName component, IBinder service) {
575 if (getSherlockActivity() != null) {
576 if (component.equals(
577 new ComponentName(getSherlockActivity(), MediaService.class))) {
578 Log_OC.d(TAG, "Media service connected");
579 mMediaServiceBinder = (MediaServiceBinder) service;
580 if (mMediaServiceBinder != null) {
581 prepareMediaController();
582 playAudio(); // do not wait for the touch of nobody to play audio
583
584 Log_OC.d(TAG, "Successfully bound to MediaService, MediaController ready");
585
586 } else {
587 Log_OC.e(TAG, "Unexpected response from MediaService while binding");
588 }
589 }
590 }
591 }
592
593 private void prepareMediaController() {
594 mMediaServiceBinder.registerMediaController(mMediaController);
595 if (mMediaController != null) {
596 mMediaController.setMediaPlayer(mMediaServiceBinder);
597 mMediaController.setEnabled(true);
598 mMediaController.updatePausePlay();
599 }
600 }
601
602 @Override
603 public void onServiceDisconnected(ComponentName component) {
604 if (component.equals(new ComponentName(getSherlockActivity(), MediaService.class))) {
605 Log_OC.e(TAG, "Media service suddenly disconnected");
606 if (mMediaController != null) {
607 mMediaController.setMediaPlayer(null);
608 } else {
609 Toast.makeText(
610 getSherlockActivity(),
611 "No media controller to release when disconnected from media service",
612 Toast.LENGTH_SHORT).show();
613 }
614 mMediaServiceBinder = null;
615 mMediaServiceConnection = null;
616 }
617 }
618 }
619
620
621
622 /**
623 * Opens the previewed file with an external application.
624 */
625 private void openFile() {
626 stopPreview(true);
627 mContainerActivity.getFileOperationsHelper().openFile(getFile());
628 finish();
629 }
630
631 /**
632 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewMediaFragment}
633 * to be previewed.
634 *
635 * @param file File to test if can be previewed.
636 * @return 'True' if the file can be handled by the fragment.
637 */
638 public static boolean canBePreviewed(OCFile file) {
639 return (file != null && (file.isAudio() || file.isVideo()));
640 }
641
642
643 public void stopPreview(boolean stopAudio) {
644 OCFile file = getFile();
645 if (file.isAudio() && stopAudio) {
646 mMediaServiceBinder.pause();
647
648 } else if (file.isVideo()) {
649 mVideoPreview.stopPlayback();
650 }
651 }
652
653
654
655 /**
656 * Finishes the preview
657 */
658 private void finish() {
659 getSherlockActivity().onBackPressed();
660 }
661
662
663 public int getPosition() {
664 if (mPrepared) {
665 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
666 }
667 Log_OC.e(TAG, "getting position: " + mSavedPlaybackPosition);
668 return mSavedPlaybackPosition;
669 }
670
671 public boolean isPlaying() {
672 if (mPrepared) {
673 mAutoplay = mVideoPreview.isPlaying();
674 }
675 return mAutoplay;
676 }
677
678 }