Forgot the new icon!
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / ui / fragment / FileDetailFragment.java
index cf13ba3..6a34c6d 100644 (file)
  */\r
 package eu.alefzero.owncloud.ui.fragment;\r
 \r
+import java.io.File;\r
 import java.io.IOException;\r
 import java.util.ArrayList;\r
 import java.util.List;\r
 \r
-import org.apache.commons.httpclient.HostConfiguration;\r
 import org.apache.commons.httpclient.HttpException;\r
-import org.apache.commons.httpclient.cookie.CookiePolicy;\r
 import org.apache.commons.httpclient.methods.GetMethod;\r
 import org.apache.commons.httpclient.methods.PostMethod;\r
 import org.apache.commons.httpclient.methods.StringRequestEntity;\r
 import org.apache.commons.httpclient.params.HttpConnectionManagerParams;\r
-import org.apache.commons.httpclient.params.HttpMethodParams;\r
 import org.apache.http.HttpStatus;\r
 import org.apache.http.NameValuePair;\r
 import org.apache.http.client.utils.URLEncodedUtils;\r
 import org.apache.http.message.BasicNameValuePair;\r
 import org.apache.http.protocol.HTTP;\r
 import org.apache.jackrabbit.webdav.client.methods.DavMethodBase;\r
-import org.apache.jackrabbit.webdav.client.methods.MoveMethod;\r
+import org.apache.jackrabbit.webdav.client.methods.DeleteMethod;\r
 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;\r
 import org.json.JSONException;\r
 import org.json.JSONObject;\r
@@ -45,19 +43,18 @@ import android.accounts.AccountManager;
 import android.content.ActivityNotFoundException;\r
 import android.content.BroadcastReceiver;\r
 import android.content.Context;\r
-import android.content.DialogInterface;\r
-import android.content.DialogInterface.OnDismissListener;\r
 import android.content.Intent;\r
 import android.content.IntentFilter;\r
+import android.content.res.Resources.NotFoundException;\r
 import android.graphics.Bitmap;\r
 import android.graphics.BitmapFactory;\r
 import android.graphics.BitmapFactory.Options;\r
 import android.graphics.Point;\r
-import android.graphics.drawable.BitmapDrawable;\r
-import android.graphics.drawable.Drawable;\r
 import android.net.Uri;\r
+import android.os.AsyncTask;\r
 import android.os.Bundle;\r
-import android.preference.PreferenceActivity.Header;\r
+import android.os.Handler;\r
+import android.support.v4.app.FragmentTransaction;\r
 import android.util.Log;\r
 import android.view.Display;\r
 import android.view.LayoutInflater;\r
@@ -68,7 +65,6 @@ import android.view.WindowManager.LayoutParams;
 import android.webkit.MimeTypeMap;\r
 import android.widget.Button;\r
 import android.widget.CheckBox;\r
-import android.widget.EditText;\r
 import android.widget.ImageView;\r
 import android.widget.TextView;\r
 import android.widget.Toast;\r
@@ -83,8 +79,10 @@ import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
 import eu.alefzero.owncloud.datamodel.FileDataStorageManager;\r
 import eu.alefzero.owncloud.datamodel.OCFile;\r
 import eu.alefzero.owncloud.files.services.FileDownloader;\r
+import eu.alefzero.owncloud.ui.activity.FileDisplayActivity;\r
 import eu.alefzero.owncloud.utils.OwnCloudVersion;\r
 import eu.alefzero.webdav.WebdavClient;\r
+import eu.alefzero.webdav.WebdavUtils;\r
 \r
 /**\r
  * This Fragment is used to display the details about a file.\r
@@ -93,7 +91,7 @@ import eu.alefzero.webdav.WebdavClient;
  * \r
  */\r
 public class FileDetailFragment extends SherlockFragment implements\r
