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