Disable change log; to remove in future
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / fragment / FileDetailFragment.java
index 7ec8d7e..2d46a55 100644 (file)
@@ -1,9 +1,10 @@
 /* ownCloud Android client application\r
  *   Copyright (C) 2011  Bartek Przybylski\r
+ *   Copyright (C) 2012-2013 ownCloud Inc.\r
  *\r
  *   This program is free software: you can redistribute it and/or modify\r
  *   it under the terms of the GNU General Public License as published by\r
- *   the Free Software Foundation, either version 3 of the License, or\r
+ *   the Free Software Foundation, either version 2 of the License, or\r
  *   (at your option) any later version.\r
  *\r
  *   This program is distributed in the hope that it will be useful,\r
@@ -50,6 +51,7 @@ import android.net.Uri;
 import android.os.AsyncTask;\r
 import android.os.Bundle;\r
 import android.os.Handler;\r
+import android.support.v4.app.DialogFragment;\r
 import android.support.v4.app.FragmentTransaction;\r
 import android.util.Log;\r
 import android.view.Display;\r
@@ -82,12 +84,13 @@ import com.owncloud.android.operations.RemoteOperationResult;
 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;\r
 import com.owncloud.android.operations.RemoveFileOperation;\r
 import com.owncloud.android.operations.RenameFileOperation;\r
+import com.owncloud.android.operations.SynchronizeFileOperation;\r
+import com.owncloud.android.ui.activity.ConflictsResolveActivity;\r
 import com.owncloud.android.ui.activity.FileDetailActivity;\r
 import com.owncloud.android.ui.activity.FileDisplayActivity;\r
 import com.owncloud.android.ui.activity.TransferServiceGetter;\r
 import com.owncloud.android.ui.dialog.EditNameDialog;\r
 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;\r
-import com.owncloud.android.utils.FileStorageUtils;\r
 import com.owncloud.android.utils.OwnCloudVersion;\r
 \r
 import com.owncloud.android.R;\r
@@ -112,6 +115,7 @@ public class FileDetailFragment extends SherlockFragment implements
     private View mView;\r
     private OCFile mFile;\r
     private Account mAccount;\r
+    private FileDataStorageManager mStorageManager;\r
     private ImageView mPreview;\r
     \r
     private DownloadFinishReceiver mDownloadFinishReceiver;\r
@@ -119,8 +123,9 @@ public class FileDetailFragment extends SherlockFragment implements
     \r
     private Handler mHandler;\r
     private RemoteOperation mLastRemoteOperation;\r
+    private DialogFragment mCurrentDialog;\r
 \r
-    private static final String TAG = "FileDetailFragment";\r
+    private static final String TAG = FileDetailFragment.class.getSimpleName();\r
     public static final String FTAG = "FileDetails"; \r
     public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";\r
 \r
@@ -133,6 +138,7 @@ public class FileDetailFragment extends SherlockFragment implements
     public FileDetailFragment() {\r
         mFile = null;\r
         mAccount = null;\r
+        mStorageManager = null;\r
         mLayout = R.layout.file_details_empty;\r
     }\r
     \r
@@ -148,11 +154,8 @@ public class FileDetailFragment extends SherlockFragment implements
     public FileDetailFragment(OCFile fileToDetail, Account ocAccount) {\r
         mFile = fileToDetail;\r
         mAccount = ocAccount;\r
+        mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment \r
         mLayout = R.layout.file_details_empty;\r
-        \r
-        if(fileToDetail != null && ocAccount != null) {\r
-            mLayout = R.layout.file_details_fragment;\r
-        }\r
     }\r
     \r
     \r
@@ -173,6 +176,10 @@ public class FileDetailFragment extends SherlockFragment implements
             mAccount = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_ACCOUNT);\r
         }\r
         \r
+        if(mFile != null && mAccount != null) {\r
+            mLayout = R.layout.file_details_fragment;\r
+        }\r
+        \r
         View view = null;\r
         view = inflater.inflate(mLayout, container, false);\r
         mView = view;\r
@@ -187,7 +194,7 @@ public class FileDetailFragment extends SherlockFragment implements
             mPreview = (ImageView)mView.findViewById(R.id.fdPreview);\r
         }\r
         \r
-        updateFileDetails();\r
+        updateFileDetails(false);\r
         return view;\r
     }\r
     \r
@@ -204,6 +211,18 @@ public class FileDetailFragment extends SherlockFragment implements
             throw new ClassCastException(activity.toString() + " must implement " + FileDetailFragment.ContainerActivity.class.getSimpleName());\r
         }\r
     }\r
+    \r
+    \r
+    /**\r
+     * {@inheritDoc}\r
+     */\r
+    @Override\r
+    public void onActivityCreated(Bundle savedInstanceState) {\r
+        super.onActivityCreated(savedInstanceState);\r
+        if (mAccount != null) {\r
+            mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());;\r
+        }\r
+    }\r
         \r
 \r
     @Override\r
