Browse Source

Merge pull request #180 from owncloud/direct_download_with_click_at_list

Direct download with click at list
masensio 11 years ago
parent
commit
cf0c96b200
30 changed files with 895 additions and 1582 deletions
  1. 1 2
      AndroidManifest.xml
  2. BIN
      res/drawable/btn_cancel.png
  3. 0 50
      res/layout-large-land/files.xml
  4. 2 2
      res/layout/file_details_empty.xml
  5. 8 5
      res/layout/file_details_fragment.xml
  6. 29 15
      res/layout/file_download_fragment.xml
  7. 20 14
      res/layout/files.xml
  8. 4 3
      res/layout/list_fragment.xml
  9. 1 1
      res/menu/file_actions_menu.xml
  10. 22 0
      res/values-large-land/bools.xml
  11. 0 4
      res/values-large/bools.xml
  12. 1 1
      res/values/bools.xml
  13. 1 1
      res/values/strings.xml
  14. 8 6
      src/com/owncloud/android/AccountUtils.java
  15. 30 0
      src/com/owncloud/android/files/FileHandler.java
  16. 3 3
      src/com/owncloud/android/files/services/FileDownloader.java
  17. 3 5
      src/com/owncloud/android/files/services/FileUploader.java
  18. 3 3
      src/com/owncloud/android/media/MediaService.java
  19. 89 25
      src/com/owncloud/android/ui/activity/FileActivity.java
  20. 0 481
      src/com/owncloud/android/ui/activity/FileDetailActivity.java
  21. 366 344
      src/com/owncloud/android/ui/activity/FileDisplayActivity.java
  22. 39 21
      src/com/owncloud/android/ui/fragment/ExtendedListFragment.java
  23. 81 263
      src/com/owncloud/android/ui/fragment/FileDetailFragment.java
  24. 33 5
      src/com/owncloud/android/ui/fragment/FileFragment.java
  25. 1 20
      src/com/owncloud/android/ui/fragment/LocalFileListFragment.java
  26. 57 114
      src/com/owncloud/android/ui/fragment/OCFileListFragment.java
  27. 14 28
      src/com/owncloud/android/ui/preview/FileDownloadFragment.java
  28. 10 12
      src/com/owncloud/android/ui/preview/PreviewImageActivity.java
  29. 25 76
      src/com/owncloud/android/ui/preview/PreviewImageFragment.java
  30. 44 78
      src/com/owncloud/android/ui/preview/PreviewMediaFragment.java

+ 1 - 2
AndroidManifest.xml

@@ -50,7 +50,7 @@
         <activity
             android:name=".ui.activity.FileDisplayActivity"
             android:label="@string/app_name"
-            android:configChanges="orientation|screenSize">
+            >
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
 
@@ -151,7 +151,6 @@
         <service android:name=".files.services.FileUploader" />
         <service android:name=".media.MediaService" />
         
-        <activity android:name=".ui.activity.FileDetailActivity" android:configChanges="orientation|screenSize"/>
         <activity android:name=".ui.activity.PinCodeActivity" />
         <activity android:name=".extensions.ExtensionsAvailableActivity"></activity>
         <activity android:name=".extensions.ExtensionsListActivity"></activity>

BIN
res/drawable/btn_cancel.png


+ 0 - 50
res/layout-large-land/files.xml

@@ -1,50 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ownCloud Android client application
-
-  Copyright (C) 2011  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 version 2,
-  as published by the Free Software Foundation.
-
-  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="fill_parent"
-    android:layout_height="fill_parent"
-    android:background="@color/owncloud_white"
-    android:orientation="horizontal" >
-
-    <LinearLayout
-        android:id="@+id/file_list_container"
-        android:layout_width="0dp"
-        android:layout_height="fill_parent"
-        android:layout_weight="1" >
-
-        <fragment
-            android:id="@+id/fileList"
-            android:layout_width="fill_parent"
-            android:layout_height="fill_parent"
-            class="com.owncloud.android.ui.fragment.OCFileListFragment" >
-
-            <!-- Preview: layout=@layout/list_layout -->
-        </fragment>
-    </LinearLayout>
-
-    <LinearLayout android:id="@+id/file_details_container"
-        android:layout_width="0dp"
-        android:layout_height="fill_parent"
-        android:layout_weight="2" >
-
-        <!-- Preview: layout=@layout/file_details_empty -->
-    </LinearLayout>
-
-</LinearLayout>

+ 2 - 2
res/layout/file_details_empty.xml

@@ -18,8 +18,8 @@
   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="fill_parent"
-    android:layout_height="fill_parent"
+	android:layout_width="match_parent"
+	android:layout_height="match_parent"
     android:background="#F7F7F7"
     android:orientation="vertical" >
 

+ 8 - 5
res/layout/file_details_fragment.xml

@@ -19,8 +19,9 @@
 -->
 <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:layout_width="match_parent"
+	android:layout_height="match_parent"
+	>
 
 	<RelativeLayout
 		android:layout_width="match_parent"
@@ -182,7 +183,7 @@
 			        android:id="@+id/fdProgressBlock"
 					android:layout_width="match_parent"
 					android:layout_height="wrap_content"
-					android:gravity="center_horizontal"
+					android:gravity="center"
 					android:layout_marginTop="12dp"
 					android:layout_marginBottom="12dp"
 					android:orientation="horizontal"
@@ -198,12 +199,14 @@
 						android:indeterminateOnly="false" 
 					/>
 				    								
-					<Button
+					<ImageButton
 						android:id="@+id/fdCancelBtn"
 						android:layout_width="wrap_content"
 						android:layout_height="wrap_content"
 						android:layout_marginLeft="12dp"
-						android:text="@string/common_cancel" />
+						android:src="@drawable/btn_cancel"
+						android:background="@android:color/transparent"
+						/>
 						
 				</LinearLayout>
 	

+ 29 - 15
res/layout/file_download_fragment.xml

@@ -32,23 +32,37 @@
 		android:layout_marginBottom="15dp"
 	/>
 	
-	<ProgressBar android:id="@+id/progressBar"
-		android:layout_width="match_parent" 
+    <LinearLayout
+        android:id="@+id/fdProgressBlock"
+		android:layout_width="match_parent"
 		android:layout_height="wrap_content"
-		android:progressDrawable="@android:drawable/progress_horizontal"
-		android:indeterminate="false" 
-		android:indeterminateOnly="false" 
+		android:gravity="center"
+		android:layout_marginTop="12dp"
 		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"
-	/>
-	
+		android:orientation="horizontal"
+		>
+	    				
+		<ProgressBar android:id="@+id/progressBar"
+			android:layout_width="0dp" 
+			android:layout_height="wrap_content"
+			android:layout_weight="1"
+			android:progressDrawable="@android:drawable/progress_horizontal"
+			android:indeterminate="false" 
+			android:indeterminateOnly="false" 
+			
+		/>
+
+		<ImageButton
+			android:id="@+id/cancelBtn"
+			android:layout_width="wrap_content"
+			android:layout_height="wrap_content"
+			android:layout_marginLeft="12dp"
+			android:src="@drawable/btn_cancel"
+			android:background="@android:color/transparent"
+		/>
+
+	</LinearLayout>
+			
 	<ImageView
 		android:id="@+id/error_image"
 		android:layout_width="wrap_content"

+ 20 - 14
res/layout/files.xml

@@ -18,19 +18,25 @@
   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="fill_parent"
-    android:layout_height="fill_parent"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
     android:background="@color/owncloud_white"
-    android:orientation="vertical"
-    android:id="@+id/file_list_view">
+    android:orientation="horizontal"
+    android:baselineAligned="false"
+    >
 
-    <fragment
-        android:id="@+id/fileList"
-        android:layout_width="fill_parent"
-        android:layout_height="fill_parent"
-        class="com.owncloud.android.ui.fragment.OCFileListFragment" >
-
-        <!-- Preview: layout=@layout/list_layout -->
-    </fragment>
-
-</LinearLayout>
+	<FrameLayout 
+		android:layout_width="0dp"
+		android:layout_height="match_parent"
+		android:layout_weight="1"
+		android:id="@+id/left_fragment_container"
+	    />
+	
+	<FrameLayout 
+		android:layout_width="0dp"
+		android:layout_height="match_parent"
+		android:layout_weight="2"
+		android:id="@+id/right_fragment_container"
+	    />
+	
+ </LinearLayout>

+ 4 - 3
res/layout/list_fragment.xml

@@ -18,9 +18,10 @@
   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="fill_parent"
-    android:layout_height="fill_parent"
-    android:orientation="vertical" >
+	android:layout_width="0dp"
+	android:layout_height="match_parent"
+	android:layout_weight="1"
+	android:orientation="vertical" >
 
 	<com.owncloud.android.ui.ExtendedListView
         android:id="@+id/list_root"

+ 1 - 1
res/menu/file_actions_menu.xml

@@ -19,7 +19,7 @@
 -->
 <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_open_file_with"			android:title="@string/actionbar_open_with"			android:icon="@android:drawable/ic_menu_edit"					android:orderInCategory="1" />
 	<item 	android:id="@+id/action_download_file" 			android:title="@string/filedetails_download"		android:icon="@drawable/ic_action_download"						android:orderInCategory="1" />
     <item 	android:id="@+id/action_sync_file"				android:title="@string/filedetails_sync_file"		android:icon="@drawable/ic_action_refresh"						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" />

+ 22 - 0
res/values-large-land/bools.xml

@@ -0,0 +1,22 @@
+<?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 version 2,
+  as published by the Free Software Foundation.
+
+  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/>.
+-->
+<!-- Large screen, landscape orientation boolean values -->
+<resources>
+    <bool name="large_land_layout">true</bool>
+</resources>

+ 0 - 4
res/values-large/bools.xml

@@ -1,4 +0,0 @@
-<!-- Large screen boolean values -->
-<resources>
-    <bool name="large_layout">true</bool>
-</resources>

+ 1 - 1
res/values/bools.xml

@@ -18,5 +18,5 @@
 -->
 <!-- Default boolean values -->
 <resources>
-    <bool name="large_layout">false</bool>
+    <bool name="large_land_layout">false</bool>
 </resources>

+ 1 - 1
res/values/strings.xml

@@ -20,6 +20,7 @@
     <string name="actionbar_upload">Upload</string>
     <string name="actionbar_upload_from_apps">Content from other apps</string>
     <string name="actionbar_upload_files">Files</string>
+    <string name="actionbar_open_with">Open with</string>
     <string name="actionbar_mkdir">Create directory</string>
     <string name="actionbar_search">Search</string>
     <string name="actionbar_settings">Settings</string>
@@ -81,7 +82,6 @@
     <string name="filedetails_download">Download</string>
     <string name="filedetails_sync_file">Refresh</string>
     <string name="filedetails_redownload">Redownload</string>
-    <string name="filedetails_open">Open</string>
     <string name="filedetails_renamed_in_upload_msg">File was renamed to %1$s during upload</string>
     <string name="common_yes">Yes</string>
     <string name="common_no">No</string>

+ 8 - 6
src/com/owncloud/android/AccountUtils.java

