瀏覽代碼

Merge branch 'feature_previews' into develop

Conflicts:
	src/com/owncloud/android/ui/activity/FileDisplayActivity.java
David A. Velasco 12 年之前
父節點
當前提交
56f1df02c4
共有 47 個文件被更改,包括 6164 次插入735 次删除
  1. 14 7
      AndroidManifest.xml
  2. 二進制
      res/drawable-hdpi/image_fail.png
  3. 二進制
      res/drawable-ldpi/image_fail.png
  4. 二進制
      res/drawable-mdpi/image_fail.png
  5. 29 0
      res/layout/audio_player.xml
  6. 222 221
      res/layout/file_details_fragment.xml
  7. 72 0
      res/layout/file_download_fragment.xml
  8. 65 0
      res/layout/file_preview.xml
  9. 94 0
      res/layout/media_control.xml
  10. 38 0
      res/layout/preview_image_activity.xml
  11. 67 0
      res/layout/preview_image_fragment.xml
  12. 11 0
      res/layout/video_layout.xml
  13. 31 0
      res/menu/file_actions_menu.xml
  14. 0 52
      res/menu/file_context_menu.xml
  15. 5 5
      res/menu/main_menu.xml
  16. 26 0
      res/values-de-rDE/strings.xml
  17. 43 6
      res/values/strings.xml
  18. 2 0
      src/com/owncloud/android/datamodel/DataStorageManager.java
  19. 17 0
      src/com/owncloud/android/datamodel/FileDataStorageManager.java
  20. 29 0
      src/com/owncloud/android/datamodel/OCFile.java
  21. 101 6
      src/com/owncloud/android/files/services/FileDownloader.java
  22. 105 18
      src/com/owncloud/android/files/services/FileUploader.java
  23. 473 0
      src/com/owncloud/android/media/MediaControlView.java
  24. 706 0
      src/com/owncloud/android/media/MediaService.java
  25. 182 0
      src/com/owncloud/android/media/MediaServiceBinder.java
  26. 33 0
      src/com/owncloud/android/network/ProgressiveDataTransferer.java
  27. 5 4
      src/com/owncloud/android/operations/ChunkedUploadFileOperation.java
  28. 15 4
      src/com/owncloud/android/operations/DownloadFileOperation.java
  29. 34 8
      src/com/owncloud/android/operations/UploadFileOperation.java
  30. 199 34
      src/com/owncloud/android/ui/activity/FileDetailActivity.java
  31. 254 66
      src/com/owncloud/android/ui/activity/FileDisplayActivity.java
  32. 1 0
      src/com/owncloud/android/ui/activity/InstantUploadActivity.java
  33. 1 8
      src/com/owncloud/android/ui/activity/UploadFilesActivity.java
  34. 1 1
      src/com/owncloud/android/ui/dialog/IndeterminateProgressDialog.java
  35. 5 0
      src/com/owncloud/android/ui/fragment/ConfirmationDialogFragment.java
  36. 203 228
      src/com/owncloud/android/ui/fragment/FileDetailFragment.java
  37. 74 0
      src/com/owncloud/android/ui/fragment/FileFragment.java
  38. 35 45
      src/com/owncloud/android/ui/fragment/OCFileListFragment.java
  39. 397 0
      src/com/owncloud/android/ui/preview/FileDownloadFragment.java
  40. 449 0
      src/com/owncloud/android/ui/preview/PreviewImageActivity.java
  41. 686 0
      src/com/owncloud/android/ui/preview/PreviewImageFragment.java
  42. 353 0
      src/com/owncloud/android/ui/preview/PreviewImagePagerAdapter.java
  43. 756 0
      src/com/owncloud/android/ui/preview/PreviewMediaFragment.java
  44. 283 0
      src/com/owncloud/android/ui/preview/PreviewVideoActivity.java
  45. 23 10
      src/eu/alefzero/webdav/ChunkFromFileChannelRequestEntity.java
  46. 24 11
      src/eu/alefzero/webdav/FileRequestEntity.java
  47. 1 1
      src/eu/alefzero/webdav/WebdavClient.java

+ 14 - 7
AndroidManifest.xml

@@ -35,7 +35,8 @@
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.READ_PHONE_STATE" />
     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
-
+    <uses-permission android:name="android.permission.WAKE_LOCK"/>
+    
     <uses-sdk
         android:minSdkVersion="8"
         android:targetSdkVersion="13" />
@@ -89,6 +90,13 @@
         </activity>
         <activity android:name=".ui.activity.PreferencesNewSessionewSession" >
         </activity>
+        
+		<activity	android:name="com.owncloud.android.ui.preview.PreviewImageActivity" />
+		        
+        <activity	android:name="com.owncloud.android.ui.preview.PreviewVideoActivity"
+					android:label="@string/app_name"
+					android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
+		</activity>        
 
         <service
             android:name=".authenticator.AccountAuthenticatorService"
@@ -132,8 +140,9 @@
             </intent-filter>
         </activity>
 
-        <service android:name=".files.services.FileDownloader" >
-        </service>
+        <service android:name=".files.services.FileDownloader" />
+        <service android:name=".files.services.FileUploader" />
+        <service android:name=".media.MediaService" />
 
         <activity android:name=".ui.activity.FileDetailActivity" />
         <activity android:name=".ui.activity.PinCodeActivity" />
@@ -143,10 +152,8 @@
         <activity android:name=".ui.activity.ConflictsResolveActivity"/>
         <activity android:name=".ui.activity.GenericExplanationActivity"/>
         <activity android:name=".ui.activity.ErrorsWhileCopyingHandlerActivity"/>
-        
-        <service android:name=".files.services.FileUploader" >
-        </service>
-        <service android:name=".files.services.InstantUploadService" />
+        
+        <service android:name=".files.services.InstantUploadService" />
         <receiver android:name=".files.InstantUploadBroadcastReceiver">
             <intent-filter>
                 <action android:name="com.android.camera.NEW_PICTURE" />

二進制
res/drawable-hdpi/image_fail.png


二進制
res/drawable-ldpi/image_fail.png


二進制
res/drawable-mdpi/image_fail.png


+ 29 - 0
res/layout/audio_player.xml

@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:id="@+id/main_audio_view"
+              android:layout_width="fill_parent"
+              android:layout_height="wrap_content"
+              android:layout_gravity="center"
+              android:orientation="vertical">
+  <TextView
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    android:layout_gravity="center"
+    android:text="Now playing:"
+    android:textSize="25sp"
+    android:textStyle="bold"
+    />
+  <TextView
+    android:id="@+id/now_playing_text"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    android:layout_marginTop="20dip"
+    android:layout_marginLeft="10dip"
+    android:layout_marginRight="10dip"
+    android:layout_gravity="center"
+    android:text="Now playing.."
+    android:textSize="16sp"
+    android:textStyle="italic"
+    />
+</LinearLayout>

+ 222 - 221
res/layout/file_details_fragment.xml

@@ -18,224 +18,225 @@
   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 -->
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="fill_parent"
-    android:layout_height="fill_parent"
-    android:background="@color/owncloud_white" >
-
-    <ScrollView
-        android:id="@+id/fdScrollView"
-        android:layout_width="fill_parent"
-        android:layout_height="fill_parent" >
-
-        <RelativeLayout
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content" >
-
-            <RelativeLayout
-                android:id="@+id/fdFileHeaderContainer"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_marginLeft="16dp"
-                android:layout_marginTop="4dp" >
-
-                <ImageView
-                    android:id="@+id/fdIcon"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:src="@drawable/file" />
-
-                <TextView
-                    android:id="@+id/fdFilename"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:layout_centerVertical="true"
-                    android:layout_toRightOf="@+id/fdIcon"
-                    android:text="file.name"
-                    android:textAppearance="?android:attr/textAppearanceLarge" />
-            </RelativeLayout>
-
-            <RelativeLayout
-                android:id="@+id/fdDetailsContainer"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/fdFileHeaderContainer" >
-
-                <RelativeLayout
-                    android:id="@+id/fdLabelContainer"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:layout_alignParentLeft="true"
-                    android:layout_alignParentTop="true"
-                    android:layout_marginLeft="16dp" >
-
-                    <TextView
-                        android:id="@+id/fdTypeLabel"
-                        android:layout_width="wrap_content"
-                        android:layout_height="wrap_content"
-                        android:layout_marginTop="24dp"
-                        android:text="@string/filedetails_type"
-                        android:textAppearance="?android:attr/textAppearanceMedium" />
-
-                    <TextView
-                        android:id="@+id/fdSizeLabel"
-                        android:layout_width="wrap_content"
-                        android:layout_height="wrap_content"
-                        android:layout_below="@+id/fdTypeLabel"
-                        android:layout_marginTop="12dp"
-                        android:text="@string/filedetails_size"
-                        android:textAppearance="?android:attr/textAppearanceMedium" />
-
-                    <TextView
-                        android:id="@+id/fdCreatedLabel"
-                        android:layout_width="wrap_content"
-                        android:layout_height="wrap_content"
-                        android:layout_below="@+id/fdSizeLabel"
-                        android:layout_marginTop="12dp"
-                        android:text="@string/filedetails_created"
-                        android:visibility="gone"
-                        android:textAppearance="?android:attr/textAppearanceMedium" />
-                    
-                    <TextView
-                        android:id="@+id/fdModifiedLabel"
-                        android:layout_width="wrap_content"
-                        android:layout_height="wrap_content"
-                        android:layout_below="@+id/fdCreatedLabel"
-                        android:layout_marginTop="12dp"
-                        android:text="@string/filedetails_modified"
-                        android:textAppearance="?android:attr/textAppearanceMedium" />
-                </RelativeLayout>
-
-                <RelativeLayout
-                    android:id="@+id/fdValueContainer"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:layout_alignParentTop="true"
-                    android:layout_marginLeft="12dp"
-                    android:layout_toRightOf="@+id/fdLabelContainer" >
-
-                    <TextView
-                        android:id="@+id/fdType"
-                        android:layout_width="wrap_content"
-                        android:layout_height="wrap_content"
-                        android:layout_marginTop="24dp"
-                        android:text="JPG Image"
-                        android:textAppearance="?android:attr/textAppearanceMedium" />
-
-                    <TextView
-                        android:id="@+id/fdSize"
-                        android:layout_width="wrap_content"
-                        android:layout_height="wrap_content"
-                        android:layout_below="@+id/fdType"
-                        android:layout_marginTop="12dp"
-                        android:text="389 KB"
-                        android:textAppearance="?android:attr/textAppearanceMedium" />
-
-                    <TextView
-                        android:id="@+id/fdCreated"
-                        android:layout_width="wrap_content"
-                        android:layout_height="wrap_content"
-                        android:layout_below="@+id/fdSize"
-                        android:layout_marginTop="12dp"
-                        android:visibility="gone"
-                        android:text="2012/05/18 12:23 PM"
-                        android:textAppearance="?android:attr/textAppearanceMedium" />
-
-                    <TextView
-                        android:id="@+id/fdModified"
-                        android:layout_width="wrap_content"
-                        android:layout_height="wrap_content"
-                        android:layout_below="@+id/fdCreated"
-                        android:layout_marginTop="12dp"
-                        android:text="2012/05/19 02:56 PM"
-                        android:textAppearance="?android:attr/textAppearanceMedium" />
-                </RelativeLayout>
-
-            </RelativeLayout>
-
-            <RelativeLayout
-                android:id="@+id/fdPreviewAndDL"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/fdDetailsContainer"
-                android:gravity="center_horizontal" >
-
-                <CheckBox
-                    android:id="@+id/fdKeepInSync"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:layout_centerHorizontal="true"
-                    android:text="@string/fd_keep_in_sync" />
-
-                <ImageView
-                    android:id="@+id/fdPreview"
-                    android:layout_width="match_parent"
-                    android:layout_height="match_parent"
-                    android:layout_below="@id/fdKeepInSync"
-                    android:layout_centerHorizontal="true"
-                    android:layout_marginTop="16dp"
-                    android:src="@drawable/owncloud_logo" />
-
-                <LinearLayout
-                    android:layout_width="match_parent"
-                    android:layout_height="wrap_content"
-                    android:layout_below="@id/fdPreview"
-                    android:orientation="vertical" >
-
-                    <LinearLayout
-                        android:layout_width="match_parent"
-                        android:layout_height="wrap_content"
-                        android:gravity="center_horizontal" >
-
-                        <Button
-                            android:id="@+id/fdRemoveBtn"
-                            android:layout_width="wrap_content"
-                            android:layout_height="wrap_content"
-                            android:layout_marginTop="12dp"
-                            android:text="@string/common_remove" />
-
-                        <Button
-                            android:id="@+id/fdOpenBtn"
-                            android:layout_width="wrap_content"
-                            android:layout_height="wrap_content"
-                            android:layout_marginTop="12dp"
-                            android:text="@string/filedetails_open" />
-
-                    </LinearLayout>
-
-                    <LinearLayout
-                        android:layout_width="match_parent"
-                        android:layout_height="wrap_content"
-                        android:gravity="center_horizontal">
-
-                        <Button
-                            android:id="@+id/fdDownloadBtn"
-                            android:layout_width="wrap_content"
-                            android:layout_height="wrap_content"
-                            android:layout_marginTop="12dp"
-                            android:text="@string/filedetails_download" />
-
-                        <Button
-                            android:id="@+id/fdRenameBtn"
-                            android:layout_width="wrap_content"
-                            android:layout_height="wrap_content"
-                            android:layout_marginTop="12dp"
-                            android:text="@string/common_rename" />
-
-                    </LinearLayout>
-<!-- 
-                    <Button
-                        android:id="@+id/fdShareBtn"
-                        android:layout_width="wrap_content"
-                        android:layout_height="wrap_content"
-                        android:layout_marginTop="12dp"
-                        android:text="@string/common_share" />
- -->
-
-                </LinearLayout>
-            </RelativeLayout>
-
-        </RelativeLayout>
-    </ScrollView>
-
-</RelativeLayout>
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+	android:id="@+id/fdScrollView"
+	android:layout_width="fill_parent"
+	android:layout_height="fill_parent" >
+
+	<RelativeLayout
+		android:layout_width="match_parent"
+		android:layout_height="wrap_content" >
+
+		<RelativeLayout
+			android:id="@+id/fdFileHeaderContainer"
+			android:layout_width="match_parent"
+			android:layout_height="wrap_content"
+			android:layout_marginLeft="16dp"
+			android:layout_marginTop="4dp" >
+	
+			<ImageView
+				android:id="@+id/fdIcon"
+				android:layout_width="wrap_content"
+				android:layout_height="wrap_content"
+				android:src="@drawable/file" />
+				
+			<TextView
+			    android:id="@+id/fdFilename"
+			    android:layout_width="wrap_content"
+			    android:layout_height="wrap_content"
+			    android:layout_centerVertical="true"
+			    android:layout_toRightOf="@+id/fdIcon"
+			    android:text="@string/placeholder_filename"
+			    android:textAppearance="?android:attr/textAppearanceLarge" />
+			
+		</RelativeLayout>
+	
+		<RelativeLayout
+			android:id="@+id/fdDetailsContainer"
+			android:layout_width="match_parent"
+			android:layout_height="wrap_content"
+			android:layout_below="@id/fdFileHeaderContainer" >
+		
+			<RelativeLayout
+				android:id="@+id/fdLabelContainer"
+				android:layout_width="wrap_content"
+				android:layout_height="wrap_content"
+				android:layout_alignParentLeft="true"
+				android:layout_alignParentTop="true"
+				android:layout_marginLeft="16dp" >
+				
+				<TextView
+					android:id="@+id/fdTypeLabel"
+					android:layout_width="wrap_content"
+					android:layout_height="wrap_content"
+					android:layout_marginTop="24dp"
+					android:text="@string/filedetails_type"
+					android:textAppearance="?android:attr/textAppearanceMedium" />
+					
+				<TextView
+					android:id="@+id/fdSizeLabel"
+					android:layout_width="wrap_content"
+					android:layout_height="wrap_content"
+					android:layout_below="@+id/fdTypeLabel"
+					android:layout_marginTop="12dp"
+					android:text="@string/filedetails_size"
+					android:textAppearance="?android:attr/textAppearanceMedium" />
+					
+				<TextView
+					android:id="@+id/fdCreatedLabel"
+					android:layout_width="wrap_content"
+					android:layout_height="wrap_content"
+					android:layout_below="@+id/fdSizeLabel"
+					android:layout_marginTop="12dp"
+					android:text="@string/filedetails_created"
+					android:visibility="gone"
+					android:textAppearance="?android:attr/textAppearanceMedium" />
+					  
+				<TextView
+					android:id="@+id/fdModifiedLabel"
+					android:layout_width="wrap_content"
+					android:layout_height="wrap_content"
+					android:layout_below="@+id/fdCreatedLabel"
+					android:layout_marginTop="12dp"
+					android:text="@string/filedetails_modified"
+					android:textAppearance="?android:attr/textAppearanceMedium" />
+			</RelativeLayout>
+	
+			<RelativeLayout
+				android:id="@+id/fdValueContainer"
+				android:layout_width="wrap_content"
+				android:layout_height="wrap_content"
+				android:layout_alignParentTop="true"
+				android:layout_marginLeft="12dp"
+				android:layout_toRightOf="@+id/fdLabelContainer" >
+				
+				<TextView
+					android:id="@+id/fdType"
+					android:layout_width="wrap_content"
+					android:layout_height="wrap_content"
+					android:layout_marginTop="24dp"
+					android:text="@string/placeholder_filetype"
+					android:textAppearance="?android:attr/textAppearanceMedium" />
+					
+				<TextView
+					android:id="@+id/fdSize"
+					android:layout_width="wrap_content"
+					android:layout_height="wrap_content"
+					android:layout_below="@+id/fdType"
+					android:layout_marginTop="12dp"
+					android:text="@string/placeholder_filesize"
+					android:textAppearance="?android:attr/textAppearanceMedium" />
+					
+				<TextView
+					android:id="@+id/fdCreated"
+					android:layout_width="wrap_content"
+					android:layout_height="wrap_content"
+					android:layout_below="@+id/fdSize"
+					android:layout_marginTop="12dp"
+					android:visibility="gone"
+					android:text="@string/placeholder_timestamp"
+					android:textAppearance="?android:attr/textAppearanceMedium" />
+					
+				<TextView
+					android:id="@+id/fdModified"
+					android:layout_width="wrap_content"
+					android:layout_height="wrap_content"
+					android:layout_below="@+id/fdCreated"
+					android:layout_marginTop="12dp"
+					android:text="@string/placeholder_timestamp"
+					android:textAppearance="?android:attr/textAppearanceMedium" />
+		
+			</RelativeLayout>
+	
+		</RelativeLayout>
+	
+		<RelativeLayout
+			android:id="@+id/fdProgressAndControl"
+			android:layout_width="match_parent"
+			android:layout_height="wrap_content"
+			android:layout_below="@+id/fdDetailsContainer"
+			android:gravity="center_horizontal" 
+			android:layout_margin="16dp"
+			>
+			
+			<CheckBox
+				android:id="@+id/fdKeepInSync"
+				android:layout_width="wrap_content"
+				android:layout_height="wrap_content"
+				android:layout_centerHorizontal="true"
+				android:text="@string/fd_keep_in_sync" />
+
+			<LinearLayout
+				android:layout_width="match_parent"
+				android:layout_height="wrap_content"
+				android:layout_below="@id/fdKeepInSync"
+				android:orientation="vertical" >
+				
+    			<TextView 
+    			    android:id="@+id/fdProgressText" 
+    			    android:layout_width="match_parent"
+      				android:layout_height="wrap_content" 
+      				android:text="@string/downloader_download_in_progress_ticker"
+      				/>
+    			
+    			<ProgressBar android:id="@+id/fdProgressBar"
+					android:layout_width="match_parent" 
+					android:layout_height="wrap_content"
+					android:progressDrawable="@android:drawable/progress_horizontal"
+					android:indeterminate="false" 
+					android:indeterminateOnly="false" 
+					/>
+				    								
+			    <LinearLayout
+					android:layout_width="match_parent"
+					android:layout_height="wrap_content"
+					android:gravity="center_horizontal"
+					android:layout_marginTop="12dp"
+					>
+				    				
+					<Button
+						android:id="@+id/fdDownloadBtn"
+						android:layout_width="0dp"
+						android:layout_height="wrap_content"
+						android:layout_weight="1"
+						android:text="@string/filedetails_download" />
+						
+					<Button
+						android:id="@+id/fdOpenBtn"
+						android:layout_width="0dp"
+						android:layout_height="wrap_content"
+						android:layout_weight="1"
+						android:text="@string/filedetails_open" />
+						
+				</LinearLayout>
+		
+				<LinearLayout
+					android:layout_width="match_parent"
+					android:layout_height="wrap_content"
+					android:gravity="center_horizontal"
+					android:layout_marginTop="12dp"
+					>
+					
+					<Button
+						android:id="@+id/fdRenameBtn"
+						android:layout_width="0dp"
+						android:layout_height="wrap_content"
+						android:layout_weight="1"
+						android:text="@string/common_rename" />
+						
+				    <Button
+						android:id="@+id/fdRemoveBtn"
+						android:layout_width="0dp"
+						android:layout_height="wrap_content"
+						android:layout_weight="1"
+						android:text="@string/common_remove" />
+						
+				</LinearLayout>
+	
+			</LinearLayout>
+			
+		</RelativeLayout>
+
+	</RelativeLayout>
+	
+</ScrollView>

+ 72 - 0
res/layout/file_download_fragment.xml

@@ -0,0 +1,72 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ownCloud Android client application
+
+  Copyright (C) 2012-2013  ownCloud Inc.
+  This program is free software: you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation, either version 3 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+-->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+	android:layout_width="match_parent"
+	android:layout_height="match_parent"
+	android:orientation="vertical" 
+	android:layout_gravity="center"
+	android:gravity="center_vertical"
+	android:padding="20dp"
+	>
+	
+	<TextView 
+	    android:id="@+id/progressText" 
+	    android:layout_width="match_parent"
+		android:layout_height="wrap_content" 
+		android:text="@string/downloader_not_downloaded_yet"
+		android:layout_marginBottom="15dp"
+	/>
+	
+	<ProgressBar android:id="@+id/progressBar"
+		android:layout_width="match_parent" 
+		android:layout_height="wrap_content"
+		android:progressDrawable="@android:drawable/progress_horizontal"
+		android:indeterminate="false" 
+		android:indeterminateOnly="false" 
+		android:layout_marginBottom="15dp"
+	/>
+	
+	<Button
+		android:id="@+id/cancelBtn"
+		android:layout_width="wrap_content"
+		android:layout_height="wrap_content"
+		android:text="@string/common_cancel" 
+		android:layout_marginBottom="15dp"
+	/>
+	
+	<ImageView
+		android:id="@+id/error_image"
+		android:layout_width="wrap_content"
+		android:layout_height="wrap_content"
+		android:layout_margin="0dp"
+		android:layout_gravity="center_horizontal"
+		android:contentDescription="@string/downloader_download_failed_ticker"
+		android:src="@drawable/image_fail" />
+										
+	<TextView 
+	    android:id="@+id/errorText" 
+	    android:layout_width="wrap_content"
+		android:layout_height="wrap_content"
+		android:layout_gravity="center_horizontal"
+		android:layout_margin="40dp"
+		android:text="@string/downloader_download_failed_ticker"
+	/>
+	
+</LinearLayout>
+

+ 65 - 0
res/layout/file_preview.xml

@@ -0,0 +1,65 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ownCloud Android client application
+
+  Copyright (C) 2012-2013  ownCloud Inc.
+  
+  This program is free software: you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation, either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  
+-->
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:id="@+id/top"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:background="@color/owncloud_white"
+    android:gravity="center"
+    tools:context=".ui.fragment.FilePreviewFragment" >
+
+    <FrameLayout 
+        android:id="@+id/visual_area"
+   	    android:layout_width="match_parent"
+   	    android:layout_height="0dp"
+   	    android:layout_alignParentTop="true"
+   	    android:layout_above="@+id/media_controller"
+        >
+    
+	    <ImageView
+	        android:id="@+id/image_preview"
+	        android:layout_width="match_parent"
+	        android:layout_height="match_parent"
+	        android:layout_margin="16dp"
+	        android:layout_gravity="center"
+	        android:contentDescription="@string/preview_image_description"
+	        android:src="@drawable/owncloud_logo" />
+	    
+	   	<VideoView  
+	   	    android:id="@+id/video_preview"
+			android:layout_width="match_parent"
+			android:layout_height="match_parent"  
+			android:layout_gravity="center" 
+			android:visibility="gone"
+			/>
+	   	
+   	</FrameLayout>
+   	
+   	<com.owncloud.android.media.MediaControlView 
+   	    android:id="@id/media_controller"
+   	    android:layout_width="match_parent"
+   	    android:layout_height="wrap_content"
+   	    android:layout_alignParentBottom="true"
+   	    />
+
+</RelativeLayout>

+ 94 - 0
res/layout/media_control.xml

@@ -0,0 +1,94 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ownCloud Android client application
+
+  Copyright (C) 2012-2013  ownCloud Inc.
+  
+  This program is free software: you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation, either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:orientation="vertical">
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:gravity="center"
+        android:paddingTop="4dip"
+        android:orientation="horizontal"
+        >
+
+        <ImageButton 
+            android:id="@+id/rewindBtn" 
+            style="@android:style/MediaButton.Rew" 
+            android:contentDescription="@string/media_rewind_description"
+            />
+        <ImageButton 
+            android:id="@+id/playBtn" 
+            style="@android:style/MediaButton.Play" 
+            android:contentDescription="@string/media_play_pause_description"
+            />
+        <ImageButton 
+            android:id="@+id/forwardBtn" 
+            style="@android:style/MediaButton.Ffwd" 
+            android:contentDescription="@string/media_forward_description"
+            />
+
+    </LinearLayout>
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal">
+
+        <TextView 
+            android:id="@+id/currentTimeText"
+            android:textSize="14sp"
+            android:textStyle="bold"
+            android:paddingTop="4dip"
+            android:paddingStart="4dip"
+            android:layout_gravity="center_horizontal"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:paddingEnd="4dip"
+            android:text="@string/placeholder_media_time"
+            />
+
+        <SeekBar
+            android:id="@+id/progressBar"
+            style="?android:attr/progressBarStyleHorizontal"
+            android:layout_width="0dip"
+            android:layout_weight="1"
+            android:layout_height="32dip"
+            android:layout_alignParentStart="true"
+            android:layout_alignParentEnd="true" />
+
+        <TextView android:id="@+id/totalTimeText"
+            android:textSize="14sp"
+            android:textStyle="bold"
+            android:paddingTop="4dip"
+            android:paddingEnd="4dip"
+            android:layout_gravity="center_horizontal"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:paddingStart="4dip"
+            android:text="@string/placeholder_media_time"
+            />
+        
+    </LinearLayout>
+
+</LinearLayout>

+ 38 - 0
res/layout/preview_image_activity.xml

@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ownCloud Android client application
+
+  Copyright (C) 2012-2013  ownCloud Inc.
+  
+  This program is free software: you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation, either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  -->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical" >
+
+    <android.support.v4.view.ViewPager 
+        android:id="@+id/fragmentPager"
+		android:layout_width="match_parent"
+		android:layout_height="match_parent" 
+		/>
+    
+    <!-- LinearLayout
+        android:id="@+id/fragment"
+            android:layout_width="match_parent"
+            android:layout_height="match_parent" >
+            <!- - Preview: layout=@layout/preview_image_fragment - ->
+    </LinearLayout -->
+
+</LinearLayout>

+ 67 - 0
res/layout/preview_image_fragment.xml

@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ownCloud Android client application
+
+  Copyright (C) 2012-2013  ownCloud Inc.
+  
+  This program is free software: you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation, either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+  
+-->
+
+<!--
+     ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/fdScrollView"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent"
+    android:background="@color/owncloud_white" 
+    android:gravity="center_horizontal"
+-->
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:id="@+id/top"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent"
+    android:background="@color/owncloud_white"
+    tools:context=".ui.fragment.PreviewImageFragment" >
+
+    <ProgressBar 
+        android:id="@+id/progressWheel"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:indeterminate="true"
+        android:indeterminateOnly="true"
+        android:layout_centerInParent="true"
+        />
+    
+    <ImageView
+        android:id="@+id/image"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_margin="0dp"
+        android:layout_centerInParent="true"
+        android:contentDescription="@string/preview_image_description"
+        android:src="@drawable/image_fail" />
+    
+    <TextView
+        android:id="@+id/message"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_centerHorizontal="true"
+        android:layout_below="@id/image"
+        android:layout_margin="40dp"
+        android:text="@string/placeholder_sentence"
+        />
+    
+</RelativeLayout>

+ 11 - 0
res/layout/video_layout.xml

@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<FrameLayout	xmlns:android="http://schemas.android.com/apk/res/android"
+				android:layout_width="fill_parent"
+				android:layout_height="fill_parent" >
+
+	<VideoView  android:id="@+id/videoPlayer"
+				android:layout_width="wrap_content"
+				android:layout_height="wrap_content"  
+				android:layout_gravity="center" />
+	
+</FrameLayout>

+ 31 - 0
res/menu/file_actions_menu.xml

@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ownCloud Android client application
+
+  Copyright (C) 2012  Bartek Przybylski
+  Copyright (C) 2012-2013 ownCloud Inc.
+
+  This program is free software: you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation, either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+-->
+<menu 	xmlns:android="http://schemas.android.com/apk/res/android">
+    
+	<item 	android:id="@+id/action_open_file_with"			android:title="@string/filedetails_open"			android:icon="@android:drawable/ic_menu_edit"					android:orderInCategory="1" />
+	<item 	android:id="@+id/action_download_file" 			android:title="@string/filedetails_download"																		android:orderInCategory="1" />
+	<item 	android:id="@+id/action_cancel_download"		android:title="@string/common_cancel_download"	 	android:icon="@android:drawable/ic_menu_close_clear_cancel"		android:orderInCategory="1" />
+	<item 	android:id="@+id/action_cancel_upload" 			android:title="@string/common_cancel_upload"		android:icon="@android:drawable/ic_menu_close_clear_cancel"		android:orderInCategory="1" />
+	<item 	android:id="@+id/action_rename_file"			android:title="@string/common_rename"				android:icon="@android:drawable/ic_menu_set_as"					android:orderInCategory="1" />
+    <item 	android:id="@+id/action_remove_file"			android:title="@string/common_remove"				android:icon="@android:drawable/ic_menu_delete"					android:orderInCategory="1" />
+    <item 	android:id="@+id/action_see_details"			android:title="@string/actionbar_see_details"		android:icon="@android:drawable/ic_menu_view"					android:orderInCategory="1" />
+    
+</menu>

+ 0 - 52
res/menu/file_context_menu.xml

@@ -1,52 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ownCloud Android client application
-
-  Copyright (C) 2012  Bartek Przybylski
-  Copyright (C) 2012-2013 ownCloud Inc.
-
-  This program is free software: you can redistribute it and/or modify
-  it under the terms of the GNU General Public License as published by
-  the Free Software Foundation, either version 2 of the License, or
-  (at your option) any later version.
-
-  This program is distributed in the hope that it will be useful,
-  but WITHOUT ANY WARRANTY; without even the implied warranty of
-  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-  GNU General Public License for more details.
-
-  You should have received a copy of the GNU General Public License
-  along with this program.  If not, see <http://www.gnu.org/licenses/>.
--->
-<menu 	xmlns:android="http://schemas.android.com/apk/res/android">
-    
-	<item 	android:id="@+id/open_file_item" 
-	    	android:title="@string/filedetails_open" 
-	    	android:icon="@android:drawable/ic_menu_edit"
-	/>
-	
-	<item 	android:id="@+id/download_file_item" 
-	    	android:title="@string/filedetails_download" 
-	/>
-	
-	<item 	android:id="@+id/cancel_download_item" 
-	    	android:title="@string/common_cancel_download" 
-	    	android:icon="@android:drawable/ic_menu_close_clear_cancel"
-	/>
-	
-	<item 	android:id="@+id/cancel_upload_item" 
-	    	android:title="@string/common_cancel_upload" 
-	    	android:icon="@android:drawable/ic_menu_close_clear_cancel"
-	/>
-	
-	<item 	android:id="@+id/rename_file_item" 
-	    	android:title="@string/common_rename" 
-	    	android:icon="@android:drawable/ic_menu_set_as"
-	/>
-	
-    <item 	android:id="@+id/remove_file_item" 
-        	android:title="@string/common_remove" 
-        	android:icon="@android:drawable/ic_menu_delete"
-	/>
-    
-</menu>