-        OnClickListener {\r
+        OnClickListener, ConfirmationDialogFragment.ConfirmationDialogFragmentListener {\r
 \r
     public static final String EXTRA_FILE = "FILE";\r
     public static final String EXTRA_ACCOUNT = "ACCOUNT";\r
@@ -102,11 +100,13 @@ public class FileDetailFragment extends SherlockFragment implements
     private View mView;\r
     private OCFile mFile;\r
     private Account mAccount;\r
+    private ImageView mPreview;\r
     \r
     private DownloadFinishReceiver mDownloadFinishReceiver;\r
 \r
     private static final String TAG = "FileDetailFragment";\r
     public static final String FTAG = "FileDetails"; \r
+    public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";\r
 \r
     \r
     /**\r
@@ -154,6 +154,16 @@ public class FileDetailFragment extends SherlockFragment implements
         view = inflater.inflate(mLayout, container, false);\r
         mView = view;\r
         \r
+        if (mLayout == R.layout.file_details_fragment) {\r
+            mView.findViewById(R.id.fdKeepInSync).setOnClickListener(this);\r
+            mView.findViewById(R.id.fdRenameBtn).setOnClickListener(this);\r
+            mView.findViewById(R.id.fdDownloadBtn).setOnClickListener(this);\r
+            mView.findViewById(R.id.fdOpenBtn).setOnClickListener(this);\r
+            mView.findViewById(R.id.fdRemoveBtn).setOnClickListener(this);\r
+            //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);\r
+            mPreview = (ImageView)mView.findViewById(R.id.fdPreview);\r
+        }\r
+        \r
         updateFileDetails();\r
         return view;\r
     }\r
@@ -176,6 +186,7 @@ public class FileDetailFragment extends SherlockFragment implements
         IntentFilter filter = new IntentFilter(\r
                 FileDownloader.DOWNLOAD_FINISH_MESSAGE);\r
         getActivity().registerReceiver(mDownloadFinishReceiver, filter);\r
+        mPreview = (ImageView)mView.findViewById(R.id.fdPreview);\r
     }\r
 \r
     @Override\r
@@ -183,6 +194,9 @@ public class FileDetailFragment extends SherlockFragment implements
         super.onPause();\r
         getActivity().unregisterReceiver(mDownloadFinishReceiver);\r
         mDownloadFinishReceiver = null;\r
+        if (mPreview != null) {\r
+            mPreview = null;\r
+        }\r
     }\r
 \r
     @Override\r
@@ -196,13 +210,16 @@ public class FileDetailFragment extends SherlockFragment implements
     public void onClick(View v) {\r
         switch (v.getId()) {\r
             case R.id.fdDownloadBtn: {\r
-                //Toast.makeText(getActivity(), "Downloading", Toast.LENGTH_LONG).show();\r
                 Intent i = new Intent(getActivity(), FileDownloader.class);\r
                 i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);\r
                 i.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mFile.getRemotePath());\r
-                i.putExtra(FileDownloader.EXTRA_FILE_PATH, mFile.getURLDecodedRemotePath());\r
+                i.putExtra(FileDownloader.EXTRA_FILE_PATH, mFile.getRemotePath());\r
                 i.putExtra(FileDownloader.EXTRA_FILE_SIZE, mFile.getFileLength());\r
-                v.setEnabled(false);\r
+                \r
+                // update ui \r
+                Toast.makeText(getActivity(), "Downloading", Toast.LENGTH_LONG).show();\r
+                setButtonsForDownloading();\r
+                \r
                 getActivity().startService(i);\r
                 break;\r
             }\r
@@ -211,7 +228,7 @@ public class FileDetailFragment extends SherlockFragment implements
                 mFile.setKeepInSync(cb.isChecked());\r
                 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());\r
                 fdsm.saveFile(mFile);\r
-                if (mFile.keepInSync() && !mFile.isDownloaded()) {\r
+                if (mFile.keepInSync()) {\r
                     onClick(getView().findViewById(R.id.fdDownloadBtn));\r
                 }\r
                 break;\r
@@ -221,6 +238,53 @@ public class FileDetailFragment extends SherlockFragment implements
                 dialog.show(getFragmentManager(), "nameeditdialog");\r
                 dialog.setOnDismissListener(this);\r
                 break;\r
+            }   \r
+            case R.id.fdRemoveBtn: {\r
+                ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance("to remove " + mFile.getFileName());\r
+                confDialog.setOnConfirmationListener(this);\r
+                confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);\r
+                break;\r
+            }\r
+            case R.id.fdOpenBtn: {\r
+                String storagePath = mFile.getStoragePath();\r
+                String encodedStoragePath = WebdavUtils.encodePath(storagePath);\r
+                try {\r
+                    Intent i = new Intent(Intent.ACTION_VIEW);\r
+                    i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());\r
+                    i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);\r
+                    startActivity(i);\r
+                    \r
+                } catch (Throwable t) {\r
+                    Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());\r
+                    boolean toastIt = true; \r
+                    String mimeType = "";\r
+                    try {\r
+                        Intent i = new Intent(Intent.ACTION_VIEW);\r
+                        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));\r
+                        if (mimeType != null && !mimeType.equals(mFile.getMimetype())) {\r
+                            i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);\r
+                            i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);\r
+                            startActivity(i);\r
+                            toastIt = false;\r
+                        }\r
+                        \r
+                    } catch (IndexOutOfBoundsException e) {\r
+                        Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);\r
+                        \r
+                    } catch (ActivityNotFoundException e) {\r
+                        Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");\r
+                        \r
+                    } catch (Throwable th) {\r
+                        Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);\r
+                        \r
+                    } finally {\r
+                        if (toastIt) {\r
+                            Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();\r
+                        }\r
+                    }\r
+                    \r
+                }\r
+                break;\r
             }\r
             default:\r
                 Log.e(TAG, "Incorrect view clicked!");\r
@@ -231,8 +295,20 @@ public class FileDetailFragment extends SherlockFragment implements
             t.start();\r
         }*/\r
     }\r
-\r
-\r
+    \r
+    \r
+    @Override\r
+    public void onConfirmation(boolean confirmation, String callerTag) {\r
+        if (confirmation && callerTag.equals(FTAG_CONFIRMATION)) {\r
+            Log.e("ASD","onConfirmation");\r
+            FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());\r
+            if (fdsm.getFileById(mFile.getFileId()) != null) {\r
+                new Thread(new RemoveRunnable(mFile, mAccount, new Handler())).start();\r
+            }\r
+        } else if (!confirmation) Log.d(TAG, "REMOVAL CANCELED");\r
+    }\r
+    \r
+    \r
     /**\r
      * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.\r
      * \r
@@ -270,7 +346,6 @@ public class FileDetailFragment extends SherlockFragment implements
 \r
         if (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment) {\r
             \r
-            Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);\r
             // set file details\r
             setFilename(mFile.getFileName());\r
             setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile\r
@@ -284,86 +359,30 @@ public class FileDetailFragment extends SherlockFragment implements
             \r
             CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);\r
             cb.setChecked(mFile.keepInSync());\r
-            cb.setOnClickListener(this);\r
-            //getView().findViewById(R.id.fdShareBtn).setOnClickListener(this);\r
-            getView().findViewById(R.id.fdRenameBtn).setOnClickListener(this);\r
-            \r
-            if (mFile.getStoragePath() != null) {\r
-                // Update preview\r
-                ImageView preview = (ImageView) getView().findViewById(R.id.fdPreview);\r
-                try {\r
-                    if (mFile.getMimetype().startsWith("image/")) {\r
-                        BitmapFactory.Options options = new Options();\r
-                        options.inScaled = true;\r
-                        options.inPurgeable = true;\r
-                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {\r
-                            options.inPreferQualityOverSpeed = false;\r
-                        }\r
-                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {\r
-                            options.inMutable = false;\r
-                        }\r
-\r
-                        Bitmap bmp = BitmapFactory.decodeFile(mFile.getStoragePath(), options);\r
-\r
-                        if (bmp != null) {\r
-                            int width = options.outWidth;\r
-                            int height = options.outHeight;\r
-                            int scale = 1;\r
-                            boolean recycle = false;\r
-                            if (width >= 2048 || height >= 2048) {\r
-                                scale = (int) (Math.ceil(Math.max(height, width)/2048.));\r
-                                options.inSampleSize = scale;\r
-                                recycle = true;\r
-                            }\r
-                                Display display = getActivity().getWindowManager().getDefaultDisplay();\r
-                                Point size = new Point();\r
-                                int screenwidth;\r
-                                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {\r
-                                    display.getSize(size);\r
-                                    screenwidth = size.x;\r
-                                } else {\r
-                                    screenwidth = display.getWidth();\r
-                                }\r
-\r
-                                Log.e("ASD", "W " + width + " SW " + screenwidth);\r
 \r
-                                if (width > screenwidth) {\r
-                                    scale = (int) (Math.ceil(Math.max(height, width)/screenwidth));\r
-                                    options.inSampleSize = scale;\r
-                                    recycle = true;\r
-                                }\r
-                            \r
-\r
-                            if (recycle) bmp.recycle();\r
-                            bmp = BitmapFactory.decodeFile(mFile.getStoragePath(), options);\r
-                            \r
-                        }\r
-                        if (bmp != null) {\r
-                            preview.setImageBitmap(bmp);\r
-                        }\r
-                    }\r
-                } catch (OutOfMemoryError e) {\r
-                    preview.setVisibility(View.INVISIBLE);\r
-                    Log.e(TAG, "Out of memory occured for file with size " + mFile.getFileLength());\r
-                    \r
-                } catch (NoSuchFieldError e) {\r
-                    preview.setVisibility(View.INVISIBLE);\r
-                    Log.e(TAG, "Error from access to unexisting field despite protection " + mFile.getFileLength());\r
-                    \r
-                } catch (Throwable t) {\r
-                    preview.setVisibility(View.INVISIBLE);\r
-                    Log.e(TAG, "Unexpected error while creating image preview " + mFile.getFileLength(), t);\r
+            // configure UI for depending upon local state of the file\r
+            if (mFile.isDownloading()) {\r
+                setButtonsForDownloading();\r
+                \r
+            } else if (mFile.isDown()) {\r
+                // Update preview\r
+                if (mFile.getMimetype().startsWith("image/")) {\r
+                    BitmapLoader bl = new BitmapLoader();\r
+                    bl.execute(new String[]{mFile.getStoragePath()});\r
                 }\r
                 \r
+                setButtonsForDown();\r
+                \r
                 // Change download button to open button\r
-                downloadButton.setText(R.string.filedetails_open);\r
+                /*downloadButton.setText(R.string.filedetails_open);\r
                 downloadButton.setOnClickListener(new OnClickListener() {\r
                     @Override\r
                     public void onClick(View v) {\r
                         String storagePath = mFile.getStoragePath();\r
+                        String encodedStoragePath = WebdavUtils.encodePath(storagePath);\r
                         try {\r
                             Intent i = new Intent(Intent.ACTION_VIEW);\r
-                            i.setDataAndType(Uri.parse("file://"+ storagePath), mFile.getMimetype());\r
+                            i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());\r
                             i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);\r
                             startActivity(i);\r
                             \r
@@ -375,7 +394,7 @@ public class FileDetailFragment extends SherlockFragment implements
                                 Intent i = new Intent(Intent.ACTION_VIEW);\r
                                 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));\r
                                 if (mimeType != null && !mimeType.equals(mFile.getMimetype())) {\r
-                                    i.setDataAndType(Uri.parse("file://"+mFile.getStoragePath()), mimeType);\r
+                                    i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);\r
                                     i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);\r
                                     startActivity(i);\r
                                     toastIt = false;\r
@@ -398,10 +417,9 @@ public class FileDetailFragment extends SherlockFragment implements
                             \r
                         }\r
                     }\r
-                });\r
+                });*/\r
             } else {\r
-                // Make download button effective\r
-                downloadButton.setOnClickListener(this);\r
+                setButtonsForRemote();\r
             }\r
         }\r
     }\r