@@ -37,12 +37,13 @@ public class AccountUtils {
     public static final String STATUS_PATH = "/status.php";
 
     /**
-     * Can be used to get the currently selected ownCloud account in the
-     * preferences
+     * Can be used to get the currently selected ownCloud {@link Account} in the
+     * application preferences.
      * 
-     * @param context The current appContext
-     * @return The current account or first available, if none is available,
-     *         then null.
+     * @param   context     The current application {@link Context}
+     * @return              The ownCloud {@link Account} currently saved in preferences, or the first 
+     *                      {@link Account} available, if valid (still registered in the system as ownCloud 
+     *                      account). If none is available and valid, returns null.
      */
     public static Account getCurrentOwnCloudAccount(Context context) {
         Account[] ocAccounts = AccountManager.get(context).getAccountsByType(
@@ -54,6 +55,7 @@ public class AccountUtils {
         String accountName = appPreferences
                 .getString("select_oc_account", null);
 
+        // account validation: the saved account MUST be in the list of ownCloud Accounts known by the AccountManager
         if (accountName != null) {
             for (Account account : ocAccounts) {
                 if (account.name.equals(accountName)) {
@@ -64,7 +66,7 @@ public class AccountUtils {
         }
         
         if (defaultAccount == null && ocAccounts.length != 0) {
-            // we at least need to take first account as fallback
+            // take first account as fallback
             defaultAccount = ocAccounts[0];
         }
 

+ 30 - 0
src/com/owncloud/android/files/FileHandler.java

@@ -0,0 +1,30 @@
+/* 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 version 2,
+ *   as published by the Free Software Foundation.
+ *
+ *   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.files;
+
+import com.owncloud.android.datamodel.OCFile;
+
+public interface FileHandler {
+
+    /**
+     * TODO
+     */
+    public void openFile(OCFile file);
+
+    
+}

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

@@ -38,7 +38,7 @@ import com.owncloud.android.operations.DownloadFileOperation;
 import com.owncloud.android.operations.RemoteOperationResult;
 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
 import com.owncloud.android.ui.activity.FileActivity;
-import com.owncloud.android.ui.activity.FileDetailActivity;
+import com.owncloud.android.ui.activity.FileDisplayActivity;
 import com.owncloud.android.ui.preview.PreviewImageActivity;
 import com.owncloud.android.ui.preview.PreviewImageFragment;
 
@@ -414,7 +414,7 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
         if (PreviewImageFragment.canBePreviewed(download.getFile())) {
             showDetailsIntent = new Intent(this, PreviewImageActivity.class);
         } else {
-            showDetailsIntent = new Intent(this, FileDetailActivity.class);
+            showDetailsIntent = new Intent(this, FileDisplayActivity.class);
         }
         showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, download.getFile());
         showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, download.getAccount());
@@ -485,7 +485,7 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
                     if (PreviewImageFragment.canBePreviewed(download.getFile())) {
                         showDetailsIntent = new Intent(this, PreviewImageActivity.class);
                     } else {
-                        showDetailsIntent = new Intent(this, FileDetailActivity.class);
+                        showDetailsIntent = new Intent(this, FileDisplayActivity.class);
                     }
                     showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, download.getFile());
                     showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, download.getAccount());

+ 3 - 5
src/com/owncloud/android/files/services/FileUploader.java

@@ -42,7 +42,6 @@ import com.owncloud.android.operations.RemoteOperation;
 import com.owncloud.android.operations.RemoteOperationResult;
 import com.owncloud.android.operations.UploadFileOperation;
 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
-import com.owncloud.android.ui.activity.FileDetailActivity;
 import com.owncloud.android.utils.OwnCloudVersion;
 
 import eu.alefzero.webdav.OnDatatransferProgressListener;
@@ -74,6 +73,7 @@ import com.owncloud.android.R;
 import com.owncloud.android.db.DbHandler;
 import com.owncloud.android.ui.activity.FailedUploadActivity;
 import com.owncloud.android.ui.activity.FileActivity;
+import com.owncloud.android.ui.activity.FileDisplayActivity;
 import com.owncloud.android.ui.activity.InstantUploadActivity;
 import com.owncloud.android.ui.preview.PreviewImageActivity;
 import com.owncloud.android.ui.preview.PreviewImageFragment;
@@ -703,8 +703,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
         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 = new Intent(this, FileDisplayActivity.class);
         }
         showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
         showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
@@ -766,8 +765,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
             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 = new Intent(this, FileDisplayActivity.class); 
             }
             showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
             showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());

+ 3 - 3
src/com/owncloud/android/media/MediaService.java

@@ -41,7 +41,7 @@ import com.owncloud.android.Log_OC;
 import com.owncloud.android.R;
 import com.owncloud.android.datamodel.OCFile;
 import com.owncloud.android.ui.activity.FileActivity;
-import com.owncloud.android.ui.activity.FileDetailActivity;
+import com.owncloud.android.ui.activity.FileDisplayActivity;
 
 /**
  * Service that handles media playback, both audio and video. 
@@ -532,7 +532,7 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
     @SuppressWarnings("deprecation")
     private void updateNotification(String content) {
         // TODO check if updating the Intent is really necessary
-        Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
+        Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
         showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, mFile);
         showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, mAccount);
         showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
@@ -569,7 +569,7 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
 
         
         /// includes a pending intent in the notification showing the details view of the file
-        Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
+        Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
         showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, mFile);
         showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, mAccount);
         showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

+ 89 - 25
src/com/owncloud/android/ui/activity/FileActivity.java

@@ -23,14 +23,20 @@ import android.accounts.AccountManager;
 import android.accounts.AccountManagerCallback;
 import android.accounts.AccountManagerFuture;
 import android.accounts.OperationCanceledException;
+import android.content.Intent;
+import android.net.Uri;
 import android.os.Bundle;
+import android.webkit.MimeTypeMap;
 
 import com.actionbarsherlock.app.SherlockFragmentActivity;
 import com.owncloud.android.AccountUtils;
 import com.owncloud.android.Log_OC;
+import com.owncloud.android.R;
 import com.owncloud.android.authentication.AccountAuthenticator;
 import com.owncloud.android.datamodel.OCFile;
 
+import eu.alefzero.webdav.WebdavUtils;
+
 /**
  * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
  * 
@@ -40,6 +46,7 @@ public abstract class FileActivity extends SherlockFragmentActivity {
 
     public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
     public static final String EXTRA_ACCOUNT = "com.owncloud.android.ui.activity.ACCOUNT";
+    public static final String EXTRA_WAITING_TO_PREVIEW = "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
     
     public static final String TAG = FileActivity.class.getSimpleName(); 
     
@@ -52,13 +59,19 @@ public abstract class FileActivity extends SherlockFragmentActivity {
     
     /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
     private boolean mRedirectingToSetupAccount = false;
-
     
+
+    /**
+     * Loads the cownCloud {@link Account} and main {@link OCFile} to be handled by the instance of 
+     * the {@link FileActivity}.
+     * 
+     * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user 
+     * is requested to create a new one.
+     */
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        
-        /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
+
         if(savedInstanceState != null) {
             mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
             mAccount = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
@@ -66,38 +79,53 @@ public abstract class FileActivity extends SherlockFragmentActivity {
             mAccount = getIntent().getParcelableExtra(FileActivity.EXTRA_ACCOUNT);
             mFile = getIntent().getParcelableExtra(FileActivity.EXTRA_FILE);
         }
-        
-        if (mAccount != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), mAccount.name)) {
-            onAccountChanged();
+
+        grantValidAccount();
+        if (mAccount != null) {
+            onAccountSet(savedInstanceState != null);
         }
     }
 
     
     /**
-     * Validate the ownCloud {@link Account} associated to the Activity any time it is 
-     * started, and if not valid tries to move to a different Account.
+     *  Since ownCloud {@link Account}s can be managed from the system setting menu, 
+     *  the existence of the {@link Account} associated to the instance must be checked 
+     *  every time it is restarted.
      */
     @Override
-    protected void onStart() {
-        Log_OC.e(TAG, "onStart en FileActivity");
-        super.onStart();
-        /// Validate account, and try to fix if wrong
-        if (mAccount == null || !AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), mAccount.name)) {
-            if (!AccountUtils.accountsAreSetup(getApplicationContext())) {
+    protected void onRestart() {
+        super.onRestart();
+        
+        Account oldAccount = mAccount;
+        grantValidAccount();
+        if (mAccount != null && !mAccount.equals(oldAccount)) {
+            onAccountSet(false);
+        }
+    }
+    
+        
+    /**
+     *  Validates the ownCloud {@link Account} associated to the Activity any time it is restarted.
+     * 
+     *  If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
+     * 
+     *  If no valid ownCloud {@link Account} exists, mAccount is set to NULL and the user is requested 
+     *  to create a new ownCloud {@link Account}.
+     */
+    private void grantValidAccount() {
+        boolean validAccount = (mAccount != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), mAccount.name));
+        if (!validAccount) {
+            // get most recently used account as default account
+            mAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
+            if (mAccount == null) {
                 /// no account available: force account creation
-                mAccount = null;
                 createFirstAccount();
                 mRedirectingToSetupAccount = true;
-                
-            } else {
-                /// get 'last current account' as default account
-                mAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
-                onAccountChanged();
             }
         }
     }
     
-        
+    
     /**
      * Launches the account creation activity. To use when no ownCloud account is available
      */
@@ -183,7 +211,7 @@ public abstract class FileActivity extends SherlockFragmentActivity {
                     String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
                     if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
                         FileActivity.this.mAccount = new Account(name, type);
-                        FileActivity.this.onAccountChanged();
+                        FileActivity.this.onAccountSet(false);
                     }
                 } catch (OperationCanceledException e) {
                     Log_OC.e(TAG, "Account creation canceled");
@@ -201,12 +229,48 @@ public abstract class FileActivity extends SherlockFragmentActivity {
         }
         
     }
-
-
+    
+    
     /**
      *  Called when the ownCloud {@link Account} associated to the Activity was just updated.
      * 
      *  Child classes must grant that state depending on the {@link Account} is updated.
      */
-    protected abstract void onAccountChanged();
+    protected abstract void onAccountSet(boolean stateWasRecovered);
+    
+    
+
+    public void openFile(OCFile file) {
+        if (file != null) {
+            String storagePath = file.getStoragePath();
+            String encodedStoragePath = WebdavUtils.encodePath(storagePath);
+            
+            Intent intentForSavedMimeType = new Intent(Intent.ACTION_VIEW);
+            intentForSavedMimeType.setDataAndType(Uri.parse("file://"+ encodedStoragePath), file.getMimetype());
+            intentForSavedMimeType.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
+            
+            Intent intentForGuessedMimeType = null;
+            if (storagePath.lastIndexOf('.') >= 0) {
+                String guessedMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
+                if (guessedMimeType != null && !guessedMimeType.equals(file.getMimetype())) {
+                    intentForGuessedMimeType = new Intent(Intent.ACTION_VIEW);
+                    intentForGuessedMimeType.setDataAndType(Uri.parse("file://"+ encodedStoragePath), guessedMimeType);
+                    intentForGuessedMimeType.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
+                }
+            }
+            
+            Intent chooserIntent = null;
+            if (intentForGuessedMimeType != null) {
+                chooserIntent = Intent.createChooser(intentForGuessedMimeType, getString(R.string.actionbar_open_with));
+            } else {
+                chooserIntent = Intent.createChooser(intentForSavedMimeType, getString(R.string.actionbar_open_with));
+            }
+            
+            startActivity(chooserIntent);
+            
+        } else {
+            Log_OC.wtf(TAG, "Trying to open a NULL OCFile");
+        }
+    }
+    
 }

+ 0 - 481
src/com/owncloud/android/ui/activity/FileDetailActivity.java