+ 5 - 5
res/menu/menu.xml → res/menu/main_menu.xml

@@ -20,11 +20,11 @@
 -->
 <menu
   xmlns:android="http://schemas.android.com/apk/res/android">
-    <item android:id="@+id/startSync" android:title="@string/actionbar_sync" android:icon="@drawable/ic_action_refresh"></item>
-    <item android:id="@+id/createDirectoryItem" android:title="@string/actionbar_mkdir" android:icon="@drawable/ic_action_create_dir"></item>
+    <item android:id="@+id/action_sync_account" 	android:title="@string/actionbar_sync" 		android:icon="@drawable/ic_action_refresh" 				android:orderInCategory="2" />
+    <item android:id="@+id/action_create_dir" 		android:title="@string/actionbar_mkdir" 	android:icon="@drawable/ic_action_create_dir"			android:orderInCategory="2" />
+    <item android:id="@+id/action_upload" 			android:title="@string/actionbar_upload" 	android:icon="@drawable/ic_action_upload" 				android:orderInCategory="2" />
+    <item android:id="@+id/action_settings" 		android:title="@string/actionbar_settings" 	android:icon="@android:drawable/ic_menu_preferences" 	android:orderInCategory="2" />
+    <item android:id="@+id/action_about_app" 		android:title="@string/about_title" 		android:icon="@android:drawable/ic_menu_info_details" 	android:orderInCategory="2" />
     
     <!--  <item android:id="@+id/search" android:title="@string/actionbar_search" android:icon="@drawable/ic_action_search"></item>-->
-    <item android:id="@+id/action_upload" android:title="@string/actionbar_upload" android:icon="@drawable/ic_action_upload"></item>
-    <item android:id="@+id/action_settings" android:title="@string/actionbar_settings" android:icon="@android:drawable/ic_menu_preferences"></item>
-    <item android:id="@+id/about_app" android:title="@string/about_title" android:icon="@android:drawable/ic_menu_info_details"></item>
 </menu>

+ 26 - 0
res/values-de-rDE/strings.xml

@@ -83,6 +83,8 @@
   <string name="common_save_exit">Speichern &amp; Schließen</string>
   <string name="common_exit">%1$s verlassen</string>
   <string name="common_error">Fehler</string>
+  <string name="common_loading">Wird geladen &#8230;</string>
+  <string name="common_error_unknown">Unbekannter Fehler</string>
   <string name="about_title">Über</string>
   <string name="delete_account">Account löschen</string>
   <string name="create_account">Account erstellen</string>
@@ -102,6 +104,7 @@
   <string name="downloader_download_succeeded_content">%1$s wurde erfolgreich heruntergeladen</string>
   <string name="downloader_download_failed_ticker">Herunterladen fehlgeschlagen</string>
   <string name="downloader_download_failed_content">Herunterladen von %1$s konnte nicht abgeschlossen werden</string>
+  <string name="downloader_not_downloaded_yet">Noch nicht heruntergeladen</string>
   <string name="common_choose_account">Konto auswählen</string>
   <string name="sync_string_contacts">Kontakte</string>
   <string name="sync_fail_ticker">Synchronisation fehlgeschlagen</string>
@@ -122,6 +125,26 @@
   <string name="pincode_wrong">Falsche App-PIN</string>
   <string name="pincode_removed">Die App-PIN wurde entfernt</string>
   <string name="pincode_stored">Die App-PIN wurde gespeichert</string>
+  <string name="media_notif_ticker">"%1$s Musik Player"</string>
+  <string name="media_state_playing">"%1$s (wird abgespielt)"</string>
+  <string name="media_state_loading">"%1$s (wird geladen)"</string>
+  <string name="media_event_done">"%1$s Wiedergabe beendet"</string>
+  <string name="media_err_nothing_to_play">Keine Media-Datei gefunden</string>
+  <string name="media_err_no_account">Ungültiger Account</string>
+  <string name="media_err_not_in_owncloud">Datei ist nicht in einem gültigen Account</string>
+  <string name="media_err_unsupported">Nicht unterstützter Medien-Codec</string>
+  <string name="media_err_io">Media-Datei konnte nicht gelesen werden</string>
+  <string name="media_err_malformed">Die Media-Datei ist noch nicht kodiert</string>
+  <string name="media_err_timeout">Zeitüberschreitung ist beim Abspielen aufgetreten</string>
+  <string name="media_err_invalid_progressive_playback">Media-Datei konnte nicht gestreamt werden</string>
+  <string name="media_err_unknown">Media-Datei kann nicht vom Standard Player wiedergegeben werden</string>
+  <string name="media_err_security_ex">Sicherheits-Fehler ist beim Abspielen aufgetreten %1$s</string>
+  <string name="media_err_io_ex">Eingabe-Fehler ist beim Abspielen aufgetreten %1$s</string>
+  <string name="media_err_unexpected">Unerwarteter Fehler bei der Wiedergabe %1$s</string>
+  <string name="media_rewind_description">Zurückspulen</string>
+  <string name="media_play_pause_description">Wiedergabe oder Pause</string>
+  <string name="media_forward_description">Vorspulen</string>
+	
   <string-array name="prefs_trackmydevice_intervall_keys">
     <item>15 Minuten</item>
     <item>30 Minuten</item>
@@ -217,6 +240,9 @@
   <string name="conflict_keep_both">Beide behalten</string>
   <string name="conflict_overwrite">Überschreiben</string>
   <string name="conflict_dont_upload">Nicht hochladen</string>
+  <string name="preview_image_description">Bildvorschau</string>
+  <string name="preview_image_error_unknown_format">Das Bild kann nicht angezeigt werden</string>
+  <string name="preview_image_error_out_of_memory">"Nicht genug Speicherplatz um das Bild anzuzeigen</string>
   
   <string name="actionbar_failed_instant_upload">Fehlgeschlagene Sofortuploads</string>  
   <string name="failed_upload_headline_text">Fehlgeschlagene Sofortuploads</string>

+ 43 - 6
res/values/strings.xml

@@ -22,6 +22,8 @@
     <string name="actionbar_mkdir">Create directory</string>
     <string name="actionbar_search">Search</string>
     <string name="actionbar_settings">Settings</string>
+    <string name="actionbar_see_details">Details</string>
+    
     <string name="prefs_category_general">General</string>
     <string name="prefs_add_session">Add new session</string>
     <string name="prefs_create_img_thumbnails">Create image thumbnails</string>
@@ -83,6 +85,8 @@
     <string name="common_save_exit">Save &amp; Exit</string>
     <string name="common_exit">Leave %1$s</string>
     <string name="common_error">Error</string>
+    <string name="common_loading">Loading &#8230;</string>
+    <string name="common_error_unknown">Unknown error</string>
     <string name="about_title">About</string>
     <string name="delete_account">Delete account</string>
     <string name="create_account">Create account</string>
@@ -102,6 +106,7 @@
     <string name="downloader_download_succeeded_content">%1$s was successfully downloaded</string>
     <string name="downloader_download_failed_ticker">Download failed</string>
     <string name="downloader_download_failed_content">Download of %1$s could not be completed</string>
+    <string name="downloader_not_downloaded_yet">Not downloaded yet</string>
     <string name="common_choose_account">Choose account</string>
     <string name="sync_string_contacts">Contacts</string>
     <string name="sync_fail_ticker">Synchronization failed</string>
@@ -131,7 +136,28 @@
     <string name="pincode_wrong">Incorrect App PIN</string>
     <string name="pincode_removed">App PIN removed</string>
     <string name="pincode_stored">App PIN stored</string>
-
+    
+    <string name="media_notif_ticker">"%1$s music player"</string>
+    <string name="media_state_playing">"%1$s (playing)"</string>
+    <string name="media_state_loading">"%1$s (loading)"</string>
+    <string name="media_event_done">"%1$s playback finished"</string>
+    <string name="media_err_nothing_to_play">No media file found</string>
+	<string name="media_err_no_account">No account provided</string>
+    <string name="media_err_not_in_owncloud">File not in a valid account</string>
+    <string name="media_err_unsupported">Unsupported media codec</string>
+    <string name="media_err_io">Media file could not be read</string>
+    <string name="media_err_malformed">Media file not correctly encoded</string>
+    <string name="media_err_timeout">Too much time trying to play</string>
+    <string name="media_err_invalid_progressive_playback">Media file cannot be streamed</string>
+    <string name="media_err_unknown">Media file cannot be played with the stock media player</string>
+    <string name="media_err_security_ex">Security error trying to play %1$s</string>
+	<string name="media_err_io_ex">Input error trying to play %1$s</string>
+	<string name="media_err_unexpected">Unexpected error trying to play %1$s</string>
+	<string name="media_previous_description">Previous track button</string>
+	<string name="media_rewind_description">Rewind button</string>
+	<string name="media_play_pause_description">Play or pause button</string>
+	<string name="media_forward_description">Fast forward button</string>
+	<string name="media_next_description">Next track button</string>
     <string-array name="prefs_trackmydevice_intervall_keys">
         <item>15 Minutes</item>
         <item>30 Minutes</item>
@@ -217,10 +243,17 @@
     <string name="ssl_validator_label_L">Location:</string>
     <string name="ssl_validator_label_validity">Validity:</string>
     <string name="ssl_validator_label_validity_from">From:</string>
-    <string name="ssl_validator_label_validity_to">To:</string>
-    <string name="ssl_validator_label_signature">Signature:</string>
-    <string name="ssl_validator_label_signature_algorithm">Algorithm:</string>
-    <string name="text_placeholder">This is a placeholder</string>
+	<string name="ssl_validator_label_validity_to">To:</string>
+	<string name="ssl_validator_label_signature">Signature:</string>
+	<string name="ssl_validator_label_signature_algorithm">Algorithm:</string>
+			
+    <string name="placeholder_sentence">This is a placeholder</string>
+    <string name="placeholder_filename">placeholder.txt</string>
+    <string name="placeholder_filetype">PNG Image</string>
+    <string name="placeholder_filesize">389 KB</string>
+    <string name="placeholder_timestamp">2012/05/18 12:23 PM</string>
+    <string name="placeholder_media_time">12:23:45</string>
+    
     <string name="instant_upload_on_wifi">Upload pictures via WiFi only</string>
     <string name="instant_upload_path">/InstantUpload</string>
     <string name="conflict_title">Update conflict</string>
@@ -228,7 +261,11 @@
     <string name="conflict_keep_both">Keep both</string>
     <string name="conflict_overwrite">Overwrite</string>
     <string name="conflict_dont_upload">Don\'t upload</string>
-
+    
+    <string name="preview_image_description">Image preview</string>
+    <string name="preview_image_error_unknown_format">This image can not be shown</string>
+    <string name="preview_image_error_out_of_memory">"Not enough memory to show this image</string>
+    
     <!-- we need to improve the communication of errors to the user -->
     <string name="error__upload__local_file_not_copied">%1$s could not be copied to %2$s local directory</string>
     <string name="actionbar_failed_instant_upload">Failed InstantUpload"</string>

+ 2 - 0
src/com/owncloud/android/datamodel/DataStorageManager.java

@@ -45,4 +45,6 @@ public interface DataStorageManager {
     public void removeDirectory(OCFile dir, boolean removeDBData, boolean removeLocalContent);
 
     public void moveDirectory(OCFile dir, String newPath);
+
+    public Vector<OCFile> getDirectoryImages(OCFile mParentFolder);
 }

+ 17 - 0
src/com/owncloud/android/datamodel/FileDataStorageManager.java

@@ -567,4 +567,21 @@ public class FileDataStorageManager implements DataStorageManager {
         }
     }
 
+    @Override
+    public Vector<OCFile> getDirectoryImages(OCFile directory) {
+        Vector<OCFile> ret = new Vector<OCFile>(); 
+        if (directory != null) {
+            // TODO better implementation, filtering in the access to database (if possible) instead of here 
+            Vector<OCFile> tmp = getDirectoryContent(directory);
+            OCFile current = null; 
+            for (int i=0; i<tmp.size(); i++) {
+                current = tmp.get(i);
+                if (current.isImage()) {
+                    ret.add(current);
+                }
+            }
+        }
+        return ret;
+    }
+
 }

+ 29 - 0
src/com/owncloud/android/datamodel/OCFile.java

@@ -21,9 +21,12 @@ package com.owncloud.android.datamodel;
 
 import java.io.File;
 
+import android.content.Intent;
+import android.net.Uri;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.util.Log;
+import android.webkit.MimeTypeMap;
 
 public class OCFile implements Parcelable, Comparable<OCFile> {
 
@@ -455,4 +458,30 @@ public class OCFile implements Parcelable, Comparable<OCFile> {
         return 0;
     }
 
+    /** @return  'True' if the file contains audio */
+    public boolean isAudio() {
+        return (mMimeType != null && mMimeType.startsWith("audio/"));
+    }
+
+    /** @return  'True' if the file contains video */
+    public boolean isVideo() {
+        return (mMimeType != null && mMimeType.startsWith("video/"));
+    }
+
+    /** @return  'True' if the file contains an image */
+    public boolean isImage() {
+        return ((mMimeType != null && mMimeType.startsWith("image/")) ||
+                 getMimeTypeFromName().startsWith("image/"));
+    }
+    
+    public String getMimeTypeFromName() {
+        String extension = "";
+        int pos = mRemotePath.lastIndexOf('.');
+        if (pos >= 0) {
+            extension = mRemotePath.substring(pos + 1);
+        }
+        String result = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
+        return (result != null) ? result : "";
+    }
+
 }

+ 101 - 6
src/com/owncloud/android/files/services/FileDownloader.java

@@ -21,7 +21,9 @@ package com.owncloud.android.files.services;
 
 import java.io.File;
 import java.util.AbstractList;
+import java.util.HashMap;
 import java.util.Iterator;
+import java.util.Map;
 import java.util.Vector;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
@@ -35,6 +37,8 @@ import com.owncloud.android.operations.DownloadFileOperation;
 import com.owncloud.android.operations.RemoteOperationResult;
 import com.owncloud.android.ui.activity.FileDetailActivity;
 import com.owncloud.android.ui.fragment.FileDetailFragment;
+import com.owncloud.android.ui.preview.PreviewImageActivity;
+import com.owncloud.android.ui.preview.PreviewImageFragment;
 
 import android.accounts.Account;
 import android.app.Notification;
@@ -52,6 +56,7 @@ import android.os.Process;
 import android.util.Log;
 import android.widget.RemoteViews;
 
+import com.owncloud.android.AccountUtils;
 import com.owncloud.android.R;
 import eu.alefzero.webdav.WebdavClient;
 
@@ -136,6 +141,7 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
             DownloadFileOperation newDownload = new DownloadFileOperation(account, file); 
             mPendingDownloads.putIfAbsent(downloadKey, newDownload);
             newDownload.addDatatransferProgressListener(this);
+            newDownload.addDatatransferProgressListener((FileDownloaderBinder)mBinder);
             requestedDownloads.add(downloadKey);
             sendBroadcastNewDownload(newDownload);
             
@@ -165,13 +171,29 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
         return mBinder;
     }
 
+
+    /**
+     * Called when ALL the bound clients were onbound.
+     */
+    @Override
+    public boolean onUnbind(Intent intent) {
+        ((FileDownloaderBinder)mBinder).clearListeners();
+        return false;   // not accepting rebinding (default behaviour)
+    }
+
     
     /**
      *  Binder to let client components to perform operations on the queue of downloads.
      * 
      *  It provides by itself the available operations.
      */
-    public class FileDownloaderBinder extends Binder {
+    public class FileDownloaderBinder extends Binder implements OnDatatransferProgressListener {
+        
+        /** 
+         * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance 
+         */
+        private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
+        
         
         /**
          * Cancels a pending or current download of a remote file.
@@ -190,6 +212,11 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
         }
         
         
+        public void clearListeners() {
+            mBoundListeners.clear();
+        }
+
+
         /**
          * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
          * 
@@ -215,6 +242,55 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
                 }
             }
         }
+
+        
+        /**
+         * Adds a listener interested in the progress of the download for a concrete file.
+         * 
+         * @param listener      Object to notify about progress of transfer.    
+         * @param account       ownCloud account holding the file of interest.
+         * @param file          {@link OCfile} of interest for listener. 
+         */
+        public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
+            if (account == null || file == null || listener == null) return;
+            String targetKey = buildRemoteName(account, file);
+            mBoundListeners.put(targetKey, listener);
+        }
+        
+        
+        
+        /**
+         * Removes a listener interested in the progress of the download for a concrete file.
+         * 
+         * @param listener      Object to notify about progress of transfer.    
+         * @param account       ownCloud account holding the file of interest.
+         * @param file          {@link OCfile} of interest for listener. 
+         */
+        public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
+            if (account == null || file == null || listener == null) return;
+            String targetKey = buildRemoteName(account, file);
+            if (mBoundListeners.get(targetKey) == listener) {
+                mBoundListeners.remove(targetKey);
+            }
+        }
+
+
+        @Override
+        public void onTransferProgress(long progressRate) {
+            // old way, should not be in use any more
+        }
+
+
+        @Override
+        public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
+                String fileName) {
+            String key = buildRemoteName(mCurrentDownload.getAccount(), mCurrentDownload.getFile());
+            OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
+            if (boundListener != null) {
+                boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName);
+            }
+        }
+        
     }
     
     
@@ -328,7 +404,12 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
         mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
         
         /// includes a pending intent in the notification showing the details view of the file
-        Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
+        Intent showDetailsIntent = null;
+        if (PreviewImageFragment.canBePreviewed(download.getFile())) {
+            showDetailsIntent = new Intent(this, PreviewImageActivity.class);
+        } else {
+            showDetailsIntent = new Intent(this, FileDetailActivity.class);
+        }
         showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, download.getFile());
         showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, download.getAccount());
         showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
@@ -376,8 +457,22 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
             int contentId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;
             Notification finalNotification = new Notification(R.drawable.icon, getString(tickerId), System.currentTimeMillis());
             finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
-            // TODO put something smart in the contentIntent below
-            finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
+            Intent showDetailsIntent = null;
+            if (downloadResult.isSuccess()) {
+                if (PreviewImageFragment.canBePreviewed(download.getFile())) {
+                    showDetailsIntent = new Intent(this, PreviewImageActivity.class);
+                } else {
+                    showDetailsIntent = new Intent(this, FileDetailActivity.class);
+                }
+                showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, download.getFile());
+                showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, download.getAccount());
+                showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+                
+            } else {
+                // TODO put something smart in showDetailsIntent
+                showDetailsIntent = new Intent();
+            }
+            finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
             finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), new File(download.getSavePath()).getName()), finalNotification.contentIntent);
             mNotificationManager.notify(tickerId, finalNotification);
         }
@@ -407,8 +502,8 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
      */
     private void sendBroadcastNewDownload(DownloadFileOperation download) {
         Intent added = new Intent(DOWNLOAD_ADDED_MESSAGE);
-        /*added.putExtra(ACCOUNT_NAME, download.getAccount().name);
-        added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());*/
+        added.putExtra(ACCOUNT_NAME, download.getAccount().name);
+        added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
         added.putExtra(EXTRA_FILE_PATH, download.getSavePath());
         sendStickyBroadcast(added);
     }

+ 105 - 18
src/com/owncloud/android/files/services/FileUploader.java

@@ -21,7 +21,9 @@ package com.owncloud.android.files.services;
 
 import java.io.File;
 import java.util.AbstractList;
+import java.util.HashMap;
 import java.util.Iterator;
+import java.util.Map;
 import java.util.Vector;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
@@ -63,6 +65,8 @@ import com.owncloud.android.ui.activity.FailedUploadActivity;
 import com.owncloud.android.ui.activity.FileDetailActivity;
 import com.owncloud.android.ui.activity.InstantUploadActivity;
 import com.owncloud.android.ui.fragment.FileDetailFragment;
+import com.owncloud.android.ui.preview.PreviewImageActivity;
+import com.owncloud.android.ui.preview.PreviewImageFragment;
 import com.owncloud.android.utils.OwnCloudVersion;
 
 import eu.alefzero.webdav.OnDatatransferProgressListener;
@@ -118,8 +122,8 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
     /**
      * Builds a key for mPendingUploads from the account and file to upload
      * 
-     * @param account Account where the file to download is stored
-     * @param file File to download
+     * @param account   Account where the file to upload is stored
+     * @param file      File to upload
      */
     private String buildRemoteName(Account account, OCFile file) {
         return account.name + file.getRemotePath();
@@ -271,6 +275,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
                 }
                 mPendingUploads.putIfAbsent(uploadKey, newUpload);
                 newUpload.addDatatransferProgressListener(this);
+                newUpload.addDatatransferProgressListener((FileUploaderBinder)mBinder);
                 requestedUploads.add(uploadKey);
             }
 
@@ -309,6 +314,16 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
     public IBinder onBind(Intent arg0) {
         return mBinder;
     }
+    
+    /**
+     * Called when ALL the bound clients were onbound.
+     */
+    @Override
+    public boolean onUnbind(Intent intent) {
+        ((FileUploaderBinder)mBinder).clearListeners();
+        return false;   // not accepting rebinding (default behaviour)
+    }
+    
 
     /**
      * Binder to let client components to perform operations on the queue of
@@ -316,8 +331,13 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
      * 
      * It provides by itself the available operations.
      */
-    public class FileUploaderBinder extends Binder {
-
+    public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
+        
+        /** 
+         * Map of listeners that will be reported about progress of uploads from a {@link FileUploaderBinder} instance 
+         */
+        private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
+        
         /**
          * Cancels a pending or current upload of a remote file.
          * 
@@ -333,13 +353,21 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
                 upload.cancel();
             }
         }
+        
+        
+        
+        public void clearListeners() {
+            mBoundListeners.clear();
+        }
+
 
+        
+        
         /**
          * Returns True when the file described by 'file' is being uploaded to
          * the ownCloud account 'account' or waiting for it
          * 
-         * If 'file' is a directory, returns 'true' if some of its descendant
-         * files is downloading or waiting to download.
+         * If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload. 
          * 
          * @param account Owncloud account where the remote file will be stored.
          * @param file A file that could be in the queue of pending uploads
@@ -350,7 +378,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
             String targetKey = buildRemoteName(account, file);
             synchronized (mPendingUploads) {
                 if (file.isDirectory()) {
-                    // this can be slow if there are many downloads :(
+                    // this can be slow if there are many uploads :(
                     Iterator<String> it = mPendingUploads.keySet().iterator();
                     boolean found = false;
                     while (it.hasNext() && !found) {
@@ -362,6 +390,55 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
                 }
             }
         }
+
+
+        /**
+         * Adds a listener interested in the progress of the upload for a concrete file.
+         * 
+         * @param listener      Object to notify about progress of transfer.    
+         * @param account       ownCloud account holding the file of interest.
+         * @param file          {@link OCfile} of interest for listener. 
+         */
+        public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
+            if (account == null || file == null || listener == null) return;
+            String targetKey = buildRemoteName(account, file);
+            mBoundListeners.put(targetKey, listener);
+        }
+        
+        
+        
+        /**
+         * Removes a listener interested in the progress of the upload for a concrete file.
+         * 
+         * @param listener      Object to notify about progress of transfer.    
+         * @param account       ownCloud account holding the file of interest.
+         * @param file          {@link OCfile} of interest for listener. 
+         */
+        public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
+            if (account == null || file == null || listener == null) return;
+            String targetKey = buildRemoteName(account, file);
+            if (mBoundListeners.get(targetKey) == listener) {
+                mBoundListeners.remove(targetKey);
+            }
+        }
+
+
+        @Override
+        public void onTransferProgress(long progressRate) {
+            // old way, should not be in use any more
+        }
+
+
+        @Override
+        public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
+                String fileName) {
+            String key = buildRemoteName(mCurrentUpload.getAccount(), mCurrentUpload.getFile());
+            OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
+            if (boundListener != null) {
+                boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName);
+            }
+        }
+        
     }
 
     /**
@@ -520,8 +597,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
         file.setMimetype(we.contentType());
         file.setModificationTimestamp(we.modifiedTimestamp());
         file.setModificationTimestampAtLastSyncForData(we.modifiedTimestamp());
-        // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where
-        // available
+        // file.setEtag(mCurrentUpload.getEtag());    // TODO Etag, where available
     }
 
     private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager) {
@@ -597,6 +673,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
      * 
      * @param upload Upload operation starting.
      */
+    @SuppressWarnings("deprecation")
     private void notifyUploadStart(UploadFileOperation upload) {
         // / create status notification with a progress bar
         mLastPercent = 0;
@@ -610,10 +687,15 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
         mNotification.contentView.setTextViewText(R.id.status_text,
                 String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName()));
         mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
-
-        // / includes a pending intent in the notification showing the details
-        // view of the file
-        Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
+        
+        /// includes a pending intent in the notification showing the details view of the file
+        Intent showDetailsIntent = null;
+        if (PreviewImageFragment.canBePreviewed(upload.getFile())) {
+            showDetailsIntent = new Intent(this, PreviewImageActivity.class);
+        } else {
+            showDetailsIntent = new Intent(this, FileDetailActivity.class);
+            showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
+        }
         showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
         showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
         showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
@@ -668,10 +750,15 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
                                                                     // flag
             mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
             mNotification.contentView = mDefaultNotificationContentView;
-
-            // / includes a pending intent in the notification showing the
-            // details view of the file
-            Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
+            
+            /// includes a pending intent in the notification showing the details view of the file
+            Intent showDetailsIntent = null;
+            if (PreviewImageFragment.canBePreviewed(upload.getFile())) {
+                showDetailsIntent = new Intent(this, PreviewImageActivity.class); 
+            } else {
+                showDetailsIntent = new Intent(this, FileDetailActivity.class); 
+                showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
+            }
             showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
             showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
             showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
@@ -714,7 +801,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
             // we add only for instant-uploads the InstantUploadActivity and the
             // db entry
             Intent detailUploadIntent = null;