@@ -258,7 +277,6 @@ public class FileDetailFragment extends SherlockFragment implements
     public void onClick(View v) {\r
         switch (v.getId()) {\r
             case R.id.fdDownloadBtn: {\r
-                //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath())) {\r
                 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();\r
                 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();\r
                 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {\r
@@ -290,52 +308,43 @@ public class FileDetailFragment extends SherlockFragment implements
                     }\r
                     \r
                 } else {\r
-                    // ISSUE 6: this button should be promoted to 'synchronize' if the file is DOWN, not just redownload\r
-                    Intent i = new Intent(getActivity(), FileDownloader.class);\r
-                    i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);\r
-                    i.putExtra(FileDownloader.EXTRA_FILE, mFile);\r
-                    /*i.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mFile.getRemotePath());\r
-                    i.putExtra(FileDownloader.EXTRA_FILE_PATH, mFile.getRemotePath());\r
-                    i.putExtra(FileDownloader.EXTRA_FILE_SIZE, mFile.getFileLength());*/\r
+                    mLastRemoteOperation = new SynchronizeFileOperation(mFile, null, mStorageManager, mAccount, true, false, getActivity());\r
+                    WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());\r
+                    mLastRemoteOperation.execute(wc, this, mHandler);\r
                 \r
                     // update ui \r
-                    setButtonsForTransferring();\r
-                \r
-                    getActivity().startService(i);\r
-                    mContainerActivity.onFileStateChanged();    // this is not working; it is performed before the fileDownloadService registers it as 'in progress'\r
+                    boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;\r
+                    getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);\r
+                    setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference\r
+                    \r
                 }\r
                 break;\r
             }\r
             case R.id.fdKeepInSync: {\r
                 CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);\r
                 mFile.setKeepInSync(cb.isChecked());\r
-                FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());\r
-                fdsm.saveFile(mFile);\r
-                if (mFile.keepInSync()) {\r
-                    onClick(getView().findViewById(R.id.fdDownloadBtn));\r
-                } else {\r
-                    mContainerActivity.onFileStateChanged();    // put inside 'else' to not call it twice (here, and in the virtual click on fdDownloadBtn)\r
-                }\r
+                mStorageManager.saveFile(mFile);\r
                 \r
+                /// register the OCFile instance in the observer service to monitor local updates;\r
+                /// if necessary, the file is download \r
                 Intent intent = new Intent(getActivity().getApplicationContext(),\r
                                            FileObserverService.class);\r
                 intent.putExtra(FileObserverService.KEY_FILE_CMD,\r
                            (cb.isChecked()?\r
                                    FileObserverService.CMD_ADD_OBSERVED_FILE:\r
                                    FileObserverService.CMD_DEL_OBSERVED_FILE));\r
-                String localPath = mFile.getStoragePath();\r
-                if (localPath == null || localPath.length() <= 0) {\r
-                    localPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile);\r
-                }\r
-                intent.putExtra(FileObserverService.KEY_CMD_ARG, localPath);\r
+                intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);\r
+                intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);\r
                 Log.e(TAG, "starting observer service");\r
                 getActivity().startService(intent);\r
                 \r
+                if (mFile.keepInSync()) {\r
+                    onClick(getView().findViewById(R.id.fdDownloadBtn));    // force an immediate synchronization\r
+                }\r
                 break;\r
             }\r
             case R.id.fdRenameBtn: {\r
-                EditNameDialog dialog = EditNameDialog.newInstance(mFile.getFileName());\r
-                dialog.setOnDismissListener(this);\r
+                EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), mFile.getFileName(), this);\r
                 dialog.show(getFragmentManager(), "nameeditdialog");\r
                 break;\r
             }   \r
@@ -347,7 +356,8 @@ public class FileDetailFragment extends SherlockFragment implements
                         mFile.isDown() ? R.string.confirmation_remove_local : -1,\r
                         R.string.common_cancel);\r
                 confDialog.setOnConfirmationListener(this);\r