@@ -1,481 +0,0 @@
-/* ownCloud Android client application
- *   Copyright (C) 2011  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 version 2,
- *   as published by the Free Software Foundation.
- *
- *   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.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 com.actionbarsherlock.app.ActionBar;
-import com.actionbarsherlock.view.MenuItem;
-import com.owncloud.android.AccountUtils;
-import com.owncloud.android.Log_OC;
-import com.owncloud.android.R;
-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.ui.preview.PreviewVideoActivity;
-
-/**
- * This activity displays the details of a file like its name, its size and so
- * on.
- * 
- * @author Bartek Przybylski
- * @author David A. Velasco
- */
-public class FileDetailActivity extends FileActivity 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 FileDownloaderBinder mDownloaderBinder = null;
-    private ServiceConnection mDownloadConnection, mUploadConnection = null;
-    private FileUploaderBinder mUploaderBinder = null;
-    private boolean mWaitingToPreview;
-    
-    private FileDataStorageManager mStorageManager;
-    private DownloadFinishReceiver mDownloadFinishReceiver;
-
-    private Configuration mNewConfigurationChangeToApplyOnStart;
-
-    private boolean mStarted;
-
-    private boolean mDualPane;
-    
-
-    @Override
-    protected void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        mStarted = false;
-        
-        // check if configuration is proper for this activity; tablets in landscape should pass the torch to FileDisplayActivity 
-        Configuration conf = getResources().getConfiguration();
-        mDualPane = (conf.orientation == Configuration.ORIENTATION_LANDSCAPE && 
-                        (conf.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE
-                    );
-
-        if (mDualPane) {
-            // only happens when notifications (downloads, uploads) are clicked at the notification bar
-            backToDisplayActivity(false);
-            
-        } else {
-            setContentView(R.layout.file_activity_details);
-        
-            ActionBar actionBar = getSupportActionBar();
-            actionBar.setDisplayHomeAsUpEnabled(true);
-    
-            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);
-        }
-    }
-    
-    /**
-     * 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;
-        OCFile file = getFile();
-        Account account = getAccount();
-        if (PreviewMediaFragment.canBePreviewed(file) && mode == MODE_PREVIEW) {
-            if (file.isDown()) {
-                int startPlaybackPosition = getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
-                boolean autoplay = getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
-                newFragment = new PreviewMediaFragment(file, account, startPlaybackPosition, autoplay);
-            
-            } else {
-                newFragment = new FileDetailFragment(file, account);
-                mWaitingToPreview = true;
-            }
-            
-        } else {
-            newFragment = new FileDetailFragment(file, account);
-        }
-        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
-        ft.replace(R.id.fragment, newFragment, FileDetailFragment.FTAG);
-        ft.commit();
-    }
-    
-    @Override
-    public void onActivityResult (int requestCode, int resultCode, Intent data) {
-        Log_OC.e(TAG, "onActivityResult");
-        super.onActivityResult(requestCode, resultCode, data);
-    }
-
-    @Override
-    public void onConfigurationChanged (Configuration newConfig) {
-        super.onConfigurationChanged(newConfig);
-        if (mStarted) {
-            checkConfigurationChange(newConfig);
-        } else {
-            mNewConfigurationChangeToApplyOnStart = newConfig;
-        }
-    }
-    
-    
-    @Override
-    protected void onSaveInstanceState(Bundle outState) {
-        super.onSaveInstanceState(outState);
-        outState.putBoolean(KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
-    }
-    
-    
-    @Override
-    public void onStart() {
-        super.onStart();
-        Log_OC.e(TAG, "onStart");
-        if (mNewConfigurationChangeToApplyOnStart != null && !isRedirectingToSetupAccount()) {
-            checkConfigurationChange(mNewConfigurationChangeToApplyOnStart);
-            mNewConfigurationChangeToApplyOnStart = null;
-        }
-        mStarted = true;
-    }
-
-    private void checkConfigurationChange(Configuration newConfig) {
-        finish();
-        Intent intent = null;
-        OCFile file = getFile();
-        Account account = getAccount();
-        if ((newConfig.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE
-                && newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
-            
-            intent = new Intent(this, FileDisplayActivity.class);
-            intent.putExtra(EXTRA_FILE, file);
-            intent.putExtra(EXTRA_ACCOUNT, account);
-            intent.putExtra(EXTRA_MODE, getIntent().getIntExtra(EXTRA_MODE, MODE_PREVIEW));
-            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
-            Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
-            if (fragment != null && file != null && fragment instanceof PreviewMediaFragment && file.isVideo()) {
-                PreviewMediaFragment videoFragment = (PreviewMediaFragment)fragment;
-                intent.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, videoFragment.getPosition());
-                intent.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, videoFragment.isPlaying());
-            }
-        
-        } else {
-            intent = new Intent(this, FileDetailActivity.class);
-            intent .putExtra(EXTRA_FILE, file);
-            intent .putExtra(EXTRA_ACCOUNT, account);
-            intent.putExtra(EXTRA_MODE, getIntent().getIntExtra(EXTRA_MODE, MODE_PREVIEW));
-            Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
-            if (fragment != null && file != null && fragment instanceof PreviewMediaFragment && file.isVideo()) {
-                PreviewMediaFragment videoFragment = (PreviewMediaFragment)fragment;
-                intent.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, videoFragment.getPosition());
-                intent.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, videoFragment.isPlaying());
-            }
-            // and maybe 'waiting to preview' flag
-        }
-        startActivity(intent);
-    }
-
-    @Override
-    public void onStop() {
-        super.onStop();
-        Log_OC.e(TAG, "onStop");
-        mStarted = false;
-    }
-    @Override
-    public void onPause() {
-        super.onPause();
-        Log_OC.e(TAG, "onPause");
-        if (mDownloadFinishReceiver != null) {
-            unregisterReceiver(mDownloadFinishReceiver);
-            mDownloadFinishReceiver = null;
-        }
-    }
-
-    
-    @Override
-    public void onResume() {
-        super.onResume();
-        Log_OC.e(TAG, "onResume");
-        // 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() */
-    private class DetailsServiceConnection implements ServiceConnection {
-
-        @Override
-        public void onServiceConnected(ComponentName component, IBinder service) {
-                
-            if (component.equals(new ComponentName(FileDetailActivity.this, FileDownloader.class))) {
-                Log_OC.d(TAG, "Download service connected");
-                mDownloaderBinder = (FileDownloaderBinder) service;
-                if (mWaitingToPreview) {
-                    requestForDownload();
-                }
-                    
-            } else if (component.equals(new ComponentName(FileDetailActivity.this, FileUploader.class))) {
-                Log_OC.d(TAG, "Upload service connected");
-                mUploaderBinder = (FileUploaderBinder) service;
-            } else {
-                return;
-            }
-            
-            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
-        public void onServiceDisconnected(ComponentName component) {
-            if (component.equals(new ComponentName(FileDetailActivity.this, FileDownloader.class))) {
-                Log_OC.d(TAG, "Download service disconnected");
-                mDownloaderBinder = null;
-            } else if (component.equals(new ComponentName(FileDetailActivity.this, FileUploader.class))) {
-                Log_OC.d(TAG, "Upload service disconnected");
-                mUploaderBinder = null;
-            }
-        }
-    };    
-    
-    
-    @Override
-    public void onDestroy() {
-        super.onDestroy();
-        Log_OC.e(TAG,  "onDestroy");
-        if (mDownloadConnection != null) {
-            unbindService(mDownloadConnection);
-            mDownloadConnection = null;
-        }
-        if (mUploadConnection != null) {
-            unbindService(mUploadConnection);
-            mUploadConnection = null;
-        }
-    }
-    
-    
-    @Override
-    public boolean onOptionsItemSelected(MenuItem item) {
-        boolean returnValue = false;
-        
-        switch(item.getItemId()){
-        case android.R.id.home:
-            backToDisplayActivity(true);
-            returnValue = true;
-            break;
-        default:
-            returnValue = super.onOptionsItemSelected(item);
-        }
-        
-        return returnValue;
-    }
-
-    @Override
-    public void onBackPressed() {
-        backToDisplayActivity(true);
-    }
-    
-    private void backToDisplayActivity(boolean moveToParent) {
-        Intent intent = new Intent(this, FileDisplayActivity.class);
-        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
-        OCFile targetFile = null;
-        OCFile file = getFile();
-        if (file != null) {
-            targetFile = moveToParent ? mStorageManager.getFileById(file.getParentId()) : file;
-        }
-        intent.putExtra(EXTRA_FILE, targetFile);
-        intent.putExtra(EXTRA_ACCOUNT, getAccount());
-        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) {
-        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
-        transaction.replace(R.id.fragment, new FileDetailFragment(file, getAccount()), FileDetailFragment.FTAG); 
-        transaction.commit();
-    }
-
-    
-    private void requestForDownload() {
-        if (!mDownloaderBinder.isDownloading(getAccount(), getFile())) {
-            Intent i = new Intent(this, FileDownloader.class);
-            i.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
-            i.putExtra(FileDownloader.EXTRA_FILE, getFile());
-            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 = (getFile() != null && getFile().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) {
-                    setFile(mStorageManager.getFileById(getFile().getFileId()));   // update the file from database, for the local storage path
-                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
-                    transaction.replace(R.id.fragment, new PreviewMediaFragment(getFile(), getAccount(), 0, true), FileDetailFragment.FTAG);
-                    transaction.commit();
-                    mWaitingToPreview = false;
-                    
-                } else {
-                    detailsFragment.updateFileDetails(false, (success));
-                    // TODO error message if !success ¿?
-                }
-            }
-        } // TODO else if (fragment != null && fragment )
-        
-    }
-
-    /**
-     * {@inheritDoc}
-     */
-    @Override
-    protected void onAccountChanged() {
-        mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
-        
-        FileFragment fragment = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
-        if (fragment != null && mStorageManager.getFileById(fragment.getFile().getFileId()) == null) {
-            /// the account was forced to be changed; probably was deleted from system settings
-            backToDisplayActivity(false);
-        }
-    }
-
-}

File diff suppressed because it is too large
+ 366 - 344
src/com/owncloud/android/ui/activity/FileDisplayActivity.java


+ 39 - 21
src/com/owncloud/android/ui/FragmentListView.java → src/com/owncloud/android/ui/fragment/ExtendedListFragment.java

@@ -16,31 +16,33 @@
  *
  */
 
-package com.owncloud.android.ui;
+package com.owncloud.android.ui.fragment;
 
 import com.actionbarsherlock.app.SherlockFragment;
+import com.owncloud.android.Log_OC;
 import com.owncloud.android.R;
-import com.owncloud.android.ui.fragment.LocalFileListFragment;
+import com.owncloud.android.ui.ExtendedListView;
 
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.AdapterView;
-import android.widget.AdapterView.OnItemLongClickListener;
 import android.widget.ListAdapter;
 import android.widget.AdapterView.OnItemClickListener;
 import android.widget.ListView;
 
-public class FragmentListView extends SherlockFragment implements
-        OnItemClickListener, OnItemLongClickListener {
-    protected ExtendedListView mList;
+/**
+ *  TODO extending SherlockListFragment instead of SherlockFragment 
+ */
+public class ExtendedListFragment extends SherlockFragment implements OnItemClickListener {
+    
+    private static final String TAG = ExtendedListFragment.class.getSimpleName();
 
-    @Override
-    public void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-    }
+    private static final String KEY_SAVED_LIST_POSITION = "SAVED_LIST_POSITION"; 
 
+    protected ExtendedListView mList;
+    
     public void setListAdapter(ListAdapter listAdapter) {
         mList.setAdapter(listAdapter);
         mList.invalidate();
@@ -50,27 +52,32 @@ public class FragmentListView extends SherlockFragment implements
         return mList;
     }
     
+    
     @Override
-    public View onCreateView(LayoutInflater inflater, ViewGroup container,
-            Bundle savedInstanceState) {
+    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+        Log_OC.e(TAG, "onCreateView");
         //mList = new ExtendedListView(getActivity());
         View v = inflater.inflate(R.layout.list_fragment, null);
         mList = (ExtendedListView)(v.findViewById(R.id.list_root));
         mList.setOnItemClickListener(this);
-        mList.setOnItemLongClickListener(this);
         //mList.setEmptyView(v.findViewById(R.id.empty_list_view));     // looks like it's not a cool idea 
         mList.setDivider(getResources().getDrawable(R.drawable.uploader_list_separator));
         mList.setDividerHeight(1);
-        return v;
-    }
 
-    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
+        if (savedInstanceState != null) {
+            int referencePosition = savedInstanceState.getInt(KEY_SAVED_LIST_POSITION);
+            setReferencePosition(referencePosition);
+        }
+        
+        return v;
     }
 