@@ -463,6 +481,53 @@ public class FileDetailFragment extends SherlockFragment implements
     }\r
     \r
     /**\r
+     * Enables or disables buttons for a file being downloaded\r
+     */\r
+    private void setButtonsForDownloading() {\r
+        if (!isEmpty()) {\r
+            Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);\r
+            downloadButton.setText(R.string.filedetails_download_in_progress);\r
+            downloadButton.setEnabled(false);   // TODO replace it with a 'cancel download' button\r
+        \r
+            // let's protect the user from himself ;)\r
+            ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);\r
+            ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(false);\r
+            ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(false);\r
+        }\r
+    }\r
+    \r
+    /**\r
+     * Enables or disables buttons for a file locally available \r
+     */\r
+    private void setButtonsForDown() {\r
+        if (!isEmpty()) {\r
+            Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);\r
+            downloadButton.setText(R.string.filedetails_redownload);\r
+            downloadButton.setEnabled(true);\r
+        \r
+            ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(true);\r
+            ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);\r
+            ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Enables or disables buttons for a file not locally available \r
+     */\r
+    private void setButtonsForRemote() {\r
+        if (!isEmpty()) {\r
+            Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);\r
+            downloadButton.setText(R.string.filedetails_download);\r
+            downloadButton.setEnabled(true);\r
+            \r
+            ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);\r
+            ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);\r
+            ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);\r
+        }\r
+    }\r
+    \r
+\r
+    /**\r
      * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return\r
      * the time that the file was created. There is a chance that this will\r
      * be fixed in future versions. Use this method to check if this version of\r
@@ -488,20 +553,20 @@ public class FileDetailFragment extends SherlockFragment implements
     private class DownloadFinishReceiver extends BroadcastReceiver {\r
         @Override\r
         public void onReceive(Context context, Intent intent) {\r
-            if (getView()!=null && getView().findViewById(R.id.fdDownloadBtn) != null) \r
-                getView().findViewById(R.id.fdDownloadBtn).setEnabled(true);\r
-            \r
-            if (intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false)) {\r
-                mFile.setStoragePath(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH));\r
-                updateFileDetails();\r
-            } else if (intent.getAction().equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {\r
-                Toast.makeText(context, R.string.downloader_download_failed , Toast.LENGTH_SHORT).show();\r
+            if (mFile != null) {\r
+                boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);\r
+                String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);\r
+                if (mFile.getRemotePath().equals(downloadedRemotePath)) {\r
+                    if (downloadWasFine) {\r
+                        mFile.setStoragePath(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH));\r
+                    }\r
+                    updateFileDetails();    // it updates the buttons; must be called although !downloadWasFine\r
+                }\r
             }\r
         }\r
-        \r
     }\r
     \r
-    // this is a temporary class for sharing purposes, it need to be replacead in transfer service\r
+    // this is a temporary class for sharing purposes, it need to be replaced in transfer service\r
     private class ShareRunnable implements Runnable {\r
         private String mPath;\r
 \r
@@ -616,7 +681,6 @@ public class FileDetailFragment extends SherlockFragment implements
     }\r
     \r
     public void onDismiss(EditNameFragment dialog) {\r
-        Log.e("ASD","ondismiss");\r
         if (dialog instanceof EditNameFragment) {\r
             if (((EditNameFragment)dialog).getResult()) {\r
                 String newFilename = ((EditNameFragment)dialog).getNewFilename();\r
@@ -624,7 +688,7 @@ public class FileDetailFragment extends SherlockFragment implements
                 if (!newFilename.equals(mFile.getFileName())) {\r
                     FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());\r
                     if (fdsm.getFileById(mFile.getFileId()) != null) {\r
-                        OCFile newFile = new OCFile(fdsm.getFileById(mFile.getParentId()).getRemotePath()+"/"+newFilename);\r
+                        OCFile newFile = new OCFile(fdsm.getFileById(mFile.getParentId()).getRemotePath() + OCFile.PATH_SEPARATOR + newFilename);\r
                         newFile.setCreationTimestamp(mFile.getCreationTimestamp());\r
                         newFile.setFileId(mFile.getFileId());\r
                         newFile.setFileLength(mFile.getFileLength());\r
@@ -633,17 +697,21 @@ public class FileDetailFragment extends SherlockFragment implements
                         newFile.setMimetype(mFile.getMimetype());\r
                         newFile.setModificationTimestamp(mFile.getModificationTimestamp());\r
                         newFile.setParentId(mFile.getParentId());\r
-                        newFile.setStoragePath(mFile.getStoragePath());\r
-                        fdsm.removeFile(mFile);\r
-                        fdsm.saveFile(newFile);\r
-                        new Thread(new RenameRunnable(mFile, newFile, mAccount)).start();\r
-                        mFile = newFile;\r
-                        updateFileDetails(mFile, mAccount);\r
+                        if (mFile.isDown()) {\r
+                            File f = new File(mFile.getStoragePath());\r
+                            Log.e(TAG, f.getAbsolutePath());\r
+                            f.renameTo(new File(f.getParent()+"/"+newFilename));\r
+                            Log.e(TAG, f.getAbsolutePath());\r
+                            newFile.setStoragePath(f.getAbsolutePath());\r
+                        }\r
+                        \r
+                        new Thread(new RenameRunnable(mFile, newFile, mAccount, new Handler())).start();\r
+\r
                     }\r
                 }\r
             }\r
         } else {\r
-            Log.e(TAG, "Unknown dialog intance passed to onDismissDalog: " + dialog.getClass().getCanonicalName());\r
+            Log.e(TAG, "Unknown dialog instance passed to onDismissDalog: " + dialog.getClass().getCanonicalName());\r
         }\r
         \r
     }\r
@@ -652,11 +720,13 @@ public class FileDetailFragment extends SherlockFragment implements
         \r
         Account mAccount;\r
         OCFile mOld, mNew;\r
+        Handler mHandler;\r
         \r
-        public RenameRunnable(OCFile oldFile, OCFile newFile, Account account) {\r
+        public RenameRunnable(OCFile oldFile, OCFile newFile, Account account, Handler handler) {\r
             mOld = oldFile;\r
             mNew = newFile;\r
             mAccount = account;\r
+            mHandler = handler;\r
         }\r
         \r
         public void run() {\r
@@ -665,15 +735,24 @@ public class FileDetailFragment extends SherlockFragment implements
             String baseUrl = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);\r
             OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));\r
             String webdav_path = AccountUtils.getWebdavPath(ocv);\r
-            Log.d("ASD", ""+baseUrl + webdav_path + mOld.getRemotePath());\r
+            Log.d("ASD", ""+baseUrl + webdav_path + WebdavUtils.encodePath(mOld.getRemotePath()));\r
 \r
-            \r
-            Log.e("ASD", Uri.parse(baseUrl).getPath() == null ? "" : Uri.parse(baseUrl).getPath() + webdav_path + mNew.getRemotePath());\r
-            LocalMoveMethod move = new LocalMoveMethod(baseUrl + webdav_path + mOld.getRemotePath(),\r
-                                             Uri.parse(baseUrl).getPath() == null ? "" : Uri.parse(baseUrl).getPath() + webdav_path + mNew.getRemotePath());\r
+            Log.e("ASD", Uri.parse(baseUrl).getPath() == null ? "" : Uri.parse(baseUrl).getPath() + webdav_path + WebdavUtils.encodePath(mNew.getRemotePath()));\r
+            LocalMoveMethod move = new LocalMoveMethod(baseUrl + webdav_path + WebdavUtils.encodePath(mOld.getRemotePath()),\r
+                                             Uri.parse(baseUrl).getPath() == null ? "" : Uri.parse(baseUrl).getPath() + webdav_path + WebdavUtils.encodePath(mNew.getRemotePath()));\r
             \r
             try {\r
                 int status = wc.executeMethod(move);\r
+                if (move.succeeded()) {\r
+                    FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());\r
+                    fdsm.removeFile(mOld);\r
+                    fdsm.saveFile(mNew);\r
+                    mFile = mNew;\r
+                    mHandler.post(new Runnable() {\r
+                        @Override\r
+                        public void run() { updateFileDetails(mFile, mAccount); }\r
+                    });\r
+                }\r
                 Log.e("ASD", ""+move.getQueryString());\r
                 Log.d("move", "returned status " + status);\r
             } catch (HttpException e) {\r
@@ -722,7 +801,9 @@ public class FileDetailFragment extends SherlockFragment implements
         public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\r
             View v = inflater.inflate(R.layout.edit_box_dialog, container, false);\r
 \r
-            String currentName = getArguments().getString("filename", "");\r
+            String currentName = getArguments().getString("filename");\r
+            if (currentName == null)\r
+                currentName = "";\r
             \r
             ((Button)v.findViewById(R.id.cancel)).setOnClickListener(this);\r
             ((Button)v.findViewById(R.id.ok)).setOnClickListener(this);\r
@@ -762,4 +843,163 @@ public class FileDetailFragment extends SherlockFragment implements
         }\r
         \r
     }\r
+    \r
+    private class RemoveRunnable implements Runnable {\r
+        \r
+        /** Arbitrary timeout for deletion */\r
+        public final static int DELETION_TIMEOUT = 5000;\r
+        \r
+        Account mAccount;\r
+        OCFile mFileToRemove;\r
+        Handler mHandler;\r
+        \r
+        public RemoveRunnable(OCFile fileToRemove, Account account, Handler handler) {\r
+            mFileToRemove = fileToRemove;\r
+            mAccount = account;\r
+            mHandler = handler;\r
+        }\r
+        \r
+        public void run() {\r
+            WebdavClient wc = new WebdavClient(mAccount, getSherlockActivity().getApplicationContext());\r
+            AccountManager am = AccountManager.get(getSherlockActivity());\r
+            String baseUrl = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);\r
+            OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));\r
+            String webdav_path = AccountUtils.getWebdavPath(ocv);\r
+            Log.d("ASD", ""+baseUrl + webdav_path + WebdavUtils.encodePath(mFileToRemove.getRemotePath()));\r
+\r
+            DeleteMethod delete = new DeleteMethod(baseUrl + webdav_path + WebdavUtils.encodePath(mFileToRemove.getRemotePath()));\r
+            \r
+            boolean success = false;\r
+            try {\r
+                int status = wc.executeMethod(delete, DELETION_TIMEOUT);\r
+                if (delete.succeeded()) {\r
+                    FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());\r
+                    fdsm.removeFile(mFileToRemove);\r
+                    mHandler.post(new Runnable() {\r
+                        @Override\r
+                        public void run() { \r
+                            try {\r
+                                Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);\r
+                                msg.show();\r
+                                if (getActivity() instanceof FileDisplayActivity) {\r
+                                    // double pane\r
+                                    FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();\r
+                                    transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment\r
+                                    transaction.commit();\r
+                                    \r
+                                } else {\r
+                                    getActivity().finish();\r
+                                }\r
+                                \r
+                            } catch (NotFoundException e) {\r
+                                e.printStackTrace();\r
+                            }\r
+                        }\r
+                    });\r
+                    success = true;\r
+                }\r
+                Log.e("ASD", ""+ delete.getQueryString());\r
+                Log.d("delete", "returned status " + status);\r
+                \r
+            } catch (HttpException e) {\r
+                e.printStackTrace();\r
+                \r
+            } catch (IOException e) {\r
+                e.printStackTrace();\r
+                \r
+            } finally {\r
+                if (!success) {\r
+                    mHandler.post(new Runnable() {\r
+                        @Override\r
+                        public void run() {\r
+                            try {\r
+                                Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG); \r
+                                msg.show();\r
+                            \r
+                            } catch (NotFoundException e) {\r
+                                e.printStackTrace();\r
+                            }\r
+                        }\r
+                    });\r
+                }\r
+            }\r
+        }\r
+        \r
+    }\r
+    \r
+    class BitmapLoader extends AsyncTask<String, Void, Bitmap> {\r
+        @Override\r
+        protected Bitmap doInBackground(String... params) {\r
+            Bitmap result = null;\r
+            if (params.length != 1) return result;\r
+            String storagePath = params[0];\r
+            try {\r
+\r
+                BitmapFactory.Options options = new Options();\r
+                options.inScaled = true;\r
+                options.inPurgeable = true;\r
+                options.inJustDecodeBounds = true;\r
+                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {\r
+                    options.inPreferQualityOverSpeed = false;\r
+                }\r
+                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {\r
+                    options.inMutable = false;\r
+                }\r
+\r
+                result = BitmapFactory.decodeFile(storagePath, options);\r
+                options.inJustDecodeBounds = false;\r
+\r
+                int width = options.outWidth;\r
+                int height = options.outHeight;\r
+                int scale = 1;\r
+                boolean recycle = false;\r
+                if (width >= 2048 || height >= 2048) {\r
+                    scale = (int) Math.ceil((Math.ceil(Math.max(height, width) / 2048.)));\r
+                    options.inSampleSize = scale;\r
+                }\r
+                Display display = getActivity().getWindowManager().getDefaultDisplay();\r
+                Point size = new Point();\r
+                int screenwidth;\r
+                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {\r
+                    display.getSize(size);\r
+                    screenwidth = size.x;\r
+                } else {\r
+                    screenwidth = display.getWidth();\r
+                }\r
+\r
+                Log.e("ASD", "W " + width + " SW " + screenwidth);\r
+\r
+                if (width > screenwidth) {\r
+                    scale = (int) Math.ceil((float)width / screenwidth);\r
+                    options.inSampleSize = scale;\r
+                }\r
+\r
+                result = BitmapFactory.decodeFile(storagePath, options);\r
+\r
+                Log.e("ASD", "W " + options.outWidth + " SW " + options.outHeight);\r
+\r
+            } catch (OutOfMemoryError e) {\r
+                result = null;\r
+                Log.e(TAG, "Out of memory occured for file with size " + storagePath);\r
+                \r
+            } catch (NoSuchFieldError e) {\r
+                result = null;\r
+                Log.e(TAG, "Error from access to unexisting field despite protection " + storagePath);\r
+                \r
+            } catch (Throwable t) {\r
+                result = null;\r
+                Log.e(TAG, "Unexpected error while creating image preview " + storagePath, t);\r
+            }\r
+            return result;\r
+        }\r
+        @Override\r
+        protected void onPostExecute(Bitmap result) {\r
+            if (result != null && mPreview != null) {\r
+                mPreview.setImageBitmap(result);\r
+            }\r
+        }\r
+        \r
+    }\r
+    \r
+\r
 }\r