-            if (upload.isInstant()) {
+            if (upload.isInstant() && InstantUploadActivity.IS_ENABLED) {
                 detailUploadIntent = new Intent(this, InstantUploadActivity.class);
                 detailUploadIntent.putExtra(FileUploader.KEY_ACCOUNT, upload.getAccount());
             } else {

+ 473 - 0
src/com/owncloud/android/media/MediaControlView.java

@@ -0,0 +1,473 @@
+/* ownCloud Android client application
+ * 
+ *   Copyright (C) 2012-2013  ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 3 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+package com.owncloud.android.media;
+
+import android.content.Context;
+import android.media.MediaPlayer;
+import android.os.Handler;
+import android.os.Message;
+import android.util.AttributeSet;
+import android.view.KeyEvent;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.view.ViewGroup;
+import android.view.accessibility.AccessibilityEvent;
+import android.view.accessibility.AccessibilityNodeInfo;
+import android.widget.FrameLayout;
+import android.widget.ImageButton;
+import android.widget.MediaController.MediaPlayerControl;
+import android.widget.ProgressBar;
+import android.widget.SeekBar;
+import android.widget.SeekBar.OnSeekBarChangeListener;
+import android.widget.TextView;
+
+import java.util.Formatter;
+import java.util.Locale;
+
+import com.owncloud.android.R;
+
+/**
+ * View containing controls for a {@link MediaPlayer}. 
+ * 
+ * Holds buttons "play / pause", "rewind", "fast forward" 
+ * and a progress slider. 
+ * 
+ * It synchronizes itself with the state of the 
+ * {@link MediaPlayer}.
+ * 
+ * @author David A. Velasco
+ */
+
+public class MediaControlView extends FrameLayout /* implements OnLayoutChangeListener, OnTouchListener */ implements OnClickListener, OnSeekBarChangeListener {
+
+    private MediaPlayerControl  mPlayer;
+    private Context             mContext;
+    private View                mRoot;
+    private ProgressBar         mProgress;
+    private TextView            mEndTime, mCurrentTime;
+    private boolean             mDragging;
+    private static final int    SHOW_PROGRESS = 1;
+    StringBuilder               mFormatBuilder;
+    Formatter                   mFormatter;
+    private ImageButton         mPauseButton;
+    private ImageButton         mFfwdButton;
+    private ImageButton         mRewButton;
+    
+    public MediaControlView(Context context, AttributeSet attrs) {
+        super(context, attrs);
+        mContext = context;
+        
+        FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
+                ViewGroup.LayoutParams.MATCH_PARENT,
+                ViewGroup.LayoutParams.MATCH_PARENT
+        );
+        LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+        mRoot = inflate.inflate(R.layout.media_control, null);
+        initControllerView(mRoot);
+        addView(mRoot, frameParams);
+        
+        setFocusable(true);
+        setFocusableInTouchMode(true);
+        setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
+        requestFocus();
+    }
+
+    @Override
+    public void onFinishInflate() {
+        /*
+        if (mRoot != null)
+            initControllerView(mRoot);
+         */
+    }
+
+    /* TODO REMOVE
+    public MediaControlView(Context context, boolean useFastForward) {
+        super(context);
+        mContext = context;
+        mUseFastForward = useFastForward;
+        initFloatingWindowLayout();
+        //initFloatingWindow();
+    }
+    */
+
+    /* TODO REMOVE
+    public MediaControlView(Context context) {
+        this(context, true);
+    }
+    */
+    
+    /* T
+    private void initFloatingWindow() {
+        mWindowManager = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
+        mWindow = PolicyManager.makeNewWindow(mContext);
+        mWindow.setWindowManager(mWindowManager, null, null);
+        mWindow.requestFeature(Window.FEATURE_NO_TITLE);
+        mDecor = mWindow.getDecorView();
+        mDecor.setOnTouchListener(mTouchListener);
+        mWindow.setContentView(this);
+        mWindow.setBackgroundDrawableResource(android.R.color.transparent);
+        
+        // While the media controller is up, the volume control keys should
+        // affect the media stream type
+        mWindow.setVolumeControlStream(AudioManager.STREAM_MUSIC);
+
+        setFocusable(true);
+        setFocusableInTouchMode(true);
+        setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
+        requestFocus();
+    }
+    */
+
+    /*
+    // Allocate and initialize the static parts of mDecorLayoutParams. Must
+    // also call updateFloatingWindowLayout() to fill in the dynamic parts
+    // (y and width) before mDecorLayoutParams can be used.
+    private void initFloatingWindowLayout() {
+        mDecorLayoutParams = new WindowManager.LayoutParams();
+        WindowManager.LayoutParams p = mDecorLayoutParams;
+        p.gravity = Gravity.TOP;
+        p.height = LayoutParams.WRAP_CONTENT;
+        p.x = 0;
+        p.format = PixelFormat.TRANSLUCENT;
+        p.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
+        p.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
+                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
+                | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH;
+        p.token = null;
+        p.windowAnimations = 0; // android.R.style.DropDownAnimationDown;
+    }
+    */
+
+    // Update the dynamic parts of mDecorLayoutParams
+    // Must be called with mAnchor != NULL.
+    /*
+    private void updateFloatingWindowLayout() {
+        int [] anchorPos = new int[2];
+        mAnchor.getLocationOnScreen(anchorPos);
+
+        WindowManager.LayoutParams p = mDecorLayoutParams;
+        p.width = mAnchor.getWidth();
+        p.y = anchorPos[1] + mAnchor.getHeight();
+    }
+    */
+
+    /*
+    // This is called whenever mAnchor's layout bound changes
+    public void onLayoutChange(View v, int left, int top, int right,
+            int bottom, int oldLeft, int oldTop, int oldRight,
+            int oldBottom) {
+        //updateFloatingWindowLayout();
+        if (mShowing) {
+            mWindowManager.updateViewLayout(mDecor, mDecorLayoutParams);
+        }
+    }
+    */
+    
+    /*
+    public boolean onTouch(View v, MotionEvent event) {
+        if (event.getAction() == MotionEvent.ACTION_DOWN) {
+            if (mShowing) {
+                hide();
+            }
+        }
+            return false;
+    }
+    */
+    
+    
+    public void setMediaPlayer(MediaPlayerControl player) {
+        mPlayer = player;
+        mHandler.sendEmptyMessage(SHOW_PROGRESS);
+        updatePausePlay();
+    }
+
+    
+    private void initControllerView(View v) {
+        mPauseButton = (ImageButton) v.findViewById(R.id.playBtn);
+        if (mPauseButton != null) {
+            mPauseButton.requestFocus();
+            mPauseButton.setOnClickListener(this);
+        }
+
+        mFfwdButton = (ImageButton) v.findViewById(R.id.forwardBtn);
+        if (mFfwdButton != null) {
+            mFfwdButton.setOnClickListener(this);
+        }
+
+        mRewButton = (ImageButton) v.findViewById(R.id.rewindBtn);
+        if (mRewButton != null) {
+            mRewButton.setOnClickListener(this);
+        }
+
+        mProgress = (ProgressBar) v.findViewById(R.id.progressBar);
+        if (mProgress != null) {
+            if (mProgress instanceof SeekBar) {
+                SeekBar seeker = (SeekBar) mProgress;
+                seeker.setOnSeekBarChangeListener(this);
+            }
+            mProgress.setMax(1000);
+        }
+
+        mEndTime = (TextView) v.findViewById(R.id.totalTimeText);
+        mCurrentTime = (TextView) v.findViewById(R.id.currentTimeText);
+        mFormatBuilder = new StringBuilder();
+        mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
+
+    }
+
+    
+    /**
+     * Disable pause or seek buttons if the stream cannot be paused or seeked.
+     * This requires the control interface to be a MediaPlayerControlExt
+     */
+    private void disableUnsupportedButtons() {
+        try {
+            if (mPauseButton != null && !mPlayer.canPause()) {
+                mPauseButton.setEnabled(false);
+            }
+            if (mRewButton != null && !mPlayer.canSeekBackward()) {
+                mRewButton.setEnabled(false);
+            }
+            if (mFfwdButton != null && !mPlayer.canSeekForward()) {
+                mFfwdButton.setEnabled(false);
+            }
+        } catch (IncompatibleClassChangeError ex) {
+            // We were given an old version of the interface, that doesn't have
+            // the canPause/canSeekXYZ methods. This is OK, it just means we
+            // assume the media can be paused and seeked, and so we don't disable
+            // the buttons.
+        }
+    }
+    
+    
+    private Handler mHandler = new Handler() {
+        @Override
+        public void handleMessage(Message msg) {
+            int pos;
+            switch (msg.what) {
+                case SHOW_PROGRESS:
+                    pos = setProgress();
+                    if (!mDragging) {
+                        msg = obtainMessage(SHOW_PROGRESS);
+                        sendMessageDelayed(msg, 1000 - (pos % 1000));
+                    }
+                    break;
+            }
+        }
+    };
+
+    private String stringForTime(int timeMs) {
+        int totalSeconds = timeMs / 1000;
+
+        int seconds = totalSeconds % 60;
+        int minutes = (totalSeconds / 60) % 60;
+        int hours   = totalSeconds / 3600;
+
+        mFormatBuilder.setLength(0);
+        if (hours > 0) {
+            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
+        } else {
+            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
+        }
+    }
+
+    private int setProgress() {
+        if (mPlayer == null || mDragging) {
+            return 0;
+        }
+        int position = mPlayer.getCurrentPosition();
+        int duration = mPlayer.getDuration();
+        if (mProgress != null) {
+            if (duration > 0) {
+                // use long to avoid overflow
+                long pos = 1000L * position / duration;
+                mProgress.setProgress( (int) pos);
+            }
+            int percent = mPlayer.getBufferPercentage();
+            mProgress.setSecondaryProgress(percent * 10);
+        }
+
+        if (mEndTime != null)
+            mEndTime.setText(stringForTime(duration));
+        if (mCurrentTime != null)
+            mCurrentTime.setText(stringForTime(position));
+
+        return position;
+    }
+    
+
+    @Override
+    public boolean dispatchKeyEvent(KeyEvent event) {
+        int keyCode = event.getKeyCode();
+        final boolean uniqueDown = event.getRepeatCount() == 0
+                && event.getAction() == KeyEvent.ACTION_DOWN;
+        if (keyCode ==  KeyEvent.KEYCODE_HEADSETHOOK
+                || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
+                || keyCode == KeyEvent.KEYCODE_SPACE) {
+            if (uniqueDown) {
+                doPauseResume();
+                //show(sDefaultTimeout);
+                if (mPauseButton != null) {
+                    mPauseButton.requestFocus();
+                }
+            }
+            return true;
+        } else if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY) {
+            if (uniqueDown && !mPlayer.isPlaying()) {
+                mPlayer.start();
+                updatePausePlay();
+                //show(sDefaultTimeout);
+            }
+            return true;
+        } else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP
+                || keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE) {
+            if (uniqueDown && mPlayer.isPlaying()) {
+                mPlayer.pause();
+                updatePausePlay();
+                //show(sDefaultTimeout);
+            }
+            return true;
+        }
+
+        //show(sDefaultTimeout);
+        return super.dispatchKeyEvent(event);
+    }
+
+    public void updatePausePlay() {
+        if (mRoot == null || mPauseButton == null)
+            return;
+
+        if (mPlayer.isPlaying()) {
+            mPauseButton.setImageResource(android.R.drawable.ic_media_pause);
+        } else {
+            mPauseButton.setImageResource(android.R.drawable.ic_media_play);
+        }
+    }
+
+    private void doPauseResume() {
+        if (mPlayer.isPlaying()) {
+            mPlayer.pause();
+        } else {
+            mPlayer.start();
+        }
+        updatePausePlay();
+    }
+
+    @Override
+    public void setEnabled(boolean enabled) {
+        if (mPauseButton != null) {
+            mPauseButton.setEnabled(enabled);
+        }
+        if (mFfwdButton != null) {
+            mFfwdButton.setEnabled(enabled);
+        }
+        if (mRewButton != null) {
+            mRewButton.setEnabled(enabled);
+        }
+        if (mProgress != null) {
+            mProgress.setEnabled(enabled);
+        }
+        disableUnsupportedButtons();
+        super.setEnabled(enabled);
+    }
+
+    @Override
+    public void onClick(View v) {
+        int pos;
+        boolean playing = mPlayer.isPlaying();
+        switch (v.getId()) {
+        
+        case R.id.playBtn: 
+            doPauseResume();
+            break;
+
+        case R.id.rewindBtn:
+            pos = mPlayer.getCurrentPosition();
+            pos -= 5000;
+            mPlayer.seekTo(pos);
+            if (!playing) mPlayer.pause();  // necessary in some 2.3.x devices 
+            setProgress();
+            break;
+
+        case R.id.forwardBtn:
+            pos = mPlayer.getCurrentPosition();
+            pos += 15000;
+            mPlayer.seekTo(pos);
+            if (!playing) mPlayer.pause(); // necessary in some 2.3.x devices
+            setProgress();
+            break;
+        
+        }
+    }
+    
+    
+    @Override
+    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
+        if (!fromUser) {
+            // We're not interested in programmatically generated changes to
+            // the progress bar's position.
+            return;
+        }
+
+        long duration = mPlayer.getDuration();
+        long newposition = (duration * progress) / 1000L;
+        mPlayer.seekTo( (int) newposition);
+        if (mCurrentTime != null)
+            mCurrentTime.setText(stringForTime( (int) newposition));
+    }
+    
+    /**
+     * Called in devices with touchpad when the user starts to adjust the 
+     * position of the seekbar's thumb.
+     * 
+     * Will be followed by several onProgressChanged notifications.
+     */
+    @Override
+    public void onStartTrackingTouch(SeekBar seekBar) {
+        mDragging = true;                           // monitors the duration of dragging 
+        mHandler.removeMessages(SHOW_PROGRESS);     // grants no more updates with media player progress while dragging 
+    }
+
+    
+    /**
+     * Called in devices with touchpad when the user finishes the
+     * adjusting of the seekbar.
+     */
+    @Override
+    public void onStopTrackingTouch(SeekBar seekBar) {
+        mDragging = false;
+        setProgress();
+        updatePausePlay();
+        mHandler.sendEmptyMessage(SHOW_PROGRESS);    // grants future updates with media player progress 
+    }
+
+    @Override
+    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
+        super.onInitializeAccessibilityEvent(event);
+        event.setClassName(MediaControlView.class.getName());
+    }
+
+    @Override
+    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
+        super.onInitializeAccessibilityNodeInfo(info);
+        info.setClassName(MediaControlView.class.getName());
+    }
+    
+}

+ 706 - 0
src/com/owncloud/android/media/MediaService.java

@@ -0,0 +1,706 @@
+/* ownCloud Android client application
+ *   Copyright 2013 ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 3 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.media;
+
+import android.accounts.Account;
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.app.Service;
+import android.content.Context;
+import android.content.Intent;
+import android.media.AudioManager;
+import android.media.MediaPlayer;
+import android.media.MediaPlayer.OnCompletionListener;
+import android.media.MediaPlayer.OnErrorListener;
+import android.media.MediaPlayer.OnPreparedListener;
+import android.net.wifi.WifiManager;
+import android.net.wifi.WifiManager.WifiLock;
+import android.os.IBinder;
+import android.os.PowerManager;
+import android.util.Log;
+import android.widget.Toast;
+
+import java.io.IOException;
+
+import com.owncloud.android.R;
+import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.ui.activity.FileDetailActivity;
+import com.owncloud.android.ui.fragment.FileDetailFragment;
+
+/**
+ * Service that handles media playback, both audio and video. 
+ * 
+ * Waits for Intents which signal the service to perform specific operations: Play, Pause,
+ * Rewind, etc.
+ * 
+ * @author David A. Velasco
+ */
+public class MediaService extends Service implements OnCompletionListener, OnPreparedListener,
+                OnErrorListener, AudioManager.OnAudioFocusChangeListener {
+
+    private static final String TAG = MediaService.class.getSimpleName();
+
+    private static final String MY_PACKAGE = MediaService.class.getPackage() != null ? MediaService.class.getPackage().getName() : "com.owncloud.android.media";
+    
+    /// Intent actions that we are prepared to handle
+    public static final String ACTION_PLAY_FILE = MY_PACKAGE + ".action.PLAY_FILE";
+    public static final String ACTION_STOP_ALL = MY_PACKAGE + ".action.STOP_ALL";
+
+    /// Keys to add extras to the action
+    public static final String EXTRA_FILE = MY_PACKAGE + ".extra.FILE";
+    public static final String EXTRA_ACCOUNT = MY_PACKAGE + ".extra.ACCOUNT";
+    public static String EXTRA_START_POSITION = MY_PACKAGE + ".extra.START_POSITION";
+    public static final String EXTRA_PLAY_ON_LOAD = MY_PACKAGE + ".extra.PLAY_ON_LOAD";
+
+
+    /** Error code for specific messages - see regular error codes at {@link MediaPlayer} */
+    public static final int OC_MEDIA_ERROR = 0;
+
+    /** Time To keep the control panel visible when the user does not use it */
+    public static final int MEDIA_CONTROL_SHORT_LIFE = 4000;
+    
+    /** Time To keep the control panel visible when the user does not use it */
+    public static final int MEDIA_CONTROL_PERMANENT = 0;
+    
+    /** Volume to set when audio focus is lost and ducking is allowed */
+    private static final float DUCK_VOLUME = 0.1f;
+
+    /** Media player instance */
+    private MediaPlayer mPlayer = null;
+    
+    /** Reference to the system AudioManager */
+    private AudioManager mAudioManager = null;
+
+    
+    /** Values to indicate the state of the service */
+    enum State {
+        STOPPED,
+        PREPARING,      
+        PLAYING,        
+        PAUSED 
+    };
+    
+
+    /** Current state */
+    private State mState = State.STOPPED;
+    
+    /** Possible focus values */
+    enum AudioFocus {
+        NO_FOCUS,            
+        NO_FOCUS_CAN_DUCK,   
+        FOCUS           
+    }
+    
+    /** Current focus state */
+    private AudioFocus mAudioFocus = AudioFocus.NO_FOCUS;
+    
+
+    /** 'True' when the current song is streaming from the network */
+    private boolean mIsStreaming = false;
+
+    /** Wifi lock kept to prevents the device from shutting off the radio when streaming a file. */
+    private WifiLock mWifiLock;
+    
+    private static final String MEDIA_WIFI_LOCK_TAG = MY_PACKAGE + ".WIFI_LOCK";
+
+    /** Notification to keep in the notification bar while a song is playing */
+    private NotificationManager mNotificationManager;
+    private Notification mNotification = null;
+
+    /** File being played */
+    private OCFile mFile;
+    
+    /** Account holding the file being played */
+    private Account mAccount;
+
+    /** Flag signaling if the audio should be played immediately when the file is prepared */ 
+    protected boolean mPlayOnPrepared;
+
+    /** Position, in miliseconds, where the audio should be started */
+    private int mStartPosition;
+    
+    /** Interface to access the service through binding */
+    private IBinder mBinder;
+
+    /** Control panel shown to the user to control the playback, to register through binding */
+    private MediaControlView mMediaController;
+    
+
+    
+    /**
+     * Helper method to get an error message suitable to show to users for errors occurred in media playback,
+     * 
+     * @param context   A context to access string resources.
+     * @param what      See {@link MediaPlayer.OnErrorListener#onError(MediaPlayer, int, int)
+     * @param extra     See {@link MediaPlayer.OnErrorListener#onError(MediaPlayer, int, int)
+     * @return          Message suitable to users.
+     */
+    public static String getMessageForMediaError(Context context, int what, int extra) {
+        int messageId;
+        
+        if (what == OC_MEDIA_ERROR) {
+            messageId = extra;
+                
+        } else if (extra == MediaPlayer.MEDIA_ERROR_UNSUPPORTED) {
+            /*  Added in API level 17
+                Bitstream is conforming to the related coding standard or file spec, but the media framework does not support the feature.
+                Constant Value: -1010 (0xfffffc0e)
+             */
+            messageId = R.string.media_err_unsupported;
+
+        } else if (extra == MediaPlayer.MEDIA_ERROR_IO) {
+            /*  Added in API level 17
+                File or network related operation errors.
+                Constant Value: -1004 (0xfffffc14) 
+             */
+            messageId = R.string.media_err_io;
+            
+        } else if (extra == MediaPlayer.MEDIA_ERROR_MALFORMED) {
+            /*  Added in API level 17
+                Bitstream is not conforming to the related coding standard or file spec.
+                Constant Value: -1007 (0xfffffc11) 
+             */
+            messageId = R.string.media_err_malformed;
+            
+        } else if (extra == MediaPlayer.MEDIA_ERROR_TIMED_OUT) {
+            /*  Added in API level 17
+                Some operation takes too long to complete, usually more than 3-5 seconds.
+                Constant Value: -110 (0xffffff92)
+            */
+            messageId = R.string.media_err_timeout;
+
+        } else if (what == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
+            /*  Added in API level 3
+                The video is streamed and its container is not valid for progressive playback i.e the video's index (e.g moov atom) is not at the start of the file.
+                Constant Value: 200 (0x000000c8)
+            */
+            messageId = R.string.media_err_invalid_progressive_playback;
+                
+        } else {
+            /*  MediaPlayer.MEDIA_ERROR_UNKNOWN
+                Added in API level 1
+                Unspecified media player error.
+                Constant Value: 1 (0x00000001)
+            */
+            /*  MediaPlayer.MEDIA_ERROR_SERVER_DIED)
+                Added in API level 1
+                Media server died. In this case, the application must release the MediaPlayer object and instantiate a new one.
+                Constant Value: 100 (0x00000064) 
+             */
+            messageId = R.string.media_err_unknown;
+        }
+        return context.getString(messageId);
+    }
+
+
+    
+    /**
+     * Initialize a service instance
+     * 
+     * {@inheritDoc}
+     */
+    @Override
+    public void onCreate() {
+        Log.d(TAG, "Creating ownCloud media service");
+
+        mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).
+                createWifiLock(WifiManager.WIFI_MODE_FULL, MEDIA_WIFI_LOCK_TAG);
+
+        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
+        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
+        mBinder = new MediaServiceBinder(this);
+    }
+
+    
+    /**
+     * Entry point for Intents requesting actions, sent here via startService.
+     * 
+     * {@inheritDoc}
+     */
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        String action = intent.getAction();
+        if (action.equals(ACTION_PLAY_FILE)) { 
+            processPlayFileRequest(intent);
+            
+        } else if (action.equals(ACTION_STOP_ALL)) {
+            processStopRequest(true);
+        }
+
+        return START_NOT_STICKY; // don't want it to restart in case it's killed.
+    }
+
+
+    /**
+     * Processes a request to play a media file received as a parameter
+     * 
+     * TODO If a new request is received when a file is being prepared, it is ignored. Is this what we want? 
+     * 
+     * @param intent    Intent received in the request with the data to identify the file to play. 
+     */
+    private void processPlayFileRequest(Intent intent) {
+        if (mState != State.PREPARING) {
+            mFile = intent.getExtras().getParcelable(EXTRA_FILE);
+            mAccount = intent.getExtras().getParcelable(EXTRA_ACCOUNT);
+            mPlayOnPrepared = intent.getExtras().getBoolean(EXTRA_PLAY_ON_LOAD, false);
+            mStartPosition = intent.getExtras().getInt(EXTRA_START_POSITION, 0);
+            tryToGetAudioFocus();
+            playMedia();
+        }
+    }
+
+    
+    /**
+     * Processes a request to play a media file.
+     */
+    protected void processPlayRequest() {
+        // request audio focus
+        tryToGetAudioFocus();
+
+        // actually play the song
+        if (mState == State.STOPPED) {
+            // (re)start playback
+            playMedia();
+            
+        } else if (mState == State.PAUSED) {
+            // continue playback
+            mState = State.PLAYING;
+            setUpAsForeground(String.format(getString(R.string.media_state_playing), mFile.getFileName()));
+            configAndStartMediaPlayer();
+            
+        }
+    }
+
+    
+    /**
+     * Makes sure the media player exists and has been reset. This will create the media player
+     * if needed, or reset the existing media player if one already exists.
+     */
+    protected void createMediaPlayerIfNeeded() {
+        if (mPlayer == null) {
+            mPlayer = new MediaPlayer();
+
+            // make sure the CPU won't go to sleep while media is playing
+            mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
+
+            // the media player will notify the service when it's ready preparing, and when it's done playing
+            mPlayer.setOnPreparedListener(this);
+            mPlayer.setOnCompletionListener(this);
+            mPlayer.setOnErrorListener(this);
+            
+        } else {
+            mPlayer.reset();
+        }
+    }
+
+    /**
+     * Processes a request to pause the current playback 
+     */
+    protected void processPauseRequest() {
+        if (mState == State.PLAYING) {
+            mState = State.PAUSED;
+            mPlayer.pause();
+            releaseResources(false); // retain media player in pause
+            // TODO polite audio focus, instead of keep it owned; or not?
+        }
+    }
+    
+    
+    /**
+     * Processes a request to stop the playback.
+     * 
+     * @param   force       When 'true', the playback is stopped no matter the value of mState
+     */
+    protected void processStopRequest(boolean force) {
+        if (mState != State.PREPARING || force) {
+            mState = State.STOPPED;
+            mFile = null;
+            mAccount = null;
+            releaseResources(true);
+            giveUpAudioFocus();
+            stopSelf();     // service is no longer necessary
+        }
+    }
+    
+
+    /**
+     * Releases resources used by the service for playback. This includes the "foreground service"
+     * status and notification, the wake locks and possibly the MediaPlayer.
+     *
+     * @param releaseMediaPlayer    Indicates whether the Media Player should also be released or not
+     */
+    protected void releaseResources(boolean releaseMediaPlayer) {
+        // stop being a foreground service
+        stopForeground(true);
+
+        // stop and release the Media Player, if it's available
+        if (releaseMediaPlayer && mPlayer != null) {
+            mPlayer.reset();
+            mPlayer.release();
+            mPlayer = null;
+        }
+
+        // release the Wifi lock, if holding it
+        if (mWifiLock.isHeld()) {
+            mWifiLock.release();
+        }
+    }
+
+    
+    /**
+     * Fully releases the audio focus.
+     */
+    private void giveUpAudioFocus() {
+        if (mAudioFocus == AudioFocus.FOCUS 
+                && mAudioManager != null  
+                && AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAudioManager.abandonAudioFocus(this))  {
+            
+            mAudioFocus = AudioFocus.NO_FOCUS;
+        }
+    }
+
+    
+    /**
+     * Reconfigures MediaPlayer according to audio focus settings and starts/restarts it. 
+     */
+    protected void configAndStartMediaPlayer() {
+        if (mPlayer == null) {
+            throw new IllegalStateException("mPlayer is NULL");
+        }
+        
+        if (mAudioFocus == AudioFocus.NO_FOCUS) {
+            if (mPlayer.isPlaying()) {
+                mPlayer.pause();        // have to be polite; but mState is not changed, to resume when focus is received again
+            }
+            
+        }  else { 
+            if (mAudioFocus == AudioFocus.NO_FOCUS_CAN_DUCK) {
+                mPlayer.setVolume(DUCK_VOLUME, DUCK_VOLUME);
+                
+            } else {
+                mPlayer.setVolume(1.0f, 1.0f); // full volume
+            }
+    
+            if (!mPlayer.isPlaying()) {
+                mPlayer.start();
+            }
+        }
+    }
+
+    
+    /**
+     * Requests the audio focus to the Audio Manager 
+     */
+    private void tryToGetAudioFocus() {
+        if (mAudioFocus != AudioFocus.FOCUS 
+                && mAudioManager != null 
+                && (AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAudioManager.requestAudioFocus( this,
+                                                                                                AudioManager.STREAM_MUSIC, 
+                                                                                                AudioManager.AUDIOFOCUS_GAIN))
+                ) {
+            mAudioFocus = AudioFocus.FOCUS;
+        }
+    }
+
+    
+    /**
+     * Starts playing the current media file. 
+     */
+    protected void playMedia() {
+        mState = State.STOPPED;
+        releaseResources(false); // release everything except MediaPlayer
+
+        try {
+            if (mFile == null) { 
+                Toast.makeText(this, R.string.media_err_nothing_to_play, Toast.LENGTH_LONG).show();
+                processStopRequest(true);
+                return;
+                
+            } else if (mAccount == null) {
+                Toast.makeText(this, R.string.media_err_not_in_owncloud, Toast.LENGTH_LONG).show();
+                processStopRequest(true);
+                return;
+            }
+
+            createMediaPlayerIfNeeded();
+            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
+            String url = mFile.getStoragePath();
+            /* Streaming is not possible right now
+            if (url == null || url.length() <= 0) {
+                url = AccountUtils.constructFullURLForAccount(this, mAccount) + mFile.getRemotePath();
+            }
+            mIsStreaming = url.startsWith("http:") || url.startsWith("https:");
+            */
+            mIsStreaming = false;
+            
+            mPlayer.setDataSource(url);
+
+            mState = State.PREPARING;
+            setUpAsForeground(String.format(getString(R.string.media_state_loading), mFile.getFileName()));
+
+            // starts preparing the media player in background
+            mPlayer.prepareAsync();
+
+            // prevent the Wifi from going to sleep when streaming
+            if (mIsStreaming) { 
+                mWifiLock.acquire();
+            } else if (mWifiLock.isHeld()) {
+                mWifiLock.release();
+            }
+            
+        } catch (SecurityException e) {
+            Log.e(TAG, "SecurityException playing " + mAccount.name + mFile.getRemotePath(), e);
+            Toast.makeText(this, String.format(getString(R.string.media_err_security_ex), mFile.getFileName()), Toast.LENGTH_LONG).show();
+            processStopRequest(true);
+            
+        } catch (IOException e) {
+            Log.e(TAG, "IOException playing " + mAccount.name + mFile.getRemotePath(), e);
+            Toast.makeText(this, String.format(getString(R.string.media_err_io_ex), mFile.getFileName()), Toast.LENGTH_LONG).show();
+            processStopRequest(true);
+            
+        } catch (IllegalStateException e) {
+            Log.e(TAG, "IllegalStateException " + mAccount.name + mFile.getRemotePath(), e);
+            Toast.makeText(this, String.format(getString(R.string.media_err_unexpected), mFile.getFileName()), Toast.LENGTH_LONG).show();
+            processStopRequest(true);
+            
+        } catch (IllegalArgumentException e) {
+            Log.e(TAG, "IllegalArgumentException " + mAccount.name + mFile.getRemotePath(), e);
+            Toast.makeText(this, String.format(getString(R.string.media_err_unexpected), mFile.getFileName()), Toast.LENGTH_LONG).show();
+            processStopRequest(true);
+        }
+    }
+
+    
+    /** Called when media player is done playing current song. */
+    public void onCompletion(MediaPlayer player) {
+        Toast.makeText(this, String.format(getString(R.string.media_event_done, mFile.getFileName())), Toast.LENGTH_LONG).show();
+        if (mMediaController != null) {
+            // somebody is still bound to the service
+            player.seekTo(0);
+            processPauseRequest();
+            mMediaController.updatePausePlay();
+        } else {
+            // nobody is bound
+            processStopRequest(true);
+        }
+        return;
+    }
+    
+
+    /** 
+     * Called when media player is done preparing. 
+     *
+     * Time to start.
+     */
+    public void onPrepared(MediaPlayer player) {
+        mState = State.PLAYING;
+        updateNotification(String.format(getString(R.string.media_state_playing), mFile.getFileName()));
+        if (mMediaController != null) {
+            mMediaController.setEnabled(true);
+        }
+        player.seekTo(mStartPosition);
+        configAndStartMediaPlayer();
+        if (!mPlayOnPrepared) {
+            processPauseRequest();
+        }
+        
+        if (mMediaController != null) {
+            mMediaController.updatePausePlay();
+        }
+    }
+    
+
+    /** 
+     * Updates the status notification
+     */
+    @SuppressWarnings("deprecation")
+    private void updateNotification(String content) {
+        // TODO check if updating the Intent is really necessary
+        Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
+        showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, mFile);
+        showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, mAccount);
+        showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+        mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 
+                                                                (int)System.currentTimeMillis(), 
+                                                                showDetailsIntent, 
+                                                                PendingIntent.FLAG_UPDATE_CURRENT);
+        mNotification.when = System.currentTimeMillis();
+        //mNotification.contentView.setTextViewText(R.id.status_text, content);
+        String ticker = String.format(getString(R.string.media_notif_ticker), getString(R.string.app_name));
+        mNotification.setLatestEventInfo(getApplicationContext(), ticker, content, mNotification.contentIntent);
+        mNotificationManager.notify(R.string.media_notif_ticker, mNotification);
+    }
+
+    
+    /**
+     * Configures the service as a foreground service.
+     * 
+     * The system will avoid finishing the service as much as possible when resources as low.
+     * 
+     * A notification must be created to keep the user aware of the existance of the service.
+     */
+    @SuppressWarnings("deprecation")
+    private void setUpAsForeground(String content) {
+        /// creates status notification
+        // TODO put a progress bar to follow the playback progress
+        mNotification = new Notification();
+        mNotification.icon = android.R.drawable.ic_media_play;
+        //mNotification.tickerText = text;
+        mNotification.when = System.currentTimeMillis();
+        mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
+        //mNotification.contentView.setTextViewText(R.id.status_text, "ownCloud Music Player");     // NULL POINTER
+        //mNotification.contentView.setTextViewText(R.id.status_text, getString(R.string.downloader_download_in_progress_content));
+
+        
+        /// includes a pending intent in the notification showing the details view of the file
+        Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
+        showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, mFile);
+        showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, mAccount);
+        showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+        mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 
+                                                                (int)System.currentTimeMillis(), 
+                                                                showDetailsIntent, 
+                                                                PendingIntent.FLAG_UPDATE_CURRENT);
+        
+        
+        //mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
+        String ticker = String.format(getString(R.string.media_notif_ticker), getString(R.string.app_name));
+        mNotification.setLatestEventInfo(getApplicationContext(), ticker, content, mNotification.contentIntent);
+        startForeground(R.string.media_notif_ticker, mNotification);
+        
+    }
+
+    /**
+     * Called when there's an error playing media. 
+     * 
+     * Warns the user about the error and resets the media player.
+     */
+    public boolean onError(MediaPlayer mp, int what, int extra) {
+        Log.e(TAG, "Error in audio playback, what = " + what + ", extra = " + extra);
+        
+        String message = getMessageForMediaError(this, what, extra);
+        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
+        
+        processStopRequest(true);
+        return true; 
+    }
+
+    /**
+     * Called by the system when another app tries to play some sound.
+     * 
+     * {@inheritDoc}
+     */
+    @Override
+    public void onAudioFocusChange(int focusChange) {
+        if (focusChange > 0) {
+            // focus gain; check AudioManager.AUDIOFOCUS_* values
+            mAudioFocus = AudioFocus.FOCUS;
+            // restart media player with new focus settings
+            if (mState == State.PLAYING)
+                configAndStartMediaPlayer();
+            
+        } else if (focusChange < 0) {
+            // focus loss; check AudioManager.AUDIOFOCUS_* values
+            boolean canDuck = AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK == focusChange;
+                mAudioFocus = canDuck ? AudioFocus.NO_FOCUS_CAN_DUCK : AudioFocus.NO_FOCUS;
+                // start/restart/pause media player with new focus settings
+                if (mPlayer != null && mPlayer.isPlaying())
+                    configAndStartMediaPlayer();
+        }
+        
+    }
+
+    /**
+     * Called when the service is finished for final clean-up.
+     * 
+     * {@inheritDoc}
+     */
+    @Override
+    public void onDestroy() {
+        mState = State.STOPPED;
+        releaseResources(true);
+        giveUpAudioFocus();
+    }
+    
+
+    /**
+     * Provides a binder object that clients can use to perform operations on the MediaPlayer managed by the MediaService. 
+     */
+    @Override
+    public IBinder onBind(Intent arg) {
+        return mBinder;
+    }
+    
+    
+    /**
+     * Called when ALL the bound clients were onbound.
+     * 
+     * The service is destroyed if playback stopped or paused
+     */
+    @Override
+    public boolean onUnbind(Intent intent) {
+        if (mState == State.PAUSED || mState == State.STOPPED)  {
+            processStopRequest(false);
+        }
+        return false;   // not accepting rebinding (default behaviour)
+    }
+
+
+    /**
+     * Accesses the current MediaPlayer instance in the service.
+     * 
+     * To be handled carefully. Visibility is protected to be accessed only 
+     * 
+     * @return Current MediaPlayer instance handled by MediaService.
+     */
+    protected MediaPlayer getPlayer() {
+        return mPlayer;
+    }
+
+
+    /**
+     * Accesses the current OCFile loaded in the service.
+     * 
+     * @return  The current OCFile loaded in the service.
+     */
+    protected OCFile getCurrentFile() {
+        return mFile;
+    }
+
+    
+    /**
+     * Accesses the current {@link State} of the MediaService.
+     * 
+     * @return  The current {@link State} of the MediaService.
+     */
+    protected State getState() {
+        return mState;
+    }
+
+
+    protected void setMediaContoller(MediaControlView mediaController) {
+        mMediaController = mediaController;
+    }
+
+    protected MediaControlView getMediaController() {
+        return mMediaController;
+    }
+
+}

+ 182 - 0
src/com/owncloud/android/media/MediaServiceBinder.java