+    
     @Override
-    public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
-            long arg3) {
-        return false;
+    public void onSaveInstanceState(Bundle savedInstanceState) {
+        super.onSaveInstanceState(savedInstanceState);
+        Log_OC.e(TAG, "onSaveInstanceState()");
+        savedInstanceState.putInt(KEY_SAVED_LIST_POSITION, getReferencePosition());
     }
 
     
@@ -83,7 +90,11 @@ public class FragmentListView extends SherlockFragment implements
      * @return      The position in the list of the visible item in the center of the screen.
      */
     protected int getReferencePosition() {
-        return (mList.getFirstVisiblePosition() + mList.getLastVisiblePosition()) / 2;
+        if (mList != null) {
+            return (mList.getFirstVisiblePosition() + mList.getLastVisiblePosition()) / 2;
+        } else {
+            return 0;
+        }
     }
 
     
@@ -93,7 +104,14 @@ public class FragmentListView extends SherlockFragment implements
      * @param   position    Reference position previously returned by {@link LocalFileListFragment#getReferencePosition()}
      */
     protected void setReferencePosition(int position) {
-        mList.setAndCenterSelection(position);
+        if (mList != null) {
+            mList.setAndCenterSelection(position);
+        }
+    }
+
+    @Override
+    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
+        // to be @overriden  
     }
 
     

+ 81 - 263
src/com/owncloud/android/ui/fragment/FileDetailFragment.java

@@ -24,12 +24,10 @@ import java.util.List;
 
 import android.accounts.Account;
 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.net.Uri;
 import android.os.Bundle;
 import android.os.Handler;
 import android.support.v4.app.FragmentTransaction;
@@ -37,14 +35,12 @@ import android.view.LayoutInflater;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.view.ViewGroup;
-import android.webkit.MimeTypeMap;
 import android.widget.CheckBox;
 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;
@@ -65,7 +61,6 @@ import com.owncloud.android.operations.RenameFileOperation;
 import com.owncloud.android.operations.SynchronizeFileOperation;
 import com.owncloud.android.ui.activity.ConflictsResolveActivity;
 import com.owncloud.android.ui.activity.FileActivity;
-import com.owncloud.android.ui.activity.FileDetailActivity;
 import com.owncloud.android.ui.activity.FileDisplayActivity;
 import com.owncloud.android.ui.dialog.EditNameDialog;
 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
@@ -73,7 +68,6 @@ import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
 import com.owncloud.android.R;
 
 import eu.alefzero.webdav.OnDatatransferProgressListener;
-import eu.alefzero.webdav.WebdavUtils;
 
 /**
  * This Fragment is used to display the details about a file.
@@ -81,16 +75,14 @@ import eu.alefzero.webdav.WebdavUtils;
  * @author Bartek Przybylski
  * @author David A. Velasco
  */
-public class FileDetailFragment extends SherlockFragment implements
+public class FileDetailFragment extends FileFragment implements
         OnClickListener, 
-        ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener, EditNameDialogListener,
-        FileFragment {
+        ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener, EditNameDialogListener {
 
     private FileFragment.ContainerActivity mContainerActivity;
     
     private int mLayout;
     private View mView;
-    private OCFile mFile;
     private Account mAccount;
     private FileDataStorageManager mStorageManager;
     
@@ -101,7 +93,6 @@ public class FileDetailFragment extends SherlockFragment implements
     private RemoteOperation mLastRemoteOperation;
     
     private static final String TAG = FileDetailFragment.class.getSimpleName();
-    public static final String FTAG = "FileDetails"; 
     public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";
     
 
@@ -111,7 +102,7 @@ public class FileDetailFragment extends SherlockFragment implements
      * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically. 
      */
     public FileDetailFragment() {
-        mFile = null;
+        super();
         mAccount = null;
         mStorageManager = null;
         mLayout = R.layout.file_details_empty;
@@ -127,7 +118,7 @@ public class FileDetailFragment extends SherlockFragment implements
      * @param ocAccount         An ownCloud account; needed to start downloads
      */
     public FileDetailFragment(OCFile fileToDetail, Account ocAccount) {
-        mFile = fileToDetail;
+        super(fileToDetail);
         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;
@@ -146,19 +137,20 @@ public class FileDetailFragment extends SherlockFragment implements
     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
             Bundle savedInstanceState) {
-        super.onCreateView(inflater, container, savedInstanceState);
+        //super.onCreateView(inflater, container, savedInstanceState);
         
         if (savedInstanceState != null) {
-            mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
+            setFile((OCFile)savedInstanceState.getParcelable(FileActivity.EXTRA_FILE));
             mAccount = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
         }
         
-        if(mFile != null && mAccount != null) {
+        if(getFile() != null && mAccount != null) {
             mLayout = R.layout.file_details_fragment;
         }
         
         View view = null;
-        view = inflater.inflate(mLayout, container, false);
+        //view = inflater.inflate(mLayout, container, false);
+        view = inflater.inflate(mLayout, null);
         mView = view;
         
         if (mLayout == R.layout.file_details_fragment) {
@@ -202,7 +194,7 @@ public class FileDetailFragment extends SherlockFragment implements
     @Override
     public void onSaveInstanceState(Bundle outState) {
         super.onSaveInstanceState(outState);
-        outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
+        outState.putParcelable(FileActivity.EXTRA_FILE, getFile());
         outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
     }
 
@@ -269,11 +261,12 @@ public class FileDetailFragment extends SherlockFragment implements
         
         List<Integer> toHide = new ArrayList<Integer>();
         List<Integer> toShow = new ArrayList<Integer>();
+        OCFile file = getFile();
         
         FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
-        boolean downloading = downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile);
+        boolean downloading = downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file);
         FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
-        boolean uploading = uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile);
+        boolean uploading = uploaderBinder != null && uploaderBinder.isUploading(mAccount, getFile());
         
         if (downloading || uploading) {
             toHide.add(R.id.action_download_file);
@@ -288,7 +281,7 @@ public class FileDetailFragment extends SherlockFragment implements
                 toShow.add(R.id.action_cancel_download);
             }
 
-        } else if (mFile != null && mFile.isDown()) {
+        } else if (file != null && file.isDown()) {
             toHide.add(R.id.action_download_file);
             toHide.add(R.id.action_cancel_download);
             toHide.add(R.id.action_cancel_upload);
@@ -298,7 +291,7 @@ public class FileDetailFragment extends SherlockFragment implements
             toShow.add(R.id.action_open_file_with);
             toShow.add(R.id.action_sync_file);
             
-        } else if (mFile != null) {
+        } else if (file != null) {
             toHide.add(R.id.action_open_file_with);
             toHide.add(R.id.action_cancel_download);
             toHide.add(R.id.action_cancel_upload);
@@ -344,7 +337,7 @@ public class FileDetailFragment extends SherlockFragment implements
     public boolean onOptionsItemSelected(MenuItem item) {
         switch (item.getItemId()) {
             case R.id.action_open_file_with: {
-                openFile();
+                mContainerActivity.openFile(getFile());
                 return true;
             }
             case R.id.action_remove_file: {
@@ -386,8 +379,9 @@ public class FileDetailFragment extends SherlockFragment implements
     
     private void toggleKeepInSync() {
         CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
-        mFile.setKeepInSync(cb.isChecked());
-        mStorageManager.saveFile(mFile);
+        OCFile file = getFile();
+        file.setKeepInSync(cb.isChecked());
+        mStorageManager.saveFile(file);
         
         /// register the OCFile instance in the observer service to monitor local updates;
         /// if necessary, the file is download 
@@ -397,22 +391,23 @@ public class FileDetailFragment extends SherlockFragment implements
                    (cb.isChecked()?
                            FileObserverService.CMD_ADD_OBSERVED_FILE:
                            FileObserverService.CMD_DEL_OBSERVED_FILE));
-        intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
+        intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, file);
         intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
         getActivity().startService(intent);
         
-        if (mFile.keepInSync()) {
+        if (file.keepInSync()) {
             synchronizeFile();   // force an immediate synchronization
         }
     }
 
 
     private void removeFile() {
+        OCFile file = getFile();
         ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
                 R.string.confirmation_remove_alert,
-                new String[]{mFile.getFileName()},
-                mFile.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
-                mFile.isDown() ? R.string.confirmation_remove_local : -1,
+                new String[]{file.getFileName()},
+                file.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
+                file.isDown() ? R.string.confirmation_remove_local : -1,
                 R.string.common_cancel);
         confDialog.setOnConfirmationListener(this);
         confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
@@ -420,116 +415,61 @@ public class FileDetailFragment extends SherlockFragment implements
 
 
     private void renameFile() {
-        String fileName = mFile.getFileName();
-        int extensionStart = mFile.isDirectory() ? -1 : fileName.lastIndexOf(".");
+        OCFile file = getFile();
+        String fileName = file.getFileName();
+        int extensionStart = file.isDirectory() ? -1 : fileName.lastIndexOf(".");
         int selectionEnd = (extensionStart >= 0) ? extensionStart : fileName.length();
         EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), fileName, 0, selectionEnd, this);
         dialog.show(getFragmentManager(), "nameeditdialog");
     }
 
     private void synchronizeFile() {
+        OCFile file = getFile();
         FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
         FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
-        if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
-            downloaderBinder.cancel(mAccount, mFile);
-            if (mFile.isDown()) {
+        if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file)) {
+            downloaderBinder.cancel(mAccount, file);
+            if (file.isDown()) {
                 setButtonsForDown();
             } else {
                 setButtonsForRemote();
             }
 
-        } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
-            uploaderBinder.cancel(mAccount, mFile);
-            if (!mFile.fileExists()) {
+        } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file)) {
+            uploaderBinder.cancel(mAccount, file);
+            if (!file.fileExists()) {
                 // TODO make something better
-                if (getActivity() instanceof FileDisplayActivity) {
-                    // double pane
-                    FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
-                    transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FTAG); // empty FileDetailFragment
-                    transaction.commit();
-                    mContainerActivity.onFileStateChanged();
-                } else {
-                    getActivity().finish();
-                }
+                ((FileDisplayActivity)getActivity()).cleanSecondFragment();
                 
-            } else if (mFile.isDown()) {
+            } else if (file.isDown()) {
                 setButtonsForDown();
             } else {
                 setButtonsForRemote();
             }
             
         } else {
-            mLastRemoteOperation = new SynchronizeFileOperation(mFile, null, mStorageManager, mAccount, true, false, getActivity());
+            mLastRemoteOperation = new SynchronizeFileOperation(file, null, mStorageManager, mAccount, true, false, getActivity());
             mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
             
             // update ui 
             boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
-            getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
-            
-        }
-    }
-
-    /**
-     * 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_OC.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_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
-                
-            } catch (ActivityNotFoundException e) {
-                Log_OC.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
-                
-            } catch (Throwable th) {
-                Log_OC.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();
-                }
-            }
+            getActivity().showDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
             
         }
     }
 
     @Override
     public void onConfirmation(String callerTag) {
+        OCFile file = getFile();
         if (callerTag.equals(FTAG_CONFIRMATION)) {
-            if (mStorageManager.getFileById(mFile.getFileId()) != null) {
-                mLastRemoteOperation = new RemoveFileOperation( mFile, 
+            if (mStorageManager.getFileById(file.getFileId()) != null) {
+                mLastRemoteOperation = new RemoveFileOperation( file, 
                                                                 true, 
                                                                 mStorageManager);
                 mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
                 
                 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
-                getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
+                getActivity().showDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
             }
         }
     }
@@ -537,11 +477,12 @@ public class FileDetailFragment extends SherlockFragment implements
     @Override
     public void onNeutral(String callerTag) {
         File f = null;
-        if (mFile.isDown() && (f = new File(mFile.getStoragePath())).exists()) {
+        OCFile file = getFile();
+        if (file.isDown() && (f = new File(file.getStoragePath())).exists()) {
             f.delete();
-            mFile.setStoragePath(null);
-            mStorageManager.saveFile(mFile);
-            updateFileDetails(mFile, mAccount);
+            file.setStoragePath(null);
+            mStorageManager.saveFile(file);
+            updateFileDetails(file, mAccount);
         }
     }
     
@@ -557,24 +498,17 @@ public class FileDetailFragment extends SherlockFragment implements
      * @return  True when the fragment was created with the empty layout.
      */
     public boolean isEmpty() {
-        return (mLayout == R.layout.file_details_empty || mFile == null || mAccount == null);
+        return (mLayout == R.layout.file_details_empty || getFile() == null || mAccount == null);
     }
 
     