-                confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);\r
+                mCurrentDialog = confDialog;\r
+                mCurrentDialog.show(getFragmentManager(), FTAG_CONFIRMATION);\r
                 break;\r
             }\r
             case R.id.fdOpenBtn: {\r
@@ -366,8 +376,13 @@ public class FileDetailFragment extends SherlockFragment implements
                     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
+                        if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {\r
+                            if (mimeType != null) {\r
+                                i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);\r
+                            } else {\r
+                                // desperate try\r
+                                i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*/*");\r
+                            }\r
                             i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);\r
                             startActivity(i);\r
                             toastIt = false;\r
@@ -405,11 +420,10 @@ public class FileDetailFragment extends SherlockFragment implements
     @Override\r
     public void onConfirmation(String callerTag) {\r
         if (callerTag.equals(FTAG_CONFIRMATION)) {\r
-            FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());\r
-            if (fdsm.getFileById(mFile.getFileId()) != null) {\r
+            if (mStorageManager.getFileById(mFile.getFileId()) != null) {\r
                 mLastRemoteOperation = new RemoveFileOperation( mFile, \r
                                                                 true, \r
-                                                                new FileDataStorageManager(mAccount, getActivity().getContentResolver()));\r
+                                                                mStorageManager);\r
                 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());\r
                 mLastRemoteOperation.execute(wc, this, mHandler);\r
                 \r
@@ -417,23 +431,28 @@ public class FileDetailFragment extends SherlockFragment implements
                 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);\r
             }\r
         }\r
+        mCurrentDialog.dismiss();\r
+        mCurrentDialog = null;\r
     }\r
     \r
     @Override\r
     public void onNeutral(String callerTag) {\r
-        FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());\r
         File f = null;\r
         if (mFile.isDown() && (f = new File(mFile.getStoragePath())).exists()) {\r
             f.delete();\r
             mFile.setStoragePath(null);\r
-            fdsm.saveFile(mFile);\r
+            mStorageManager.saveFile(mFile);\r
             updateFileDetails(mFile, mAccount);\r
         }\r
+        mCurrentDialog.dismiss();\r
+        mCurrentDialog = null;\r
     }\r
     \r
     @Override\r
     public void onCancel(String callerTag) {\r
         Log.d(TAG, "REMOVAL CANCELED");\r
+        mCurrentDialog.dismiss();\r
+        mCurrentDialog = null;\r
     }\r
     \r
     \r
@@ -443,7 +462,7 @@ public class FileDetailFragment extends SherlockFragment implements
      * @return  True when the fragment was created with the empty layout.\r
      */\r
     public boolean isEmpty() {\r
-        return mLayout == R.layout.file_details_empty;\r
+        return (mLayout == R.layout.file_details_empty || mFile == null || mAccount == null);\r
     }\r
 \r
     \r
@@ -462,22 +481,34 @@ public class FileDetailFragment extends SherlockFragment implements
      */\r
     public void updateFileDetails(OCFile file, Account ocAccount) {\r
         mFile = file;\r
+        if (ocAccount != null && ( \r
+                mStorageManager == null || \r
+                (mAccount != null && !mAccount.equals(ocAccount))\r
+           )) {\r
+            mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());\r
+        }\r
         mAccount = ocAccount;\r
-        updateFileDetails();\r
+        updateFileDetails(false);\r
     }\r
     \r
 \r
     /**\r
      * Updates the view with all relevant details about that file.\r
+     *\r
+     * TODO Remove parameter when the transferring state of files is kept in database. \r
+     * \r
+     * @param transferring      Flag signaling if the file should be considered as downloading or uploading, \r
+     *                          although {@link FileDownloaderBinder#isDownloading(Account, OCFile)}  and \r
+     *                          {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.\r
+     * \r
      */\r
-    public void updateFileDetails() {\r
+    public void updateFileDetails(boolean transferring) {\r
 \r
         if (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment) {\r
             \r
             // set file details\r
             setFilename(mFile.getFileName());\r
-            setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile\r
-                    .getMimetype()));\r
+            setFiletype(mFile.getMimetype());\r
             setFilesize(mFile.getFileLength());\r
             if(ocVersionSupportsTimeCreated()){\r
                 setTimeCreated(mFile.getCreationTimestamp());\r
@@ -492,7 +523,7 @@ public class FileDetailFragment extends SherlockFragment implements
             //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {\r
             FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();\r
             FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();\r
-            if ((downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) || (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile))) {\r
+            if (transferring || (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) || (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile))) {\r
                 setButtonsForTransferring();\r
                 \r
             } else if (mFile.isDown()) {\r
@@ -505,9 +536,11 @@ public class FileDetailFragment extends SherlockFragment implements
                 setButtonsForDown();\r
                 \r
             } else {\r
+                // TODO load default preview image; when the local file is removed, the preview remains there\r
                 setButtonsForRemote();\r
             }\r
         }\r
+        getView().invalidate();\r
     }\r
     \r
     \r