@@ -0,0 +1,182 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2013 ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 3 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.media;
+
+
+import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.media.MediaService.State;
+
+import android.accounts.Account;
+import android.content.Intent;
+import android.media.MediaPlayer;
+import android.os.Binder;
+import android.util.Log;
+import android.widget.MediaController;
+
+
+/**
+ *  Binder allowing client components to perform operations on on the MediaPlayer managed by a MediaService instance.
+ * 
+ *  Provides the operations of {@link MediaController.MediaPlayerControl}, and an extra method to check if
+ *  an {@link OCFile} instance is handled by the MediaService.
+ *  
+ *  @author David A. Velasco
+ */
+public class MediaServiceBinder extends Binder implements MediaController.MediaPlayerControl {
+
+    private static final String TAG = MediaServiceBinder.class.getSimpleName();
+    /**
+     * {@link MediaService} instance to access with the binder
+     */
+    private MediaService mService = null;
+    
+    /**
+     * Public constructor
+     * 
+     * @param service       A {@link MediaService} instance to access with the binder 
+     */
+    public MediaServiceBinder(MediaService service) {
+        if (service == null) {
+            throw new IllegalArgumentException("Argument 'service' can not be null");
+        }
+        mService = service;
+    }
+    
+    
+    public boolean isPlaying(OCFile mFile) {
+        return (mFile != null && mFile.equals(mService.getCurrentFile())); 
+    }
+
+    
+    @Override
+    public boolean canPause() {
+        return true;
+    }
+
+    @Override
+    public boolean canSeekBackward() {
+        return true;
+    }
+
+    @Override
+    public boolean canSeekForward() {
+        return true;
+    }
+
+    @Override
+    public int getBufferPercentage() {
+        MediaPlayer currentPlayer = mService.getPlayer();
+        if (currentPlayer != null) {
+            return 100;
+            // TODO update for streamed playback; add OnBufferUpdateListener in MediaService
+        } else {
+            return 0;
+        }
+    }
+
+    @Override
+    public int getCurrentPosition() {
+        MediaPlayer currentPlayer = mService.getPlayer();
+        if (currentPlayer != null) {
+            int pos = currentPlayer.getCurrentPosition();
+            return pos;
+        } else {
+            return 0;
+        }
+    }
+
+    @Override
+    public int getDuration() {
+        MediaPlayer currentPlayer = mService.getPlayer();
+        if (currentPlayer != null) {
+            int dur = currentPlayer.getDuration();
+            return dur;
+        } else {
+            return 0;
+        }
+    }
+
+    
+    /**
+     * Reports if the MediaService is playing a file or not.
+     * 
+     * Considers that the file is being played when it is in preparation because the expected
+     * client of this method is a {@link MediaController} , and we do not want that the 'play'
+     * button is shown when the file is being prepared by the MediaService.
+     */
+    @Override
+    public boolean isPlaying() {
+        MediaService.State currentState = mService.getState();
+        return (currentState == State.PLAYING || (currentState == State.PREPARING && mService.mPlayOnPrepared));
+    }
+
+    
+    @Override
+    public void pause() {
+        Log.d(TAG, "Pausing through binder...");
+        mService.processPauseRequest();
+    }
+
+    @Override
+    public void seekTo(int pos) {
+        Log.d(TAG, "Seeking " + pos + " through binder...");
+        MediaPlayer currentPlayer = mService.getPlayer();
+        MediaService.State currentState = mService.getState();
+        if (currentPlayer != null && currentState != State.PREPARING && currentState != State.STOPPED) {
+            currentPlayer.seekTo(pos);
+        }
+    }
+
+    @Override
+    public void start() {
+        Log.d(TAG, "Starting through binder...");
+        mService.processPlayRequest();  // this will finish the service if there is no file preloaded to play
+    }
+    
+    public void start(Account account, OCFile file, boolean playImmediately, int position) {
+        Log.d(TAG, "Loading and starting through binder...");
+        Intent i = new Intent(mService, MediaService.class);
+        i.putExtra(MediaService.EXTRA_ACCOUNT, account);
+        i.putExtra(MediaService.EXTRA_FILE, file);
+        i.putExtra(MediaService.EXTRA_PLAY_ON_LOAD, playImmediately);
+        i.putExtra(MediaService.EXTRA_START_POSITION, position);
+        i.setAction(MediaService.ACTION_PLAY_FILE);
+        mService.startService(i);
+    }
+
+
+    public void registerMediaController(MediaControlView mediaController) {
+        mService.setMediaContoller(mediaController);
+    }
+    
+    public void unregisterMediaController(MediaControlView mediaController) {
+        if (mediaController != null && mediaController == mService.getMediaController()) {
+            mService.setMediaContoller(null);
+        }
+        
+    }
+
+    public boolean isInPlaybackState() {
+        MediaService.State currentState = mService.getState();
+        return (currentState == MediaService.State.PLAYING || currentState == MediaService.State.PAUSED);
+    }
+
+}
+
+

+ 33 - 0
src/com/owncloud/android/network/ProgressiveDataTransferer.java

@@ -0,0 +1,33 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013 ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 3 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.network;
+
+import java.util.Collection;
+
+import eu.alefzero.webdav.OnDatatransferProgressListener;
+
+public interface ProgressiveDataTransferer {
+
+    public void addDatatransferProgressListener (OnDatatransferProgressListener listener);
+    
+    public void addDatatransferProgressListeners(Collection<OnDatatransferProgressListener> listeners);
+
+    public void removeDatatransferProgressListener(OnDatatransferProgressListener listener);
+
+}

+ 5 - 4
src/com/owncloud/android/operations/ChunkedUploadFileOperation.java

@@ -29,6 +29,7 @@ import org.apache.commons.httpclient.HttpException;
 import org.apache.commons.httpclient.methods.PutMethod;
 
 import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.network.ProgressiveDataTransferer;
 
 import android.accounts.Account;
 import android.util.Log;
@@ -62,16 +63,16 @@ public class ChunkedUploadFileOperation extends UploadFileOperation {
             File file = new File(getStoragePath());
             raf = new RandomAccessFile(file, "r");
             channel = raf.getChannel();
-            ChunkFromFileChannelRequestEntity entity = new ChunkFromFileChannelRequestEntity(channel, getMimeType(), CHUNK_SIZE, file);
-            entity.addOnDatatransferProgressListeners(getDataTransferListeners());
+            mEntity = new ChunkFromFileChannelRequestEntity(channel, getMimeType(), CHUNK_SIZE, file);
+            ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(getDataTransferListeners());
             long offset = 0;
             String uriPrefix = client.getBaseUri() + WebdavUtils.encodePath(getRemotePath()) + "-chunking-" + Math.abs((new Random()).nextInt(9000)+1000) + "-" ;
             long chunkCount = (long) Math.ceil((double)file.length() / CHUNK_SIZE);
             for (int chunkIndex = 0; chunkIndex < chunkCount ; chunkIndex++, offset += CHUNK_SIZE) {
                 mPutMethod = new PutMethod(uriPrefix + chunkCount + "-" + chunkIndex);
                 mPutMethod.addRequestHeader(OC_CHUNKED_HEADER, OC_CHUNKED_HEADER);
-                entity.setOffset(offset);
-                mPutMethod.setRequestEntity(entity);
+                ((ChunkFromFileChannelRequestEntity)mEntity).setOffset(offset);
+                mPutMethod.setRequestEntity(mEntity);
                 status = client.executeMethod(mPutMethod);
                 client.exhaustResponse(mPutMethod.getResponseBodyAsStream());
                 Log.d(TAG, "Upload of " + getStoragePath() + " to " + getRemotePath() + ", chunk index " + chunkIndex + ", count " + chunkCount + ", HTTP result status " + status);

+ 15 - 4
src/com/owncloud/android/operations/DownloadFileOperation.java

@@ -123,9 +123,17 @@ public class DownloadFileOperation extends RemoteOperation {
     
     
     public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
-        mDataTransferListeners.add(listener);
+        synchronized (mDataTransferListeners) {
+            mDataTransferListeners.add(listener);
+        }
     }
     
+    public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
+        synchronized (mDataTransferListeners) {
+            mDataTransferListeners.remove(listener);
+        }
+    }
+
     @Override
     protected RemoteOperationResult run(WebdavClient client) {
         RemoteOperationResult result = null;
@@ -190,9 +198,11 @@ public class DownloadFileOperation extends RemoteOperation {
                     }
                     fos.write(bytes, 0, readResult);
                     transferred += readResult;
-                    it = mDataTransferListeners.iterator();
-                    while (it.hasNext()) {
-                        it.next().onTransferProgress(readResult, transferred, mFile.getFileLength(), targetFile.getName());
+                    synchronized (mDataTransferListeners) {
+                        it = mDataTransferListeners.iterator();
+                        while (it.hasNext()) {
+                            it.next().onTransferProgress(readResult, transferred, mFile.getFileLength(), targetFile.getName());
+                        }
                     }
                 }
                 savedFile = true;
@@ -221,4 +231,5 @@ public class DownloadFileOperation extends RemoteOperation {
         mCancellationRequested.set(true);   // atomic set; there is no need of synchronizing it
     }
 
+
 }

+ 34 - 8
src/com/owncloud/android/operations/UploadFileOperation.java

@@ -30,6 +30,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
 
 import org.apache.commons.httpclient.HttpException;
 import org.apache.commons.httpclient.methods.PutMethod;
+import org.apache.commons.httpclient.methods.RequestEntity;
 import org.apache.http.HttpStatus;
 
 import android.accounts.Account;
@@ -37,6 +38,9 @@ import android.util.Log;
 
 import com.owncloud.android.datamodel.OCFile;
 import com.owncloud.android.files.services.FileUploader;
+import com.owncloud.android.network.ProgressiveDataTransferer;
+import com.owncloud.android.operations.RemoteOperation;
+import com.owncloud.android.operations.RemoteOperationResult;
 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
 import com.owncloud.android.utils.FileStorageUtils;
 
@@ -69,8 +73,14 @@ public class UploadFileOperation extends RemoteOperation {
     private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
     private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
 
-    public UploadFileOperation(Account account, OCFile file, boolean isInstant, boolean forceOverwrite,
-            int localBehaviour) {
+    protected RequestEntity mEntity = null;
+
+    
+    public UploadFileOperation( Account account,
+                                OCFile file,
+                                boolean isInstant, 
+                                boolean forceOverwrite,
+                                int localBehaviour) {
         if (account == null)
             throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
         if (file == null)
@@ -147,9 +157,23 @@ public class UploadFileOperation extends RemoteOperation {
     public Set<OnDatatransferProgressListener> getDataTransferListeners() {
         return mDataTransferListeners;
     }
-
-    public void addDatatransferProgressListener(OnDatatransferProgressListener listener) {
-        mDataTransferListeners.add(listener);
+    
+    public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
+        synchronized (mDataTransferListeners) {
+            mDataTransferListeners.add(listener);
+        }
+        if (mEntity != null) {
+            ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListener(listener);
+        }
+    }
+    
+    public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
+        synchronized (mDataTransferListeners) {
+            mDataTransferListeners.remove(listener);
+        }
+        if (mEntity != null) {
+            ((ProgressiveDataTransferer)mEntity).removeDatatransferProgressListener(listener);
+        }
     }
 
     @Override
@@ -348,9 +372,11 @@ public class UploadFileOperation extends RemoteOperation {
         int status = -1;
         try {
             File f = new File(mFile.getStoragePath());
-            FileRequestEntity entity = new FileRequestEntity(f, getMimeType());
-            entity.addOnDatatransferProgressListeners(mDataTransferListeners);
-            mPutMethod.setRequestEntity(entity);
+            mEntity  = new FileRequestEntity(f, getMimeType());
+            synchronized (mDataTransferListeners) {
+                ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(mDataTransferListeners);
+            }
+            mPutMethod.setRequestEntity(mEntity);
             status = client.executeMethod(mPutMethod);
             client.exhaustResponse(mPutMethod.getResponseBodyAsStream());
 

+ 199 - 34
src/com/owncloud/android/ui/activity/FileDetailActivity.java

@@ -21,26 +21,33 @@ package com.owncloud.android.ui.activity;
 import android.accounts.Account;
 import android.app.Dialog;
 import android.app.ProgressDialog;
+import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.content.ServiceConnection;
 import android.content.res.Configuration;
 import android.os.Bundle;
 import android.os.IBinder;
+import android.support.v4.app.Fragment;
 import android.support.v4.app.FragmentTransaction;
 import android.util.Log;
 
 import com.actionbarsherlock.app.ActionBar;
 import com.actionbarsherlock.app.SherlockFragmentActivity;
 import com.actionbarsherlock.view.MenuItem;
+import com.owncloud.android.datamodel.FileDataStorageManager;
 import com.owncloud.android.datamodel.OCFile;
 import com.owncloud.android.files.services.FileDownloader;
 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
 import com.owncloud.android.files.services.FileUploader;
 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
 import com.owncloud.android.ui.fragment.FileDetailFragment;
+import com.owncloud.android.ui.fragment.FileFragment;
+import com.owncloud.android.ui.preview.PreviewMediaFragment;
 
+import com.owncloud.android.AccountUtils;
 import com.owncloud.android.R;
 
 /**
@@ -48,24 +55,41 @@ import com.owncloud.android.R;
  * on.
  * 
  * @author Bartek Przybylski
- * 
+ * @author David A. Velasco
  */
-public class FileDetailActivity extends SherlockFragmentActivity implements FileDetailFragment.ContainerActivity {
+public class FileDetailActivity extends SherlockFragmentActivity implements FileFragment.ContainerActivity {
     
     public static final int DIALOG_SHORT_WAIT = 0;
 
     public static final String TAG = FileDetailActivity.class.getSimpleName();
     
+    public static final String EXTRA_MODE = "MODE";
+    public static final int MODE_DETAILS = 0;
+    public static final int MODE_PREVIEW = 1;
+
+    public static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
+    
     private boolean mConfigurationChangedToLandscape = false;
     private FileDownloaderBinder mDownloaderBinder = null;
     private ServiceConnection mDownloadConnection, mUploadConnection = null;
     private FileUploaderBinder mUploaderBinder = null;
+    private boolean mWaitingToPreview;
+    
+    private OCFile mFile;
+    private Account mAccount;
 
+    private FileDataStorageManager mStorageManager;
+    private DownloadFinishReceiver mDownloadFinishReceiver;
+    
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
+        mFile = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
+        mAccount = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_ACCOUNT);
+        mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
+        
         // check if configuration changed to large-land ; for a tablet being changed from portrait to landscape when in FileDetailActivity 
         Configuration conf = getResources().getConfiguration();
         mConfigurationChangedToLandscape = (conf.orientation == Configuration.ORIENTATION_LANDSCAPE && 
@@ -73,30 +97,90 @@ public class FileDetailActivity extends SherlockFragmentActivity implements File
                                            );
 
         if (!mConfigurationChangedToLandscape) {
-            mDownloadConnection = new DetailsServiceConnection();
-            bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
-            mUploadConnection = new DetailsServiceConnection();
-            bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
-            
             setContentView(R.layout.file_activity_details);
         
             ActionBar actionBar = getSupportActionBar();
             actionBar.setDisplayHomeAsUpEnabled(true);
 
-            OCFile file = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
-            Account account = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_ACCOUNT);
-            FileDetailFragment mFileDetail = new FileDetailFragment(file, account);
-        
-            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
-            ft.replace(R.id.fragment, mFileDetail, FileDetailFragment.FTAG);
-            ft.commit();
+            if (savedInstanceState == null) {
+                mWaitingToPreview = false;
+                createChildFragment();
+            } else {
+                mWaitingToPreview = savedInstanceState.getBoolean(KEY_WAITING_TO_PREVIEW);
+            }
+            
+            mDownloadConnection = new DetailsServiceConnection();
+            bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
+            mUploadConnection = new DetailsServiceConnection();
+            bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
+            
             
         }  else {
-            backToDisplayActivity();   // the 'back' won't be effective until this.onStart() and this.onResume() are completed;
+            backToDisplayActivity(false);   // the 'back' won't be effective until this.onStart() and this.onResume() are completed;
         }
         
         
     }
+
+    /**
+     * Creates the proper fragment depending upon the state of the handled {@link OCFile} and
+     * the requested {@link Intent}.
+     */
+    private void createChildFragment() {
+        int mode = getIntent().getIntExtra(EXTRA_MODE, MODE_PREVIEW); 
+        
+        Fragment newFragment = null;
+        if (PreviewMediaFragment.canBePreviewed(mFile) && mode == MODE_PREVIEW) {
+            if (mFile.isDown()) {
+                newFragment = new PreviewMediaFragment(mFile, mAccount);
+            
+            } else {
+                newFragment = new FileDetailFragment(mFile, mAccount);
+                mWaitingToPreview = true;
+            }
+            
+        } else {
+            newFragment = new FileDetailFragment(mFile, mAccount);
+        }
+        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
+        ft.replace(R.id.fragment, newFragment, FileDetailFragment.FTAG);
+        ft.commit();
+    }
+    
+
+    @Override
+    protected void onSaveInstanceState(Bundle outState) {
+        super.onSaveInstanceState(outState);
+        outState.putBoolean(KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
+    }
+    
+    
+    @Override
+    public void onPause() {
+        super.onPause();
+        if (mDownloadFinishReceiver != null) {
+            unregisterReceiver(mDownloadFinishReceiver);
+            mDownloadFinishReceiver = null;
+        }
+    }
+    
+    
+    @Override
+    public void onResume() {
+        super.onResume();
+        if (!mConfigurationChangedToLandscape) {
+            // TODO this is probably unnecessary
+            Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
+            if (fragment != null && fragment instanceof FileDetailFragment) {
+                ((FileDetailFragment) fragment).updateFileDetails(false, false);
+            }
+        }
+        // Listen for download messages
+        IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_ADDED_MESSAGE);
+        downloadIntentFilter.addAction(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
+        mDownloadFinishReceiver = new DownloadFinishReceiver();
+        registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
+    }
     
     
     /** Defines callbacks for service binding, passed to bindService() */
@@ -104,18 +188,27 @@ public class FileDetailActivity extends SherlockFragmentActivity implements File
 
         @Override
         public void onServiceConnected(ComponentName component, IBinder service) {
+                
             if (component.equals(new ComponentName(FileDetailActivity.this, FileDownloader.class))) {
                 Log.d(TAG, "Download service connected");
                 mDownloaderBinder = (FileDownloaderBinder) service;
+                if (mWaitingToPreview) {
+                    requestForDownload();
+                }
+                    
             } else if (component.equals(new ComponentName(FileDetailActivity.this, FileUploader.class))) {
                 Log.d(TAG, "Upload service connected");
                 mUploaderBinder = (FileUploaderBinder) service;
             } else {
                 return;
             }
-            FileDetailFragment fragment = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
-            if (fragment != null)
-                fragment.updateFileDetails(false);   // let the fragment gets the mDownloadBinder through getDownloadBinder() (see FileDetailFragment#updateFileDetais())
+            
+            Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
+            FileDetailFragment detailsFragment = (fragment instanceof FileDetailFragment) ? (FileDetailFragment) fragment : null;
+            if (detailsFragment != null) {
+                detailsFragment.listenForTransferProgress();
+                detailsFragment.updateFileDetails(mWaitingToPreview, false);   // let the fragment gets the mDownloadBinder through getDownloadBinder() (see FileDetailFragment#updateFileDetais())
+            }
         }
 
         @Override
@@ -130,7 +223,7 @@ public class FileDetailActivity extends SherlockFragmentActivity implements File
         }
     };    
     
-
+    
     @Override
     public void onDestroy() {
         super.onDestroy();
@@ -151,7 +244,7 @@ public class FileDetailActivity extends SherlockFragmentActivity implements File
         
         switch(item.getItemId()){
         case android.R.id.home:
-            backToDisplayActivity();
+            backToDisplayActivity(true);
             returnValue = true;
             break;
         default:
@@ -163,22 +256,15 @@ public class FileDetailActivity extends SherlockFragmentActivity implements File
 
 
 
-    @Override
-    protected void onResume() {
-        
-        super.onResume();
-        if (!mConfigurationChangedToLandscape) { 
-            FileDetailFragment fragment = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
-            fragment.updateFileDetails(false);
-        }
-    }
-    
-
-    private void backToDisplayActivity() {
+    private void backToDisplayActivity(boolean moveToParent) {
         Intent intent = new Intent(this, FileDisplayActivity.class);
         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
-        intent.putExtra(FileDetailFragment.EXTRA_FILE, getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE));
-        intent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, getIntent().getParcelableExtra(FileDetailFragment.EXTRA_ACCOUNT));
+        OCFile targetFile = null;
+        if (mFile != null) {
+            targetFile = moveToParent ? mStorageManager.getFileById(mFile.getParentId()) : mFile;
+        }
+        intent.putExtra(FileDetailFragment.EXTRA_FILE, targetFile);
+        intent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, mAccount);
         startActivity(intent);
         finish();
     }
@@ -226,5 +312,84 @@ public class FileDetailActivity extends SherlockFragmentActivity implements File
     public FileUploaderBinder getFileUploaderBinder() {
         return mUploaderBinder;
     }
+
+
+    @Override
+    public void showFragmentWithDetails(OCFile file) {
+        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
+        transaction.replace(R.id.fragment, new FileDetailFragment(file, mAccount), FileDetailFragment.FTAG); 
+        transaction.commit();
+    }
+
+    
+    private void requestForDownload() {
+        if (!mDownloaderBinder.isDownloading(mAccount, mFile)) {
+            Intent i = new Intent(this, FileDownloader.class);
+            i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
+            i.putExtra(FileDownloader.EXTRA_FILE, mFile);
+            startService(i);
+        }
+    }
+
     
+    /**
+     * Class waiting for broadcast events from the {@link FielDownloader} service.
+     * 
+     * Updates the UI when a download is started or finished, provided that it is relevant for the
+     * current file.
+     */
+    private class DownloadFinishReceiver extends BroadcastReceiver {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            boolean sameAccount = isSameAccount(context, intent);
+            String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
+            boolean samePath = (mFile != null && mFile.getRemotePath().equals(downloadedRemotePath));
+            
+            if (sameAccount && samePath) {
+                updateChildFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
+            }
+            
+            removeStickyBroadcast(intent);
+        }
+
+        private boolean isSameAccount(Context context, Intent intent) {
+            String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
+            return (accountName != null && accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name));
+        }
+    }
+
+
+    public void updateChildFragment(String downloadEvent, String downloadedRemotePath, boolean success) {
+        Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
+        if (fragment != null && fragment instanceof FileDetailFragment) {
+            FileDetailFragment detailsFragment = (FileDetailFragment) fragment;
+            OCFile fileInFragment = detailsFragment.getFile();
+            if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
+                // this never should happen; fileInFragment should be always equals to mFile, that was compared to downloadedRemotePath in DownloadReceiver 
+                mWaitingToPreview = false;
+                
+            } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_ADDED_MESSAGE)) {
+                // grants that the progress bar is updated
+                detailsFragment.listenForTransferProgress();
+                detailsFragment.updateFileDetails(true, false);
+                
+            } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
+                //  refresh the details fragment 
+                if (success && mWaitingToPreview) {
+                    mFile = mStorageManager.getFileById(mFile.getFileId());   // update the file from database, for the local storage path
+                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
+                    transaction.replace(R.id.fragment, new PreviewMediaFragment(mFile, mAccount), FileDetailFragment.FTAG);
+                    transaction.commit();
+                    mWaitingToPreview = false;
+                    
+                } else {
+                    detailsFragment.updateFileDetails(false, (success));
+                    // TODO error message if !success ¿?
+                }
+            }
+        } // TODO else if (fragment != null && fragment )
+        
+        
+    }
+
 }

+ 254 - 66
src/com/owncloud/android/ui/activity/FileDisplayActivity.java

@@ -4,7 +4,7 @@
  *
  *   This program is free software: you can redistribute it and/or modify
  *   it under the terms of the GNU General Public License as published by
- *   the Free Software Foundation, either version 2 of the License, or
+ *   the Free Software Foundation, either version 3 of the License, or
  *   (at your option) any later version.
  *
  *   This program is distributed in the hope that it will be useful,
@@ -49,6 +49,7 @@ import android.os.Handler;
 import android.os.IBinder;
 import android.preference.PreferenceManager;
 import android.provider.MediaStore;
+import android.support.v4.app.Fragment;
 import android.support.v4.app.FragmentTransaction;
 import android.util.Log;
 import android.view.View;
@@ -90,7 +91,11 @@ import com.owncloud.android.ui.dialog.SslValidatorDialog;
 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
 import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
 import com.owncloud.android.ui.fragment.FileDetailFragment;
+import com.owncloud.android.ui.fragment.FileFragment;
 import com.owncloud.android.ui.fragment.OCFileListFragment;
+import com.owncloud.android.ui.preview.PreviewImageActivity;
+import com.owncloud.android.ui.preview.PreviewImageFragment;
+import com.owncloud.android.ui.preview.PreviewMediaFragment;
 
 import com.owncloud.android.R;
 import eu.alefzero.webdav.WebdavClient;
@@ -99,7 +104,7 @@ import eu.alefzero.webdav.WebdavClient;
  * Displays, what files the user has available in his ownCloud.
  * 
  * @author Bartek Przybylski
- * 
+ * @author David A. Velasco
  */
 
 public class FileDisplayActivity extends SherlockFragmentActivity implements
@@ -138,7 +143,11 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
     
     private static final String TAG = "FileDisplayActivity";
 
-    private static int[] mMenuIdentifiersToPatch = {R.id.about_app};
+    private static int[] mMenuIdentifiersToPatch = {R.id.action_about_app};
+    
+    private OCFile mWaitingToPreview;
+    private Handler mHandler;
+
     
     @Override
     public void onCreate(Bundle savedInstanceState) {
@@ -155,6 +164,10 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
         if(savedInstanceState != null) {
             // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
             mCurrentDir = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
+            mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDetailActivity.KEY_WAITING_TO_PREVIEW);
+
+        } else {
+            mWaitingToPreview = null;
         }
         
         if (!AccountUtils.accountsAreSetup(this)) {
@@ -201,7 +214,20 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
         mFileList = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
         mDualPane = (findViewById(R.id.file_details_container) != null);
         if (mDualPane) {
-            initFileDetailsInDualPane();
+            if (savedInstanceState == null) initFileDetailsInDualPane();
+        } else {
+            // quick patchES to fix problem in turn from landscape to portrait, when a file is selected in the right pane
+            // TODO serious refactorization in activities and fragments providing file browsing and handling 
+            if (mCurrentFile != null) {
+                onFileClick(mCurrentFile);
+                mCurrentFile = null;
+            }
+            Fragment rightPanel = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
+            if (rightPanel != null) {
+                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
+                transaction.remove(rightPanel);
+                transaction.commit();
+            }
         }
             
         // Action bar setup
@@ -257,7 +283,7 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
         startActivity(intent);  // the new activity won't be created until this.onStart() and this.onResume() are finished;
     }
 
-
+    
     /**
      *  Load of state dependent of the existence of an ownCloud account
      */
