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