@@ -527,8 +560,14 @@ public class FileDetailFragment extends SherlockFragment implements
      */\r
     private void setFiletype(String mimetype) {\r
         TextView tv = (TextView) getView().findViewById(R.id.fdType);\r
-        if (tv != null)\r
-            tv.setText(mimetype);\r
+        if (tv != null) {\r
+            String printableMimetype = DisplayUtils.convertMIMEtoPrettyPrint(mimetype);;        \r
+            tv.setText(printableMimetype);\r
+        }\r
+        ImageView iv = (ImageView) getView().findViewById(R.id.fdIcon);\r
+        if (iv != null) {\r
+            iv.setImageResource(DisplayUtils.getResourceId(mimetype));\r
+        }\r
     }\r
 \r
     /**\r
@@ -589,8 +628,7 @@ public class FileDetailFragment extends SherlockFragment implements
     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
+            downloadButton.setText(R.string.filedetails_sync_file);\r
         \r
             ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(true);\r
             ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);\r
@@ -673,9 +711,9 @@ public class FileDetailFragment extends SherlockFragment implements
                 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));    // updates the local object without accessing the database again\r
+                        mFile = mStorageManager.getFileByPath(downloadedRemotePath);\r
                     }\r
-                    updateFileDetails();    // it updates the buttons; must be called although !downloadWasFine\r
+                    updateFileDetails(false);    // it updates the buttons; must be called although !downloadWasFine\r
                 }\r
             }\r
         }\r
@@ -700,12 +738,19 @@ public class FileDetailFragment extends SherlockFragment implements
             if (!isEmpty() && accountName.equals(mAccount.name)) {\r
                 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);\r
                 String uploadRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);\r
-                if (mFile.getRemotePath().equals(uploadRemotePath)) {\r
+                boolean renamedInUpload = mFile.getRemotePath().equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));\r
+                if (mFile.getRemotePath().equals(uploadRemotePath) ||\r
+                    renamedInUpload) {\r
                     if (uploadWasFine) {\r
-                        FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());\r
-                        mFile = fdsm.getFileByPath(mFile.getRemotePath());\r
+                        mFile = mStorageManager.getFileByPath(uploadRemotePath);\r
+                    }\r
+                    if (renamedInUpload) {\r
+                        String newName = (new File(uploadRemotePath)).getName();\r
+                        Toast msg = Toast.makeText(getActivity().getApplicationContext(), String.format(getString(R.string.filedetails_renamed_in_upload_msg), newName), Toast.LENGTH_LONG);\r
+                        msg.show();\r
                     }\r
-                    updateFileDetails();    // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server\r
+                    getSherlockActivity().removeStickyBroadcast(intent);    // not the best place to do this; a small refactorization of BroadcastReceivers should be done\r
+                    updateFileDetails(false);    // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server\r
                 }\r
             }\r
         }\r
@@ -821,6 +866,7 @@ public class FileDetailFragment extends SherlockFragment implements
             String newFilename = dialog.getNewFilename();\r
             Log.d(TAG, "name edit dialog dismissed with new name " + newFilename);\r
             mLastRemoteOperation = new RenameFileOperation( mFile, \r
+                                                            mAccount, \r
                                                             newFilename, \r
                                                             new FileDataStorageManager(mAccount, getActivity().getContentResolver()));\r
             WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());\r
@@ -916,6 +962,9 @@ public class FileDetailFragment extends SherlockFragment implements
                 \r
             } else if (operation instanceof RenameFileOperation) {\r
                 onRenameFileOperationFinish((RenameFileOperation)operation, result);\r
+                \r
+            } else if (operation instanceof SynchronizeFileOperation) {\r
+                onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);\r
             }\r
         }\r
     }\r
@@ -970,5 +1019,44 @@ public class FileDetailFragment extends SherlockFragment implements
         }\r
     }\r
     \r
+    private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {\r
+        boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;\r
+        getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);\r
+\r
+        if (!result.isSuccess()) {\r
+            if (result.getCode() == ResultCode.SYNC_CONFLICT) {\r
+                Intent i = new Intent(getActivity(), ConflictsResolveActivity.class);\r
+                i.putExtra(ConflictsResolveActivity.EXTRA_FILE, mFile);\r
+                i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, mAccount);\r
+                startActivity(i);\r
+                \r
+            } else {\r
+                Toast msg = Toast.makeText(getActivity(), R.string.sync_file_fail_msg, Toast.LENGTH_LONG); \r
+                msg.show();\r
+            }\r
+            \r
+            if (mFile.isDown()) {\r
+                setButtonsForDown();\r
+                \r
+            } else {\r
+                setButtonsForRemote();\r
+            }\r
+            \r
+        } else {\r
+            if (operation.transferWasRequested()) {\r
+                mContainerActivity.onFileStateChanged();    // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so \r
+                                                            // checking the service to see if the file is downloading results in FALSE\r
+            } else {\r
+                Toast msg = Toast.makeText(getActivity(), R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG); \r
+                msg.show();\r
+                if (mFile.isDown()) {\r
+                    setButtonsForDown();\r
+                    \r
+                } else {\r
+                    setButtonsForRemote();\r
+                }\r
+            }\r
+        }\r
+    }\r
 \r
 }\r