@@ -294,8 +320,18 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
         if (mDualPane && getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG) == null) {
             FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
             if (mCurrentFile != null) {
-                transaction.replace(R.id.file_details_container, new FileDetailFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG); // empty FileDetailFragment
+                if (PreviewMediaFragment.canBePreviewed(mCurrentFile)) {
+                    if (mCurrentFile.isDown()) {
+                        transaction.replace(R.id.file_details_container, new PreviewMediaFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
+                    } else {
+                        transaction.replace(R.id.file_details_container, new FileDetailFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
+                        mWaitingToPreview = mCurrentFile;
+                    }
+                } else {
+                    transaction.replace(R.id.file_details_container, new FileDetailFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
+                }
                 mCurrentFile = null;
+                
             } else {
                 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
             }
@@ -317,7 +353,7 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         MenuInflater inflater = getSherlock().getMenuInflater();
-            inflater.inflate(R.menu.menu, menu);
+            inflater.inflate(R.menu.main_menu, menu);
             
             patchHiddenAccents(menu);
             
@@ -348,12 +384,12 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
     public boolean onOptionsItemSelected(MenuItem item) {
         boolean retval = true;
         switch (item.getItemId()) {
-            case R.id.createDirectoryItem: {
-                //showDialog(DIALOG_CREATE_DIR);
+            case R.id.action_create_dir: {
                 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.uploader_info_dirname), "", this);
                 dialog.show(getSupportFragmentManager(), "createdirdialog");
+                break;
             }
-            case R.id.startSync: {
+            case R.id.action_sync_account: {
                 startSynchronization();
                 break;
             }
@@ -366,7 +402,7 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
                 startActivity(settingsIntent);
                 break;
             }
-            case R.id.about_app : {
+            case R.id.action_about_app: {
                 showDialog(DIALOG_ABOUT_APP);
                 break;
             }
@@ -510,11 +546,10 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
         
         if (mDualPane) {
             // Resets the FileDetailsFragment on Tablets so that it always displays
-            FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
-            if (fileDetails != null && !fileDetails.isEmpty()) {
+            Fragment fileFragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
+            if (fileFragment != null && (fileFragment instanceof PreviewMediaFragment || !((FileDetailFragment) fileFragment).isEmpty())) {
                 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
-                transaction.remove(fileDetails);
-                transaction.add(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG);
+                transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment                
                 transaction.commit();
             }
         }
@@ -532,19 +567,21 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
         super.onSaveInstanceState(outState);
         outState.putParcelable(FileDetailFragment.EXTRA_FILE, mCurrentDir);
         if (mDualPane) {
-            FileDetailFragment fragment = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
+            FileFragment fragment = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
             if (fragment != null) {
-                OCFile file = fragment.getDisplayedFile();
+                OCFile file = fragment.getFile();
                 if (file != null) {
                     outState.putParcelable(FileDetailFragment.EXTRA_FILE, file);
                 }
             }
         }
+        outState.putParcelable(FileDetailActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
         Log.d(getClass().toString(), "onSaveInstanceState() end");
     }
 
+    
     @Override
-    protected void onResume() {
+    public void onResume() {
         Log.d(getClass().toString(), "onResume() start");
         super.onResume();
 
@@ -570,7 +607,8 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
             registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
             
             // Listen for download messages
-            IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
+            IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_ADDED_MESSAGE);
+            downloadIntentFilter.addAction(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
             mDownloadFinishReceiver = new DownloadFinishReceiver();
             registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
         
@@ -588,7 +626,7 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
 
     
     @Override
-    protected void onPause() {
+    public void onPause() {
         Log.d(getClass().toString(), "onPause() start");
         super.onPause();
         if (mSyncBroadcastReceiver != null) {
@@ -719,28 +757,41 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
             break;
         }
         case DIALOG_CHOOSE_UPLOAD_SOURCE: {
-            final String [] items = {   getString(R.string.actionbar_upload_files), 
-                                        getString(R.string.actionbar_upload_from_apps) }; 
+            
+            String[] items = null;
+            
+            String[] allTheItems = { getString(R.string.actionbar_upload_files),
+                                     getString(R.string.actionbar_upload_from_apps),
+                                     getString(R.string.actionbar_failed_instant_upload) };
+            
+            String[] commonItems = { getString(R.string.actionbar_upload_files),
+                                     getString(R.string.actionbar_upload_from_apps) };
+            
+            if (InstantUploadActivity.IS_ENABLED)
+                items = allTheItems;
+            else 
+                items = commonItems;
+            
             builder = new AlertDialog.Builder(this);
             builder.setTitle(R.string.actionbar_upload);
             builder.setItems(items, new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int item) {
                     if (item == 0) {
-                        //if (!mDualPane) { 
-                            Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
-                            action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this));
-                            startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
-                        //} else {
-                            // TODO create and handle new fragment LocalFileListFragment
-                        //}
+                        // if (!mDualPane) {
+                        Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
+                        action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT,
+                                AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this));
+                        startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
+                        // } else {
+                        // TODO create and handle new fragment
+                        // LocalFileListFragment
+                        // }
                     } else if (item == 1) {
                         Intent action = new Intent(Intent.ACTION_GET_CONTENT);
-                        action = action.setType("*/*")
-                                .addCategory(Intent.CATEGORY_OPENABLE);
-                        startActivityForResult(
-                                Intent.createChooser(action, getString(R.string.upload_chooser_title)),
+                        action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
+                        startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
                                 ACTION_SELECT_CONTENT_FROM_APPS);
-                    } else if (item == 2) {
+                    } else if (item == 2 && InstantUploadActivity.IS_ENABLED) {
                         Account account = AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this);
                         Intent action = new Intent(FileDisplayActivity.this, InstantUploadActivity.class);
                         action.putExtra(FileUploader.KEY_ACCOUNT, account);
@@ -977,27 +1028,78 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
     
     
     /**
-     * Once the file download has finished -> update view
+     * Class waiting for broadcast events from the {@link FielDownloader} service.
+     * 
+     * Updates the UI when a download is started or finished, provided that it is relevant for the
+     * current folder.
      */
     private class DownloadFinishReceiver extends BroadcastReceiver {
         @Override
         public void onReceive(Context context, Intent intent) {
+            boolean sameAccount = isSameAccount(context, intent);
             String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
-            String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
-            boolean sameAccount = accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name);
-            boolean isDescendant = (mCurrentDir != null) && (downloadedRemotePath != null) && (downloadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
+            boolean isDescendant = isDescendant(downloadedRemotePath);
+            
             if (sameAccount && isDescendant) {
-                OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
-                if (fileListFragment != null) { 
-                    fileListFragment.listDirectory();
+                updateLeftPanel();
+                if (mDualPane) {
+                    updateRightPanel(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
                 }
             }
+            
+            removeStickyBroadcast(intent);
+        }
+
+        private boolean isDescendant(String downloadedRemotePath) {
+            return (mCurrentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
+        }
+
+        private boolean isSameAccount(Context context, Intent intent) {
+            String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
+            return (accountName != null && accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name));
         }
     }
     
     
-    
-    
+    protected void updateLeftPanel() {
+        OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
+        if (fileListFragment != null) { 
+            fileListFragment.listDirectory();
+        }
+    }
+
+    protected void updateRightPanel(String downloadEvent, String downloadedRemotePath, boolean success) {
+        Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
+        boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
+        if (fragment != null && fragment instanceof FileDetailFragment) {
+            FileDetailFragment detailsFragment = (FileDetailFragment) fragment;
+            OCFile fileInFragment = detailsFragment.getFile();
+            if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
+                // the user browsed to other file ; forget the automatic preview 
+                mWaitingToPreview = null;
+                
+            } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_ADDED_MESSAGE)) {
+                // grant that the right panel updates the progress bar
+                detailsFragment.listenForTransferProgress();
+                detailsFragment.updateFileDetails(true, false);
+                
+            } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
+                //  update the right panel 
+                if (success && waitedPreview) {
+                    mWaitingToPreview = mStorageManager.getFileById(mWaitingToPreview.getFileId());   // update the file from database, for the local storage path
+                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
+                    transaction.replace(R.id.file_details_container, new PreviewMediaFragment(mWaitingToPreview, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
+                    transaction.commit();
+                    mWaitingToPreview = null;
+                    
+                } else {
+                    detailsFragment.updateFileDetails(false, (success));
+                }
+            }
+        }
+    }
+
+
     /**
      * {@inheritDoc}
      */
@@ -1006,7 +1108,7 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
         return mStorageManager;
     }
     
-    
+
     /**
      * {@inheritDoc}
      */
@@ -1018,11 +1120,10 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
         
         if (mDualPane) {
             // Resets the FileDetailsFragment on Tablets so that it always displays
-            FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
-            if (fileDetails != null && !fileDetails.isEmpty()) {
+            Fragment fileFragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
+            if (fileFragment != null && (fileFragment instanceof PreviewMediaFragment || !((FileDetailFragment) fileFragment).isEmpty())) {
                 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
-                transaction.remove(fileDetails);
-                transaction.add(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG);
+                transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment                
                 transaction.commit();
             }
         }
@@ -1034,16 +1135,40 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
      */
     @Override
     public void onFileClick(OCFile file) {
-        
-        // If we are on a large device -> update fragment
+        if (file != null && PreviewImageFragment.canBePreviewed(file)) {
+            // preview image - it handles the download, if needed
+            startPreviewImage(file);
+            
+        } else if (file != null && PreviewMediaFragment.canBePreviewed(file)) {
+            if (file.isDown()) {
+                // general preview
+                startMediaPreview(file);
+                
+            } else {
+                // automatic download, preview on finish
+                startDownloadForPreview(file);
+                
+            }
+        } else {
+            // details view
+            startDetails(file);
+        }
+    }
+
+    private void startPreviewImage(OCFile file) {
+        Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
+        showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
+        showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
+        startActivity(showDetailsIntent);
+    }
+    
+    private void startMediaPreview(OCFile file) {
         if (mDualPane) {
-            // buttons in the details view are problematic when trying to reuse an existing fragment; create always a new one solves some of them, BUT no all; downloads are 'dangerous'
             FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
-            transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
-            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
+            transaction.replace(R.id.file_details_container, new PreviewMediaFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
             transaction.commit();
             
-        } else {    // small or medium screen device -> new Activity
+        } else {
             Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
             showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
             showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
@@ -1051,7 +1176,37 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
         }
     }
     
+    private void startDownloadForPreview(OCFile file) {
+        if (mDualPane) {
+            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
+            transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
+            transaction.commit();
+            mWaitingToPreview = file;
+            requestForDownload();
+            
+        } else {
+            Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
+            showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
+            showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
+            startActivity(showDetailsIntent);
+        }
+    }
+
     
+    private void startDetails(OCFile file) {
+        if (mDualPane && !file.isImage()) {
+            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
+            transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
+            transaction.commit();
+        } else {
+            Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
+            showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
+            showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
+            startActivity(showDetailsIntent);
+        }
+    }
+
+
     /**
      * {@inheritDoc}
      */
@@ -1099,6 +1254,10 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
             if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
                 Log.d(TAG, "Download service connected");
                 mDownloaderBinder = (FileDownloaderBinder) service;
+                if (mWaitingToPreview != null) {
+                    requestForDownload();
+                }
+                
             } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
                 Log.d(TAG, "Upload service connected");
                 mUploaderBinder = (FileUploaderBinder) service;
@@ -1109,9 +1268,12 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
             if (mFileList != null)
                 mFileList.listDirectory();
             if (mDualPane) {
-                FileDetailFragment fragment = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
-                if (fragment != null)
-                    fragment.updateFileDetails(false);
+                Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
+                if (fragment != null && fragment instanceof FileDetailFragment) {
+                    FileDetailFragment detailFragment = (FileDetailFragment)fragment;
+                    detailFragment.listenForTransferProgress();
+                    detailFragment.updateFileDetails(false, false);
+                }
             }
         }
 
@@ -1191,8 +1353,8 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
             msg.show();
             OCFile removedFile = operation.getFile();
             if (mDualPane) {
-                FileDetailFragment details = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
-                if (details != null && removedFile.equals(details.getDisplayedFile()) ) {
+                FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
+                if (details != null && removedFile.equals(details.getFile())) {
                     FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                     transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
                     transaction.commit();
@@ -1224,9 +1386,9 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
         OCFile renamedFile = operation.getFile();
         if (result.isSuccess()) {
             if (mDualPane) {
-                FileDetailFragment details = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
-                if (details != null && renamedFile.equals(details.getDisplayedFile()) ) {
-                    details.updateFileDetails(renamedFile, AccountUtils.getCurrentOwnCloudAccount(this));
+                FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
+                if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
+                    ((FileDetailFragment) details).updateFileDetails(renamedFile, AccountUtils.getCurrentOwnCloudAccount(this));
                 }
             }
             if (mStorageManager.getFileById(renamedFile.getParentId()).equals(mCurrentDir)) {
@@ -1288,12 +1450,12 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
             fileListFragment.listDirectory();
         }*/
         if (mDualPane) {
-            FileDetailFragment details = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
-            if (details != null && file.equals(details.getDisplayedFile()) ) {
+            FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
+            if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
                 if (downloading || uploading) {
-                    details.updateFileDetails(file, AccountUtils.getCurrentOwnCloudAccount(this));
+                    ((FileDetailFragment)details).updateFileDetails(file, AccountUtils.getCurrentOwnCloudAccount(this));
                 } else {
-                    details.updateFileDetails(downloading || uploading);
+                    ((FileDetailFragment)details).updateFileDetails(false, true);
                 }
             }
         }
@@ -1301,6 +1463,21 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
 
 
     @Override
+    public void showFragmentWithDetails(OCFile file) {
+        if (mDualPane) {
+            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
+            transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG); 
+            transaction.commit();
+            
+        } else {
+            Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
+            showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
+            showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
+            showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
+            startActivity(showDetailsIntent);
+        }
+    }
+
     public void onDismiss(EditNameDialog dialog) {
         //dialog.dismiss();
         if (dialog.getResult()) {
@@ -1328,4 +1505,15 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
         }
     }
 
+    private void requestForDownload() {
+        Account account = AccountUtils.getCurrentOwnCloudAccount(this);
+        if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
+            Intent i = new Intent(this, FileDownloader.class);
+            i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
+            i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
+            startService(i);
+        }
+    }
+
+    
 }

+ 1 - 0
src/com/owncloud/android/ui/activity/InstantUploadActivity.java

@@ -75,6 +75,7 @@ public class InstantUploadActivity extends Activity {
     private static final String LOG_TAG = InstantUploadActivity.class.getSimpleName();
     private LinearLayout listView;
     private static final String retry_chexbox_tag = "retry_chexbox_tag";
+    public static final boolean IS_ENABLED = false;
     private static int MAX_LOAD_IMAGES = 5;
     private int lastLoadImageIdx = 0;
 

+ 1 - 8
src/com/owncloud/android/ui/activity/UploadFilesActivity.java

@@ -347,8 +347,7 @@ public class UploadFilesActivity extends SherlockFragmentActivity implements
                 String[] args = {getString(R.string.app_name)};
                 ConfirmationDialogFragment dialog = ConfirmationDialogFragment.newInstance(R.string.upload_query_move_foreign_files, args, R.string.common_yes, -1, R.string.common_no);
                 dialog.setOnConfirmationListener(UploadFilesActivity.this);
-                mCurrentDialog = dialog;
-                mCurrentDialog.show(getSupportFragmentManager(), QUERY_TO_MOVE_DIALOG_TAG);
+                dialog.show(getSupportFragmentManager(), QUERY_TO_MOVE_DIALOG_TAG);
             }
         }
     }
@@ -363,16 +362,12 @@ public class UploadFilesActivity extends SherlockFragmentActivity implements
             setResult(RESULT_OK_AND_MOVE, data);
             finish();
         }
-        mCurrentDialog.dismiss();
-        mCurrentDialog = null;
     }
 
 
     @Override
     public void onNeutral(String callerTag) {
         Log.d(TAG, "Phantom neutral button in dialog was clicked; dialog tag is " + callerTag);
-        mCurrentDialog.dismiss();
-        mCurrentDialog = null;
     }
 
 
@@ -380,8 +375,6 @@ public class UploadFilesActivity extends SherlockFragmentActivity implements
     public void onCancel(String callerTag) {
         /// nothing to do; don't finish, let the user change the selection
         Log.d(TAG, "Negative button in dialog was clicked; dialog tag is " + callerTag);
-        mCurrentDialog.dismiss();
-        mCurrentDialog = null;
     }    
 
     

+ 1 - 1
src/com/owncloud/android/ui/dialog/IndeterminateProgressDialog.java

@@ -61,7 +61,7 @@ public class IndeterminateProgressDialog extends SherlockDialogFragment {
         dialog.setIndeterminate(true);
         
         /// set message
-        int messageId = getArguments().getInt(ARG_MESSAGE_ID, R.string.text_placeholder);
+        int messageId = getArguments().getInt(ARG_MESSAGE_ID, R.string.placeholder_sentence);
         dialog.setMessage(getString(messageId));
         
         /// set cancellation behavior

+ 5 - 0
src/com/owncloud/android/ui/fragment/ConfirmationDialogFragment.java

@@ -36,6 +36,8 @@ public class ConfirmationDialogFragment extends SherlockDialogFragment {
     public final static String ARG_NEUTRAL_BTN_RES = "neutral_btn_res";
     public final static String ARG_NEGATIVE_BTN_RES = "negative_btn_res";
     
+    public static final String FTAG_CONFIRMATION = "CONFIRMATION_FRAGMENT";
+
     private ConfirmationDialogFragmentListener mListener;
     
     /**
@@ -90,6 +92,7 @@ public class ConfirmationDialogFragment extends SherlockDialogFragment {
                     new DialogInterface.OnClickListener() {
                         public void onClick(DialogInterface dialog, int whichButton) {
                             mListener.onConfirmation(getTag()); 
+                            dialog.dismiss();
                         }
                     });
         if (neuBtn != -1)
@@ -97,6 +100,7 @@ public class ConfirmationDialogFragment extends SherlockDialogFragment {
                     new DialogInterface.OnClickListener() {
                         public void onClick(DialogInterface dialog, int whichButton) {
                             mListener.onNeutral(getTag()); 
+                            dialog.dismiss();
                         }
                     });
         if (negBtn != -1)
@@ -105,6 +109,7 @@ public class ConfirmationDialogFragment extends SherlockDialogFragment {
                         @Override
                         public void onClick(DialogInterface dialog, int which) {
                             mListener.onCancel(getTag());
+                            dialog.dismiss();
                         }
                     });
       return builder.create();

+ 203 - 228
src/com/owncloud/android/ui/fragment/FileDetailFragment.java

@@ -19,6 +19,7 @@
 package com.owncloud.android.ui.fragment;
 
 import java.io.File;
+import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -36,25 +37,17 @@ import org.json.JSONObject;
 
 import android.accounts.Account;
 import android.accounts.AccountManager;
-import android.annotation.SuppressLint;
 import android.app.Activity;
 import android.content.ActivityNotFoundException;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.BitmapFactory.Options;
-import android.graphics.Point;
 import android.net.Uri;
-import android.os.AsyncTask;
 import android.os.Bundle;
 import android.os.Handler;
-import android.support.v4.app.DialogFragment;
 import android.support.v4.app.FragmentTransaction;
 import android.util.Log;
-import android.view.Display;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.View.OnClickListener;
@@ -63,6 +56,7 @@ import android.webkit.MimeTypeMap;
 import android.widget.Button;
 import android.widget.CheckBox;
 import android.widget.ImageView;
+import android.widget.ProgressBar;
 import android.widget.TextView;
 import android.widget.Toast;
 
@@ -72,7 +66,6 @@ import com.owncloud.android.DisplayUtils;
 import com.owncloud.android.authenticator.AccountAuthenticator;
 import com.owncloud.android.datamodel.FileDataStorageManager;
 import com.owncloud.android.datamodel.OCFile;
-import com.owncloud.android.files.services.FileDownloader;
 import com.owncloud.android.files.services.FileObserverService;
 import com.owncloud.android.files.services.FileUploader;
 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
@@ -88,12 +81,13 @@ import com.owncloud.android.operations.SynchronizeFileOperation;
 import com.owncloud.android.ui.activity.ConflictsResolveActivity;
 import com.owncloud.android.ui.activity.FileDetailActivity;
 import com.owncloud.android.ui.activity.FileDisplayActivity;
-import com.owncloud.android.ui.activity.TransferServiceGetter;
 import com.owncloud.android.ui.dialog.EditNameDialog;
 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
 import com.owncloud.android.utils.OwnCloudVersion;
 
 import com.owncloud.android.R;
+
+import eu.alefzero.webdav.OnDatatransferProgressListener;
 import eu.alefzero.webdav.WebdavClient;
 import eu.alefzero.webdav.WebdavUtils;
 
@@ -101,30 +95,30 @@ import eu.alefzero.webdav.WebdavUtils;
  * This Fragment is used to display the details about a file.
  * 
  * @author Bartek Przybylski
- * 
+ * @author David A. Velasco
  */
 public class FileDetailFragment extends SherlockFragment implements
-        OnClickListener, ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener, EditNameDialogListener {
+        OnClickListener, 
+        ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener, EditNameDialogListener,
+        FileFragment {
 
     public static final String EXTRA_FILE = "FILE";
     public static final String EXTRA_ACCOUNT = "ACCOUNT";
 
-    private FileDetailFragment.ContainerActivity mContainerActivity;
+    private FileFragment.ContainerActivity mContainerActivity;
     
     private int mLayout;
     private View mView;
     private OCFile mFile;
     private Account mAccount;
     private FileDataStorageManager mStorageManager;
-    private ImageView mPreview;
     
-    private DownloadFinishReceiver mDownloadFinishReceiver;
     private UploadFinishReceiver mUploadFinishReceiver;
+    public ProgressListener mProgressListener;
     
     private Handler mHandler;
     private RemoteOperation mLastRemoteOperation;
-    private DialogFragment mCurrentDialog;
-
+    
     private static final String TAG = FileDetailFragment.class.getSimpleName();
     public static final String FTAG = "FileDetails"; 
     public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";
@@ -140,6 +134,7 @@ public class FileDetailFragment extends SherlockFragment implements
         mAccount = null;
         mStorageManager = null;
         mLayout = R.layout.file_details_empty;
+        mProgressListener = null;
     }
     
     
@@ -156,6 +151,7 @@ public class FileDetailFragment extends SherlockFragment implements
         mAccount = ocAccount;
         mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment 
         mLayout = R.layout.file_details_empty;
+        mProgressListener = null;
     }
     
     
@@ -191,10 +187,11 @@ public class FileDetailFragment extends SherlockFragment implements
             mView.findViewById(R.id.fdOpenBtn).setOnClickListener(this);
             mView.findViewById(R.id.fdRemoveBtn).setOnClickListener(this);
             //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
-            mPreview = (ImageView)mView.findViewById(R.id.fdPreview);
+            ProgressBar progressBar = (ProgressBar)mView.findViewById(R.id.fdProgressBar);
+            mProgressListener = new ProgressListener(progressBar);
         }
         
-        updateFileDetails(false);
+        updateFileDetails(false, false);
         return view;
     }
     
@@ -207,6 +204,7 @@ public class FileDetailFragment extends SherlockFragment implements
         super.onAttach(activity);
         try {
             mContainerActivity = (ContainerActivity) activity;
+            
         } catch (ClassCastException e) {
             throw new ClassCastException(activity.toString() + " must implement " + FileDetailFragment.ContainerActivity.class.getSimpleName());
         }
@@ -220,59 +218,57 @@ public class FileDetailFragment extends SherlockFragment implements
     public void onActivityCreated(Bundle savedInstanceState) {
         super.onActivityCreated(savedInstanceState);
         if (mAccount != null) {
-            mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());;
+            mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
         }
     }
         
 
     @Override
     public void onSaveInstanceState(Bundle outState) {
-        Log.i(getClass().toString(), "onSaveInstanceState() start");
         super.onSaveInstanceState(outState);
         outState.putParcelable(FileDetailFragment.EXTRA_FILE, mFile);
         outState.putParcelable(FileDetailFragment.EXTRA_ACCOUNT, mAccount);
-        Log.i(getClass().toString(), "onSaveInstanceState() end");
     }
 
+    @Override
+    public void onStart() {
+        super.onStart();
+        listenForTransferProgress();
+    }
     
     @Override
     public void onResume() {
         super.onResume();
-        
-        mDownloadFinishReceiver = new DownloadFinishReceiver();
-        IntentFilter filter = new IntentFilter(
-                FileDownloader.DOWNLOAD_FINISH_MESSAGE);
-        getActivity().registerReceiver(mDownloadFinishReceiver, filter);
-        
         mUploadFinishReceiver = new UploadFinishReceiver();
-        filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
+        IntentFilter filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
         getActivity().registerReceiver(mUploadFinishReceiver, filter);
-        
-        mPreview = (ImageView)mView.findViewById(R.id.fdPreview);
+
     }
 
+
     @Override
     public void onPause() {
         super.onPause();
-        
-        getActivity().unregisterReceiver(mDownloadFinishReceiver);
-        mDownloadFinishReceiver = null;
-        
-        getActivity().unregisterReceiver(mUploadFinishReceiver);
-        mUploadFinishReceiver = null;
-        
-        if (mPreview != null) {
-            mPreview = null;
+        if (mUploadFinishReceiver != null) {
+            getActivity().unregisterReceiver(mUploadFinishReceiver);
+            mUploadFinishReceiver = null;
         }
     }
 
+    
+    @Override
+    public void onStop() {
+        super.onStop();
+        leaveTransferProgress();
+    }
+
+    
     @Override
     public View getView() {
         return super.getView() == null ? mView : super.getView();
     }
 
     
-    
     @Override
     public void onClick(View v) {
         switch (v.getId()) {
@@ -315,7 +311,6 @@ public class FileDetailFragment extends SherlockFragment implements
                     // update ui 
                     boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
                     getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
-                    setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
                     
                 }
                 break;
@@ -335,7 +330,6 @@ public class FileDetailFragment extends SherlockFragment implements
                                    FileObserverService.CMD_DEL_OBSERVED_FILE));
                 intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
                 intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
-                Log.e(TAG, "starting observer service");
                 getActivity().startService(intent);
                 
                 if (mFile.keepInSync()) {
@@ -356,54 +350,11 @@ public class FileDetailFragment extends SherlockFragment implements
                         mFile.isDown() ? R.string.confirmation_remove_local : -1,
                         R.string.common_cancel);
                 confDialog.setOnConfirmationListener(this);
-                mCurrentDialog = confDialog;
-                mCurrentDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
+                confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
                 break;
             }
             case R.id.fdOpenBtn: {
-                String storagePath = mFile.getStoragePath();
-                String encodedStoragePath = WebdavUtils.encodePath(storagePath);
-                try {
-                    Intent i = new Intent(Intent.ACTION_VIEW);
-                    i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
-                    i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
-                    startActivity(i);
-                    
-                } catch (Throwable t) {
-                    Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
-                    boolean toastIt = true; 
-                    String mimeType = "";
-                    try {
-                        Intent i = new Intent(Intent.ACTION_VIEW);
-                        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
-                        if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
-                            if (mimeType != null) {
-                                i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
-                            } else {
-                                // desperate try
-                                i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*/*");
-                            }
-                            i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
-                            startActivity(i);
-                            toastIt = false;
-                        }
-                        
-                    } catch (IndexOutOfBoundsException e) {
-                        Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
-                        
-                    } catch (ActivityNotFoundException e) {
-                        Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
-                        
-                    } catch (Throwable th) {
-                        Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
-                        
-                    } finally {
-                        if (toastIt) {
-                            Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
-                        }
-                    }
-                    
-                }
+                openFile();
                 break;
             }
             default:
@@ -417,6 +368,57 @@ public class FileDetailFragment extends SherlockFragment implements
     }
     
     
+    /**
+     * Opens mFile.
+     */
+    private void openFile() {
+        
+        String storagePath = mFile.getStoragePath();
+        String encodedStoragePath = WebdavUtils.encodePath(storagePath);
+        try {
+            Intent i = new Intent(Intent.ACTION_VIEW);
+            i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
+            i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
+            startActivity(i);
+            
+        } catch (Throwable t) {
+            Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
+            boolean toastIt = true; 
+            String mimeType = "";
+            try {
+                Intent i = new Intent(Intent.ACTION_VIEW);
+                mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
+                if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
+                    if (mimeType != null) {
+                        i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
+                    } else {
+                        // desperate try
+                        i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*/*");
+                    }
+                    i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
+                    startActivity(i);
+                    toastIt = false;
+                }
+                
+            } catch (IndexOutOfBoundsException e) {
+                Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
+                
+            } catch (ActivityNotFoundException e) {
+                Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
+                
+            } catch (Throwable th) {
+                Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
+                
+            } finally {
+                if (toastIt) {
+                    Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
+                }
+            }
+            
+        }
+    }
+
+
     @Override
     public void onConfirmation(String callerTag) {
         if (callerTag.equals(FTAG_CONFIRMATION)) {
@@ -431,8 +433,6 @@ public class FileDetailFragment extends SherlockFragment implements
                 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
             }
         }
-        mCurrentDialog.dismiss();
-        mCurrentDialog = null;
     }
     
     @Override
@@ -444,15 +444,11 @@ public class FileDetailFragment extends SherlockFragment implements
             mStorageManager.saveFile(mFile);
             updateFileDetails(mFile, mAccount);
         }
-        mCurrentDialog.dismiss();
-        mCurrentDialog = null;
     }
     
     @Override
     public void onCancel(String callerTag) {
         Log.d(TAG, "REMOVAL CANCELED");
-        mCurrentDialog.dismiss();
-        mCurrentDialog = null;
     }
     
     
@@ -467,10 +463,9 @@ public class FileDetailFragment extends SherlockFragment implements
 
     
     /**
-     * Can be used to get the file that is currently being displayed.
-     * @return The file on the screen.
+     * {@inheritDoc}
      */
-    public OCFile getDisplayedFile(){
+    public OCFile getFile(){
         return mFile;
     }
     
@@ -488,7 +483,7 @@ public class FileDetailFragment extends SherlockFragment implements
             mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
         }
         mAccount = ocAccount;
-        updateFileDetails(false);
+        updateFileDetails(false, false);
     }
     
 
@@ -497,14 +492,21 @@ public class FileDetailFragment extends SherlockFragment implements
      *
      * TODO Remove parameter when the transferring state of files is kept in database. 
      * 
+     * TODO REFACTORING! this method called 5 times before every time the fragment is shown! 
+     * 
      * @param transferring      Flag signaling if the file should be considered as downloading or uploading, 
      *                          although {@link FileDownloaderBinder#isDownloading(Account, OCFile)}  and 
      *                          {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
-     * 
+     *                          
+     * @param refresh           If 'true', try to refresh the hold file from the database
      */
-    public void updateFileDetails(boolean transferring) {
+    public void updateFileDetails(boolean transferring, boolean refresh) {
 
-        if (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment) {
+        if (readyToShow()) {
+            
+            if (refresh && mStorageManager != null) {
+                mFile = mStorageManager.getFileByPath(mFile.getRemotePath());
+            }
             
             // set file details
             setFilename(mFile.getFileName());
@@ -527,11 +529,6 @@ public class FileDetailFragment extends SherlockFragment implements
                 setButtonsForTransferring();
                 
             } else if (mFile.isDown()) {
-                // Update preview
-                if (mFile.getMimetype().startsWith("image/")) {
-                    BitmapLoader bl = new BitmapLoader();
-                    bl.execute(new String[]{mFile.getStoragePath()});
-                }
                 
                 setButtonsForDown();
                 
@@ -544,6 +541,17 @@ public class FileDetailFragment extends SherlockFragment implements
     }
     
     
+    /**
+     * Checks if the fragment is ready to show details of a OCFile
+     *  
+     * @return  'True' when the fragment is ready to show details of a file
+     */
+    private boolean readyToShow() {
+        return (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment);        
+    }
+
+
+
     /**
      * Updates the filename in view
      * @param filename to set
@@ -619,9 +627,23 @@ public class FileDetailFragment extends SherlockFragment implements
             ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(false);
             ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(false);
             getView().findViewById(R.id.fdKeepInSync).setEnabled(false);
+            
+            // show the progress bar for the transfer
+            ProgressBar progressBar = (ProgressBar)getView().findViewById(R.id.fdProgressBar);
+            progressBar.setVisibility(View.VISIBLE);
+            TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
+            progressText.setVisibility(View.VISIBLE);
+            FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
+            FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
+            if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
+                progressText.setText(R.string.downloader_download_in_progress_ticker);
+            } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
+                progressText.setText(R.string.uploader_upload_in_progress_ticker);
+            }
         }
     }
     
+
     /**
      * Enables or disables buttons for a file locally available 
      */
@@ -634,6 +656,12 @@ public class FileDetailFragment extends SherlockFragment implements
             ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
             ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
             getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
+            
+            // hides the progress bar
+            ProgressBar progressBar = (ProgressBar)getView().findViewById(R.id.fdProgressBar);
+            progressBar.setVisibility(View.GONE);
+            TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
+            progressText.setVisibility(View.GONE);
         }
     }
 
@@ -649,6 +677,12 @@ public class FileDetailFragment extends SherlockFragment implements
             ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
             ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
             getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
+            
+            // hides the progress bar
+            ProgressBar progressBar = (ProgressBar)getView().findViewById(R.id.fdProgressBar);
+            progressBar.setVisibility(View.GONE);
+            TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
+            progressText.setVisibility(View.GONE);
         }
     }
     
@@ -673,53 +707,6 @@ public class FileDetailFragment extends SherlockFragment implements
     }
     
     
-    /**
-     * Interface to implement by any Activity that includes some instance of FileDetailFragment
-     * 
-     * @author David A. Velasco
-     */
-    public interface ContainerActivity extends TransferServiceGetter {
-
-        /**
-         * Callback method invoked when the detail fragment wants to notice its container 
-         * activity about a relevant state the file shown by the fragment.
-         * 
-         * Added to notify to FileDisplayActivity about the need of refresh the files list. 
-         * 
-         * Currently called when:
-         *  - a download is started;
-         *  - a rename is completed;
-         *  - a deletion is completed;
-         *  - the 'inSync' flag is changed;
-         */
-        public void onFileStateChanged();
-        
-    }
-    
-
-    /**
-     * Once the file download has finished -> update view
-     * @author Bartek Przybylski
-     */
-    private class DownloadFinishReceiver extends BroadcastReceiver {
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
-
-            if (!isEmpty() && accountName.equals(mAccount.name)) {
-                boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
-                String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
-                if (mFile.getRemotePath().equals(downloadedRemotePath)) {
-                    if (downloadWasFine) {
-                        mFile = mStorageManager.getFileByPath(downloadedRemotePath);
-                    }
-                    updateFileDetails(false);    // it updates the buttons; must be called although !downloadWasFine
-                }
-            }
-        }
-    }
-    
-    
     /**
      * Once the file upload has finished -> update view
      * 
@@ -750,7 +737,7 @@ public class FileDetailFragment extends SherlockFragment implements
                         msg.show();
                     }
                     getSherlockActivity().removeStickyBroadcast(intent);    // not the best place to do this; a small refactorization of BroadcastReceivers should be done
-                    updateFileDetails(false);    // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
+                    updateFileDetails(false, false);    // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
                 }
             }
         }
@@ -877,80 +864,6 @@ public class FileDetailFragment extends SherlockFragment implements
     }
     
     
-    class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
-        @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
-		@Override
-        protected Bitmap doInBackground(String... params) {
-            Bitmap result = null;
-            if (params.length != 1) return result;
-            String storagePath = params[0];
-            try {
-
-                BitmapFactory.Options options = new Options();
-                options.inScaled = true;
-                options.inPurgeable = true;
-                options.inJustDecodeBounds = true;
-                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
-                    options.inPreferQualityOverSpeed = false;
-                }
-                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
-                    options.inMutable = false;
-                }
-
-                result = BitmapFactory.decodeFile(storagePath, options);
-                options.inJustDecodeBounds = false;
-
-                int width = options.outWidth;
-                int height = options.outHeight;
-                int scale = 1;
-                if (width >= 2048 || height >= 2048) {
-                    scale = (int) Math.ceil((Math.ceil(Math.max(height, width) / 2048.)));
-                    options.inSampleSize = scale;
-                }
-                Display display = getActivity().getWindowManager().getDefaultDisplay();
-                Point size = new Point();
-                int screenwidth;
-                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
-                    display.getSize(size);
-                    screenwidth = size.x;
-                } else {
-                    screenwidth = display.getWidth();
-                }
-
-                Log.e("ASD", "W " + width + " SW " + screenwidth);
-
-                if (width > screenwidth) {
-                    scale = (int) Math.ceil((float)width / screenwidth);
-                    options.inSampleSize = scale;
-                }
-
-                result = BitmapFactory.decodeFile(storagePath, options);
-
-                Log.e("ASD", "W " + options.outWidth + " SW " + options.outHeight);
-
-            } catch (OutOfMemoryError e) {
-                result = null;
-                Log.e(TAG, "Out of memory occured for file with size " + storagePath);
-                
-            } catch (NoSuchFieldError e) {
-                result = null;
-                Log.e(TAG, "Error from access to unexisting field despite protection " + storagePath);
-                
-            } catch (Throwable t) {
-                result = null;
-                Log.e(TAG, "Unexpected error while creating image preview " + storagePath, t);
-            }
-            return result;
-        }
-        @Override
-        protected void onPostExecute(Bitmap result) {
-            if (result != null && mPreview != null) {
-                mPreview.setImageBitmap(result);
-            }
-        }
-        
-    }
-
     /**
      * {@inheritDoc}
      */
@@ -1044,6 +957,7 @@ public class FileDetailFragment extends SherlockFragment implements
             
         } else {
             if (operation.transferWasRequested()) {
+                setButtonsForTransferring();
                 mContainerActivity.onFileStateChanged();    // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so 
                                                             // checking the service to see if the file is downloading results in FALSE
             } else {
@@ -1058,5 +972,66 @@ public class FileDetailFragment extends SherlockFragment implements
             }
         }
     }
+    
+    
+    public void listenForTransferProgress() {
+        if (mProgressListener != null) {
+            if (mContainerActivity.getFileDownloaderBinder() != null) {
+                mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
+            }
+            if (mContainerActivity.getFileUploaderBinder() != null) {
+                mContainerActivity.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
+            }
+        }
+    }
+    
+    
+    public void leaveTransferProgress() {
+        if (mProgressListener != null) {
+            if (mContainerActivity.getFileDownloaderBinder() != null) {
+                mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
+            }
+            if (mContainerActivity.getFileUploaderBinder() != null) {
+                mContainerActivity.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
+            }
+        }
+    }
+
+
+    
+    /**
+     * Helper class responsible for updating the progress bar shown for file uploading or downloading  
+     * 
+     * @author David A. Velasco
+     */
+    private class ProgressListener implements OnDatatransferProgressListener {
+        int mLastPercent = 0;
+        WeakReference<ProgressBar> mProgressBar = null;
+        
+        ProgressListener(ProgressBar progressBar) {
+            mProgressBar = new WeakReference<ProgressBar>(progressBar);
+        }
+        
+        @Override
+        public void onTransferProgress(long progressRate) {
+            // old method, nothing here
+        };
+
+        @Override
+        public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filename) {
+            int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
+            if (percent != mLastPercent) {
+                ProgressBar pb = mProgressBar.get();
+                if (pb != null) {
+                    pb.setProgress(percent);
+                    pb.postInvalidate();
+                }
+            }
+            mLastPercent = percent;
+        }
+
+    };
+    
+
 
 }

+ 74 - 0
src/com/owncloud/android/ui/fragment/FileFragment.java

@@ -0,0 +1,74 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013  ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 3 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.ui.fragment;
+
+import android.content.Intent;
+import android.support.v4.app.Fragment;
+
+import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.ui.activity.TransferServiceGetter;
+
+/**
+ * Common methods for {@link Fragment}s containing {@link OCFile}s
+ * 
+ * @author David A. Velasco
+ *
+ */
+public interface FileFragment {
+    
+    /**
+     * Getter for the hold {@link OCFile}
+     * 
+     * @return The {@link OCFile} hold
+     */
+    public OCFile getFile();
+    
+    
+    /**
+     * Interface to implement by any Activity that includes some instance of FileFragment
+     * 
+     * @author David A. Velasco
+     */
+    public interface ContainerActivity extends TransferServiceGetter {
+
+        /**
+         * Callback method invoked when the detail fragment wants to notice its container 
+         * activity about a relevant state the file shown by the fragment.
+         * 
+         * Added to notify to FileDisplayActivity about the need of refresh the files list. 
+         * 
+         * Currently called when:
+         *  - a download is started;
+         *  - a rename is completed;
+         *  - a deletion is completed;
+         *  - the 'inSync' flag is changed;
+         */
+        public void onFileStateChanged();
+
+        /**
+         * Request the parent activity to show the details of an {@link OCFile}.
+         * 
+         * @param file      File to show details
+         */
+        public void showFragmentWithDetails(OCFile file);
+        
+        
+    }
+    
+}

+ 35 - 45
src/com/owncloud/android/ui/fragment/OCFileListFragment.java

@@ -81,8 +81,6 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
     private Handler mHandler;
     private OCFile mTargetFile;
     
-    private DialogFragment mCurrentDialog;
-    
     /**
      * {@inheritDoc}
      */
@@ -163,7 +161,7 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
     public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
         super.onCreateContextMenu(menu, v, menuInfo);
         MenuInflater inflater = getActivity().getMenuInflater();
-        inflater.inflate(R.menu.file_context_menu, menu);
+        inflater.inflate(R.menu.file_actions_menu, menu);
         AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
         OCFile targetFile = (OCFile) mAdapter.getItem(info.position);
         List<Integer> toHide = new ArrayList<Integer>();    
@@ -172,46 +170,47 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
         MenuItem item = null;
         if (targetFile.isDirectory()) {
             // contextual menu for folders
-            toHide.add(R.id.open_file_item);
-            toHide.add(R.id.download_file_item);
-            toHide.add(R.id.cancel_download_item);
-            toHide.add(R.id.cancel_upload_item);
+            toHide.add(R.id.action_open_file_with);
+            toHide.add(R.id.action_download_file);
+            toHide.add(R.id.action_cancel_download);
+            toHide.add(R.id.action_cancel_upload);
+            toHide.add(R.id.action_see_details);
             if (    mContainerActivity.getFileDownloaderBinder().isDownloading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile) ||
                     mContainerActivity.getFileUploaderBinder().isUploading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile)           ) {
-                toDisable.add(R.id.rename_file_item);
-                toDisable.add(R.id.remove_file_item);
+                toDisable.add(R.id.action_rename_file);
+                toDisable.add(R.id.action_remove_file);
                 
             }
             
         } else {
             // contextual menu for regular files
             if (targetFile.isDown()) {
-                toHide.add(R.id.cancel_download_item);
-                toHide.add(R.id.cancel_upload_item);
-                item = menu.findItem(R.id.download_file_item);
+                toHide.add(R.id.action_cancel_download);
+                toHide.add(R.id.action_cancel_upload);
+                item = menu.findItem(R.id.action_download_file);
                 if (item != null) {
                     item.setTitle(R.string.filedetails_sync_file);
                 }
             } else {
-                toHide.add(R.id.open_file_item);
+                toHide.add(R.id.action_open_file_with);
             }
             if ( mContainerActivity.getFileDownloaderBinder().isDownloading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile)) {
-                toHide.add(R.id.download_file_item);
-                toHide.add(R.id.cancel_upload_item);
-                toDisable.add(R.id.open_file_item);
-                toDisable.add(R.id.rename_file_item);
-                toDisable.add(R.id.remove_file_item);
+                toHide.add(R.id.action_download_file);
+                toHide.add(R.id.action_cancel_upload);
+                toDisable.add(R.id.action_open_file_with);
+                toDisable.add(R.id.action_rename_file);
+                toDisable.add(R.id.action_remove_file);
                     
             } else if ( mContainerActivity.getFileUploaderBinder().isUploading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile)) {
-                toHide.add(R.id.download_file_item);
-                toHide.add(R.id.cancel_download_item);
-                toDisable.add(R.id.open_file_item);
-                toDisable.add(R.id.rename_file_item);
-                toDisable.add(R.id.remove_file_item);
+                toHide.add(R.id.action_download_file);
+                toHide.add(R.id.action_cancel_download);
+                toDisable.add(R.id.action_open_file_with);
+                toDisable.add(R.id.action_rename_file);
+                toDisable.add(R.id.action_remove_file);
                     
             } else {
-                toHide.add(R.id.cancel_download_item);
-                toHide.add(R.id.cancel_upload_item);
+                toHide.add(R.id.action_cancel_download);
+                toHide.add(R.id.action_cancel_upload);
             }
         }
 
@@ -240,12 +239,12 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
         AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();        
         mTargetFile = (OCFile) mAdapter.getItem(info.position);
         switch (item.getItemId()) {
-            case R.id.rename_file_item: {
+            case R.id.action_rename_file: {
                 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), mTargetFile.getFileName(), this);
                 dialog.show(getFragmentManager(), EditNameDialog.TAG);
                 return true;
             }
-            case R.id.remove_file_item: {
+            case R.id.action_remove_file: {
                 int messageStringId = R.string.confirmation_remove_alert;
                 int posBtnStringId = R.string.confirmation_remove_remote;
                 int neuBtnStringId = -1;
@@ -264,11 +263,10 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
                         neuBtnStringId,
                         R.string.common_cancel);
                 confDialog.setOnConfirmationListener(this);
-                mCurrentDialog = confDialog;
-                mCurrentDialog.show(getFragmentManager(), FileDetailFragment.FTAG_CONFIRMATION);
+                confDialog.show(getFragmentManager(), FileDetailFragment.FTAG_CONFIRMATION);
                 return true;
             }
-            case R.id.open_file_item: {
+            case R.id.action_open_file_with: {
                 String storagePath = mTargetFile.getStoragePath();
                 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
                 try {
@@ -314,7 +312,7 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
                 }
                 return true;
             }
-            case R.id.download_file_item: {
+            case R.id.action_download_file: {
                 Account account = AccountUtils.getCurrentOwnCloudAccount(getSherlockActivity());
                 RemoteOperation operation = new SynchronizeFileOperation(mTargetFile, null, mContainerActivity.getStorageManager(), account, true, false, getSherlockActivity());
                 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getSherlockActivity().getApplicationContext());
@@ -322,7 +320,7 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
                 getSherlockActivity().showDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
                 return true;
             }
-            case R.id.cancel_download_item: {
+            case R.id.action_cancel_download: {
                 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
                 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
                 if (downloaderBinder != null && downloaderBinder.isDownloading(account, mTargetFile)) {
@@ -332,7 +330,7 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
                 }
                 return true;
             }
-            case R.id.cancel_upload_item: {
+            case R.id.action_cancel_upload: {
                 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
                 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
                 if (uploaderBinder != null && uploaderBinder.isUploading(account, mTargetFile)) {
@@ -342,6 +340,10 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
                 }
                 return true;
             }
+            case R.id.action_see_details: {
+                ((FileFragment.ContainerActivity)getActivity()).showFragmentWithDetails(mTargetFile);
+                return true;
+            }
             default:
                 return super.onContextItemSelected(item); 
         }
@@ -499,10 +501,6 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
                 
                 getActivity().showDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
             }
-            if (mCurrentDialog != null) {
-                mCurrentDialog.dismiss();
-                mCurrentDialog = null;
-            }
         }
     }
     