-    /**
-     * {@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;
+        setFile(file);
         if (ocAccount != null && ( 
                 mStorageManager == null || 
                 (mAccount != null && !mAccount.equals(ocAccount))
@@ -603,30 +537,31 @@ public class FileDetailFragment extends SherlockFragment implements
         if (readyToShow()) {
             
             if (refresh && mStorageManager != null) {
-                mFile = mStorageManager.getFileByPath(mFile.getRemotePath());
+                setFile(mStorageManager.getFileByPath(getFile().getRemotePath()));
             }
+            OCFile file = getFile();
             
             // set file details
-            setFilename(mFile.getFileName());
-            setFiletype(mFile.getMimetype());
-            setFilesize(mFile.getFileLength());
+            setFilename(file.getFileName());
+            setFiletype(file.getMimetype());
+            setFilesize(file.getFileLength());
             if(ocVersionSupportsTimeCreated()){
-                setTimeCreated(mFile.getCreationTimestamp());
+                setTimeCreated(file.getCreationTimestamp());
             }
            
-            setTimeModified(mFile.getModificationTimestamp());
+            setTimeModified(file.getModificationTimestamp());
             
             CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);
-            cb.setChecked(mFile.keepInSync());
+            cb.setChecked(file.keepInSync());
 
             // configure UI for depending upon local state of the file
             //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
             FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
             FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
-            if (transferring || (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) || (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile))) {
+            if (transferring || (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file)) || (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file))) {
                 setButtonsForTransferring();
                 
-            } else if (mFile.isDown()) {
+            } else if (file.isDown()) {
                 
                 setButtonsForDown();
                 
@@ -644,7 +579,7 @@ public class FileDetailFragment extends SherlockFragment implements
      * @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);        
+        return (getFile() != null && mAccount != null && mLayout == R.layout.file_details_fragment);        
     }
 
 
@@ -723,9 +658,9 @@ public class FileDetailFragment extends SherlockFragment implements
             progressText.setVisibility(View.VISIBLE);
             FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
             FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
-            if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
+            if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, getFile())) {
                 progressText.setText(R.string.downloader_download_in_progress_ticker);
-            } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
+            } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, getFile())) {
                 progressText.setText(R.string.uploader_upload_in_progress_ticker);
             }
         }
@@ -798,11 +733,11 @@ public class FileDetailFragment extends SherlockFragment implements
             if (!isEmpty() && accountName.equals(mAccount.name)) {
                 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
                 String uploadRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
-                boolean renamedInUpload = mFile.getRemotePath().equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
-                if (mFile.getRemotePath().equals(uploadRemotePath) ||
+                boolean renamedInUpload = getFile().getRemotePath().equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
+                if (getFile().getRemotePath().equals(uploadRemotePath) ||
                     renamedInUpload) {
                     if (uploadWasFine) {
-                        mFile = mStorageManager.getFileByPath(uploadRemotePath);
+                        setFile(mStorageManager.getFileByPath(uploadRemotePath));
                     }
                     if (renamedInUpload) {
                         String newName = (new File(uploadRemotePath)).getName();
@@ -821,13 +756,13 @@ public class FileDetailFragment extends SherlockFragment implements
         if (dialog.getResult()) {
             String newFilename = dialog.getNewFilename();
             Log_OC.d(TAG, "name edit dialog dismissed with new name " + newFilename);
-            mLastRemoteOperation = new RenameFileOperation( mFile, 
+            mLastRemoteOperation = new RenameFileOperation( getFile(), 
                                                             mAccount, 
                                                             newFilename, 
                                                             new FileDataStorageManager(mAccount, getActivity().getContentResolver()));
             mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
             boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
-            getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
+            getActivity().showDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
         }
     }
     
@@ -852,22 +787,13 @@ public class FileDetailFragment extends SherlockFragment implements
     
     
     private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
-        boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
-        getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
+        getActivity().dismissDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
         
         if (result.isSuccess()) {
             Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
             msg.show();
-            if (inDisplayActivity) {
-                // double pane
-                FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
-                transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
-                transaction.commit();
-                mContainerActivity.onFileStateChanged();
-            } else {
-                getActivity().finish();
-            }
-                
+            ((FileDisplayActivity)getActivity()).cleanSecondFragment();
+
         } else {
             Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG); 
             msg.show();
@@ -878,8 +804,7 @@ public class FileDetailFragment extends SherlockFragment implements
     }
     
     private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
-        boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
-        getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
+        getActivity().dismissDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
         
         if (result.isSuccess()) {
             updateFileDetails(((RenameFileOperation)operation).getFile(), mAccount);
@@ -901,13 +826,12 @@ public class FileDetailFragment extends SherlockFragment implements
     }
     
     private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
-        boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
-        getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
-
+        getActivity().dismissDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
+        OCFile file = getFile();
         if (!result.isSuccess()) {
             if (result.getCode() == ResultCode.SYNC_CONFLICT) {
                 Intent i = new Intent(getActivity(), ConflictsResolveActivity.class);
-                i.putExtra(ConflictsResolveActivity.EXTRA_FILE, mFile);
+                i.putExtra(ConflictsResolveActivity.EXTRA_FILE, file);
                 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, mAccount);
                 startActivity(i);
                 
@@ -916,7 +840,7 @@ public class FileDetailFragment extends SherlockFragment implements
                 msg.show();
             }
             
-            if (mFile.isDown()) {
+            if (file.isDown()) {
                 setButtonsForDown();
                 
             } else {
@@ -931,7 +855,7 @@ public class FileDetailFragment extends SherlockFragment implements
             } else {
                 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG); 
                 msg.show();
-                if (mFile.isDown()) {
+                if (file.isDown()) {
                     setButtonsForDown();
                     
                 } else {
@@ -945,10 +869,10 @@ public class FileDetailFragment extends SherlockFragment implements
     public void listenForTransferProgress() {
         if (mProgressListener != null) {
             if (mContainerActivity.getFileDownloaderBinder() != null) {
-                mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
+                mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, getFile());
             }
             if (mContainerActivity.getFileUploaderBinder() != null) {
-                mContainerActivity.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
+                mContainerActivity.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, getFile());
             }
         }
     }
@@ -957,10 +881,10 @@ public class FileDetailFragment extends SherlockFragment implements
     public void leaveTransferProgress() {
         if (mProgressListener != null) {
             if (mContainerActivity.getFileDownloaderBinder() != null) {
-                mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
+                mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, getFile());
             }
             if (mContainerActivity.getFileUploaderBinder() != null) {
-                mContainerActivity.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
+                mContainerActivity.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, getFile());
             }
         }
     }
@@ -1000,110 +924,4 @@ public class FileDetailFragment extends SherlockFragment implements
 
     };
 
-    /*
-    // this is a temporary class for sharing purposes, it need to be replaced in transfer service
-    @SuppressWarnings("unused")
-    private class ShareRunnable implements Runnable {
-        private String mPath;
-
-        public ShareRunnable(String path) {
-            mPath = path;
-        }
-        
-        public void run() {
-            AccountManager am = AccountManager.get(getActivity());
-            Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
-            OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
-            String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
-
-            Log_OC.d("share", "sharing for version " + ocv.toString());
-
-            if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
-                String APPS_PATH = "/apps/files_sharing/";
-                String SHARE_PATH = "ajax/share.php";
-
-                String SHARED_PATH = "/apps/files_sharing/get.php?token=";
-                
-                final String WEBDAV_SCRIPT = "webdav.php";
-                final String WEBDAV_FILES_LOCATION = "/files/";
-                
-                WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
-                HttpConnectionManagerParams params = new HttpConnectionManagerParams();
-                params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
-
-                //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
-                //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
-
-                PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
-
-                post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
-                post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
-                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
-                Log_OC.d("share", mPath+"");
-                formparams.add(new BasicNameValuePair("sources",mPath));
-                formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
-                formparams.add(new BasicNameValuePair("permissions", "0"));
-                post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
-
-                int status;
-                try {
-                    PropFindMethod find = new PropFindMethod(url+"/");
-                    find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
-                    Log_OC.d("sharer", ""+ url+"/");
-                    
-                    for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
-                        Log_OC.d("sharer-h", a.getName() + ":"+a.getValue());
-                    }
-                    
-                    int status2 = wc.executeMethod(find);
-
-                    Log_OC.d("sharer", "propstatus "+status2);
-                    
-                    GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
-                    get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
-                    
-                    status2 = wc.executeMethod(get);
-
-                    Log_OC.d("sharer", "getstatus "+status2);
-                    Log_OC.d("sharer", "" + get.getResponseBodyAsString());
-                    
-                    for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
-                        Log_OC.d("sharer", a.getName() + ":"+a.getValue());
-                    }
-
-                    status = wc.executeMethod(post);
-                    for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
-                        Log_OC.d("sharer-h", a.getName() + ":"+a.getValue());
-                    }
-                    for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
-                        Log_OC.d("sharer", a.getName() + ":"+a.getValue());
-                    }
-                    String resp = post.getResponseBodyAsString();
-                    Log_OC.d("share", ""+post.getURI().toString());
-                    Log_OC.d("share", "returned status " + status);
-                    Log_OC.d("share", " " +resp);
-                    
-                    if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
-                        return;
-                     }
-
-                    JSONObject jsonObject = new JSONObject (resp);
-                    String jsonStatus = jsonObject.getString("status");
-                    if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
-                    
-                    String token = jsonObject.getString("data");
-                    String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token; 
-                    Log_OC.d("Actions:shareFile ok", "url: " + uri);   
-                    
-                } catch (Exception e) {
-                    e.printStackTrace();
-                }
-                
-            } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
-                
-            }
-        }
-    }
-    */
-    
 }

+ 33 - 5
src/com/owncloud/android/ui/fragment/FileFragment.java

@@ -17,10 +17,11 @@
 
 package com.owncloud.android.ui.fragment;
 
-import android.content.Intent;
 import android.support.v4.app.Fragment;
 
+import com.actionbarsherlock.app.SherlockFragment;
 import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.files.FileHandler;
 import com.owncloud.android.ui.activity.TransferServiceGetter;
 
 /**
@@ -29,22 +30,49 @@ import com.owncloud.android.ui.activity.TransferServiceGetter;
  * @author David A. Velasco
  *
  */