@@ -518,10 +516,6 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
             mTargetFile.setStoragePath(null);
             mContainerActivity.getStorageManager().saveFile(mTargetFile);
         }
-        if (mCurrentDialog != null) {
-            mCurrentDialog.dismiss();
-            mCurrentDialog = null;
-        }
         listDirectory();
         mContainerActivity.onTransferStateChanged(mTargetFile, false, false);
     }
@@ -529,10 +523,6 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
     @Override
     public void onCancel(String callerTag) {
         Log.d(TAG, "REMOVAL CANCELED");
-        if (mCurrentDialog != null) {
-            mCurrentDialog.dismiss();
-            mCurrentDialog = null;
-        }
     }
 
 

+ 397 - 0
src/com/owncloud/android/ui/preview/FileDownloadFragment.java

@@ -0,0 +1,397 @@
+/* ownCloud Android client application
+ * 
+ *   Copyright (C) 2012-2013  ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 3 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+package com.owncloud.android.ui.preview;
+
+import java.lang.ref.WeakReference;
+
+import android.accounts.Account;
+import android.app.Activity;
+import android.os.Bundle;
+import android.support.v4.app.FragmentStatePagerAdapter;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.ProgressBar;
+import android.widget.TextView;
+
+import com.actionbarsherlock.app.SherlockFragment;
+import com.owncloud.android.datamodel.FileDataStorageManager;
+import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
+import com.owncloud.android.ui.fragment.FileFragment;
+
+import com.owncloud.android.R;
+
+import eu.alefzero.webdav.OnDatatransferProgressListener;
+
+/**
+ * This Fragment is used to monitor the progress of a file downloading.
+ * 
+ * @author David A. Velasco
+ */
+public class FileDownloadFragment extends SherlockFragment implements OnClickListener, FileFragment {
+
+    public static final String EXTRA_FILE = "FILE";
+    public static final String EXTRA_ACCOUNT = "ACCOUNT";
+    private static final String EXTRA_ERROR = "ERROR";
+
+    private FileFragment.ContainerActivity mContainerActivity;
+    
+    private View mView;
+    private OCFile mFile;
+    private Account mAccount;
+    private FileDataStorageManager mStorageManager;
+    
+    public ProgressListener mProgressListener;
+    private boolean mListening;
+    
+    private static final String TAG = FileDownloadFragment.class.getSimpleName();
+    
+    private boolean mIgnoreFirstSavedState;
+    private boolean mError;
+    
+
+    /**
+     * Creates an empty details fragment.
+     * 
+     * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically. 
+     */
+    public FileDownloadFragment() {
+        mFile = null;
+        mAccount = null;
+        mStorageManager = null;
+        mProgressListener = null;
+        mListening = false;
+        mIgnoreFirstSavedState = false;
+        mError = false;
+    }
+    
+    
+    /**
+     * Creates a details fragment.
+     * 
+     * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
+     * 
+     * @param fileToDetail      An {@link OCFile} to show in the fragment
+     * @param ocAccount         An ownCloud account; needed to start downloads
+     * @param ignoreFirstSavedState     Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution 
+     */
+    public FileDownloadFragment(OCFile fileToDetail, Account ocAccount, boolean ignoreFirstSavedState) {
+        mFile = fileToDetail;
+        mAccount = ocAccount;
+        mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment 
+        mProgressListener = null;
+        mListening = false;
+        mIgnoreFirstSavedState = ignoreFirstSavedState;
+        mError = false;
+    }
+    
+    
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+    }
+    
+
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container,
+            Bundle savedInstanceState) {
+        super.onCreateView(inflater, container, savedInstanceState);
+        
+        if (savedInstanceState != null) {
+            if (!mIgnoreFirstSavedState) {
+                mFile = savedInstanceState.getParcelable(FileDownloadFragment.EXTRA_FILE);
+                mAccount = savedInstanceState.getParcelable(FileDownloadFragment.EXTRA_ACCOUNT);
+                mError = savedInstanceState.getBoolean(FileDownloadFragment.EXTRA_ERROR);
+            } else {
+                mIgnoreFirstSavedState = false;
+            }
+        }
+        
+        View view = null;
+        view = inflater.inflate(R.layout.file_download_fragment, container, false);
+        mView = view;
+        
+        ProgressBar progressBar = (ProgressBar)mView.findViewById(R.id.progressBar);
+        mProgressListener = new ProgressListener(progressBar);
+        
+        ((Button)mView.findViewById(R.id.cancelBtn)).setOnClickListener(this);
+        
+        if (mError) {
+            setButtonsForRemote();
+        } else {
+            setButtonsForTransferring();
+        }
+        
+        return view;
+    }
+    
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onAttach(Activity activity) {
+        super.onAttach(activity);
+        try {
+            mContainerActivity = (ContainerActivity) activity;
+            
+        } catch (ClassCastException e) {
+            throw new ClassCastException(activity.toString() + " must implement " + FileFragment.ContainerActivity.class.getSimpleName());
+        }
+    }
+    
+    
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onActivityCreated(Bundle savedInstanceState) {
+        super.onActivityCreated(savedInstanceState);
+        if (mAccount != null) {
+            mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());;
+        }
+    }
+        
+
+    @Override
+    public void onSaveInstanceState(Bundle outState) {
+        super.onSaveInstanceState(outState);
+        outState.putParcelable(FileDownloadFragment.EXTRA_FILE, mFile);
+        outState.putParcelable(FileDownloadFragment.EXTRA_ACCOUNT, mAccount);
+        outState.putBoolean(FileDownloadFragment.EXTRA_ERROR, mError);
+    }
+
+    @Override
+    public void onStart() {
+        super.onStart();
+        listenForTransferProgress();
+    }
+    
+    @Override
+    public void onResume() {
+        super.onResume();
+    }
+
+
+    @Override
+    public void onPause() {
+        super.onPause();
+    }
+
+    
+    @Override
+    public void onStop() {
+        super.onStop();
+        leaveTransferProgress();
+    }
+    
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+    }
+    
+    
+    @Override
+    public View getView() {
+        if (!mListening) {
+            listenForTransferProgress();
+        }
+        return super.getView() == null ? mView : super.getView();
+    }
+
+    
+    @Override
+    public void onClick(View v) {
+        switch (v.getId()) {
+            case R.id.cancelBtn: {
+                FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
+                if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
+                    downloaderBinder.cancel(mAccount, mFile);
+                    getActivity().finish(); // :)
+                    /*
+                    leaveTransferProgress();
+                    if (mFile.isDown()) {
+                        setButtonsForDown();
+                    } else {
+                        setButtonsForRemote();
+                    }
+                    */
+                }
+                break;
+            }
+            default:
+                Log.e(TAG, "Incorrect view clicked!");
+        }
+    }
+
+    
+    /**
+     * {@inheritDoc}
+     */
+    public OCFile getFile(){
+        return mFile;
+    }
+    
+    
+    /**
+     * Updates the view depending upon the state of the downloading file.
+     * 
+     * @param   transferring    When true, the view must be updated assuming that the holded file is 
+     *                          downloading, no matter what the downloaderBinder says.
+     */
+    public void updateView(boolean transferring) {
+        // configure UI for depending upon local state of the file
+        FileDownloaderBinder downloaderBinder = (mContainerActivity == null) ? null : mContainerActivity.getFileDownloaderBinder();
+        if (transferring || (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile))) {
+            setButtonsForTransferring();
+            
+        } else if (mFile.isDown()) {
+            
+            setButtonsForDown();
+            
+        } else {
+            setButtonsForRemote();
+        }
+        getView().invalidate();
+        
+    }
+
+
+    /**
+     * Enables or disables buttons for a file being downloaded
+     */
+    private void setButtonsForTransferring() {
+        getView().findViewById(R.id.cancelBtn).setVisibility(View.VISIBLE);
+    
+        // show the progress bar for the transfer
+        getView().findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
+        TextView progressText = (TextView)getView().findViewById(R.id.progressText);
+        progressText.setText(R.string.downloader_download_in_progress_ticker);
+        progressText.setVisibility(View.VISIBLE);
+                
+        // hides the error icon
+        getView().findViewById(R.id.errorText).setVisibility(View.GONE);
+        getView().findViewById(R.id.error_image).setVisibility(View.GONE);
+    }
+    
+
+    /**
+     * Enables or disables buttons for a file locally available 
+     */
+    private void setButtonsForDown() {
+        getView().findViewById(R.id.cancelBtn).setVisibility(View.GONE);
+    
+        // hides the progress bar
+        getView().findViewById(R.id.progressBar).setVisibility(View.GONE);
+        
+        // updates the text message
+        TextView progressText = (TextView)getView().findViewById(R.id.progressText);
+        progressText.setText(R.string.common_loading);
+        progressText.setVisibility(View.VISIBLE);
+        
+        // hides the error icon
+        getView().findViewById(R.id.errorText).setVisibility(View.GONE);
+        getView().findViewById(R.id.error_image).setVisibility(View.GONE);
+    }
+
+    
+    /**
+     * Enables or disables buttons for a file not locally available 
+     * 
+     * Currently, this is only used when a download was failed
+     */
+    private void setButtonsForRemote() {
+        getView().findViewById(R.id.cancelBtn).setVisibility(View.GONE);
+        
+        // hides the progress bar and message
+        getView().findViewById(R.id.progressBar).setVisibility(View.GONE);
+        getView().findViewById(R.id.progressText).setVisibility(View.GONE);
+
+        // shows the error icon and message
+        getView().findViewById(R.id.errorText).setVisibility(View.VISIBLE);
+        getView().findViewById(R.id.error_image).setVisibility(View.VISIBLE);
+    }
+    
+
+    public void listenForTransferProgress() {
+        if (mProgressListener != null && !mListening) {
+            if (mContainerActivity.getFileDownloaderBinder() != null) {
+                mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
+                mListening = true;
+                setButtonsForTransferring();
+            }
+        }
+    }
+    
+    
+    public void leaveTransferProgress() {
+        if (mProgressListener != null) {
+            if (mContainerActivity.getFileDownloaderBinder() != null) {
+                mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
+                mListening = false;
+            }
+        }
+    }
+
+    
+    /**
+     * Helper class responsible for updating the progress bar shown for file uploading or downloading  
+     * 
+     * @author David A. Velasco
+     */
+    private class ProgressListener implements OnDatatransferProgressListener {
+        int mLastPercent = 0;
+        WeakReference<ProgressBar> mProgressBar = null;
+        
+        ProgressListener(ProgressBar progressBar) {
+            mProgressBar = new WeakReference<ProgressBar>(progressBar);
+        }
+        
+        @Override
+        public void onTransferProgress(long progressRate) {
+            // old method, nothing here
+        };
+
+        @Override
+        public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filename) {
+            int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
+            if (percent != mLastPercent) {
+                ProgressBar pb = mProgressBar.get();
+                if (pb != null) {
+                    pb.setProgress(percent);
+                    pb.postInvalidate();
+                }
+            }
+            mLastPercent = percent;
+        }
+
+    }
+
+
+    public void setError(boolean error) {
+        mError = error;
+    };
+    
+
+
+}

+ 449 - 0
src/com/owncloud/android/ui/preview/PreviewImageActivity.java

@@ -0,0 +1,449 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013  ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 2 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+package com.owncloud.android.ui.preview;
+
+import org.apache.commons.httpclient.methods.PostMethod;
+
+import android.accounts.Account;
+import android.app.Dialog;
+import android.app.ProgressDialog;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.ServiceConnection;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.support.v4.app.Fragment;
+import android.support.v4.view.ViewPager;
+import android.util.Log;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.View.OnTouchListener;
+
+import com.actionbarsherlock.app.ActionBar;
+import com.actionbarsherlock.app.SherlockFragmentActivity;
+import com.actionbarsherlock.view.MenuItem;
+import com.actionbarsherlock.view.Window;
+import com.owncloud.android.datamodel.DataStorageManager;
+import com.owncloud.android.datamodel.FileDataStorageManager;
+import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.files.services.FileDownloader;
+import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
+import com.owncloud.android.files.services.FileUploader;
+import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
+import com.owncloud.android.ui.activity.FileDetailActivity;
+import com.owncloud.android.ui.fragment.FileDetailFragment;
+import com.owncloud.android.ui.fragment.FileFragment;
+
+import com.owncloud.android.AccountUtils;
+import com.owncloud.android.R;
+
+/**
+ *  Used as an utility to preview image files contained in an ownCloud account.
+ *  
+ *  @author David A. Velasco
+ */
+public class PreviewImageActivity extends SherlockFragmentActivity implements FileFragment.ContainerActivity, ViewPager.OnPageChangeListener, OnTouchListener {
+    
+    public static final int DIALOG_SHORT_WAIT = 0;
+
+    public static final String TAG = PreviewImageActivity.class.getSimpleName();
+    
+    public static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
+    private static final String KEY_WAITING_FOR_BINDER = "WAITING_FOR_BINDER";
+    
+    private OCFile mFile;
+    private OCFile mParentFolder;  
+    private Account mAccount;
+    private DataStorageManager mStorageManager;
+    
+    private ViewPager mViewPager; 
+    private PreviewImagePagerAdapter mPreviewImagePagerAdapter;    
+    
+    private FileDownloaderBinder mDownloaderBinder = null;
+    private ServiceConnection mDownloadConnection, mUploadConnection = null;
+    private FileUploaderBinder mUploaderBinder = null;
+
+    private boolean mRequestWaitingForBinder;
+    
+    private DownloadFinishReceiver mDownloadFinishReceiver;
+
+    private boolean mFullScreen;
+    
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        mFile = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
+        mAccount = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_ACCOUNT);
+        if (mFile == null) {
+            throw new IllegalStateException("Instanced with a NULL OCFile");
+        }
+        if (mAccount == null) {
+            throw new IllegalStateException("Instanced with a NULL ownCloud Account");
+        }
+        if (!mFile.isImage()) {
+            throw new IllegalArgumentException("Non-image file passed as argument");
+        }
+        requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
+        setContentView(R.layout.preview_image_activity);
+    
+        ActionBar actionBar = getSupportActionBar();
+        actionBar.setDisplayHomeAsUpEnabled(true);
+        actionBar.setTitle(mFile.getFileName());
+        actionBar.hide();
+        
+        mFullScreen = true;
+        
+        mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
+        mParentFolder = mStorageManager.getFileById(mFile.getParentId());
+        if (mParentFolder == null) {
+            // should not be necessary
+            mParentFolder = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
+        }
+
+        if (savedInstanceState != null) {
+            mRequestWaitingForBinder = savedInstanceState.getBoolean(KEY_WAITING_FOR_BINDER);
+        } else {
+            mRequestWaitingForBinder = false;
+        }
+        
+        createViewPager();
+
+    }
+
+    private void createViewPager() {
+        mPreviewImagePagerAdapter = new PreviewImagePagerAdapter(getSupportFragmentManager(), mParentFolder, mAccount, mStorageManager);
+        mViewPager = (ViewPager) findViewById(R.id.fragmentPager);
+        int position = mPreviewImagePagerAdapter.getFilePosition(mFile);
+        position = (position >= 0) ? position : 0;
+        mViewPager.setAdapter(mPreviewImagePagerAdapter); 
+        mViewPager.setOnPageChangeListener(this);
+        mViewPager.setCurrentItem(position);
+        if (position == 0 && !mFile.isDown()) {
+            // this is necessary because mViewPager.setCurrentItem(0) just after setting the adapter does not result in a call to #onPageSelected(0) 
+            mRequestWaitingForBinder = true;
+        }
+    }
+    
+    
+    @Override
+    public void onStart() {
+        super.onStart();
+        mDownloadConnection = new PreviewImageServiceConnection();
+        bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
+        mUploadConnection = new PreviewImageServiceConnection();
+        bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
+    }
+    
+    @Override
+    protected void onSaveInstanceState(Bundle outState) {
+        super.onSaveInstanceState(outState);
+        outState.putBoolean(KEY_WAITING_FOR_BINDER, mRequestWaitingForBinder);    
+    }
+
+
+    /** Defines callbacks for service binding, passed to bindService() */
+    private class PreviewImageServiceConnection implements ServiceConnection {
+
+        @Override
+        public void onServiceConnected(ComponentName component, IBinder service) {
+                
+            if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
+                mDownloaderBinder = (FileDownloaderBinder) service;
+                if (mRequestWaitingForBinder) {
+                    mRequestWaitingForBinder = false;
+                    Log.d(TAG, "Simulating reselection of current page after connection of download binder");
+                    onPageSelected(mViewPager.getCurrentItem());
+                }
+                    
+            } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
+                Log.d(TAG, "Upload service connected");
+                mUploaderBinder = (FileUploaderBinder) service;
+            } else {
+                return;
+            }
+            
+        }
+
+        @Override
+        public void onServiceDisconnected(ComponentName component) {
+            if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
+                Log.d(TAG, "Download service suddenly disconnected");
+                mDownloaderBinder = null;
+            } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
+                Log.d(TAG, "Upload service suddenly disconnected");
+                mUploaderBinder = null;
+            }
+        }
+    };    
+    
+    
+    @Override
+    public void onStop() {
+        super.onStop();
+        if (mDownloadConnection != null) {
+            unbindService(mDownloadConnection);
+            mDownloadConnection = null;
+        }
+        if (mUploadConnection != null) {
+            unbindService(mUploadConnection);
+            mUploadConnection = null;
+        }
+    }
+    
+    
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+    }
+    
+    
+    @Override
+    public boolean onOptionsItemSelected(MenuItem item) {
+        boolean returnValue = false;
+        
+        switch(item.getItemId()){
+        case android.R.id.home:
+            backToDisplayActivity();
+            returnValue = true;
+            break;
+        default:
+        	returnValue = super.onOptionsItemSelected(item);
+        }
+        
+        return returnValue;
+    }
+
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        //Log.e(TAG, "ACTIVITY, ONRESUME");
+        mDownloadFinishReceiver = new DownloadFinishReceiver();
+        IntentFilter filter = new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
+        filter.addAction(FileDownloader.DOWNLOAD_ADDED_MESSAGE);
+        registerReceiver(mDownloadFinishReceiver, filter);
+    }
+
+    @Override
+    protected void onPostResume() {
+        //Log.e(TAG, "ACTIVITY, ONPOSTRESUME");
+        super.onPostResume();
+    }
+    
+    @Override
+    public void onPause() {
+        super.onPause();
+        unregisterReceiver(mDownloadFinishReceiver);
+        mDownloadFinishReceiver = null;
+    }
+    
+
+    private void backToDisplayActivity() {
+        /*
+        Intent intent = new Intent(this, FileDisplayActivity.class);
+        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+        intent.putExtra(FileDetailFragment.EXTRA_FILE, mFile);
+        intent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, mAccount);
+        startActivity(intent);
+        */
+        finish();
+    }
+    
+    
+    @Override
+    protected Dialog onCreateDialog(int id) {
+        Dialog dialog = null;
+        switch (id) {
+        case DIALOG_SHORT_WAIT: {
+            ProgressDialog working_dialog = new ProgressDialog(this);
+            working_dialog.setMessage(getResources().getString(
+                    R.string.wait_a_moment));
+            working_dialog.setIndeterminate(true);
+            working_dialog.setCancelable(false);
+            dialog = working_dialog;
+            break;
+        }
+        default:
+            dialog = null;
+        }
+        return dialog;
+    }
+    
+    
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onFileStateChanged() {
+        // nothing to do here!
+    }
+
+    
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public FileDownloaderBinder getFileDownloaderBinder() {
+        return mDownloaderBinder;
+    }
+
+
+    @Override
+    public FileUploaderBinder getFileUploaderBinder() {
+        return mUploaderBinder;
+    }
+
+
+    @Override
+    public void showFragmentWithDetails(OCFile file) {
+        Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
+        showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
+        showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
+        showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
+        startActivity(showDetailsIntent);
+        int pos = mPreviewImagePagerAdapter.getFilePosition(file);
+        file = mPreviewImagePagerAdapter.getFileAt(pos);
+        
+    }
+
+    
+    private void requestForDownload(OCFile file) {
+        if (mDownloaderBinder == null) {
+            Log.d(TAG, "requestForDownload called without binder to download service");
+            
+        } else if (!mDownloaderBinder.isDownloading(mAccount, file)) {
+            Intent i = new Intent(this, FileDownloader.class);
+            i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
+            i.putExtra(FileDownloader.EXTRA_FILE, file);
+            startService(i);
+        }
+    }
+
+    /**
+     * This method will be invoked when a new page becomes selected. Animation is not necessarily complete.
+     * 
+     *  @param  Position        Position index of the new selected page
+     */
+    @Override
+    public void onPageSelected(int position) {
+        if (mDownloaderBinder == null) {
+            mRequestWaitingForBinder = true;
+            
+        } else {
+            OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position); 
+            getSupportActionBar().setTitle(currentFile.getFileName());
+            if (!currentFile.isDown()) {
+                if (!mPreviewImagePagerAdapter.pendingErrorAt(position)) {
+                    requestForDownload(currentFile);
+                }
+            }
+        }
+    }
+    
+    /**
+     * Called when the scroll state changes. Useful for discovering when the user begins dragging, 
+     * when the pager is automatically settling to the current page, or when it is fully stopped/idle.
+     * 
+     * @param   State       The new scroll state (SCROLL_STATE_IDLE, _DRAGGING, _SETTLING
+     */
+    @Override
+    public void onPageScrollStateChanged(int state) {
+    }
+
+    /**
+     * This method will be invoked when the current page is scrolled, either as part of a programmatically 
+     * initiated smooth scroll or a user initiated touch scroll.
+     * 
+     * @param   position                Position index of the first page currently being displayed. 
+     *                                  Page position+1 will be visible if positionOffset is nonzero.
+     *                                  
+     * @param   positionOffset          Value from [0, 1) indicating the offset from the page at position.
+     * @param   positionOffsetPixels    Value in pixels indicating the offset from position. 
+     */
+    @Override
+    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
+    }
+    
+
+    /**
+     * Class waiting for broadcast events from the {@link FielDownloader} service.
+     * 
+     * Updates the UI when a download is started or finished, provided that it is relevant for the
+     * folder displayed in the gallery.
+     */
+    private class DownloadFinishReceiver extends BroadcastReceiver {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
+            String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
+            if (mAccount.name.equals(accountName) && 
+                    downloadedRemotePath != null) {
+
+                OCFile file = mStorageManager.getFileByPath(downloadedRemotePath);
+                int position = mPreviewImagePagerAdapter.getFilePosition(file);
+                boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
+                //boolean isOffscreen =  Math.abs((mViewPager.getCurrentItem() - position)) <= mViewPager.getOffscreenPageLimit();
+                
+                if (position >= 0 && intent.getAction().equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
+                    if (downloadWasFine) {
+                        mPreviewImagePagerAdapter.updateFile(position, file);   
+                        
+                    } else {
+                        mPreviewImagePagerAdapter.updateWithDownloadError(position);
+                    }
+                    mPreviewImagePagerAdapter.notifyDataSetChanged();   // will trigger the creation of new fragments
+                    
+                } else {
+                    Log.d(TAG, "Download finished, but the fragment is offscreen");
+                }
+                
+            }
+            removeStickyBroadcast(intent);
+        }
+
+    }
+
+
+    @Override
+    public boolean onTouch(View v, MotionEvent event) {
+        if (event.getAction() == MotionEvent.ACTION_UP) {
+           toggleFullScreen();
+        }
+        return true;
+    }
+
+    
+    private void toggleFullScreen() {
+        ActionBar actionBar = getSupportActionBar();
+        if (mFullScreen) {
+            actionBar.show();
+            
+        } else {
+            actionBar.hide();
+            
+        }
+        mFullScreen = !mFullScreen;
+    }
+    
+    
+}

+ 686 - 0
src/com/owncloud/android/ui/preview/PreviewImageFragment.java

@@ -0,0 +1,686 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013 ownCloud Inc. 
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 2 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+package com.owncloud.android.ui.preview;
+
+import java.io.File;
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.List;
+
+
+import android.accounts.Account;
+import android.annotation.SuppressLint;
+import android.app.Activity;
+import android.content.ActivityNotFoundException;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.BitmapFactory.Options;
+import android.graphics.Point;
+import android.net.Uri;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.os.Handler;
+import android.support.v4.app.FragmentStatePagerAdapter;
+import android.util.Log;
+import android.view.Display;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.View.OnTouchListener;
+import android.view.ViewGroup;
+import android.webkit.MimeTypeMap;
+import android.widget.ImageView;
+import android.widget.ProgressBar;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.actionbarsherlock.app.SherlockFragment;
+import com.actionbarsherlock.view.Menu;
+import com.actionbarsherlock.view.MenuInflater;
+import com.actionbarsherlock.view.MenuItem;
+import com.owncloud.android.datamodel.FileDataStorageManager;
+import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.network.OwnCloudClientUtils;
+import com.owncloud.android.operations.OnRemoteOperationListener;
+import com.owncloud.android.operations.RemoteOperation;
+import com.owncloud.android.operations.RemoteOperationResult;
+import com.owncloud.android.operations.RemoveFileOperation;
+import com.owncloud.android.ui.fragment.ConfirmationDialogFragment;
+import com.owncloud.android.ui.fragment.FileFragment;
+
+import com.owncloud.android.R;
+import eu.alefzero.webdav.WebdavClient;
+import eu.alefzero.webdav.WebdavUtils;
+
+
+/**
+ * This fragment shows a preview of a downloaded image.
+ * 
+ * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
+ * 
+ * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
+ * 
+ * @author David A. Velasco
+ */
+public class PreviewImageFragment extends SherlockFragment implements   FileFragment, 
+                                                                        OnRemoteOperationListener, 
+                                                                        ConfirmationDialogFragment.ConfirmationDialogFragmentListener {
+    public static final String EXTRA_FILE = "FILE";
+    public static final String EXTRA_ACCOUNT = "ACCOUNT";
+
+    private View mView;
+    private OCFile mFile;
+    private Account mAccount;
+    private FileDataStorageManager mStorageManager;
+    private ImageView mImageView;
+    private TextView mMessageView;
+    private ProgressBar mProgressWheel;
+
+    public Bitmap mBitmap = null;
+    
+    private Handler mHandler;
+    private RemoteOperation mLastRemoteOperation;
+    
+    private static final String TAG = PreviewImageFragment.class.getSimpleName();
+
+    private boolean mIgnoreFirstSavedState;
+
+    
+    /**
+     * Creates a fragment to preview an image.
+     * 
+     * When 'imageFile' or 'ocAccount' are null
+     * 
+     * @param imageFile                 An {@link OCFile} to preview as an image in the fragment
+     * @param ocAccount                 An ownCloud account; needed to start downloads
+     * @param ignoreFirstSavedState     Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution 
+     */
+    public PreviewImageFragment(OCFile fileToDetail, Account ocAccount, boolean ignoreFirstSavedState) {
+        mFile = fileToDetail;
+        mAccount = ocAccount;
+        mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment
+        mIgnoreFirstSavedState = ignoreFirstSavedState;
+    }
+    
+    
+    /**
+     *  Creates an empty fragment for image previews.
+     * 
+     *  MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
+     * 
+     *  DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction 
+     */
+    public PreviewImageFragment() {
+        mFile = null;
+        mAccount = null;
+        mStorageManager = null;
+        mIgnoreFirstSavedState = false;
+    }
+    
+    
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mHandler = new Handler();
+        setHasOptionsMenu(true);
+    }
+    
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container,
+            Bundle savedInstanceState) {
+        super.onCreateView(inflater, container, savedInstanceState);
+        mView = inflater.inflate(R.layout.preview_image_fragment, container, false);
+        mImageView = (ImageView)mView.findViewById(R.id.image);
+        mImageView.setVisibility(View.GONE);
+        mView.setOnTouchListener((OnTouchListener)getActivity());   // WATCH OUT THAT CAST
+        mMessageView = (TextView)mView.findViewById(R.id.message);
+        mMessageView.setVisibility(View.GONE);
+        mProgressWheel = (ProgressBar)mView.findViewById(R.id.progressWheel);
+        mProgressWheel.setVisibility(View.VISIBLE);
+        return mView;
+    }
+    
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onAttach(Activity activity) {
+        super.onAttach(activity);
+        if (!(activity instanceof FileFragment.ContainerActivity))
+            throw new ClassCastException(activity.toString() + " must implement " + FileFragment.ContainerActivity.class.getSimpleName());
+    }
+    
+    
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onActivityCreated(Bundle savedInstanceState) {
+        super.onActivityCreated(savedInstanceState);
+        mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
+        if (savedInstanceState != null) {
+            if (!mIgnoreFirstSavedState) {
+                mFile = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE);
+                mAccount = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_ACCOUNT);
+            } else {
+                mIgnoreFirstSavedState = false;
+            }
+        }
+        if (mFile == null) {
+            throw new IllegalStateException("Instanced with a NULL OCFile");
+        }
+        if (mAccount == null) {
+            throw new IllegalStateException("Instanced with a NULL ownCloud Account");
+        }
+        if (!mFile.isDown()) {
+            throw new IllegalStateException("There is no local file to preview");
+        }
+    }
+        
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onSaveInstanceState(Bundle outState) {
+        super.onSaveInstanceState(outState);
+        outState.putParcelable(PreviewImageFragment.EXTRA_FILE, mFile);
+        outState.putParcelable(PreviewImageFragment.EXTRA_ACCOUNT, mAccount);
+    }
+    
+
+    @Override
+    public void onStart() {
+        super.onStart();
+        if (mFile != null) {
+           BitmapLoader bl = new BitmapLoader(mImageView, mMessageView, mProgressWheel);
+           bl.execute(new String[]{mFile.getStoragePath()});
+        }
+    }
+    
+    
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+        super.onCreateOptionsMenu(menu, inflater);
+
+        inflater.inflate(R.menu.file_actions_menu, menu);
+        List<Integer> toHide = new ArrayList<Integer>();    
+        
+        MenuItem item = null;
+        toHide.add(R.id.action_cancel_download);
+        toHide.add(R.id.action_cancel_upload);
+        toHide.add(R.id.action_download_file);
+        toHide.add(R.id.action_rename_file);    // by now
+
+        for (int i : toHide) {
+            item = menu.findItem(i);
+            if (item != null) {
+                item.setVisible(false);
+                item.setEnabled(false);
+            }
+        }
+        
+    }
+
+    
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public boolean onOptionsItemSelected(MenuItem item) {
+        switch (item.getItemId()) {
+            case R.id.action_open_file_with: {
+                openFile();
+                return true;
+            }
+            case R.id.action_remove_file: {
+                removeFile();
+                return true;
+            }
+            case R.id.action_see_details: {
+                seeDetails();
+                return true;
+            }
+            
+            default:
+                return false;
+        }
+    }
+
+    
+    private void seeDetails() {
+        ((FileFragment.ContainerActivity)getActivity()).showFragmentWithDetails(mFile);        
+    }
+
+
+    @Override
+    public void onResume() {
+        super.onResume();
+        //Log.e(TAG, "FRAGMENT, ONRESUME");
+        /*
+        mDownloadFinishReceiver = new DownloadFinishReceiver();
+        IntentFilter filter = new IntentFilter(
+                FileDownloader.DOWNLOAD_FINISH_MESSAGE);
+        getActivity().registerReceiver(mDownloadFinishReceiver, filter);
+        
+        mUploadFinishReceiver = new UploadFinishReceiver();
+        filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
+        getActivity().registerReceiver(mUploadFinishReceiver, filter);
+        */
+
+    }
+
+
+    @Override
+    public void onPause() {
+        super.onPause();
+        /*
+        if (mVideoPreview.getVisibility() == View.VISIBLE) {
+            mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
+        }*/
+        /*
+        getActivity().unregisterReceiver(mDownloadFinishReceiver);
+        mDownloadFinishReceiver = null;
+        
+        getActivity().unregisterReceiver(mUploadFinishReceiver);
+        mUploadFinishReceiver = null;
+        */
+    }
+
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        if (mBitmap != null) {
+            mBitmap.recycle();
+        }
+    }
+
+    
+    /**
+     * Opens the previewed image with an external application.
+     * 
+     * TODO - improve this; instead of prioritize the actions available for the MIME type in the server, 
+     * we should get a list of available apps for MIME tpye in the server and join it with the list of 
+     * available apps for the MIME type known from the file extension, to let the user choose
+     */
+    private void openFile() {
+        String storagePath = mFile.getStoragePath();
+        String encodedStoragePath = WebdavUtils.encodePath(storagePath);
+        try {
+            Intent i = new Intent(Intent.ACTION_VIEW);
+            i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
+            i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
+            startActivity(i);
+            
+        } catch (Throwable t) {
+            Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
+            boolean toastIt = true; 
+            String mimeType = "";
+            try {
+                Intent i = new Intent(Intent.ACTION_VIEW);
+                mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
+                if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
+                    if (mimeType != null) {
+                        i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
+                    } else {
+                        // desperate try
+                        i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*-/*");
+                    }
+                    i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
+                    startActivity(i);
+                    toastIt = false;
+                }
+                
+            } catch (IndexOutOfBoundsException e) {
+                Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
+                
+            } catch (ActivityNotFoundException e) {
+                Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
+                
+            } catch (Throwable th) {
+                Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
+                
+            } finally {
+                if (toastIt) {
+                    Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
+                }
+            }
+            
+        }
+        finish();
+    }
+    
+    
+    /**
+     * Starts a the removal of the previewed file.
+     * 
+     * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
+     * depending upon the user selection in the dialog. 
+     */
+    private void removeFile() {
+        ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
+                R.string.confirmation_remove_alert,
+                new String[]{mFile.getFileName()},
+                R.string.confirmation_remove_remote_and_local,
+                R.string.confirmation_remove_local,
+                R.string.common_cancel);
+        confDialog.setOnConfirmationListener(this);
+        confDialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
+    }
+
+    
+    /**
+     * Performs the removal of the previewed file, both locally and in the server.
+     */
+    @Override
+    public void onConfirmation(String callerTag) {
+        if (mStorageManager.getFileById(mFile.getFileId()) != null) {   // check that the file is still there;
+            mLastRemoteOperation = new RemoveFileOperation( mFile,      // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
+                                                            true, 
+                                                            mStorageManager);
+            WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
+            mLastRemoteOperation.execute(wc, this, mHandler);
+            
+            getActivity().showDialog(PreviewImageActivity.DIALOG_SHORT_WAIT);
+        }
+    }
+    
+    
+    /**
+     * Removes the file from local storage
+     */
+    @Override
+    public void onNeutral(String callerTag) {
+        // TODO this code should be made in a secondary thread,
+        if (mFile.isDown()) {   // checks it is still there
+            File f = new File(mFile.getStoragePath());
+            f.delete();
+            mFile.setStoragePath(null);
+            mStorageManager.saveFile(mFile);
+            finish();
+        }
+    }
+    
+    /**
+     * User cancelled the removal action.
+     */
+    @Override
+    public void onCancel(String callerTag) {
+        // nothing to do here
+    }
+    
+
+    /**
+     * {@inheritDoc}
+     */
+    public OCFile getFile(){
+        return mFile;
+    }
+    
+    /*
+    /**
+     * Use this method to signal this Activity that it shall update its view.
+     * 
+     * @param file : An {@link OCFile}
+     *-/
+    public void updateFileDetails(OCFile file, Account ocAccount) {
+        mFile = file;
+        if (ocAccount != null && ( 
+                mStorageManager == null || 
+                (mAccount != null && !mAccount.equals(ocAccount))
+           )) {
+            mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
+        }
+        mAccount = ocAccount;
+        updateFileDetails(false);
+    }
+    */
+    
+
+    private class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
+
+        /**
+         * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
+         * 
+         * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
+         */
+        private final WeakReference<ImageView> mImageViewRef;
+
+        /**
+         * Weak reference to the target {@link TextView} where error messages will be written.
+         * 
+         * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
+         */
+        private final WeakReference<TextView> mMessageViewRef;
+
+        
+        /**
+         * Weak reference to the target {@link Progressbar} shown while the load is in progress.
+         * 
+         * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
+         */
+        private final WeakReference<ProgressBar> mProgressWheelRef;
+
+        
+        /**
+         * Error message to show when a load fails 
+         */
+        private int mErrorMessageId;
+        
+        
+        /**
+         * Constructor.
+         * 
+         * @param imageView     Target {@link ImageView} where the bitmap will be loaded into.
+         */
+        public BitmapLoader(ImageView imageView, TextView messageView, ProgressBar progressWheel) {
+            mImageViewRef = new WeakReference<ImageView>(imageView);
+            mMessageViewRef = new WeakReference<TextView>(messageView);
+            mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
+        }
+        
+        
+        @SuppressWarnings("deprecation")
+        @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
+		@Override
+        protected Bitmap doInBackground(String... params) {
+            Bitmap result = null;
+            if (params.length != 1) return result;
+            String storagePath = params[0];
+            try {
+                // set desired options that will affect the size of the bitmap
+                BitmapFactory.Options options = new Options();
+                options.inScaled = true;
+                options.inPurgeable = true;
+                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
+                    options.inPreferQualityOverSpeed = false;
+                }
+                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
+                    options.inMutable = false;
+                }
+                // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
+                options.inJustDecodeBounds = true;
+                BitmapFactory.decodeFile(storagePath, options);   
+                
+                int width = options.outWidth;
+                int height = options.outHeight;
+                int scale = 1;
+                
+                Display display = getActivity().getWindowManager().getDefaultDisplay();
+                Point size = new Point();
+                int screenWidth;
+                int screenHeight;
+                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
+                    display.getSize(size);
+                    screenWidth = size.x;
+                    screenHeight = size.y;
+                } else {
+                    screenWidth = display.getWidth();
+                    screenHeight = display.getHeight();
+                }
+
+                if (width > screenWidth) {
+                    // second try to scale down the image , this time depending upon the screen size 
+                    scale = (int) Math.floor((float)width / screenWidth);
+                }
+                if (height > screenHeight) {
+                    scale = Math.max(scale, (int) Math.floor((float)height / screenHeight));
+                }
+                options.inSampleSize = scale;
+
+                // really load the bitmap
+                options.inJustDecodeBounds = false; // the next decodeFile call will be real
+                result = BitmapFactory.decodeFile(storagePath, options);
+                //Log.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
+
+                if (result == null) {
+                    mErrorMessageId = R.string.preview_image_error_unknown_format;
+                    Log.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
+                }
+                
+            } catch (OutOfMemoryError e) {
+                mErrorMessageId = R.string.preview_image_error_unknown_format;
+                Log.e(TAG, "Out of memory occured for file " + storagePath, e);
+                    
+            } catch (NoSuchFieldError e) {
+                mErrorMessageId = R.string.common_error_unknown;
+                Log.e(TAG, "Error from access to unexisting field despite protection; file " + storagePath, e);
+                    
+            } catch (Throwable t) {
+                mErrorMessageId = R.string.common_error_unknown;
+                Log.e(TAG, "Unexpected error loading " + mFile.getStoragePath(), t);
+                
+            }
+            return result;
+        }
+        
+        @Override
+        protected void onPostExecute(Bitmap result) {
+            hideProgressWheel();
+            if (result != null) {
+                showLoadedImage(result);
+            } else {
+                showErrorMessage();
+            }
+        }
+        
+        private void showLoadedImage(Bitmap result) {
+            if (mImageViewRef != null) {
+                final ImageView imageView = mImageViewRef.get();
+                if (imageView != null) {
+                    imageView.setImageBitmap(result);
+                    imageView.setVisibility(View.VISIBLE);
+                    mBitmap  = result;
+                } // else , silently finish, the fragment was destroyed
+            }
+            if (mMessageViewRef != null) {
+                final TextView messageView = mMessageViewRef.get();
+                if (messageView != null) {
+                    messageView.setVisibility(View.GONE);
+                } // else , silently finish, the fragment was destroyed
+            }
+        }
+        
+        private void showErrorMessage() {
+            if (mImageViewRef != null) {
+                final ImageView imageView = mImageViewRef.get();
+                if (imageView != null) {
+                    // shows the default error icon
+                    imageView.setVisibility(View.VISIBLE);
+                } // else , silently finish, the fragment was destroyed
+            }
+            if (mMessageViewRef != null) {
+                final TextView messageView = mMessageViewRef.get();
+                if (messageView != null) {
+                    messageView.setText(mErrorMessageId);
+                    messageView.setVisibility(View.VISIBLE);
+                } // else , silently finish, the fragment was destroyed
+            }
+        }
+        
+        private void hideProgressWheel() {
+            if (mProgressWheelRef != null) {
+                final ProgressBar progressWheel = mProgressWheelRef.get();
+                if (progressWheel != null) {
+                    progressWheel.setVisibility(View.GONE);
+                }
+            }
+        }
+        
+    }
+
+    /**
+     * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
+     * 
+     * @param file      File to test if can be previewed.
+     * @return          'True' if the file can be handled by the fragment.
+     */
+    public static boolean canBePreviewed(OCFile file) {
+        return (file != null && file.isImage());
+    }
+
+    
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
+        if (operation.equals(mLastRemoteOperation) && operation instanceof RemoveFileOperation) {
+            onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
+        }
+    }
+    
+    private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
+        getActivity().dismissDialog(PreviewImageActivity.DIALOG_SHORT_WAIT);
+        
+        if (result.isSuccess()) {
+            Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
+            msg.show();
+            finish();
+                
+        } else {
+            Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG); 
+            msg.show();
+            if (result.isSslRecoverableException()) {
+                // TODO show the SSL warning dialog
+            }
+        }
+    }
+
+    /**
+     * Finishes the preview
+     */
+    private void finish() {
+        Activity container = getActivity();
+        container.finish();
+    }
+    
+    
+}

+ 353 - 0
src/com/owncloud/android/ui/preview/PreviewImagePagerAdapter.java

@@ -0,0 +1,353 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013  ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 2 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+package com.owncloud.android.ui.preview;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.Vector;
+
+import android.accounts.Account;
+import android.os.Bundle;
+import android.os.Parcelable;
+import android.support.v4.app.Fragment;
+import android.support.v4.app.FragmentManager;
+import android.support.v4.app.FragmentStatePagerAdapter;
+import android.support.v4.app.FragmentTransaction;
+import android.support.v4.view.PagerAdapter;
+import android.support.v4.view.ViewPager;
+import android.util.Log;
+import android.view.View;
+import android.view.ViewGroup;
+
+import com.owncloud.android.datamodel.DataStorageManager;
+import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.ui.fragment.FileFragment;
+
+/**
+ * Adapter class that provides Fragment instances  
+ * 
+ * @author David A. Velasco
+ */
+//public class PreviewImagePagerAdapter extends PagerAdapter {
+public class PreviewImagePagerAdapter extends FragmentStatePagerAdapter {
+    
+    private static final String TAG = PreviewImagePagerAdapter.class.getSimpleName();
+            
+    private Vector<OCFile> mImageFiles;
+    private Account mAccount;
+    private Set<Object> mObsoleteFragments;
+    private Set<Integer> mObsoletePositions;
+    private Set<Integer> mDownloadErrors;
+    private DataStorageManager mStorageManager;
+    
+    private Map<Integer, FileFragment> mCachedFragments;
+
+    /*
+    private final FragmentManager mFragmentManager;
+    private FragmentTransaction mCurTransaction = null;
+    private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<Fragment.SavedState>();
+    private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
+    private Fragment mCurrentPrimaryItem = null;
+    */
+
+    /**
+     * Constructor.
+     * 
+     * @param fragmentManager   {@link FragmentManager} instance that will handle the {@link Fragment}s provided by the adapter. 
+     * @param parentFolder      Folder where images will be searched for.
+     * @param storageManager    Bridge to database.
+     */
+    public PreviewImagePagerAdapter(FragmentManager fragmentManager, OCFile parentFolder, Account account, DataStorageManager storageManager) {
+        super(fragmentManager);
+        
+        if (fragmentManager == null) {
+            throw new IllegalArgumentException("NULL FragmentManager instance");
+        }
+        if (parentFolder == null) {
+            throw new IllegalArgumentException("NULL parent folder");
+        } 
+        if (storageManager == null) {
+            throw new IllegalArgumentException("NULL storage manager");
+        }
+
+        mAccount = account;
+        mStorageManager = storageManager;
+        mImageFiles = mStorageManager.getDirectoryImages(parentFolder); 
+        mObsoleteFragments = new HashSet<Object>();
+        mObsoletePositions = new HashSet<Integer>();
+        mDownloadErrors = new HashSet<Integer>();
+        //mFragmentManager = fragmentManager;
+        mCachedFragments = new HashMap<Integer, FileFragment>();
+    }
+
+    
+    /**
+     * Returns the image files handled by the adapter.
+     * 
+     * @return  A vector with the image files handled by the adapter.
+     */
+    protected OCFile getFileAt(int position) {
+        return mImageFiles.get(position);
+    }
+
+    
+    public Fragment getItem(int i) {
+        OCFile file = mImageFiles.get(i);
+        Fragment fragment = null;
+        if (file.isDown()) {
+            fragment = new PreviewImageFragment(file, mAccount, mObsoletePositions.contains(Integer.valueOf(i)));
+            
+        } else if (mDownloadErrors.contains(Integer.valueOf(i))) {
+            fragment = new FileDownloadFragment(file, mAccount, true);
+            ((FileDownloadFragment)fragment).setError(true);
+            mDownloadErrors.remove(Integer.valueOf(i));
+            
+        } else {
+            fragment = new FileDownloadFragment(file, mAccount, mObsoletePositions.contains(Integer.valueOf(i)));
+        }
+        mObsoletePositions.remove(Integer.valueOf(i));
+        return fragment;
+    }
+
+    public int getFilePosition(OCFile file) {
+        return mImageFiles.indexOf(file);
+    }
+    
+    @Override
+    public int getCount() {
+        return mImageFiles.size();
+    }
+
+    @Override
+    public CharSequence getPageTitle(int position) {
+        return mImageFiles.get(position).getFileName();
+    }
+
+    
+    public void updateFile(int position, OCFile file) {
+        FileFragment fragmentToUpdate = mCachedFragments.get(Integer.valueOf(position));
+        if (fragmentToUpdate != null) {
+            mObsoleteFragments.add(fragmentToUpdate);
+        }
+        mObsoletePositions.add(Integer.valueOf(position));
+        mImageFiles.set(position, file);
+    }
+    
+    
+    public void updateWithDownloadError(int position) {
+        FileFragment fragmentToUpdate = mCachedFragments.get(Integer.valueOf(position));
+        if (fragmentToUpdate != null) {
+            mObsoleteFragments.add(fragmentToUpdate);
+        }
+        mDownloadErrors.add(Integer.valueOf(position));
+    }
+    
+    public void clearErrorAt(int position) {
+        FileFragment fragmentToUpdate = mCachedFragments.get(Integer.valueOf(position));
+        if (fragmentToUpdate != null) {
+            mObsoleteFragments.add(fragmentToUpdate);
+        }
+        mDownloadErrors.remove(Integer.valueOf(position));
+    }
+    
+    
+    @Override
+    public int getItemPosition(Object object) {
+        if (mObsoleteFragments.contains(object)) {
+            mObsoleteFragments.remove(object);
+            return POSITION_NONE;
+        }
+        return super.getItemPosition(object);
+    }
+
+
+    @Override
+    public Object instantiateItem(ViewGroup container, int position) {
+        Object fragment = super.instantiateItem(container, position);
+        mCachedFragments.put(Integer.valueOf(position), (FileFragment)fragment);
+        return fragment;
+    }
+    
+    @Override
+    public void destroyItem(ViewGroup container, int position, Object object) {
+       mCachedFragments.remove(Integer.valueOf(position));
+       super.destroyItem(container, position, object);
+    }
+
+
+    public boolean pendingErrorAt(int position) {
+        return mDownloadErrors.contains(Integer.valueOf(position));
+    }
+
+
+    
+    /* -*
+     * Called when a change in the shown pages is going to start being made.
+     * 
+     * @param   container   The containing View which is displaying this adapter's page views.
+     *- /
+    @Override
+    public void startUpdate(ViewGroup container) {
+        Log.e(TAG, "** startUpdate");
+    }
+
+    @Override
+    public Object instantiateItem(ViewGroup container, int position) {
+        Log.e(TAG, "** instantiateItem " + position);
+        
+        if (mFragments.size() > position) {
+            Fragment fragment = mFragments.get(position);
+            if (fragment != null) {
+                Log.e(TAG, "** \t returning cached item");
+                return fragment;
+            }
+        }
+
+        if (mCurTransaction == null) {
+            mCurTransaction = mFragmentManager.beginTransaction();
+        }
+
+        Fragment fragment = getItem(position);
+        if (mSavedState.size() > position) {
+            Fragment.SavedState savedState = mSavedState.get(position);
+            if (savedState != null) {
+                // TODO WATCH OUT:
+                // * The Fragment must currently be attached to the FragmentManager.
+                // * A new Fragment created using this saved state must be the same class type as the Fragment it was created from.
+                // * The saved state can not contain dependencies on other fragments -- that is it can't use putFragment(Bundle, String, Fragment) 
+                //   to store a fragment reference                 
+                fragment.setInitialSavedState(savedState);
+            }
+        }
+        while (mFragments.size() <= position) {
+            mFragments.add(null);
+        }
+        fragment.setMenuVisibility(false);
+        mFragments.set(position, fragment);
+        //Log.e(TAG, "** \t adding fragment at position " + position + ", containerId " + container.getId());
+        mCurTransaction.add(container.getId(), fragment);
+
+        return fragment;
+    }
+
+    @Override
+    public void destroyItem(ViewGroup container, int position, Object object) {
+        Log.e(TAG, "** destroyItem " + position);
+        Fragment fragment = (Fragment)object;
+        
+        if (mCurTransaction == null) {
+            mCurTransaction = mFragmentManager.beginTransaction();
+        }
+        Log.e(TAG, "** \t removing fragment at position " + position);
+        while (mSavedState.size() <= position) {
+            mSavedState.add(null);
+        }
+        mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment));
+        mFragments.set(position, null);
+
+        mCurTransaction.remove(fragment);
+    }
+
+    @Override
+    public void setPrimaryItem(ViewGroup container, int position, Object object) {
+        Fragment fragment = (Fragment)object;
+        if (fragment != mCurrentPrimaryItem) {
+            if (mCurrentPrimaryItem != null) {
+                mCurrentPrimaryItem.setMenuVisibility(false);
+            }
+            if (fragment != null) {
+                fragment.setMenuVisibility(true);
+            }
+            mCurrentPrimaryItem = fragment;
+        }
+    }
+
+    @Override
+    public void finishUpdate(ViewGroup container) {
+        Log.e(TAG, "** finishUpdate (start)");
+        if (mCurTransaction != null) {
+            mCurTransaction.commitAllowingStateLoss();
+            mCurTransaction = null;
+            mFragmentManager.executePendingTransactions();
+        }
+        Log.e(TAG, "** finishUpdate (end)");
+    }
+
+    @Override
+    public boolean isViewFromObject(View view, Object object) {
+        return ((Fragment)object).getView() == view;
+    }
+
+    @Override
+    public Parcelable saveState() {
+        Bundle state = null;
+        if (mSavedState.size() > 0) {
+            state = new Bundle();
+            Fragment.SavedState[] savedStates = new Fragment.SavedState[mSavedState.size()];
+            mSavedState.toArray(savedStates);
+            state.putParcelableArray("states", savedStates);
+        }
+        for (int i=0; i<mFragments.size(); i++) {
+            Fragment fragment = mFragments.get(i);
+            if (fragment != null) {
+                if (state == null) {
+                    state = new Bundle();
+                }
+                String key = "f" + i;
+                mFragmentManager.putFragment(state, key, fragment);
+            }
+        }
+        return state;
+    }
+
+    @Override
+    public void restoreState(Parcelable state, ClassLoader loader) {
+        if (state != null) {
+            Bundle bundle = (Bundle)state;
+            bundle.setClassLoader(loader);
+            Parcelable[] states = bundle.getParcelableArray("states");
+            mSavedState.clear();
+            mFragments.clear();
+            if (states != null) {
+                for (int i=0; i<states.length; i++) {
+                    mSavedState.add((Fragment.SavedState)states[i]);
+                }
+            }
+            Iterable<String> keys = bundle.keySet();
+            for (String key: keys) {
+                if (key.startsWith("f")) {
+                    int index = Integer.parseInt(key.substring(1));
+                    Fragment f = mFragmentManager.getFragment(bundle, key);
+                    if (f != null) {
+                        while (mFragments.size() <= index) {
+                            mFragments.add(null);
+                        }
+                        f.setMenuVisibility(false);
+                        mFragments.set(index, f);
+                    } else {
+                        Log.w(TAG, "Bad fragment at key " + key);
+                    }
+                }
+            }
+        }
+    }
+    */
+}

+ 756 - 0
src/com/owncloud/android/ui/preview/PreviewMediaFragment.java