-public interface FileFragment {
+public class FileFragment extends SherlockFragment {
+    
+    private OCFile mFile;
+
+
+    /**
+     * Creates an empty fragment.
+     * 
+     * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically. 
+     */
+    public FileFragment() {
+        mFile = null;
+    }
     
+    /**
+     * Creates an instance for a given {@OCFile}.
+     * 
+     * @param file
+     */
+    public FileFragment(OCFile file) {
+        mFile = file;
+    }
+
     /**
      * Getter for the hold {@link OCFile}
      * 
      * @return The {@link OCFile} hold
      */
-    public OCFile getFile();
+    public OCFile getFile() {
+        return mFile;
+    }
     
     
+    protected void setFile(OCFile file) {
+        mFile = file;
+    }
+
     /**
      * Interface to implement by any Activity that includes some instance of FileFragment
      * 
      * @author David A. Velasco
      */
-    public interface ContainerActivity extends TransferServiceGetter {
+    public interface ContainerActivity extends TransferServiceGetter, FileHandler {
 
         /**
          * Callback method invoked when the detail fragment wants to notice its container 
@@ -65,7 +93,7 @@ public interface FileFragment {
          * 
          * @param file      File to show details
          */
-        public void showFragmentWithDetails(OCFile file);
+        public void showDetails(OCFile file);
         
         
     }

+ 1 - 20
src/com/owncloud/android/ui/fragment/LocalFileListFragment.java

@@ -19,7 +19,6 @@ package com.owncloud.android.ui.fragment;
 
 import java.io.File;
 
-import com.owncloud.android.ui.FragmentListView;
 import com.owncloud.android.ui.adapter.LocalFileListAdapter;
 
 import android.app.Activity;
@@ -42,9 +41,8 @@ import com.owncloud.android.R;
  * @author David A. Velasco
  * 
  */
-public class LocalFileListFragment extends FragmentListView {
+public class LocalFileListFragment extends ExtendedListFragment {
     private static final String TAG = "LocalFileListFragment";
-    private static final String SAVED_LIST_POSITION = "LIST_POSITION"; 
     
     /** Reference to the Activity which this fragment is attached to. For callbacks */
     private LocalFileListFragment.ContainerActivity mContainerActivity;
@@ -94,27 +92,10 @@ public class LocalFileListFragment extends FragmentListView {
         mAdapter = new LocalFileListAdapter(mContainerActivity.getInitialDirectory(), getActivity());
         setListAdapter(mAdapter);
         
-        if (savedInstanceState != null) {
-            Log_OC.i(TAG, "savedInstanceState is not null");
-            int position = savedInstanceState.getInt(SAVED_LIST_POSITION);
-            setReferencePosition(position);
-        }
-        
         Log_OC.i(TAG, "onActivityCreated() stop");
     }
     
     
-    @Override
-    public void onSaveInstanceState(Bundle savedInstanceState) {
-        Log_OC.i(TAG, "onSaveInstanceState() start");
-        
-        savedInstanceState.putInt(SAVED_LIST_POSITION, getReferencePosition());
-        
-        
-        Log_OC.i(TAG, "onSaveInstanceState() stop");
-    }
-    
-    
     /**
      * Checks the file clicked over. Browses inside if it is a directory. Notifies the container activity in any case.
      */

+ 57 - 114
src/com/owncloud/android/ui/fragment/OCFileListFragment.java

@@ -26,6 +26,7 @@ import com.owncloud.android.Log_OC;
 import com.owncloud.android.R;
 import com.owncloud.android.datamodel.DataStorageManager;
 import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.files.FileHandler;
 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
 import com.owncloud.android.operations.OnRemoteOperationListener;
@@ -33,30 +34,24 @@ import com.owncloud.android.operations.RemoteOperation;
 import com.owncloud.android.operations.RemoveFileOperation;
 import com.owncloud.android.operations.RenameFileOperation;
 import com.owncloud.android.operations.SynchronizeFileOperation;
-import com.owncloud.android.ui.FragmentListView;
 import com.owncloud.android.ui.activity.FileDisplayActivity;
 import com.owncloud.android.ui.activity.TransferServiceGetter;
 import com.owncloud.android.ui.adapter.FileListListAdapter;
 import com.owncloud.android.ui.dialog.EditNameDialog;
 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
 import com.owncloud.android.ui.fragment.ConfirmationDialogFragment.ConfirmationDialogFragmentListener;
-
-import eu.alefzero.webdav.WebdavUtils;
+import com.owncloud.android.ui.preview.PreviewImageFragment;
+import com.owncloud.android.ui.preview.PreviewMediaFragment;
 
 import android.accounts.Account;
 import android.app.Activity;
-import android.content.ActivityNotFoundException;
-import android.content.Intent;
-import android.net.Uri;
 import android.os.Bundle;
 import android.os.Handler;
 import android.view.ContextMenu;
 import android.view.MenuInflater;
 import android.view.MenuItem;
 import android.view.View;
-import android.webkit.MimeTypeMap;
 import android.widget.AdapterView;
-import android.widget.Toast;
 import android.widget.AdapterView.AdapterContextMenuInfo;
 
 /**
@@ -65,9 +60,9 @@ import android.widget.AdapterView.AdapterContextMenuInfo;
  * @author Bartek Przybylski
  * 
  */
-public class OCFileListFragment extends FragmentListView implements EditNameDialogListener, ConfirmationDialogFragmentListener {
-    private static final String TAG = "FileListFragment";
-    private static final String SAVED_LIST_POSITION = "LIST_POSITION"; 
+public class OCFileListFragment extends ExtendedListFragment implements EditNameDialogListener, ConfirmationDialogFragmentListener {
+    
+    private static final String TAG = OCFileListFragment.class.getSimpleName();
     
     private OCFileListFragment.ContainerActivity mContainerActivity;
     
@@ -83,6 +78,7 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
     @Override
     public void onAttach(Activity activity) {
         super.onAttach(activity);
+        Log_OC.e(TAG, "onAttach");
         try {
             mContainerActivity = (ContainerActivity) activity;
         } catch (ClassCastException e) {
@@ -96,52 +92,62 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
      */
     @Override
     public void onActivityCreated(Bundle savedInstanceState) {
-        Log_OC.i(TAG, "onActivityCreated() start");
-        
         super.onActivityCreated(savedInstanceState);
+        Log_OC.e(TAG, "onActivityCreated() start");
         mAdapter = new FileListListAdapter(mContainerActivity.getInitialDirectory(), mContainerActivity.getStorageManager(), getActivity(), mContainerActivity);
         setListAdapter(mAdapter);
         
-        if (savedInstanceState != null) {
-            Log_OC.i(TAG, "savedInstanceState is not null");
-            int position = savedInstanceState.getInt(SAVED_LIST_POSITION);
-            setReferencePosition(position);
-        }
-        
         registerForContextMenu(getListView());
         getListView().setOnCreateContextMenuListener(this);        
         
         mHandler = new Handler();
-        
-        Log_OC.i(TAG, "onActivityCreated() stop");
     }
     
-    
 
-    @Override
-    public void onSaveInstanceState(Bundle savedInstanceState) {
-        Log_OC.i(TAG, "onSaveInstanceState() start");
-        
-        savedInstanceState.putInt(SAVED_LIST_POSITION, getReferencePosition());
+    /**
+     * Call this, when the user presses the up button
+     */
+    public void onBrowseUp() {
+        OCFile parentDir = null;
         
-        Log_OC.i(TAG, "onSaveInstanceState() stop");
+        if(mFile != null){
+            DataStorageManager storageManager = mContainerActivity.getStorageManager();
+            parentDir = storageManager.getFileById(mFile.getParentId());
+            mFile = parentDir;
+        }
+        listDirectory(parentDir);
     }
     
-    
     @Override
     public void onItemClick(AdapterView<?> l, View v, int position, long id) {
         OCFile file = (OCFile) mAdapter.getItem(position);
         if (file != null) {
-            /// Click on a directory
-            if (file.getMimetype().equals("DIR")) {
-                // just local updates
+            if (file.isDirectory()) { 
+                // update state and view of this fragment
                 mFile = file;
                 listDirectory(file);
-                // any other updates are let to the container Activity
-                mContainerActivity.onDirectoryClick(file);
-            
-            } else {    /// Click on a file
-                mContainerActivity.onFileClick(file, false);
+                // then, notify parent activity to let it update its state and view, and other fragments
+                mContainerActivity.onBrowsedDownTo(file);
+                
+            } else { /// Click on a file
+                if (PreviewImageFragment.canBePreviewed(file)) {
+                    // preview image - it handles the download, if needed
+                    mContainerActivity.startImagePreview(file);
+                    
+                } else if (file.isDown()) {
+                    if (PreviewMediaFragment.canBePreviewed(file)) {
+                        // media preview
+                        mContainerActivity.startMediaPreview(file, 0, true);
+                    } else {
+                        // open with
+                        mContainerActivity.openFile(file);
+                    }
+                    
+                } else {
+                    // automatic download, preview on finish
+                    mContainerActivity.startDownloadForPreview(file);
+                }
+                    
             }
             
         } else {
@@ -181,26 +187,25 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
             
         } else {
             // contextual menu for regular files
+            
+            // new design: 'download' and 'open with' won't be available anymore in context menu
+            toHide.add(R.id.action_download_file);
+            toHide.add(R.id.action_open_file_with);
+            
             if (targetFile.isDown()) {
                 toHide.add(R.id.action_cancel_download);
                 toHide.add(R.id.action_cancel_upload);
-                toHide.add(R.id.action_download_file);
                 
             } else {
-                toHide.add(R.id.action_open_file_with);
                 toHide.add(R.id.action_sync_file);
             }
             if ( mContainerActivity.getFileDownloaderBinder().isDownloading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile)) {
-                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.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);
                     
@@ -265,53 +270,6 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
                 confDialog.show(getFragmentManager(), FileDetailFragment.FTAG_CONFIRMATION);
                 return true;
             }
-            case R.id.action_open_file_with: {
-                String storagePath = mTargetFile.getStoragePath();
-                String encodedStoragePath = WebdavUtils.encodePath(storagePath);
-                try {
-                    Intent i = new Intent(Intent.ACTION_VIEW);
-                    i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mTargetFile.getMimetype());
-                    i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
-                    startActivity(i);
-                    
-                } catch (Throwable t) {
-                    Log_OC.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mTargetFile.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(mTargetFile.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_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
-                        
-                    } catch (ActivityNotFoundException e) {
-                        Log_OC.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
-                        
-                    } catch (Throwable th) {
-                        Log_OC.e(TAG, "Unexpected problem when opening: " + storagePath, th);
-                        
-                    } finally {
-                        if (toastIt) {
-                            Toast.makeText(getActivity(), "There is no application to handle file " + mTargetFile.getFileName(), Toast.LENGTH_SHORT).show();
-                        }
-                    }
-                    
-                }
-                return true;
-            }
-            case R.id.action_download_file: 
             case R.id.action_sync_file: {
                 Account account = AccountUtils.getCurrentOwnCloudAccount(getSherlockActivity());
                 RemoteOperation operation = new SynchronizeFileOperation(mTargetFile, null, mContainerActivity.getStorageManager(), account, true, false, getSherlockActivity());
@@ -340,7 +298,7 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
                 return true;
             }
             case R.id.action_see_details: {
-                ((FileFragment.ContainerActivity)getActivity()).showFragmentWithDetails(mTargetFile);
+                ((FileFragment.ContainerActivity)getActivity()).showDetails(mTargetFile);
                 return true;
             }
             default:
@@ -349,20 +307,6 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
     }
     
 
-    /**
-     * Call this, when the user presses the up button
-     */
-    public void onNavigateUp() {
-        OCFile parentDir = null;
-        
-        if(mFile != null){
-            DataStorageManager storageManager = mContainerActivity.getStorageManager();
-            parentDir = storageManager.getFileById(mFile.getParentId());
-            mFile = parentDir;
-        }
-        listDirectory(parentDir);
-    }
-
     /**
      * Use this to query the {@link OCFile} that is currently
      * being displayed by this fragment
@@ -422,21 +366,20 @@ public class OCFileListFragment extends FragmentListView implements EditNameDial
      * 
      * @author David A. Velasco
      */
-    public interface ContainerActivity extends TransferServiceGetter, OnRemoteOperationListener {
+    public interface ContainerActivity extends TransferServiceGetter, OnRemoteOperationListener, FileHandler {
 
         /**
-         * Callback method invoked when a directory is clicked by the user on the files list
+         * Callback method invoked when a the user browsed into a different folder through the list of files
          *  
          * @param file
          */
-        public void onDirectoryClick(OCFile file);
+        public void onBrowsedDownTo(OCFile folder);
         
-        /**
-         * Callback method invoked when a file (non directory) is clicked by the user on the files list
-         *  
-         * @param file
-         */
-        public void onFileClick(OCFile file, boolean realClick);
+        public void startDownloadForPreview(OCFile file);
+
+        public void startMediaPreview(OCFile file, int i, boolean b);
+
+        public void startImagePreview(OCFile file);
 
         /**
          * Getter for the current DataStorageManager in the container activity

+ 14 - 28
src/com/owncloud/android/ui/preview/FileDownloadFragment.java

@@ -27,12 +27,10 @@ import android.view.LayoutInflater;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.view.ViewGroup;
-import android.widget.Button;
+import android.widget.ImageButton;
 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;
@@ -47,7 +45,7 @@ import eu.alefzero.webdav.OnDatatransferProgressListener;
  * 
  * @author David A. Velasco
  */
-public class FileDownloadFragment extends SherlockFragment implements OnClickListener, FileFragment {
+public class FileDownloadFragment extends FileFragment implements OnClickListener {
 
     public static final String EXTRA_FILE = "FILE";
     public static final String EXTRA_ACCOUNT = "ACCOUNT";
@@ -56,9 +54,7 @@ public class FileDownloadFragment extends SherlockFragment implements OnClickLis
     private FileFragment.ContainerActivity mContainerActivity;
     
     private View mView;
-    private OCFile mFile;
     private Account mAccount;
-    private FileDataStorageManager mStorageManager;
     
     public ProgressListener mProgressListener;
     private boolean mListening;
@@ -75,9 +71,8 @@ public class FileDownloadFragment extends SherlockFragment implements OnClickLis
      * 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;
+        super();
         mAccount = null;
-        mStorageManager = null;
         mProgressListener = null;
         mListening = false;
         mIgnoreFirstSavedState = false;
@@ -95,9 +90,8 @@ public class FileDownloadFragment extends SherlockFragment implements OnClickLis
      * @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;
+        super(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;
@@ -118,7 +112,7 @@ public class FileDownloadFragment extends SherlockFragment implements OnClickLis
         
         if (savedInstanceState != null) {
             if (!mIgnoreFirstSavedState) {
-                mFile = savedInstanceState.getParcelable(FileDownloadFragment.EXTRA_FILE);
+                setFile((OCFile)savedInstanceState.getParcelable(FileDownloadFragment.EXTRA_FILE));
                 mAccount = savedInstanceState.getParcelable(FileDownloadFragment.EXTRA_ACCOUNT);
                 mError = savedInstanceState.getBoolean(FileDownloadFragment.EXTRA_ERROR);
             } else {
@@ -133,7 +127,7 @@ public class FileDownloadFragment extends SherlockFragment implements OnClickLis
         ProgressBar progressBar = (ProgressBar)mView.findViewById(R.id.progressBar);
         mProgressListener = new ProgressListener(progressBar);
         
-        ((Button)mView.findViewById(R.id.cancelBtn)).setOnClickListener(this);
+        ((ImageButton)mView.findViewById(R.id.cancelBtn)).setOnClickListener(this);
         
         if (mError) {
             setButtonsForRemote();
@@ -167,7 +161,7 @@ public class FileDownloadFragment extends SherlockFragment implements OnClickLis
     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());;
         }
     }
         
@@ -175,7 +169,7 @@ public class FileDownloadFragment extends SherlockFragment implements OnClickLis
     @Override
     public void onSaveInstanceState(Bundle outState) {
         super.onSaveInstanceState(outState);
-        outState.putParcelable(FileDownloadFragment.EXTRA_FILE, mFile);
+        outState.putParcelable(FileDownloadFragment.EXTRA_FILE, getFile());
         outState.putParcelable(FileDownloadFragment.EXTRA_ACCOUNT, mAccount);
         outState.putBoolean(FileDownloadFragment.EXTRA_ERROR, mError);
     }
@@ -224,8 +218,8 @@ public class FileDownloadFragment extends SherlockFragment implements OnClickLis
         switch (v.getId()) {
             case R.id.cancelBtn: {
                 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
-                if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
-                    downloaderBinder.cancel(mAccount, mFile);
+                if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, getFile())) {
+                    downloaderBinder.cancel(mAccount, getFile());
                     getActivity().finish(); // :)
                     /*
                     leaveTransferProgress();
@@ -244,14 +238,6 @@ public class FileDownloadFragment extends SherlockFragment implements OnClickLis
     }
 
     
-    /**
-     * {@inheritDoc}
-     */
-    public OCFile getFile(){
-        return mFile;
-    }
-    
-    
     /**
      * Updates the view depending upon the state of the downloading file.
      * 
@@ -261,10 +247,10 @@ public class FileDownloadFragment extends SherlockFragment implements OnClickLis
     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))) {
+        if (transferring || (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, getFile()))) {
             setButtonsForTransferring();
             
-        } else if (mFile.isDown()) {
+        } else if (getFile().isDown()) {
             
             setButtonsForDown();
             
@@ -335,7 +321,7 @@ public class FileDownloadFragment extends SherlockFragment implements OnClickLis
     public void listenForTransferProgress() {
         if (mProgressListener != null && !mListening) {
             if (mContainerActivity.getFileDownloaderBinder() != null) {
-                mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
+                mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, getFile());
                 mListening = true;
                 setButtonsForTransferring();
             }
@@ -346,7 +332,7 @@ public class FileDownloadFragment extends SherlockFragment implements OnClickLis
     public void leaveTransferProgress() {
         if (mProgressListener != null) {
             if (mContainerActivity.getFileDownloaderBinder() != null) {
-                mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
+                mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, getFile());
                 mListening = false;
             }
         }

+ 10 - 12
src/com/owncloud/android/ui/preview/PreviewImageActivity.java

@@ -44,7 +44,7 @@ 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.FileActivity;
-import com.owncloud.android.ui.activity.FileDetailActivity;
+import com.owncloud.android.ui.activity.FileDisplayActivity;
 import com.owncloud.android.ui.fragment.FileFragment;
 
 import com.owncloud.android.AccountUtils;
@@ -56,7 +56,7 @@ import com.owncloud.android.R;
  *  
  *  @author David A. Velasco
  */
-public class PreviewImageActivity extends SherlockFragmentActivity implements FileFragment.ContainerActivity, ViewPager.OnPageChangeListener, OnTouchListener {
+public class PreviewImageActivity extends FileActivity implements FileFragment.ContainerActivity, ViewPager.OnPageChangeListener, OnTouchListener {
     
     public static final int DIALOG_SHORT_WAIT = 0;
 
@@ -255,13 +255,6 @@ public class PreviewImageActivity extends SherlockFragmentActivity implements Fi
     
 
     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();
     }
     
@@ -311,11 +304,11 @@ public class PreviewImageActivity extends SherlockFragmentActivity implements Fi
 
 
     @Override
-    public void showFragmentWithDetails(OCFile file) {
-        Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
+    public void showDetails(OCFile file) {
+        Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
+        showDetailsIntent.setAction(FileDisplayActivity.ACTION_DETAILS);
         showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, file);
         showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
-        showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
         startActivity(showDetailsIntent);
         int pos = mPreviewImagePagerAdapter.getFilePosition(file);
         file = mPreviewImagePagerAdapter.getFileAt(pos);
@@ -440,6 +433,11 @@ public class PreviewImageActivity extends SherlockFragmentActivity implements Fi
         }
         mFullScreen = !mFullScreen;
     }
+
+    @Override
+    protected void onAccountSet(boolean stateWasRecovered) {
+        // TODO
+    }
     
     
 }

+ 25 - 76
src/com/owncloud/android/ui/preview/PreviewImageFragment.java

@@ -47,7 +47,6 @@ 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;
@@ -74,14 +73,12 @@ import eu.alefzero.webdav.WebdavUtils;
  * 
  * @author David A. Velasco
  */
-public class PreviewImageFragment extends SherlockFragment implements   FileFragment, 
-                                                                        OnRemoteOperationListener, 
+public class PreviewImageFragment extends FileFragment implements   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;
@@ -108,7 +105,7 @@ public class PreviewImageFragment extends SherlockFragment implements   FileFrag
      * @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;
+        super(fileToDetail);
         mAccount = ocAccount;
         mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment
         mIgnoreFirstSavedState = ignoreFirstSavedState;
@@ -123,7 +120,7 @@ public class PreviewImageFragment extends SherlockFragment implements   FileFrag
      *  DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction 
      */
     public PreviewImageFragment() {
-        mFile = null;
+        super();
         mAccount = null;
         mStorageManager = null;
         mIgnoreFirstSavedState = false;
@@ -180,19 +177,19 @@ public class PreviewImageFragment extends SherlockFragment implements   FileFrag
         mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
         if (savedInstanceState != null) {
             if (!mIgnoreFirstSavedState) {
-                mFile = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE);
+                setFile((OCFile)savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE));
                 mAccount = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_ACCOUNT);
             } else {
                 mIgnoreFirstSavedState = false;
             }
         }
-        if (mFile == null) {
+        if (getFile() == null) {
             throw new IllegalStateException("Instanced with a NULL OCFile");
         }
         if (mAccount == null) {
             throw new IllegalStateException("Instanced with a NULL ownCloud Account");
         }
-        if (!mFile.isDown()) {
+        if (!getFile().isDown()) {
             throw new IllegalStateException("There is no local file to preview");
         }
     }
@@ -204,7 +201,7 @@ public class PreviewImageFragment extends SherlockFragment implements   FileFrag
     @Override
     public void onSaveInstanceState(Bundle outState) {
         super.onSaveInstanceState(outState);
-        outState.putParcelable(PreviewImageFragment.EXTRA_FILE, mFile);
+        outState.putParcelable(PreviewImageFragment.EXTRA_FILE, getFile());
         outState.putParcelable(PreviewImageFragment.EXTRA_ACCOUNT, mAccount);
     }
     
@@ -212,9 +209,9 @@ public class PreviewImageFragment extends SherlockFragment implements   FileFrag
     @Override
     public void onStart() {
         super.onStart();
-        if (mFile != null) {
+        if (getFile() != null) {
            BitmapLoader bl = new BitmapLoader(mImageView, mMessageView, mProgressWheel);
-           bl.execute(new String[]{mFile.getStoragePath()});
+           bl.execute(new String[]{getFile().getStoragePath()});
         }
     }
     
@@ -272,42 +269,19 @@ public class PreviewImageFragment extends SherlockFragment implements   FileFrag
 
     
     private void seeDetails() {
-        ((FileFragment.ContainerActivity)getActivity()).showFragmentWithDetails(mFile);        
+        ((FileFragment.ContainerActivity)getActivity()).showDetails(getFile());        
     }
 
 
     @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;
-        */
     }
 
 
@@ -328,22 +302,23 @@ public class PreviewImageFragment extends SherlockFragment implements   FileFrag
      * available apps for the MIME type known from the file extension, to let the user choose
      */
     private void openFile() {
-        String storagePath = mFile.getStoragePath();
+        OCFile file = getFile();
+        String storagePath = file.getStoragePath();
         String encodedStoragePath = WebdavUtils.encodePath(storagePath);
         try {
             Intent i = new Intent(Intent.ACTION_VIEW);
-            i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
+            i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), file.getMimetype());
             i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
             startActivity(i);
             
         } catch (Throwable t) {
-            Log_OC.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
+            Log_OC.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + file.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 || !mimeType.equals(file.getMimetype())) {
                     if (mimeType != null) {
                         i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
                     } else {
@@ -366,7 +341,7 @@ public class PreviewImageFragment extends SherlockFragment implements   FileFrag
                 
             } finally {
                 if (toastIt) {
-                    Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
+                    Toast.makeText(getActivity(), "There is no application to handle file " + file.getFileName(), Toast.LENGTH_SHORT).show();
                 }
             }
             
@@ -384,7 +359,7 @@ public class PreviewImageFragment extends SherlockFragment implements   FileFrag
     private void removeFile() {
         ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
                 R.string.confirmation_remove_alert,
-                new String[]{mFile.getFileName()},
+                new String[]{getFile().getFileName()},
                 R.string.confirmation_remove_remote_and_local,
                 R.string.confirmation_remove_local,
                 R.string.common_cancel);
@@ -398,8 +373,8 @@ public class PreviewImageFragment extends SherlockFragment implements   FileFrag
      */
     @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
+        if (mStorageManager.getFileById(getFile().getFileId()) != null) {   // check that the file is still there;
+            mLastRemoteOperation = new RemoveFileOperation( getFile(),      // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
                                                             true, 
                                                             mStorageManager);
             mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
@@ -415,11 +390,12 @@ public class PreviewImageFragment extends SherlockFragment implements   FileFrag
     @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());
+        OCFile file = getFile();
+        if (file.isDown()) {   // checks it is still there
+            File f = new File(file.getStoragePath());
             f.delete();
-            mFile.setStoragePath(null);
-            mStorageManager.saveFile(mFile);
+            file.setStoragePath(null);
+            mStorageManager.saveFile(file);
             finish();
         }
     }
@@ -433,33 +409,6 @@ public class PreviewImageFragment extends SherlockFragment implements   FileFrag
     }
     
 
-    /**
-     * {@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> {
 
         /**
@@ -571,7 +520,7 @@ public class PreviewImageFragment extends SherlockFragment implements   FileFrag
                     
             } catch (Throwable t) {
                 mErrorMessageId = R.string.common_error_unknown;
-                Log_OC.e(TAG, "Unexpected error loading " + mFile.getStoragePath(), t);
+                Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
                 
             }
             return result;

+ 44 - 78
src/com/owncloud/android/ui/preview/PreviewMediaFragment.java

@@ -39,7 +39,6 @@ import android.os.Build;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.IBinder;
-import android.support.v4.app.FragmentTransaction;
 import android.view.LayoutInflater;
 import android.view.MotionEvent;
 import android.view.View;
@@ -50,7 +49,6 @@ 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;
@@ -63,10 +61,8 @@ 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.Log_OC;
@@ -82,8 +78,8 @@ import eu.alefzero.webdav.WebdavUtils;
  * 
  * @author David A. Velasco
  */
-public class PreviewMediaFragment extends SherlockFragment implements
-        OnTouchListener , FileFragment,  
+public class PreviewMediaFragment extends FileFragment implements
+        OnTouchListener,  
         ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener  {
 
     public static final String EXTRA_FILE = "FILE";
@@ -92,7 +88,6 @@ public class PreviewMediaFragment extends SherlockFragment implements
     private static final String EXTRA_PLAYING = "PLAYING";
 
     private View mView;
-    private OCFile mFile;
     private Account mAccount;
     private FileDataStorageManager mStorageManager;
     private ImageView mImagePreview;
@@ -121,7 +116,7 @@ public class PreviewMediaFragment extends SherlockFragment implements
      * @param ocAccount         An ownCloud account; needed to start downloads
      */
     public PreviewMediaFragment(OCFile fileToDetail, Account ocAccount, int startPlaybackPosition, boolean autoplay) {
-        mFile = fileToDetail;
+        super(fileToDetail);
         mAccount = ocAccount;
         mSavedPlaybackPosition = startPlaybackPosition;
         mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment 
@@ -137,7 +132,7 @@ public class PreviewMediaFragment extends SherlockFragment implements
      *  DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction 
      */
     public PreviewMediaFragment() {
-        mFile = null;
+        super();
         mAccount = null;
         mSavedPlaybackPosition = 0;
         mStorageManager = null;
@@ -201,22 +196,23 @@ public class PreviewMediaFragment extends SherlockFragment implements
 
         mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
         if (savedInstanceState != null) {
-            mFile = savedInstanceState.getParcelable(PreviewMediaFragment.EXTRA_FILE);
+            setFile((OCFile)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) {
+        OCFile file = getFile();
+        if (file == null) {
             throw new IllegalStateException("Instanced with a NULL OCFile");
         }
         if (mAccount == null) {
             throw new IllegalStateException("Instanced with a NULL ownCloud Account");
         }
-        if (!mFile.isDown()) {
+        if (!file.isDown()) {
             throw new IllegalStateException("There is no local file to preview");
         }
-        if (mFile.isVideo()) {
+        if (file.isVideo()) {
             mVideoPreview.setVisibility(View.VISIBLE);
             mImagePreview.setVisibility(View.GONE);
             prepareVideo();
@@ -237,10 +233,10 @@ public class PreviewMediaFragment extends SherlockFragment implements
         super.onSaveInstanceState(outState);
         Log_OC.e(TAG, "onSaveInstanceState");
         
-        outState.putParcelable(PreviewMediaFragment.EXTRA_FILE, mFile);
+        outState.putParcelable(PreviewMediaFragment.EXTRA_FILE, getFile());
         outState.putParcelable(PreviewMediaFragment.EXTRA_ACCOUNT, mAccount);
         
-        if (mFile.isVideo()) {
+        if (getFile().isVideo()) {
             mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
             mAutoplay = mVideoPreview.isPlaying();
             outState.putInt(PreviewMediaFragment.EXTRA_PLAY_POSITION , mSavedPlaybackPosition);
@@ -257,11 +253,12 @@ public class PreviewMediaFragment extends SherlockFragment implements
         super.onStart();
         Log_OC.e(TAG, "onStart");
 
-        if (mFile != null) {
-           if (mFile.isAudio()) {
+        OCFile file = getFile();
+        if (file != null) {
+           if (file.isAudio()) {
                bindMediaService();
                
-           } else if (mFile.isVideo()) {
+           } else if (file.isVideo()) {
                stopAudio();
                playVideo(); 
            }
@@ -331,7 +328,7 @@ public class PreviewMediaFragment extends SherlockFragment implements
     
     private void seeDetails() {
         stopPreview(false);
-        ((FileFragment.ContainerActivity)getActivity()).showFragmentWithDetails(mFile);        
+        ((FileFragment.ContainerActivity)getActivity()).showDetails(getFile());        
     }
 
 
@@ -348,7 +345,7 @@ public class PreviewMediaFragment extends SherlockFragment implements
         mMediaController.setMediaPlayer(mVideoPreview);
         
         // load the video file in the video player ; when done, VideoHelper#onPrepared() will be called
-        mVideoPreview.setVideoPath(mFile.getStoragePath()); 
+        mVideoPreview.setVideoPath(getFile().getStoragePath()); 
     }
     
 
@@ -397,7 +394,7 @@ public class PreviewMediaFragment extends SherlockFragment implements
                     mVideoPreview.stopPlayback();
                     mAutoplay = false;
                     mSavedPlaybackPosition = 0;
-                    mVideoPreview.setVideoPath(mFile.getStoragePath());
+                    mVideoPreview.setVideoPath(getFile().getStoragePath());
                 }
             } // else : called from onError()
             mMediaController.updatePausePlay();
@@ -481,7 +478,7 @@ public class PreviewMediaFragment extends SherlockFragment implements
     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_FILE, getFile());
         i.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, mVideoPreview.isPlaying());
         mVideoPreview.pause();
         i.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, mVideoPreview.getCurrentPosition());
@@ -505,9 +502,10 @@ public class PreviewMediaFragment extends SherlockFragment implements
     
 
     private void playAudio() {
-        if (!mMediaServiceBinder.isPlaying(mFile)) {
-            Log_OC.d(TAG, "starting playback of " + mFile.getStoragePath());
-            mMediaServiceBinder.start(mAccount, mFile, mAutoplay, mSavedPlaybackPosition);
+        OCFile file = getFile();
+        if (!mMediaServiceBinder.isPlaying(file)) {
+            Log_OC.d(TAG, "starting playback of " + file.getStoragePath());
+            mMediaServiceBinder.start(mAccount, file, mAutoplay, mSavedPlaybackPosition);
             
         } else {
             if (!mMediaServiceBinder.isPlaying() && mAutoplay) {
@@ -584,23 +582,24 @@ public class PreviewMediaFragment extends SherlockFragment implements
      * available apps for the MIME type known from the file extension, to let the user choose
      */
     private void openFile() {
+        OCFile file = getFile();
         stopPreview(true);
-        String storagePath = mFile.getStoragePath();
+        String storagePath = file.getStoragePath();
         String encodedStoragePath = WebdavUtils.encodePath(storagePath);
         try {
             Intent i = new Intent(Intent.ACTION_VIEW);
-            i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
+            i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), file.getMimetype());
             i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
             startActivity(i);
             
         } catch (Throwable t) {
-            Log_OC.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
+            Log_OC.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + file.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 || !mimeType.equals(file.getMimetype())) {
                     if (mimeType != null) {
                         i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
                     } else {
@@ -623,7 +622,7 @@ public class PreviewMediaFragment extends SherlockFragment implements
                 
             } finally {
                 if (toastIt) {
-                    Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
+                    Toast.makeText(getActivity(), "There is no application to handle file " + file.getFileName(), Toast.LENGTH_SHORT).show();
                 }
             }
             
@@ -640,7 +639,7 @@ public class PreviewMediaFragment extends SherlockFragment implements
     private void removeFile() {
         ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
                 R.string.confirmation_remove_alert,
-                new String[]{mFile.getFileName()},
+                new String[]{getFile().getFileName()},
                 R.string.confirmation_remove_remote_and_local,
                 R.string.confirmation_remove_local,
                 R.string.common_cancel);
@@ -654,15 +653,16 @@ public class PreviewMediaFragment extends SherlockFragment implements
      */
     @Override
     public void onConfirmation(String callerTag) {
-        if (mStorageManager.getFileById(mFile.getFileId()) != null) {   // check that the file is still there;
+        OCFile file = getFile();
+        if (mStorageManager.getFileById(file.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
+            mLastRemoteOperation = new RemoveFileOperation( file,      // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
                                                             true, 
                                                             mStorageManager);
             mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
             
             boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
-            getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
+            getActivity().showDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
         }
     }
     
@@ -673,12 +673,13 @@ public class PreviewMediaFragment extends SherlockFragment implements
     @Override
     public void onNeutral(String callerTag) {
         // TODO this code should be made in a secondary thread,
-        if (mFile.isDown()) {   // checks it is still there
+        OCFile file = getFile();
+        if (file.isDown()) {   // checks it is still there
             stopPreview(true);
-            File f = new File(mFile.getStoragePath());
+            File f = new File(file.getStoragePath());
             f.delete();
-            mFile.setStoragePath(null);
-            mStorageManager.saveFile(mFile);
+            file.setStoragePath(null);
+            mStorageManager.saveFile(file);
             finish();
         }
     }
@@ -692,33 +693,6 @@ public class PreviewMediaFragment extends SherlockFragment implements
     }
     
 
-    /**
-     * {@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.
      * 
@@ -743,7 +717,7 @@ public class PreviewMediaFragment extends SherlockFragment implements
     
     private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
         boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
-        getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
+        getActivity().dismissDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
         
         if (result.isSuccess()) {
             Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
@@ -760,10 +734,11 @@ public class PreviewMediaFragment extends SherlockFragment implements
     }
 
     private void stopPreview(boolean stopAudio) {
-        if (mFile.isAudio() && stopAudio) {
+        OCFile file = getFile();
+        if (file.isAudio() && stopAudio) {
             mMediaServiceBinder.pause();
             
-        } else if (mFile.isVideo()) {
+        } else if (file.isVideo()) {
             mVideoPreview.stopPlayback();
         }
     }
@@ -774,16 +749,7 @@ public class PreviewMediaFragment extends SherlockFragment implements
      * 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();
-        }
+        getActivity().onBackPressed();
     }
 
 

Some files were not shown because too many files changed in this diff