@@ -0,0 +1,756 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013 ownCloud Inc. 
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 2 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+package com.owncloud.android.ui.preview;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+import android.accounts.Account;
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.ActivityNotFoundException;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.media.MediaPlayer;
+import android.media.MediaPlayer.OnCompletionListener;
+import android.media.MediaPlayer.OnErrorListener;
+import android.media.MediaPlayer.OnPreparedListener;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.IBinder;
+import android.support.v4.app.FragmentTransaction;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.View.OnTouchListener;
+import android.view.ViewGroup;
+import android.webkit.MimeTypeMap;
+import android.widget.ImageView;
+import android.widget.Toast;
+import android.widget.VideoView;
+
+import com.actionbarsherlock.app.SherlockFragment;
+import com.actionbarsherlock.view.Menu;
+import com.actionbarsherlock.view.MenuInflater;
+import com.actionbarsherlock.view.MenuItem;
+import com.owncloud.android.datamodel.FileDataStorageManager;
+import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.media.MediaControlView;
+import com.owncloud.android.media.MediaService;
+import com.owncloud.android.media.MediaServiceBinder;
+import com.owncloud.android.network.OwnCloudClientUtils;
+import com.owncloud.android.operations.OnRemoteOperationListener;
+import com.owncloud.android.operations.RemoteOperation;
+import com.owncloud.android.operations.RemoteOperationResult;
+import com.owncloud.android.operations.RemoveFileOperation;
+import com.owncloud.android.ui.activity.FileDetailActivity;
+import com.owncloud.android.ui.activity.FileDisplayActivity;
+import com.owncloud.android.ui.fragment.ConfirmationDialogFragment;
+import com.owncloud.android.ui.fragment.FileDetailFragment;
+import com.owncloud.android.ui.fragment.FileFragment;
+
+import com.owncloud.android.R;
+import eu.alefzero.webdav.WebdavClient;
+import eu.alefzero.webdav.WebdavUtils;
+
+/**
+ * This fragment shows a preview of a downloaded media file (audio or video).
+ * 
+ * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
+ * 
+ * By now, if the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
+ * 
+ * @author David A. Velasco
+ */
+public class PreviewMediaFragment extends SherlockFragment implements
+        OnTouchListener , FileFragment,  
+        ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener  {
+
+    public static final String EXTRA_FILE = "FILE";
+    public static final String EXTRA_ACCOUNT = "ACCOUNT";
+    private static final String EXTRA_PLAY_POSITION = "PLAY_POSITION";
+    private static final String EXTRA_PLAYING = "PLAYING";
+
+    private View mView;
+    private OCFile mFile;
+    private Account mAccount;
+    private FileDataStorageManager mStorageManager;
+    private ImageView mImagePreview;
+    private VideoView mVideoPreview;
+    private int mSavedPlaybackPosition;
+    
+    private Handler mHandler;
+    private RemoteOperation mLastRemoteOperation;
+    
+    private MediaServiceBinder mMediaServiceBinder = null;
+    private MediaControlView mMediaController = null;
+    private MediaServiceConnection mMediaServiceConnection = null;
+    private VideoHelper mVideoHelper;
+    private boolean mAutoplay;
+    
+    private static final String TAG = PreviewMediaFragment.class.getSimpleName();
+
+    
+    /**
+     * Creates a fragment to preview a file.
+     * 
+     * When 'fileToDetail' or 'ocAccount' are null
+     * 
+     * @param fileToDetail      An {@link OCFile} to preview in the fragment
+     * @param ocAccount         An ownCloud account; needed to start downloads
+     */
+    public PreviewMediaFragment(OCFile fileToDetail, Account ocAccount) {
+        mFile = fileToDetail;
+        mAccount = ocAccount;
+        mSavedPlaybackPosition = 0;
+        mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment 
+        mAutoplay = true;
+    }
+    
+    
+    /**
+     *  Creates an empty fragment for previews.
+     * 
+     *  MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
+     * 
+     *  DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction 
+     */
+    public PreviewMediaFragment() {
+        mFile = null;
+        mAccount = null;
+        mSavedPlaybackPosition = 0;
+        mStorageManager = null;
+        mAutoplay = true;
+    }
+    
+    
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mHandler = new Handler();
+        setHasOptionsMenu(true);
+    }
+    
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container,
+            Bundle savedInstanceState) {
+        super.onCreateView(inflater, container, savedInstanceState);
+        
+        mView = inflater.inflate(R.layout.file_preview, container, false);
+        
+        mImagePreview = (ImageView)mView.findViewById(R.id.image_preview);
+        mVideoPreview = (VideoView)mView.findViewById(R.id.video_preview);
+        mVideoPreview.setOnTouchListener(this);
+        
+        mMediaController = (MediaControlView)mView.findViewById(R.id.media_controller);
+        
+        return mView;
+    }
+    
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onAttach(Activity activity) {
+        super.onAttach(activity);
+        if (!(activity instanceof FileFragment.ContainerActivity))
+            throw new ClassCastException(activity.toString() + " must implement " + FileFragment.ContainerActivity.class.getSimpleName());
+    }
+    
+    
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onActivityCreated(Bundle savedInstanceState) {
+        super.onActivityCreated(savedInstanceState);
+
+        mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
+        if (savedInstanceState != null) {
+            mFile = savedInstanceState.getParcelable(PreviewMediaFragment.EXTRA_FILE);
+            mAccount = savedInstanceState.getParcelable(PreviewMediaFragment.EXTRA_ACCOUNT);
+            mSavedPlaybackPosition = savedInstanceState.getInt(PreviewMediaFragment.EXTRA_PLAY_POSITION);
+            mAutoplay = savedInstanceState.getBoolean(PreviewMediaFragment.EXTRA_PLAYING);
+            
+        }
+        if (mFile == null) {
+            throw new IllegalStateException("Instanced with a NULL OCFile");
+        }
+        if (mAccount == null) {
+            throw new IllegalStateException("Instanced with a NULL ownCloud Account");
+        }
+        if (!mFile.isDown()) {
+            throw new IllegalStateException("There is no local file to preview");
+        }
+        if (mFile.isVideo()) {
+            mVideoPreview.setVisibility(View.VISIBLE);
+            mImagePreview.setVisibility(View.GONE);
+            prepareVideo();
+            
+        } else {
+            mVideoPreview.setVisibility(View.GONE);
+            mImagePreview.setVisibility(View.VISIBLE);
+        }
+        
+    }
+        
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onSaveInstanceState(Bundle outState) {
+        super.onSaveInstanceState(outState);
+        outState.putParcelable(PreviewMediaFragment.EXTRA_FILE, mFile);
+        outState.putParcelable(PreviewMediaFragment.EXTRA_ACCOUNT, mAccount);
+        
+        if (mFile.isVideo()) {
+            mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
+            mAutoplay = mVideoPreview.isPlaying();
+            outState.putInt(PreviewMediaFragment.EXTRA_PLAY_POSITION , mSavedPlaybackPosition);
+            outState.putBoolean(PreviewMediaFragment.EXTRA_PLAYING , mAutoplay);
+        } else {
+            outState.putInt(PreviewMediaFragment.EXTRA_PLAY_POSITION , mMediaServiceBinder.getCurrentPosition());
+            outState.putBoolean(PreviewMediaFragment.EXTRA_PLAYING , mMediaServiceBinder.isPlaying());
+        }
+    }
+    
+
+    @Override
+    public void onStart() {
+        super.onStart();
+
+        if (mFile != null) {
+           if (mFile.isAudio()) {
+               bindMediaService();
+               
+           } else if (mFile.isVideo()) {
+               stopAudio();
+               playVideo(); 
+           }
+        }
+    }
+    
+    
+    private void stopAudio() {
+        Intent i = new Intent(getSherlockActivity(), MediaService.class);
+        i.setAction(MediaService.ACTION_STOP_ALL);
+        getSherlockActivity().startService(i);
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+        super.onCreateOptionsMenu(menu, inflater);
+
+        inflater.inflate(R.menu.file_actions_menu, menu);
+        List<Integer> toHide = new ArrayList<Integer>();    
+        
+        MenuItem item = null;
+        toHide.add(R.id.action_cancel_download);
+        toHide.add(R.id.action_cancel_upload);
+        toHide.add(R.id.action_download_file);
+        toHide.add(R.id.action_rename_file);    // by now
+
+        for (int i : toHide) {
+            item = menu.findItem(i);
+            if (item != null) {
+                item.setVisible(false);
+                item.setEnabled(false);
+            }
+        }
+        
+    }
+
+    
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public boolean onOptionsItemSelected(MenuItem item) {
+        switch (item.getItemId()) {
+            case R.id.action_open_file_with: {
+                openFile();
+                return true;
+            }
+            case R.id.action_remove_file: {
+                removeFile();
+                return true;
+            }
+            case R.id.action_see_details: {
+                seeDetails();
+                return true;
+            }
+            
+            default:
+                return false;
+        }
+    }
+
+    
+    private void seeDetails() {
+        stopPreview(false);
+        ((FileFragment.ContainerActivity)getActivity()).showFragmentWithDetails(mFile);        
+    }
+
+
+    private void prepareVideo() {
+        // create helper to get more control on the playback
+        mVideoHelper = new VideoHelper();
+        mVideoPreview.setOnPreparedListener(mVideoHelper);
+        mVideoPreview.setOnCompletionListener(mVideoHelper);
+        mVideoPreview.setOnErrorListener(mVideoHelper);
+    }
+    
+    private void playVideo() {
+        // create and prepare control panel for the user
+        mMediaController.setMediaPlayer(mVideoPreview);
+        
+        // load the video file in the video player ; when done, VideoHelper#onPrepared() will be called
+        mVideoPreview.setVideoPath(mFile.getStoragePath()); 
+    }
+    
+
+    private class VideoHelper implements OnCompletionListener, OnPreparedListener, OnErrorListener {
+        
+        /** 
+         * Called when the file is ready to be played.
+         * 
+         * Just starts the playback.
+         * 
+         * @param   mp    {@link MediaPlayer} instance performing the playback.
+         */
+        @Override
+        public void onPrepared(MediaPlayer vp) {
+            Log.e(TAG, "onPrepared");
+            mVideoPreview.seekTo(mSavedPlaybackPosition);
+            if (mAutoplay) { 
+                mVideoPreview.start();
+            }
+            mMediaController.setEnabled(true);
+            mMediaController.updatePausePlay();
+        }
+        
+        
+        /**
+         * Called when the file is finished playing.
+         *  
+         * Finishes the activity.
+         * 
+         * @param   mp    {@link MediaPlayer} instance performing the playback.
+         */
+        @Override
+        public void onCompletion(MediaPlayer  mp) {
+            Log.e(TAG, "completed");
+            if (mp != null) {
+                mVideoPreview.seekTo(0);
+                // next lines are necessary to work around undesired video loops
+                if (Build.VERSION.SDK_INT == Build.VERSION_CODES.GINGERBREAD) {
+                    mVideoPreview.pause();   
+                    
+                } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.GINGERBREAD_MR1) {
+                    // mVideePreview.pause() is not enough
+                    
+                    mMediaController.setEnabled(false);
+                    mVideoPreview.stopPlayback();
+                    mAutoplay = false;
+                    mSavedPlaybackPosition = 0;
+                    mVideoPreview.setVideoPath(mFile.getStoragePath());
+                }
+            } // else : called from onError()
+            mMediaController.updatePausePlay();
+        }
+        
+        
+        /**
+         * Called when an error in playback occurs.
+         * 
+         * @param   mp      {@link MediaPlayer} instance performing the playback.
+         * @param   what    Type of error
+         * @param   extra   Extra code specific to the error
+         */
+        @Override
+        public boolean onError(MediaPlayer mp, int what, int extra) {
+            if (mVideoPreview.getWindowToken() != null) {
+                String message = MediaService.getMessageForMediaError(getActivity(), what, extra);
+                new AlertDialog.Builder(getActivity())
+                        .setMessage(message)
+                        .setPositiveButton(android.R.string.VideoView_error_button,
+                                new DialogInterface.OnClickListener() {
+                                    public void onClick(DialogInterface dialog, int whichButton) {
+                                        dialog.dismiss();
+                                        VideoHelper.this.onCompletion(null);
+                                    }
+                                })
+                        .setCancelable(false)
+                        .show();
+            }
+            return true;
+        }
+        
+    }
+
+    
+    @Override
+    public void onStop() {
+        super.onStop();
+        
+        if (mMediaServiceConnection != null) {
+            Log.d(TAG, "Unbinding from MediaService ...");
+            if (mMediaServiceBinder != null && mMediaController != null) {
+                mMediaServiceBinder.unregisterMediaController(mMediaController);
+            }
+            getActivity().unbindService(mMediaServiceConnection);
+            mMediaServiceConnection = null;
+            mMediaServiceBinder = null;
+        }
+    }
+    
+    @Override
+    public boolean onTouch(View v, MotionEvent event) {
+        if (event.getAction() == MotionEvent.ACTION_DOWN && v == mVideoPreview) {
+            startFullScreenVideo();
+            return true;        
+        }
+        return false;
+    }
+
+    
+    private void startFullScreenVideo() {
+        Intent i = new Intent(getActivity(), PreviewVideoActivity.class);
+        i.putExtra(PreviewVideoActivity.EXTRA_ACCOUNT, mAccount);
+        i.putExtra(PreviewVideoActivity.EXTRA_FILE, mFile);
+        i.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, mVideoPreview.isPlaying());
+        mVideoPreview.pause();
+        i.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, mVideoPreview.getCurrentPosition());
+        startActivityForResult(i, 0);
+    }
+
+    
+    @Override
+    public void onActivityResult (int requestCode, int resultCode, Intent data) {
+        super.onActivityResult(requestCode, resultCode, data);
+        if (resultCode == Activity.RESULT_OK) {
+            mSavedPlaybackPosition = data.getExtras().getInt(PreviewVideoActivity.EXTRA_START_POSITION);
+            mAutoplay = data.getExtras().getBoolean(PreviewVideoActivity.EXTRA_AUTOPLAY); 
+        }
+    }
+    
+
+    private void playAudio() {
+        if (!mMediaServiceBinder.isPlaying(mFile)) {
+            Log.d(TAG, "starting playback of " + mFile.getStoragePath());
+            mMediaServiceBinder.start(mAccount, mFile, mAutoplay, mSavedPlaybackPosition);
+            
+        } else {
+            if (!mMediaServiceBinder.isPlaying() && mAutoplay) {
+                mMediaServiceBinder.start();
+                mMediaController.updatePausePlay();
+            }
+        }
+    }
+
+
+    private void bindMediaService() {
+        Log.d(TAG, "Binding to MediaService...");
+        if (mMediaServiceConnection == null) {
+            mMediaServiceConnection = new MediaServiceConnection();
+        }
+        getActivity().bindService(  new Intent(getActivity(), 
+                                    MediaService.class),
+                                    mMediaServiceConnection, 
+                                    Context.BIND_AUTO_CREATE);
+            // follow the flow in MediaServiceConnection#onServiceConnected(...)
+    }
+    
+    /** Defines callbacks for service binding, passed to bindService() */
+    private class MediaServiceConnection implements ServiceConnection {
+
+        @Override
+        public void onServiceConnected(ComponentName component, IBinder service) {
+            if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
+                Log.d(TAG, "Media service connected");
+                mMediaServiceBinder = (MediaServiceBinder) service;
+                if (mMediaServiceBinder != null) {
+                    prepareMediaController();
+                    playAudio();    // do not wait for the touch of nobody to play audio
+                    
+                    Log.d(TAG, "Successfully bound to MediaService, MediaController ready");
+                    
+                } else {
+                    Log.e(TAG, "Unexpected response from MediaService while binding");
+                }
+            }
+        }
+
+        private void prepareMediaController() {
+            mMediaServiceBinder.registerMediaController(mMediaController);
+            if (mMediaController != null) {
+                mMediaController.setMediaPlayer(mMediaServiceBinder);
+                mMediaController.setEnabled(true);
+                mMediaController.updatePausePlay();
+            }
+        }
+
+        @Override
+        public void onServiceDisconnected(ComponentName component) {
+            if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
+                Log.e(TAG, "Media service suddenly disconnected");
+                if (mMediaController != null) {
+                    mMediaController.setMediaPlayer(null);
+                } else {
+                    Toast.makeText(getActivity(), "No media controller to release when disconnected from media service", Toast.LENGTH_SHORT).show();
+                }
+                mMediaServiceBinder = null;
+                mMediaServiceConnection = null;
+            }
+        }
+    }    
+
+    
+
+    /**
+     * Opens the previewed file with an external application.
+     * 
+     * TODO - improve this; instead of prioritize the actions available for the MIME type in the server, 
+     * we should get a list of available apps for MIME tpye in the server and join it with the list of 
+     * available apps for the MIME type known from the file extension, to let the user choose
+     */
+    private void openFile() {
+        stopPreview(true);
+        String storagePath = mFile.getStoragePath();
+        String encodedStoragePath = WebdavUtils.encodePath(storagePath);
+        try {
+            Intent i = new Intent(Intent.ACTION_VIEW);
+            i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
+            i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
+            startActivity(i);
+            
+        } catch (Throwable t) {
+            Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
+            boolean toastIt = true; 
+            String mimeType = "";
+            try {
+                Intent i = new Intent(Intent.ACTION_VIEW);
+                mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
+                if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
+                    if (mimeType != null) {
+                        i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
+                    } else {
+                        // desperate try
+                        i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*-/*");
+                    }
+                    i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
+                    startActivity(i);
+                    toastIt = false;
+                }
+                
+            } catch (IndexOutOfBoundsException e) {
+                Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
+                
+            } catch (ActivityNotFoundException e) {
+                Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
+                
+            } catch (Throwable th) {
+                Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
+                
+            } finally {
+                if (toastIt) {
+                    Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
+                }
+            }
+            
+        }
+        finish();
+    }
+    
+    /**
+     * Starts a the removal of the previewed file.
+     * 
+     * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
+     * depending upon the user selection in the dialog. 
+     */
+    private void removeFile() {
+        ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
+                R.string.confirmation_remove_alert,
+                new String[]{mFile.getFileName()},
+                R.string.confirmation_remove_remote_and_local,
+                R.string.confirmation_remove_local,
+                R.string.common_cancel);
+        confDialog.setOnConfirmationListener(this);
+        confDialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
+    }
+
+    
+    /**
+     * Performs the removal of the previewed file, both locally and in the server.
+     */
+    @Override
+    public void onConfirmation(String callerTag) {
+        if (mStorageManager.getFileById(mFile.getFileId()) != null) {   // check that the file is still there;
+            stopPreview(true);
+            mLastRemoteOperation = new RemoveFileOperation( mFile,      // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
+                                                            true, 
+                                                            mStorageManager);
+            WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
+            mLastRemoteOperation.execute(wc, this, mHandler);
+            
+            boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
+            getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
+        }
+    }
+    
+    
+    /**
+     * Removes the file from local storage
+     */
+    @Override
+    public void onNeutral(String callerTag) {
+        // TODO this code should be made in a secondary thread,
+        if (mFile.isDown()) {   // checks it is still there
+            stopPreview(true);
+            File f = new File(mFile.getStoragePath());
+            f.delete();
+            mFile.setStoragePath(null);
+            mStorageManager.saveFile(mFile);
+            finish();
+        }
+    }
+    
+    /**
+     * User cancelled the removal action.
+     */
+    @Override
+    public void onCancel(String callerTag) {
+        // nothing to do here
+    }
+    
+
+    /**
+     * {@inheritDoc}
+     */
+    public OCFile getFile(){
+        return mFile;
+    }
+    
+    /*
+    /**
+     * Use this method to signal this Activity that it shall update its view.
+     * 
+     * @param file : An {@link OCFile}
+     *-/
+    public void updateFileDetails(OCFile file, Account ocAccount) {
+        mFile = file;
+        if (ocAccount != null && ( 
+                mStorageManager == null || 
+                (mAccount != null && !mAccount.equals(ocAccount))
+           )) {
+            mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
+        }
+        mAccount = ocAccount;
+        updateFileDetails(false);
+    }
+    */
+    
+
+    /**
+     * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewMediaFragment} to be previewed.
+     * 
+     * @param file      File to test if can be previewed.
+     * @return          'True' if the file can be handled by the fragment.
+     */
+    public static boolean canBePreviewed(OCFile file) {
+        return (file != null && (file.isAudio() || file.isVideo()));
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
+        if (operation.equals(mLastRemoteOperation)) {
+            if (operation instanceof RemoveFileOperation) {
+                onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
+            }
+        }
+    }
+    
+    private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
+        boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
+        getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
+        
+        if (result.isSuccess()) {
+            Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
+            msg.show();
+            finish();
+                
+        } else {
+            Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG); 
+            msg.show();
+            if (result.isSslRecoverableException()) {
+                // TODO show the SSL warning dialog
+            }
+        }
+    }
+
+    private void stopPreview(boolean stopAudio) {
+        if (mFile.isAudio() && stopAudio) {
+            mMediaServiceBinder.pause();
+            
+        } else if (mFile.isVideo()) {
+            mVideoPreview.stopPlayback();
+        }
+    }
+
+
+
+    /**
+     * Finishes the preview
+     */
+    private void finish() {
+        Activity container = getActivity();
+        if (container instanceof FileDisplayActivity) {
+            // double pane
+            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
+            transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
+            transaction.commit();
+            ((FileFragment.ContainerActivity)container).onFileStateChanged();
+        } else {
+            container.finish();
+        }
+    }
+    
+}

+ 283 - 0
src/com/owncloud/android/ui/preview/PreviewVideoActivity.java

@@ -0,0 +1,283 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013 ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 2 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.ui.preview;
+
+import android.accounts.Account;
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.media.MediaPlayer;
+import android.media.MediaPlayer.OnCompletionListener;
+import android.media.MediaPlayer.OnErrorListener;
+import android.media.MediaPlayer.OnPreparedListener;
+import android.net.Uri;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.MotionEvent;
+import android.widget.MediaController;
+import android.widget.VideoView;
+
+import com.owncloud.android.AccountUtils;
+import com.owncloud.android.R;
+import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.media.MediaService;
+
+/**
+ *  Activity implementing a basic video player.
+ * 
+ *  Used as an utility to preview video files contained in an ownCloud account.
+ *  
+ *  Currently, it always plays in landscape mode, full screen. When the playback ends,
+ *  the activity is finished. 
+ *  
+ *  @author David A. Velasco
+ */
+public class PreviewVideoActivity extends Activity implements OnCompletionListener, OnPreparedListener, OnErrorListener {
+
+    /** Key to receive an {@link OCFile} to play as an extra value in an {@link Intent} */
+    public static final String EXTRA_FILE = "FILE";
+    
+    /** Key to receive the ownCloud {@link Account} where the file to play is saved as an extra value in an {@link Intent} */
+    public static final String EXTRA_ACCOUNT = "ACCOUNT";
+    
+    /** Key to receive a flag signaling if the video should be started immediately */
+    public static final String EXTRA_AUTOPLAY = "AUTOPLAY";
+    
+    /** Key to receive the position of the playback where the video should be put at start */
+    public static final String EXTRA_START_POSITION = "START_POSITION";
+    
+    private static final String TAG = PreviewVideoActivity.class.getSimpleName();
+
+    private OCFile mFile;                       // video file to play
+    private Account mAccount;                   // ownCloud account holding mFile
+    private int mSavedPlaybackPosition;         // in the unit time handled by MediaPlayer.getCurrentPosition()
+    private boolean mAutoplay;                  // when 'true', the playback starts immediately with the activity
+    private VideoView mVideoPlayer;             // view to play the file; both performs and show the playback
+    private MediaController mMediaController;   // panel control used by the user to control the playback
+          
+    /** 
+     *  Called when the activity is first created.
+     *  
+     *  Searches for an {@link OCFile} and ownCloud {@link Account} holding it in the starting {@link Intent}.
+     *  
+     *  The {@link Account} is unnecessary if the file is downloaded; else, the {@link Account} is used to 
+     *  try to stream the remote file - TODO get the streaming works
+     * 
+     *  {@inheritDoc}
+     */
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        Log.e(TAG, "ACTIVITY\t\tonCreate");
+        
+        setContentView(R.layout.video_layout);
+    
+        if (savedInstanceState == null) {
+            Bundle extras = getIntent().getExtras();
+            mFile = extras.getParcelable(EXTRA_FILE);
+            mAccount = extras.getParcelable(EXTRA_ACCOUNT);
+            mSavedPlaybackPosition = extras.getInt(EXTRA_START_POSITION);
+            mAutoplay = extras.getBoolean(EXTRA_AUTOPLAY);
+            
+        } else {
+            mFile = savedInstanceState.getParcelable(EXTRA_FILE);
+            mAccount = savedInstanceState.getParcelable(EXTRA_ACCOUNT);
+            mSavedPlaybackPosition = savedInstanceState.getInt(EXTRA_START_POSITION);
+            mAutoplay = savedInstanceState.getBoolean(EXTRA_AUTOPLAY);
+        }
+          
+        mVideoPlayer = (VideoView) findViewById(R.id.videoPlayer);
+
+        // set listeners to get more contol on the playback
+        mVideoPlayer.setOnPreparedListener(this);
+        mVideoPlayer.setOnCompletionListener(this);
+        mVideoPlayer.setOnErrorListener(this);
+          
+        // keep the screen on while the playback is performed (prevents screen off by battery save)
+        mVideoPlayer.setKeepScreenOn(true);
+        
+        if (mFile != null) {
+            if (mFile.isDown()) {
+                mVideoPlayer.setVideoPath(mFile.getStoragePath());
+                
+            } else if (mAccount != null) {
+                // not working now
+                String url = AccountUtils.constructFullURLForAccount(this, mAccount) + mFile.getRemotePath();
+                mVideoPlayer.setVideoURI(Uri.parse(url));
+                
+            } else {
+                onError(null, MediaService.OC_MEDIA_ERROR, R.string.media_err_no_account);
+            }
+            
+            // create and prepare control panel for the user
+            mMediaController = new MediaController(this);
+            mMediaController.setMediaPlayer(mVideoPlayer);
+            mMediaController.setAnchorView(mVideoPlayer);
+            mVideoPlayer.setMediaController(mMediaController);
+            
+        } else {
+            onError(null, MediaService.OC_MEDIA_ERROR, R.string.media_err_nothing_to_play);
+        }
+    }    
+    
+    
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void onSaveInstanceState(Bundle outState) {
+        super.onSaveInstanceState(outState);
+        Log.e(TAG, "ACTIVITY\t\tonSaveInstanceState");
+        outState.putParcelable(PreviewVideoActivity.EXTRA_FILE, mFile);
+        outState.putParcelable(PreviewVideoActivity.EXTRA_ACCOUNT, mAccount);
+        outState.putInt(PreviewVideoActivity.EXTRA_START_POSITION, mVideoPlayer.getCurrentPosition());
+        outState.putBoolean(PreviewVideoActivity.EXTRA_AUTOPLAY , mVideoPlayer.isPlaying());
+    }
+
+    
+    @Override
+    public void onBackPressed() {
+        Log.e(TAG, "ACTIVTIY\t\tonBackPressed");
+        Intent i = new Intent();
+        i.putExtra(EXTRA_AUTOPLAY, mVideoPlayer.isPlaying());
+        i.putExtra(EXTRA_START_POSITION, mVideoPlayer.getCurrentPosition());
+        setResult(RESULT_OK, i);
+        super.onBackPressed();
+    }
+
+    
+    @Override
+    public void onResume() {
+        super.onResume();
+        Log.e(TAG, "ACTIVTIY\t\tonResume");
+    }
+
+    
+    @Override
+    public void onStart() {
+        super.onStart();
+        Log.e(TAG, "ACTIVTIY\t\tonStart");
+    }
+    
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        Log.e(TAG, "ACTIVITY\t\tonDestroy");
+    }
+    
+    @Override
+    public void onStop() {
+        super.onStop();
+        Log.e(TAG, "ACTIVTIY\t\tonStop");
+    }
+    
+    
+    @Override
+    public void onPause() {
+        super.onPause();
+        Log.e(TAG, "ACTIVTIY\t\tonPause");
+    }
+    
+    
+    /** 
+     * Called when the file is ready to be played.
+     * 
+     * Just starts the playback.
+     * 
+     * @param   mp    {@link MediaPlayer} instance performing the playback.
+     */
+    @Override
+    public void onPrepared(MediaPlayer mp) {
+        Log.e(TAG, "ACTIVITY\t\tonPrepare");
+        mVideoPlayer.seekTo(mSavedPlaybackPosition);
+        if (mAutoplay) { 
+            mVideoPlayer.start();
+        }
+        mMediaController.show(5000);  
+    }
+    
+    
+    /**
+     * Called when the file is finished playing.
+     *  
+     * Rewinds the video
+     * 
+     * @param   mp    {@link MediaPlayer} instance performing the playback.
+     */
+    @Override
+    public void onCompletion(MediaPlayer  mp) {
+        mVideoPlayer.seekTo(0);
+    }
+    
+    
+    /**
+     * Called when an error in playback occurs.
+     * 
+     * @param   mp      {@link MediaPlayer} instance performing the playback.
+     * @param   what    Type of error
+     * @param   extra   Extra code specific to the error
+     */
+    @Override
+    public boolean onError(MediaPlayer mp, int what, int extra) {
+        Log.e(TAG, "Error in video playback, what = " + what + ", extra = " + extra);
+        
+        if (mMediaController != null) {
+            mMediaController.hide();
+        }
+        
+        if (mVideoPlayer.getWindowToken() != null) {
+            String message = MediaService.getMessageForMediaError(this, what, extra);
+            new AlertDialog.Builder(this)
+                    .setMessage(message)
+                    .setPositiveButton(android.R.string.VideoView_error_button,
+                            new DialogInterface.OnClickListener() {
+                                public void onClick(DialogInterface dialog, int whichButton) {
+                                    PreviewVideoActivity.this.onCompletion(null);
+                                }
+                            })
+                    .setCancelable(false)
+                    .show();
+        }
+        return true;
+    }
+    
+    
+    /**  
+     * Screen touches trigger the appearance of the control panel for a limited time.
+     *
+     * {@inheritDoc}
+     */
+    @Override
+    public boolean onTouchEvent (MotionEvent ev){ 
+        /*if (ev.getAction() == MotionEvent.ACTION_DOWN) {
+            if (mMediaController.isShowing()) {
+                mMediaController.hide();
+            } else {
+                mMediaController.show(MediaService.MEDIA_CONTROL_SHORT_LIFE);
+            }
+            return true;        
+        } else {
+            return false;
+        }*/
+        return false;
+    }
+
+
+}

+ 23 - 10
src/eu/alefzero/webdav/ChunkFromFileChannelRequestEntity.java

@@ -30,6 +30,8 @@ import java.util.Set;
 
 import org.apache.commons.httpclient.methods.RequestEntity;
 
+import com.owncloud.android.network.ProgressiveDataTransferer;
+
 import eu.alefzero.webdav.OnDatatransferProgressListener;
 
 import android.util.Log;
@@ -40,7 +42,7 @@ import android.util.Log;
  * 
  * @author David A. Velasco
  */
-public class ChunkFromFileChannelRequestEntity implements RequestEntity {
+public class ChunkFromFileChannelRequestEntity implements RequestEntity, ProgressiveDataTransferer {
 
     private static final String TAG = ChunkFromFileChannelRequestEntity.class.getSimpleName();
     
@@ -90,16 +92,25 @@ public class ChunkFromFileChannelRequestEntity implements RequestEntity {
         return true;
     }
     
-    public void addOnDatatransferProgressListener(OnDatatransferProgressListener listener) {
-        mDataTransferListeners.add(listener);
+    @Override
+    public void addDatatransferProgressListener(OnDatatransferProgressListener listener) {
+        synchronized (mDataTransferListeners) {
+            mDataTransferListeners.add(listener);
+        }
     }
     
-    public void addOnDatatransferProgressListeners(Collection<OnDatatransferProgressListener> listeners) {
-        mDataTransferListeners.addAll(listeners);
+    @Override
+    public void addDatatransferProgressListeners(Collection<OnDatatransferProgressListener> listeners) {
+        synchronized (mDataTransferListeners) {
+            mDataTransferListeners.addAll(listeners);
+        }
     }
     
-    public void removeOnDatatransferProgressListener(OnDatatransferProgressListener listener) {
-        mDataTransferListeners.remove(listener);
+    @Override
+    public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
+        synchronized (mDataTransferListeners) {
+            mDataTransferListeners.remove(listener);
+        }
     }
     
     
@@ -116,9 +127,11 @@ public class ChunkFromFileChannelRequestEntity implements RequestEntity {
                 out.write(mBuffer.array(), 0, readCount);
                 mBuffer.clear();
                 mTransferred += readCount;
-                it = mDataTransferListeners.iterator();
-                while (it.hasNext()) {
-                    it.next().onTransferProgress(readCount, mTransferred, size, mFile.getName());
+                synchronized (mDataTransferListeners) {
+                    it = mDataTransferListeners.iterator();
+                    while (it.hasNext()) {
+                        it.next().onTransferProgress(readCount, mTransferred, size, mFile.getName());
+                    }
                 }
             }
             

+ 24 - 11
src/eu/alefzero/webdav/FileRequestEntity.java

@@ -32,6 +32,8 @@ import java.util.Set;
 
 import org.apache.commons.httpclient.methods.RequestEntity;
 
+import com.owncloud.android.network.ProgressiveDataTransferer;
+
 import eu.alefzero.webdav.OnDatatransferProgressListener;
 
 import android.util.Log;
@@ -41,7 +43,7 @@ import android.util.Log;
  * A RequestEntity that represents a File.
  * 
  */
-public class FileRequestEntity implements RequestEntity {
+public class FileRequestEntity implements RequestEntity, ProgressiveDataTransferer {
 
     final File mFile;
     final String mContentType;
@@ -70,17 +72,26 @@ public class FileRequestEntity implements RequestEntity {
     public boolean isRepeatable() {
         return true;
     }
-    
-    public void addOnDatatransferProgressListener(OnDatatransferProgressListener listener) {
-        mDataTransferListeners.add(listener);
+
+    @Override
+    public void addDatatransferProgressListener(OnDatatransferProgressListener listener) {
+        synchronized (mDataTransferListeners) {
+            mDataTransferListeners.add(listener);
+        }
     }
     
-    public void addOnDatatransferProgressListeners(Collection<OnDatatransferProgressListener> listeners) {
-        mDataTransferListeners.addAll(listeners);
+    @Override
+    public void addDatatransferProgressListeners(Collection<OnDatatransferProgressListener> listeners) {
+        synchronized (mDataTransferListeners) {
+            mDataTransferListeners.addAll(listeners);
+        }
     }
     
-    public void removeOnDatatransferProgressListener(OnDatatransferProgressListener listener) {
-        mDataTransferListeners.remove(listener);
+    @Override
+    public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
+        synchronized (mDataTransferListeners) {
+            mDataTransferListeners.remove(listener);
+        }
     }
     
     
@@ -103,9 +114,11 @@ public class FileRequestEntity implements RequestEntity {
                 out.write(tmp.array(), 0, readResult);
                 tmp.clear();
                 transferred += readResult;
-                it = mDataTransferListeners.iterator();
-                while (it.hasNext()) {
-                    it.next().onTransferProgress(readResult, transferred, size, mFile.getName());
+                synchronized (mDataTransferListeners) {
+                    it = mDataTransferListeners.iterator();
+                    while (it.hasNext()) {
+                        it.next().onTransferProgress(readResult, transferred, size, mFile.getName());
+                    }
                 }
             }
             

+ 1 - 1
src/eu/alefzero/webdav/WebdavClient.java

@@ -166,7 +166,7 @@ public class WebdavClient extends HttpClient {
         try {
             File f = new File(localFile);
             FileRequestEntity entity = new FileRequestEntity(f, contentType);
-            entity.addOnDatatransferProgressListener(mDataTransferListener);
+            entity.addDatatransferProgressListener(mDataTransferListener);
             put.setRequestEntity(entity);
             status = executeMethod(put);